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