blob: ce95a1e614aa7c139c05d489b8c8bc66519358d5 [file] [log] [blame]
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001//===---- SemaInherit.cpp - C++ Inheritance ---------------------*- 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 provides Sema routines for C++ inheritance semantics,
Anders Carlsson60d6b0d2009-03-27 04:43:36 +000011// including searching the inheritance hierarchy.
Douglas Gregorbc0805a2008-10-23 00:40:37 +000012//
13//===----------------------------------------------------------------------===//
14
Douglas Gregor94b1dd22008-10-24 04:54:22 +000015#include "SemaInherit.h"
Sebastian Redl7c8bd602009-02-07 20:10:22 +000016#include "Sema.h"
Douglas Gregorbc0805a2008-10-23 00:40:37 +000017#include "clang/AST/ASTContext.h"
18#include "clang/AST/DeclCXX.h"
Douglas Gregor94b1dd22008-10-24 04:54:22 +000019#include "clang/AST/Type.h"
20#include "clang/AST/TypeOrdering.h"
Douglas Gregor7176fff2009-01-15 00:26:24 +000021#include <algorithm>
Douglas Gregor94b1dd22008-10-24 04:54:22 +000022#include <memory>
23#include <set>
24#include <string>
Douglas Gregorbc0805a2008-10-23 00:40:37 +000025
Douglas Gregor0575d4a2008-10-24 16:17:19 +000026using namespace clang;
Douglas Gregorbc0805a2008-10-23 00:40:37 +000027
Douglas Gregor94b1dd22008-10-24 04:54:22 +000028/// isAmbiguous - Determines whether the set of paths provided is
29/// ambiguous, i.e., there are two or more paths that refer to
30/// different base class subobjects of the same type. BaseType must be
31/// an unqualified, canonical class type.
32bool BasePaths::isAmbiguous(QualType BaseType) {
Douglas Gregor0575d4a2008-10-24 16:17:19 +000033 assert(BaseType->isCanonical() && "Base type must be the canonical type");
34 assert(BaseType.getCVRQualifiers() == 0 && "Base type must be unqualified");
Douglas Gregor94b1dd22008-10-24 04:54:22 +000035 std::pair<bool, unsigned>& Subobjects = ClassSubobjects[BaseType];
36 return Subobjects.second + (Subobjects.first? 1 : 0) > 1;
37}
38
39/// clear - Clear out all prior path information.
40void BasePaths::clear() {
41 Paths.clear();
42 ClassSubobjects.clear();
43 ScratchPath.clear();
Sebastian Redl07779722008-10-31 14:43:28 +000044 DetectedVirtual = 0;
Douglas Gregor94b1dd22008-10-24 04:54:22 +000045}
46
Douglas Gregor7176fff2009-01-15 00:26:24 +000047/// @brief Swaps the contents of this BasePaths structure with the
48/// contents of Other.
49void BasePaths::swap(BasePaths &Other) {
Douglas Gregor4dc6b1c2009-01-16 00:38:09 +000050 std::swap(Origin, Other.Origin);
Douglas Gregor7176fff2009-01-15 00:26:24 +000051 Paths.swap(Other.Paths);
52 ClassSubobjects.swap(Other.ClassSubobjects);
53 std::swap(FindAmbiguities, Other.FindAmbiguities);
54 std::swap(RecordPaths, Other.RecordPaths);
55 std::swap(DetectVirtual, Other.DetectVirtual);
56 std::swap(DetectedVirtual, Other.DetectedVirtual);
57}
58
Douglas Gregor27c8dc02008-10-29 00:13:59 +000059/// IsDerivedFrom - Determine whether the type Derived is derived from
60/// the type Base, ignoring qualifiers on Base and Derived. This
61/// routine does not assess whether an actual conversion from a
62/// Derived* to a Base* is legal, because it does not account for
63/// ambiguous conversions or conversions to private/protected bases.
Douglas Gregor94b1dd22008-10-24 04:54:22 +000064bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
Sebastian Redl07779722008-10-31 14:43:28 +000065 BasePaths Paths(/*FindAmbiguities=*/false, /*RecordPaths=*/false,
66 /*DetectVirtual=*/false);
Douglas Gregor94b1dd22008-10-24 04:54:22 +000067 return IsDerivedFrom(Derived, Base, Paths);
68}
69
Douglas Gregor27c8dc02008-10-29 00:13:59 +000070/// IsDerivedFrom - Determine whether the type Derived is derived from
71/// the type Base, ignoring qualifiers on Base and Derived. This
72/// routine does not assess whether an actual conversion from a
73/// Derived* to a Base* is legal, because it does not account for
74/// ambiguous conversions or conversions to private/protected
Douglas Gregor94b1dd22008-10-24 04:54:22 +000075/// bases. This routine will use Paths to determine if there are
76/// ambiguous paths (if @c Paths.isFindingAmbiguities()) and record
Douglas Gregor27c8dc02008-10-29 00:13:59 +000077/// information about all of the paths (if @c Paths.isRecordingPaths()).
Douglas Gregor94b1dd22008-10-24 04:54:22 +000078bool Sema::IsDerivedFrom(QualType Derived, QualType Base, BasePaths &Paths) {
Douglas Gregorbc0805a2008-10-23 00:40:37 +000079 Derived = Context.getCanonicalType(Derived).getUnqualifiedType();
80 Base = Context.getCanonicalType(Base).getUnqualifiedType();
Sebastian Redl07779722008-10-31 14:43:28 +000081
Douglas Gregor27c8dc02008-10-29 00:13:59 +000082 if (!Derived->isRecordType() || !Base->isRecordType())
83 return false;
Douglas Gregorbc0805a2008-10-23 00:40:37 +000084
85 if (Derived == Base)
86 return false;
87
Douglas Gregor4dc6b1c2009-01-16 00:38:09 +000088 Paths.setOrigin(Derived);
Douglas Gregorc1efaec2009-02-28 01:32:25 +000089 return LookupInBases(cast<CXXRecordDecl>(Derived->getAsRecordType()->getDecl()),
Douglas Gregor7176fff2009-01-15 00:26:24 +000090 MemberLookupCriteria(Base), Paths);
91}
Douglas Gregor94b1dd22008-10-24 04:54:22 +000092
Douglas Gregor7176fff2009-01-15 00:26:24 +000093/// LookupInBases - Look for something that meets the specified
94/// Criteria within the base classes of Class (or any of its base
95/// classes, transitively). This routine populates BasePaths with the
96/// list of paths that one can take to find the entity that meets the
97/// search criteria, and returns true if any such entity is found. The
98/// various options passed to the BasePath constructor will affect the
99/// behavior of this lookup, e.g., whether it finds ambiguities,
100/// records paths, or attempts to detect the use of virtual base
101/// classes.
102bool Sema::LookupInBases(CXXRecordDecl *Class,
103 const MemberLookupCriteria& Criteria,
104 BasePaths &Paths) {
105 bool FoundPath = false;
106
107 for (CXXRecordDecl::base_class_const_iterator BaseSpec = Class->bases_begin(),
108 BaseSpecEnd = Class->bases_end();
109 BaseSpec != BaseSpecEnd; ++BaseSpec) {
110 // Find the record of the base class subobjects for this type.
111 QualType BaseType = Context.getCanonicalType(BaseSpec->getType());
112 BaseType = BaseType.getUnqualifiedType();
113
114 // Determine whether we need to visit this base class at all,
115 // updating the count of subobjects appropriately.
116 std::pair<bool, unsigned>& Subobjects = Paths.ClassSubobjects[BaseType];
117 bool VisitBase = true;
118 bool SetVirtual = false;
119 if (BaseSpec->isVirtual()) {
120 VisitBase = !Subobjects.first;
121 Subobjects.first = true;
122 if (Paths.isDetectingVirtual() && Paths.DetectedVirtual == 0) {
123 // If this is the first virtual we find, remember it. If it turns out
124 // there is no base path here, we'll reset it later.
Douglas Gregorc1efaec2009-02-28 01:32:25 +0000125 Paths.DetectedVirtual = BaseType->getAsRecordType();
Douglas Gregor7176fff2009-01-15 00:26:24 +0000126 SetVirtual = true;
127 }
128 } else
129 ++Subobjects.second;
130
131 if (Paths.isRecordingPaths()) {
132 // Add this base specifier to the current path.
133 BasePathElement Element;
134 Element.Base = &*BaseSpec;
135 if (BaseSpec->isVirtual())
136 Element.SubobjectNumber = 0;
137 else
138 Element.SubobjectNumber = Subobjects.second;
139 Paths.ScratchPath.push_back(Element);
140 }
141
142 CXXRecordDecl *BaseRecord
143 = cast<CXXRecordDecl>(BaseSpec->getType()->getAsRecordType()->getDecl());
144
145 // Either look at the base class type or look into the base class
146 // type to see if we've found a member that meets the search
147 // criteria.
148 bool FoundPathToThisBase = false;
149 if (Criteria.LookupBase) {
150 FoundPathToThisBase
151 = (Context.getCanonicalType(BaseSpec->getType()) == Criteria.Base);
152 } else {
153 Paths.ScratchPath.Decls = BaseRecord->lookup(Criteria.Name);
154 while (Paths.ScratchPath.Decls.first != Paths.ScratchPath.Decls.second) {
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000155 if (isAcceptableLookupResult(*Paths.ScratchPath.Decls.first,
156 Criteria.NameKind, Criteria.IDNS)) {
Douglas Gregor7176fff2009-01-15 00:26:24 +0000157 FoundPathToThisBase = true;
158 break;
159 }
160 ++Paths.ScratchPath.Decls.first;
161 }
162 }
163
164 if (FoundPathToThisBase) {
165 // We've found a path that terminates that this base.
166 FoundPath = true;
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000167 if (Paths.isRecordingPaths()) {
Douglas Gregor7176fff2009-01-15 00:26:24 +0000168 // We have a path. Make a copy of it before moving on.
169 Paths.Paths.push_back(Paths.ScratchPath);
170 } else if (!Paths.isFindingAmbiguities()) {
171 // We found a path and we don't care about ambiguities;
172 // return immediately.
173 return FoundPath;
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000174 }
Douglas Gregor7176fff2009-01-15 00:26:24 +0000175 }
176 // C++ [class.member.lookup]p2:
177 // A member name f in one sub-object B hides a member name f in
178 // a sub-object A if A is a base class sub-object of B. Any
179 // declarations that are so hidden are eliminated from
180 // consideration.
181 else if (VisitBase && LookupInBases(BaseRecord, Criteria, Paths)) {
182 // There is a path to a base class that meets the criteria. If we're not
183 // collecting paths or finding ambiguities, we're done.
184 FoundPath = true;
185 if (!Paths.isFindingAmbiguities())
186 return FoundPath;
187 }
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000188
Douglas Gregor7176fff2009-01-15 00:26:24 +0000189 // Pop this base specifier off the current path (if we're
190 // collecting paths).
191 if (Paths.isRecordingPaths())
192 Paths.ScratchPath.pop_back();
193 // If we set a virtual earlier, and this isn't a path, forget it again.
194 if (SetVirtual && !FoundPath) {
195 Paths.DetectedVirtual = 0;
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000196 }
197 }
198
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000199 return FoundPath;
200}
201
202/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
203/// conversion (where Derived and Base are class types) is
204/// well-formed, meaning that the conversion is unambiguous (and
205/// FIXME: that all of the base classes are accessible). Returns true
206/// and emits a diagnostic if the code is ill-formed, returns false
207/// otherwise. Loc is the location where this routine should point to
208/// if there is an error, and Range is the source range to highlight
209/// if there is an error.
210bool
Douglas Gregor0575d4a2008-10-24 16:17:19 +0000211Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
212 SourceLocation Loc, SourceRange Range) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000213 // First, determine whether the path from Derived to Base is
214 // ambiguous. This is slightly more expensive than checking whether
215 // the Derived to Base conversion exists, because here we need to
216 // explore multiple paths to determine if there is an ambiguity.
Sebastian Redl07779722008-10-31 14:43:28 +0000217 BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
218 /*DetectVirtual=*/false);
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000219 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
Sebastian Redl21593ac2009-01-28 18:33:18 +0000220 assert(DerivationOkay &&
221 "Can only be used with a derived-to-base conversion");
222 (void)DerivationOkay;
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000223
Douglas Gregor0575d4a2008-10-24 16:17:19 +0000224 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType()))
225 return false;
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000226
Douglas Gregor0575d4a2008-10-24 16:17:19 +0000227 // We know that the derived-to-base conversion is ambiguous, and
228 // we're going to produce a diagnostic. Perform the derived-to-base
229 // search just one more time to compute all of the possible paths so
230 // that we can print them out. This is more expensive than any of
231 // the previous derived-to-base checks we've done, but at this point
232 // performance isn't as much of an issue.
233 Paths.clear();
234 Paths.setRecordingPaths(true);
235 bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
236 assert(StillOkay && "Can only be used with a derived-to-base conversion");
Sebastian Redl21593ac2009-01-28 18:33:18 +0000237 (void)StillOkay;
Douglas Gregor0575d4a2008-10-24 16:17:19 +0000238
239 // Build up a textual representation of the ambiguous paths, e.g.,
240 // D -> B -> A, that will be used to illustrate the ambiguous
241 // conversions in the diagnostic. We only print one of the paths
242 // to each base class subobject.
Douglas Gregor4dc6b1c2009-01-16 00:38:09 +0000243 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
244
245 Diag(Loc, diag::err_ambiguous_derived_to_base_conv)
246 << Derived << Base << PathDisplayStr << Range;
247 return true;
248}
249
250/// @brief Builds a string representing ambiguous paths from a
251/// specific derived class to different subobjects of the same base
252/// class.
253///
254/// This function builds a string that can be used in error messages
255/// to show the different paths that one can take through the
256/// inheritance hierarchy to go from the derived class to different
257/// subobjects of a base class. The result looks something like this:
258/// @code
259/// struct D -> struct B -> struct A
260/// struct D -> struct C -> struct A
261/// @endcode
262std::string Sema::getAmbiguousPathsDisplayString(BasePaths &Paths) {
Douglas Gregor0575d4a2008-10-24 16:17:19 +0000263 std::string PathDisplayStr;
264 std::set<unsigned> DisplayedPaths;
265 for (BasePaths::paths_iterator Path = Paths.begin();
266 Path != Paths.end(); ++Path) {
267 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
268 // We haven't displayed a path to this particular base
269 // class subobject yet.
270 PathDisplayStr += "\n ";
Douglas Gregor4dc6b1c2009-01-16 00:38:09 +0000271 PathDisplayStr += Paths.getOrigin().getAsString();
Douglas Gregor0575d4a2008-10-24 16:17:19 +0000272 for (BasePath::const_iterator Element = Path->begin();
273 Element != Path->end(); ++Element)
274 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
275 }
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000276 }
Douglas Gregor4dc6b1c2009-01-16 00:38:09 +0000277
278 return PathDisplayStr;
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000279}