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