blob: a6a62a9e3775fd90c8bcfb5251d4b5ead3fff0e5 [file] [log] [blame]
Chris Lattner4b009652007-07-25 00:24:17 +00001//===--- SemaExprCXX.cpp - Semantic Analysis for Expressions --------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner959e5be2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner4b009652007-07-25 00:24:17 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for C++ expressions.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
15#include "clang/AST/ExprCXX.h"
Steve Naroffac5d4f12007-08-25 14:02:58 +000016#include "clang/AST/ASTContext.h"
Argiris Kirtzidis810c0f72008-09-10 02:17:11 +000017#include "clang/Parse/DeclSpec.h"
Argiris Kirtzidiscf4e8f82008-10-06 23:16:35 +000018#include "clang/Lex/Preprocessor.h"
Daniel Dunbar8d03cbe2008-08-11 03:27:53 +000019#include "clang/Basic/Diagnostic.h"
Chris Lattner4b009652007-07-25 00:24:17 +000020using namespace clang;
21
Steve Naroff5cbb02f2007-09-16 14:56:35 +000022/// ActOnCXXBoolLiteral - Parse {true,false} literals.
Chris Lattner4b009652007-07-25 00:24:17 +000023Action::ExprResult
Steve Naroff5cbb02f2007-09-16 14:56:35 +000024Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
Douglas Gregorf8e92702008-10-24 15:36:09 +000025 assert((Kind == tok::kw_true || Kind == tok::kw_false) &&
Chris Lattner4b009652007-07-25 00:24:17 +000026 "Unknown C++ Boolean value!");
Steve Naroffac5d4f12007-08-25 14:02:58 +000027 return new CXXBoolLiteralExpr(Kind == tok::kw_true, Context.BoolTy, OpLoc);
Chris Lattner4b009652007-07-25 00:24:17 +000028}
Chris Lattnera7447ba2008-02-26 00:51:44 +000029
30/// ActOnCXXThrow - Parse throw expressions.
31Action::ExprResult
32Sema::ActOnCXXThrow(SourceLocation OpLoc, ExprTy *E) {
33 return new CXXThrowExpr((Expr*)E, Context.VoidTy, OpLoc);
34}
Argiris Kirtzidis38f16712008-07-01 10:37:29 +000035
36Action::ExprResult Sema::ActOnCXXThis(SourceLocation ThisLoc) {
37 /// C++ 9.3.2: In the body of a non-static member function, the keyword this
38 /// is a non-lvalue expression whose value is the address of the object for
39 /// which the function is called.
40
41 if (!isa<FunctionDecl>(CurContext)) {
42 Diag(ThisLoc, diag::err_invalid_this_use);
43 return ExprResult(true);
44 }
45
46 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext))
47 if (MD->isInstance())
Douglas Gregora5b022a2008-11-04 14:32:21 +000048 return new CXXThisExpr(ThisLoc, MD->getThisType(Context));
Argiris Kirtzidis38f16712008-07-01 10:37:29 +000049
50 return Diag(ThisLoc, diag::err_invalid_this_use);
51}
Argiris Kirtzidis7a1e7412008-08-22 15:38:55 +000052
53/// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
54/// Can be interpreted either as function-style casting ("int(x)")
55/// or class type construction ("ClassType(x,y,z)")
56/// or creation of a value-initialized type ("int()").
57Action::ExprResult
58Sema::ActOnCXXTypeConstructExpr(SourceRange TypeRange, TypeTy *TypeRep,
59 SourceLocation LParenLoc,
60 ExprTy **ExprTys, unsigned NumExprs,
61 SourceLocation *CommaLocs,
62 SourceLocation RParenLoc) {
63 assert(TypeRep && "Missing type!");
64 QualType Ty = QualType::getFromOpaquePtr(TypeRep);
65 Expr **Exprs = (Expr**)ExprTys;
66 SourceLocation TyBeginLoc = TypeRange.getBegin();
67 SourceRange FullRange = SourceRange(TyBeginLoc, RParenLoc);
68
69 if (const RecordType *RT = Ty->getAsRecordType()) {
70 // C++ 5.2.3p1:
71 // If the simple-type-specifier specifies a class type, the class type shall
72 // be complete.
73 //
74 if (!RT->getDecl()->isDefinition())
75 return Diag(TyBeginLoc, diag::err_invalid_incomplete_type_use,
76 Ty.getAsString(), FullRange);
77
Argiris Kirtzidiscf4e8f82008-10-06 23:16:35 +000078 unsigned DiagID = PP.getDiagnostics().getCustomDiagID(Diagnostic::Error,
79 "class constructors are not supported yet");
80 return Diag(TyBeginLoc, DiagID);
Argiris Kirtzidis7a1e7412008-08-22 15:38:55 +000081 }
82
83 // C++ 5.2.3p1:
84 // If the expression list is a single expression, the type conversion
85 // expression is equivalent (in definedness, and if defined in meaning) to the
86 // corresponding cast expression.
87 //
88 if (NumExprs == 1) {
89 if (CheckCastTypes(TypeRange, Ty, Exprs[0]))
90 return true;
Douglas Gregor21a04f32008-10-27 19:41:14 +000091 return new CXXFunctionalCastExpr(Ty.getNonReferenceType(), Ty, TyBeginLoc,
92 Exprs[0], RParenLoc);
Argiris Kirtzidis7a1e7412008-08-22 15:38:55 +000093 }
94
95 // C++ 5.2.3p1:
96 // If the expression list specifies more than a single value, the type shall
97 // be a class with a suitably declared constructor.
98 //
99 if (NumExprs > 1)
100 return Diag(CommaLocs[0], diag::err_builtin_func_cast_more_than_one_arg,
101 FullRange);
102
103 assert(NumExprs == 0 && "Expected 0 expressions");
104
105 // C++ 5.2.3p2:
106 // The expression T(), where T is a simple-type-specifier for a non-array
107 // complete object type or the (possibly cv-qualified) void type, creates an
108 // rvalue of the specified type, which is value-initialized.
109 //
110 if (Ty->isArrayType())
111 return Diag(TyBeginLoc, diag::err_value_init_for_array_type, FullRange);
112 if (Ty->isIncompleteType() && !Ty->isVoidType())
113 return Diag(TyBeginLoc, diag::err_invalid_incomplete_type_use,
114 Ty.getAsString(), FullRange);
115
116 return new CXXZeroInitValueExpr(Ty, TyBeginLoc, RParenLoc);
117}
Argiris Kirtzidis810c0f72008-09-10 02:17:11 +0000118
119
120/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
121/// C++ if/switch/while/for statement.
122/// e.g: "if (int x = f()) {...}"
123Action::ExprResult
124Sema::ActOnCXXConditionDeclarationExpr(Scope *S, SourceLocation StartLoc,
125 Declarator &D,
126 SourceLocation EqualLoc,
127 ExprTy *AssignExprVal) {
128 assert(AssignExprVal && "Null assignment expression");
129
130 // C++ 6.4p2:
131 // The declarator shall not specify a function or an array.
132 // The type-specifier-seq shall not contain typedef and shall not declare a
133 // new class or enumeration.
134
135 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
136 "Parser allowed 'typedef' as storage class of condition decl.");
137
138 QualType Ty = GetTypeForDeclarator(D, S);
139
140 if (Ty->isFunctionType()) { // The declarator shall not specify a function...
141 // We exit without creating a CXXConditionDeclExpr because a FunctionDecl
142 // would be created and CXXConditionDeclExpr wants a VarDecl.
143 return Diag(StartLoc, diag::err_invalid_use_of_function_type,
144 SourceRange(StartLoc, EqualLoc));
145 } else if (Ty->isArrayType()) { // ...or an array.
146 Diag(StartLoc, diag::err_invalid_use_of_array_type,
147 SourceRange(StartLoc, EqualLoc));
148 } else if (const RecordType *RT = Ty->getAsRecordType()) {
149 RecordDecl *RD = RT->getDecl();
150 // The type-specifier-seq shall not declare a new class...
151 if (RD->isDefinition() && (RD->getIdentifier() == 0 || S->isDeclScope(RD)))
152 Diag(RD->getLocation(), diag::err_type_defined_in_condition);
153 } else if (const EnumType *ET = Ty->getAsEnumType()) {
154 EnumDecl *ED = ET->getDecl();
155 // ...or enumeration.
156 if (ED->isDefinition() && (ED->getIdentifier() == 0 || S->isDeclScope(ED)))
157 Diag(ED->getLocation(), diag::err_type_defined_in_condition);
158 }
159
160 DeclTy *Dcl = ActOnDeclarator(S, D, 0);
161 if (!Dcl)
162 return true;
163 AddInitializerToDecl(Dcl, AssignExprVal);
164
165 return new CXXConditionDeclExpr(StartLoc, EqualLoc,
166 cast<VarDecl>(static_cast<Decl *>(Dcl)));
167}
168
169/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
170bool Sema::CheckCXXBooleanCondition(Expr *&CondExpr) {
171 // C++ 6.4p4:
172 // The value of a condition that is an initialized declaration in a statement
173 // other than a switch statement is the value of the declared variable
174 // implicitly converted to type bool. If that conversion is ill-formed, the
175 // program is ill-formed.
176 // The value of a condition that is an expression is the value of the
177 // expression, implicitly converted to bool.
178 //
179 QualType Ty = CondExpr->getType(); // Save the type.
180 AssignConvertType
181 ConvTy = CheckSingleAssignmentConstraints(Context.BoolTy, CondExpr);
182 if (ConvTy == Incompatible)
183 return Diag(CondExpr->getLocStart(), diag::err_typecheck_bool_condition,
184 Ty.getAsString(), CondExpr->getSourceRange());
185 return false;
186}
Douglas Gregor1815b3b2008-09-12 00:47:35 +0000187
188/// Helper function to determine whether this is the (deprecated) C++
189/// conversion from a string literal to a pointer to non-const char or
190/// non-const wchar_t (for narrow and wide string literals,
191/// respectively).
192bool
193Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
194 // Look inside the implicit cast, if it exists.
195 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
196 From = Cast->getSubExpr();
197
198 // A string literal (2.13.4) that is not a wide string literal can
199 // be converted to an rvalue of type "pointer to char"; a wide
200 // string literal can be converted to an rvalue of type "pointer
201 // to wchar_t" (C++ 4.2p2).
202 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From))
203 if (const PointerType *ToPtrType = ToType->getAsPointerType())
204 if (const BuiltinType *ToPointeeType
205 = ToPtrType->getPointeeType()->getAsBuiltinType()) {
206 // This conversion is considered only when there is an
207 // explicit appropriate pointer target type (C++ 4.2p2).
208 if (ToPtrType->getPointeeType().getCVRQualifiers() == 0 &&
209 ((StrLit->isWide() && ToPointeeType->isWideCharType()) ||
210 (!StrLit->isWide() &&
211 (ToPointeeType->getKind() == BuiltinType::Char_U ||
212 ToPointeeType->getKind() == BuiltinType::Char_S))))
213 return true;
214 }
215
216 return false;
217}
Douglas Gregorbb461502008-10-24 04:54:22 +0000218
219/// PerformImplicitConversion - Perform an implicit conversion of the
220/// expression From to the type ToType. Returns true if there was an
221/// error, false otherwise. The expression From is replaced with the
222/// converted expression.
223bool
224Sema::PerformImplicitConversion(Expr *&From, QualType ToType)
225{
Douglas Gregor81c29152008-10-29 00:13:59 +0000226 ImplicitConversionSequence ICS = TryImplicitConversion(From, ToType);
Douglas Gregorbb461502008-10-24 04:54:22 +0000227 switch (ICS.ConversionKind) {
228 case ImplicitConversionSequence::StandardConversion:
229 if (PerformImplicitConversion(From, ToType, ICS.Standard))
230 return true;
231 break;
232
233 case ImplicitConversionSequence::UserDefinedConversion:
234 // FIXME: This is, of course, wrong. We'll need to actually call
235 // the constructor or conversion operator, and then cope with the
236 // standard conversions.
237 ImpCastExprToType(From, ToType);
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000238 return false;
Douglas Gregorbb461502008-10-24 04:54:22 +0000239
240 case ImplicitConversionSequence::EllipsisConversion:
241 assert(false && "Cannot perform an ellipsis conversion");
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000242 return false;
Douglas Gregorbb461502008-10-24 04:54:22 +0000243
244 case ImplicitConversionSequence::BadConversion:
245 return true;
246 }
247
248 // Everything went well.
249 return false;
250}
251
252/// PerformImplicitConversion - Perform an implicit conversion of the
253/// expression From to the type ToType by following the standard
254/// conversion sequence SCS. Returns true if there was an error, false
255/// otherwise. The expression From is replaced with the converted
256/// expression.
257bool
258Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
259 const StandardConversionSequence& SCS)
260{
261 // Overall FIXME: we are recomputing too many types here and doing
262 // far too much extra work. What this means is that we need to keep
263 // track of more information that is computed when we try the
264 // implicit conversion initially, so that we don't need to recompute
265 // anything here.
266 QualType FromType = From->getType();
267
Douglas Gregora3b34bb2008-11-03 19:09:14 +0000268 if (SCS.CopyConstructor) {
269 // FIXME: Create a temporary object by calling the copy
270 // constructor.
271 ImpCastExprToType(From, ToType);
272 return false;
273 }
274
Douglas Gregorbb461502008-10-24 04:54:22 +0000275 // Perform the first implicit conversion.
276 switch (SCS.First) {
277 case ICK_Identity:
278 case ICK_Lvalue_To_Rvalue:
279 // Nothing to do.
280 break;
281
282 case ICK_Array_To_Pointer:
Douglas Gregor45014fd2008-11-10 20:40:00 +0000283 if (FromType->isOverloadType()) {
284 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType, true);
285 if (!Fn)
286 return true;
287
288 FixOverloadedFunctionReference(From, Fn);
289 FromType = From->getType();
290 } else {
291 FromType = Context.getArrayDecayedType(FromType);
292 }
Douglas Gregorbb461502008-10-24 04:54:22 +0000293 ImpCastExprToType(From, FromType);
294 break;
295
296 case ICK_Function_To_Pointer:
297 FromType = Context.getPointerType(FromType);
298 ImpCastExprToType(From, FromType);
299 break;
300
301 default:
302 assert(false && "Improper first standard conversion");
303 break;
304 }
305
306 // Perform the second implicit conversion
307 switch (SCS.Second) {
308 case ICK_Identity:
309 // Nothing to do.
310 break;
311
312 case ICK_Integral_Promotion:
313 case ICK_Floating_Promotion:
314 case ICK_Integral_Conversion:
315 case ICK_Floating_Conversion:
316 case ICK_Floating_Integral:
317 FromType = ToType.getUnqualifiedType();
318 ImpCastExprToType(From, FromType);
319 break;
320
321 case ICK_Pointer_Conversion:
322 if (CheckPointerConversion(From, ToType))
323 return true;
324 ImpCastExprToType(From, ToType);
325 break;
326
327 case ICK_Pointer_Member:
328 // FIXME: Implement pointer-to-member conversions.
329 assert(false && "Pointer-to-member conversions are unsupported");
330 break;
331
332 case ICK_Boolean_Conversion:
333 FromType = Context.BoolTy;
334 ImpCastExprToType(From, FromType);
335 break;
336
337 default:
338 assert(false && "Improper second standard conversion");
339 break;
340 }
341
342 switch (SCS.Third) {
343 case ICK_Identity:
344 // Nothing to do.
345 break;
346
347 case ICK_Qualification:
348 ImpCastExprToType(From, ToType);
349 break;
350
351 default:
352 assert(false && "Improper second standard conversion");
353 break;
354 }
355
356 return false;
357}
358