1//===-- DeclBase.h - Base Classes for representing declarations -*- 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// This file defines the Decl and DeclContext interfaces.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_CLANG_AST_DECLBASE_H
15#define LLVM_CLANG_AST_DECLBASE_H
16
17#include "clang/AST/AttrIterator.h"
18#include "clang/AST/DeclarationName.h"
19#include "clang/Basic/Specifiers.h"
20#include "clang/Basic/VersionTuple.h"
21#include "llvm/ADT/PointerUnion.h"
22#include "llvm/ADT/iterator.h"
23#include "llvm/ADT/iterator_range.h"
24#include "llvm/Support/Compiler.h"
25#include "llvm/Support/PrettyStackTrace.h"
26
27namespace clang {
28class ASTMutationListener;
29class BlockDecl;
30class CXXRecordDecl;
31class CompoundStmt;
32class DeclContext;
33class DeclarationName;
34class DependentDiagnostic;
35class EnumDecl;
36class ExportDecl;
37class ExternalSourceSymbolAttr;
38class FunctionDecl;
39class FunctionType;
40enum Linkage : unsigned char;
41class LinkageComputer;
42class LinkageSpecDecl;
43class Module;
44class NamedDecl;
45class NamespaceDecl;
46class ObjCCategoryDecl;
47class ObjCCategoryImplDecl;
48class ObjCContainerDecl;
49class ObjCImplDecl;
50class ObjCImplementationDecl;
51class ObjCInterfaceDecl;
52class ObjCMethodDecl;
53class ObjCProtocolDecl;
54struct PrintingPolicy;
55class RecordDecl;
56class Stmt;
57class StoredDeclsMap;
58class TemplateDecl;
59class TranslationUnitDecl;
60class UsingDirectiveDecl;
61}
62
63namespace clang {
64
65 /// \brief Captures the result of checking the availability of a
66 /// declaration.
67 enum AvailabilityResult {
68 AR_Available = 0,
69 AR_NotYetIntroduced,
70 AR_Deprecated,
71 AR_Unavailable
72 };
73
74/// Decl - This represents one declaration (or definition), e.g. a variable,
75/// typedef, function, struct, etc.
76///
77/// Note: There are objects tacked on before the *beginning* of Decl
78/// (and its subclasses) in its Decl::operator new(). Proper alignment
79/// of all subclasses (not requiring more than the alignment of Decl) is
80/// asserted in DeclBase.cpp.
81class LLVM_ALIGNAS(/*alignof(uint64_t)*/ 8) Decl {
82public:
83 /// \brief Lists the kind of concrete classes of Decl.
84 enum Kind {
85#define DECL(DERIVED, BASE) DERIVED,
86#define ABSTRACT_DECL(DECL)
87#define DECL_RANGE(BASE, START, END) \
88 first##BASE = START, last##BASE = END,
89#define LAST_DECL_RANGE(BASE, START, END) \
90 first##BASE = START, last##BASE = END
91#include "clang/AST/DeclNodes.inc"
92 };
93
94 /// \brief A placeholder type used to construct an empty shell of a
95 /// decl-derived type that will be filled in later (e.g., by some
96 /// deserialization method).
97 struct EmptyShell { };
98
99 /// IdentifierNamespace - The different namespaces in which
100 /// declarations may appear. According to C99 6.2.3, there are
101 /// four namespaces, labels, tags, members and ordinary
102 /// identifiers. C++ describes lookup completely differently:
103 /// certain lookups merely "ignore" certain kinds of declarations,
104 /// usually based on whether the declaration is of a type, etc.
105 ///
106 /// These are meant as bitmasks, so that searches in
107 /// C++ can look into the "tag" namespace during ordinary lookup.
108 ///
109 /// Decl currently provides 15 bits of IDNS bits.
110 enum IdentifierNamespace {
111 /// Labels, declared with 'x:' and referenced with 'goto x'.
112 IDNS_Label = 0x0001,
113
114 /// Tags, declared with 'struct foo;' and referenced with
115 /// 'struct foo'. All tags are also types. This is what
116 /// elaborated-type-specifiers look for in C.
117 /// This also contains names that conflict with tags in the
118 /// same scope but that are otherwise ordinary names (non-type
119 /// template parameters and indirect field declarations).
120 IDNS_Tag = 0x0002,
121
122 /// Types, declared with 'struct foo', typedefs, etc.
123 /// This is what elaborated-type-specifiers look for in C++,
124 /// but note that it's ill-formed to find a non-tag.
125 IDNS_Type = 0x0004,
126
127 /// Members, declared with object declarations within tag
128 /// definitions. In C, these can only be found by "qualified"
129 /// lookup in member expressions. In C++, they're found by
130 /// normal lookup.
131 IDNS_Member = 0x0008,
132
133 /// Namespaces, declared with 'namespace foo {}'.
134 /// Lookup for nested-name-specifiers find these.
135 IDNS_Namespace = 0x0010,
136
137 /// Ordinary names. In C, everything that's not a label, tag,
138 /// member, or function-local extern ends up here.
139 IDNS_Ordinary = 0x0020,
140
141 /// Objective C \@protocol.
142 IDNS_ObjCProtocol = 0x0040,
143
144 /// This declaration is a friend function. A friend function
145 /// declaration is always in this namespace but may also be in
146 /// IDNS_Ordinary if it was previously declared.
147 IDNS_OrdinaryFriend = 0x0080,
148
149 /// This declaration is a friend class. A friend class
150 /// declaration is always in this namespace but may also be in
151 /// IDNS_Tag|IDNS_Type if it was previously declared.
152 IDNS_TagFriend = 0x0100,
153
154 /// This declaration is a using declaration. A using declaration
155 /// *introduces* a number of other declarations into the current
156 /// scope, and those declarations use the IDNS of their targets,
157 /// but the actual using declarations go in this namespace.
158 IDNS_Using = 0x0200,
159
160 /// This declaration is a C++ operator declared in a non-class
161 /// context. All such operators are also in IDNS_Ordinary.
162 /// C++ lexical operator lookup looks for these.
163 IDNS_NonMemberOperator = 0x0400,
164
165 /// This declaration is a function-local extern declaration of a
166 /// variable or function. This may also be IDNS_Ordinary if it
167 /// has been declared outside any function. These act mostly like
168 /// invisible friend declarations, but are also visible to unqualified
169 /// lookup within the scope of the declaring function.
170 IDNS_LocalExtern = 0x0800,
171
172 /// This declaration is an OpenMP user defined reduction construction.
173 IDNS_OMPReduction = 0x1000
174 };
175
176 /// ObjCDeclQualifier - 'Qualifiers' written next to the return and
177 /// parameter types in method declarations. Other than remembering
178 /// them and mangling them into the method's signature string, these
179 /// are ignored by the compiler; they are consumed by certain
180 /// remote-messaging frameworks.
181 ///
182 /// in, inout, and out are mutually exclusive and apply only to
183 /// method parameters. bycopy and byref are mutually exclusive and
184 /// apply only to method parameters (?). oneway applies only to
185 /// results. All of these expect their corresponding parameter to
186 /// have a particular type. None of this is currently enforced by
187 /// clang.
188 ///
189 /// This should be kept in sync with ObjCDeclSpec::ObjCDeclQualifier.
190 enum ObjCDeclQualifier {
191 OBJC_TQ_None = 0x0,
192 OBJC_TQ_In = 0x1,
193 OBJC_TQ_Inout = 0x2,
194 OBJC_TQ_Out = 0x4,
195 OBJC_TQ_Bycopy = 0x8,
196 OBJC_TQ_Byref = 0x10,
197 OBJC_TQ_Oneway = 0x20,
198
199 /// The nullability qualifier is set when the nullability of the
200 /// result or parameter was expressed via a context-sensitive
201 /// keyword.
202 OBJC_TQ_CSNullability = 0x40
203 };
204
205 /// The kind of ownership a declaration has, for visibility purposes.
206 /// This enumeration is designed such that higher values represent higher
207 /// levels of name hiding.
208 enum class ModuleOwnershipKind : unsigned {
209 /// This declaration is not owned by a module.
210 Unowned,
211 /// This declaration has an owning module, but is globally visible
212 /// (typically because its owning module is visible and we know that
213 /// modules cannot later become hidden in this compilation).
214 /// After serialization and deserialization, this will be converted
215 /// to VisibleWhenImported.
216 Visible,
217 /// This declaration has an owning module, and is visible when that
218 /// module is imported.
219 VisibleWhenImported,
220 /// This declaration has an owning module, but is only visible to
221 /// lookups that occur within that module.
222 ModulePrivate
223 };
224
225protected:
226 /// \brief The next declaration within the same lexical
227 /// DeclContext. These pointers form the linked list that is
228 /// traversed via DeclContext's decls_begin()/decls_end().
229 ///
230 /// The extra two bits are used for the ModuleOwnershipKind.
231 llvm::PointerIntPair<Decl *, 2, ModuleOwnershipKind> NextInContextAndBits;
232
233private:
234 friend class DeclContext;
235
236 struct MultipleDC {
237 DeclContext *SemanticDC;
238 DeclContext *LexicalDC;
239 };
240
241
242 /// DeclCtx - Holds either a DeclContext* or a MultipleDC*.
243 /// For declarations that don't contain C++ scope specifiers, it contains
244 /// the DeclContext where the Decl was declared.
245 /// For declarations with C++ scope specifiers, it contains a MultipleDC*
246 /// with the context where it semantically belongs (SemanticDC) and the
247 /// context where it was lexically declared (LexicalDC).
248 /// e.g.:
249 ///
250 /// namespace A {
251 /// void f(); // SemanticDC == LexicalDC == 'namespace A'
252 /// }
253 /// void A::f(); // SemanticDC == namespace 'A'
254 /// // LexicalDC == global namespace
255 llvm::PointerUnion<DeclContext*, MultipleDC*> DeclCtx;
256
257 inline bool isInSemaDC() const { return DeclCtx.is<DeclContext*>(); }
258 inline bool isOutOfSemaDC() const { return DeclCtx.is<MultipleDC*>(); }
259 inline MultipleDC *getMultipleDC() const {
260 return DeclCtx.get<MultipleDC*>();
261 }
262 inline DeclContext *getSemanticDC() const {
263 return DeclCtx.get<DeclContext*>();
264 }
265
266 /// Loc - The location of this decl.
267 SourceLocation Loc;
268
269 /// DeclKind - This indicates which class this is.
270 unsigned DeclKind : 7;
271
272 /// InvalidDecl - This indicates a semantic error occurred.
273 unsigned InvalidDecl : 1;
274
275 /// HasAttrs - This indicates whether the decl has attributes or not.
276 unsigned HasAttrs : 1;
277
278 /// Implicit - Whether this declaration was implicitly generated by
279 /// the implementation rather than explicitly written by the user.
280 unsigned Implicit : 1;
281
282 /// \brief Whether this declaration was "used", meaning that a definition is
283 /// required.
284 unsigned Used : 1;
285
286 /// \brief Whether this declaration was "referenced".
287 /// The difference with 'Used' is whether the reference appears in a
288 /// evaluated context or not, e.g. functions used in uninstantiated templates
289 /// are regarded as "referenced" but not "used".
290 unsigned Referenced : 1;
291
292 /// \brief Whether this declaration is a top-level declaration (function,
293 /// global variable, etc.) that is lexically inside an objc container
294 /// definition.
295 unsigned TopLevelDeclInObjCContainer : 1;
296
297 /// \brief Whether statistic collection is enabled.
298 static bool StatisticsEnabled;
299
300protected:
301 /// Access - Used by C++ decls for the access specifier.
302 // NOTE: VC++ treats enums as signed, avoid using the AccessSpecifier enum
303 unsigned Access : 2;
304 friend class CXXClassMemberWrapper;
305
306 /// \brief Whether this declaration was loaded from an AST file.
307 unsigned FromASTFile : 1;
308
309 /// IdentifierNamespace - This specifies what IDNS_* namespace this lives in.
310 unsigned IdentifierNamespace : 13;
311
312 /// \brief If 0, we have not computed the linkage of this declaration.
313 /// Otherwise, it is the linkage + 1.
314 mutable unsigned CacheValidAndLinkage : 3;
315
316 friend class ASTDeclWriter;
317 friend class ASTDeclReader;
318 friend class ASTReader;
319 friend class LinkageComputer;
320
321 template<typename decl_type> friend class Redeclarable;
322
323 /// \brief Allocate memory for a deserialized declaration.
324 ///
325 /// This routine must be used to allocate memory for any declaration that is
326 /// deserialized from a module file.
327 ///
328 /// \param Size The size of the allocated object.
329 /// \param Ctx The context in which we will allocate memory.
330 /// \param ID The global ID of the deserialized declaration.
331 /// \param Extra The amount of extra space to allocate after the object.
332 void *operator new(std::size_t Size, const ASTContext &Ctx, unsigned ID,
333 std::size_t Extra = 0);
334
335 /// \brief Allocate memory for a non-deserialized declaration.
336 void *operator new(std::size_t Size, const ASTContext &Ctx,
337 DeclContext *Parent, std::size_t Extra = 0);
338
339private:
340 bool AccessDeclContextSanity() const;
341
342 /// Get the module ownership kind to use for a local lexical child of \p DC,
343 /// which may be either a local or (rarely) an imported declaration.
344 static ModuleOwnershipKind getModuleOwnershipKindForChildOf(DeclContext *DC) {
345 if (DC) {
346 auto *D = cast<Decl>(DC);
347 auto MOK = D->getModuleOwnershipKind();
348 if (MOK != ModuleOwnershipKind::Unowned &&
349 (!D->isFromASTFile() || D->hasLocalOwningModuleStorage()))
350 return MOK;
351 // If D is not local and we have no local module storage, then we don't
352 // need to track module ownership at all.
353 }
354 return ModuleOwnershipKind::Unowned;
355 }
356
357protected:
358 Decl(Kind DK, DeclContext *DC, SourceLocation L)
359 : NextInContextAndBits(nullptr, getModuleOwnershipKindForChildOf(DC)),
360 DeclCtx(DC), Loc(L), DeclKind(DK), InvalidDecl(0), HasAttrs(false),
361 Implicit(false), Used(false), Referenced(false),
362 TopLevelDeclInObjCContainer(false), Access(AS_none), FromASTFile(0),
363 IdentifierNamespace(getIdentifierNamespaceForKind(DK)),
364 CacheValidAndLinkage(0) {
365 if (StatisticsEnabled) add(DK);
366 }
367
368 Decl(Kind DK, EmptyShell Empty)
369 : NextInContextAndBits(), DeclKind(DK), InvalidDecl(0), HasAttrs(false),
370 Implicit(false), Used(false), Referenced(false),
371 TopLevelDeclInObjCContainer(false), Access(AS_none), FromASTFile(0),
372 IdentifierNamespace(getIdentifierNamespaceForKind(DK)),
373 CacheValidAndLinkage(0) {
374 if (StatisticsEnabled) add(DK);
375 }
376
377 virtual ~Decl();
378
379 /// \brief Update a potentially out-of-date declaration.
380 void updateOutOfDate(IdentifierInfo &II) const;
381
382 Linkage getCachedLinkage() const {
383 return Linkage(CacheValidAndLinkage - 1);
384 }
385
386 void setCachedLinkage(Linkage L) const {
387 CacheValidAndLinkage = L + 1;
388 }
389
390 bool hasCachedLinkage() const {
391 return CacheValidAndLinkage;
392 }
393
394public:
395
396 /// \brief Source range that this declaration covers.
397 virtual SourceRange getSourceRange() const LLVM_READONLY {
398 return SourceRange(getLocation(), getLocation());
399 }
400 SourceLocation getLocStart() const LLVM_READONLY {
401 return getSourceRange().getBegin();
402 }
403 SourceLocation getLocEnd() const LLVM_READONLY {
404 return getSourceRange().getEnd();
405 }
406
407 SourceLocation getLocation() const { return Loc; }
408 void setLocation(SourceLocation L) { Loc = L; }
409
410 Kind getKind() const { return static_cast<Kind>(DeclKind); }
411 const char *getDeclKindName() const;
412
413 Decl *getNextDeclInContext() { return NextInContextAndBits.getPointer(); }
414 const Decl *getNextDeclInContext() const {return NextInContextAndBits.getPointer();}
415
416 DeclContext *getDeclContext() {
417 if (isInSemaDC())
418 return getSemanticDC();
419 return getMultipleDC()->SemanticDC;
420 }
421 const DeclContext *getDeclContext() const {
422 return const_cast<Decl*>(this)->getDeclContext();
423 }
424
425 /// Find the innermost non-closure ancestor of this declaration,
426 /// walking up through blocks, lambdas, etc. If that ancestor is
427 /// not a code context (!isFunctionOrMethod()), returns null.
428 ///
429 /// A declaration may be its own non-closure context.
430 Decl *getNonClosureContext();
431 const Decl *getNonClosureContext() const {
432 return const_cast<Decl*>(this)->getNonClosureContext();
433 }
434
435 TranslationUnitDecl *getTranslationUnitDecl();
436 const TranslationUnitDecl *getTranslationUnitDecl() const {
437 return const_cast<Decl*>(this)->getTranslationUnitDecl();
438 }
439
440 bool isInAnonymousNamespace() const;
441
442 bool isInStdNamespace() const;
443
444 ASTContext &getASTContext() const LLVM_READONLY;
445
446 void setAccess(AccessSpecifier AS) {
447 Access = AS;
448 assert(AccessDeclContextSanity());
449 }
450
451 AccessSpecifier getAccess() const {
452 assert(AccessDeclContextSanity());
453 return AccessSpecifier(Access);
454 }
455
456 /// \brief Retrieve the access specifier for this declaration, even though
457 /// it may not yet have been properly set.
458 AccessSpecifier getAccessUnsafe() const {
459 return AccessSpecifier(Access);
460 }
461
462 bool hasAttrs() const { return HasAttrs; }
463 void setAttrs(const AttrVec& Attrs) {
464 return setAttrsImpl(Attrs, getASTContext());
465 }
466 AttrVec &getAttrs() {
467 return const_cast<AttrVec&>(const_cast<const Decl*>(this)->getAttrs());
468 }
469 const AttrVec &getAttrs() const;
470 void dropAttrs();
471
472 void addAttr(Attr *A) {
473 if (hasAttrs())
474 getAttrs().push_back(A);
475 else
476 setAttrs(AttrVec(1, A));
477 }
478
479 typedef AttrVec::const_iterator attr_iterator;
480 typedef llvm::iterator_range<attr_iterator> attr_range;
481
482 attr_range attrs() const {
483 return attr_range(attr_begin(), attr_end());
484 }
485
486 attr_iterator attr_begin() const {
487 return hasAttrs() ? getAttrs().begin() : nullptr;
488 }
489 attr_iterator attr_end() const {
490 return hasAttrs() ? getAttrs().end() : nullptr;
491 }
492
493 template <typename T>
494 void dropAttr() {
495 if (!HasAttrs) return;
496
497 AttrVec &Vec = getAttrs();
498 Vec.erase(std::remove_if(Vec.begin(), Vec.end(), isa<T, Attr*>), Vec.end());
499
500 if (Vec.empty())
501 HasAttrs = false;
502 }
503
504 template <typename T>
505 llvm::iterator_range<specific_attr_iterator<T>> specific_attrs() const {
506 return llvm::make_range(specific_attr_begin<T>(), specific_attr_end<T>());
507 }
508
509 template <typename T>
510 specific_attr_iterator<T> specific_attr_begin() const {
511 return specific_attr_iterator<T>(attr_begin());
512 }
513 template <typename T>
514 specific_attr_iterator<T> specific_attr_end() const {
515 return specific_attr_iterator<T>(attr_end());
516 }
517
518 template<typename T> T *getAttr() const {
519 return hasAttrs() ? getSpecificAttr<T>(getAttrs()) : nullptr;
520 }
521 template<typename T> bool hasAttr() const {
522 return hasAttrs() && hasSpecificAttr<T>(getAttrs());
523 }
524
525 /// getMaxAlignment - return the maximum alignment specified by attributes
526 /// on this decl, 0 if there are none.
527 unsigned getMaxAlignment() const;
528
529 /// setInvalidDecl - Indicates the Decl had a semantic error. This
530 /// allows for graceful error recovery.
531 void setInvalidDecl(bool Invalid = true);
532 bool isInvalidDecl() const { return (bool) InvalidDecl; }
533
534 /// isImplicit - Indicates whether the declaration was implicitly
535 /// generated by the implementation. If false, this declaration
536 /// was written explicitly in the source code.
537 bool isImplicit() const { return Implicit; }
538 void setImplicit(bool I = true) { Implicit = I; }
539
540 /// \brief Whether *any* (re-)declaration of the entity was used, meaning that
541 /// a definition is required.
542 ///
543 /// \param CheckUsedAttr When true, also consider the "used" attribute
544 /// (in addition to the "used" bit set by \c setUsed()) when determining
545 /// whether the function is used.
546 bool isUsed(bool CheckUsedAttr = true) const;
547
548 /// \brief Set whether the declaration is used, in the sense of odr-use.
549 ///
550 /// This should only be used immediately after creating a declaration.
551 /// It intentionally doesn't notify any listeners.
552 void setIsUsed() { getCanonicalDecl()->Used = true; }
553
554 /// \brief Mark the declaration used, in the sense of odr-use.
555 ///
556 /// This notifies any mutation listeners in addition to setting a bit
557 /// indicating the declaration is used.
558 void markUsed(ASTContext &C);
559
560 /// \brief Whether any declaration of this entity was referenced.
561 bool isReferenced() const;
562
563 /// \brief Whether this declaration was referenced. This should not be relied
564 /// upon for anything other than debugging.
565 bool isThisDeclarationReferenced() const { return Referenced; }
566
567 void setReferenced(bool R = true) { Referenced = R; }
568
569 /// \brief Whether this declaration is a top-level declaration (function,
570 /// global variable, etc.) that is lexically inside an objc container
571 /// definition.
572 bool isTopLevelDeclInObjCContainer() const {
573 return TopLevelDeclInObjCContainer;
574 }
575
576 void setTopLevelDeclInObjCContainer(bool V = true) {
577 TopLevelDeclInObjCContainer = V;
578 }
579
580 /// \brief Looks on this and related declarations for an applicable
581 /// external source symbol attribute.
582 ExternalSourceSymbolAttr *getExternalSourceSymbolAttr() const;
583
584 /// \brief Whether this declaration was marked as being private to the
585 /// module in which it was defined.
586 bool isModulePrivate() const {
587 return getModuleOwnershipKind() == ModuleOwnershipKind::ModulePrivate;
588 }
589
590 /// \brief Whether this declaration is exported (by virtue of being lexically
591 /// within an ExportDecl or by being a NamespaceDecl).
592 bool isExported() const;
593
594 /// Return true if this declaration has an attribute which acts as
595 /// definition of the entity, such as 'alias' or 'ifunc'.
596 bool hasDefiningAttr() const;
597
598 /// Return this declaration's defining attribute if it has one.
599 const Attr *getDefiningAttr() const;
600
601protected:
602 /// \brief Specify that this declaration was marked as being private
603 /// to the module in which it was defined.
604 void setModulePrivate() {
605 // The module-private specifier has no effect on unowned declarations.
606 // FIXME: We should track this in some way for source fidelity.
607 if (getModuleOwnershipKind() == ModuleOwnershipKind::Unowned)
608 return;
609 setModuleOwnershipKind(ModuleOwnershipKind::ModulePrivate);
610 }
611
612 /// \brief Set the owning module ID.
613 void setOwningModuleID(unsigned ID) {
614 assert(isFromASTFile() && "Only works on a deserialized declaration");
615 *((unsigned*)this - 2) = ID;
616 }
617
618public:
619
620 /// \brief Determine the availability of the given declaration.
621 ///
622 /// This routine will determine the most restrictive availability of
623 /// the given declaration (e.g., preferring 'unavailable' to
624 /// 'deprecated').
625 ///
626 /// \param Message If non-NULL and the result is not \c
627 /// AR_Available, will be set to a (possibly empty) message
628 /// describing why the declaration has not been introduced, is
629 /// deprecated, or is unavailable.
630 ///
631 /// \param EnclosingVersion The version to compare with. If empty, assume the
632 /// deployment target version.
633 AvailabilityResult
634 getAvailability(std::string *Message = nullptr,
635 VersionTuple EnclosingVersion = VersionTuple()) const;
636
637 /// \brief Retrieve the version of the target platform in which this
638 /// declaration was introduced.
639 ///
640 /// \returns An empty version tuple if this declaration has no 'introduced'
641 /// availability attributes, or the version tuple that's specified in the
642 /// attribute otherwise.
643 VersionTuple getVersionIntroduced() const;
644
645 /// \brief Determine whether this declaration is marked 'deprecated'.
646 ///
647 /// \param Message If non-NULL and the declaration is deprecated,
648 /// this will be set to the message describing why the declaration
649 /// was deprecated (which may be empty).
650 bool isDeprecated(std::string *Message = nullptr) const {
651 return getAvailability(Message) == AR_Deprecated;
652 }
653
654 /// \brief Determine whether this declaration is marked 'unavailable'.
655 ///
656 /// \param Message If non-NULL and the declaration is unavailable,
657 /// this will be set to the message describing why the declaration
658 /// was made unavailable (which may be empty).
659 bool isUnavailable(std::string *Message = nullptr) const {
660 return getAvailability(Message) == AR_Unavailable;
661 }
662
663 /// \brief Determine whether this is a weak-imported symbol.
664 ///
665 /// Weak-imported symbols are typically marked with the
666 /// 'weak_import' attribute, but may also be marked with an
667 /// 'availability' attribute where we're targing a platform prior to
668 /// the introduction of this feature.
669 bool isWeakImported() const;
670
671 /// \brief Determines whether this symbol can be weak-imported,
672 /// e.g., whether it would be well-formed to add the weak_import
673 /// attribute.
674 ///
675 /// \param IsDefinition Set to \c true to indicate that this
676 /// declaration cannot be weak-imported because it has a definition.
677 bool canBeWeakImported(bool &IsDefinition) const;
678
679 /// \brief Determine whether this declaration came from an AST file (such as
680 /// a precompiled header or module) rather than having been parsed.
681 bool isFromASTFile() const { return FromASTFile; }
682
683 /// \brief Retrieve the global declaration ID associated with this
684 /// declaration, which specifies where this Decl was loaded from.
685 unsigned getGlobalID() const {
686 if (isFromASTFile())
687 return *((const unsigned*)this - 1);
688 return 0;
689 }
690
691 /// \brief Retrieve the global ID of the module that owns this particular
692 /// declaration.
693 unsigned getOwningModuleID() const {
694 if (isFromASTFile())
695 return *((const unsigned*)this - 2);
696 return 0;
697 }
698
699private:
700 Module *getOwningModuleSlow() const;
701protected:
702 bool hasLocalOwningModuleStorage() const;
703
704public:
705 /// \brief Get the imported owning module, if this decl is from an imported
706 /// (non-local) module.
707 Module *getImportedOwningModule() const {
708 if (!isFromASTFile() || !hasOwningModule())
709 return nullptr;
710
711 return getOwningModuleSlow();
712 }
713
714 /// \brief Get the local owning module, if known. Returns nullptr if owner is
715 /// not yet known or declaration is not from a module.
716 Module *getLocalOwningModule() const {
717 if (isFromASTFile() || !hasOwningModule())
718 return nullptr;
719
720 assert(hasLocalOwningModuleStorage() &&
721 "owned local decl but no local module storage");
722 return reinterpret_cast<Module *const *>(this)[-1];
723 }
724 void setLocalOwningModule(Module *M) {
725 assert(!isFromASTFile() && hasOwningModule() &&
726 hasLocalOwningModuleStorage() &&
727 "should not have a cached owning module");
728 reinterpret_cast<Module **>(this)[-1] = M;
729 }
730
731 /// Is this declaration owned by some module?
732 bool hasOwningModule() const {
733 return getModuleOwnershipKind() != ModuleOwnershipKind::Unowned;
734 }
735
736 /// Get the module that owns this declaration.
737 Module *getOwningModule() const {
738 return isFromASTFile() ? getImportedOwningModule() : getLocalOwningModule();
739 }
740
741 /// \brief Determine whether this declaration might be hidden from name
742 /// lookup. Note that the declaration might be visible even if this returns
743 /// \c false, if the owning module is visible within the query context.
744 // FIXME: Rename this to make it clearer what it does.
745 bool isHidden() const {
746 return (int)getModuleOwnershipKind() > (int)ModuleOwnershipKind::Visible;
747 }
748
749 /// Set that this declaration is globally visible, even if it came from a
750 /// module that is not visible.
751 void setVisibleDespiteOwningModule() {
752 if (isHidden())
753 setModuleOwnershipKind(ModuleOwnershipKind::Visible);
754 }
755
756 /// \brief Get the kind of module ownership for this declaration.
757 ModuleOwnershipKind getModuleOwnershipKind() const {
758 return NextInContextAndBits.getInt();
759 }
760
761 /// \brief Set whether this declaration is hidden from name lookup.
762 void setModuleOwnershipKind(ModuleOwnershipKind MOK) {
763 assert(!(getModuleOwnershipKind() == ModuleOwnershipKind::Unowned &&
764 MOK != ModuleOwnershipKind::Unowned && !isFromASTFile() &&
765 !hasLocalOwningModuleStorage()) &&
766 "no storage available for owning module for this declaration");
767 NextInContextAndBits.setInt(MOK);
768 }
769
770 unsigned getIdentifierNamespace() const {
771 return IdentifierNamespace;
772 }
773 bool isInIdentifierNamespace(unsigned NS) const {
774 return getIdentifierNamespace() & NS;
775 }
776 static unsigned getIdentifierNamespaceForKind(Kind DK);
777
778 bool hasTagIdentifierNamespace() const {
779 return isTagIdentifierNamespace(getIdentifierNamespace());
780 }
781 static bool isTagIdentifierNamespace(unsigned NS) {
782 // TagDecls have Tag and Type set and may also have TagFriend.
783 return (NS & ~IDNS_TagFriend) == (IDNS_Tag | IDNS_Type);
784 }
785
786 /// getLexicalDeclContext - The declaration context where this Decl was
787 /// lexically declared (LexicalDC). May be different from
788 /// getDeclContext() (SemanticDC).
789 /// e.g.:
790 ///
791 /// namespace A {
792 /// void f(); // SemanticDC == LexicalDC == 'namespace A'
793 /// }
794 /// void A::f(); // SemanticDC == namespace 'A'
795 /// // LexicalDC == global namespace
796 DeclContext *getLexicalDeclContext() {
797 if (isInSemaDC())
798 return getSemanticDC();
799 return getMultipleDC()->LexicalDC;
800 }
801 const DeclContext *getLexicalDeclContext() const {
802 return const_cast<Decl*>(this)->getLexicalDeclContext();
803 }
804
805 /// Determine whether this declaration is declared out of line (outside its
806 /// semantic context).
807 virtual bool isOutOfLine() const;
808
809 /// setDeclContext - Set both the semantic and lexical DeclContext
810 /// to DC.
811 void setDeclContext(DeclContext *DC);
812
813 void setLexicalDeclContext(DeclContext *DC);
814
815 /// isDefinedOutsideFunctionOrMethod - This predicate returns true if this
816 /// scoped decl is defined outside the current function or method. This is
817 /// roughly global variables and functions, but also handles enums (which
818 /// could be defined inside or outside a function etc).
819 bool isDefinedOutsideFunctionOrMethod() const {
820 return getParentFunctionOrMethod() == nullptr;
821 }
822
823 /// \brief Returns true if this declaration lexically is inside a function.
824 /// It recognizes non-defining declarations as well as members of local
825 /// classes:
826 /// \code
827 /// void foo() { void bar(); }
828 /// void foo2() { class ABC { void bar(); }; }
829 /// \endcode
830 bool isLexicallyWithinFunctionOrMethod() const;
831
832 /// \brief If this decl is defined inside a function/method/block it returns
833 /// the corresponding DeclContext, otherwise it returns null.
834 const DeclContext *getParentFunctionOrMethod() const;
835 DeclContext *getParentFunctionOrMethod() {
836 return const_cast<DeclContext*>(
837 const_cast<const Decl*>(this)->getParentFunctionOrMethod());
838 }
839
840 /// \brief Retrieves the "canonical" declaration of the given declaration.
841 virtual Decl *getCanonicalDecl() { return this; }
842 const Decl *getCanonicalDecl() const {
843 return const_cast<Decl*>(this)->getCanonicalDecl();
844 }
845
846 /// \brief Whether this particular Decl is a canonical one.
847 bool isCanonicalDecl() const { return getCanonicalDecl() == this; }
848
849protected:
850 /// \brief Returns the next redeclaration or itself if this is the only decl.
851 ///
852 /// Decl subclasses that can be redeclared should override this method so that
853 /// Decl::redecl_iterator can iterate over them.
854 virtual Decl *getNextRedeclarationImpl() { return this; }
855
856 /// \brief Implementation of getPreviousDecl(), to be overridden by any
857 /// subclass that has a redeclaration chain.
858 virtual Decl *getPreviousDeclImpl() { return nullptr; }
859
860 /// \brief Implementation of getMostRecentDecl(), to be overridden by any
861 /// subclass that has a redeclaration chain.
862 virtual Decl *getMostRecentDeclImpl() { return this; }
863
864public:
865 /// \brief Iterates through all the redeclarations of the same decl.
866 class redecl_iterator {
867 /// Current - The current declaration.
868 Decl *Current;
869 Decl *Starter;
870
871 public:
872 typedef Decl *value_type;
873 typedef const value_type &reference;
874 typedef const value_type *pointer;
875 typedef std::forward_iterator_tag iterator_category;
876 typedef std::ptrdiff_t difference_type;
877
878 redecl_iterator() : Current(nullptr) { }
879 explicit redecl_iterator(Decl *C) : Current(C), Starter(C) { }
880
881 reference operator*() const { return Current; }
882 value_type operator->() const { return Current; }
883
884 redecl_iterator& operator++() {
885 assert(Current && "Advancing while iterator has reached end");
886 // Get either previous decl or latest decl.
887 Decl *Next = Current->getNextRedeclarationImpl();
888 assert(Next && "Should return next redeclaration or itself, never null!");
889 Current = (Next != Starter) ? Next : nullptr;
890 return *this;
891 }
892
893 redecl_iterator operator++(int) {
894 redecl_iterator tmp(*this);
895 ++(*this);
896 return tmp;
897 }
898
899 friend bool operator==(redecl_iterator x, redecl_iterator y) {
900 return x.Current == y.Current;
901 }
902 friend bool operator!=(redecl_iterator x, redecl_iterator y) {
903 return x.Current != y.Current;
904 }
905 };
906
907 typedef llvm::iterator_range<redecl_iterator> redecl_range;
908
909 /// \brief Returns an iterator range for all the redeclarations of the same
910 /// decl. It will iterate at least once (when this decl is the only one).
911 redecl_range redecls() const {
912 return redecl_range(redecls_begin(), redecls_end());
913 }
914
915 redecl_iterator redecls_begin() const {
916 return redecl_iterator(const_cast<Decl *>(this));
917 }
918 redecl_iterator redecls_end() const { return redecl_iterator(); }
919
920 /// \brief Retrieve the previous declaration that declares the same entity
921 /// as this declaration, or NULL if there is no previous declaration.
922 Decl *getPreviousDecl() { return getPreviousDeclImpl(); }
923
924 /// \brief Retrieve the most recent declaration that declares the same entity
925 /// as this declaration, or NULL if there is no previous declaration.
926 const Decl *getPreviousDecl() const {
927 return const_cast<Decl *>(this)->getPreviousDeclImpl();
928 }
929
930 /// \brief True if this is the first declaration in its redeclaration chain.
931 bool isFirstDecl() const {
932 return getPreviousDecl() == nullptr;
933 }
934
935 /// \brief Retrieve the most recent declaration that declares the same entity
936 /// as this declaration (which may be this declaration).
937 Decl *getMostRecentDecl() { return getMostRecentDeclImpl(); }
938
939 /// \brief Retrieve the most recent declaration that declares the same entity
940 /// as this declaration (which may be this declaration).
941 const Decl *getMostRecentDecl() const {
942 return const_cast<Decl *>(this)->getMostRecentDeclImpl();
943 }
944
945 /// getBody - If this Decl represents a declaration for a body of code,
946 /// such as a function or method definition, this method returns the
947 /// top-level Stmt* of that body. Otherwise this method returns null.
948 virtual Stmt* getBody() const { return nullptr; }
949
950 /// \brief Returns true if this \c Decl represents a declaration for a body of
951 /// code, such as a function or method definition.
952 /// Note that \c hasBody can also return true if any redeclaration of this
953 /// \c Decl represents a declaration for a body of code.
954 virtual bool hasBody() const { return getBody() != nullptr; }
955
956 /// getBodyRBrace - Gets the right brace of the body, if a body exists.
957 /// This works whether the body is a CompoundStmt or a CXXTryStmt.
958 SourceLocation getBodyRBrace() const;
959
960 // global temp stats (until we have a per-module visitor)
961 static void add(Kind k);
962 static void EnableStatistics();
963 static void PrintStats();
964
965 /// isTemplateParameter - Determines whether this declaration is a
966 /// template parameter.
967 bool isTemplateParameter() const;
968
969 /// isTemplateParameter - Determines whether this declaration is a
970 /// template parameter pack.
971 bool isTemplateParameterPack() const;
972
973 /// \brief Whether this declaration is a parameter pack.
974 bool isParameterPack() const;
975
976 /// \brief returns true if this declaration is a template
977 bool isTemplateDecl() const;
978
979 /// \brief Whether this declaration is a function or function template.
980 bool isFunctionOrFunctionTemplate() const {
981 return (DeclKind >= Decl::firstFunction &&
982 DeclKind <= Decl::lastFunction) ||
983 DeclKind == FunctionTemplate;
984 }
985
986 /// \brief If this is a declaration that describes some template, this
987 /// method returns that template declaration.
988 TemplateDecl *getDescribedTemplate() const;
989
990 /// \brief Returns the function itself, or the templated function if this is a
991 /// function template.
992 FunctionDecl *getAsFunction() LLVM_READONLY;
993
994 const FunctionDecl *getAsFunction() const {
995 return const_cast<Decl *>(this)->getAsFunction();
996 }
997
998 /// \brief Changes the namespace of this declaration to reflect that it's
999 /// a function-local extern declaration.
1000 ///
1001 /// These declarations appear in the lexical context of the extern
1002 /// declaration, but in the semantic context of the enclosing namespace
1003 /// scope.
1004 void setLocalExternDecl() {
1005 assert((IdentifierNamespace == IDNS_Ordinary ||
1006 IdentifierNamespace == IDNS_OrdinaryFriend) &&
1007 "namespace is not ordinary");
1008
1009 Decl *Prev = getPreviousDecl();
1010 IdentifierNamespace &= ~IDNS_Ordinary;
1011
1012 IdentifierNamespace |= IDNS_LocalExtern;
1013 if (Prev && Prev->getIdentifierNamespace() & IDNS_Ordinary)
1014 IdentifierNamespace |= IDNS_Ordinary;
1015 }
1016
1017 /// \brief Determine whether this is a block-scope declaration with linkage.
1018 /// This will either be a local variable declaration declared 'extern', or a
1019 /// local function declaration.
1020 bool isLocalExternDecl() {
1021 return IdentifierNamespace & IDNS_LocalExtern;
1022 }
1023
1024 /// \brief Changes the namespace of this declaration to reflect that it's
1025 /// the object of a friend declaration.
1026 ///
1027 /// These declarations appear in the lexical context of the friending
1028 /// class, but in the semantic context of the actual entity. This property
1029 /// applies only to a specific decl object; other redeclarations of the
1030 /// same entity may not (and probably don't) share this property.
1031 void setObjectOfFriendDecl(bool PerformFriendInjection = false) {
1032 unsigned OldNS = IdentifierNamespace;
1033 assert((OldNS & (IDNS_Tag | IDNS_Ordinary |
1034 IDNS_TagFriend | IDNS_OrdinaryFriend |
1035 IDNS_LocalExtern)) &&
1036 "namespace includes neither ordinary nor tag");
1037 assert(!(OldNS & ~(IDNS_Tag | IDNS_Ordinary | IDNS_Type |
1038 IDNS_TagFriend | IDNS_OrdinaryFriend |
1039 IDNS_LocalExtern)) &&
1040 "namespace includes other than ordinary or tag");
1041
1042 Decl *Prev = getPreviousDecl();
1043 IdentifierNamespace &= ~(IDNS_Ordinary | IDNS_Tag | IDNS_Type);
1044
1045 if (OldNS & (IDNS_Tag | IDNS_TagFriend)) {
1046 IdentifierNamespace |= IDNS_TagFriend;
1047 if (PerformFriendInjection ||
1048 (Prev && Prev->getIdentifierNamespace() & IDNS_Tag))
1049 IdentifierNamespace |= IDNS_Tag | IDNS_Type;
1050 }
1051
1052 if (OldNS & (IDNS_Ordinary | IDNS_OrdinaryFriend | IDNS_LocalExtern)) {
1053 IdentifierNamespace |= IDNS_OrdinaryFriend;
1054 if (PerformFriendInjection ||
1055 (Prev && Prev->getIdentifierNamespace() & IDNS_Ordinary))
1056 IdentifierNamespace |= IDNS_Ordinary;
1057 }
1058 }
1059
1060 enum FriendObjectKind {
1061 FOK_None, ///< Not a friend object.
1062 FOK_Declared, ///< A friend of a previously-declared entity.
1063 FOK_Undeclared ///< A friend of a previously-undeclared entity.
1064 };
1065
1066 /// \brief Determines whether this declaration is the object of a
1067 /// friend declaration and, if so, what kind.
1068 ///
1069 /// There is currently no direct way to find the associated FriendDecl.
1070 FriendObjectKind getFriendObjectKind() const {
1071 unsigned mask =
1072 (IdentifierNamespace & (IDNS_TagFriend | IDNS_OrdinaryFriend));
1073 if (!mask) return FOK_None;
1074 return (IdentifierNamespace & (IDNS_Tag | IDNS_Ordinary) ? FOK_Declared
1075 : FOK_Undeclared);
1076 }
1077
1078 /// Specifies that this declaration is a C++ overloaded non-member.
1079 void setNonMemberOperator() {
1080 assert(getKind() == Function || getKind() == FunctionTemplate);
1081 assert((IdentifierNamespace & IDNS_Ordinary) &&
1082 "visible non-member operators should be in ordinary namespace");
1083 IdentifierNamespace |= IDNS_NonMemberOperator;
1084 }
1085
1086 static bool classofKind(Kind K) { return true; }
1087 static DeclContext *castToDeclContext(const Decl *);
1088 static Decl *castFromDeclContext(const DeclContext *);
1089
1090 void print(raw_ostream &Out, unsigned Indentation = 0,
1091 bool PrintInstantiation = false) const;
1092 void print(raw_ostream &Out, const PrintingPolicy &Policy,
1093 unsigned Indentation = 0, bool PrintInstantiation = false) const;
1094 static void printGroup(Decl** Begin, unsigned NumDecls,
1095 raw_ostream &Out, const PrintingPolicy &Policy,
1096 unsigned Indentation = 0);
1097 // Debuggers don't usually respect default arguments.
1098 void dump() const;
1099 // Same as dump(), but forces color printing.
1100 void dumpColor() const;
1101 void dump(raw_ostream &Out, bool Deserialize = false) const;
1102
1103 /// \brief Looks through the Decl's underlying type to extract a FunctionType
1104 /// when possible. Will return null if the type underlying the Decl does not
1105 /// have a FunctionType.
1106 const FunctionType *getFunctionType(bool BlocksToo = true) const;
1107
1108private:
1109 void setAttrsImpl(const AttrVec& Attrs, ASTContext &Ctx);
1110 void setDeclContextsImpl(DeclContext *SemaDC, DeclContext *LexicalDC,
1111 ASTContext &Ctx);
1112
1113protected:
1114 ASTMutationListener *getASTMutationListener() const;
1115};
1116
1117/// \brief Determine whether two declarations declare the same entity.
1118inline bool declaresSameEntity(const Decl *D1, const Decl *D2) {
1119 if (!D1 || !D2)
1120 return false;
1121
1122 if (D1 == D2)
1123 return true;
1124
1125 return D1->getCanonicalDecl() == D2->getCanonicalDecl();
1126}
1127
1128/// PrettyStackTraceDecl - If a crash occurs, indicate that it happened when
1129/// doing something to a specific decl.
1130class PrettyStackTraceDecl : public llvm::PrettyStackTraceEntry {
1131 const Decl *TheDecl;
1132 SourceLocation Loc;
1133 SourceManager &SM;
1134 const char *Message;
1135public:
1136 PrettyStackTraceDecl(const Decl *theDecl, SourceLocation L,
1137 SourceManager &sm, const char *Msg)
1138 : TheDecl(theDecl), Loc(L), SM(sm), Message(Msg) {}
1139
1140 void print(raw_ostream &OS) const override;
1141};
1142
1143/// \brief The results of name lookup within a DeclContext. This is either a
1144/// single result (with no stable storage) or a collection of results (with
1145/// stable storage provided by the lookup table).
1146class DeclContextLookupResult {
1147 typedef ArrayRef<NamedDecl *> ResultTy;
1148 ResultTy Result;
1149 // If there is only one lookup result, it would be invalidated by
1150 // reallocations of the name table, so store it separately.
1151 NamedDecl *Single;
1152
1153 static NamedDecl *const SingleElementDummyList;
1154
1155public:
1156 DeclContextLookupResult() : Result(), Single() {}
1157 DeclContextLookupResult(ArrayRef<NamedDecl *> Result)
1158 : Result(Result), Single() {}
1159 DeclContextLookupResult(NamedDecl *Single)
1160 : Result(SingleElementDummyList), Single(Single) {}
1161
1162 class iterator;
1163 typedef llvm::iterator_adaptor_base<iterator, ResultTy::iterator,
1164 std::random_access_iterator_tag,
1165 NamedDecl *const> IteratorBase;
1166 class iterator : public IteratorBase {
1167 value_type SingleElement;
1168
1169 public:
1170 iterator() : IteratorBase(), SingleElement() {}
1171 explicit iterator(pointer Pos, value_type Single = nullptr)
1172 : IteratorBase(Pos), SingleElement(Single) {}
1173
1174 reference operator*() const {
1175 return SingleElement ? SingleElement : IteratorBase::operator*();
1176 }
1177 };
1178 typedef iterator const_iterator;
1179 typedef iterator::pointer pointer;
1180 typedef iterator::reference reference;
1181
1182 iterator begin() const { return iterator(Result.begin(), Single); }
1183 iterator end() const { return iterator(Result.end(), Single); }
1184
1185 bool empty() const { return Result.empty(); }
1186 pointer data() const { return Single ? &Single : Result.data(); }
1187 size_t size() const { return Single ? 1 : Result.size(); }
1188 reference front() const { return Single ? Single : Result.front(); }
1189 reference back() const { return Single ? Single : Result.back(); }
1190 reference operator[](size_t N) const { return Single ? Single : Result[N]; }
1191
1192 // FIXME: Remove this from the interface
1193 DeclContextLookupResult slice(size_t N) const {
1194 DeclContextLookupResult Sliced = Result.slice(N);
1195 Sliced.Single = Single;
1196 return Sliced;
1197 }
1198};
1199
1200/// DeclContext - This is used only as base class of specific decl types that
1201/// can act as declaration contexts. These decls are (only the top classes
1202/// that directly derive from DeclContext are mentioned, not their subclasses):
1203///
1204/// TranslationUnitDecl
1205/// NamespaceDecl
1206/// FunctionDecl
1207/// TagDecl
1208/// ObjCMethodDecl
1209/// ObjCContainerDecl
1210/// LinkageSpecDecl
1211/// ExportDecl
1212/// BlockDecl
1213/// OMPDeclareReductionDecl
1214///
1215class DeclContext {
1216 /// DeclKind - This indicates which class this is.
1217 unsigned DeclKind : 8;
1218
1219 /// \brief Whether this declaration context also has some external
1220 /// storage that contains additional declarations that are lexically
1221 /// part of this context.
1222 mutable bool ExternalLexicalStorage : 1;
1223
1224 /// \brief Whether this declaration context also has some external
1225 /// storage that contains additional declarations that are visible
1226 /// in this context.
1227 mutable bool ExternalVisibleStorage : 1;
1228
1229 /// \brief Whether this declaration context has had external visible
1230 /// storage added since the last lookup. In this case, \c LookupPtr's
1231 /// invariant may not hold and needs to be fixed before we perform
1232 /// another lookup.
1233 mutable bool NeedToReconcileExternalVisibleStorage : 1;
1234
1235 /// \brief If \c true, this context may have local lexical declarations
1236 /// that are missing from the lookup table.
1237 mutable bool HasLazyLocalLexicalLookups : 1;
1238
1239 /// \brief If \c true, the external source may have lexical declarations
1240 /// that are missing from the lookup table.
1241 mutable bool HasLazyExternalLexicalLookups : 1;
1242
1243 /// \brief If \c true, lookups should only return identifier from
1244 /// DeclContext scope (for example TranslationUnit). Used in
1245 /// LookupQualifiedName()
1246 mutable bool UseQualifiedLookup : 1;
1247
1248 /// \brief Pointer to the data structure used to lookup declarations
1249 /// within this context (or a DependentStoredDeclsMap if this is a
1250 /// dependent context). We maintain the invariant that, if the map
1251 /// contains an entry for a DeclarationName (and we haven't lazily
1252 /// omitted anything), then it contains all relevant entries for that
1253 /// name (modulo the hasExternalDecls() flag).
1254 mutable StoredDeclsMap *LookupPtr;
1255
1256protected:
1257 /// FirstDecl - The first declaration stored within this declaration
1258 /// context.
1259 mutable Decl *FirstDecl;
1260
1261 /// LastDecl - The last declaration stored within this declaration
1262 /// context. FIXME: We could probably cache this value somewhere
1263 /// outside of the DeclContext, to reduce the size of DeclContext by
1264 /// another pointer.
1265 mutable Decl *LastDecl;
1266
1267 friend class ExternalASTSource;
1268 friend class ASTDeclReader;
1269 friend class ASTWriter;
1270
1271 /// \brief Build up a chain of declarations.
1272 ///
1273 /// \returns the first/last pair of declarations.
1274 static std::pair<Decl *, Decl *>
1275 BuildDeclChain(ArrayRef<Decl*> Decls, bool FieldsAlreadyLoaded);
1276
1277 DeclContext(Decl::Kind K)
1278 : DeclKind(K), ExternalLexicalStorage(false),
1279 ExternalVisibleStorage(false),
1280 NeedToReconcileExternalVisibleStorage(false),
1281 HasLazyLocalLexicalLookups(false), HasLazyExternalLexicalLookups(false),
1282 UseQualifiedLookup(false),
1283 LookupPtr(nullptr), FirstDecl(nullptr), LastDecl(nullptr) {}
1284
1285public:
1286 ~DeclContext();
1287
1288 Decl::Kind getDeclKind() const {
1289 return static_cast<Decl::Kind>(DeclKind);
1290 }
1291 const char *getDeclKindName() const;
1292
1293 /// getParent - Returns the containing DeclContext.
1294 DeclContext *getParent() {
1295 return cast<Decl>(this)->getDeclContext();
1296 }
1297 const DeclContext *getParent() const {
1298 return const_cast<DeclContext*>(this)->getParent();
1299 }
1300
1301 /// getLexicalParent - Returns the containing lexical DeclContext. May be
1302 /// different from getParent, e.g.:
1303 ///
1304 /// namespace A {
1305 /// struct S;
1306 /// }
1307 /// struct A::S {}; // getParent() == namespace 'A'
1308 /// // getLexicalParent() == translation unit
1309 ///
1310 DeclContext *getLexicalParent() {
1311 return cast<Decl>(this)->getLexicalDeclContext();
1312 }
1313 const DeclContext *getLexicalParent() const {
1314 return const_cast<DeclContext*>(this)->getLexicalParent();
1315 }
1316
1317 DeclContext *getLookupParent();
1318
1319 const DeclContext *getLookupParent() const {
1320 return const_cast<DeclContext*>(this)->getLookupParent();
1321 }
1322
1323 ASTContext &getParentASTContext() const {
1324 return cast<Decl>(this)->getASTContext();
1325 }
1326
1327 bool isClosure() const {
1328 return DeclKind == Decl::Block;
1329 }
1330
1331 bool isObjCContainer() const {
1332 switch (DeclKind) {
1333 case Decl::ObjCCategory:
1334 case Decl::ObjCCategoryImpl:
1335 case Decl::ObjCImplementation:
1336 case Decl::ObjCInterface:
1337 case Decl::ObjCProtocol:
1338 return true;
1339 }
1340 return false;
1341 }
1342
1343 bool isFunctionOrMethod() const {
1344 switch (DeclKind) {
1345 case Decl::Block:
1346 case Decl::Captured:
1347 case Decl::ObjCMethod:
1348 return true;
1349 default:
1350 return DeclKind >= Decl::firstFunction && DeclKind <= Decl::lastFunction;
1351 }
1352 }
1353
1354 /// \brief Test whether the context supports looking up names.
1355 bool isLookupContext() const {
1356 return !isFunctionOrMethod() && DeclKind != Decl::LinkageSpec &&
1357 DeclKind != Decl::Export;
1358 }
1359
1360 bool isFileContext() const {
1361 return DeclKind == Decl::TranslationUnit || DeclKind == Decl::Namespace;
1362 }
1363
1364 bool isTranslationUnit() const {
1365 return DeclKind == Decl::TranslationUnit;
1366 }
1367
1368 bool isRecord() const {
1369 return DeclKind >= Decl::firstRecord && DeclKind <= Decl::lastRecord;
1370 }
1371
1372 bool isNamespace() const {
1373 return DeclKind == Decl::Namespace;
1374 }
1375
1376 bool isStdNamespace() const;
1377
1378 bool isInlineNamespace() const;
1379
1380 /// \brief Determines whether this context is dependent on a
1381 /// template parameter.
1382 bool isDependentContext() const;
1383
1384 /// isTransparentContext - Determines whether this context is a
1385 /// "transparent" context, meaning that the members declared in this
1386 /// context are semantically declared in the nearest enclosing
1387 /// non-transparent (opaque) context but are lexically declared in
1388 /// this context. For example, consider the enumerators of an
1389 /// enumeration type:
1390 /// @code
1391 /// enum E {
1392 /// Val1
1393 /// };
1394 /// @endcode
1395 /// Here, E is a transparent context, so its enumerator (Val1) will
1396 /// appear (semantically) that it is in the same context of E.
1397 /// Examples of transparent contexts include: enumerations (except for
1398 /// C++0x scoped enums), and C++ linkage specifications.
1399 bool isTransparentContext() const;
1400
1401 /// \brief Determines whether this context or some of its ancestors is a
1402 /// linkage specification context that specifies C linkage.
1403 bool isExternCContext() const;
1404
1405 /// \brief Retrieve the nearest enclosing C linkage specification context.
1406 const LinkageSpecDecl *getExternCContext() const;
1407
1408 /// \brief Determines whether this context or some of its ancestors is a
1409 /// linkage specification context that specifies C++ linkage.
1410 bool isExternCXXContext() const;
1411
1412 /// \brief Determine whether this declaration context is equivalent
1413 /// to the declaration context DC.
1414 bool Equals(const DeclContext *DC) const {
1415 return DC && this->getPrimaryContext() == DC->getPrimaryContext();
1416 }
1417
1418 /// \brief Determine whether this declaration context encloses the
1419 /// declaration context DC.
1420 bool Encloses(const DeclContext *DC) const;
1421
1422 /// \brief Find the nearest non-closure ancestor of this context,
1423 /// i.e. the innermost semantic parent of this context which is not
1424 /// a closure. A context may be its own non-closure ancestor.
1425 Decl *getNonClosureAncestor();
1426 const Decl *getNonClosureAncestor() const {
1427 return const_cast<DeclContext*>(this)->getNonClosureAncestor();
1428 }
1429
1430 /// getPrimaryContext - There may be many different
1431 /// declarations of the same entity (including forward declarations
1432 /// of classes, multiple definitions of namespaces, etc.), each with
1433 /// a different set of declarations. This routine returns the
1434 /// "primary" DeclContext structure, which will contain the
1435 /// information needed to perform name lookup into this context.
1436 DeclContext *getPrimaryContext();
1437 const DeclContext *getPrimaryContext() const {
1438 return const_cast<DeclContext*>(this)->getPrimaryContext();
1439 }
1440
1441 /// getRedeclContext - Retrieve the context in which an entity conflicts with
1442 /// other entities of the same name, or where it is a redeclaration if the
1443 /// two entities are compatible. This skips through transparent contexts.
1444 DeclContext *getRedeclContext();
1445 const DeclContext *getRedeclContext() const {
1446 return const_cast<DeclContext *>(this)->getRedeclContext();
1447 }
1448
1449 /// \brief Retrieve the nearest enclosing namespace context.
1450 DeclContext *getEnclosingNamespaceContext();
1451 const DeclContext *getEnclosingNamespaceContext() const {
1452 return const_cast<DeclContext *>(this)->getEnclosingNamespaceContext();
1453 }
1454
1455 /// \brief Retrieve the outermost lexically enclosing record context.
1456 RecordDecl *getOuterLexicalRecordContext();
1457 const RecordDecl *getOuterLexicalRecordContext() const {
1458 return const_cast<DeclContext *>(this)->getOuterLexicalRecordContext();
1459 }
1460
1461 /// \brief Test if this context is part of the enclosing namespace set of
1462 /// the context NS, as defined in C++0x [namespace.def]p9. If either context
1463 /// isn't a namespace, this is equivalent to Equals().
1464 ///
1465 /// The enclosing namespace set of a namespace is the namespace and, if it is
1466 /// inline, its enclosing namespace, recursively.
1467 bool InEnclosingNamespaceSetOf(const DeclContext *NS) const;
1468
1469 /// \brief Collects all of the declaration contexts that are semantically
1470 /// connected to this declaration context.
1471 ///
1472 /// For declaration contexts that have multiple semantically connected but
1473 /// syntactically distinct contexts, such as C++ namespaces, this routine
1474 /// retrieves the complete set of such declaration contexts in source order.
1475 /// For example, given:
1476 ///
1477 /// \code
1478 /// namespace N {
1479 /// int x;
1480 /// }
1481 /// namespace N {
1482 /// int y;
1483 /// }
1484 /// \endcode
1485 ///
1486 /// The \c Contexts parameter will contain both definitions of N.
1487 ///
1488 /// \param Contexts Will be cleared and set to the set of declaration
1489 /// contexts that are semanticaly connected to this declaration context,
1490 /// in source order, including this context (which may be the only result,
1491 /// for non-namespace contexts).
1492 void collectAllContexts(SmallVectorImpl<DeclContext *> &Contexts);
1493
1494 /// decl_iterator - Iterates through the declarations stored
1495 /// within this context.
1496 class decl_iterator {
1497 /// Current - The current declaration.
1498 Decl *Current;
1499
1500 public:
1501 typedef Decl *value_type;
1502 typedef const value_type &reference;
1503 typedef const value_type *pointer;
1504 typedef std::forward_iterator_tag iterator_category;
1505 typedef std::ptrdiff_t difference_type;
1506
1507 decl_iterator() : Current(nullptr) { }
1508 explicit decl_iterator(Decl *C) : Current(C) { }
1509
1510 reference operator*() const { return Current; }
1511 // This doesn't meet the iterator requirements, but it's convenient
1512 value_type operator->() const { return Current; }
1513
1514 decl_iterator& operator++() {
1515 Current = Current->getNextDeclInContext();
1516 return *this;
1517 }
1518
1519 decl_iterator operator++(int) {
1520 decl_iterator tmp(*this);
1521 ++(*this);
1522 return tmp;
1523 }
1524
1525 friend bool operator==(decl_iterator x, decl_iterator y) {
1526 return x.Current == y.Current;
1527 }
1528 friend bool operator!=(decl_iterator x, decl_iterator y) {
1529 return x.Current != y.Current;
1530 }
1531 };
1532
1533 typedef llvm::iterator_range<decl_iterator> decl_range;
1534
1535 /// decls_begin/decls_end - Iterate over the declarations stored in
1536 /// this context.
1537 decl_range decls() const { return decl_range(decls_begin(), decls_end()); }
1538 decl_iterator decls_begin() const;
1539 decl_iterator decls_end() const { return decl_iterator(); }
1540 bool decls_empty() const;
1541
1542 /// noload_decls_begin/end - Iterate over the declarations stored in this
1543 /// context that are currently loaded; don't attempt to retrieve anything
1544 /// from an external source.
1545 decl_range noload_decls() const {
1546 return decl_range(noload_decls_begin(), noload_decls_end());
1547 }
1548 decl_iterator noload_decls_begin() const { return decl_iterator(FirstDecl); }
1549 decl_iterator noload_decls_end() const { return decl_iterator(); }
1550
1551 /// specific_decl_iterator - Iterates over a subrange of
1552 /// declarations stored in a DeclContext, providing only those that
1553 /// are of type SpecificDecl (or a class derived from it). This
1554 /// iterator is used, for example, to provide iteration over just
1555 /// the fields within a RecordDecl (with SpecificDecl = FieldDecl).
1556 template<typename SpecificDecl>
1557 class specific_decl_iterator {
1558 /// Current - The current, underlying declaration iterator, which
1559 /// will either be NULL or will point to a declaration of
1560 /// type SpecificDecl.
1561 DeclContext::decl_iterator Current;
1562
1563 /// SkipToNextDecl - Advances the current position up to the next
1564 /// declaration of type SpecificDecl that also meets the criteria
1565 /// required by Acceptable.
1566 void SkipToNextDecl() {
1567 while (*Current && !isa<SpecificDecl>(*Current))
1568 ++Current;
1569 }
1570
1571 public:
1572 typedef SpecificDecl *value_type;
1573 // TODO: Add reference and pointer typedefs (with some appropriate proxy
1574 // type) if we ever have a need for them.
1575 typedef void reference;
1576 typedef void pointer;
1577 typedef std::iterator_traits<DeclContext::decl_iterator>::difference_type
1578 difference_type;
1579 typedef std::forward_iterator_tag iterator_category;
1580
1581 specific_decl_iterator() : Current() { }
1582
1583 /// specific_decl_iterator - Construct a new iterator over a
1584 /// subset of the declarations the range [C,
1585 /// end-of-declarations). If A is non-NULL, it is a pointer to a
1586 /// member function of SpecificDecl that should return true for
1587 /// all of the SpecificDecl instances that will be in the subset
1588 /// of iterators. For example, if you want Objective-C instance
1589 /// methods, SpecificDecl will be ObjCMethodDecl and A will be
1590 /// &ObjCMethodDecl::isInstanceMethod.
1591 explicit specific_decl_iterator(DeclContext::decl_iterator C) : Current(C) {
1592 SkipToNextDecl();
1593 }
1594
1595 value_type operator*() const { return cast<SpecificDecl>(*Current); }
1596 // This doesn't meet the iterator requirements, but it's convenient
1597 value_type operator->() const { return **this; }
1598
1599 specific_decl_iterator& operator++() {
1600 ++Current;
1601 SkipToNextDecl();
1602 return *this;
1603 }
1604
1605 specific_decl_iterator operator++(int) {
1606 specific_decl_iterator tmp(*this);
1607 ++(*this);
1608 return tmp;
1609 }
1610
1611 friend bool operator==(const specific_decl_iterator& x,
1612 const specific_decl_iterator& y) {
1613 return x.Current == y.Current;
1614 }
1615
1616 friend bool operator!=(const specific_decl_iterator& x,
1617 const specific_decl_iterator& y) {
1618 return x.Current != y.Current;
1619 }
1620 };
1621
1622 /// \brief Iterates over a filtered subrange of declarations stored
1623 /// in a DeclContext.
1624 ///
1625 /// This iterator visits only those declarations that are of type
1626 /// SpecificDecl (or a class derived from it) and that meet some
1627 /// additional run-time criteria. This iterator is used, for
1628 /// example, to provide access to the instance methods within an
1629 /// Objective-C interface (with SpecificDecl = ObjCMethodDecl and
1630 /// Acceptable = ObjCMethodDecl::isInstanceMethod).
1631 template<typename SpecificDecl, bool (SpecificDecl::*Acceptable)() const>
1632 class filtered_decl_iterator {
1633 /// Current - The current, underlying declaration iterator, which
1634 /// will either be NULL or will point to a declaration of
1635 /// type SpecificDecl.
1636 DeclContext::decl_iterator Current;
1637
1638 /// SkipToNextDecl - Advances the current position up to the next
1639 /// declaration of type SpecificDecl that also meets the criteria
1640 /// required by Acceptable.
1641 void SkipToNextDecl() {
1642 while (*Current &&
1643 (!isa<SpecificDecl>(*Current) ||
1644 (Acceptable && !(cast<SpecificDecl>(*Current)->*Acceptable)())))
1645 ++Current;
1646 }
1647
1648 public:
1649 typedef SpecificDecl *value_type;
1650 // TODO: Add reference and pointer typedefs (with some appropriate proxy
1651 // type) if we ever have a need for them.
1652 typedef void reference;
1653 typedef void pointer;
1654 typedef std::iterator_traits<DeclContext::decl_iterator>::difference_type
1655 difference_type;
1656 typedef std::forward_iterator_tag iterator_category;
1657
1658 filtered_decl_iterator() : Current() { }
1659
1660 /// filtered_decl_iterator - Construct a new iterator over a
1661 /// subset of the declarations the range [C,
1662 /// end-of-declarations). If A is non-NULL, it is a pointer to a
1663 /// member function of SpecificDecl that should return true for
1664 /// all of the SpecificDecl instances that will be in the subset
1665 /// of iterators. For example, if you want Objective-C instance
1666 /// methods, SpecificDecl will be ObjCMethodDecl and A will be
1667 /// &ObjCMethodDecl::isInstanceMethod.
1668 explicit filtered_decl_iterator(DeclContext::decl_iterator C) : Current(C) {
1669 SkipToNextDecl();
1670 }
1671
1672 value_type operator*() const { return cast<SpecificDecl>(*Current); }
1673 value_type operator->() const { return cast<SpecificDecl>(*Current); }
1674
1675 filtered_decl_iterator& operator++() {
1676 ++Current;
1677 SkipToNextDecl();
1678 return *this;
1679 }
1680
1681 filtered_decl_iterator operator++(int) {
1682 filtered_decl_iterator tmp(*this);
1683 ++(*this);
1684 return tmp;
1685 }
1686
1687 friend bool operator==(const filtered_decl_iterator& x,
1688 const filtered_decl_iterator& y) {
1689 return x.Current == y.Current;
1690 }
1691
1692 friend bool operator!=(const filtered_decl_iterator& x,
1693 const filtered_decl_iterator& y) {
1694 return x.Current != y.Current;
1695 }
1696 };
1697
1698 /// @brief Add the declaration D into this context.
1699 ///
1700 /// This routine should be invoked when the declaration D has first
1701 /// been declared, to place D into the context where it was
1702 /// (lexically) defined. Every declaration must be added to one
1703 /// (and only one!) context, where it can be visited via
1704 /// [decls_begin(), decls_end()). Once a declaration has been added
1705 /// to its lexical context, the corresponding DeclContext owns the
1706 /// declaration.
1707 ///
1708 /// If D is also a NamedDecl, it will be made visible within its
1709 /// semantic context via makeDeclVisibleInContext.
1710 void addDecl(Decl *D);
1711
1712 /// @brief Add the declaration D into this context, but suppress
1713 /// searches for external declarations with the same name.
1714 ///
1715 /// Although analogous in function to addDecl, this removes an
1716 /// important check. This is only useful if the Decl is being
1717 /// added in response to an external search; in all other cases,
1718 /// addDecl() is the right function to use.
1719 /// See the ASTImporter for use cases.
1720 void addDeclInternal(Decl *D);
1721
1722 /// @brief Add the declaration D to this context without modifying
1723 /// any lookup tables.
1724 ///
1725 /// This is useful for some operations in dependent contexts where
1726 /// the semantic context might not be dependent; this basically
1727 /// only happens with friends.
1728 void addHiddenDecl(Decl *D);
1729
1730 /// @brief Removes a declaration from this context.
1731 void removeDecl(Decl *D);
1732
1733 /// @brief Checks whether a declaration is in this context.
1734 bool containsDecl(Decl *D) const;
1735
1736 typedef DeclContextLookupResult lookup_result;
1737 typedef lookup_result::iterator lookup_iterator;
1738
1739 /// lookup - Find the declarations (if any) with the given Name in
1740 /// this context. Returns a range of iterators that contains all of
1741 /// the declarations with this name, with object, function, member,
1742 /// and enumerator names preceding any tag name. Note that this
1743 /// routine will not look into parent contexts.
1744 lookup_result lookup(DeclarationName Name) const;
1745
1746 /// \brief Find the declarations with the given name that are visible
1747 /// within this context; don't attempt to retrieve anything from an
1748 /// external source.
1749 lookup_result noload_lookup(DeclarationName Name);
1750
1751 /// \brief A simplistic name lookup mechanism that performs name lookup
1752 /// into this declaration context without consulting the external source.
1753 ///
1754 /// This function should almost never be used, because it subverts the
1755 /// usual relationship between a DeclContext and the external source.
1756 /// See the ASTImporter for the (few, but important) use cases.
1757 ///
1758 /// FIXME: This is very inefficient; replace uses of it with uses of
1759 /// noload_lookup.
1760 void localUncachedLookup(DeclarationName Name,
1761 SmallVectorImpl<NamedDecl *> &Results);
1762
1763 /// @brief Makes a declaration visible within this context.
1764 ///
1765 /// This routine makes the declaration D visible to name lookup
1766 /// within this context and, if this is a transparent context,
1767 /// within its parent contexts up to the first enclosing
1768 /// non-transparent context. Making a declaration visible within a
1769 /// context does not transfer ownership of a declaration, and a
1770 /// declaration can be visible in many contexts that aren't its
1771 /// lexical context.
1772 ///
1773 /// If D is a redeclaration of an existing declaration that is
1774 /// visible from this context, as determined by
1775 /// NamedDecl::declarationReplaces, the previous declaration will be
1776 /// replaced with D.
1777 void makeDeclVisibleInContext(NamedDecl *D);
1778
1779 /// all_lookups_iterator - An iterator that provides a view over the results
1780 /// of looking up every possible name.
1781 class all_lookups_iterator;
1782
1783 typedef llvm::iterator_range<all_lookups_iterator> lookups_range;
1784
1785 lookups_range lookups() const;
1786 lookups_range noload_lookups() const;
1787
1788 /// \brief Iterators over all possible lookups within this context.
1789 all_lookups_iterator lookups_begin() const;
1790 all_lookups_iterator lookups_end() const;
1791
1792 /// \brief Iterators over all possible lookups within this context that are
1793 /// currently loaded; don't attempt to retrieve anything from an external
1794 /// source.
1795 all_lookups_iterator noload_lookups_begin() const;
1796 all_lookups_iterator noload_lookups_end() const;
1797
1798 struct udir_iterator;
1799 typedef llvm::iterator_adaptor_base<udir_iterator, lookup_iterator,
1800 std::random_access_iterator_tag,
1801 UsingDirectiveDecl *> udir_iterator_base;
1802 struct udir_iterator : udir_iterator_base {
1803 udir_iterator(lookup_iterator I) : udir_iterator_base(I) {}
1804 UsingDirectiveDecl *operator*() const;
1805 };
1806
1807 typedef llvm::iterator_range<udir_iterator> udir_range;
1808
1809 udir_range using_directives() const;
1810
1811 // These are all defined in DependentDiagnostic.h.
1812 class ddiag_iterator;
1813 typedef llvm::iterator_range<DeclContext::ddiag_iterator> ddiag_range;
1814
1815 inline ddiag_range ddiags() const;
1816
1817 // Low-level accessors
1818
1819 /// \brief Mark that there are external lexical declarations that we need
1820 /// to include in our lookup table (and that are not available as external
1821 /// visible lookups). These extra lookup results will be found by walking
1822 /// the lexical declarations of this context. This should be used only if
1823 /// setHasExternalLexicalStorage() has been called on any decl context for
1824 /// which this is the primary context.
1825 void setMustBuildLookupTable() {
1826 assert(this == getPrimaryContext() &&
1827 "should only be called on primary context");
1828 HasLazyExternalLexicalLookups = true;
1829 }
1830
1831 /// \brief Retrieve the internal representation of the lookup structure.
1832 /// This may omit some names if we are lazily building the structure.
1833 StoredDeclsMap *getLookupPtr() const { return LookupPtr; }
1834
1835 /// \brief Ensure the lookup structure is fully-built and return it.
1836 StoredDeclsMap *buildLookup();
1837
1838 /// \brief Whether this DeclContext has external storage containing
1839 /// additional declarations that are lexically in this context.
1840 bool hasExternalLexicalStorage() const { return ExternalLexicalStorage; }
1841
1842 /// \brief State whether this DeclContext has external storage for
1843 /// declarations lexically in this context.
1844 void setHasExternalLexicalStorage(bool ES = true) {
1845 ExternalLexicalStorage = ES;
1846 }
1847
1848 /// \brief Whether this DeclContext has external storage containing
1849 /// additional declarations that are visible in this context.
1850 bool hasExternalVisibleStorage() const { return ExternalVisibleStorage; }
1851
1852 /// \brief State whether this DeclContext has external storage for
1853 /// declarations visible in this context.
1854 void setHasExternalVisibleStorage(bool ES = true) {
1855 ExternalVisibleStorage = ES;
1856 if (ES && LookupPtr)
1857 NeedToReconcileExternalVisibleStorage = true;
1858 }
1859
1860 /// \brief Determine whether the given declaration is stored in the list of
1861 /// declarations lexically within this context.
1862 bool isDeclInLexicalTraversal(const Decl *D) const {
1863 return D && (D->NextInContextAndBits.getPointer() || D == FirstDecl ||
1864 D == LastDecl);
1865 }
1866
1867 bool setUseQualifiedLookup(bool use = true) {
1868 bool old_value = UseQualifiedLookup;
1869 UseQualifiedLookup = use;
1870 return old_value;
1871 }
1872
1873 bool shouldUseQualifiedLookup() const {
1874 return UseQualifiedLookup;
1875 }
1876
1877 static bool classof(const Decl *D);
1878 static bool classof(const DeclContext *D) { return true; }
1879
1880 void dumpDeclContext() const;
1881 void dumpLookups() const;
1882 void dumpLookups(llvm::raw_ostream &OS, bool DumpDecls = false,
1883 bool Deserialize = false) const;
1884
1885private:
1886 void reconcileExternalVisibleStorage() const;
1887 bool LoadLexicalDeclsFromExternalStorage() const;
1888
1889 /// @brief Makes a declaration visible within this context, but
1890 /// suppresses searches for external declarations with the same
1891 /// name.
1892 ///
1893 /// Analogous to makeDeclVisibleInContext, but for the exclusive
1894 /// use of addDeclInternal().
1895 void makeDeclVisibleInContextInternal(NamedDecl *D);
1896
1897 friend class DependentDiagnostic;
1898 StoredDeclsMap *CreateStoredDeclsMap(ASTContext &C) const;
1899
1900 void buildLookupImpl(DeclContext *DCtx, bool Internal);
1901 void makeDeclVisibleInContextWithFlags(NamedDecl *D, bool Internal,
1902 bool Rediscoverable);
1903 void makeDeclVisibleInContextImpl(NamedDecl *D, bool Internal);
1904};
1905
1906inline bool Decl::isTemplateParameter() const {
1907 return getKind() == TemplateTypeParm || getKind() == NonTypeTemplateParm ||
1908 getKind() == TemplateTemplateParm;
1909}
1910
1911// Specialization selected when ToTy is not a known subclass of DeclContext.
1912template <class ToTy,
1913 bool IsKnownSubtype = ::std::is_base_of<DeclContext, ToTy>::value>
1914struct cast_convert_decl_context {
1915 static const ToTy *doit(const DeclContext *Val) {
1916 return static_cast<const ToTy*>(Decl::castFromDeclContext(Val));
1917 }
1918
1919 static ToTy *doit(DeclContext *Val) {
1920 return static_cast<ToTy*>(Decl::castFromDeclContext(Val));
1921 }
1922};
1923
1924// Specialization selected when ToTy is a known subclass of DeclContext.
1925template <class ToTy>
1926struct cast_convert_decl_context<ToTy, true> {
1927 static const ToTy *doit(const DeclContext *Val) {
1928 return static_cast<const ToTy*>(Val);
1929 }
1930
1931 static ToTy *doit(DeclContext *Val) {
1932 return static_cast<ToTy*>(Val);
1933 }
1934};
1935
1936
1937} // end clang.
1938
1939namespace llvm {
1940
1941/// isa<T>(DeclContext*)
1942template <typename To>
1943struct isa_impl<To, ::clang::DeclContext> {
1944 static bool doit(const ::clang::DeclContext &Val) {
1945 return To::classofKind(Val.getDeclKind());
1946 }
1947};
1948
1949/// cast<T>(DeclContext*)
1950template<class ToTy>
1951struct cast_convert_val<ToTy,
1952 const ::clang::DeclContext,const ::clang::DeclContext> {
1953 static const ToTy &doit(const ::clang::DeclContext &Val) {
1954 return *::clang::cast_convert_decl_context<ToTy>::doit(&Val);
1955 }
1956};
1957template<class ToTy>
1958struct cast_convert_val<ToTy, ::clang::DeclContext, ::clang::DeclContext> {
1959 static ToTy &doit(::clang::DeclContext &Val) {
1960 return *::clang::cast_convert_decl_context<ToTy>::doit(&Val);
1961 }
1962};
1963template<class ToTy>
1964struct cast_convert_val<ToTy,
1965 const ::clang::DeclContext*, const ::clang::DeclContext*> {
1966 static const ToTy *doit(const ::clang::DeclContext *Val) {
1967 return ::clang::cast_convert_decl_context<ToTy>::doit(Val);
1968 }
1969};
1970template<class ToTy>
1971struct cast_convert_val<ToTy, ::clang::DeclContext*, ::clang::DeclContext*> {
1972 static ToTy *doit(::clang::DeclContext *Val) {
1973 return ::clang::cast_convert_decl_context<ToTy>::doit(Val);
1974 }
1975};
1976
1977/// Implement cast_convert_val for Decl -> DeclContext conversions.
1978template<class FromTy>
1979struct cast_convert_val< ::clang::DeclContext, FromTy, FromTy> {
1980 static ::clang::DeclContext &doit(const FromTy &Val) {
1981 return *FromTy::castToDeclContext(&Val);
1982 }
1983};
1984
1985template<class FromTy>
1986struct cast_convert_val< ::clang::DeclContext, FromTy*, FromTy*> {
1987 static ::clang::DeclContext *doit(const FromTy *Val) {
1988 return FromTy::castToDeclContext(Val);
1989 }
1990};
1991
1992template<class FromTy>
1993struct cast_convert_val< const ::clang::DeclContext, FromTy, FromTy> {
1994 static const ::clang::DeclContext &doit(const FromTy &Val) {
1995 return *FromTy::castToDeclContext(&Val);
1996 }
1997};
1998
1999template<class FromTy>
2000struct cast_convert_val< const ::clang::DeclContext, FromTy*, FromTy*> {
2001 static const ::clang::DeclContext *doit(const FromTy *Val) {
2002 return FromTy::castToDeclContext(Val);
2003 }
2004};
2005
2006} // end namespace llvm
2007
2008#endif
2009