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