]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/clang/include/clang/Basic/IdentifierTable.h
Merge clang trunk r300422 and resolve conflicts.
[FreeBSD/FreeBSD.git] / contrib / llvm / tools / clang / include / clang / Basic / IdentifierTable.h
1 //===--- IdentifierTable.h - Hash table for identifier lookup ---*- C++ -*-===//
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 /// \file
11 /// \brief Defines the clang::IdentifierInfo, clang::IdentifierTable, and
12 /// clang::Selector interfaces.
13 ///
14 //===----------------------------------------------------------------------===//
15
16 #ifndef LLVM_CLANG_BASIC_IDENTIFIERTABLE_H
17 #define LLVM_CLANG_BASIC_IDENTIFIERTABLE_H
18
19 #include "clang/Basic/LLVM.h"
20 #include "clang/Basic/TokenKinds.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 <cassert>
26 #include <cstddef>
27 #include <cstdint>
28 #include <cstring>
29 #include <new>
30 #include <string>
31 #include <utility>
32
33 namespace llvm {
34
35   template <typename T> struct DenseMapInfo;
36
37 } // end namespace llvm
38
39 namespace clang {
40
41   class LangOptions;
42   class IdentifierInfo;
43   class IdentifierTable;
44   class SourceLocation;
45   class MultiKeywordSelector; // private class used by Selector
46   class DeclarationName;      // AST class that stores declaration names
47
48   /// \brief A simple pair of identifier info and location.
49   typedef std::pair<IdentifierInfo*, SourceLocation> IdentifierLocPair;
50
51 /// One of these records is kept for each identifier that
52 /// is lexed.  This contains information about whether the token was \#define'd,
53 /// is a language keyword, or if it is a front-end token of some sort (e.g. a
54 /// variable or function name).  The preprocessor keeps this information in a
55 /// set, and all tok::identifier tokens have a pointer to one of these.
56 class IdentifierInfo {
57   friend class IdentifierTable;
58
59   unsigned TokenID            : 9; // Front-end token ID or tok::identifier.
60   // Objective-C keyword ('protocol' in '@protocol') or builtin (__builtin_inf).
61   // First NUM_OBJC_KEYWORDS values are for Objective-C, the remaining values
62   // are for builtins.
63   unsigned ObjCOrBuiltinID    :13;
64   bool HasMacro               : 1; // True if there is a #define for this.
65   bool HadMacro               : 1; // True if there was a #define for this.
66   bool IsExtension            : 1; // True if identifier is a lang extension.
67   bool IsFutureCompatKeyword  : 1; // True if identifier is a keyword in a
68                                    // newer Standard or proposed Standard.
69   bool IsPoisoned             : 1; // True if identifier is poisoned.
70   bool IsCPPOperatorKeyword   : 1; // True if ident is a C++ operator keyword.
71   bool NeedsHandleIdentifier  : 1; // See "RecomputeNeedsHandleIdentifier".
72   bool IsFromAST              : 1; // True if identifier was loaded (at least 
73                                    // partially) from an AST file.
74   bool ChangedAfterLoad       : 1; // True if identifier has changed from the
75                                    // definition loaded from an AST file.
76   bool FEChangedAfterLoad     : 1; // True if identifier's frontend information
77                                    // has changed from the definition loaded
78                                    // from an AST file.
79   bool RevertedTokenID        : 1; // True if revertTokenIDToIdentifier was
80                                    // called.
81   bool OutOfDate              : 1; // True if there may be additional
82                                    // information about this identifier
83                                    // stored externally.
84   bool IsModulesImport        : 1; // True if this is the 'import' contextual
85                                    // keyword.
86   // 29 bit left in 64-bit word.
87
88   void *FETokenInfo;               // Managed by the language front-end.
89   llvm::StringMapEntry<IdentifierInfo*> *Entry;
90
91 public:
92   IdentifierInfo();
93   IdentifierInfo(const IdentifierInfo &) = delete;
94   IdentifierInfo &operator=(const IdentifierInfo &) = delete;
95
96   /// \brief Return true if this is the identifier for the specified string.
97   ///
98   /// This is intended to be used for string literals only: II->isStr("foo").
99   template <std::size_t StrLen>
100   bool isStr(const char (&Str)[StrLen]) const {
101     return getLength() == StrLen-1 &&
102            memcmp(getNameStart(), Str, StrLen-1) == 0;
103   }
104
105   /// \brief Return the beginning of the actual null-terminated string for this
106   /// identifier.
107   ///
108   const char *getNameStart() const {
109     if (Entry) return Entry->getKeyData();
110     // FIXME: This is gross. It would be best not to embed specific details
111     // of the PTH file format here.
112     // The 'this' pointer really points to a
113     // std::pair<IdentifierInfo, const char*>, where internal pointer
114     // points to the external string data.
115     typedef std::pair<IdentifierInfo, const char*> actualtype;
116     return ((const actualtype*) this)->second;
117   }
118
119   /// \brief Efficiently return the length of this identifier info.
120   ///
121   unsigned getLength() const {
122     if (Entry) return Entry->getKeyLength();
123     // FIXME: This is gross. It would be best not to embed specific details
124     // of the PTH file format here.
125     // The 'this' pointer really points to a
126     // std::pair<IdentifierInfo, const char*>, where internal pointer
127     // points to the external string data.
128     typedef std::pair<IdentifierInfo, const char*> actualtype;
129     const char* p = ((const actualtype*) this)->second - 2;
130     return (((unsigned) p[0]) | (((unsigned) p[1]) << 8)) - 1;
131   }
132
133   /// \brief Return the actual identifier string.
134   StringRef getName() const {
135     return StringRef(getNameStart(), getLength());
136   }
137
138   /// \brief Return true if this identifier is \#defined to some other value.
139   /// \note The current definition may be in a module and not currently visible.
140   bool hasMacroDefinition() const {
141     return HasMacro;
142   }
143   void setHasMacroDefinition(bool Val) {
144     if (HasMacro == Val) return;
145
146     HasMacro = Val;
147     if (Val) {
148       NeedsHandleIdentifier = true;
149       HadMacro = true;
150     } else {
151       RecomputeNeedsHandleIdentifier();
152     }
153   }
154   /// \brief Returns true if this identifier was \#defined to some value at any
155   /// moment. In this case there should be an entry for the identifier in the
156   /// macro history table in Preprocessor.
157   bool hadMacroDefinition() const {
158     return HadMacro;
159   }
160
161   /// If this is a source-language token (e.g. 'for'), this API
162   /// can be used to cause the lexer to map identifiers to source-language
163   /// tokens.
164   tok::TokenKind getTokenID() const { return (tok::TokenKind)TokenID; }
165
166   /// \brief True if revertTokenIDToIdentifier() was called.
167   bool hasRevertedTokenIDToIdentifier() const { return RevertedTokenID; }
168
169   /// \brief Revert TokenID to tok::identifier; used for GNU libstdc++ 4.2
170   /// compatibility.
171   ///
172   /// TokenID is normally read-only but there are 2 instances where we revert it
173   /// to tok::identifier for libstdc++ 4.2. Keep track of when this happens
174   /// using this method so we can inform serialization about it.
175   void revertTokenIDToIdentifier() {
176     assert(TokenID != tok::identifier && "Already at tok::identifier");
177     TokenID = tok::identifier;
178     RevertedTokenID = true;
179   }
180   void revertIdentifierToTokenID(tok::TokenKind TK) {
181     assert(TokenID == tok::identifier && "Should be at tok::identifier");
182     TokenID = TK;
183     RevertedTokenID = false;
184   }
185
186   /// \brief Return the preprocessor keyword ID for this identifier.
187   ///
188   /// For example, "define" will return tok::pp_define.
189   tok::PPKeywordKind getPPKeywordID() const;
190
191   /// \brief Return the Objective-C keyword ID for the this identifier.
192   ///
193   /// For example, 'class' will return tok::objc_class if ObjC is enabled.
194   tok::ObjCKeywordKind getObjCKeywordID() const {
195     if (ObjCOrBuiltinID < tok::NUM_OBJC_KEYWORDS)
196       return tok::ObjCKeywordKind(ObjCOrBuiltinID);
197     else
198       return tok::objc_not_keyword;
199   }
200   void setObjCKeywordID(tok::ObjCKeywordKind ID) { ObjCOrBuiltinID = ID; }
201
202   /// \brief True if setNotBuiltin() was called.
203   bool hasRevertedBuiltin() const {
204     return ObjCOrBuiltinID == tok::NUM_OBJC_KEYWORDS;
205   }
206
207   /// \brief Revert the identifier to a non-builtin identifier. We do this if
208   /// the name of a known builtin library function is used to declare that
209   /// function, but an unexpected type is specified.
210   void revertBuiltin() {
211     setBuiltinID(0);
212   }
213
214   /// \brief Return a value indicating whether this is a builtin function.
215   ///
216   /// 0 is not-built-in. 1+ are specific builtin functions.
217   unsigned getBuiltinID() const {
218     if (ObjCOrBuiltinID >= tok::NUM_OBJC_KEYWORDS)
219       return ObjCOrBuiltinID - tok::NUM_OBJC_KEYWORDS;
220     else
221       return 0;
222   }
223   void setBuiltinID(unsigned ID) {
224     ObjCOrBuiltinID = ID + tok::NUM_OBJC_KEYWORDS;
225     assert(ObjCOrBuiltinID - unsigned(tok::NUM_OBJC_KEYWORDS) == ID
226            && "ID too large for field!");
227   }
228
229   unsigned getObjCOrBuiltinID() const { return ObjCOrBuiltinID; }
230   void setObjCOrBuiltinID(unsigned ID) { ObjCOrBuiltinID = ID; }
231
232   /// get/setExtension - Initialize information about whether or not this
233   /// language token is an extension.  This controls extension warnings, and is
234   /// only valid if a custom token ID is set.
235   bool isExtensionToken() const { return IsExtension; }
236   void setIsExtensionToken(bool Val) {
237     IsExtension = Val;
238     if (Val)
239       NeedsHandleIdentifier = true;
240     else
241       RecomputeNeedsHandleIdentifier();
242   }
243
244   /// is/setIsFutureCompatKeyword - Initialize information about whether or not
245   /// this language token is a keyword in a newer or proposed Standard. This
246   /// controls compatibility warnings, and is only true when not parsing the
247   /// corresponding Standard. Once a compatibility problem has been diagnosed
248   /// with this keyword, the flag will be cleared.
249   bool isFutureCompatKeyword() const { return IsFutureCompatKeyword; }
250   void setIsFutureCompatKeyword(bool Val) {
251     IsFutureCompatKeyword = Val;
252     if (Val)
253       NeedsHandleIdentifier = true;
254     else
255       RecomputeNeedsHandleIdentifier();
256   }
257
258   /// setIsPoisoned - Mark this identifier as poisoned.  After poisoning, the
259   /// Preprocessor will emit an error every time this token is used.
260   void setIsPoisoned(bool Value = true) {
261     IsPoisoned = Value;
262     if (Value)
263       NeedsHandleIdentifier = true;
264     else
265       RecomputeNeedsHandleIdentifier();
266   }
267
268   /// \brief Return true if this token has been poisoned.
269   bool isPoisoned() const { return IsPoisoned; }
270
271   /// isCPlusPlusOperatorKeyword/setIsCPlusPlusOperatorKeyword controls whether
272   /// this identifier is a C++ alternate representation of an operator.
273   void setIsCPlusPlusOperatorKeyword(bool Val = true) {
274     IsCPPOperatorKeyword = Val;
275     if (Val)
276       NeedsHandleIdentifier = true;
277     else
278       RecomputeNeedsHandleIdentifier();
279   }
280   bool isCPlusPlusOperatorKeyword() const { return IsCPPOperatorKeyword; }
281
282   /// \brief Return true if this token is a keyword in the specified language.
283   bool isKeyword(const LangOptions &LangOpts) const;
284
285   /// \brief Return true if this token is a C++ keyword in the specified
286   /// language.
287   bool isCPlusPlusKeyword(const LangOptions &LangOpts) const;
288
289   /// getFETokenInfo/setFETokenInfo - The language front-end is allowed to
290   /// associate arbitrary metadata with this token.
291   template<typename T>
292   T *getFETokenInfo() const { return static_cast<T*>(FETokenInfo); }
293   void setFETokenInfo(void *T) { FETokenInfo = T; }
294
295   /// \brief Return true if the Preprocessor::HandleIdentifier must be called
296   /// on a token of this identifier.
297   ///
298   /// If this returns false, we know that HandleIdentifier will not affect
299   /// the token.
300   bool isHandleIdentifierCase() const { return NeedsHandleIdentifier; }
301
302   /// \brief Return true if the identifier in its current state was loaded
303   /// from an AST file.
304   bool isFromAST() const { return IsFromAST; }
305
306   void setIsFromAST() { IsFromAST = true; }
307
308   /// \brief Determine whether this identifier has changed since it was loaded
309   /// from an AST file.
310   bool hasChangedSinceDeserialization() const {
311     return ChangedAfterLoad;
312   }
313   
314   /// \brief Note that this identifier has changed since it was loaded from
315   /// an AST file.
316   void setChangedSinceDeserialization() {
317     ChangedAfterLoad = true;
318   }
319
320   /// \brief Determine whether the frontend token information for this
321   /// identifier has changed since it was loaded from an AST file.
322   bool hasFETokenInfoChangedSinceDeserialization() const {
323     return FEChangedAfterLoad;
324   }
325   
326   /// \brief Note that the frontend token information for this identifier has
327   /// changed since it was loaded from an AST file.
328   void setFETokenInfoChangedSinceDeserialization() {
329     FEChangedAfterLoad = true;
330   }
331
332   /// \brief Determine whether the information for this identifier is out of
333   /// date with respect to the external source.
334   bool isOutOfDate() const { return OutOfDate; }
335   
336   /// \brief Set whether the information for this identifier is out of
337   /// date with respect to the external source.
338   void setOutOfDate(bool OOD) {
339     OutOfDate = OOD;
340     if (OOD)
341       NeedsHandleIdentifier = true;
342     else
343       RecomputeNeedsHandleIdentifier();
344   }
345   
346   /// \brief Determine whether this is the contextual keyword \c import.
347   bool isModulesImport() const { return IsModulesImport; }
348   
349   /// \brief Set whether this identifier is the contextual keyword \c import.
350   void setModulesImport(bool I) {
351     IsModulesImport = I;
352     if (I)
353       NeedsHandleIdentifier = true;
354     else
355       RecomputeNeedsHandleIdentifier();
356   }
357
358   /// \brief Provide less than operator for lexicographical sorting.
359   bool operator<(const IdentifierInfo &RHS) const {
360     return getName() < RHS.getName();
361   }
362
363 private:
364   /// The Preprocessor::HandleIdentifier does several special (but rare)
365   /// things to identifiers of various sorts.  For example, it changes the
366   /// \c for keyword token from tok::identifier to tok::for.
367   ///
368   /// This method is very tied to the definition of HandleIdentifier.  Any
369   /// change to it should be reflected here.
370   void RecomputeNeedsHandleIdentifier() {
371     NeedsHandleIdentifier =
372       (isPoisoned() | hasMacroDefinition() | isCPlusPlusOperatorKeyword() |
373        isExtensionToken() | isFutureCompatKeyword() || isOutOfDate() ||
374        isModulesImport());
375   }
376 };
377
378 /// \brief An RAII object for [un]poisoning an identifier within a scope.
379 ///
380 /// \p II is allowed to be null, in which case objects of this type have
381 /// no effect.
382 class PoisonIdentifierRAIIObject {
383   IdentifierInfo *const II;
384   const bool OldValue;
385
386 public:
387   PoisonIdentifierRAIIObject(IdentifierInfo *II, bool NewValue)
388     : II(II), OldValue(II ? II->isPoisoned() : false) {
389     if(II)
390       II->setIsPoisoned(NewValue);
391   }
392
393   ~PoisonIdentifierRAIIObject() {
394     if(II)
395       II->setIsPoisoned(OldValue);
396   }
397 };
398
399 /// \brief An iterator that walks over all of the known identifiers
400 /// in the lookup table.
401 ///
402 /// Since this iterator uses an abstract interface via virtual
403 /// functions, it uses an object-oriented interface rather than the
404 /// more standard C++ STL iterator interface. In this OO-style
405 /// iteration, the single function \c Next() provides dereference,
406 /// advance, and end-of-sequence checking in a single
407 /// operation. Subclasses of this iterator type will provide the
408 /// actual functionality.
409 class IdentifierIterator {
410 protected:
411   IdentifierIterator() = default;
412   
413 public:
414   IdentifierIterator(const IdentifierIterator &) = delete;
415   IdentifierIterator &operator=(const IdentifierIterator &) = delete;
416
417   virtual ~IdentifierIterator();
418
419   /// \brief Retrieve the next string in the identifier table and
420   /// advances the iterator for the following string.
421   ///
422   /// \returns The next string in the identifier table. If there is
423   /// no such string, returns an empty \c StringRef.
424   virtual StringRef Next() = 0;
425 };
426
427 /// \brief Provides lookups to, and iteration over, IdentiferInfo objects.
428 class IdentifierInfoLookup {
429 public:
430   virtual ~IdentifierInfoLookup();
431
432   /// \brief Return the IdentifierInfo for the specified named identifier.
433   ///
434   /// Unlike the version in IdentifierTable, this returns a pointer instead
435   /// of a reference.  If the pointer is null then the IdentifierInfo cannot
436   /// be found.
437   virtual IdentifierInfo* get(StringRef Name) = 0;
438
439   /// \brief Retrieve an iterator into the set of all identifiers
440   /// known to this identifier lookup source.
441   ///
442   /// This routine provides access to all of the identifiers known to
443   /// the identifier lookup, allowing access to the contents of the
444   /// identifiers without introducing the overhead of constructing
445   /// IdentifierInfo objects for each.
446   ///
447   /// \returns A new iterator into the set of known identifiers. The
448   /// caller is responsible for deleting this iterator.
449   virtual IdentifierIterator *getIdentifiers();
450 };
451
452 /// \brief Implements an efficient mapping from strings to IdentifierInfo nodes.
453 ///
454 /// This has no other purpose, but this is an extremely performance-critical
455 /// piece of the code, as each occurrence of every identifier goes through
456 /// here when lexed.
457 class IdentifierTable {
458   // Shark shows that using MallocAllocator is *much* slower than using this
459   // BumpPtrAllocator!
460   typedef llvm::StringMap<IdentifierInfo*, llvm::BumpPtrAllocator> HashTableTy;
461   HashTableTy HashTable;
462
463   IdentifierInfoLookup* ExternalLookup;
464
465 public:
466   /// \brief Create the identifier table, populating it with info about the
467   /// language keywords for the language specified by \p LangOpts.
468   IdentifierTable(const LangOptions &LangOpts,
469                   IdentifierInfoLookup* externalLookup = nullptr);
470
471   /// \brief Set the external identifier lookup mechanism.
472   void setExternalIdentifierLookup(IdentifierInfoLookup *IILookup) {
473     ExternalLookup = IILookup;
474   }
475
476   /// \brief Retrieve the external identifier lookup object, if any.
477   IdentifierInfoLookup *getExternalIdentifierLookup() const {
478     return ExternalLookup;
479   }
480   
481   llvm::BumpPtrAllocator& getAllocator() {
482     return HashTable.getAllocator();
483   }
484
485   /// \brief Return the identifier token info for the specified named
486   /// identifier.
487   IdentifierInfo &get(StringRef Name) {
488     auto &Entry = *HashTable.insert(std::make_pair(Name, nullptr)).first;
489
490     IdentifierInfo *&II = Entry.second;
491     if (II) return *II;
492
493     // No entry; if we have an external lookup, look there first.
494     if (ExternalLookup) {
495       II = ExternalLookup->get(Name);
496       if (II)
497         return *II;
498     }
499
500     // Lookups failed, make a new IdentifierInfo.
501     void *Mem = getAllocator().Allocate<IdentifierInfo>();
502     II = new (Mem) IdentifierInfo();
503
504     // Make sure getName() knows how to find the IdentifierInfo
505     // contents.
506     II->Entry = &Entry;
507
508     return *II;
509   }
510
511   IdentifierInfo &get(StringRef Name, tok::TokenKind TokenCode) {
512     IdentifierInfo &II = get(Name);
513     II.TokenID = TokenCode;
514     assert(II.TokenID == (unsigned) TokenCode && "TokenCode too large");
515     return II;
516   }
517
518   /// \brief Gets an IdentifierInfo for the given name without consulting
519   ///        external sources.
520   ///
521   /// This is a version of get() meant for external sources that want to
522   /// introduce or modify an identifier. If they called get(), they would
523   /// likely end up in a recursion.
524   IdentifierInfo &getOwn(StringRef Name) {
525     auto &Entry = *HashTable.insert(std::make_pair(Name, nullptr)).first;
526
527     IdentifierInfo *&II = Entry.second;
528     if (II)
529       return *II;
530
531     // Lookups failed, make a new IdentifierInfo.
532     void *Mem = getAllocator().Allocate<IdentifierInfo>();
533     II = new (Mem) IdentifierInfo();
534
535     // Make sure getName() knows how to find the IdentifierInfo
536     // contents.
537     II->Entry = &Entry;
538
539     // If this is the 'import' contextual keyword, mark it as such.
540     if (Name.equals("import"))
541       II->setModulesImport(true);
542
543     return *II;
544   }
545
546   typedef HashTableTy::const_iterator iterator;
547   typedef HashTableTy::const_iterator const_iterator;
548
549   iterator begin() const { return HashTable.begin(); }
550   iterator end() const   { return HashTable.end(); }
551   unsigned size() const  { return HashTable.size(); }
552
553   /// \brief Print some statistics to stderr that indicate how well the
554   /// hashing is doing.
555   void PrintStats() const;
556
557   void AddKeywords(const LangOptions &LangOpts);
558 };
559
560 /// \brief A family of Objective-C methods. 
561 ///
562 /// These families have no inherent meaning in the language, but are
563 /// nonetheless central enough in the existing implementations to
564 /// merit direct AST support.  While, in theory, arbitrary methods can
565 /// be considered to form families, we focus here on the methods
566 /// involving allocation and retain-count management, as these are the
567 /// most "core" and the most likely to be useful to diverse clients
568 /// without extra information.
569 ///
570 /// Both selectors and actual method declarations may be classified
571 /// into families.  Method families may impose additional restrictions
572 /// beyond their selector name; for example, a method called '_init'
573 /// that returns void is not considered to be in the 'init' family
574 /// (but would be if it returned 'id').  It is also possible to
575 /// explicitly change or remove a method's family.  Therefore the
576 /// method's family should be considered the single source of truth.
577 enum ObjCMethodFamily {
578   /// \brief No particular method family.
579   OMF_None,
580
581   // Selectors in these families may have arbitrary arity, may be
582   // written with arbitrary leading underscores, and may have
583   // additional CamelCase "words" in their first selector chunk
584   // following the family name.
585   OMF_alloc,
586   OMF_copy,
587   OMF_init,
588   OMF_mutableCopy,
589   OMF_new,
590
591   // These families are singletons consisting only of the nullary
592   // selector with the given name.
593   OMF_autorelease,
594   OMF_dealloc,
595   OMF_finalize,
596   OMF_release,
597   OMF_retain,
598   OMF_retainCount,
599   OMF_self,
600   OMF_initialize,
601
602   // performSelector families
603   OMF_performSelector
604 };
605
606 /// Enough bits to store any enumerator in ObjCMethodFamily or
607 /// InvalidObjCMethodFamily.
608 enum { ObjCMethodFamilyBitWidth = 4 };
609
610 /// \brief An invalid value of ObjCMethodFamily.
611 enum { InvalidObjCMethodFamily = (1 << ObjCMethodFamilyBitWidth) - 1 };
612
613 /// \brief A family of Objective-C methods.
614 ///
615 /// These are family of methods whose result type is initially 'id', but
616 /// but are candidate for the result type to be changed to 'instancetype'.
617 enum ObjCInstanceTypeFamily {
618   OIT_None,
619   OIT_Array,
620   OIT_Dictionary,
621   OIT_Singleton,
622   OIT_Init,
623   OIT_ReturnsSelf
624 };
625
626 enum ObjCStringFormatFamily {
627   SFF_None,
628   SFF_NSString,
629   SFF_CFString
630 };
631
632 /// \brief Smart pointer class that efficiently represents Objective-C method
633 /// names.
634 ///
635 /// This class will either point to an IdentifierInfo or a
636 /// MultiKeywordSelector (which is private). This enables us to optimize
637 /// selectors that take no arguments and selectors that take 1 argument, which
638 /// accounts for 78% of all selectors in Cocoa.h.
639 class Selector {
640   friend class Diagnostic;
641
642   enum IdentifierInfoFlag {
643     // Empty selector = 0.
644     ZeroArg  = 0x1,
645     OneArg   = 0x2,
646     MultiArg = 0x3,
647     ArgFlags = ZeroArg|OneArg
648   };
649   uintptr_t InfoPtr; // a pointer to the MultiKeywordSelector or IdentifierInfo.
650
651   Selector(IdentifierInfo *II, unsigned nArgs) {
652     InfoPtr = reinterpret_cast<uintptr_t>(II);
653     assert((InfoPtr & ArgFlags) == 0 &&"Insufficiently aligned IdentifierInfo");
654     assert(nArgs < 2 && "nArgs not equal to 0/1");
655     InfoPtr |= nArgs+1;
656   }
657   Selector(MultiKeywordSelector *SI) {
658     InfoPtr = reinterpret_cast<uintptr_t>(SI);
659     assert((InfoPtr & ArgFlags) == 0 &&"Insufficiently aligned IdentifierInfo");
660     InfoPtr |= MultiArg;
661   }
662
663   IdentifierInfo *getAsIdentifierInfo() const {
664     if (getIdentifierInfoFlag() < MultiArg)
665       return reinterpret_cast<IdentifierInfo *>(InfoPtr & ~ArgFlags);
666     return nullptr;
667   }
668
669   MultiKeywordSelector *getMultiKeywordSelector() const {
670     return reinterpret_cast<MultiKeywordSelector *>(InfoPtr & ~ArgFlags);
671   }
672   
673   unsigned getIdentifierInfoFlag() const {
674     return InfoPtr & ArgFlags;
675   }
676
677   static ObjCMethodFamily getMethodFamilyImpl(Selector sel);
678   
679   static ObjCStringFormatFamily getStringFormatFamilyImpl(Selector sel);
680
681 public:
682   friend class SelectorTable; // only the SelectorTable can create these
683   friend class DeclarationName; // and the AST's DeclarationName.
684
685   /// The default ctor should only be used when creating data structures that
686   ///  will contain selectors.
687   Selector() : InfoPtr(0) {}
688   Selector(uintptr_t V) : InfoPtr(V) {}
689
690   /// operator==/!= - Indicate whether the specified selectors are identical.
691   bool operator==(Selector RHS) const {
692     return InfoPtr == RHS.InfoPtr;
693   }
694   bool operator!=(Selector RHS) const {
695     return InfoPtr != RHS.InfoPtr;
696   }
697
698   void *getAsOpaquePtr() const {
699     return reinterpret_cast<void*>(InfoPtr);
700   }
701
702   /// \brief Determine whether this is the empty selector.
703   bool isNull() const { return InfoPtr == 0; }
704
705   // Predicates to identify the selector type.
706   bool isKeywordSelector() const {
707     return getIdentifierInfoFlag() != ZeroArg;
708   }
709
710   bool isUnarySelector() const {
711     return getIdentifierInfoFlag() == ZeroArg;
712   }
713
714   unsigned getNumArgs() const;
715   
716   /// \brief Retrieve the identifier at a given position in the selector.
717   ///
718   /// Note that the identifier pointer returned may be NULL. Clients that only
719   /// care about the text of the identifier string, and not the specific, 
720   /// uniqued identifier pointer, should use \c getNameForSlot(), which returns
721   /// an empty string when the identifier pointer would be NULL.
722   ///
723   /// \param argIndex The index for which we want to retrieve the identifier.
724   /// This index shall be less than \c getNumArgs() unless this is a keyword
725   /// selector, in which case 0 is the only permissible value.
726   ///
727   /// \returns the uniqued identifier for this slot, or NULL if this slot has
728   /// no corresponding identifier.
729   IdentifierInfo *getIdentifierInfoForSlot(unsigned argIndex) const;
730   
731   /// \brief Retrieve the name at a given position in the selector.
732   ///
733   /// \param argIndex The index for which we want to retrieve the name.
734   /// This index shall be less than \c getNumArgs() unless this is a keyword
735   /// selector, in which case 0 is the only permissible value.
736   ///
737   /// \returns the name for this slot, which may be the empty string if no
738   /// name was supplied.
739   StringRef getNameForSlot(unsigned argIndex) const;
740   
741   /// \brief Derive the full selector name (e.g. "foo:bar:") and return
742   /// it as an std::string.
743   std::string getAsString() const;
744
745   /// \brief Prints the full selector name (e.g. "foo:bar:").
746   void print(llvm::raw_ostream &OS) const;
747
748   /// \brief Derive the conventional family of this method.
749   ObjCMethodFamily getMethodFamily() const {
750     return getMethodFamilyImpl(*this);
751   }
752   
753   ObjCStringFormatFamily getStringFormatFamily() const {
754     return getStringFormatFamilyImpl(*this);
755   }
756   
757   static Selector getEmptyMarker() {
758     return Selector(uintptr_t(-1));
759   }
760
761   static Selector getTombstoneMarker() {
762     return Selector(uintptr_t(-2));
763   }
764   
765   static ObjCInstanceTypeFamily getInstTypeMethodFamily(Selector sel);
766 };
767
768 /// \brief This table allows us to fully hide how we implement
769 /// multi-keyword caching.
770 class SelectorTable {
771   void *Impl;  // Actually a SelectorTableImpl
772
773 public:
774   SelectorTable();
775   SelectorTable(const SelectorTable &) = delete;
776   SelectorTable &operator=(const SelectorTable &) = delete;
777   ~SelectorTable();
778
779   /// \brief Can create any sort of selector.
780   ///
781   /// \p NumArgs indicates whether this is a no argument selector "foo", a
782   /// single argument selector "foo:" or multi-argument "foo:bar:".
783   Selector getSelector(unsigned NumArgs, IdentifierInfo **IIV);
784
785   Selector getUnarySelector(IdentifierInfo *ID) {
786     return Selector(ID, 1);
787   }
788   Selector getNullarySelector(IdentifierInfo *ID) {
789     return Selector(ID, 0);
790   }
791
792   /// \brief Return the total amount of memory allocated for managing selectors.
793   size_t getTotalMemory() const;
794
795   /// \brief Return the default setter name for the given identifier.
796   ///
797   /// This is "set" + \p Name where the initial character of \p Name
798   /// has been capitalized.
799   static SmallString<64> constructSetterName(StringRef Name);
800
801   /// \brief Return the default setter selector for the given identifier.
802   ///
803   /// This is "set" + \p Name where the initial character of \p Name
804   /// has been capitalized.
805   static Selector constructSetterSelector(IdentifierTable &Idents,
806                                           SelectorTable &SelTable,
807                                           const IdentifierInfo *Name);
808 };
809
810 /// DeclarationNameExtra - Common base of the MultiKeywordSelector,
811 /// CXXSpecialName, and CXXOperatorIdName classes, all of which are
812 /// private classes that describe different kinds of names.
813 class DeclarationNameExtra {
814 public:
815   /// ExtraKind - The kind of "extra" information stored in the
816   /// DeclarationName. See @c ExtraKindOrNumArgs for an explanation of
817   /// how these enumerator values are used.
818   enum ExtraKind {
819     CXXConstructor = 0,
820     CXXDestructor,
821     CXXConversionFunction,
822 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
823     CXXOperator##Name,
824 #include "clang/Basic/OperatorKinds.def"
825     CXXDeductionGuide,
826     CXXLiteralOperator,
827     CXXUsingDirective,
828     NUM_EXTRA_KINDS
829   };
830
831   /// ExtraKindOrNumArgs - Either the kind of C++ special name or
832   /// operator-id (if the value is one of the CXX* enumerators of
833   /// ExtraKind), in which case the DeclarationNameExtra is also a
834   /// CXXSpecialName, (for CXXConstructor, CXXDestructor, or
835   /// CXXConversionFunction) CXXOperatorIdName, or CXXLiteralOperatorName,
836   /// it may be also name common to C++ using-directives (CXXUsingDirective),
837   /// otherwise it is NUM_EXTRA_KINDS+NumArgs, where NumArgs is the number of
838   /// arguments in the Objective-C selector, in which case the
839   /// DeclarationNameExtra is also a MultiKeywordSelector.
840   unsigned ExtraKindOrNumArgs;
841 };
842
843 }  // end namespace clang
844
845 namespace llvm {
846
847 /// Define DenseMapInfo so that Selectors can be used as keys in DenseMap and
848 /// DenseSets.
849 template <>
850 struct DenseMapInfo<clang::Selector> {
851   static inline clang::Selector getEmptyKey() {
852     return clang::Selector::getEmptyMarker();
853   }
854
855   static inline clang::Selector getTombstoneKey() {
856     return clang::Selector::getTombstoneMarker();
857   }
858
859   static unsigned getHashValue(clang::Selector S);
860
861   static bool isEqual(clang::Selector LHS, clang::Selector RHS) {
862     return LHS == RHS;
863   }
864 };
865
866 template <>
867 struct isPodLike<clang::Selector> { static const bool value = true; };
868
869 template <typename T> class PointerLikeTypeTraits;
870
871 template<>
872 class PointerLikeTypeTraits<clang::Selector> {
873 public:
874   static inline const void *getAsVoidPointer(clang::Selector P) {
875     return P.getAsOpaquePtr();
876   }
877
878   static inline clang::Selector getFromVoidPointer(const void *P) {
879     return clang::Selector(reinterpret_cast<uintptr_t>(P));
880   }
881
882   enum { NumLowBitsAvailable = 0 };  
883 };
884
885 // Provide PointerLikeTypeTraits for IdentifierInfo pointers, which
886 // are not guaranteed to be 8-byte aligned.
887 template<>
888 class PointerLikeTypeTraits<clang::IdentifierInfo*> {
889 public:
890   static inline void *getAsVoidPointer(clang::IdentifierInfo* P) {
891     return P;
892   }
893
894   static inline clang::IdentifierInfo *getFromVoidPointer(void *P) {
895     return static_cast<clang::IdentifierInfo*>(P);
896   }
897
898   enum { NumLowBitsAvailable = 1 };
899 };
900
901 template<>
902 class PointerLikeTypeTraits<const clang::IdentifierInfo*> {
903 public:
904   static inline const void *getAsVoidPointer(const clang::IdentifierInfo* P) {
905     return P;
906   }
907
908   static inline const clang::IdentifierInfo *getFromVoidPointer(const void *P) {
909     return static_cast<const clang::IdentifierInfo*>(P);
910   }
911
912   enum { NumLowBitsAvailable = 1 };
913 };
914
915 } // end namespace llvm
916
917 #endif // LLVM_CLANG_BASIC_IDENTIFIERTABLE_H