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