blob: e420ce59916769868805232b49bdc50c4ee66a56 [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- SemaExprCXX.cpp - Semantic Analysis for Expressions --------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +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 Naroff210679c2007-08-25 14:02:58 +000016#include "clang/AST/ASTContext.h"
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +000017#include "clang/Parse/DeclSpec.h"
Argyrios Kyrtzidis4021a842008-10-06 23:16:35 +000018#include "clang/Lex/Preprocessor.h"
Daniel Dunbar12bc6922008-08-11 03:27:53 +000019#include "clang/Basic/Diagnostic.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000020using namespace clang;
21
Sebastian Redlc42e1182008-11-11 11:37:55 +000022
23/// ActOnCXXTypeidOfType - Parse typeid( type-id ).
24Action::ExprResult
25Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc,
26 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
27 const NamespaceDecl *StdNs = GetStdNamespace();
28 if (!StdNs) {
29 Diag(OpLoc, diag::err_need_header_before_typeid);
30 return ExprResult(true);
31 }
32 if (!Ident_TypeInfo) {
33 Ident_TypeInfo = &PP.getIdentifierTable().get("type_info");
34 }
35 Decl *TypeInfoDecl = LookupDecl(Ident_TypeInfo,
36 Decl::IDNS_Tag | Decl::IDNS_Ordinary,
37 0, StdNs, /*createBuiltins=*/false);
38 RecordDecl *TypeInfoRecordDecl = dyn_cast_or_null<RecordDecl>(TypeInfoDecl);
39 if (!TypeInfoRecordDecl) {
40 Diag(OpLoc, diag::err_need_header_before_typeid);
41 return ExprResult(true);
42 }
43
44 QualType TypeInfoType = Context.getTypeDeclType(TypeInfoRecordDecl);
45
46 return new CXXTypeidExpr(isType, TyOrExpr, TypeInfoType.withConst(),
47 SourceRange(OpLoc, RParenLoc));
48}
49
Steve Naroff1b273c42007-09-16 14:56:35 +000050/// ActOnCXXBoolLiteral - Parse {true,false} literals.
Reid Spencer5f016e22007-07-11 17:01:13 +000051Action::ExprResult
Steve Naroff1b273c42007-09-16 14:56:35 +000052Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
Douglas Gregor2f639b92008-10-24 15:36:09 +000053 assert((Kind == tok::kw_true || Kind == tok::kw_false) &&
Reid Spencer5f016e22007-07-11 17:01:13 +000054 "Unknown C++ Boolean value!");
Steve Naroff210679c2007-08-25 14:02:58 +000055 return new CXXBoolLiteralExpr(Kind == tok::kw_true, Context.BoolTy, OpLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +000056}
Chris Lattner50dd2892008-02-26 00:51:44 +000057
58/// ActOnCXXThrow - Parse throw expressions.
59Action::ExprResult
60Sema::ActOnCXXThrow(SourceLocation OpLoc, ExprTy *E) {
61 return new CXXThrowExpr((Expr*)E, Context.VoidTy, OpLoc);
62}
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +000063
64Action::ExprResult Sema::ActOnCXXThis(SourceLocation ThisLoc) {
65 /// C++ 9.3.2: In the body of a non-static member function, the keyword this
66 /// is a non-lvalue expression whose value is the address of the object for
67 /// which the function is called.
68
69 if (!isa<FunctionDecl>(CurContext)) {
70 Diag(ThisLoc, diag::err_invalid_this_use);
71 return ExprResult(true);
72 }
73
74 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext))
75 if (MD->isInstance())
Douglas Gregor796da182008-11-04 14:32:21 +000076 return new CXXThisExpr(ThisLoc, MD->getThisType(Context));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +000077
78 return Diag(ThisLoc, diag::err_invalid_this_use);
79}
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +000080
81/// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
82/// Can be interpreted either as function-style casting ("int(x)")
83/// or class type construction ("ClassType(x,y,z)")
84/// or creation of a value-initialized type ("int()").
85Action::ExprResult
86Sema::ActOnCXXTypeConstructExpr(SourceRange TypeRange, TypeTy *TypeRep,
87 SourceLocation LParenLoc,
88 ExprTy **ExprTys, unsigned NumExprs,
89 SourceLocation *CommaLocs,
90 SourceLocation RParenLoc) {
91 assert(TypeRep && "Missing type!");
92 QualType Ty = QualType::getFromOpaquePtr(TypeRep);
93 Expr **Exprs = (Expr**)ExprTys;
94 SourceLocation TyBeginLoc = TypeRange.getBegin();
95 SourceRange FullRange = SourceRange(TyBeginLoc, RParenLoc);
96
97 if (const RecordType *RT = Ty->getAsRecordType()) {
98 // C++ 5.2.3p1:
99 // If the simple-type-specifier specifies a class type, the class type shall
100 // be complete.
101 //
102 if (!RT->getDecl()->isDefinition())
103 return Diag(TyBeginLoc, diag::err_invalid_incomplete_type_use,
104 Ty.getAsString(), FullRange);
105
Argyrios Kyrtzidis4021a842008-10-06 23:16:35 +0000106 unsigned DiagID = PP.getDiagnostics().getCustomDiagID(Diagnostic::Error,
107 "class constructors are not supported yet");
108 return Diag(TyBeginLoc, DiagID);
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000109 }
110
111 // C++ 5.2.3p1:
112 // If the expression list is a single expression, the type conversion
113 // expression is equivalent (in definedness, and if defined in meaning) to the
114 // corresponding cast expression.
115 //
116 if (NumExprs == 1) {
117 if (CheckCastTypes(TypeRange, Ty, Exprs[0]))
118 return true;
Douglas Gregor49badde2008-10-27 19:41:14 +0000119 return new CXXFunctionalCastExpr(Ty.getNonReferenceType(), Ty, TyBeginLoc,
120 Exprs[0], RParenLoc);
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000121 }
122
123 // C++ 5.2.3p1:
124 // If the expression list specifies more than a single value, the type shall
125 // be a class with a suitably declared constructor.
126 //
127 if (NumExprs > 1)
128 return Diag(CommaLocs[0], diag::err_builtin_func_cast_more_than_one_arg,
129 FullRange);
130
131 assert(NumExprs == 0 && "Expected 0 expressions");
132
133 // C++ 5.2.3p2:
134 // The expression T(), where T is a simple-type-specifier for a non-array
135 // complete object type or the (possibly cv-qualified) void type, creates an
136 // rvalue of the specified type, which is value-initialized.
137 //
138 if (Ty->isArrayType())
139 return Diag(TyBeginLoc, diag::err_value_init_for_array_type, FullRange);
140 if (Ty->isIncompleteType() && !Ty->isVoidType())
141 return Diag(TyBeginLoc, diag::err_invalid_incomplete_type_use,
142 Ty.getAsString(), FullRange);
143
144 return new CXXZeroInitValueExpr(Ty, TyBeginLoc, RParenLoc);
145}
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000146
147
148/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
149/// C++ if/switch/while/for statement.
150/// e.g: "if (int x = f()) {...}"
151Action::ExprResult
152Sema::ActOnCXXConditionDeclarationExpr(Scope *S, SourceLocation StartLoc,
153 Declarator &D,
154 SourceLocation EqualLoc,
155 ExprTy *AssignExprVal) {
156 assert(AssignExprVal && "Null assignment expression");
157
158 // C++ 6.4p2:
159 // The declarator shall not specify a function or an array.
160 // The type-specifier-seq shall not contain typedef and shall not declare a
161 // new class or enumeration.
162
163 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
164 "Parser allowed 'typedef' as storage class of condition decl.");
165
166 QualType Ty = GetTypeForDeclarator(D, S);
167
168 if (Ty->isFunctionType()) { // The declarator shall not specify a function...
169 // We exit without creating a CXXConditionDeclExpr because a FunctionDecl
170 // would be created and CXXConditionDeclExpr wants a VarDecl.
171 return Diag(StartLoc, diag::err_invalid_use_of_function_type,
172 SourceRange(StartLoc, EqualLoc));
173 } else if (Ty->isArrayType()) { // ...or an array.
174 Diag(StartLoc, diag::err_invalid_use_of_array_type,
175 SourceRange(StartLoc, EqualLoc));
176 } else if (const RecordType *RT = Ty->getAsRecordType()) {
177 RecordDecl *RD = RT->getDecl();
178 // The type-specifier-seq shall not declare a new class...
179 if (RD->isDefinition() && (RD->getIdentifier() == 0 || S->isDeclScope(RD)))
180 Diag(RD->getLocation(), diag::err_type_defined_in_condition);
181 } else if (const EnumType *ET = Ty->getAsEnumType()) {
182 EnumDecl *ED = ET->getDecl();
183 // ...or enumeration.
184 if (ED->isDefinition() && (ED->getIdentifier() == 0 || S->isDeclScope(ED)))
185 Diag(ED->getLocation(), diag::err_type_defined_in_condition);
186 }
187
188 DeclTy *Dcl = ActOnDeclarator(S, D, 0);
189 if (!Dcl)
190 return true;
191 AddInitializerToDecl(Dcl, AssignExprVal);
192
193 return new CXXConditionDeclExpr(StartLoc, EqualLoc,
194 cast<VarDecl>(static_cast<Decl *>(Dcl)));
195}
196
197/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
198bool Sema::CheckCXXBooleanCondition(Expr *&CondExpr) {
199 // C++ 6.4p4:
200 // The value of a condition that is an initialized declaration in a statement
201 // other than a switch statement is the value of the declared variable
202 // implicitly converted to type bool. If that conversion is ill-formed, the
203 // program is ill-formed.
204 // The value of a condition that is an expression is the value of the
205 // expression, implicitly converted to bool.
206 //
207 QualType Ty = CondExpr->getType(); // Save the type.
208 AssignConvertType
209 ConvTy = CheckSingleAssignmentConstraints(Context.BoolTy, CondExpr);
210 if (ConvTy == Incompatible)
211 return Diag(CondExpr->getLocStart(), diag::err_typecheck_bool_condition,
212 Ty.getAsString(), CondExpr->getSourceRange());
213 return false;
214}
Douglas Gregor77a52232008-09-12 00:47:35 +0000215
216/// Helper function to determine whether this is the (deprecated) C++
217/// conversion from a string literal to a pointer to non-const char or
218/// non-const wchar_t (for narrow and wide string literals,
219/// respectively).
220bool
221Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
222 // Look inside the implicit cast, if it exists.
223 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
224 From = Cast->getSubExpr();
225
226 // A string literal (2.13.4) that is not a wide string literal can
227 // be converted to an rvalue of type "pointer to char"; a wide
228 // string literal can be converted to an rvalue of type "pointer
229 // to wchar_t" (C++ 4.2p2).
230 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From))
231 if (const PointerType *ToPtrType = ToType->getAsPointerType())
232 if (const BuiltinType *ToPointeeType
233 = ToPtrType->getPointeeType()->getAsBuiltinType()) {
234 // This conversion is considered only when there is an
235 // explicit appropriate pointer target type (C++ 4.2p2).
236 if (ToPtrType->getPointeeType().getCVRQualifiers() == 0 &&
237 ((StrLit->isWide() && ToPointeeType->isWideCharType()) ||
238 (!StrLit->isWide() &&
239 (ToPointeeType->getKind() == BuiltinType::Char_U ||
240 ToPointeeType->getKind() == BuiltinType::Char_S))))
241 return true;
242 }
243
244 return false;
245}
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000246
247/// PerformImplicitConversion - Perform an implicit conversion of the
248/// expression From to the type ToType. Returns true if there was an
249/// error, false otherwise. The expression From is replaced with the
250/// converted expression.
251bool
252Sema::PerformImplicitConversion(Expr *&From, QualType ToType)
253{
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000254 ImplicitConversionSequence ICS = TryImplicitConversion(From, ToType);
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000255 switch (ICS.ConversionKind) {
256 case ImplicitConversionSequence::StandardConversion:
257 if (PerformImplicitConversion(From, ToType, ICS.Standard))
258 return true;
259 break;
260
261 case ImplicitConversionSequence::UserDefinedConversion:
262 // FIXME: This is, of course, wrong. We'll need to actually call
263 // the constructor or conversion operator, and then cope with the
264 // standard conversions.
265 ImpCastExprToType(From, ToType);
Douglas Gregor60d62c22008-10-31 16:23:19 +0000266 return false;
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000267
268 case ImplicitConversionSequence::EllipsisConversion:
269 assert(false && "Cannot perform an ellipsis conversion");
Douglas Gregor60d62c22008-10-31 16:23:19 +0000270 return false;
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000271
272 case ImplicitConversionSequence::BadConversion:
273 return true;
274 }
275
276 // Everything went well.
277 return false;
278}
279
280/// PerformImplicitConversion - Perform an implicit conversion of the
281/// expression From to the type ToType by following the standard
282/// conversion sequence SCS. Returns true if there was an error, false
283/// otherwise. The expression From is replaced with the converted
284/// expression.
285bool
286Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
287 const StandardConversionSequence& SCS)
288{
289 // Overall FIXME: we are recomputing too many types here and doing
290 // far too much extra work. What this means is that we need to keep
291 // track of more information that is computed when we try the
292 // implicit conversion initially, so that we don't need to recompute
293 // anything here.
294 QualType FromType = From->getType();
295
Douglas Gregor225c41e2008-11-03 19:09:14 +0000296 if (SCS.CopyConstructor) {
297 // FIXME: Create a temporary object by calling the copy
298 // constructor.
299 ImpCastExprToType(From, ToType);
300 return false;
301 }
302
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000303 // Perform the first implicit conversion.
304 switch (SCS.First) {
305 case ICK_Identity:
306 case ICK_Lvalue_To_Rvalue:
307 // Nothing to do.
308 break;
309
310 case ICK_Array_To_Pointer:
Douglas Gregor904eed32008-11-10 20:40:00 +0000311 if (FromType->isOverloadType()) {
312 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType, true);
313 if (!Fn)
314 return true;
315
316 FixOverloadedFunctionReference(From, Fn);
317 FromType = From->getType();
318 } else {
319 FromType = Context.getArrayDecayedType(FromType);
320 }
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000321 ImpCastExprToType(From, FromType);
322 break;
323
324 case ICK_Function_To_Pointer:
325 FromType = Context.getPointerType(FromType);
326 ImpCastExprToType(From, FromType);
327 break;
328
329 default:
330 assert(false && "Improper first standard conversion");
331 break;
332 }
333
334 // Perform the second implicit conversion
335 switch (SCS.Second) {
336 case ICK_Identity:
337 // Nothing to do.
338 break;
339
340 case ICK_Integral_Promotion:
341 case ICK_Floating_Promotion:
342 case ICK_Integral_Conversion:
343 case ICK_Floating_Conversion:
344 case ICK_Floating_Integral:
345 FromType = ToType.getUnqualifiedType();
346 ImpCastExprToType(From, FromType);
347 break;
348
349 case ICK_Pointer_Conversion:
350 if (CheckPointerConversion(From, ToType))
351 return true;
352 ImpCastExprToType(From, ToType);
353 break;
354
355 case ICK_Pointer_Member:
356 // FIXME: Implement pointer-to-member conversions.
357 assert(false && "Pointer-to-member conversions are unsupported");
358 break;
359
360 case ICK_Boolean_Conversion:
361 FromType = Context.BoolTy;
362 ImpCastExprToType(From, FromType);
363 break;
364
365 default:
366 assert(false && "Improper second standard conversion");
367 break;
368 }
369
370 switch (SCS.Third) {
371 case ICK_Identity:
372 // Nothing to do.
373 break;
374
375 case ICK_Qualification:
376 ImpCastExprToType(From, ToType);
377 break;
378
379 default:
380 assert(false && "Improper second standard conversion");
381 break;
382 }
383
384 return false;
385}
386