SemaExprCXX.cpp revision 904eed3f6148758d39a2d3c88f3133274460d645
1//===--- SemaExprCXX.cpp - Semantic Analysis for Expressions --------------===// 2// 3// The LLVM Compiler Infrastructure 4// 5// This file is distributed under the University of Illinois Open Source 6// License. See LICENSE.TXT for details. 7// 8//===----------------------------------------------------------------------===// 9// 10// This file implements semantic analysis for C++ expressions. 11// 12//===----------------------------------------------------------------------===// 13 14#include "Sema.h" 15#include "clang/AST/ExprCXX.h" 16#include "clang/AST/ASTContext.h" 17#include "clang/Parse/DeclSpec.h" 18#include "clang/Lex/Preprocessor.h" 19#include "clang/Basic/Diagnostic.h" 20using namespace clang; 21 22/// ActOnCXXBoolLiteral - Parse {true,false} literals. 23Action::ExprResult 24Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) { 25 assert((Kind == tok::kw_true || Kind == tok::kw_false) && 26 "Unknown C++ Boolean value!"); 27 return new CXXBoolLiteralExpr(Kind == tok::kw_true, Context.BoolTy, OpLoc); 28} 29 30/// ActOnCXXThrow - Parse throw expressions. 31Action::ExprResult 32Sema::ActOnCXXThrow(SourceLocation OpLoc, ExprTy *E) { 33 return new CXXThrowExpr((Expr*)E, Context.VoidTy, OpLoc); 34} 35 36Action::ExprResult Sema::ActOnCXXThis(SourceLocation ThisLoc) { 37 /// C++ 9.3.2: In the body of a non-static member function, the keyword this 38 /// is a non-lvalue expression whose value is the address of the object for 39 /// which the function is called. 40 41 if (!isa<FunctionDecl>(CurContext)) { 42 Diag(ThisLoc, diag::err_invalid_this_use); 43 return ExprResult(true); 44 } 45 46 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) 47 if (MD->isInstance()) 48 return new CXXThisExpr(ThisLoc, MD->getThisType(Context)); 49 50 return Diag(ThisLoc, diag::err_invalid_this_use); 51} 52 53/// ActOnCXXTypeConstructExpr - Parse construction of a specified type. 54/// Can be interpreted either as function-style casting ("int(x)") 55/// or class type construction ("ClassType(x,y,z)") 56/// or creation of a value-initialized type ("int()"). 57Action::ExprResult 58Sema::ActOnCXXTypeConstructExpr(SourceRange TypeRange, TypeTy *TypeRep, 59 SourceLocation LParenLoc, 60 ExprTy **ExprTys, unsigned NumExprs, 61 SourceLocation *CommaLocs, 62 SourceLocation RParenLoc) { 63 assert(TypeRep && "Missing type!"); 64 QualType Ty = QualType::getFromOpaquePtr(TypeRep); 65 Expr **Exprs = (Expr**)ExprTys; 66 SourceLocation TyBeginLoc = TypeRange.getBegin(); 67 SourceRange FullRange = SourceRange(TyBeginLoc, RParenLoc); 68 69 if (const RecordType *RT = Ty->getAsRecordType()) { 70 // C++ 5.2.3p1: 71 // If the simple-type-specifier specifies a class type, the class type shall 72 // be complete. 73 // 74 if (!RT->getDecl()->isDefinition()) 75 return Diag(TyBeginLoc, diag::err_invalid_incomplete_type_use, 76 Ty.getAsString(), FullRange); 77 78 unsigned DiagID = PP.getDiagnostics().getCustomDiagID(Diagnostic::Error, 79 "class constructors are not supported yet"); 80 return Diag(TyBeginLoc, DiagID); 81 } 82 83 // C++ 5.2.3p1: 84 // If the expression list is a single expression, the type conversion 85 // expression is equivalent (in definedness, and if defined in meaning) to the 86 // corresponding cast expression. 87 // 88 if (NumExprs == 1) { 89 if (CheckCastTypes(TypeRange, Ty, Exprs[0])) 90 return true; 91 return new CXXFunctionalCastExpr(Ty.getNonReferenceType(), Ty, TyBeginLoc, 92 Exprs[0], RParenLoc); 93 } 94 95 // C++ 5.2.3p1: 96 // If the expression list specifies more than a single value, the type shall 97 // be a class with a suitably declared constructor. 98 // 99 if (NumExprs > 1) 100 return Diag(CommaLocs[0], diag::err_builtin_func_cast_more_than_one_arg, 101 FullRange); 102 103 assert(NumExprs == 0 && "Expected 0 expressions"); 104 105 // C++ 5.2.3p2: 106 // The expression T(), where T is a simple-type-specifier for a non-array 107 // complete object type or the (possibly cv-qualified) void type, creates an 108 // rvalue of the specified type, which is value-initialized. 109 // 110 if (Ty->isArrayType()) 111 return Diag(TyBeginLoc, diag::err_value_init_for_array_type, FullRange); 112 if (Ty->isIncompleteType() && !Ty->isVoidType()) 113 return Diag(TyBeginLoc, diag::err_invalid_incomplete_type_use, 114 Ty.getAsString(), FullRange); 115 116 return new CXXZeroInitValueExpr(Ty, TyBeginLoc, RParenLoc); 117} 118 119 120/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a 121/// C++ if/switch/while/for statement. 122/// e.g: "if (int x = f()) {...}" 123Action::ExprResult 124Sema::ActOnCXXConditionDeclarationExpr(Scope *S, SourceLocation StartLoc, 125 Declarator &D, 126 SourceLocation EqualLoc, 127 ExprTy *AssignExprVal) { 128 assert(AssignExprVal && "Null assignment expression"); 129 130 // C++ 6.4p2: 131 // The declarator shall not specify a function or an array. 132 // The type-specifier-seq shall not contain typedef and shall not declare a 133 // new class or enumeration. 134 135 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && 136 "Parser allowed 'typedef' as storage class of condition decl."); 137 138 QualType Ty = GetTypeForDeclarator(D, S); 139 140 if (Ty->isFunctionType()) { // The declarator shall not specify a function... 141 // We exit without creating a CXXConditionDeclExpr because a FunctionDecl 142 // would be created and CXXConditionDeclExpr wants a VarDecl. 143 return Diag(StartLoc, diag::err_invalid_use_of_function_type, 144 SourceRange(StartLoc, EqualLoc)); 145 } else if (Ty->isArrayType()) { // ...or an array. 146 Diag(StartLoc, diag::err_invalid_use_of_array_type, 147 SourceRange(StartLoc, EqualLoc)); 148 } else if (const RecordType *RT = Ty->getAsRecordType()) { 149 RecordDecl *RD = RT->getDecl(); 150 // The type-specifier-seq shall not declare a new class... 151 if (RD->isDefinition() && (RD->getIdentifier() == 0 || S->isDeclScope(RD))) 152 Diag(RD->getLocation(), diag::err_type_defined_in_condition); 153 } else if (const EnumType *ET = Ty->getAsEnumType()) { 154 EnumDecl *ED = ET->getDecl(); 155 // ...or enumeration. 156 if (ED->isDefinition() && (ED->getIdentifier() == 0 || S->isDeclScope(ED))) 157 Diag(ED->getLocation(), diag::err_type_defined_in_condition); 158 } 159 160 DeclTy *Dcl = ActOnDeclarator(S, D, 0); 161 if (!Dcl) 162 return true; 163 AddInitializerToDecl(Dcl, AssignExprVal); 164 165 return new CXXConditionDeclExpr(StartLoc, EqualLoc, 166 cast<VarDecl>(static_cast<Decl *>(Dcl))); 167} 168 169/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid. 170bool Sema::CheckCXXBooleanCondition(Expr *&CondExpr) { 171 // C++ 6.4p4: 172 // The value of a condition that is an initialized declaration in a statement 173 // other than a switch statement is the value of the declared variable 174 // implicitly converted to type bool. If that conversion is ill-formed, the 175 // program is ill-formed. 176 // The value of a condition that is an expression is the value of the 177 // expression, implicitly converted to bool. 178 // 179 QualType Ty = CondExpr->getType(); // Save the type. 180 AssignConvertType 181 ConvTy = CheckSingleAssignmentConstraints(Context.BoolTy, CondExpr); 182 if (ConvTy == Incompatible) 183 return Diag(CondExpr->getLocStart(), diag::err_typecheck_bool_condition, 184 Ty.getAsString(), CondExpr->getSourceRange()); 185 return false; 186} 187 188/// Helper function to determine whether this is the (deprecated) C++ 189/// conversion from a string literal to a pointer to non-const char or 190/// non-const wchar_t (for narrow and wide string literals, 191/// respectively). 192bool 193Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) { 194 // Look inside the implicit cast, if it exists. 195 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From)) 196 From = Cast->getSubExpr(); 197 198 // A string literal (2.13.4) that is not a wide string literal can 199 // be converted to an rvalue of type "pointer to char"; a wide 200 // string literal can be converted to an rvalue of type "pointer 201 // to wchar_t" (C++ 4.2p2). 202 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From)) 203 if (const PointerType *ToPtrType = ToType->getAsPointerType()) 204 if (const BuiltinType *ToPointeeType 205 = ToPtrType->getPointeeType()->getAsBuiltinType()) { 206 // This conversion is considered only when there is an 207 // explicit appropriate pointer target type (C++ 4.2p2). 208 if (ToPtrType->getPointeeType().getCVRQualifiers() == 0 && 209 ((StrLit->isWide() && ToPointeeType->isWideCharType()) || 210 (!StrLit->isWide() && 211 (ToPointeeType->getKind() == BuiltinType::Char_U || 212 ToPointeeType->getKind() == BuiltinType::Char_S)))) 213 return true; 214 } 215 216 return false; 217} 218 219/// PerformImplicitConversion - Perform an implicit conversion of the 220/// expression From to the type ToType. Returns true if there was an 221/// error, false otherwise. The expression From is replaced with the 222/// converted expression. 223bool 224Sema::PerformImplicitConversion(Expr *&From, QualType ToType) 225{ 226 ImplicitConversionSequence ICS = TryImplicitConversion(From, ToType); 227 switch (ICS.ConversionKind) { 228 case ImplicitConversionSequence::StandardConversion: 229 if (PerformImplicitConversion(From, ToType, ICS.Standard)) 230 return true; 231 break; 232 233 case ImplicitConversionSequence::UserDefinedConversion: 234 // FIXME: This is, of course, wrong. We'll need to actually call 235 // the constructor or conversion operator, and then cope with the 236 // standard conversions. 237 ImpCastExprToType(From, ToType); 238 return false; 239 240 case ImplicitConversionSequence::EllipsisConversion: 241 assert(false && "Cannot perform an ellipsis conversion"); 242 return false; 243 244 case ImplicitConversionSequence::BadConversion: 245 return true; 246 } 247 248 // Everything went well. 249 return false; 250} 251 252/// PerformImplicitConversion - Perform an implicit conversion of the 253/// expression From to the type ToType by following the standard 254/// conversion sequence SCS. Returns true if there was an error, false 255/// otherwise. The expression From is replaced with the converted 256/// expression. 257bool 258Sema::PerformImplicitConversion(Expr *&From, QualType ToType, 259 const StandardConversionSequence& SCS) 260{ 261 // Overall FIXME: we are recomputing too many types here and doing 262 // far too much extra work. What this means is that we need to keep 263 // track of more information that is computed when we try the 264 // implicit conversion initially, so that we don't need to recompute 265 // anything here. 266 QualType FromType = From->getType(); 267 268 if (SCS.CopyConstructor) { 269 // FIXME: Create a temporary object by calling the copy 270 // constructor. 271 ImpCastExprToType(From, ToType); 272 return false; 273 } 274 275 // Perform the first implicit conversion. 276 switch (SCS.First) { 277 case ICK_Identity: 278 case ICK_Lvalue_To_Rvalue: 279 // Nothing to do. 280 break; 281 282 case ICK_Array_To_Pointer: 283 if (FromType->isOverloadType()) { 284 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType, true); 285 if (!Fn) 286 return true; 287 288 FixOverloadedFunctionReference(From, Fn); 289 FromType = From->getType(); 290 } else { 291 FromType = Context.getArrayDecayedType(FromType); 292 } 293 ImpCastExprToType(From, FromType); 294 break; 295 296 case ICK_Function_To_Pointer: 297 FromType = Context.getPointerType(FromType); 298 ImpCastExprToType(From, FromType); 299 break; 300 301 default: 302 assert(false && "Improper first standard conversion"); 303 break; 304 } 305 306 // Perform the second implicit conversion 307 switch (SCS.Second) { 308 case ICK_Identity: 309 // Nothing to do. 310 break; 311 312 case ICK_Integral_Promotion: 313 case ICK_Floating_Promotion: 314 case ICK_Integral_Conversion: 315 case ICK_Floating_Conversion: 316 case ICK_Floating_Integral: 317 FromType = ToType.getUnqualifiedType(); 318 ImpCastExprToType(From, FromType); 319 break; 320 321 case ICK_Pointer_Conversion: 322 if (CheckPointerConversion(From, ToType)) 323 return true; 324 ImpCastExprToType(From, ToType); 325 break; 326 327 case ICK_Pointer_Member: 328 // FIXME: Implement pointer-to-member conversions. 329 assert(false && "Pointer-to-member conversions are unsupported"); 330 break; 331 332 case ICK_Boolean_Conversion: 333 FromType = Context.BoolTy; 334 ImpCastExprToType(From, FromType); 335 break; 336 337 default: 338 assert(false && "Improper second standard conversion"); 339 break; 340 } 341 342 switch (SCS.Third) { 343 case ICK_Identity: 344 // Nothing to do. 345 break; 346 347 case ICK_Qualification: 348 ImpCastExprToType(From, ToType); 349 break; 350 351 default: 352 assert(false && "Improper second standard conversion"); 353 break; 354 } 355 356 return false; 357} 358 359