blob: f2c6c3b35b17a6052dbe4813febb94581e350a59 [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);
36
37 // We only expect to find a CXXConversionDecl.
38 Decl *D;
39 if (SS && !SS->isEmpty()) {
40 DeclContext *DC = static_cast<DeclContext*>(SS->getScopeRep());
41 if (DC == 0)
42 return true;
43 D = LookupDecl(ConvName, Decl::IDNS_Ordinary, S, DC);
44 } else
45 D = LookupDecl(ConvName, Decl::IDNS_Ordinary, S);
46
47 if (D == 0) {
48 // If there is no conversion function that converts to this type,
49 // diagnose the problem.
50 if (SS && !SS->isEmpty())
51 return Diag(OperatorLoc, diag::err_typecheck_no_member,
52 ConvType.getAsString(), SS->getRange());
53 else
54 return Diag(OperatorLoc, diag::err_no_conv_function,
55 ConvType.getAsString());
56 }
57
58 assert(isa<CXXConversionDecl>(D) && "we had to find a conversion function");
59 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(D);
60
61 // check if referencing a declaration with __attribute__((deprecated)).
62 if (Conversion->getAttr<DeprecatedAttr>())
63 Diag(OperatorLoc, diag::warn_deprecated, Conversion->getName());
64
65 // Only create DeclRefExpr's for valid Decl's.
66 if (Conversion->isInvalidDecl())
67 return true;
68
69 // Create a normal DeclRefExpr.
70 return new DeclRefExpr(Conversion, Conversion->getType(), OperatorLoc);
71}
Sebastian Redlb93b49c2008-11-11 11:37:55 +000072
Douglas Gregor96a32dd2008-11-18 14:39:36 +000073/// ActOnOperatorFunctionIdExpr - Parse a C++ overloaded operator
74/// name (e.g., @c operator+ ) as an expression. This is very
75/// similar to ActOnIdentifierExpr, except that instead of providing
76/// an identifier the parser provides the kind of overloaded
77/// operator that was parsed.
78Sema::ExprResult Sema::ActOnOperatorFunctionIdExpr(Scope *S,
79 SourceLocation OperatorLoc,
80 OverloadedOperatorKind Op,
81 bool HasTrailingLParen,
82 const CXXScopeSpec *SS) {
83 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(Op);
84
85 Decl *D;
86 if (SS && !SS->isEmpty()) {
87 DeclContext *DC = static_cast<DeclContext*>(SS->getScopeRep());
88 if (DC == 0)
89 return true;
90 D = LookupDecl(Name, Decl::IDNS_Ordinary, S, DC);
91 } else
92 D = LookupDecl(Name, Decl::IDNS_Ordinary, S);
93
94 if (D == 0) {
95 // If there is no conversion function that converts to this type,
96 // diagnose the problem.
97 if (SS && !SS->isEmpty())
98 return Diag(OperatorLoc, diag::err_typecheck_no_member,
99 Name.getAsString(), SS->getRange());
100 else
101 return Diag(OperatorLoc, diag::err_undeclared_var_use,
102 Name.getAsString());
103 }
104
105 ValueDecl *VD = cast<ValueDecl>(D);
106
107 // check if referencing a declaration with __attribute__((deprecated)).
108 if (VD->getAttr<DeprecatedAttr>())
109 Diag(OperatorLoc, diag::warn_deprecated, Name.getAsString());
110
111 // Only create DeclRefExpr's for valid Decl's.
112 if (VD->isInvalidDecl())
113 return true;
114
115 // Create a normal DeclRefExpr.
116 return new DeclRefExpr(VD, VD->getType(), OperatorLoc);
117}
118
Sebastian Redlb93b49c2008-11-11 11:37:55 +0000119/// ActOnCXXTypeidOfType - Parse typeid( type-id ).
120Action::ExprResult
121Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc,
122 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
123 const NamespaceDecl *StdNs = GetStdNamespace();
124 if (!StdNs) {
125 Diag(OpLoc, diag::err_need_header_before_typeid);
126 return ExprResult(true);
127 }
128 if (!Ident_TypeInfo) {
129 Ident_TypeInfo = &PP.getIdentifierTable().get("type_info");
130 }
131 Decl *TypeInfoDecl = LookupDecl(Ident_TypeInfo,
132 Decl::IDNS_Tag | Decl::IDNS_Ordinary,
133 0, StdNs, /*createBuiltins=*/false);
134 RecordDecl *TypeInfoRecordDecl = dyn_cast_or_null<RecordDecl>(TypeInfoDecl);
135 if (!TypeInfoRecordDecl) {
136 Diag(OpLoc, diag::err_need_header_before_typeid);
137 return ExprResult(true);
138 }
139
140 QualType TypeInfoType = Context.getTypeDeclType(TypeInfoRecordDecl);
141
142 return new CXXTypeidExpr(isType, TyOrExpr, TypeInfoType.withConst(),
143 SourceRange(OpLoc, RParenLoc));
144}
145
Steve Naroff5cbb02f2007-09-16 14:56:35 +0000146/// ActOnCXXBoolLiteral - Parse {true,false} literals.
Chris Lattner4b009652007-07-25 00:24:17 +0000147Action::ExprResult
Steve Naroff5cbb02f2007-09-16 14:56:35 +0000148Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
Douglas Gregorf8e92702008-10-24 15:36:09 +0000149 assert((Kind == tok::kw_true || Kind == tok::kw_false) &&
Chris Lattner4b009652007-07-25 00:24:17 +0000150 "Unknown C++ Boolean value!");
Steve Naroffac5d4f12007-08-25 14:02:58 +0000151 return new CXXBoolLiteralExpr(Kind == tok::kw_true, Context.BoolTy, OpLoc);
Chris Lattner4b009652007-07-25 00:24:17 +0000152}
Chris Lattnera7447ba2008-02-26 00:51:44 +0000153
154/// ActOnCXXThrow - Parse throw expressions.
155Action::ExprResult
156Sema::ActOnCXXThrow(SourceLocation OpLoc, ExprTy *E) {
157 return new CXXThrowExpr((Expr*)E, Context.VoidTy, OpLoc);
158}
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000159
160Action::ExprResult Sema::ActOnCXXThis(SourceLocation ThisLoc) {
161 /// C++ 9.3.2: In the body of a non-static member function, the keyword this
162 /// is a non-lvalue expression whose value is the address of the object for
163 /// which the function is called.
164
165 if (!isa<FunctionDecl>(CurContext)) {
166 Diag(ThisLoc, diag::err_invalid_this_use);
167 return ExprResult(true);
168 }
169
170 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext))
171 if (MD->isInstance())
Douglas Gregora5b022a2008-11-04 14:32:21 +0000172 return new CXXThisExpr(ThisLoc, MD->getThisType(Context));
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000173
174 return Diag(ThisLoc, diag::err_invalid_this_use);
175}
Argiris Kirtzidis7a1e7412008-08-22 15:38:55 +0000176
177/// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
178/// Can be interpreted either as function-style casting ("int(x)")
179/// or class type construction ("ClassType(x,y,z)")
180/// or creation of a value-initialized type ("int()").
181Action::ExprResult
182Sema::ActOnCXXTypeConstructExpr(SourceRange TypeRange, TypeTy *TypeRep,
183 SourceLocation LParenLoc,
184 ExprTy **ExprTys, unsigned NumExprs,
185 SourceLocation *CommaLocs,
186 SourceLocation RParenLoc) {
187 assert(TypeRep && "Missing type!");
188 QualType Ty = QualType::getFromOpaquePtr(TypeRep);
189 Expr **Exprs = (Expr**)ExprTys;
190 SourceLocation TyBeginLoc = TypeRange.getBegin();
191 SourceRange FullRange = SourceRange(TyBeginLoc, RParenLoc);
192
193 if (const RecordType *RT = Ty->getAsRecordType()) {
194 // C++ 5.2.3p1:
195 // If the simple-type-specifier specifies a class type, the class type shall
196 // be complete.
197 //
198 if (!RT->getDecl()->isDefinition())
199 return Diag(TyBeginLoc, diag::err_invalid_incomplete_type_use,
200 Ty.getAsString(), FullRange);
201
Argiris Kirtzidiscf4e8f82008-10-06 23:16:35 +0000202 unsigned DiagID = PP.getDiagnostics().getCustomDiagID(Diagnostic::Error,
203 "class constructors are not supported yet");
204 return Diag(TyBeginLoc, DiagID);
Argiris Kirtzidis7a1e7412008-08-22 15:38:55 +0000205 }
206
207 // C++ 5.2.3p1:
208 // If the expression list is a single expression, the type conversion
209 // expression is equivalent (in definedness, and if defined in meaning) to the
210 // corresponding cast expression.
211 //
212 if (NumExprs == 1) {
213 if (CheckCastTypes(TypeRange, Ty, Exprs[0]))
214 return true;
Douglas Gregor21a04f32008-10-27 19:41:14 +0000215 return new CXXFunctionalCastExpr(Ty.getNonReferenceType(), Ty, TyBeginLoc,
216 Exprs[0], RParenLoc);
Argiris Kirtzidis7a1e7412008-08-22 15:38:55 +0000217 }
218
219 // C++ 5.2.3p1:
220 // If the expression list specifies more than a single value, the type shall
221 // be a class with a suitably declared constructor.
222 //
223 if (NumExprs > 1)
224 return Diag(CommaLocs[0], diag::err_builtin_func_cast_more_than_one_arg,
225 FullRange);
226
227 assert(NumExprs == 0 && "Expected 0 expressions");
228
229 // C++ 5.2.3p2:
230 // The expression T(), where T is a simple-type-specifier for a non-array
231 // complete object type or the (possibly cv-qualified) void type, creates an
232 // rvalue of the specified type, which is value-initialized.
233 //
234 if (Ty->isArrayType())
235 return Diag(TyBeginLoc, diag::err_value_init_for_array_type, FullRange);
236 if (Ty->isIncompleteType() && !Ty->isVoidType())
237 return Diag(TyBeginLoc, diag::err_invalid_incomplete_type_use,
238 Ty.getAsString(), FullRange);
239
240 return new CXXZeroInitValueExpr(Ty, TyBeginLoc, RParenLoc);
241}
Argiris Kirtzidis810c0f72008-09-10 02:17:11 +0000242
243
244/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
245/// C++ if/switch/while/for statement.
246/// e.g: "if (int x = f()) {...}"
247Action::ExprResult
248Sema::ActOnCXXConditionDeclarationExpr(Scope *S, SourceLocation StartLoc,
249 Declarator &D,
250 SourceLocation EqualLoc,
251 ExprTy *AssignExprVal) {
252 assert(AssignExprVal && "Null assignment expression");
253
254 // C++ 6.4p2:
255 // The declarator shall not specify a function or an array.
256 // The type-specifier-seq shall not contain typedef and shall not declare a
257 // new class or enumeration.
258
259 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
260 "Parser allowed 'typedef' as storage class of condition decl.");
261
262 QualType Ty = GetTypeForDeclarator(D, S);
263
264 if (Ty->isFunctionType()) { // The declarator shall not specify a function...
265 // We exit without creating a CXXConditionDeclExpr because a FunctionDecl
266 // would be created and CXXConditionDeclExpr wants a VarDecl.
267 return Diag(StartLoc, diag::err_invalid_use_of_function_type,
268 SourceRange(StartLoc, EqualLoc));
269 } else if (Ty->isArrayType()) { // ...or an array.
270 Diag(StartLoc, diag::err_invalid_use_of_array_type,
271 SourceRange(StartLoc, EqualLoc));
272 } else if (const RecordType *RT = Ty->getAsRecordType()) {
273 RecordDecl *RD = RT->getDecl();
274 // The type-specifier-seq shall not declare a new class...
275 if (RD->isDefinition() && (RD->getIdentifier() == 0 || S->isDeclScope(RD)))
276 Diag(RD->getLocation(), diag::err_type_defined_in_condition);
277 } else if (const EnumType *ET = Ty->getAsEnumType()) {
278 EnumDecl *ED = ET->getDecl();
279 // ...or enumeration.
280 if (ED->isDefinition() && (ED->getIdentifier() == 0 || S->isDeclScope(ED)))
281 Diag(ED->getLocation(), diag::err_type_defined_in_condition);
282 }
283
284 DeclTy *Dcl = ActOnDeclarator(S, D, 0);
285 if (!Dcl)
286 return true;
287 AddInitializerToDecl(Dcl, AssignExprVal);
288
289 return new CXXConditionDeclExpr(StartLoc, EqualLoc,
290 cast<VarDecl>(static_cast<Decl *>(Dcl)));
291}
292
293/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
294bool Sema::CheckCXXBooleanCondition(Expr *&CondExpr) {
295 // C++ 6.4p4:
296 // The value of a condition that is an initialized declaration in a statement
297 // other than a switch statement is the value of the declared variable
298 // implicitly converted to type bool. If that conversion is ill-formed, the
299 // program is ill-formed.
300 // The value of a condition that is an expression is the value of the
301 // expression, implicitly converted to bool.
302 //
303 QualType Ty = CondExpr->getType(); // Save the type.
304 AssignConvertType
305 ConvTy = CheckSingleAssignmentConstraints(Context.BoolTy, CondExpr);
306 if (ConvTy == Incompatible)
307 return Diag(CondExpr->getLocStart(), diag::err_typecheck_bool_condition,
308 Ty.getAsString(), CondExpr->getSourceRange());
309 return false;
310}
Douglas Gregor1815b3b2008-09-12 00:47:35 +0000311
312/// Helper function to determine whether this is the (deprecated) C++
313/// conversion from a string literal to a pointer to non-const char or
314/// non-const wchar_t (for narrow and wide string literals,
315/// respectively).
316bool
317Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
318 // Look inside the implicit cast, if it exists.
319 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
320 From = Cast->getSubExpr();
321
322 // A string literal (2.13.4) that is not a wide string literal can
323 // be converted to an rvalue of type "pointer to char"; a wide
324 // string literal can be converted to an rvalue of type "pointer
325 // to wchar_t" (C++ 4.2p2).
326 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From))
327 if (const PointerType *ToPtrType = ToType->getAsPointerType())
328 if (const BuiltinType *ToPointeeType
329 = ToPtrType->getPointeeType()->getAsBuiltinType()) {
330 // This conversion is considered only when there is an
331 // explicit appropriate pointer target type (C++ 4.2p2).
332 if (ToPtrType->getPointeeType().getCVRQualifiers() == 0 &&
333 ((StrLit->isWide() && ToPointeeType->isWideCharType()) ||
334 (!StrLit->isWide() &&
335 (ToPointeeType->getKind() == BuiltinType::Char_U ||
336 ToPointeeType->getKind() == BuiltinType::Char_S))))
337 return true;
338 }
339
340 return false;
341}
Douglas Gregorbb461502008-10-24 04:54:22 +0000342
343/// PerformImplicitConversion - Perform an implicit conversion of the
344/// expression From to the type ToType. Returns true if there was an
345/// error, false otherwise. The expression From is replaced with the
346/// converted expression.
347bool
348Sema::PerformImplicitConversion(Expr *&From, QualType ToType)
349{
Douglas Gregor81c29152008-10-29 00:13:59 +0000350 ImplicitConversionSequence ICS = TryImplicitConversion(From, ToType);
Douglas Gregorbb461502008-10-24 04:54:22 +0000351 switch (ICS.ConversionKind) {
352 case ImplicitConversionSequence::StandardConversion:
353 if (PerformImplicitConversion(From, ToType, ICS.Standard))
354 return true;
355 break;
356
357 case ImplicitConversionSequence::UserDefinedConversion:
358 // FIXME: This is, of course, wrong. We'll need to actually call
359 // the constructor or conversion operator, and then cope with the
360 // standard conversions.
361 ImpCastExprToType(From, ToType);
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000362 return false;
Douglas Gregorbb461502008-10-24 04:54:22 +0000363
364 case ImplicitConversionSequence::EllipsisConversion:
365 assert(false && "Cannot perform an ellipsis conversion");
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000366 return false;
Douglas Gregorbb461502008-10-24 04:54:22 +0000367
368 case ImplicitConversionSequence::BadConversion:
369 return true;
370 }
371
372 // Everything went well.
373 return false;
374}
375
376/// PerformImplicitConversion - Perform an implicit conversion of the
377/// expression From to the type ToType by following the standard
378/// conversion sequence SCS. Returns true if there was an error, false
379/// otherwise. The expression From is replaced with the converted
380/// expression.
381bool
382Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
383 const StandardConversionSequence& SCS)
384{
385 // Overall FIXME: we are recomputing too many types here and doing
386 // far too much extra work. What this means is that we need to keep
387 // track of more information that is computed when we try the
388 // implicit conversion initially, so that we don't need to recompute
389 // anything here.
390 QualType FromType = From->getType();
391
Douglas Gregora3b34bb2008-11-03 19:09:14 +0000392 if (SCS.CopyConstructor) {
393 // FIXME: Create a temporary object by calling the copy
394 // constructor.
395 ImpCastExprToType(From, ToType);
396 return false;
397 }
398
Douglas Gregorbb461502008-10-24 04:54:22 +0000399 // Perform the first implicit conversion.
400 switch (SCS.First) {
401 case ICK_Identity:
402 case ICK_Lvalue_To_Rvalue:
403 // Nothing to do.
404 break;
405
406 case ICK_Array_To_Pointer:
Douglas Gregor45014fd2008-11-10 20:40:00 +0000407 if (FromType->isOverloadType()) {
408 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType, true);
409 if (!Fn)
410 return true;
411
412 FixOverloadedFunctionReference(From, Fn);
413 FromType = From->getType();
414 } else {
415 FromType = Context.getArrayDecayedType(FromType);
416 }
Douglas Gregorbb461502008-10-24 04:54:22 +0000417 ImpCastExprToType(From, FromType);
418 break;
419
420 case ICK_Function_To_Pointer:
421 FromType = Context.getPointerType(FromType);
422 ImpCastExprToType(From, FromType);
423 break;
424
425 default:
426 assert(false && "Improper first standard conversion");
427 break;
428 }
429
430 // Perform the second implicit conversion
431 switch (SCS.Second) {
432 case ICK_Identity:
433 // Nothing to do.
434 break;
435
436 case ICK_Integral_Promotion:
437 case ICK_Floating_Promotion:
438 case ICK_Integral_Conversion:
439 case ICK_Floating_Conversion:
440 case ICK_Floating_Integral:
441 FromType = ToType.getUnqualifiedType();
442 ImpCastExprToType(From, FromType);
443 break;
444
445 case ICK_Pointer_Conversion:
446 if (CheckPointerConversion(From, ToType))
447 return true;
448 ImpCastExprToType(From, ToType);
449 break;
450
451 case ICK_Pointer_Member:
452 // FIXME: Implement pointer-to-member conversions.
453 assert(false && "Pointer-to-member conversions are unsupported");
454 break;
455
456 case ICK_Boolean_Conversion:
457 FromType = Context.BoolTy;
458 ImpCastExprToType(From, FromType);
459 break;
460
461 default:
462 assert(false && "Improper second standard conversion");
463 break;
464 }
465
466 switch (SCS.Third) {
467 case ICK_Identity:
468 // Nothing to do.
469 break;
470
471 case ICK_Qualification:
472 ImpCastExprToType(From, ToType);
473 break;
474
475 default:
476 assert(false && "Improper second standard conversion");
477 break;
478 }
479
480 return false;
481}
482