blob: 246df63373f83b79b15a1619ae4e6e21c2682ca3 [file] [log] [blame]
Sebastian Redl2b6b14c2008-11-05 21:50:06 +00001//===--- SemaNamedCast.cpp - Semantic Analysis for Named Casts ------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for C++ named casts.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
15#include "SemaInherit.h"
16#include "clang/AST/ExprCXX.h"
17#include "clang/AST/ASTContext.h"
18#include "clang/Basic/Diagnostic.h"
19#include "llvm/ADT/SmallVector.h"
Sebastian Redl0528e1c2008-11-07 23:29:29 +000020#include <set>
Sebastian Redl2b6b14c2008-11-05 21:50:06 +000021using namespace clang;
22
23/// ActOnCXXNamedCast - Parse {dynamic,static,reinterpret,const}_cast's.
24Action::ExprResult
25Sema::ActOnCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind,
26 SourceLocation LAngleBracketLoc, TypeTy *Ty,
27 SourceLocation RAngleBracketLoc,
28 SourceLocation LParenLoc, ExprTy *E,
29 SourceLocation RParenLoc) {
30 Expr *Ex = (Expr*)E;
31 QualType DestType = QualType::getFromOpaquePtr(Ty);
32 SourceRange OpRange(OpLoc, RParenLoc);
33 SourceRange DestRange(LAngleBracketLoc, RAngleBracketLoc);
34
35 switch (Kind) {
36 default: assert(0 && "Unknown C++ cast!");
37
38 case tok::kw_const_cast:
39 CheckConstCast(Ex, DestType, OpRange, DestRange);
40 return new CXXConstCastExpr(DestType.getNonReferenceType(), Ex,
41 DestType, OpLoc);
42
43 case tok::kw_dynamic_cast:
44 CheckDynamicCast(Ex, DestType, OpRange, DestRange);
45 return new CXXDynamicCastExpr(DestType.getNonReferenceType(), Ex,
46 DestType, OpLoc);
47
48 case tok::kw_reinterpret_cast:
49 CheckReinterpretCast(Ex, DestType, OpRange, DestRange);
50 return new CXXReinterpretCastExpr(DestType.getNonReferenceType(), Ex,
51 DestType, OpLoc);
52
53 case tok::kw_static_cast:
54 CheckStaticCast(Ex, DestType, OpRange);
55 return new CXXStaticCastExpr(DestType.getNonReferenceType(), Ex,
56 DestType, OpLoc);
57 }
58
59 return true;
60}
61
62/// CheckConstCast - Check that a const_cast\<DestType\>(SrcExpr) is valid.
63/// Refer to C++ 5.2.11 for details. const_cast is typically used in code
64/// like this:
65/// const char *str = "literal";
66/// legacy_function(const_cast\<char*\>(str));
67void
68Sema::CheckConstCast(Expr *&SrcExpr, QualType DestType,
69 const SourceRange &OpRange, const SourceRange &DestRange)
70{
71 QualType OrigDestType = DestType, OrigSrcType = SrcExpr->getType();
72
73 DestType = Context.getCanonicalType(DestType);
74 QualType SrcType = SrcExpr->getType();
75 if (const ReferenceType *DestTypeTmp = DestType->getAsReferenceType()) {
76 if (SrcExpr->isLvalue(Context) != Expr::LV_Valid) {
77 // Cannot cast non-lvalue to reference type.
78 Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_rvalue,
79 "const_cast", OrigDestType.getAsString(), SrcExpr->getSourceRange());
80 return;
81 }
82
83 // C++ 5.2.11p4: An lvalue of type T1 can be [cast] to an lvalue of type T2
84 // [...] if a pointer to T1 can be [cast] to the type pointer to T2.
85 DestType = Context.getPointerType(DestTypeTmp->getPointeeType());
86 SrcType = Context.getPointerType(SrcType);
87 } else {
88 // C++ 5.2.11p1: Otherwise, the result is an rvalue and the
89 // lvalue-to-rvalue, array-to-pointer, and function-to-pointer standard
90 // conversions are performed on the expression.
91 DefaultFunctionArrayConversion(SrcExpr);
92 SrcType = SrcExpr->getType();
93 }
94
95 if (!DestType->isPointerType()) {
96 // Cannot cast to non-pointer, non-reference type. Note that, if DestType
97 // was a reference type, we converted it to a pointer above.
98 // C++ 5.2.11p3: For two pointer types [...]
99 Diag(OpRange.getBegin(), diag::err_bad_const_cast_dest,
100 OrigDestType.getAsString(), DestRange);
101 return;
102 }
103 if (DestType->isFunctionPointerType()) {
104 // Cannot cast direct function pointers.
105 // C++ 5.2.11p2: [...] where T is any object type or the void type [...]
106 // T is the ultimate pointee of source and target type.
107 Diag(OpRange.getBegin(), diag::err_bad_const_cast_dest,
108 OrigDestType.getAsString(), DestRange);
109 return;
110 }
111 SrcType = Context.getCanonicalType(SrcType);
112
113 // Unwrap the pointers. Ignore qualifiers. Terminate early if the types are
114 // completely equal.
115 // FIXME: const_cast should probably not be able to convert between pointers
116 // to different address spaces.
117 // C++ 5.2.11p3 describes the core semantics of const_cast. All cv specifiers
118 // in multi-level pointers may change, but the level count must be the same,
119 // as must be the final pointee type.
120 while (SrcType != DestType && UnwrapSimilarPointerTypes(SrcType, DestType)) {
121 SrcType = SrcType.getUnqualifiedType();
122 DestType = DestType.getUnqualifiedType();
123 }
124
125 // Doug Gregor said to disallow this until users complain.
126#if 0
127 // If we end up with constant arrays of equal size, unwrap those too. A cast
128 // from const int [N] to int (&)[N] is invalid by my reading of the
129 // standard, but g++ accepts it even with -ansi -pedantic.
130 // No more than one level, though, so don't embed this in the unwrap loop
131 // above.
132 const ConstantArrayType *SrcTypeArr, *DestTypeArr;
133 if ((SrcTypeArr = Context.getAsConstantArrayType(SrcType)) &&
134 (DestTypeArr = Context.getAsConstantArrayType(DestType)))
135 {
136 if (SrcTypeArr->getSize() != DestTypeArr->getSize()) {
137 // Different array sizes.
138 Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_generic, "const_cast",
139 OrigDestType.getAsString(), OrigSrcType.getAsString(), OpRange);
140 return;
141 }
142 SrcType = SrcTypeArr->getElementType().getUnqualifiedType();
143 DestType = DestTypeArr->getElementType().getUnqualifiedType();
144 }
145#endif
146
147 // Since we're dealing in canonical types, the remainder must be the same.
148 if (SrcType != DestType) {
149 // Cast between unrelated types.
150 Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_generic, "const_cast",
151 OrigDestType.getAsString(), OrigSrcType.getAsString(), OpRange);
152 return;
153 }
154}
155
156/// CheckReinterpretCast - Check that a reinterpret_cast\<DestType\>(SrcExpr) is
157/// valid.
158/// Refer to C++ 5.2.10 for details. reinterpret_cast is typically used in code
159/// like this:
160/// char *bytes = reinterpret_cast\<char*\>(int_ptr);
161void
162Sema::CheckReinterpretCast(Expr *&SrcExpr, QualType DestType,
163 const SourceRange &OpRange,
164 const SourceRange &DestRange)
165{
166 QualType OrigDestType = DestType, OrigSrcType = SrcExpr->getType();
167
168 DestType = Context.getCanonicalType(DestType);
169 QualType SrcType = SrcExpr->getType();
170 if (const ReferenceType *DestTypeTmp = DestType->getAsReferenceType()) {
171 if (SrcExpr->isLvalue(Context) != Expr::LV_Valid) {
172 // Cannot cast non-lvalue to reference type.
173 Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_rvalue,
174 "reinterpret_cast", OrigDestType.getAsString(),
175 SrcExpr->getSourceRange());
176 return;
177 }
178
179 // C++ 5.2.10p10: [...] a reference cast reinterpret_cast<T&>(x) has the
180 // same effect as the conversion *reinterpret_cast<T*>(&x) with the
181 // built-in & and * operators.
182 // This code does this transformation for the checked types.
183 DestType = Context.getPointerType(DestTypeTmp->getPointeeType());
184 SrcType = Context.getPointerType(SrcType);
185 } else {
186 // C++ 5.2.10p1: [...] the lvalue-to-rvalue, array-to-pointer, and
187 // function-to-pointer standard conversions are performed on the
188 // expression v.
189 DefaultFunctionArrayConversion(SrcExpr);
190 SrcType = SrcExpr->getType();
191 }
192
193 // Canonicalize source for comparison.
194 SrcType = Context.getCanonicalType(SrcType);
195
196 bool destIsPtr = DestType->isPointerType();
197 bool srcIsPtr = SrcType->isPointerType();
198 if (!destIsPtr && !srcIsPtr) {
199 // Except for std::nullptr_t->integer, which is not supported yet, and
200 // lvalue->reference, which is handled above, at least one of the two
201 // arguments must be a pointer.
202 Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_generic, "reinterpret_cast",
203 OrigDestType.getAsString(), OrigSrcType.getAsString(), OpRange);
204 return;
205 }
206
207 if (SrcType == DestType) {
208 // C++ 5.2.10p2 has a note that mentions that, subject to all other
209 // restrictions, a cast to the same type is allowed. The intent is not
210 // entirely clear here, since all other paragraphs explicitly forbid casts
211 // to the same type. However, the behavior of compilers is pretty consistent
212 // on this point: allow same-type conversion if the involved are pointers,
213 // disallow otherwise.
214 return;
215 }
216
217 // Note: Clang treats enumeration types as integral types. If this is ever
218 // changed for C++, the additional check here will be redundant.
219 if (DestType->isIntegralType() && !DestType->isEnumeralType()) {
Sebastian Redldbed5902008-11-05 22:15:14 +0000220 assert(srcIsPtr && "One type must be a pointer");
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000221 // C++ 5.2.10p4: A pointer can be explicitly converted to any integral
222 // type large enough to hold it.
223 if (Context.getTypeSize(SrcType) > Context.getTypeSize(DestType)) {
224 Diag(OpRange.getBegin(), diag::err_bad_reinterpret_cast_small_int,
225 OrigDestType.getAsString(), DestRange);
226 }
227 return;
228 }
229
230 if (SrcType->isIntegralType() || SrcType->isEnumeralType()) {
Sebastian Redldbed5902008-11-05 22:15:14 +0000231 assert(destIsPtr && "One type must be a pointer");
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000232 // C++ 5.2.10p5: A value of integral or enumeration type can be explicitly
233 // converted to a pointer.
234 return;
235 }
236
237 if (!destIsPtr || !srcIsPtr) {
238 // With the valid non-pointer conversions out of the way, we can be even
239 // more stringent.
240 Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_generic, "reinterpret_cast",
241 OrigDestType.getAsString(), OrigSrcType.getAsString(), OpRange);
242 return;
243 }
244
245 // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away constness.
246 if (CastsAwayConstness(SrcType, DestType)) {
247 Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_const_away,
248 "reinterpret_cast", OrigDestType.getAsString(), OrigSrcType.getAsString(),
249 OpRange);
250 return;
251 }
252
253 // Not casting away constness, so the only remaining check is for compatible
254 // pointer categories.
255
256 if (SrcType->isFunctionPointerType()) {
257 if (DestType->isFunctionPointerType()) {
258 // C++ 5.2.10p6: A pointer to a function can be explicitly converted to
259 // a pointer to a function of a different type.
260 return;
261 }
262
263 // FIXME: Handle member pointers.
264
265 // C++0x 5.2.10p8: Converting a pointer to a function into a pointer to
266 // an object type or vice versa is conditionally-supported.
267 // Compilers support it in C++03 too, though, because it's necessary for
268 // casting the return value of dlsym() and GetProcAddress().
269 // FIXME: Conditionally-supported behavior should be configurable in the
270 // TargetInfo or similar.
271 if (!getLangOptions().CPlusPlus0x) {
272 Diag(OpRange.getBegin(), diag::ext_reinterpret_cast_fn_obj, OpRange);
273 }
274 return;
275 }
276
277 // FIXME: Handle member pointers.
278
279 if (DestType->isFunctionPointerType()) {
280 // See above.
281 if (!getLangOptions().CPlusPlus0x) {
282 Diag(OpRange.getBegin(), diag::ext_reinterpret_cast_fn_obj, OpRange);
283 }
284 return;
285 }
286
287 // C++ 5.2.10p7: A pointer to an object can be explicitly converted to
288 // a pointer to an object of different type.
289 // Void pointers are not specified, but supported by every compiler out there.
290 // So we finish by allowing everything that remains - it's got to be two
291 // object pointers.
292}
293
294/// CastsAwayConstness - Check if the pointer conversion from SrcType
295/// to DestType casts away constness as defined in C++
296/// 5.2.11p8ff. This is used by the cast checkers. Both arguments
297/// must denote pointer types.
298bool
299Sema::CastsAwayConstness(QualType SrcType, QualType DestType)
300{
301 // Casting away constness is defined in C++ 5.2.11p8 with reference to
302 // C++ 4.4.
303 // We piggyback on Sema::IsQualificationConversion for this, since the rules
304 // are non-trivial. So first we construct Tcv *...cv* as described in
305 // C++ 5.2.11p8.
306
307 QualType UnwrappedSrcType = SrcType, UnwrappedDestType = DestType;
308 llvm::SmallVector<unsigned, 8> cv1, cv2;
309
310 // Find the qualifications.
311 while (UnwrapSimilarPointerTypes(UnwrappedSrcType, UnwrappedDestType)) {
312 cv1.push_back(UnwrappedSrcType.getCVRQualifiers());
313 cv2.push_back(UnwrappedDestType.getCVRQualifiers());
314 }
315 assert(cv1.size() > 0 && "Must have at least one pointer level.");
316
317 // Construct void pointers with those qualifiers (in reverse order of
318 // unwrapping, of course).
319 QualType SrcConstruct = Context.VoidTy;
320 QualType DestConstruct = Context.VoidTy;
321 for (llvm::SmallVector<unsigned, 8>::reverse_iterator i1 = cv1.rbegin(),
322 i2 = cv2.rbegin();
323 i1 != cv1.rend(); ++i1, ++i2)
324 {
325 SrcConstruct = Context.getPointerType(SrcConstruct.getQualifiedType(*i1));
326 DestConstruct = Context.getPointerType(DestConstruct.getQualifiedType(*i2));
327 }
328
329 // Test if they're compatible.
330 return SrcConstruct != DestConstruct &&
331 !IsQualificationConversion(SrcConstruct, DestConstruct);
332}
333
334/// CheckStaticCast - Check that a static_cast\<DestType\>(SrcExpr) is valid.
335/// Refer to C++ 5.2.9 for details. Static casts are mostly used for making
336/// implicit conversions explicit and getting rid of data loss warnings.
337void
338Sema::CheckStaticCast(Expr *&SrcExpr, QualType DestType,
339 const SourceRange &OpRange)
340{
341 // The order the tests is not entirely arbitrary. There is one conversion
342 // that can be handled in two different ways. Given:
343 // struct A {};
344 // struct B : public A {
345 // B(); B(const A&);
346 // };
347 // const A &a = B();
348 // the cast static_cast<const B&>(a) could be seen as either a static
349 // reference downcast, or an explicit invocation of the user-defined
350 // conversion using B's conversion constructor.
351 // DR 427 specifies that the downcast is to be applied here.
352
353 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
354 if (DestType->isVoidType()) {
355 return;
356 }
357
358 // C++ 5.2.9p5, reference downcast.
359 // See the function for details.
360 // DR 427 specifies that this is to be applied before paragraph 2.
Sebastian Redl0528e1c2008-11-07 23:29:29 +0000361 if (TryStaticReferenceDowncast(SrcExpr, DestType, OpRange)
362 > TSC_NotApplicable) {
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000363 return;
364 }
365
366 // C++ 5.2.9p2: An expression e can be explicitly converted to a type T
367 // [...] if the declaration "T t(e);" is well-formed, [...].
Sebastian Redl0528e1c2008-11-07 23:29:29 +0000368 if (TryStaticImplicitCast(SrcExpr, DestType, OpRange) > TSC_NotApplicable) {
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000369 return;
370 }
371
372 // C++ 5.2.9p6: May apply the reverse of any standard conversion, except
373 // lvalue-to-rvalue, array-to-pointer, function-to-pointer, and boolean
374 // conversions, subject to further restrictions.
375 // Also, C++ 5.2.9p1 forbids casting away constness, which makes reversal
376 // of qualification conversions impossible.
377
378 // The lvalue-to-rvalue, array-to-pointer and function-to-pointer conversions
379 // are applied to the expression.
380 QualType OrigSrcType = SrcExpr->getType();
381 DefaultFunctionArrayConversion(SrcExpr);
382
383 QualType SrcType = Context.getCanonicalType(SrcExpr->getType());
384
385 // Reverse integral promotion/conversion. All such conversions are themselves
386 // again integral promotions or conversions and are thus already handled by
387 // p2 (TryDirectInitialization above).
388 // (Note: any data loss warnings should be suppressed.)
389 // The exception is the reverse of enum->integer, i.e. integer->enum (and
390 // enum->enum). See also C++ 5.2.9p7.
391 // The same goes for reverse floating point promotion/conversion and
392 // floating-integral conversions. Again, only floating->enum is relevant.
393 if (DestType->isEnumeralType()) {
394 if (SrcType->isComplexType() || SrcType->isVectorType()) {
395 // Fall through - these cannot be converted.
396 } else if (SrcType->isArithmeticType() || SrcType->isEnumeralType()) {
397 return;
398 }
399 }
400
401 // Reverse pointer upcast. C++ 4.10p3 specifies pointer upcast.
402 // C++ 5.2.9p8 additionally disallows a cast path through virtual inheritance.
Sebastian Redl0528e1c2008-11-07 23:29:29 +0000403 if (TryStaticPointerDowncast(SrcType, DestType, OpRange)
404 > TSC_NotApplicable) {
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000405 return;
406 }
407
408 // Reverse member pointer conversion. C++ 5.11 specifies member pointer
409 // conversion. C++ 5.2.9p9 has additional information.
410 // DR54's access restrictions apply here also.
411 // FIXME: Don't have member pointers yet.
412
413 // Reverse pointer conversion to void*. C++ 4.10.p2 specifies conversion to
414 // void*. C++ 5.2.9p10 specifies additional restrictions, which really is
415 // just the usual constness stuff.
416 if (const PointerType *SrcPointer = SrcType->getAsPointerType()) {
417 QualType SrcPointee = SrcPointer->getPointeeType();
418 if (SrcPointee->isVoidType()) {
419 if (const PointerType *DestPointer = DestType->getAsPointerType()) {
420 QualType DestPointee = DestPointer->getPointeeType();
421 if (DestPointee->isObjectType()) {
422 // This is definitely the intended conversion, but it might fail due
423 // to a const violation.
424 if (!DestPointee.isAtLeastAsQualifiedAs(SrcPointee)) {
425 Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_const_away,
426 "static_cast", DestType.getAsString(),
427 OrigSrcType.getAsString(), OpRange);
428 }
429 return;
430 }
431 }
432 }
433 }
434
435 // We tried everything. Everything! Nothing works! :-(
436 // FIXME: Error reporting could be a lot better. Should store the reason
437 // why every substep failed and, at the end, select the most specific and
438 // report that.
439 Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_generic, "static_cast",
440 DestType.getAsString(), OrigSrcType.getAsString(), OpRange);
441}
442
443/// Tests whether a conversion according to C++ 5.2.9p5 is valid.
Sebastian Redl0528e1c2008-11-07 23:29:29 +0000444Sema::TryStaticCastResult
445Sema::TryStaticReferenceDowncast(Expr *SrcExpr, QualType DestType,
446 const SourceRange &OpRange)
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000447{
448 // C++ 5.2.9p5: An lvalue of type "cv1 B", where B is a class type, can be
449 // cast to type "reference to cv2 D", where D is a class derived from B,
450 // if a valid standard conversion from "pointer to D" to "pointer to B"
451 // exists, cv2 >= cv1, and B is not a virtual base class of D.
452 // In addition, DR54 clarifies that the base must be accessible in the
453 // current context. Although the wording of DR54 only applies to the pointer
454 // variant of this rule, the intent is clearly for it to apply to the this
455 // conversion as well.
456
457 if (SrcExpr->isLvalue(Context) != Expr::LV_Valid) {
Sebastian Redl0528e1c2008-11-07 23:29:29 +0000458 return TSC_NotApplicable;
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000459 }
460
461 const ReferenceType *DestReference = DestType->getAsReferenceType();
462 if (!DestReference) {
Sebastian Redl0528e1c2008-11-07 23:29:29 +0000463 return TSC_NotApplicable;
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000464 }
465 QualType DestPointee = DestReference->getPointeeType();
466
Sebastian Redl0528e1c2008-11-07 23:29:29 +0000467 return TryStaticDowncast(SrcExpr->getType(), DestPointee, OpRange,
468 SrcExpr->getType(), DestType);
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000469}
470
471/// Tests whether a conversion according to C++ 5.2.9p8 is valid.
Sebastian Redl0528e1c2008-11-07 23:29:29 +0000472Sema::TryStaticCastResult
473Sema::TryStaticPointerDowncast(QualType SrcType, QualType DestType,
474 const SourceRange &OpRange)
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000475{
476 // C++ 5.2.9p8: An rvalue of type "pointer to cv1 B", where B is a class
477 // type, can be converted to an rvalue of type "pointer to cv2 D", where D
478 // is a class derived from B, if a valid standard conversion from "pointer
479 // to D" to "pointer to B" exists, cv2 >= cv1, and B is not a virtual base
480 // class of D.
481 // In addition, DR54 clarifies that the base must be accessible in the
482 // current context.
483
484 const PointerType *SrcPointer = SrcType->getAsPointerType();
485 if (!SrcPointer) {
Sebastian Redl0528e1c2008-11-07 23:29:29 +0000486 return TSC_NotApplicable;
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000487 }
488
489 const PointerType *DestPointer = DestType->getAsPointerType();
490 if (!DestPointer) {
Sebastian Redl0528e1c2008-11-07 23:29:29 +0000491 return TSC_NotApplicable;
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000492 }
493
Sebastian Redl0528e1c2008-11-07 23:29:29 +0000494 return TryStaticDowncast(SrcPointer->getPointeeType(),
495 DestPointer->getPointeeType(),
496 OpRange, SrcType, DestType);
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000497}
498
Sebastian Redl0528e1c2008-11-07 23:29:29 +0000499/// TryStaticDowncast - Common functionality of TryStaticReferenceDowncast and
500/// TryStaticPointerDowncast. Tests whether a static downcast from SrcType to
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000501/// DestType, both of which must be canonical, is possible and allowed.
Sebastian Redl0528e1c2008-11-07 23:29:29 +0000502Sema::TryStaticCastResult
503Sema::TryStaticDowncast(QualType SrcType, QualType DestType,
504 const SourceRange &OpRange, QualType OrigSrcType,
505 QualType OrigDestType)
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000506{
507 // Downcast can only happen in class hierarchies, so we need classes.
508 if (!DestType->isRecordType() || !SrcType->isRecordType()) {
Sebastian Redl0528e1c2008-11-07 23:29:29 +0000509 return TSC_NotApplicable;
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000510 }
511
512 BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
513 /*DetectVirtual=*/true);
514 if (!IsDerivedFrom(DestType, SrcType, Paths)) {
Sebastian Redl0528e1c2008-11-07 23:29:29 +0000515 return TSC_NotApplicable;
516 }
517
518 // Target type does derive from source type. Now we're serious. If an error
519 // appears now, it's not ignored.
520 // This may not be entirely in line with the standard. Take for example:
521 // struct A {};
522 // struct B : virtual A {
523 // B(A&);
524 // };
525 //
526 // void f()
527 // {
528 // (void)static_cast<const B&>(*((A*)0));
529 // }
530 // As far as the standard is concerned, p5 does not apply (A is virtual), so
531 // p2 should be used instead - "const B& t(*((A*)0));" is perfectly valid.
532 // However, both GCC and Comeau reject this example, and accepting it would
533 // mean more complex code if we're to preserve the nice error message.
534 // FIXME: Being 100% compliant here would be nice to have.
535
536 // Must preserve cv, as always.
537 if (!DestType.isAtLeastAsQualifiedAs(SrcType)) {
538 Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_const_away,
539 "static_cast", OrigDestType.getAsString(), OrigSrcType.getAsString(),
540 OpRange);
541 return TSC_Failed;
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000542 }
543
544 if (Paths.isAmbiguous(SrcType.getUnqualifiedType())) {
Sebastian Redl0528e1c2008-11-07 23:29:29 +0000545 // This code is analoguous to that in CheckDerivedToBaseConversion, except
546 // that it builds the paths in reverse order.
547 // To sum up: record all paths to the base and build a nice string from
548 // them. Use it to spice up the error message.
549 Paths.clear();
550 Paths.setRecordingPaths(true);
551 IsDerivedFrom(DestType, SrcType, Paths);
552 std::string PathDisplayStr;
553 std::set<unsigned> DisplayedPaths;
554 for (BasePaths::paths_iterator Path = Paths.begin();
555 Path != Paths.end(); ++Path) {
556 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
557 // We haven't displayed a path to this particular base
558 // class subobject yet.
559 PathDisplayStr += "\n ";
560 for (BasePath::const_reverse_iterator Element = Path->rbegin();
561 Element != Path->rend(); ++Element)
562 PathDisplayStr += Element->Base->getType().getAsString() + " -> ";
563 PathDisplayStr += DestType.getAsString();
564 }
565 }
566
567 Diag(OpRange.getBegin(), diag::err_ambiguous_base_to_derived_cast,
568 SrcType.getUnqualifiedType().getAsString(),
569 DestType.getUnqualifiedType().getAsString(),
570 PathDisplayStr, OpRange);
571 return TSC_Failed;
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000572 }
573
574 if (Paths.getDetectedVirtual() != 0) {
Sebastian Redl0528e1c2008-11-07 23:29:29 +0000575 QualType VirtualBase(Paths.getDetectedVirtual(), 0);
576 Diag(OpRange.getBegin(), diag::err_static_downcast_via_virtual,
577 OrigSrcType.getAsString(), OrigDestType.getAsString(),
578 VirtualBase.getAsString(), OpRange);
579 return TSC_Failed;
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000580 }
581
582 // FIXME: Test accessibility.
583
Sebastian Redl0528e1c2008-11-07 23:29:29 +0000584 return TSC_Success;
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000585}
586
Sebastian Redl0528e1c2008-11-07 23:29:29 +0000587/// TryStaticImplicitCast - Tests whether a conversion according to C++ 5.2.9p2
588/// is valid:
589///
590/// An expression e can be explicitly converted to a type T using a
591/// @c static_cast if the declaration "T t(e);" is well-formed [...].
592Sema::TryStaticCastResult
593Sema::TryStaticImplicitCast(Expr *SrcExpr, QualType DestType,
594 const SourceRange &OpRange)
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000595{
Sebastian Redl0528e1c2008-11-07 23:29:29 +0000596 if (DestType->isReferenceType()) {
597 // At this point of CheckStaticCast, if the destination is a reference,
598 // this has to work. There is no other way that works.
599 return CheckReferenceInit(SrcExpr, DestType) ? TSC_Failed : TSC_Success;
600 }
601 if (DestType->isRecordType()) {
602 // FIXME: Use an implementation of C++ [over.match.ctor] for this.
603 return TSC_NotApplicable;
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000604 }
605
Sebastian Redl0528e1c2008-11-07 23:29:29 +0000606 // FIXME: To get a proper error from invalid conversions here, we need to
607 // reimplement more of this.
608 ImplicitConversionSequence ICS = TryImplicitConversion(SrcExpr, DestType);
609 return ICS.ConversionKind == ImplicitConversionSequence::BadConversion ?
610 TSC_NotApplicable : TSC_Success;
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000611}
612
613/// CheckDynamicCast - Check that a dynamic_cast\<DestType\>(SrcExpr) is valid.
614/// Refer to C++ 5.2.7 for details. Dynamic casts are used mostly for runtime-
615/// checked downcasts in class hierarchies.
616void
617Sema::CheckDynamicCast(Expr *&SrcExpr, QualType DestType,
618 const SourceRange &OpRange,
619 const SourceRange &DestRange)
620{
621 QualType OrigDestType = DestType, OrigSrcType = SrcExpr->getType();
622 DestType = Context.getCanonicalType(DestType);
623
624 // C++ 5.2.7p1: T shall be a pointer or reference to a complete class type,
625 // or "pointer to cv void".
626
627 QualType DestPointee;
628 const PointerType *DestPointer = DestType->getAsPointerType();
629 const ReferenceType *DestReference = DestType->getAsReferenceType();
630 if (DestPointer) {
631 DestPointee = DestPointer->getPointeeType();
632 } else if (DestReference) {
633 DestPointee = DestReference->getPointeeType();
634 } else {
635 Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ref_or_ptr,
636 OrigDestType.getAsString(), DestRange);
637 return;
638 }
639
640 const RecordType *DestRecord = DestPointee->getAsRecordType();
641 if (DestPointee->isVoidType()) {
642 assert(DestPointer && "Reference to void is not possible");
643 } else if (DestRecord) {
644 if (!DestRecord->getDecl()->isDefinition()) {
645 Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_incomplete,
646 DestPointee.getUnqualifiedType().getAsString(), DestRange);
647 return;
648 }
649 } else {
650 Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class,
651 DestPointee.getUnqualifiedType().getAsString(), DestRange);
652 return;
653 }
654
655 // C++ 5.2.7p2: If T is a pointer type, v shall be an rvalue of a pointer to
656 // complete class type, [...]. If T is a reference type, v shall be an
657 // lvalue of a complete class type, [...].
658
659 QualType SrcType = Context.getCanonicalType(OrigSrcType);
660 QualType SrcPointee;
661 if (DestPointer) {
662 if (const PointerType *SrcPointer = SrcType->getAsPointerType()) {
663 SrcPointee = SrcPointer->getPointeeType();
664 } else {
665 Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ptr,
666 OrigSrcType.getAsString(), SrcExpr->getSourceRange());
667 return;
668 }
669 } else {
670 if (SrcExpr->isLvalue(Context) != Expr::LV_Valid) {
671 Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_rvalue, "dynamic_cast",
672 OrigDestType.getAsString(), OpRange);
673 }
674 SrcPointee = SrcType;
675 }
676
677 const RecordType *SrcRecord = SrcPointee->getAsRecordType();
678 if (SrcRecord) {
679 if (!SrcRecord->getDecl()->isDefinition()) {
680 Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_incomplete,
681 SrcPointee.getUnqualifiedType().getAsString(),
682 SrcExpr->getSourceRange());
683 return;
684 }
685 } else {
686 Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class,
687 SrcPointee.getUnqualifiedType().getAsString(),
688 SrcExpr->getSourceRange());
689 return;
690 }
691
692 assert((DestPointer || DestReference) &&
693 "Bad destination non-ptr/ref slipped through.");
694 assert((DestRecord || DestPointee->isVoidType()) &&
695 "Bad destination pointee slipped through.");
696 assert(SrcRecord && "Bad source pointee slipped through.");
697
698 // C++ 5.2.7p1: The dynamic_cast operator shall not cast away constness.
699 if (!DestPointee.isAtLeastAsQualifiedAs(SrcPointee)) {
700 Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_const_away, "dynamic_cast",
701 OrigDestType.getAsString(), OrigSrcType.getAsString(), OpRange);
702 return;
703 }
704
705 // C++ 5.2.7p3: If the type of v is the same as the required result type,
706 // [except for cv].
707 if (DestRecord == SrcRecord) {
708 return;
709 }
710
711 // C++ 5.2.7p5
712 // Upcasts are resolved statically.
713 if (DestRecord && IsDerivedFrom(SrcPointee, DestPointee)) {
714 CheckDerivedToBaseConversion(SrcPointee, DestPointee, OpRange.getBegin(),
715 OpRange);
716 // Diagnostic already emitted on error.
717 return;
718 }
719
720 // C++ 5.2.7p6: Otherwise, v shall be [polymorphic].
Sebastian Redla1cf66a2008-11-06 15:59:35 +0000721 const RecordDecl *SrcDecl = SrcRecord->getDecl()->getDefinition(Context);
722 assert(SrcDecl && "Definition missing");
723 if (!cast<CXXRecordDecl>(SrcDecl)->isPolymorphic()) {
724 Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_polymorphic,
725 SrcPointee.getUnqualifiedType().getAsString(), SrcExpr->getSourceRange());
726 }
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000727
728 // Done. Everything else is run-time checks.
729}