blob: 80bd8eeef37518cde8a69e1b9da7af925e1fc238 [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
Douglas Gregor487a75a2008-11-19 19:09:45 +000022/// ActOnCXXConversionFunctionExpr - Parse a C++ conversion function
Douglas Gregor2def4832008-11-17 20:34:05 +000023/// name (e.g., operator void const *) as an expression. This is
24/// very similar to ActOnIdentifierExpr, except that instead of
25/// providing an identifier the parser provides the type of the
26/// conversion function.
Douglas Gregor487a75a2008-11-19 19:09:45 +000027Sema::ExprResult
28Sema::ActOnCXXConversionFunctionExpr(Scope *S, SourceLocation OperatorLoc,
29 TypeTy *Ty, bool HasTrailingLParen,
30 const CXXScopeSpec &SS) {
Douglas Gregor2def4832008-11-17 20:34:05 +000031 QualType ConvType = QualType::getFromOpaquePtr(Ty);
32 QualType ConvTypeCanon = Context.getCanonicalType(ConvType);
33 DeclarationName ConvName
34 = Context.DeclarationNames.getCXXConversionFunctionName(ConvTypeCanon);
Douglas Gregor10c42622008-11-18 15:03:34 +000035 return ActOnDeclarationNameExpr(S, OperatorLoc, ConvName, HasTrailingLParen,
Douglas Gregor487a75a2008-11-19 19:09:45 +000036 &SS);
Douglas Gregor2def4832008-11-17 20:34:05 +000037}
Sebastian Redlc42e1182008-11-11 11:37:55 +000038
Douglas Gregor487a75a2008-11-19 19:09:45 +000039/// ActOnCXXOperatorFunctionIdExpr - Parse a C++ overloaded operator
Douglas Gregore94ca9e42008-11-18 14:39:36 +000040/// name (e.g., @c operator+ ) as an expression. This is very
41/// similar to ActOnIdentifierExpr, except that instead of providing
42/// an identifier the parser provides the kind of overloaded
43/// operator that was parsed.
Douglas Gregor487a75a2008-11-19 19:09:45 +000044Sema::ExprResult
45Sema::ActOnCXXOperatorFunctionIdExpr(Scope *S, SourceLocation OperatorLoc,
46 OverloadedOperatorKind Op,
47 bool HasTrailingLParen,
48 const CXXScopeSpec &SS) {
Douglas Gregore94ca9e42008-11-18 14:39:36 +000049 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(Op);
Douglas Gregor487a75a2008-11-19 19:09:45 +000050 return ActOnDeclarationNameExpr(S, OperatorLoc, Name, HasTrailingLParen, &SS);
Douglas Gregore94ca9e42008-11-18 14:39:36 +000051}
52
Sebastian Redlc42e1182008-11-11 11:37:55 +000053/// ActOnCXXTypeidOfType - Parse typeid( type-id ).
54Action::ExprResult
55Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc,
56 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
57 const NamespaceDecl *StdNs = GetStdNamespace();
Chris Lattner572af492008-11-20 05:51:55 +000058 if (!StdNs)
59 return Diag(OpLoc, diag::err_need_header_before_typeid);
60
61 IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info");
62 Decl *TypeInfoDecl = LookupDecl(TypeInfoII,
Sebastian Redlc42e1182008-11-11 11:37:55 +000063 Decl::IDNS_Tag | Decl::IDNS_Ordinary,
64 0, StdNs, /*createBuiltins=*/false);
65 RecordDecl *TypeInfoRecordDecl = dyn_cast_or_null<RecordDecl>(TypeInfoDecl);
Chris Lattner572af492008-11-20 05:51:55 +000066 if (!TypeInfoRecordDecl)
67 return Diag(OpLoc, diag::err_need_header_before_typeid);
Sebastian Redlc42e1182008-11-11 11:37:55 +000068
69 QualType TypeInfoType = Context.getTypeDeclType(TypeInfoRecordDecl);
70
71 return new CXXTypeidExpr(isType, TyOrExpr, TypeInfoType.withConst(),
72 SourceRange(OpLoc, RParenLoc));
73}
74
Steve Naroff1b273c42007-09-16 14:56:35 +000075/// ActOnCXXBoolLiteral - Parse {true,false} literals.
Reid Spencer5f016e22007-07-11 17:01:13 +000076Action::ExprResult
Steve Naroff1b273c42007-09-16 14:56:35 +000077Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
Douglas Gregor2f639b92008-10-24 15:36:09 +000078 assert((Kind == tok::kw_true || Kind == tok::kw_false) &&
Reid Spencer5f016e22007-07-11 17:01:13 +000079 "Unknown C++ Boolean value!");
Steve Naroff210679c2007-08-25 14:02:58 +000080 return new CXXBoolLiteralExpr(Kind == tok::kw_true, Context.BoolTy, OpLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +000081}
Chris Lattner50dd2892008-02-26 00:51:44 +000082
83/// ActOnCXXThrow - Parse throw expressions.
84Action::ExprResult
85Sema::ActOnCXXThrow(SourceLocation OpLoc, ExprTy *E) {
86 return new CXXThrowExpr((Expr*)E, Context.VoidTy, OpLoc);
87}
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +000088
89Action::ExprResult Sema::ActOnCXXThis(SourceLocation ThisLoc) {
90 /// C++ 9.3.2: In the body of a non-static member function, the keyword this
91 /// is a non-lvalue expression whose value is the address of the object for
92 /// which the function is called.
93
94 if (!isa<FunctionDecl>(CurContext)) {
95 Diag(ThisLoc, diag::err_invalid_this_use);
96 return ExprResult(true);
97 }
98
99 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext))
100 if (MD->isInstance())
Douglas Gregor796da182008-11-04 14:32:21 +0000101 return new CXXThisExpr(ThisLoc, MD->getThisType(Context));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000102
103 return Diag(ThisLoc, diag::err_invalid_this_use);
104}
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000105
106/// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
107/// Can be interpreted either as function-style casting ("int(x)")
108/// or class type construction ("ClassType(x,y,z)")
109/// or creation of a value-initialized type ("int()").
110Action::ExprResult
111Sema::ActOnCXXTypeConstructExpr(SourceRange TypeRange, TypeTy *TypeRep,
112 SourceLocation LParenLoc,
113 ExprTy **ExprTys, unsigned NumExprs,
114 SourceLocation *CommaLocs,
115 SourceLocation RParenLoc) {
116 assert(TypeRep && "Missing type!");
117 QualType Ty = QualType::getFromOpaquePtr(TypeRep);
118 Expr **Exprs = (Expr**)ExprTys;
119 SourceLocation TyBeginLoc = TypeRange.getBegin();
120 SourceRange FullRange = SourceRange(TyBeginLoc, RParenLoc);
121
122 if (const RecordType *RT = Ty->getAsRecordType()) {
123 // C++ 5.2.3p1:
124 // If the simple-type-specifier specifies a class type, the class type shall
125 // be complete.
126 //
127 if (!RT->getDecl()->isDefinition())
128 return Diag(TyBeginLoc, diag::err_invalid_incomplete_type_use,
129 Ty.getAsString(), FullRange);
130
Argyrios Kyrtzidis4021a842008-10-06 23:16:35 +0000131 unsigned DiagID = PP.getDiagnostics().getCustomDiagID(Diagnostic::Error,
132 "class constructors are not supported yet");
133 return Diag(TyBeginLoc, DiagID);
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000134 }
135
136 // C++ 5.2.3p1:
137 // If the expression list is a single expression, the type conversion
138 // expression is equivalent (in definedness, and if defined in meaning) to the
139 // corresponding cast expression.
140 //
141 if (NumExprs == 1) {
142 if (CheckCastTypes(TypeRange, Ty, Exprs[0]))
143 return true;
Douglas Gregor49badde2008-10-27 19:41:14 +0000144 return new CXXFunctionalCastExpr(Ty.getNonReferenceType(), Ty, TyBeginLoc,
145 Exprs[0], RParenLoc);
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000146 }
147
148 // C++ 5.2.3p1:
149 // If the expression list specifies more than a single value, the type shall
150 // be a class with a suitably declared constructor.
151 //
152 if (NumExprs > 1)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000153 return Diag(CommaLocs[0], diag::err_builtin_func_cast_more_than_one_arg)
154 << FullRange;
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000155
156 assert(NumExprs == 0 && "Expected 0 expressions");
157
158 // C++ 5.2.3p2:
159 // The expression T(), where T is a simple-type-specifier for a non-array
160 // complete object type or the (possibly cv-qualified) void type, creates an
161 // rvalue of the specified type, which is value-initialized.
162 //
163 if (Ty->isArrayType())
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000164 return Diag(TyBeginLoc, diag::err_value_init_for_array_type) << FullRange;
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000165 if (Ty->isIncompleteType() && !Ty->isVoidType())
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000166 return Diag(TyBeginLoc, diag::err_invalid_incomplete_type_use)
167 << Ty.getAsString() << FullRange;
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000168
169 return new CXXZeroInitValueExpr(Ty, TyBeginLoc, RParenLoc);
170}
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000171
172
173/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
174/// C++ if/switch/while/for statement.
175/// e.g: "if (int x = f()) {...}"
176Action::ExprResult
177Sema::ActOnCXXConditionDeclarationExpr(Scope *S, SourceLocation StartLoc,
178 Declarator &D,
179 SourceLocation EqualLoc,
180 ExprTy *AssignExprVal) {
181 assert(AssignExprVal && "Null assignment expression");
182
183 // C++ 6.4p2:
184 // The declarator shall not specify a function or an array.
185 // The type-specifier-seq shall not contain typedef and shall not declare a
186 // new class or enumeration.
187
188 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
189 "Parser allowed 'typedef' as storage class of condition decl.");
190
191 QualType Ty = GetTypeForDeclarator(D, S);
192
193 if (Ty->isFunctionType()) { // The declarator shall not specify a function...
194 // We exit without creating a CXXConditionDeclExpr because a FunctionDecl
195 // would be created and CXXConditionDeclExpr wants a VarDecl.
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000196 return Diag(StartLoc, diag::err_invalid_use_of_function_type)
197 << SourceRange(StartLoc, EqualLoc);
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000198 } else if (Ty->isArrayType()) { // ...or an array.
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000199 Diag(StartLoc, diag::err_invalid_use_of_array_type)
200 << SourceRange(StartLoc, EqualLoc);
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000201 } else if (const RecordType *RT = Ty->getAsRecordType()) {
202 RecordDecl *RD = RT->getDecl();
203 // The type-specifier-seq shall not declare a new class...
204 if (RD->isDefinition() && (RD->getIdentifier() == 0 || S->isDeclScope(RD)))
205 Diag(RD->getLocation(), diag::err_type_defined_in_condition);
206 } else if (const EnumType *ET = Ty->getAsEnumType()) {
207 EnumDecl *ED = ET->getDecl();
208 // ...or enumeration.
209 if (ED->isDefinition() && (ED->getIdentifier() == 0 || S->isDeclScope(ED)))
210 Diag(ED->getLocation(), diag::err_type_defined_in_condition);
211 }
212
213 DeclTy *Dcl = ActOnDeclarator(S, D, 0);
214 if (!Dcl)
215 return true;
216 AddInitializerToDecl(Dcl, AssignExprVal);
217
218 return new CXXConditionDeclExpr(StartLoc, EqualLoc,
219 cast<VarDecl>(static_cast<Decl *>(Dcl)));
220}
221
222/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
223bool Sema::CheckCXXBooleanCondition(Expr *&CondExpr) {
224 // C++ 6.4p4:
225 // The value of a condition that is an initialized declaration in a statement
226 // other than a switch statement is the value of the declared variable
227 // implicitly converted to type bool. If that conversion is ill-formed, the
228 // program is ill-formed.
229 // The value of a condition that is an expression is the value of the
230 // expression, implicitly converted to bool.
231 //
232 QualType Ty = CondExpr->getType(); // Save the type.
233 AssignConvertType
234 ConvTy = CheckSingleAssignmentConstraints(Context.BoolTy, CondExpr);
235 if (ConvTy == Incompatible)
236 return Diag(CondExpr->getLocStart(), diag::err_typecheck_bool_condition,
237 Ty.getAsString(), CondExpr->getSourceRange());
238 return false;
239}
Douglas Gregor77a52232008-09-12 00:47:35 +0000240
241/// Helper function to determine whether this is the (deprecated) C++
242/// conversion from a string literal to a pointer to non-const char or
243/// non-const wchar_t (for narrow and wide string literals,
244/// respectively).
245bool
246Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
247 // Look inside the implicit cast, if it exists.
248 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
249 From = Cast->getSubExpr();
250
251 // A string literal (2.13.4) that is not a wide string literal can
252 // be converted to an rvalue of type "pointer to char"; a wide
253 // string literal can be converted to an rvalue of type "pointer
254 // to wchar_t" (C++ 4.2p2).
255 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From))
256 if (const PointerType *ToPtrType = ToType->getAsPointerType())
257 if (const BuiltinType *ToPointeeType
258 = ToPtrType->getPointeeType()->getAsBuiltinType()) {
259 // This conversion is considered only when there is an
260 // explicit appropriate pointer target type (C++ 4.2p2).
261 if (ToPtrType->getPointeeType().getCVRQualifiers() == 0 &&
262 ((StrLit->isWide() && ToPointeeType->isWideCharType()) ||
263 (!StrLit->isWide() &&
264 (ToPointeeType->getKind() == BuiltinType::Char_U ||
265 ToPointeeType->getKind() == BuiltinType::Char_S))))
266 return true;
267 }
268
269 return false;
270}
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000271
272/// PerformImplicitConversion - Perform an implicit conversion of the
273/// expression From to the type ToType. Returns true if there was an
274/// error, false otherwise. The expression From is replaced with the
275/// converted expression.
276bool
277Sema::PerformImplicitConversion(Expr *&From, QualType ToType)
278{
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000279 ImplicitConversionSequence ICS = TryImplicitConversion(From, ToType);
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000280 switch (ICS.ConversionKind) {
281 case ImplicitConversionSequence::StandardConversion:
282 if (PerformImplicitConversion(From, ToType, ICS.Standard))
283 return true;
284 break;
285
286 case ImplicitConversionSequence::UserDefinedConversion:
287 // FIXME: This is, of course, wrong. We'll need to actually call
288 // the constructor or conversion operator, and then cope with the
289 // standard conversions.
290 ImpCastExprToType(From, ToType);
Douglas Gregor60d62c22008-10-31 16:23:19 +0000291 return false;
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000292
293 case ImplicitConversionSequence::EllipsisConversion:
294 assert(false && "Cannot perform an ellipsis conversion");
Douglas Gregor60d62c22008-10-31 16:23:19 +0000295 return false;
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000296
297 case ImplicitConversionSequence::BadConversion:
298 return true;
299 }
300
301 // Everything went well.
302 return false;
303}
304
305/// PerformImplicitConversion - Perform an implicit conversion of the
306/// expression From to the type ToType by following the standard
307/// conversion sequence SCS. Returns true if there was an error, false
308/// otherwise. The expression From is replaced with the converted
309/// expression.
310bool
311Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
312 const StandardConversionSequence& SCS)
313{
314 // Overall FIXME: we are recomputing too many types here and doing
315 // far too much extra work. What this means is that we need to keep
316 // track of more information that is computed when we try the
317 // implicit conversion initially, so that we don't need to recompute
318 // anything here.
319 QualType FromType = From->getType();
320
Douglas Gregor225c41e2008-11-03 19:09:14 +0000321 if (SCS.CopyConstructor) {
322 // FIXME: Create a temporary object by calling the copy
323 // constructor.
324 ImpCastExprToType(From, ToType);
325 return false;
326 }
327
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000328 // Perform the first implicit conversion.
329 switch (SCS.First) {
330 case ICK_Identity:
331 case ICK_Lvalue_To_Rvalue:
332 // Nothing to do.
333 break;
334
335 case ICK_Array_To_Pointer:
Douglas Gregor904eed32008-11-10 20:40:00 +0000336 if (FromType->isOverloadType()) {
337 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType, true);
338 if (!Fn)
339 return true;
340
341 FixOverloadedFunctionReference(From, Fn);
342 FromType = From->getType();
343 } else {
344 FromType = Context.getArrayDecayedType(FromType);
345 }
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000346 ImpCastExprToType(From, FromType);
347 break;
348
349 case ICK_Function_To_Pointer:
350 FromType = Context.getPointerType(FromType);
351 ImpCastExprToType(From, FromType);
352 break;
353
354 default:
355 assert(false && "Improper first standard conversion");
356 break;
357 }
358
359 // Perform the second implicit conversion
360 switch (SCS.Second) {
361 case ICK_Identity:
362 // Nothing to do.
363 break;
364
365 case ICK_Integral_Promotion:
366 case ICK_Floating_Promotion:
367 case ICK_Integral_Conversion:
368 case ICK_Floating_Conversion:
369 case ICK_Floating_Integral:
370 FromType = ToType.getUnqualifiedType();
371 ImpCastExprToType(From, FromType);
372 break;
373
374 case ICK_Pointer_Conversion:
375 if (CheckPointerConversion(From, ToType))
376 return true;
377 ImpCastExprToType(From, ToType);
378 break;
379
380 case ICK_Pointer_Member:
381 // FIXME: Implement pointer-to-member conversions.
382 assert(false && "Pointer-to-member conversions are unsupported");
383 break;
384
385 case ICK_Boolean_Conversion:
386 FromType = Context.BoolTy;
387 ImpCastExprToType(From, FromType);
388 break;
389
390 default:
391 assert(false && "Improper second standard conversion");
392 break;
393 }
394
395 switch (SCS.Third) {
396 case ICK_Identity:
397 // Nothing to do.
398 break;
399
400 case ICK_Qualification:
401 ImpCastExprToType(From, ToType);
402 break;
403
404 default:
405 assert(false && "Improper second standard conversion");
406 break;
407 }
408
409 return false;
410}
411