1 //===--- IdentifierTable.cpp - Hash table for identifier lookup -----------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the IdentifierInfo, IdentifierVisitor, and
11 // IdentifierTable interfaces.
13 //===----------------------------------------------------------------------===//
15 #include "clang/Basic/CharInfo.h"
16 #include "clang/Basic/IdentifierTable.h"
17 #include "clang/Basic/LangOptions.h"
18 #include "clang/Basic/OperatorKinds.h"
19 #include "clang/Basic/Specifiers.h"
20 #include "llvm/ADT/DenseMap.h"
21 #include "llvm/ADT/FoldingSet.h"
22 #include "llvm/ADT/SmallString.h"
23 #include "llvm/Support/ErrorHandling.h"
24 #include "llvm/Support/raw_ostream.h"
27 using namespace clang;
29 //===----------------------------------------------------------------------===//
30 // IdentifierInfo Implementation
31 //===----------------------------------------------------------------------===//
33 IdentifierInfo::IdentifierInfo() {
34 TokenID = tok::identifier;
39 IsFutureCompatKeyword = false;
41 IsCPPOperatorKeyword = false;
42 NeedsHandleIdentifier = false;
44 ChangedAfterLoad = false;
45 RevertedTokenID = false;
47 IsModulesImport = false;
48 FETokenInfo = nullptr;
52 //===----------------------------------------------------------------------===//
53 // IdentifierTable Implementation
54 //===----------------------------------------------------------------------===//
56 IdentifierIterator::~IdentifierIterator() { }
58 IdentifierInfoLookup::~IdentifierInfoLookup() {}
61 /// \brief A simple identifier lookup iterator that represents an
62 /// empty sequence of identifiers.
63 class EmptyLookupIterator : public IdentifierIterator
66 StringRef Next() override { return StringRef(); }
70 IdentifierIterator *IdentifierInfoLookup::getIdentifiers() {
71 return new EmptyLookupIterator();
74 IdentifierTable::IdentifierTable(const LangOptions &LangOpts,
75 IdentifierInfoLookup* externalLookup)
76 : HashTable(8192), // Start with space for 8K identifiers.
77 ExternalLookup(externalLookup) {
79 // Populate the identifier table with info about keywords for the current
81 AddKeywords(LangOpts);
84 // Add the '_experimental_modules_import' contextual keyword.
85 get("import").setModulesImport(true);
88 //===----------------------------------------------------------------------===//
89 // Language Keyword Implementation
90 //===----------------------------------------------------------------------===//
92 // Constants for TokenKinds.def
108 KEYNOOPENCL = 0x02000,
109 WCHARSUPPORT = 0x04000,
110 HALFSUPPORT = 0x08000,
111 KEYCONCEPTS = 0x10000,
113 KEYALL = (0x3ffff & ~KEYNOMS18 &
114 ~KEYNOOPENCL) // KEYNOMS18 and KEYNOOPENCL are used to exclude.
117 /// \brief How a keyword is treated in the selected standard.
119 KS_Disabled, // Disabled
120 KS_Extension, // Is an extension
121 KS_Enabled, // Enabled
122 KS_Future // Is a keyword in future standard
126 /// \brief Translates flags as specified in TokenKinds.def into keyword status
127 /// in the given language standard.
128 static KeywordStatus getKeywordStatus(const LangOptions &LangOpts,
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.C99 && (Flags & KEYC99)) return KS_Enabled;
134 if (LangOpts.GNUKeywords && (Flags & KEYGNU)) return KS_Extension;
135 if (LangOpts.MicrosoftExt && (Flags & KEYMS)) return KS_Extension;
136 if (LangOpts.Borland && (Flags & KEYBORLAND)) return KS_Extension;
137 if (LangOpts.Bool && (Flags & BOOLSUPPORT)) return KS_Enabled;
138 if (LangOpts.Half && (Flags & HALFSUPPORT)) return KS_Enabled;
139 if (LangOpts.WChar && (Flags & WCHARSUPPORT)) return KS_Enabled;
140 if (LangOpts.AltiVec && (Flags & KEYALTIVEC)) return KS_Enabled;
141 if (LangOpts.OpenCL && (Flags & KEYOPENCL)) return KS_Enabled;
142 if (!LangOpts.CPlusPlus && (Flags & KEYNOCXX)) return KS_Enabled;
143 if (LangOpts.C11 && (Flags & KEYC11)) return KS_Enabled;
144 // We treat bridge casts as objective-C keywords so we can warn on them
146 if (LangOpts.ObjC2 && (Flags & KEYARC)) return KS_Enabled;
147 if (LangOpts.ConceptsTS && (Flags & KEYCONCEPTS)) return KS_Enabled;
148 if (LangOpts.ObjC2 && (Flags & KEYOBJC2)) return KS_Enabled;
149 if (LangOpts.CPlusPlus && (Flags & KEYCXX11)) return KS_Future;
153 /// AddKeyword - This method is used to associate a token ID with specific
154 /// identifiers because they are language keywords. This causes the lexer to
155 /// automatically map matching identifiers to specialized token codes.
156 static void AddKeyword(StringRef Keyword,
157 tok::TokenKind TokenCode, unsigned Flags,
158 const LangOptions &LangOpts, IdentifierTable &Table) {
159 KeywordStatus AddResult = getKeywordStatus(LangOpts, Flags);
161 // Don't add this keyword under MSVCCompat.
162 if (LangOpts.MSVCCompat && (Flags & KEYNOMS18) &&
163 !LangOpts.isCompatibleWithMSVC(LangOptions::MSVC2015))
166 // Don't add this keyword under OpenCL.
167 if (LangOpts.OpenCL && (Flags & KEYNOOPENCL))
170 // Don't add this keyword if disabled in this language.
171 if (AddResult == KS_Disabled) return;
173 IdentifierInfo &Info =
174 Table.get(Keyword, AddResult == KS_Future ? tok::identifier : TokenCode);
175 Info.setIsExtensionToken(AddResult == KS_Extension);
176 Info.setIsFutureCompatKeyword(AddResult == KS_Future);
179 /// AddCXXOperatorKeyword - Register a C++ operator keyword alternative
181 static void AddCXXOperatorKeyword(StringRef Keyword,
182 tok::TokenKind TokenCode,
183 IdentifierTable &Table) {
184 IdentifierInfo &Info = Table.get(Keyword, TokenCode);
185 Info.setIsCPlusPlusOperatorKeyword();
188 /// AddObjCKeyword - Register an Objective-C \@keyword like "class" "selector"
190 static void AddObjCKeyword(StringRef Name,
191 tok::ObjCKeywordKind ObjCID,
192 IdentifierTable &Table) {
193 Table.get(Name).setObjCKeywordID(ObjCID);
196 /// AddKeywords - Add all keywords to the symbol table.
198 void IdentifierTable::AddKeywords(const LangOptions &LangOpts) {
199 // Add keywords and tokens for the current language.
200 #define KEYWORD(NAME, FLAGS) \
201 AddKeyword(StringRef(#NAME), tok::kw_ ## NAME, \
202 FLAGS, LangOpts, *this);
203 #define ALIAS(NAME, TOK, FLAGS) \
204 AddKeyword(StringRef(NAME), tok::kw_ ## TOK, \
205 FLAGS, LangOpts, *this);
206 #define CXX_KEYWORD_OPERATOR(NAME, ALIAS) \
207 if (LangOpts.CXXOperatorNames) \
208 AddCXXOperatorKeyword(StringRef(#NAME), tok::ALIAS, *this);
209 #define OBJC1_AT_KEYWORD(NAME) \
210 if (LangOpts.ObjC1) \
211 AddObjCKeyword(StringRef(#NAME), tok::objc_##NAME, *this);
212 #define OBJC2_AT_KEYWORD(NAME) \
213 if (LangOpts.ObjC2) \
214 AddObjCKeyword(StringRef(#NAME), tok::objc_##NAME, *this);
215 #define TESTING_KEYWORD(NAME, FLAGS)
216 #include "clang/Basic/TokenKinds.def"
218 if (LangOpts.ParseUnknownAnytype)
219 AddKeyword("__unknown_anytype", tok::kw___unknown_anytype, KEYALL,
222 // FIXME: __declspec isn't really a CUDA extension, however it is required for
223 // supporting cuda_builtin_vars.h, which uses __declspec(property). Once that
224 // has been rewritten in terms of something more generic, remove this code.
226 AddKeyword("__declspec", tok::kw___declspec, KEYALL, LangOpts, *this);
229 /// \brief Checks if the specified token kind represents a keyword in the
230 /// specified language.
231 /// \returns Status of the keyword in the language.
232 static KeywordStatus getTokenKwStatus(const LangOptions &LangOpts,
235 #define KEYWORD(NAME, FLAGS) \
236 case tok::kw_##NAME: return getKeywordStatus(LangOpts, FLAGS);
237 #include "clang/Basic/TokenKinds.def"
238 default: return KS_Disabled;
242 /// \brief Returns true if the identifier represents a keyword in the
243 /// specified language.
244 bool IdentifierInfo::isKeyword(const LangOptions &LangOpts) {
245 switch (getTokenKwStatus(LangOpts, getTokenID())) {
254 tok::PPKeywordKind IdentifierInfo::getPPKeywordID() const {
255 // We use a perfect hash function here involving the length of the keyword,
256 // the first and third character. For preprocessor ID's there are no
257 // collisions (if there were, the switch below would complain about duplicate
258 // case values). Note that this depends on 'if' being null terminated.
260 #define HASH(LEN, FIRST, THIRD) \
261 (LEN << 5) + (((FIRST-'a') + (THIRD-'a')) & 31)
262 #define CASE(LEN, FIRST, THIRD, NAME) \
263 case HASH(LEN, FIRST, THIRD): \
264 return memcmp(Name, #NAME, LEN) ? tok::pp_not_keyword : tok::pp_ ## NAME
266 unsigned Len = getLength();
267 if (Len < 2) return tok::pp_not_keyword;
268 const char *Name = getNameStart();
269 switch (HASH(Len, Name[0], Name[2])) {
270 default: return tok::pp_not_keyword;
271 CASE( 2, 'i', '\0', if);
272 CASE( 4, 'e', 'i', elif);
273 CASE( 4, 'e', 's', else);
274 CASE( 4, 'l', 'n', line);
275 CASE( 4, 's', 'c', sccs);
276 CASE( 5, 'e', 'd', endif);
277 CASE( 5, 'e', 'r', error);
278 CASE( 5, 'i', 'e', ident);
279 CASE( 5, 'i', 'd', ifdef);
280 CASE( 5, 'u', 'd', undef);
282 CASE( 6, 'a', 's', assert);
283 CASE( 6, 'd', 'f', define);
284 CASE( 6, 'i', 'n', ifndef);
285 CASE( 6, 'i', 'p', import);
286 CASE( 6, 'p', 'a', pragma);
288 CASE( 7, 'd', 'f', defined);
289 CASE( 7, 'i', 'c', include);
290 CASE( 7, 'w', 'r', warning);
292 CASE( 8, 'u', 'a', unassert);
293 CASE(12, 'i', 'c', include_next);
295 CASE(14, '_', 'p', __public_macro);
297 CASE(15, '_', 'p', __private_macro);
299 CASE(16, '_', 'i', __include_macros);
305 //===----------------------------------------------------------------------===//
306 // Stats Implementation
307 //===----------------------------------------------------------------------===//
309 /// PrintStats - Print statistics about how well the identifier table is doing
310 /// at hashing identifiers.
311 void IdentifierTable::PrintStats() const {
312 unsigned NumBuckets = HashTable.getNumBuckets();
313 unsigned NumIdentifiers = HashTable.getNumItems();
314 unsigned NumEmptyBuckets = NumBuckets-NumIdentifiers;
315 unsigned AverageIdentifierSize = 0;
316 unsigned MaxIdentifierLength = 0;
318 // TODO: Figure out maximum times an identifier had to probe for -stats.
319 for (llvm::StringMap<IdentifierInfo*, llvm::BumpPtrAllocator>::const_iterator
320 I = HashTable.begin(), E = HashTable.end(); I != E; ++I) {
321 unsigned IdLen = I->getKeyLength();
322 AverageIdentifierSize += IdLen;
323 if (MaxIdentifierLength < IdLen)
324 MaxIdentifierLength = IdLen;
327 fprintf(stderr, "\n*** Identifier Table Stats:\n");
328 fprintf(stderr, "# Identifiers: %d\n", NumIdentifiers);
329 fprintf(stderr, "# Empty Buckets: %d\n", NumEmptyBuckets);
330 fprintf(stderr, "Hash density (#identifiers per bucket): %f\n",
331 NumIdentifiers/(double)NumBuckets);
332 fprintf(stderr, "Ave identifier length: %f\n",
333 (AverageIdentifierSize/(double)NumIdentifiers));
334 fprintf(stderr, "Max identifier length: %d\n", MaxIdentifierLength);
336 // Compute statistics about the memory allocated for identifiers.
337 HashTable.getAllocator().PrintStats();
340 //===----------------------------------------------------------------------===//
341 // SelectorTable Implementation
342 //===----------------------------------------------------------------------===//
344 unsigned llvm::DenseMapInfo<clang::Selector>::getHashValue(clang::Selector S) {
345 return DenseMapInfo<void*>::getHashValue(S.getAsOpaquePtr());
349 /// MultiKeywordSelector - One of these variable length records is kept for each
350 /// selector containing more than one keyword. We use a folding set
351 /// to unique aggregate names (keyword selectors in ObjC parlance). Access to
352 /// this class is provided strictly through Selector.
353 class MultiKeywordSelector
354 : public DeclarationNameExtra, public llvm::FoldingSetNode {
355 MultiKeywordSelector(unsigned nKeys) {
356 ExtraKindOrNumArgs = NUM_EXTRA_KINDS + nKeys;
359 // Constructor for keyword selectors.
360 MultiKeywordSelector(unsigned nKeys, IdentifierInfo **IIV) {
361 assert((nKeys > 1) && "not a multi-keyword selector");
362 ExtraKindOrNumArgs = NUM_EXTRA_KINDS + nKeys;
364 // Fill in the trailing keyword array.
365 IdentifierInfo **KeyInfo = reinterpret_cast<IdentifierInfo **>(this+1);
366 for (unsigned i = 0; i != nKeys; ++i)
370 // getName - Derive the full selector name and return it.
371 std::string getName() const;
373 unsigned getNumArgs() const { return ExtraKindOrNumArgs - NUM_EXTRA_KINDS; }
375 typedef IdentifierInfo *const *keyword_iterator;
376 keyword_iterator keyword_begin() const {
377 return reinterpret_cast<keyword_iterator>(this+1);
379 keyword_iterator keyword_end() const {
380 return keyword_begin()+getNumArgs();
382 IdentifierInfo *getIdentifierInfoForSlot(unsigned i) const {
383 assert(i < getNumArgs() && "getIdentifierInfoForSlot(): illegal index");
384 return keyword_begin()[i];
386 static void Profile(llvm::FoldingSetNodeID &ID,
387 keyword_iterator ArgTys, unsigned NumArgs) {
388 ID.AddInteger(NumArgs);
389 for (unsigned i = 0; i != NumArgs; ++i)
390 ID.AddPointer(ArgTys[i]);
392 void Profile(llvm::FoldingSetNodeID &ID) {
393 Profile(ID, keyword_begin(), getNumArgs());
396 } // end namespace clang.
398 unsigned Selector::getNumArgs() const {
399 unsigned IIF = getIdentifierInfoFlag();
404 // We point to a MultiKeywordSelector.
405 MultiKeywordSelector *SI = getMultiKeywordSelector();
406 return SI->getNumArgs();
409 IdentifierInfo *Selector::getIdentifierInfoForSlot(unsigned argIndex) const {
410 if (getIdentifierInfoFlag() < MultiArg) {
411 assert(argIndex == 0 && "illegal keyword index");
412 return getAsIdentifierInfo();
414 // We point to a MultiKeywordSelector.
415 MultiKeywordSelector *SI = getMultiKeywordSelector();
416 return SI->getIdentifierInfoForSlot(argIndex);
419 StringRef Selector::getNameForSlot(unsigned int argIndex) const {
420 IdentifierInfo *II = getIdentifierInfoForSlot(argIndex);
421 return II? II->getName() : StringRef();
424 std::string MultiKeywordSelector::getName() const {
425 SmallString<256> Str;
426 llvm::raw_svector_ostream OS(Str);
427 for (keyword_iterator I = keyword_begin(), E = keyword_end(); I != E; ++I) {
429 OS << (*I)->getName();
436 std::string Selector::getAsString() const {
438 return "<null selector>";
440 if (getIdentifierInfoFlag() < MultiArg) {
441 IdentifierInfo *II = getAsIdentifierInfo();
443 // If the number of arguments is 0 then II is guaranteed to not be null.
444 if (getNumArgs() == 0)
445 return II->getName();
450 return II->getName().str() + ":";
453 // We have a multiple keyword selector.
454 return getMultiKeywordSelector()->getName();
457 void Selector::print(llvm::raw_ostream &OS) const {
461 /// Interpreting the given string using the normal CamelCase
462 /// conventions, determine whether the given string starts with the
463 /// given "word", which is assumed to end in a lowercase letter.
464 static bool startsWithWord(StringRef name, StringRef word) {
465 if (name.size() < word.size()) return false;
466 return ((name.size() == word.size() || !isLowercase(name[word.size()])) &&
467 name.startswith(word));
470 ObjCMethodFamily Selector::getMethodFamilyImpl(Selector sel) {
471 IdentifierInfo *first = sel.getIdentifierInfoForSlot(0);
472 if (!first) return OMF_None;
474 StringRef name = first->getName();
475 if (sel.isUnarySelector()) {
476 if (name == "autorelease") return OMF_autorelease;
477 if (name == "dealloc") return OMF_dealloc;
478 if (name == "finalize") return OMF_finalize;
479 if (name == "release") return OMF_release;
480 if (name == "retain") return OMF_retain;
481 if (name == "retainCount") return OMF_retainCount;
482 if (name == "self") return OMF_self;
483 if (name == "initialize") return OMF_initialize;
486 if (name == "performSelector") return OMF_performSelector;
488 // The other method families may begin with a prefix of underscores.
489 while (!name.empty() && name.front() == '_')
490 name = name.substr(1);
492 if (name.empty()) return OMF_None;
493 switch (name.front()) {
495 if (startsWithWord(name, "alloc")) return OMF_alloc;
498 if (startsWithWord(name, "copy")) return OMF_copy;
501 if (startsWithWord(name, "init")) return OMF_init;
504 if (startsWithWord(name, "mutableCopy")) return OMF_mutableCopy;
507 if (startsWithWord(name, "new")) return OMF_new;
516 ObjCInstanceTypeFamily Selector::getInstTypeMethodFamily(Selector sel) {
517 IdentifierInfo *first = sel.getIdentifierInfoForSlot(0);
518 if (!first) return OIT_None;
520 StringRef name = first->getName();
522 if (name.empty()) return OIT_None;
523 switch (name.front()) {
525 if (startsWithWord(name, "array")) return OIT_Array;
528 if (startsWithWord(name, "default")) return OIT_ReturnsSelf;
529 if (startsWithWord(name, "dictionary")) return OIT_Dictionary;
532 if (startsWithWord(name, "shared")) return OIT_ReturnsSelf;
533 if (startsWithWord(name, "standard")) return OIT_Singleton;
535 if (startsWithWord(name, "init")) return OIT_Init;
542 ObjCStringFormatFamily Selector::getStringFormatFamilyImpl(Selector sel) {
543 IdentifierInfo *first = sel.getIdentifierInfoForSlot(0);
544 if (!first) return SFF_None;
546 StringRef name = first->getName();
548 switch (name.front()) {
550 if (name == "appendFormat") return SFF_NSString;
554 if (name == "initWithFormat") return SFF_NSString;
558 if (name == "localizedStringWithFormat") return SFF_NSString;
562 if (name == "stringByAppendingFormat" ||
563 name == "stringWithFormat") return SFF_NSString;
570 struct SelectorTableImpl {
571 llvm::FoldingSet<MultiKeywordSelector> Table;
572 llvm::BumpPtrAllocator Allocator;
574 } // end anonymous namespace.
576 static SelectorTableImpl &getSelectorTableImpl(void *P) {
577 return *static_cast<SelectorTableImpl*>(P);
581 SelectorTable::constructSetterName(StringRef Name) {
582 SmallString<64> SetterName("set");
584 SetterName[3] = toUppercase(SetterName[3]);
589 SelectorTable::constructSetterSelector(IdentifierTable &Idents,
590 SelectorTable &SelTable,
591 const IdentifierInfo *Name) {
592 IdentifierInfo *SetterName =
593 &Idents.get(constructSetterName(Name->getName()));
594 return SelTable.getUnarySelector(SetterName);
597 size_t SelectorTable::getTotalMemory() const {
598 SelectorTableImpl &SelTabImpl = getSelectorTableImpl(Impl);
599 return SelTabImpl.Allocator.getTotalMemory();
602 Selector SelectorTable::getSelector(unsigned nKeys, IdentifierInfo **IIV) {
604 return Selector(IIV[0], nKeys);
606 SelectorTableImpl &SelTabImpl = getSelectorTableImpl(Impl);
608 // Unique selector, to guarantee there is one per name.
609 llvm::FoldingSetNodeID ID;
610 MultiKeywordSelector::Profile(ID, IIV, nKeys);
612 void *InsertPos = nullptr;
613 if (MultiKeywordSelector *SI =
614 SelTabImpl.Table.FindNodeOrInsertPos(ID, InsertPos))
617 // MultiKeywordSelector objects are not allocated with new because they have a
618 // variable size array (for parameter types) at the end of them.
619 unsigned Size = sizeof(MultiKeywordSelector) + nKeys*sizeof(IdentifierInfo *);
620 MultiKeywordSelector *SI =
621 (MultiKeywordSelector*)SelTabImpl.Allocator.Allocate(Size,
622 llvm::alignOf<MultiKeywordSelector>());
623 new (SI) MultiKeywordSelector(nKeys, IIV);
624 SelTabImpl.Table.InsertNode(SI, InsertPos);
628 SelectorTable::SelectorTable() {
629 Impl = new SelectorTableImpl();
632 SelectorTable::~SelectorTable() {
633 delete &getSelectorTableImpl(Impl);
636 const char *clang::getOperatorSpelling(OverloadedOperatorKind Operator) {
639 case NUM_OVERLOADED_OPERATORS:
642 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
643 case OO_##Name: return Spelling;
644 #include "clang/Basic/OperatorKinds.def"
647 llvm_unreachable("Invalid OverloadedOperatorKind!");
650 StringRef clang::getNullabilitySpelling(NullabilityKind kind,
651 bool isContextSensitive) {
653 case NullabilityKind::NonNull:
654 return isContextSensitive ? "nonnull" : "_Nonnull";
656 case NullabilityKind::Nullable:
657 return isContextSensitive ? "nullable" : "_Nullable";
659 case NullabilityKind::Unspecified:
660 return isContextSensitive ? "null_unspecified" : "_Null_unspecified";
662 llvm_unreachable("Unknown nullability kind.");