/home/runner/work/DirectXShaderCompiler/DirectXShaderCompiler/tools/clang/lib/Sema/SemaExprObjC.cpp
Line | Count | Source (jump to first uncovered line) |
1 | | //===--- SemaExprObjC.cpp - Semantic Analysis for ObjC 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 Objective-C expressions. |
11 | | // |
12 | | //===----------------------------------------------------------------------===// |
13 | | |
14 | | #include "clang/Sema/SemaInternal.h" |
15 | | #include "clang/AST/ASTContext.h" |
16 | | #include "clang/AST/DeclObjC.h" |
17 | | #include "clang/AST/ExprObjC.h" |
18 | | #include "clang/AST/StmtVisitor.h" |
19 | | #include "clang/AST/TypeLoc.h" |
20 | | #include "clang/Analysis/DomainSpecific/CocoaConventions.h" |
21 | | #include "clang/Edit/Commit.h" |
22 | | #include "clang/Edit/Rewriters.h" |
23 | | #include "clang/Lex/Preprocessor.h" |
24 | | #include "clang/Sema/Initialization.h" |
25 | | #include "clang/Sema/Lookup.h" |
26 | | #include "clang/Sema/Scope.h" |
27 | | #include "clang/Sema/ScopeInfo.h" |
28 | | #include "llvm/ADT/SmallString.h" |
29 | | |
30 | | using namespace clang; |
31 | | using namespace sema; |
32 | | using llvm::makeArrayRef; |
33 | | |
34 | | // HLSL Change Starts |
35 | | // No ObjC parse/sema support, so simply skip all of this compilation. |
36 | | // Here are enough stubs to link the current targets. |
37 | | #if 1 |
38 | | ExprResult Sema::ParseObjCStringLiteral(SourceLocation *AtLocs, |
39 | | Expr **strings, |
40 | 0 | unsigned NumStrings) { |
41 | 0 | llvm_unreachable("HLSL does not support ObjC constructs"); |
42 | 0 | } |
43 | | |
44 | 0 | ExprResult Sema::BuildObjCStringLiteral(SourceLocation AtLoc, StringLiteral *S) { |
45 | 0 | llvm_unreachable("HLSL does not support ObjC constructs"); |
46 | 0 | } |
47 | | |
48 | 0 | ExprResult Sema::BuildObjCNumericLiteral(SourceLocation AtLoc, Expr *Number) { |
49 | 0 | llvm_unreachable("HLSL does not support ObjC constructs"); |
50 | 0 | } |
51 | | |
52 | | ExprResult Sema::ActOnObjCBoolLiteral(SourceLocation AtLoc, |
53 | | SourceLocation ValueLoc, |
54 | 0 | bool Value) { |
55 | 0 | llvm_unreachable("HLSL does not support ObjC constructs"); |
56 | 0 | } |
57 | | |
58 | 0 | ExprResult Sema::BuildObjCBoxedExpr(SourceRange SR, Expr *ValueExpr) { |
59 | 0 | llvm_unreachable("HLSL does not support ObjC constructs"); |
60 | 0 | } |
61 | | |
62 | | ExprResult Sema::BuildObjCSubscriptExpression(SourceLocation RB, Expr *BaseExpr, |
63 | | Expr *IndexExpr, |
64 | | ObjCMethodDecl *getterMethod, |
65 | 0 | ObjCMethodDecl *setterMethod) { |
66 | 0 | llvm_unreachable("HLSL does not support ObjC constructs"); |
67 | 0 | } |
68 | | |
69 | 0 | ExprResult Sema::BuildObjCArrayLiteral(SourceRange SR, MultiExprArg Elements) { |
70 | 0 | llvm_unreachable("HLSL does not support ObjC constructs"); |
71 | 0 | } |
72 | | |
73 | | ExprResult Sema::BuildObjCDictionaryLiteral(SourceRange SR, |
74 | | ObjCDictionaryElement *Elements, |
75 | 0 | unsigned NumElements) { |
76 | 0 | llvm_unreachable("HLSL does not support ObjC constructs"); |
77 | 0 | } |
78 | | |
79 | | ExprResult Sema::BuildObjCEncodeExpression(SourceLocation AtLoc, |
80 | | TypeSourceInfo *EncodedTypeInfo, |
81 | 0 | SourceLocation RParenLoc) { |
82 | 0 | llvm_unreachable("HLSL does not support ObjC constructs"); |
83 | 0 | } |
84 | | |
85 | | ExprResult Sema::ParseObjCEncodeExpression(SourceLocation AtLoc, |
86 | | SourceLocation EncodeLoc, |
87 | | SourceLocation LParenLoc, |
88 | | ParsedType ty, |
89 | 0 | SourceLocation RParenLoc) { |
90 | 0 | llvm_unreachable("HLSL does not support ObjC constructs"); |
91 | 0 | } |
92 | | |
93 | | ExprResult Sema::ParseObjCSelectorExpression(Selector Sel, |
94 | | SourceLocation AtLoc, |
95 | | SourceLocation SelLoc, |
96 | | SourceLocation LParenLoc, |
97 | | SourceLocation RParenLoc, |
98 | 0 | bool WarnMultipleSelectors) { |
99 | 0 | llvm_unreachable("HLSL does not support ObjC constructs"); |
100 | 0 | } |
101 | | |
102 | | ExprResult Sema::ParseObjCProtocolExpression(IdentifierInfo *ProtocolId, |
103 | | SourceLocation AtLoc, |
104 | | SourceLocation ProtoLoc, |
105 | | SourceLocation LParenLoc, |
106 | | SourceLocation ProtoIdLoc, |
107 | 0 | SourceLocation RParenLoc) { |
108 | 0 | llvm_unreachable("HLSL does not support ObjC constructs"); |
109 | 0 | return ExprError(); |
110 | 0 | } |
111 | | |
112 | | /// Try to capture an implicit reference to 'self'. |
113 | 0 | ObjCMethodDecl *Sema::tryCaptureObjCSelf(SourceLocation Loc) { |
114 | 0 | llvm_unreachable("HLSL does not support ObjC constructs"); |
115 | 0 | return nullptr; |
116 | 0 | } |
117 | | |
118 | | QualType Sema::getMessageSendResultType(QualType ReceiverType, |
119 | | ObjCMethodDecl *Method, |
120 | | bool isClassMessage, |
121 | 0 | bool isSuperMessage) { |
122 | 0 | llvm_unreachable("HLSL does not support ObjC constructs"); |
123 | 0 | return QualType(); |
124 | 0 | } |
125 | | |
126 | 0 | void Sema::EmitRelatedResultTypeNoteForReturn(QualType destType) { |
127 | 0 | llvm_unreachable("HLSL does not support ObjC constructs"); |
128 | 0 | } |
129 | | |
130 | 0 | void Sema::EmitRelatedResultTypeNote(const Expr *E) { |
131 | 0 | llvm_unreachable("HLSL does not support ObjC constructs"); |
132 | 0 | } |
133 | | |
134 | | bool Sema::CheckMessageArgumentTypes(QualType ReceiverType, |
135 | | MultiExprArg Args, |
136 | | Selector Sel, |
137 | | ArrayRef<SourceLocation> SelectorLocs, |
138 | | ObjCMethodDecl *Method, |
139 | | bool isClassMessage, bool isSuperMessage, |
140 | | SourceLocation lbrac, SourceLocation rbrac, |
141 | | SourceRange RecRange, |
142 | 0 | QualType &ReturnType, ExprValueKind &VK) { |
143 | 0 | llvm_unreachable("HLSL does not support ObjC constructs"); |
144 | 0 | return false; |
145 | 0 | } |
146 | | |
147 | 0 | bool Sema::isSelfExpr(Expr *RExpr) { |
148 | 0 | llvm_unreachable("HLSL does not support ObjC constructs"); |
149 | 0 | return false; |
150 | 0 | } |
151 | | |
152 | 0 | bool Sema::isSelfExpr(Expr *receiver, const ObjCMethodDecl *method) { |
153 | 0 | llvm_unreachable("HLSL does not support ObjC constructs"); |
154 | 0 | return false; |
155 | 0 | } |
156 | | |
157 | | ObjCMethodDecl *Sema::LookupMethodInObjectType(Selector sel, QualType type, |
158 | 0 | bool isInstance) { |
159 | 0 | llvm_unreachable("HLSL does not support ObjC constructs"); |
160 | 0 | return nullptr; |
161 | 0 | } |
162 | | |
163 | | ObjCMethodDecl *Sema::LookupMethodInQualifiedType(Selector Sel, |
164 | | const ObjCObjectPointerType *OPT, |
165 | | bool Instance) |
166 | 0 | { |
167 | 0 | llvm_unreachable("HLSL does not support ObjC constructs"); |
168 | 0 | return nullptr; |
169 | 0 | } |
170 | | |
171 | | ExprResult Sema:: |
172 | | HandleExprPropertyRefExpr(const ObjCObjectPointerType *OPT, |
173 | | Expr *BaseExpr, SourceLocation OpLoc, |
174 | | DeclarationName MemberName, |
175 | | SourceLocation MemberLoc, |
176 | | SourceLocation SuperLoc, QualType SuperType, |
177 | 0 | bool Super) { |
178 | 0 | llvm_unreachable("HLSL does not support ObjC constructs"); |
179 | 0 | return ExprError(); |
180 | 0 | } |
181 | | |
182 | | ExprResult Sema:: |
183 | | ActOnClassPropertyRefExpr(IdentifierInfo &receiverName, |
184 | | IdentifierInfo &propertyName, |
185 | | SourceLocation receiverNameLoc, |
186 | 0 | SourceLocation propertyNameLoc) { |
187 | 0 | llvm_unreachable("HLSL does not support ObjC constructs"); |
188 | 0 | return ExprError(); |
189 | 0 | } |
190 | | |
191 | | Sema::ObjCMessageKind Sema::getObjCMessageKind(Scope *S, |
192 | | IdentifierInfo *Name, |
193 | | SourceLocation NameLoc, |
194 | | bool IsSuper, |
195 | | bool HasTrailingDot, |
196 | 0 | ParsedType &ReceiverType) { |
197 | 0 | llvm_unreachable("HLSL does not support ObjC constructs"); |
198 | 0 | } |
199 | | |
200 | | ExprResult Sema::ActOnSuperMessage(Scope *S, |
201 | | SourceLocation SuperLoc, |
202 | | Selector Sel, |
203 | | SourceLocation LBracLoc, |
204 | | ArrayRef<SourceLocation> SelectorLocs, |
205 | | SourceLocation RBracLoc, |
206 | 0 | MultiExprArg Args) { |
207 | 0 | llvm_unreachable("HLSL does not support ObjC constructs"); |
208 | 0 | return ExprError(); |
209 | 0 | } |
210 | | |
211 | | |
212 | | ExprResult Sema::BuildClassMessageImplicit(QualType ReceiverType, |
213 | | bool isSuperReceiver, |
214 | | SourceLocation Loc, |
215 | | Selector Sel, |
216 | | ObjCMethodDecl *Method, |
217 | 0 | MultiExprArg Args) { |
218 | 0 | llvm_unreachable("HLSL does not support ObjC constructs"); |
219 | 0 | return ExprError(); |
220 | 0 | } |
221 | | |
222 | | ExprResult Sema::BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo, |
223 | | QualType ReceiverType, |
224 | | SourceLocation SuperLoc, |
225 | | Selector Sel, |
226 | | ObjCMethodDecl *Method, |
227 | | SourceLocation LBracLoc, |
228 | | ArrayRef<SourceLocation> SelectorLocs, |
229 | | SourceLocation RBracLoc, |
230 | | MultiExprArg ArgsIn, |
231 | 0 | bool isImplicit) { |
232 | 0 | llvm_unreachable("HLSL does not support ObjC constructs"); |
233 | 0 | return ExprError(); |
234 | 0 | } |
235 | | |
236 | | ExprResult Sema::ActOnClassMessage(Scope *S, |
237 | | ParsedType Receiver, |
238 | | Selector Sel, |
239 | | SourceLocation LBracLoc, |
240 | | ArrayRef<SourceLocation> SelectorLocs, |
241 | | SourceLocation RBracLoc, |
242 | 0 | MultiExprArg Args) { |
243 | 0 | llvm_unreachable("HLSL does not support ObjC constructs"); |
244 | 0 | } |
245 | | |
246 | | ExprResult Sema::BuildInstanceMessageImplicit(Expr *Receiver, |
247 | | QualType ReceiverType, |
248 | | SourceLocation Loc, |
249 | | Selector Sel, |
250 | | ObjCMethodDecl *Method, |
251 | 0 | MultiExprArg Args) { |
252 | 0 | llvm_unreachable("HLSL does not support ObjC constructs"); |
253 | 0 | } |
254 | | |
255 | | ExprResult Sema::BuildInstanceMessage(Expr *Receiver, |
256 | | QualType ReceiverType, |
257 | | SourceLocation SuperLoc, |
258 | | Selector Sel, |
259 | | ObjCMethodDecl *Method, |
260 | | SourceLocation LBracLoc, |
261 | | ArrayRef<SourceLocation> SelectorLocs, |
262 | | SourceLocation RBracLoc, |
263 | | MultiExprArg ArgsIn, |
264 | 0 | bool isImplicit) { |
265 | 0 | llvm_unreachable("HLSL does not support ObjC constructs"); |
266 | 0 | } |
267 | | |
268 | | ExprResult Sema::ActOnInstanceMessage(Scope *S, |
269 | | Expr *Receiver, |
270 | | Selector Sel, |
271 | | SourceLocation LBracLoc, |
272 | | ArrayRef<SourceLocation> SelectorLocs, |
273 | | SourceLocation RBracLoc, |
274 | 0 | MultiExprArg Args) { |
275 | 0 | llvm_unreachable("HLSL does not support ObjC constructs"); |
276 | 0 | } |
277 | | |
278 | 0 | bool Sema::isKnownName(StringRef name) { |
279 | 0 | if (name.empty()) |
280 | 0 | return false; |
281 | 0 | LookupResult R(*this, &Context.Idents.get(name), SourceLocation(), |
282 | 0 | Sema::LookupOrdinaryName); |
283 | 0 | return LookupName(R, TUScope, false); |
284 | 0 | } |
285 | | |
286 | 0 | void Sema::CheckTollFreeBridgeCast(QualType castType, Expr *castExpr) { |
287 | 0 | llvm_unreachable("HLSL does not support ObjC constructs"); |
288 | 0 | } |
289 | | |
290 | 0 | void Sema::CheckObjCBridgeRelatedCast(QualType castType, Expr *castExpr) { |
291 | 0 | llvm_unreachable("HLSL does not support ObjC constructs"); |
292 | 0 | } |
293 | | |
294 | | bool Sema::CheckTollFreeBridgeStaticCast(QualType castType, Expr *castExpr, |
295 | 0 | CastKind &Kind) { |
296 | 0 | llvm_unreachable("HLSL does not support ObjC constructs"); |
297 | 0 | } |
298 | | |
299 | | bool Sema::checkObjCBridgeRelatedComponents(SourceLocation Loc, |
300 | | QualType DestType, QualType SrcType, |
301 | | ObjCInterfaceDecl *&RelatedClass, |
302 | | ObjCMethodDecl *&ClassMethod, |
303 | | ObjCMethodDecl *&InstanceMethod, |
304 | | TypedefNameDecl *&TDNDecl, |
305 | 0 | bool CfToNs) { |
306 | 0 | llvm_unreachable("HLSL does not support ObjC constructs"); |
307 | 0 | } |
308 | | |
309 | | bool |
310 | | Sema::CheckObjCBridgeRelatedConversions(SourceLocation Loc, |
311 | | QualType DestType, QualType SrcType, |
312 | 0 | Expr *&SrcExpr) { |
313 | 0 | llvm_unreachable("HLSL does not support ObjC constructs"); |
314 | 0 | } |
315 | | |
316 | | Sema::ARCConversionResult |
317 | | Sema::CheckObjCARCConversion(SourceRange castRange, QualType castType, |
318 | | Expr *&castExpr, CheckedConversionKind CCK, |
319 | | bool DiagnoseCFAudited, |
320 | 0 | BinaryOperatorKind Opc) { |
321 | 0 | llvm_unreachable("HLSL does not support ObjC constructs"); |
322 | 0 | } |
323 | | |
324 | | /// Given that we saw an expression with the ARCUnbridgedCastTy |
325 | | /// placeholder type, complain bitterly. |
326 | 0 | void Sema::diagnoseARCUnbridgedCast(Expr *e) { |
327 | 0 | llvm_unreachable("HLSL does not support ObjC constructs"); |
328 | 0 | } |
329 | | |
330 | | /// stripARCUnbridgedCast - Given an expression of ARCUnbridgedCast |
331 | | /// type, remove the placeholder cast. |
332 | 0 | Expr *Sema::stripARCUnbridgedCast(Expr *e) { |
333 | 0 | llvm_unreachable("HLSL does not support ObjC constructs"); |
334 | 0 | } |
335 | | |
336 | | bool Sema::CheckObjCARCUnavailableWeakConversion(QualType castType, |
337 | 0 | QualType exprType) { |
338 | 0 | llvm_unreachable("HLSL does not support ObjC constructs"); |
339 | 0 | } |
340 | | |
341 | | ExprResult Sema::BuildObjCBridgedCast(SourceLocation LParenLoc, |
342 | | ObjCBridgeCastKind Kind, |
343 | | SourceLocation BridgeKeywordLoc, |
344 | | TypeSourceInfo *TSInfo, |
345 | 0 | Expr *SubExpr) { |
346 | 0 | llvm_unreachable("HLSL does not support ObjC constructs"); |
347 | 0 | } |
348 | | |
349 | | ExprResult Sema::ActOnObjCBridgedCast(Scope *S, |
350 | | SourceLocation LParenLoc, |
351 | | ObjCBridgeCastKind Kind, |
352 | | SourceLocation BridgeKeywordLoc, |
353 | | ParsedType Type, |
354 | | SourceLocation RParenLoc, |
355 | 0 | Expr *SubExpr) { |
356 | 0 | llvm_unreachable("HLSL does not support ObjC constructs"); |
357 | 0 | } |
358 | | |
359 | | #else |
360 | | // HLSL Change Ends |
361 | | |
362 | | ExprResult Sema::ParseObjCStringLiteral(SourceLocation *AtLocs, |
363 | | Expr **strings, |
364 | | unsigned NumStrings) { |
365 | | StringLiteral **Strings = reinterpret_cast<StringLiteral**>(strings); |
366 | | |
367 | | // Most ObjC strings are formed out of a single piece. However, we *can* |
368 | | // have strings formed out of multiple @ strings with multiple pptokens in |
369 | | // each one, e.g. @"foo" "bar" @"baz" "qux" which need to be turned into one |
370 | | // StringLiteral for ObjCStringLiteral to hold onto. |
371 | | StringLiteral *S = Strings[0]; |
372 | | |
373 | | // If we have a multi-part string, merge it all together. |
374 | | if (NumStrings != 1) { |
375 | | // Concatenate objc strings. |
376 | | SmallString<128> StrBuf; |
377 | | SmallVector<SourceLocation, 8> StrLocs; |
378 | | |
379 | | for (unsigned i = 0; i != NumStrings; ++i) { |
380 | | S = Strings[i]; |
381 | | |
382 | | // ObjC strings can't be wide or UTF. |
383 | | if (!S->isAscii()) { |
384 | | Diag(S->getLocStart(), diag::err_cfstring_literal_not_string_constant) |
385 | | << S->getSourceRange(); |
386 | | return true; |
387 | | } |
388 | | |
389 | | // Append the string. |
390 | | StrBuf += S->getString(); |
391 | | |
392 | | // Get the locations of the string tokens. |
393 | | StrLocs.append(S->tokloc_begin(), S->tokloc_end()); |
394 | | } |
395 | | |
396 | | // Create the aggregate string with the appropriate content and location |
397 | | // information. |
398 | | const ConstantArrayType *CAT = Context.getAsConstantArrayType(S->getType()); |
399 | | assert(CAT && "String literal not of constant array type!"); |
400 | | QualType StrTy = Context.getConstantArrayType( |
401 | | CAT->getElementType(), llvm::APInt(32, StrBuf.size() + 1), |
402 | | CAT->getSizeModifier(), CAT->getIndexTypeCVRQualifiers()); |
403 | | S = StringLiteral::Create(Context, StrBuf, StringLiteral::Ascii, |
404 | | /*Pascal=*/false, StrTy, &StrLocs[0], |
405 | | StrLocs.size()); |
406 | | } |
407 | | |
408 | | return BuildObjCStringLiteral(AtLocs[0], S); |
409 | | } |
410 | | |
411 | | ExprResult Sema::BuildObjCStringLiteral(SourceLocation AtLoc, StringLiteral *S){ |
412 | | // Verify that this composite string is acceptable for ObjC strings. |
413 | | if (CheckObjCString(S)) |
414 | | return true; |
415 | | |
416 | | // Initialize the constant string interface lazily. This assumes |
417 | | // the NSString interface is seen in this translation unit. Note: We |
418 | | // don't use NSConstantString, since the runtime team considers this |
419 | | // interface private (even though it appears in the header files). |
420 | | QualType Ty = Context.getObjCConstantStringInterface(); |
421 | | if (!Ty.isNull()) { |
422 | | Ty = Context.getObjCObjectPointerType(Ty); |
423 | | } else if (getLangOpts().NoConstantCFStrings) { |
424 | | IdentifierInfo *NSIdent=nullptr; |
425 | | std::string StringClass(getLangOpts().ObjCConstantStringClass); |
426 | | |
427 | | if (StringClass.empty()) |
428 | | NSIdent = &Context.Idents.get("NSConstantString"); |
429 | | else |
430 | | NSIdent = &Context.Idents.get(StringClass); |
431 | | |
432 | | NamedDecl *IF = LookupSingleName(TUScope, NSIdent, AtLoc, |
433 | | LookupOrdinaryName); |
434 | | if (ObjCInterfaceDecl *StrIF = dyn_cast_or_null<ObjCInterfaceDecl>(IF)) { |
435 | | Context.setObjCConstantStringInterface(StrIF); |
436 | | Ty = Context.getObjCConstantStringInterface(); |
437 | | Ty = Context.getObjCObjectPointerType(Ty); |
438 | | } else { |
439 | | // If there is no NSConstantString interface defined then treat this |
440 | | // as error and recover from it. |
441 | | Diag(S->getLocStart(), diag::err_no_nsconstant_string_class) << NSIdent |
442 | | << S->getSourceRange(); |
443 | | Ty = Context.getObjCIdType(); |
444 | | } |
445 | | } else { |
446 | | IdentifierInfo *NSIdent = NSAPIObj->getNSClassId(NSAPI::ClassId_NSString); |
447 | | NamedDecl *IF = LookupSingleName(TUScope, NSIdent, AtLoc, |
448 | | LookupOrdinaryName); |
449 | | if (ObjCInterfaceDecl *StrIF = dyn_cast_or_null<ObjCInterfaceDecl>(IF)) { |
450 | | Context.setObjCConstantStringInterface(StrIF); |
451 | | Ty = Context.getObjCConstantStringInterface(); |
452 | | Ty = Context.getObjCObjectPointerType(Ty); |
453 | | } else { |
454 | | // If there is no NSString interface defined, implicitly declare |
455 | | // a @class NSString; and use that instead. This is to make sure |
456 | | // type of an NSString literal is represented correctly, instead of |
457 | | // being an 'id' type. |
458 | | Ty = Context.getObjCNSStringType(); |
459 | | if (Ty.isNull()) { |
460 | | ObjCInterfaceDecl *NSStringIDecl = |
461 | | ObjCInterfaceDecl::Create (Context, |
462 | | Context.getTranslationUnitDecl(), |
463 | | SourceLocation(), NSIdent, |
464 | | nullptr, nullptr, SourceLocation()); |
465 | | Ty = Context.getObjCInterfaceType(NSStringIDecl); |
466 | | Context.setObjCNSStringType(Ty); |
467 | | } |
468 | | Ty = Context.getObjCObjectPointerType(Ty); |
469 | | } |
470 | | } |
471 | | |
472 | | return new (Context) ObjCStringLiteral(S, Ty, AtLoc); |
473 | | } |
474 | | |
475 | | /// \brief Emits an error if the given method does not exist, or if the return |
476 | | /// type is not an Objective-C object. |
477 | | static bool validateBoxingMethod(Sema &S, SourceLocation Loc, |
478 | | const ObjCInterfaceDecl *Class, |
479 | | Selector Sel, const ObjCMethodDecl *Method) { |
480 | | if (!Method) { |
481 | | // FIXME: Is there a better way to avoid quotes than using getName()? |
482 | | S.Diag(Loc, diag::err_undeclared_boxing_method) << Sel << Class->getName(); |
483 | | return false; |
484 | | } |
485 | | |
486 | | // Make sure the return type is reasonable. |
487 | | QualType ReturnType = Method->getReturnType(); |
488 | | if (!ReturnType->isObjCObjectPointerType()) { |
489 | | S.Diag(Loc, diag::err_objc_literal_method_sig) |
490 | | << Sel; |
491 | | S.Diag(Method->getLocation(), diag::note_objc_literal_method_return) |
492 | | << ReturnType; |
493 | | return false; |
494 | | } |
495 | | |
496 | | return true; |
497 | | } |
498 | | |
499 | | /// \brief Retrieve the NSNumber factory method that should be used to create |
500 | | /// an Objective-C literal for the given type. |
501 | | static ObjCMethodDecl *getNSNumberFactoryMethod(Sema &S, SourceLocation Loc, |
502 | | QualType NumberType, |
503 | | bool isLiteral = false, |
504 | | SourceRange R = SourceRange()) { |
505 | | Optional<NSAPI::NSNumberLiteralMethodKind> Kind = |
506 | | S.NSAPIObj->getNSNumberFactoryMethodKind(NumberType); |
507 | | |
508 | | if (!Kind) { |
509 | | if (isLiteral) { |
510 | | S.Diag(Loc, diag::err_invalid_nsnumber_type) |
511 | | << NumberType << R; |
512 | | } |
513 | | return nullptr; |
514 | | } |
515 | | |
516 | | // If we already looked up this method, we're done. |
517 | | if (S.NSNumberLiteralMethods[*Kind]) |
518 | | return S.NSNumberLiteralMethods[*Kind]; |
519 | | |
520 | | Selector Sel = S.NSAPIObj->getNSNumberLiteralSelector(*Kind, |
521 | | /*Instance=*/false); |
522 | | |
523 | | ASTContext &CX = S.Context; |
524 | | |
525 | | // Look up the NSNumber class, if we haven't done so already. It's cached |
526 | | // in the Sema instance. |
527 | | if (!S.NSNumberDecl) { |
528 | | IdentifierInfo *NSNumberId = |
529 | | S.NSAPIObj->getNSClassId(NSAPI::ClassId_NSNumber); |
530 | | NamedDecl *IF = S.LookupSingleName(S.TUScope, NSNumberId, |
531 | | Loc, Sema::LookupOrdinaryName); |
532 | | S.NSNumberDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF); |
533 | | if (!S.NSNumberDecl) { |
534 | | if (S.getLangOpts().DebuggerObjCLiteral) { |
535 | | // Create a stub definition of NSNumber. |
536 | | S.NSNumberDecl = ObjCInterfaceDecl::Create(CX, |
537 | | CX.getTranslationUnitDecl(), |
538 | | SourceLocation(), NSNumberId, |
539 | | nullptr, nullptr, |
540 | | SourceLocation()); |
541 | | } else { |
542 | | // Otherwise, require a declaration of NSNumber. |
543 | | S.Diag(Loc, diag::err_undeclared_nsnumber); |
544 | | return nullptr; |
545 | | } |
546 | | } else if (!S.NSNumberDecl->hasDefinition()) { |
547 | | S.Diag(Loc, diag::err_undeclared_nsnumber); |
548 | | return nullptr; |
549 | | } |
550 | | } |
551 | | |
552 | | if (S.NSNumberPointer.isNull()) { |
553 | | // generate the pointer to NSNumber type. |
554 | | QualType NSNumberObject = CX.getObjCInterfaceType(S.NSNumberDecl); |
555 | | S.NSNumberPointer = CX.getObjCObjectPointerType(NSNumberObject); |
556 | | } |
557 | | |
558 | | // Look for the appropriate method within NSNumber. |
559 | | ObjCMethodDecl *Method = S.NSNumberDecl->lookupClassMethod(Sel); |
560 | | if (!Method && S.getLangOpts().DebuggerObjCLiteral) { |
561 | | // create a stub definition this NSNumber factory method. |
562 | | TypeSourceInfo *ReturnTInfo = nullptr; |
563 | | Method = |
564 | | ObjCMethodDecl::Create(CX, SourceLocation(), SourceLocation(), Sel, |
565 | | S.NSNumberPointer, ReturnTInfo, S.NSNumberDecl, |
566 | | /*isInstance=*/false, /*isVariadic=*/false, |
567 | | /*isPropertyAccessor=*/false, |
568 | | /*isImplicitlyDeclared=*/true, |
569 | | /*isDefined=*/false, ObjCMethodDecl::Required, |
570 | | /*HasRelatedResultType=*/false); |
571 | | ParmVarDecl *value = ParmVarDecl::Create(S.Context, Method, |
572 | | SourceLocation(), SourceLocation(), |
573 | | &CX.Idents.get("value"), |
574 | | NumberType, /*TInfo=*/nullptr, |
575 | | SC_None, nullptr); |
576 | | Method->setMethodParams(S.Context, value, None); |
577 | | } |
578 | | |
579 | | if (!validateBoxingMethod(S, Loc, S.NSNumberDecl, Sel, Method)) |
580 | | return nullptr; |
581 | | |
582 | | // Note: if the parameter type is out-of-line, we'll catch it later in the |
583 | | // implicit conversion. |
584 | | |
585 | | S.NSNumberLiteralMethods[*Kind] = Method; |
586 | | return Method; |
587 | | } |
588 | | |
589 | | /// BuildObjCNumericLiteral - builds an ObjCBoxedExpr AST node for the |
590 | | /// numeric literal expression. Type of the expression will be "NSNumber *". |
591 | | ExprResult Sema::BuildObjCNumericLiteral(SourceLocation AtLoc, Expr *Number) { |
592 | | // Determine the type of the literal. |
593 | | QualType NumberType = Number->getType(); |
594 | | if (CharacterLiteral *Char = dyn_cast<CharacterLiteral>(Number)) { |
595 | | // In C, character literals have type 'int'. That's not the type we want |
596 | | // to use to determine the Objective-c literal kind. |
597 | | switch (Char->getKind()) { |
598 | | case CharacterLiteral::Ascii: |
599 | | NumberType = Context.CharTy; |
600 | | break; |
601 | | |
602 | | case CharacterLiteral::Wide: |
603 | | NumberType = Context.getWideCharType(); |
604 | | break; |
605 | | |
606 | | case CharacterLiteral::UTF16: |
607 | | NumberType = Context.Char16Ty; |
608 | | break; |
609 | | |
610 | | case CharacterLiteral::UTF32: |
611 | | NumberType = Context.Char32Ty; |
612 | | break; |
613 | | } |
614 | | } |
615 | | |
616 | | // Look for the appropriate method within NSNumber. |
617 | | // Construct the literal. |
618 | | SourceRange NR(Number->getSourceRange()); |
619 | | ObjCMethodDecl *Method = getNSNumberFactoryMethod(*this, AtLoc, NumberType, |
620 | | true, NR); |
621 | | if (!Method) |
622 | | return ExprError(); |
623 | | |
624 | | // Convert the number to the type that the parameter expects. |
625 | | ParmVarDecl *ParamDecl = Method->parameters()[0]; |
626 | | InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, |
627 | | ParamDecl); |
628 | | ExprResult ConvertedNumber = PerformCopyInitialization(Entity, |
629 | | SourceLocation(), |
630 | | Number); |
631 | | if (ConvertedNumber.isInvalid()) |
632 | | return ExprError(); |
633 | | Number = ConvertedNumber.get(); |
634 | | |
635 | | // Use the effective source range of the literal, including the leading '@'. |
636 | | return MaybeBindToTemporary( |
637 | | new (Context) ObjCBoxedExpr(Number, NSNumberPointer, Method, |
638 | | SourceRange(AtLoc, NR.getEnd()))); |
639 | | } |
640 | | |
641 | | ExprResult Sema::ActOnObjCBoolLiteral(SourceLocation AtLoc, |
642 | | SourceLocation ValueLoc, |
643 | | bool Value) { |
644 | | ExprResult Inner; |
645 | | if (getLangOpts().CPlusPlus) { |
646 | | Inner = ActOnCXXBoolLiteral(ValueLoc, Value? tok::kw_true : tok::kw_false); |
647 | | } else { |
648 | | // C doesn't actually have a way to represent literal values of type |
649 | | // _Bool. So, we'll use 0/1 and implicit cast to _Bool. |
650 | | Inner = ActOnIntegerConstant(ValueLoc, Value? 1 : 0); |
651 | | Inner = ImpCastExprToType(Inner.get(), Context.BoolTy, |
652 | | CK_IntegralToBoolean); |
653 | | } |
654 | | |
655 | | return BuildObjCNumericLiteral(AtLoc, Inner.get()); |
656 | | } |
657 | | |
658 | | /// \brief Check that the given expression is a valid element of an Objective-C |
659 | | /// collection literal. |
660 | | static ExprResult CheckObjCCollectionLiteralElement(Sema &S, Expr *Element, |
661 | | QualType T, |
662 | | bool ArrayLiteral = false) { |
663 | | // If the expression is type-dependent, there's nothing for us to do. |
664 | | if (Element->isTypeDependent()) |
665 | | return Element; |
666 | | |
667 | | ExprResult Result = S.CheckPlaceholderExpr(Element); |
668 | | if (Result.isInvalid()) |
669 | | return ExprError(); |
670 | | Element = Result.get(); |
671 | | |
672 | | // In C++, check for an implicit conversion to an Objective-C object pointer |
673 | | // type. |
674 | | if (S.getLangOpts().CPlusPlus && Element->getType()->isRecordType()) { |
675 | | InitializedEntity Entity |
676 | | = InitializedEntity::InitializeParameter(S.Context, T, |
677 | | /*Consumed=*/false); |
678 | | InitializationKind Kind |
679 | | = InitializationKind::CreateCopy(Element->getLocStart(), |
680 | | SourceLocation()); |
681 | | InitializationSequence Seq(S, Entity, Kind, Element); |
682 | | if (!Seq.Failed()) |
683 | | return Seq.Perform(S, Entity, Kind, Element); |
684 | | } |
685 | | |
686 | | Expr *OrigElement = Element; |
687 | | |
688 | | // Perform lvalue-to-rvalue conversion. |
689 | | Result = S.DefaultLvalueConversion(Element); |
690 | | if (Result.isInvalid()) |
691 | | return ExprError(); |
692 | | Element = Result.get(); |
693 | | |
694 | | // Make sure that we have an Objective-C pointer type or block. |
695 | | if (!Element->getType()->isObjCObjectPointerType() && |
696 | | !Element->getType()->isBlockPointerType()) { |
697 | | bool Recovered = false; |
698 | | |
699 | | // If this is potentially an Objective-C numeric literal, add the '@'. |
700 | | if (isa<IntegerLiteral>(OrigElement) || |
701 | | isa<CharacterLiteral>(OrigElement) || |
702 | | isa<FloatingLiteral>(OrigElement) || |
703 | | isa<ObjCBoolLiteralExpr>(OrigElement) || |
704 | | isa<CXXBoolLiteralExpr>(OrigElement)) { |
705 | | if (S.NSAPIObj->getNSNumberFactoryMethodKind(OrigElement->getType())) { |
706 | | int Which = isa<CharacterLiteral>(OrigElement) ? 1 |
707 | | : (isa<CXXBoolLiteralExpr>(OrigElement) || |
708 | | isa<ObjCBoolLiteralExpr>(OrigElement)) ? 2 |
709 | | : 3; |
710 | | |
711 | | S.Diag(OrigElement->getLocStart(), diag::err_box_literal_collection) |
712 | | << Which << OrigElement->getSourceRange() |
713 | | << FixItHint::CreateInsertion(OrigElement->getLocStart(), "@"); |
714 | | |
715 | | Result = S.BuildObjCNumericLiteral(OrigElement->getLocStart(), |
716 | | OrigElement); |
717 | | if (Result.isInvalid()) |
718 | | return ExprError(); |
719 | | |
720 | | Element = Result.get(); |
721 | | Recovered = true; |
722 | | } |
723 | | } |
724 | | // If this is potentially an Objective-C string literal, add the '@'. |
725 | | else if (StringLiteral *String = dyn_cast<StringLiteral>(OrigElement)) { |
726 | | if (String->isAscii()) { |
727 | | S.Diag(OrigElement->getLocStart(), diag::err_box_literal_collection) |
728 | | << 0 << OrigElement->getSourceRange() |
729 | | << FixItHint::CreateInsertion(OrigElement->getLocStart(), "@"); |
730 | | |
731 | | Result = S.BuildObjCStringLiteral(OrigElement->getLocStart(), String); |
732 | | if (Result.isInvalid()) |
733 | | return ExprError(); |
734 | | |
735 | | Element = Result.get(); |
736 | | Recovered = true; |
737 | | } |
738 | | } |
739 | | |
740 | | if (!Recovered) { |
741 | | S.Diag(Element->getLocStart(), diag::err_invalid_collection_element) |
742 | | << Element->getType(); |
743 | | return ExprError(); |
744 | | } |
745 | | } |
746 | | if (ArrayLiteral) |
747 | | if (ObjCStringLiteral *getString = |
748 | | dyn_cast<ObjCStringLiteral>(OrigElement)) { |
749 | | if (StringLiteral *SL = getString->getString()) { |
750 | | unsigned numConcat = SL->getNumConcatenated(); |
751 | | if (numConcat > 1) { |
752 | | // Only warn if the concatenated string doesn't come from a macro. |
753 | | bool hasMacro = false; |
754 | | for (unsigned i = 0; i < numConcat ; ++i) |
755 | | if (SL->getStrTokenLoc(i).isMacroID()) { |
756 | | hasMacro = true; |
757 | | break; |
758 | | } |
759 | | if (!hasMacro) |
760 | | S.Diag(Element->getLocStart(), |
761 | | diag::warn_concatenated_nsarray_literal) |
762 | | << Element->getType(); |
763 | | } |
764 | | } |
765 | | } |
766 | | |
767 | | // Make sure that the element has the type that the container factory |
768 | | // function expects. |
769 | | return S.PerformCopyInitialization( |
770 | | InitializedEntity::InitializeParameter(S.Context, T, |
771 | | /*Consumed=*/false), |
772 | | Element->getLocStart(), Element); |
773 | | } |
774 | | |
775 | | ExprResult Sema::BuildObjCBoxedExpr(SourceRange SR, Expr *ValueExpr) { |
776 | | if (ValueExpr->isTypeDependent()) { |
777 | | ObjCBoxedExpr *BoxedExpr = |
778 | | new (Context) ObjCBoxedExpr(ValueExpr, Context.DependentTy, nullptr, SR); |
779 | | return BoxedExpr; |
780 | | } |
781 | | ObjCMethodDecl *BoxingMethod = nullptr; |
782 | | QualType BoxedType; |
783 | | // Convert the expression to an RValue, so we can check for pointer types... |
784 | | ExprResult RValue = DefaultFunctionArrayLvalueConversion(ValueExpr); |
785 | | if (RValue.isInvalid()) { |
786 | | return ExprError(); |
787 | | } |
788 | | ValueExpr = RValue.get(); |
789 | | QualType ValueType(ValueExpr->getType()); |
790 | | if (const PointerType *PT = ValueType->getAs<PointerType>()) { |
791 | | QualType PointeeType = PT->getPointeeType(); |
792 | | if (Context.hasSameUnqualifiedType(PointeeType, Context.CharTy)) { |
793 | | |
794 | | if (!NSStringDecl) { |
795 | | IdentifierInfo *NSStringId = |
796 | | NSAPIObj->getNSClassId(NSAPI::ClassId_NSString); |
797 | | NamedDecl *Decl = LookupSingleName(TUScope, NSStringId, |
798 | | SR.getBegin(), LookupOrdinaryName); |
799 | | NSStringDecl = dyn_cast_or_null<ObjCInterfaceDecl>(Decl); |
800 | | if (!NSStringDecl) { |
801 | | if (getLangOpts().DebuggerObjCLiteral) { |
802 | | // Support boxed expressions in the debugger w/o NSString declaration. |
803 | | DeclContext *TU = Context.getTranslationUnitDecl(); |
804 | | NSStringDecl = ObjCInterfaceDecl::Create(Context, TU, |
805 | | SourceLocation(), |
806 | | NSStringId, |
807 | | nullptr, nullptr, |
808 | | SourceLocation()); |
809 | | } else { |
810 | | Diag(SR.getBegin(), diag::err_undeclared_nsstring); |
811 | | return ExprError(); |
812 | | } |
813 | | } else if (!NSStringDecl->hasDefinition()) { |
814 | | Diag(SR.getBegin(), diag::err_undeclared_nsstring); |
815 | | return ExprError(); |
816 | | } |
817 | | assert(NSStringDecl && "NSStringDecl should not be NULL"); |
818 | | QualType NSStringObject = Context.getObjCInterfaceType(NSStringDecl); |
819 | | NSStringPointer = Context.getObjCObjectPointerType(NSStringObject); |
820 | | } |
821 | | |
822 | | if (!StringWithUTF8StringMethod) { |
823 | | IdentifierInfo *II = &Context.Idents.get("stringWithUTF8String"); |
824 | | Selector stringWithUTF8String = Context.Selectors.getUnarySelector(II); |
825 | | |
826 | | // Look for the appropriate method within NSString. |
827 | | BoxingMethod = NSStringDecl->lookupClassMethod(stringWithUTF8String); |
828 | | if (!BoxingMethod && getLangOpts().DebuggerObjCLiteral) { |
829 | | // Debugger needs to work even if NSString hasn't been defined. |
830 | | TypeSourceInfo *ReturnTInfo = nullptr; |
831 | | ObjCMethodDecl *M = ObjCMethodDecl::Create( |
832 | | Context, SourceLocation(), SourceLocation(), stringWithUTF8String, |
833 | | NSStringPointer, ReturnTInfo, NSStringDecl, |
834 | | /*isInstance=*/false, /*isVariadic=*/false, |
835 | | /*isPropertyAccessor=*/false, |
836 | | /*isImplicitlyDeclared=*/true, |
837 | | /*isDefined=*/false, ObjCMethodDecl::Required, |
838 | | /*HasRelatedResultType=*/false); |
839 | | QualType ConstCharType = Context.CharTy.withConst(); |
840 | | ParmVarDecl *value = |
841 | | ParmVarDecl::Create(Context, M, |
842 | | SourceLocation(), SourceLocation(), |
843 | | &Context.Idents.get("value"), |
844 | | Context.getPointerType(ConstCharType), |
845 | | /*TInfo=*/nullptr, |
846 | | SC_None, nullptr); |
847 | | M->setMethodParams(Context, value, None); |
848 | | BoxingMethod = M; |
849 | | } |
850 | | |
851 | | if (!validateBoxingMethod(*this, SR.getBegin(), NSStringDecl, |
852 | | stringWithUTF8String, BoxingMethod)) |
853 | | return ExprError(); |
854 | | |
855 | | StringWithUTF8StringMethod = BoxingMethod; |
856 | | } |
857 | | |
858 | | BoxingMethod = StringWithUTF8StringMethod; |
859 | | BoxedType = NSStringPointer; |
860 | | } |
861 | | } else if (ValueType->isBuiltinType()) { |
862 | | // The other types we support are numeric, char and BOOL/bool. We could also |
863 | | // provide limited support for structure types, such as NSRange, NSRect, and |
864 | | // NSSize. See NSValue (NSValueGeometryExtensions) in <Foundation/NSGeometry.h> |
865 | | // for more details. |
866 | | |
867 | | // Check for a top-level character literal. |
868 | | if (const CharacterLiteral *Char = |
869 | | dyn_cast<CharacterLiteral>(ValueExpr->IgnoreParens())) { |
870 | | // In C, character literals have type 'int'. That's not the type we want |
871 | | // to use to determine the Objective-c literal kind. |
872 | | switch (Char->getKind()) { |
873 | | case CharacterLiteral::Ascii: |
874 | | ValueType = Context.CharTy; |
875 | | break; |
876 | | |
877 | | case CharacterLiteral::Wide: |
878 | | ValueType = Context.getWideCharType(); |
879 | | break; |
880 | | |
881 | | case CharacterLiteral::UTF16: |
882 | | ValueType = Context.Char16Ty; |
883 | | break; |
884 | | |
885 | | case CharacterLiteral::UTF32: |
886 | | ValueType = Context.Char32Ty; |
887 | | break; |
888 | | } |
889 | | } |
890 | | CheckForIntOverflow(ValueExpr); |
891 | | // FIXME: Do I need to do anything special with BoolTy expressions? |
892 | | |
893 | | // Look for the appropriate method within NSNumber. |
894 | | BoxingMethod = getNSNumberFactoryMethod(*this, SR.getBegin(), ValueType); |
895 | | BoxedType = NSNumberPointer; |
896 | | } else if (const EnumType *ET = ValueType->getAs<EnumType>()) { |
897 | | if (!ET->getDecl()->isComplete()) { |
898 | | Diag(SR.getBegin(), diag::err_objc_incomplete_boxed_expression_type) |
899 | | << ValueType << ValueExpr->getSourceRange(); |
900 | | return ExprError(); |
901 | | } |
902 | | |
903 | | BoxingMethod = getNSNumberFactoryMethod(*this, SR.getBegin(), |
904 | | ET->getDecl()->getIntegerType()); |
905 | | BoxedType = NSNumberPointer; |
906 | | } else if (ValueType->isObjCBoxableRecordType()) { |
907 | | // Support for structure types, that marked as objc_boxable |
908 | | // struct __attribute__((objc_boxable)) s { ... }; |
909 | | |
910 | | // Look up the NSValue class, if we haven't done so already. It's cached |
911 | | // in the Sema instance. |
912 | | if (!NSValueDecl) { |
913 | | IdentifierInfo *NSValueId = |
914 | | NSAPIObj->getNSClassId(NSAPI::ClassId_NSValue); |
915 | | NamedDecl *IF = LookupSingleName(TUScope, NSValueId, |
916 | | SR.getBegin(), Sema::LookupOrdinaryName); |
917 | | NSValueDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF); |
918 | | if (!NSValueDecl) { |
919 | | if (getLangOpts().DebuggerObjCLiteral) { |
920 | | // Create a stub definition of NSValue. |
921 | | DeclContext *TU = Context.getTranslationUnitDecl(); |
922 | | NSValueDecl = ObjCInterfaceDecl::Create(Context, TU, |
923 | | SourceLocation(), NSValueId, |
924 | | nullptr, nullptr, |
925 | | SourceLocation()); |
926 | | } else { |
927 | | // Otherwise, require a declaration of NSValue. |
928 | | Diag(SR.getBegin(), diag::err_undeclared_nsvalue); |
929 | | return ExprError(); |
930 | | } |
931 | | } else if (!NSValueDecl->hasDefinition()) { |
932 | | Diag(SR.getBegin(), diag::err_undeclared_nsvalue); |
933 | | return ExprError(); |
934 | | } |
935 | | |
936 | | // generate the pointer to NSValue type. |
937 | | QualType NSValueObject = Context.getObjCInterfaceType(NSValueDecl); |
938 | | NSValuePointer = Context.getObjCObjectPointerType(NSValueObject); |
939 | | } |
940 | | |
941 | | if (!ValueWithBytesObjCTypeMethod) { |
942 | | IdentifierInfo *II[] = { |
943 | | &Context.Idents.get("valueWithBytes"), |
944 | | &Context.Idents.get("objCType") |
945 | | }; |
946 | | Selector ValueWithBytesObjCType = Context.Selectors.getSelector(2, II); |
947 | | |
948 | | // Look for the appropriate method within NSValue. |
949 | | BoxingMethod = NSValueDecl->lookupClassMethod(ValueWithBytesObjCType); |
950 | | if (!BoxingMethod && getLangOpts().DebuggerObjCLiteral) { |
951 | | // Debugger needs to work even if NSValue hasn't been defined. |
952 | | TypeSourceInfo *ReturnTInfo = nullptr; |
953 | | ObjCMethodDecl *M = ObjCMethodDecl::Create( |
954 | | Context, |
955 | | SourceLocation(), |
956 | | SourceLocation(), |
957 | | ValueWithBytesObjCType, |
958 | | NSValuePointer, |
959 | | ReturnTInfo, |
960 | | NSValueDecl, |
961 | | /*isInstance=*/false, |
962 | | /*isVariadic=*/false, |
963 | | /*isPropertyAccessor=*/false, |
964 | | /*isImplicitlyDeclared=*/true, |
965 | | /*isDefined=*/false, |
966 | | ObjCMethodDecl::Required, |
967 | | /*HasRelatedResultType=*/false); |
968 | | |
969 | | SmallVector<ParmVarDecl *, 2> Params; |
970 | | |
971 | | ParmVarDecl *bytes = |
972 | | ParmVarDecl::Create(Context, M, |
973 | | SourceLocation(), SourceLocation(), |
974 | | &Context.Idents.get("bytes"), |
975 | | Context.VoidPtrTy.withConst(), |
976 | | /*TInfo=*/nullptr, |
977 | | SC_None, nullptr); |
978 | | Params.push_back(bytes); |
979 | | |
980 | | QualType ConstCharType = Context.CharTy.withConst(); |
981 | | ParmVarDecl *type = |
982 | | ParmVarDecl::Create(Context, M, |
983 | | SourceLocation(), SourceLocation(), |
984 | | &Context.Idents.get("type"), |
985 | | Context.getPointerType(ConstCharType), |
986 | | /*TInfo=*/nullptr, |
987 | | SC_None, nullptr); |
988 | | Params.push_back(type); |
989 | | |
990 | | M->setMethodParams(Context, Params, None); |
991 | | BoxingMethod = M; |
992 | | } |
993 | | |
994 | | if (!validateBoxingMethod(*this, SR.getBegin(), NSValueDecl, |
995 | | ValueWithBytesObjCType, BoxingMethod)) |
996 | | return ExprError(); |
997 | | |
998 | | ValueWithBytesObjCTypeMethod = BoxingMethod; |
999 | | } |
1000 | | |
1001 | | if (!ValueType.isTriviallyCopyableType(Context)) { |
1002 | | Diag(SR.getBegin(), |
1003 | | diag::err_objc_non_trivially_copyable_boxed_expression_type) |
1004 | | << ValueType << ValueExpr->getSourceRange(); |
1005 | | return ExprError(); |
1006 | | } |
1007 | | |
1008 | | BoxingMethod = ValueWithBytesObjCTypeMethod; |
1009 | | BoxedType = NSValuePointer; |
1010 | | } |
1011 | | |
1012 | | if (!BoxingMethod) { |
1013 | | Diag(SR.getBegin(), diag::err_objc_illegal_boxed_expression_type) |
1014 | | << ValueType << ValueExpr->getSourceRange(); |
1015 | | return ExprError(); |
1016 | | } |
1017 | | |
1018 | | DiagnoseUseOfDecl(BoxingMethod, SR.getBegin()); |
1019 | | |
1020 | | ExprResult ConvertedValueExpr; |
1021 | | if (ValueType->isObjCBoxableRecordType()) { |
1022 | | InitializedEntity IE = InitializedEntity::InitializeTemporary(ValueType); |
1023 | | ConvertedValueExpr = PerformCopyInitialization(IE, ValueExpr->getExprLoc(), |
1024 | | ValueExpr); |
1025 | | } else { |
1026 | | // Convert the expression to the type that the parameter requires. |
1027 | | ParmVarDecl *ParamDecl = BoxingMethod->parameters()[0]; |
1028 | | InitializedEntity IE = InitializedEntity::InitializeParameter(Context, |
1029 | | ParamDecl); |
1030 | | ConvertedValueExpr = PerformCopyInitialization(IE, SourceLocation(), |
1031 | | ValueExpr); |
1032 | | } |
1033 | | |
1034 | | if (ConvertedValueExpr.isInvalid()) |
1035 | | return ExprError(); |
1036 | | ValueExpr = ConvertedValueExpr.get(); |
1037 | | |
1038 | | ObjCBoxedExpr *BoxedExpr = |
1039 | | new (Context) ObjCBoxedExpr(ValueExpr, BoxedType, |
1040 | | BoxingMethod, SR); |
1041 | | return MaybeBindToTemporary(BoxedExpr); |
1042 | | } |
1043 | | |
1044 | | /// Build an ObjC subscript pseudo-object expression, given that |
1045 | | /// that's supported by the runtime. |
1046 | | ExprResult Sema::BuildObjCSubscriptExpression(SourceLocation RB, Expr *BaseExpr, |
1047 | | Expr *IndexExpr, |
1048 | | ObjCMethodDecl *getterMethod, |
1049 | | ObjCMethodDecl *setterMethod) { |
1050 | | assert(!LangOpts.isSubscriptPointerArithmetic()); |
1051 | | |
1052 | | // We can't get dependent types here; our callers should have |
1053 | | // filtered them out. |
1054 | | assert((!BaseExpr->isTypeDependent() && !IndexExpr->isTypeDependent()) && |
1055 | | "base or index cannot have dependent type here"); |
1056 | | |
1057 | | // Filter out placeholders in the index. In theory, overloads could |
1058 | | // be preserved here, although that might not actually work correctly. |
1059 | | ExprResult Result = CheckPlaceholderExpr(IndexExpr); |
1060 | | if (Result.isInvalid()) |
1061 | | return ExprError(); |
1062 | | IndexExpr = Result.get(); |
1063 | | |
1064 | | // Perform lvalue-to-rvalue conversion on the base. |
1065 | | Result = DefaultLvalueConversion(BaseExpr); |
1066 | | if (Result.isInvalid()) |
1067 | | return ExprError(); |
1068 | | BaseExpr = Result.get(); |
1069 | | |
1070 | | // Build the pseudo-object expression. |
1071 | | return ObjCSubscriptRefExpr::Create(Context, BaseExpr, IndexExpr, |
1072 | | Context.PseudoObjectTy, getterMethod, |
1073 | | setterMethod, RB); |
1074 | | } |
1075 | | |
1076 | | ExprResult Sema::BuildObjCArrayLiteral(SourceRange SR, MultiExprArg Elements) { |
1077 | | // Look up the NSArray class, if we haven't done so already. |
1078 | | if (!NSArrayDecl) { |
1079 | | NamedDecl *IF = LookupSingleName(TUScope, |
1080 | | NSAPIObj->getNSClassId(NSAPI::ClassId_NSArray), |
1081 | | SR.getBegin(), |
1082 | | LookupOrdinaryName); |
1083 | | NSArrayDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF); |
1084 | | if (!NSArrayDecl && getLangOpts().DebuggerObjCLiteral) |
1085 | | NSArrayDecl = ObjCInterfaceDecl::Create (Context, |
1086 | | Context.getTranslationUnitDecl(), |
1087 | | SourceLocation(), |
1088 | | NSAPIObj->getNSClassId(NSAPI::ClassId_NSArray), |
1089 | | nullptr, nullptr, SourceLocation()); |
1090 | | |
1091 | | if (!NSArrayDecl) { |
1092 | | Diag(SR.getBegin(), diag::err_undeclared_nsarray); |
1093 | | return ExprError(); |
1094 | | } |
1095 | | } |
1096 | | |
1097 | | // Find the arrayWithObjects:count: method, if we haven't done so already. |
1098 | | QualType IdT = Context.getObjCIdType(); |
1099 | | if (!ArrayWithObjectsMethod) { |
1100 | | Selector |
1101 | | Sel = NSAPIObj->getNSArraySelector(NSAPI::NSArr_arrayWithObjectsCount); |
1102 | | ObjCMethodDecl *Method = NSArrayDecl->lookupClassMethod(Sel); |
1103 | | if (!Method && getLangOpts().DebuggerObjCLiteral) { |
1104 | | TypeSourceInfo *ReturnTInfo = nullptr; |
1105 | | Method = ObjCMethodDecl::Create( |
1106 | | Context, SourceLocation(), SourceLocation(), Sel, IdT, ReturnTInfo, |
1107 | | Context.getTranslationUnitDecl(), false /*Instance*/, |
1108 | | false /*isVariadic*/, |
1109 | | /*isPropertyAccessor=*/false, |
1110 | | /*isImplicitlyDeclared=*/true, /*isDefined=*/false, |
1111 | | ObjCMethodDecl::Required, false); |
1112 | | SmallVector<ParmVarDecl *, 2> Params; |
1113 | | ParmVarDecl *objects = ParmVarDecl::Create(Context, Method, |
1114 | | SourceLocation(), |
1115 | | SourceLocation(), |
1116 | | &Context.Idents.get("objects"), |
1117 | | Context.getPointerType(IdT), |
1118 | | /*TInfo=*/nullptr, |
1119 | | SC_None, nullptr); |
1120 | | Params.push_back(objects); |
1121 | | ParmVarDecl *cnt = ParmVarDecl::Create(Context, Method, |
1122 | | SourceLocation(), |
1123 | | SourceLocation(), |
1124 | | &Context.Idents.get("cnt"), |
1125 | | Context.UnsignedLongTy, |
1126 | | /*TInfo=*/nullptr, SC_None, |
1127 | | nullptr); |
1128 | | Params.push_back(cnt); |
1129 | | Method->setMethodParams(Context, Params, None); |
1130 | | } |
1131 | | |
1132 | | if (!validateBoxingMethod(*this, SR.getBegin(), NSArrayDecl, Sel, Method)) |
1133 | | return ExprError(); |
1134 | | |
1135 | | // Dig out the type that all elements should be converted to. |
1136 | | QualType T = Method->parameters()[0]->getType(); |
1137 | | const PointerType *PtrT = T->getAs<PointerType>(); |
1138 | | if (!PtrT || |
1139 | | !Context.hasSameUnqualifiedType(PtrT->getPointeeType(), IdT)) { |
1140 | | Diag(SR.getBegin(), diag::err_objc_literal_method_sig) |
1141 | | << Sel; |
1142 | | Diag(Method->parameters()[0]->getLocation(), |
1143 | | diag::note_objc_literal_method_param) |
1144 | | << 0 << T |
1145 | | << Context.getPointerType(IdT.withConst()); |
1146 | | return ExprError(); |
1147 | | } |
1148 | | |
1149 | | // Check that the 'count' parameter is integral. |
1150 | | if (!Method->parameters()[1]->getType()->isIntegerType()) { |
1151 | | Diag(SR.getBegin(), diag::err_objc_literal_method_sig) |
1152 | | << Sel; |
1153 | | Diag(Method->parameters()[1]->getLocation(), |
1154 | | diag::note_objc_literal_method_param) |
1155 | | << 1 |
1156 | | << Method->parameters()[1]->getType() |
1157 | | << "integral"; |
1158 | | return ExprError(); |
1159 | | } |
1160 | | |
1161 | | // We've found a good +arrayWithObjects:count: method. Save it! |
1162 | | ArrayWithObjectsMethod = Method; |
1163 | | } |
1164 | | |
1165 | | QualType ObjectsType = ArrayWithObjectsMethod->parameters()[0]->getType(); |
1166 | | QualType RequiredType = ObjectsType->castAs<PointerType>()->getPointeeType(); |
1167 | | |
1168 | | // Check that each of the elements provided is valid in a collection literal, |
1169 | | // performing conversions as necessary. |
1170 | | Expr **ElementsBuffer = Elements.data(); |
1171 | | for (unsigned I = 0, N = Elements.size(); I != N; ++I) { |
1172 | | ExprResult Converted = CheckObjCCollectionLiteralElement(*this, |
1173 | | ElementsBuffer[I], |
1174 | | RequiredType, true); |
1175 | | if (Converted.isInvalid()) |
1176 | | return ExprError(); |
1177 | | |
1178 | | ElementsBuffer[I] = Converted.get(); |
1179 | | } |
1180 | | |
1181 | | QualType Ty |
1182 | | = Context.getObjCObjectPointerType( |
1183 | | Context.getObjCInterfaceType(NSArrayDecl)); |
1184 | | |
1185 | | return MaybeBindToTemporary( |
1186 | | ObjCArrayLiteral::Create(Context, Elements, Ty, |
1187 | | ArrayWithObjectsMethod, SR)); |
1188 | | } |
1189 | | |
1190 | | ExprResult Sema::BuildObjCDictionaryLiteral(SourceRange SR, |
1191 | | ObjCDictionaryElement *Elements, |
1192 | | unsigned NumElements) { |
1193 | | // Look up the NSDictionary class, if we haven't done so already. |
1194 | | if (!NSDictionaryDecl) { |
1195 | | NamedDecl *IF = LookupSingleName(TUScope, |
1196 | | NSAPIObj->getNSClassId(NSAPI::ClassId_NSDictionary), |
1197 | | SR.getBegin(), LookupOrdinaryName); |
1198 | | NSDictionaryDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF); |
1199 | | if (!NSDictionaryDecl && getLangOpts().DebuggerObjCLiteral) |
1200 | | NSDictionaryDecl = ObjCInterfaceDecl::Create (Context, |
1201 | | Context.getTranslationUnitDecl(), |
1202 | | SourceLocation(), |
1203 | | NSAPIObj->getNSClassId(NSAPI::ClassId_NSDictionary), |
1204 | | nullptr, nullptr, SourceLocation()); |
1205 | | |
1206 | | if (!NSDictionaryDecl) { |
1207 | | Diag(SR.getBegin(), diag::err_undeclared_nsdictionary); |
1208 | | return ExprError(); |
1209 | | } |
1210 | | } |
1211 | | |
1212 | | // Find the dictionaryWithObjects:forKeys:count: method, if we haven't done |
1213 | | // so already. |
1214 | | QualType IdT = Context.getObjCIdType(); |
1215 | | if (!DictionaryWithObjectsMethod) { |
1216 | | Selector Sel = NSAPIObj->getNSDictionarySelector( |
1217 | | NSAPI::NSDict_dictionaryWithObjectsForKeysCount); |
1218 | | ObjCMethodDecl *Method = NSDictionaryDecl->lookupClassMethod(Sel); |
1219 | | if (!Method && getLangOpts().DebuggerObjCLiteral) { |
1220 | | Method = ObjCMethodDecl::Create(Context, |
1221 | | SourceLocation(), SourceLocation(), Sel, |
1222 | | IdT, |
1223 | | nullptr /*TypeSourceInfo */, |
1224 | | Context.getTranslationUnitDecl(), |
1225 | | false /*Instance*/, false/*isVariadic*/, |
1226 | | /*isPropertyAccessor=*/false, |
1227 | | /*isImplicitlyDeclared=*/true, /*isDefined=*/false, |
1228 | | ObjCMethodDecl::Required, |
1229 | | false); |
1230 | | SmallVector<ParmVarDecl *, 3> Params; |
1231 | | ParmVarDecl *objects = ParmVarDecl::Create(Context, Method, |
1232 | | SourceLocation(), |
1233 | | SourceLocation(), |
1234 | | &Context.Idents.get("objects"), |
1235 | | Context.getPointerType(IdT), |
1236 | | /*TInfo=*/nullptr, SC_None, |
1237 | | nullptr); |
1238 | | Params.push_back(objects); |
1239 | | ParmVarDecl *keys = ParmVarDecl::Create(Context, Method, |
1240 | | SourceLocation(), |
1241 | | SourceLocation(), |
1242 | | &Context.Idents.get("keys"), |
1243 | | Context.getPointerType(IdT), |
1244 | | /*TInfo=*/nullptr, SC_None, |
1245 | | nullptr); |
1246 | | Params.push_back(keys); |
1247 | | ParmVarDecl *cnt = ParmVarDecl::Create(Context, Method, |
1248 | | SourceLocation(), |
1249 | | SourceLocation(), |
1250 | | &Context.Idents.get("cnt"), |
1251 | | Context.UnsignedLongTy, |
1252 | | /*TInfo=*/nullptr, SC_None, |
1253 | | nullptr); |
1254 | | Params.push_back(cnt); |
1255 | | Method->setMethodParams(Context, Params, None); |
1256 | | } |
1257 | | |
1258 | | if (!validateBoxingMethod(*this, SR.getBegin(), NSDictionaryDecl, Sel, |
1259 | | Method)) |
1260 | | return ExprError(); |
1261 | | |
1262 | | // Dig out the type that all values should be converted to. |
1263 | | QualType ValueT = Method->parameters()[0]->getType(); |
1264 | | const PointerType *PtrValue = ValueT->getAs<PointerType>(); |
1265 | | if (!PtrValue || |
1266 | | !Context.hasSameUnqualifiedType(PtrValue->getPointeeType(), IdT)) { |
1267 | | Diag(SR.getBegin(), diag::err_objc_literal_method_sig) |
1268 | | << Sel; |
1269 | | Diag(Method->parameters()[0]->getLocation(), |
1270 | | diag::note_objc_literal_method_param) |
1271 | | << 0 << ValueT |
1272 | | << Context.getPointerType(IdT.withConst()); |
1273 | | return ExprError(); |
1274 | | } |
1275 | | |
1276 | | // Dig out the type that all keys should be converted to. |
1277 | | QualType KeyT = Method->parameters()[1]->getType(); |
1278 | | const PointerType *PtrKey = KeyT->getAs<PointerType>(); |
1279 | | if (!PtrKey || |
1280 | | !Context.hasSameUnqualifiedType(PtrKey->getPointeeType(), |
1281 | | IdT)) { |
1282 | | bool err = true; |
1283 | | if (PtrKey) { |
1284 | | if (QIDNSCopying.isNull()) { |
1285 | | // key argument of selector is id<NSCopying>? |
1286 | | if (ObjCProtocolDecl *NSCopyingPDecl = |
1287 | | LookupProtocol(&Context.Idents.get("NSCopying"), SR.getBegin())) { |
1288 | | ObjCProtocolDecl *PQ[] = {NSCopyingPDecl}; |
1289 | | QIDNSCopying = |
1290 | | Context.getObjCObjectType(Context.ObjCBuiltinIdTy, { }, |
1291 | | llvm::makeArrayRef( |
1292 | | (ObjCProtocolDecl**) PQ, |
1293 | | 1), |
1294 | | false); |
1295 | | QIDNSCopying = Context.getObjCObjectPointerType(QIDNSCopying); |
1296 | | } |
1297 | | } |
1298 | | if (!QIDNSCopying.isNull()) |
1299 | | err = !Context.hasSameUnqualifiedType(PtrKey->getPointeeType(), |
1300 | | QIDNSCopying); |
1301 | | } |
1302 | | |
1303 | | if (err) { |
1304 | | Diag(SR.getBegin(), diag::err_objc_literal_method_sig) |
1305 | | << Sel; |
1306 | | Diag(Method->parameters()[1]->getLocation(), |
1307 | | diag::note_objc_literal_method_param) |
1308 | | << 1 << KeyT |
1309 | | << Context.getPointerType(IdT.withConst()); |
1310 | | return ExprError(); |
1311 | | } |
1312 | | } |
1313 | | |
1314 | | // Check that the 'count' parameter is integral. |
1315 | | QualType CountType = Method->parameters()[2]->getType(); |
1316 | | if (!CountType->isIntegerType()) { |
1317 | | Diag(SR.getBegin(), diag::err_objc_literal_method_sig) |
1318 | | << Sel; |
1319 | | Diag(Method->parameters()[2]->getLocation(), |
1320 | | diag::note_objc_literal_method_param) |
1321 | | << 2 << CountType |
1322 | | << "integral"; |
1323 | | return ExprError(); |
1324 | | } |
1325 | | |
1326 | | // We've found a good +dictionaryWithObjects:keys:count: method; save it! |
1327 | | DictionaryWithObjectsMethod = Method; |
1328 | | } |
1329 | | |
1330 | | QualType ValuesT = DictionaryWithObjectsMethod->parameters()[0]->getType(); |
1331 | | QualType ValueT = ValuesT->castAs<PointerType>()->getPointeeType(); |
1332 | | QualType KeysT = DictionaryWithObjectsMethod->parameters()[1]->getType(); |
1333 | | QualType KeyT = KeysT->castAs<PointerType>()->getPointeeType(); |
1334 | | |
1335 | | // Check that each of the keys and values provided is valid in a collection |
1336 | | // literal, performing conversions as necessary. |
1337 | | bool HasPackExpansions = false; |
1338 | | for (unsigned I = 0, N = NumElements; I != N; ++I) { |
1339 | | // Check the key. |
1340 | | ExprResult Key = CheckObjCCollectionLiteralElement(*this, Elements[I].Key, |
1341 | | KeyT); |
1342 | | if (Key.isInvalid()) |
1343 | | return ExprError(); |
1344 | | |
1345 | | // Check the value. |
1346 | | ExprResult Value |
1347 | | = CheckObjCCollectionLiteralElement(*this, Elements[I].Value, ValueT); |
1348 | | if (Value.isInvalid()) |
1349 | | return ExprError(); |
1350 | | |
1351 | | Elements[I].Key = Key.get(); |
1352 | | Elements[I].Value = Value.get(); |
1353 | | |
1354 | | if (Elements[I].EllipsisLoc.isInvalid()) |
1355 | | continue; |
1356 | | |
1357 | | if (!Elements[I].Key->containsUnexpandedParameterPack() && |
1358 | | !Elements[I].Value->containsUnexpandedParameterPack()) { |
1359 | | Diag(Elements[I].EllipsisLoc, |
1360 | | diag::err_pack_expansion_without_parameter_packs) |
1361 | | << SourceRange(Elements[I].Key->getLocStart(), |
1362 | | Elements[I].Value->getLocEnd()); |
1363 | | return ExprError(); |
1364 | | } |
1365 | | |
1366 | | HasPackExpansions = true; |
1367 | | } |
1368 | | |
1369 | | |
1370 | | QualType Ty |
1371 | | = Context.getObjCObjectPointerType( |
1372 | | Context.getObjCInterfaceType(NSDictionaryDecl)); |
1373 | | return MaybeBindToTemporary(ObjCDictionaryLiteral::Create( |
1374 | | Context, makeArrayRef(Elements, NumElements), HasPackExpansions, Ty, |
1375 | | DictionaryWithObjectsMethod, SR)); |
1376 | | } |
1377 | | |
1378 | | ExprResult Sema::BuildObjCEncodeExpression(SourceLocation AtLoc, |
1379 | | TypeSourceInfo *EncodedTypeInfo, |
1380 | | SourceLocation RParenLoc) { |
1381 | | QualType EncodedType = EncodedTypeInfo->getType(); |
1382 | | QualType StrTy; |
1383 | | if (EncodedType->isDependentType()) |
1384 | | StrTy = Context.DependentTy; |
1385 | | else { |
1386 | | if (!EncodedType->getAsArrayTypeUnsafe() && //// Incomplete array is handled. |
1387 | | !EncodedType->isVoidType()) // void is handled too. |
1388 | | if (RequireCompleteType(AtLoc, EncodedType, |
1389 | | diag::err_incomplete_type_objc_at_encode, |
1390 | | EncodedTypeInfo->getTypeLoc())) |
1391 | | return ExprError(); |
1392 | | |
1393 | | std::string Str; |
1394 | | QualType NotEncodedT; |
1395 | | Context.getObjCEncodingForType(EncodedType, Str, nullptr, &NotEncodedT); |
1396 | | if (!NotEncodedT.isNull()) |
1397 | | Diag(AtLoc, diag::warn_incomplete_encoded_type) |
1398 | | << EncodedType << NotEncodedT; |
1399 | | |
1400 | | // The type of @encode is the same as the type of the corresponding string, |
1401 | | // which is an array type. |
1402 | | StrTy = Context.CharTy; |
1403 | | // A C++ string literal has a const-qualified element type (C++ 2.13.4p1). |
1404 | | if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings) |
1405 | | StrTy.addConst(); |
1406 | | StrTy = Context.getConstantArrayType(StrTy, llvm::APInt(32, Str.size()+1), |
1407 | | ArrayType::Normal, 0); |
1408 | | } |
1409 | | |
1410 | | return new (Context) ObjCEncodeExpr(StrTy, EncodedTypeInfo, AtLoc, RParenLoc); |
1411 | | } |
1412 | | |
1413 | | ExprResult Sema::ParseObjCEncodeExpression(SourceLocation AtLoc, |
1414 | | SourceLocation EncodeLoc, |
1415 | | SourceLocation LParenLoc, |
1416 | | ParsedType ty, |
1417 | | SourceLocation RParenLoc) { |
1418 | | // FIXME: Preserve type source info ? |
1419 | | TypeSourceInfo *TInfo; |
1420 | | QualType EncodedType = GetTypeFromParser(ty, &TInfo); |
1421 | | if (!TInfo) |
1422 | | TInfo = Context.getTrivialTypeSourceInfo(EncodedType, |
1423 | | PP.getLocForEndOfToken(LParenLoc)); |
1424 | | |
1425 | | return BuildObjCEncodeExpression(AtLoc, TInfo, RParenLoc); |
1426 | | } |
1427 | | |
1428 | | static bool HelperToDiagnoseMismatchedMethodsInGlobalPool(Sema &S, |
1429 | | SourceLocation AtLoc, |
1430 | | SourceLocation LParenLoc, |
1431 | | SourceLocation RParenLoc, |
1432 | | ObjCMethodDecl *Method, |
1433 | | ObjCMethodList &MethList) { |
1434 | | ObjCMethodList *M = &MethList; |
1435 | | bool Warned = false; |
1436 | | for (M = M->getNext(); M; M=M->getNext()) { |
1437 | | ObjCMethodDecl *MatchingMethodDecl = M->getMethod(); |
1438 | | if (MatchingMethodDecl == Method || |
1439 | | isa<ObjCImplDecl>(MatchingMethodDecl->getDeclContext()) || |
1440 | | MatchingMethodDecl->getSelector() != Method->getSelector()) |
1441 | | continue; |
1442 | | if (!S.MatchTwoMethodDeclarations(Method, |
1443 | | MatchingMethodDecl, Sema::MMS_loose)) { |
1444 | | if (!Warned) { |
1445 | | Warned = true; |
1446 | | S.Diag(AtLoc, diag::warning_multiple_selectors) |
1447 | | << Method->getSelector() << FixItHint::CreateInsertion(LParenLoc, "(") |
1448 | | << FixItHint::CreateInsertion(RParenLoc, ")"); |
1449 | | S.Diag(Method->getLocation(), diag::note_method_declared_at) |
1450 | | << Method->getDeclName(); |
1451 | | } |
1452 | | S.Diag(MatchingMethodDecl->getLocation(), diag::note_method_declared_at) |
1453 | | << MatchingMethodDecl->getDeclName(); |
1454 | | } |
1455 | | } |
1456 | | return Warned; |
1457 | | } |
1458 | | |
1459 | | static void DiagnoseMismatchedSelectors(Sema &S, SourceLocation AtLoc, |
1460 | | ObjCMethodDecl *Method, |
1461 | | SourceLocation LParenLoc, |
1462 | | SourceLocation RParenLoc, |
1463 | | bool WarnMultipleSelectors) { |
1464 | | if (!WarnMultipleSelectors || |
1465 | | S.Diags.isIgnored(diag::warning_multiple_selectors, SourceLocation())) |
1466 | | return; |
1467 | | bool Warned = false; |
1468 | | for (Sema::GlobalMethodPool::iterator b = S.MethodPool.begin(), |
1469 | | e = S.MethodPool.end(); b != e; b++) { |
1470 | | // first, instance methods |
1471 | | ObjCMethodList &InstMethList = b->second.first; |
1472 | | if (HelperToDiagnoseMismatchedMethodsInGlobalPool(S, AtLoc, LParenLoc, RParenLoc, |
1473 | | Method, InstMethList)) |
1474 | | Warned = true; |
1475 | | |
1476 | | // second, class methods |
1477 | | ObjCMethodList &ClsMethList = b->second.second; |
1478 | | if (HelperToDiagnoseMismatchedMethodsInGlobalPool(S, AtLoc, LParenLoc, RParenLoc, |
1479 | | Method, ClsMethList) || Warned) |
1480 | | return; |
1481 | | } |
1482 | | } |
1483 | | |
1484 | | ExprResult Sema::ParseObjCSelectorExpression(Selector Sel, |
1485 | | SourceLocation AtLoc, |
1486 | | SourceLocation SelLoc, |
1487 | | SourceLocation LParenLoc, |
1488 | | SourceLocation RParenLoc, |
1489 | | bool WarnMultipleSelectors) { |
1490 | | ObjCMethodDecl *Method = LookupInstanceMethodInGlobalPool(Sel, |
1491 | | SourceRange(LParenLoc, RParenLoc)); |
1492 | | if (!Method) |
1493 | | Method = LookupFactoryMethodInGlobalPool(Sel, |
1494 | | SourceRange(LParenLoc, RParenLoc)); |
1495 | | if (!Method) { |
1496 | | if (const ObjCMethodDecl *OM = SelectorsForTypoCorrection(Sel)) { |
1497 | | Selector MatchedSel = OM->getSelector(); |
1498 | | SourceRange SelectorRange(LParenLoc.getLocWithOffset(1), |
1499 | | RParenLoc.getLocWithOffset(-1)); |
1500 | | Diag(SelLoc, diag::warn_undeclared_selector_with_typo) |
1501 | | << Sel << MatchedSel |
1502 | | << FixItHint::CreateReplacement(SelectorRange, MatchedSel.getAsString()); |
1503 | | |
1504 | | } else |
1505 | | Diag(SelLoc, diag::warn_undeclared_selector) << Sel; |
1506 | | } else |
1507 | | DiagnoseMismatchedSelectors(*this, AtLoc, Method, LParenLoc, RParenLoc, |
1508 | | WarnMultipleSelectors); |
1509 | | |
1510 | | if (Method && |
1511 | | Method->getImplementationControl() != ObjCMethodDecl::Optional && |
1512 | | !getSourceManager().isInSystemHeader(Method->getLocation())) |
1513 | | ReferencedSelectors.insert(std::make_pair(Sel, AtLoc)); |
1514 | | |
1515 | | // In ARC, forbid the user from using @selector for |
1516 | | // retain/release/autorelease/dealloc/retainCount. |
1517 | | if (getLangOpts().ObjCAutoRefCount) { |
1518 | | switch (Sel.getMethodFamily()) { |
1519 | | case OMF_retain: |
1520 | | case OMF_release: |
1521 | | case OMF_autorelease: |
1522 | | case OMF_retainCount: |
1523 | | case OMF_dealloc: |
1524 | | Diag(AtLoc, diag::err_arc_illegal_selector) << |
1525 | | Sel << SourceRange(LParenLoc, RParenLoc); |
1526 | | break; |
1527 | | |
1528 | | case OMF_None: |
1529 | | case OMF_alloc: |
1530 | | case OMF_copy: |
1531 | | case OMF_finalize: |
1532 | | case OMF_init: |
1533 | | case OMF_mutableCopy: |
1534 | | case OMF_new: |
1535 | | case OMF_self: |
1536 | | case OMF_initialize: |
1537 | | case OMF_performSelector: |
1538 | | break; |
1539 | | } |
1540 | | } |
1541 | | QualType Ty = Context.getObjCSelType(); |
1542 | | return new (Context) ObjCSelectorExpr(Ty, Sel, AtLoc, RParenLoc); |
1543 | | } |
1544 | | |
1545 | | ExprResult Sema::ParseObjCProtocolExpression(IdentifierInfo *ProtocolId, |
1546 | | SourceLocation AtLoc, |
1547 | | SourceLocation ProtoLoc, |
1548 | | SourceLocation LParenLoc, |
1549 | | SourceLocation ProtoIdLoc, |
1550 | | SourceLocation RParenLoc) { |
1551 | | ObjCProtocolDecl* PDecl = LookupProtocol(ProtocolId, ProtoIdLoc); |
1552 | | if (!PDecl) { |
1553 | | Diag(ProtoLoc, diag::err_undeclared_protocol) << ProtocolId; |
1554 | | return true; |
1555 | | } |
1556 | | if (PDecl->hasDefinition()) |
1557 | | PDecl = PDecl->getDefinition(); |
1558 | | |
1559 | | QualType Ty = Context.getObjCProtoType(); |
1560 | | if (Ty.isNull()) |
1561 | | return true; |
1562 | | Ty = Context.getObjCObjectPointerType(Ty); |
1563 | | return new (Context) ObjCProtocolExpr(Ty, PDecl, AtLoc, ProtoIdLoc, RParenLoc); |
1564 | | } |
1565 | | |
1566 | | /// Try to capture an implicit reference to 'self'. |
1567 | | ObjCMethodDecl *Sema::tryCaptureObjCSelf(SourceLocation Loc) { |
1568 | | DeclContext *DC = getFunctionLevelDeclContext(); |
1569 | | |
1570 | | // If we're not in an ObjC method, error out. Note that, unlike the |
1571 | | // C++ case, we don't require an instance method --- class methods |
1572 | | // still have a 'self', and we really do still need to capture it! |
1573 | | ObjCMethodDecl *method = dyn_cast<ObjCMethodDecl>(DC); |
1574 | | if (!method) |
1575 | | return nullptr; |
1576 | | |
1577 | | tryCaptureVariable(method->getSelfDecl(), Loc); |
1578 | | |
1579 | | return method; |
1580 | | } |
1581 | | |
1582 | | static QualType stripObjCInstanceType(ASTContext &Context, QualType T) { |
1583 | | QualType origType = T; |
1584 | | if (auto nullability = AttributedType::stripOuterNullability(T)) { |
1585 | | if (T == Context.getObjCInstanceType()) { |
1586 | | return Context.getAttributedType( |
1587 | | AttributedType::getNullabilityAttrKind(*nullability), |
1588 | | Context.getObjCIdType(), |
1589 | | Context.getObjCIdType()); |
1590 | | } |
1591 | | |
1592 | | return origType; |
1593 | | } |
1594 | | |
1595 | | if (T == Context.getObjCInstanceType()) |
1596 | | return Context.getObjCIdType(); |
1597 | | |
1598 | | return origType; |
1599 | | } |
1600 | | |
1601 | | /// Determine the result type of a message send based on the receiver type, |
1602 | | /// method, and the kind of message send. |
1603 | | /// |
1604 | | /// This is the "base" result type, which will still need to be adjusted |
1605 | | /// to account for nullability. |
1606 | | static QualType getBaseMessageSendResultType(Sema &S, |
1607 | | QualType ReceiverType, |
1608 | | ObjCMethodDecl *Method, |
1609 | | bool isClassMessage, |
1610 | | bool isSuperMessage) { |
1611 | | assert(Method && "Must have a method"); |
1612 | | if (!Method->hasRelatedResultType()) |
1613 | | return Method->getSendResultType(ReceiverType); |
1614 | | |
1615 | | ASTContext &Context = S.Context; |
1616 | | |
1617 | | // Local function that transfers the nullability of the method's |
1618 | | // result type to the returned result. |
1619 | | auto transferNullability = [&](QualType type) -> QualType { |
1620 | | // If the method's result type has nullability, extract it. |
1621 | | if (auto nullability = Method->getSendResultType(ReceiverType) |
1622 | | ->getNullability(Context)){ |
1623 | | // Strip off any outer nullability sugar from the provided type. |
1624 | | (void)AttributedType::stripOuterNullability(type); |
1625 | | |
1626 | | // Form a new attributed type using the method result type's nullability. |
1627 | | return Context.getAttributedType( |
1628 | | AttributedType::getNullabilityAttrKind(*nullability), |
1629 | | type, |
1630 | | type); |
1631 | | } |
1632 | | |
1633 | | return type; |
1634 | | }; |
1635 | | |
1636 | | // If a method has a related return type: |
1637 | | // - if the method found is an instance method, but the message send |
1638 | | // was a class message send, T is the declared return type of the method |
1639 | | // found |
1640 | | if (Method->isInstanceMethod() && isClassMessage) |
1641 | | return stripObjCInstanceType(Context, |
1642 | | Method->getSendResultType(ReceiverType)); |
1643 | | |
1644 | | // - if the receiver is super, T is a pointer to the class of the |
1645 | | // enclosing method definition |
1646 | | if (isSuperMessage) { |
1647 | | if (ObjCMethodDecl *CurMethod = S.getCurMethodDecl()) |
1648 | | if (ObjCInterfaceDecl *Class = CurMethod->getClassInterface()) { |
1649 | | return transferNullability( |
1650 | | Context.getObjCObjectPointerType( |
1651 | | Context.getObjCInterfaceType(Class))); |
1652 | | } |
1653 | | } |
1654 | | |
1655 | | // - if the receiver is the name of a class U, T is a pointer to U |
1656 | | if (ReceiverType->getAsObjCInterfaceType()) |
1657 | | return transferNullability(Context.getObjCObjectPointerType(ReceiverType)); |
1658 | | // - if the receiver is of type Class or qualified Class type, |
1659 | | // T is the declared return type of the method. |
1660 | | if (ReceiverType->isObjCClassType() || |
1661 | | ReceiverType->isObjCQualifiedClassType()) |
1662 | | return stripObjCInstanceType(Context, |
1663 | | Method->getSendResultType(ReceiverType)); |
1664 | | |
1665 | | // - if the receiver is id, qualified id, Class, or qualified Class, T |
1666 | | // is the receiver type, otherwise |
1667 | | // - T is the type of the receiver expression. |
1668 | | return transferNullability(ReceiverType); |
1669 | | } |
1670 | | |
1671 | | QualType Sema::getMessageSendResultType(QualType ReceiverType, |
1672 | | ObjCMethodDecl *Method, |
1673 | | bool isClassMessage, |
1674 | | bool isSuperMessage) { |
1675 | | // Produce the result type. |
1676 | | QualType resultType = getBaseMessageSendResultType(*this, ReceiverType, |
1677 | | Method, |
1678 | | isClassMessage, |
1679 | | isSuperMessage); |
1680 | | |
1681 | | // If this is a class message, ignore the nullability of the receiver. |
1682 | | if (isClassMessage) |
1683 | | return resultType; |
1684 | | |
1685 | | // Map the nullability of the result into a table index. |
1686 | | unsigned receiverNullabilityIdx = 0; |
1687 | | if (auto nullability = ReceiverType->getNullability(Context)) |
1688 | | receiverNullabilityIdx = 1 + static_cast<unsigned>(*nullability); |
1689 | | |
1690 | | unsigned resultNullabilityIdx = 0; |
1691 | | if (auto nullability = resultType->getNullability(Context)) |
1692 | | resultNullabilityIdx = 1 + static_cast<unsigned>(*nullability); |
1693 | | |
1694 | | // The table of nullability mappings, indexed by the receiver's nullability |
1695 | | // and then the result type's nullability. |
1696 | | static const uint8_t None = 0; |
1697 | | static const uint8_t NonNull = 1; |
1698 | | static const uint8_t Nullable = 2; |
1699 | | static const uint8_t Unspecified = 3; |
1700 | | static const uint8_t nullabilityMap[4][4] = { |
1701 | | // None NonNull Nullable Unspecified |
1702 | | /* None */ { None, None, Nullable, None }, |
1703 | | /* NonNull */ { None, NonNull, Nullable, Unspecified }, |
1704 | | /* Nullable */ { Nullable, Nullable, Nullable, Nullable }, |
1705 | | /* Unspecified */ { None, Unspecified, Nullable, Unspecified } |
1706 | | }; |
1707 | | |
1708 | | unsigned newResultNullabilityIdx |
1709 | | = nullabilityMap[receiverNullabilityIdx][resultNullabilityIdx]; |
1710 | | if (newResultNullabilityIdx == resultNullabilityIdx) |
1711 | | return resultType; |
1712 | | |
1713 | | // Strip off the existing nullability. This removes as little type sugar as |
1714 | | // possible. |
1715 | | do { |
1716 | | if (auto attributed = dyn_cast<AttributedType>(resultType.getTypePtr())) { |
1717 | | resultType = attributed->getModifiedType(); |
1718 | | } else { |
1719 | | resultType = resultType.getDesugaredType(Context); |
1720 | | } |
1721 | | } while (resultType->getNullability(Context)); |
1722 | | |
1723 | | // Add nullability back if needed. |
1724 | | if (newResultNullabilityIdx > 0) { |
1725 | | auto newNullability |
1726 | | = static_cast<NullabilityKind>(newResultNullabilityIdx-1); |
1727 | | return Context.getAttributedType( |
1728 | | AttributedType::getNullabilityAttrKind(newNullability), |
1729 | | resultType, resultType); |
1730 | | } |
1731 | | |
1732 | | return resultType; |
1733 | | } |
1734 | | |
1735 | | /// Look for an ObjC method whose result type exactly matches the given type. |
1736 | | static const ObjCMethodDecl * |
1737 | | findExplicitInstancetypeDeclarer(const ObjCMethodDecl *MD, |
1738 | | QualType instancetype) { |
1739 | | if (MD->getReturnType() == instancetype) |
1740 | | return MD; |
1741 | | |
1742 | | // For these purposes, a method in an @implementation overrides a |
1743 | | // declaration in the @interface. |
1744 | | if (const ObjCImplDecl *impl = |
1745 | | dyn_cast<ObjCImplDecl>(MD->getDeclContext())) { |
1746 | | const ObjCContainerDecl *iface; |
1747 | | if (const ObjCCategoryImplDecl *catImpl = |
1748 | | dyn_cast<ObjCCategoryImplDecl>(impl)) { |
1749 | | iface = catImpl->getCategoryDecl(); |
1750 | | } else { |
1751 | | iface = impl->getClassInterface(); |
1752 | | } |
1753 | | |
1754 | | const ObjCMethodDecl *ifaceMD = |
1755 | | iface->getMethod(MD->getSelector(), MD->isInstanceMethod()); |
1756 | | if (ifaceMD) return findExplicitInstancetypeDeclarer(ifaceMD, instancetype); |
1757 | | } |
1758 | | |
1759 | | SmallVector<const ObjCMethodDecl *, 4> overrides; |
1760 | | MD->getOverriddenMethods(overrides); |
1761 | | for (unsigned i = 0, e = overrides.size(); i != e; ++i) { |
1762 | | if (const ObjCMethodDecl *result = |
1763 | | findExplicitInstancetypeDeclarer(overrides[i], instancetype)) |
1764 | | return result; |
1765 | | } |
1766 | | |
1767 | | return nullptr; |
1768 | | } |
1769 | | |
1770 | | void Sema::EmitRelatedResultTypeNoteForReturn(QualType destType) { |
1771 | | // Only complain if we're in an ObjC method and the required return |
1772 | | // type doesn't match the method's declared return type. |
1773 | | ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(CurContext); |
1774 | | if (!MD || !MD->hasRelatedResultType() || |
1775 | | Context.hasSameUnqualifiedType(destType, MD->getReturnType())) |
1776 | | return; |
1777 | | |
1778 | | // Look for a method overridden by this method which explicitly uses |
1779 | | // 'instancetype'. |
1780 | | if (const ObjCMethodDecl *overridden = |
1781 | | findExplicitInstancetypeDeclarer(MD, Context.getObjCInstanceType())) { |
1782 | | SourceRange range = overridden->getReturnTypeSourceRange(); |
1783 | | SourceLocation loc = range.getBegin(); |
1784 | | if (loc.isInvalid()) |
1785 | | loc = overridden->getLocation(); |
1786 | | Diag(loc, diag::note_related_result_type_explicit) |
1787 | | << /*current method*/ 1 << range; |
1788 | | return; |
1789 | | } |
1790 | | |
1791 | | // Otherwise, if we have an interesting method family, note that. |
1792 | | // This should always trigger if the above didn't. |
1793 | | if (ObjCMethodFamily family = MD->getMethodFamily()) |
1794 | | Diag(MD->getLocation(), diag::note_related_result_type_family) |
1795 | | << /*current method*/ 1 |
1796 | | << family; |
1797 | | } |
1798 | | |
1799 | | void Sema::EmitRelatedResultTypeNote(const Expr *E) { |
1800 | | E = E->IgnoreParenImpCasts(); |
1801 | | const ObjCMessageExpr *MsgSend = dyn_cast<ObjCMessageExpr>(E); |
1802 | | if (!MsgSend) |
1803 | | return; |
1804 | | |
1805 | | const ObjCMethodDecl *Method = MsgSend->getMethodDecl(); |
1806 | | if (!Method) |
1807 | | return; |
1808 | | |
1809 | | if (!Method->hasRelatedResultType()) |
1810 | | return; |
1811 | | |
1812 | | if (Context.hasSameUnqualifiedType( |
1813 | | Method->getReturnType().getNonReferenceType(), MsgSend->getType())) |
1814 | | return; |
1815 | | |
1816 | | if (!Context.hasSameUnqualifiedType(Method->getReturnType(), |
1817 | | Context.getObjCInstanceType())) |
1818 | | return; |
1819 | | |
1820 | | Diag(Method->getLocation(), diag::note_related_result_type_inferred) |
1821 | | << Method->isInstanceMethod() << Method->getSelector() |
1822 | | << MsgSend->getType(); |
1823 | | } |
1824 | | |
1825 | | bool Sema::CheckMessageArgumentTypes(QualType ReceiverType, |
1826 | | MultiExprArg Args, |
1827 | | Selector Sel, |
1828 | | ArrayRef<SourceLocation> SelectorLocs, |
1829 | | ObjCMethodDecl *Method, |
1830 | | bool isClassMessage, bool isSuperMessage, |
1831 | | SourceLocation lbrac, SourceLocation rbrac, |
1832 | | SourceRange RecRange, |
1833 | | QualType &ReturnType, ExprValueKind &VK) { |
1834 | | SourceLocation SelLoc; |
1835 | | if (!SelectorLocs.empty() && SelectorLocs.front().isValid()) |
1836 | | SelLoc = SelectorLocs.front(); |
1837 | | else |
1838 | | SelLoc = lbrac; |
1839 | | |
1840 | | if (!Method) { |
1841 | | // Apply default argument promotion as for (C99 6.5.2.2p6). |
1842 | | for (unsigned i = 0, e = Args.size(); i != e; i++) { |
1843 | | if (Args[i]->isTypeDependent()) |
1844 | | continue; |
1845 | | |
1846 | | ExprResult result; |
1847 | | if (getLangOpts().DebuggerSupport) { |
1848 | | QualType paramTy; // ignored |
1849 | | result = checkUnknownAnyArg(SelLoc, Args[i], paramTy); |
1850 | | } else { |
1851 | | result = DefaultArgumentPromotion(Args[i]); |
1852 | | } |
1853 | | if (result.isInvalid()) |
1854 | | return true; |
1855 | | Args[i] = result.get(); |
1856 | | } |
1857 | | |
1858 | | unsigned DiagID; |
1859 | | if (getLangOpts().ObjCAutoRefCount) |
1860 | | DiagID = diag::err_arc_method_not_found; |
1861 | | else |
1862 | | DiagID = isClassMessage ? diag::warn_class_method_not_found |
1863 | | : diag::warn_inst_method_not_found; |
1864 | | if (!getLangOpts().DebuggerSupport) { |
1865 | | const ObjCMethodDecl *OMD = SelectorsForTypoCorrection(Sel, ReceiverType); |
1866 | | if (OMD && !OMD->isInvalidDecl()) { |
1867 | | if (getLangOpts().ObjCAutoRefCount) |
1868 | | DiagID = diag::error_method_not_found_with_typo; |
1869 | | else |
1870 | | DiagID = isClassMessage ? diag::warn_class_method_not_found_with_typo |
1871 | | : diag::warn_instance_method_not_found_with_typo; |
1872 | | Selector MatchedSel = OMD->getSelector(); |
1873 | | SourceRange SelectorRange(SelectorLocs.front(), SelectorLocs.back()); |
1874 | | if (MatchedSel.isUnarySelector()) |
1875 | | Diag(SelLoc, DiagID) |
1876 | | << Sel<< isClassMessage << MatchedSel |
1877 | | << FixItHint::CreateReplacement(SelectorRange, MatchedSel.getAsString()); |
1878 | | else |
1879 | | Diag(SelLoc, DiagID) << Sel<< isClassMessage << MatchedSel; |
1880 | | } |
1881 | | else |
1882 | | Diag(SelLoc, DiagID) |
1883 | | << Sel << isClassMessage << SourceRange(SelectorLocs.front(), |
1884 | | SelectorLocs.back()); |
1885 | | // Find the class to which we are sending this message. |
1886 | | if (ReceiverType->isObjCObjectPointerType()) { |
1887 | | if (ObjCInterfaceDecl *ThisClass = |
1888 | | ReceiverType->getAs<ObjCObjectPointerType>()->getInterfaceDecl()) { |
1889 | | Diag(ThisClass->getLocation(), diag::note_receiver_class_declared); |
1890 | | if (!RecRange.isInvalid()) |
1891 | | if (ThisClass->lookupClassMethod(Sel)) |
1892 | | Diag(RecRange.getBegin(),diag::note_receiver_expr_here) |
1893 | | << FixItHint::CreateReplacement(RecRange, |
1894 | | ThisClass->getNameAsString()); |
1895 | | } |
1896 | | } |
1897 | | } |
1898 | | |
1899 | | // In debuggers, we want to use __unknown_anytype for these |
1900 | | // results so that clients can cast them. |
1901 | | if (getLangOpts().DebuggerSupport) { |
1902 | | ReturnType = Context.UnknownAnyTy; |
1903 | | } else { |
1904 | | ReturnType = Context.getObjCIdType(); |
1905 | | } |
1906 | | VK = VK_RValue; |
1907 | | return false; |
1908 | | } |
1909 | | |
1910 | | ReturnType = getMessageSendResultType(ReceiverType, Method, isClassMessage, |
1911 | | isSuperMessage); |
1912 | | VK = Expr::getValueKindForType(Method->getReturnType()); |
1913 | | |
1914 | | unsigned NumNamedArgs = Sel.getNumArgs(); |
1915 | | // Method might have more arguments than selector indicates. This is due |
1916 | | // to addition of c-style arguments in method. |
1917 | | if (Method->param_size() > Sel.getNumArgs()) |
1918 | | NumNamedArgs = Method->param_size(); |
1919 | | // FIXME. This need be cleaned up. |
1920 | | if (Args.size() < NumNamedArgs) { |
1921 | | Diag(SelLoc, diag::err_typecheck_call_too_few_args) |
1922 | | << 2 << NumNamedArgs << static_cast<unsigned>(Args.size()); |
1923 | | return false; |
1924 | | } |
1925 | | |
1926 | | // Compute the set of type arguments to be substituted into each parameter |
1927 | | // type. |
1928 | | Optional<ArrayRef<QualType>> typeArgs |
1929 | | = ReceiverType->getObjCSubstitutions(Method->getDeclContext()); |
1930 | | bool IsError = false; |
1931 | | for (unsigned i = 0; i < NumNamedArgs; i++) { |
1932 | | // We can't do any type-checking on a type-dependent argument. |
1933 | | if (Args[i]->isTypeDependent()) |
1934 | | continue; |
1935 | | |
1936 | | Expr *argExpr = Args[i]; |
1937 | | |
1938 | | ParmVarDecl *param = Method->parameters()[i]; |
1939 | | assert(argExpr && "CheckMessageArgumentTypes(): missing expression"); |
1940 | | |
1941 | | // Strip the unbridged-cast placeholder expression off unless it's |
1942 | | // a consumed argument. |
1943 | | if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) && |
1944 | | !param->hasAttr<CFConsumedAttr>()) |
1945 | | argExpr = stripARCUnbridgedCast(argExpr); |
1946 | | |
1947 | | // If the parameter is __unknown_anytype, infer its type |
1948 | | // from the argument. |
1949 | | if (param->getType() == Context.UnknownAnyTy) { |
1950 | | QualType paramType; |
1951 | | ExprResult argE = checkUnknownAnyArg(SelLoc, argExpr, paramType); |
1952 | | if (argE.isInvalid()) { |
1953 | | IsError = true; |
1954 | | } else { |
1955 | | Args[i] = argE.get(); |
1956 | | |
1957 | | // Update the parameter type in-place. |
1958 | | param->setType(paramType); |
1959 | | } |
1960 | | continue; |
1961 | | } |
1962 | | |
1963 | | QualType origParamType = param->getType(); |
1964 | | QualType paramType = param->getType(); |
1965 | | if (typeArgs) |
1966 | | paramType = paramType.substObjCTypeArgs( |
1967 | | Context, |
1968 | | *typeArgs, |
1969 | | ObjCSubstitutionContext::Parameter); |
1970 | | |
1971 | | if (RequireCompleteType(argExpr->getSourceRange().getBegin(), |
1972 | | paramType, |
1973 | | diag::err_call_incomplete_argument, argExpr)) |
1974 | | return true; |
1975 | | |
1976 | | InitializedEntity Entity |
1977 | | = InitializedEntity::InitializeParameter(Context, param, paramType); |
1978 | | ExprResult ArgE = PerformCopyInitialization(Entity, SourceLocation(), argExpr); |
1979 | | if (ArgE.isInvalid()) |
1980 | | IsError = true; |
1981 | | else { |
1982 | | Args[i] = ArgE.getAs<Expr>(); |
1983 | | |
1984 | | // If we are type-erasing a block to a block-compatible |
1985 | | // Objective-C pointer type, we may need to extend the lifetime |
1986 | | // of the block object. |
1987 | | if (typeArgs && Args[i]->isRValue() && paramType->isBlockPointerType() && |
1988 | | origParamType->isBlockCompatibleObjCPointerType(Context)) { |
1989 | | ExprResult arg = Args[i]; |
1990 | | maybeExtendBlockObject(arg); |
1991 | | Args[i] = arg.get(); |
1992 | | } |
1993 | | } |
1994 | | } |
1995 | | |
1996 | | // Promote additional arguments to variadic methods. |
1997 | | if (Method->isVariadic()) { |
1998 | | for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) { |
1999 | | if (Args[i]->isTypeDependent()) |
2000 | | continue; |
2001 | | |
2002 | | ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, |
2003 | | nullptr); |
2004 | | IsError |= Arg.isInvalid(); |
2005 | | Args[i] = Arg.get(); |
2006 | | } |
2007 | | } else { |
2008 | | // Check for extra arguments to non-variadic methods. |
2009 | | if (Args.size() != NumNamedArgs) { |
2010 | | Diag(Args[NumNamedArgs]->getLocStart(), |
2011 | | diag::err_typecheck_call_too_many_args) |
2012 | | << 2 /*method*/ << NumNamedArgs << static_cast<unsigned>(Args.size()) |
2013 | | << Method->getSourceRange() |
2014 | | << SourceRange(Args[NumNamedArgs]->getLocStart(), |
2015 | | Args.back()->getLocEnd()); |
2016 | | } |
2017 | | } |
2018 | | |
2019 | | DiagnoseSentinelCalls(Method, SelLoc, Args); |
2020 | | |
2021 | | // Do additional checkings on method. |
2022 | | IsError |= CheckObjCMethodCall( |
2023 | | Method, SelLoc, makeArrayRef(Args.data(), Args.size())); |
2024 | | |
2025 | | return IsError; |
2026 | | } |
2027 | | |
2028 | | bool Sema::isSelfExpr(Expr *RExpr) { |
2029 | | // 'self' is objc 'self' in an objc method only. |
2030 | | ObjCMethodDecl *Method = |
2031 | | dyn_cast_or_null<ObjCMethodDecl>(CurContext->getNonClosureAncestor()); |
2032 | | return isSelfExpr(RExpr, Method); |
2033 | | } |
2034 | | |
2035 | | bool Sema::isSelfExpr(Expr *receiver, const ObjCMethodDecl *method) { |
2036 | | if (!method) return false; |
2037 | | |
2038 | | receiver = receiver->IgnoreParenLValueCasts(); |
2039 | | if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(receiver)) |
2040 | | if (DRE->getDecl() == method->getSelfDecl()) |
2041 | | return true; |
2042 | | return false; |
2043 | | } |
2044 | | |
2045 | | /// LookupMethodInType - Look up a method in an ObjCObjectType. |
2046 | | ObjCMethodDecl *Sema::LookupMethodInObjectType(Selector sel, QualType type, |
2047 | | bool isInstance) { |
2048 | | const ObjCObjectType *objType = type->castAs<ObjCObjectType>(); |
2049 | | if (ObjCInterfaceDecl *iface = objType->getInterface()) { |
2050 | | // Look it up in the main interface (and categories, etc.) |
2051 | | if (ObjCMethodDecl *method = iface->lookupMethod(sel, isInstance)) |
2052 | | return method; |
2053 | | |
2054 | | // Okay, look for "private" methods declared in any |
2055 | | // @implementations we've seen. |
2056 | | if (ObjCMethodDecl *method = iface->lookupPrivateMethod(sel, isInstance)) |
2057 | | return method; |
2058 | | } |
2059 | | |
2060 | | // Check qualifiers. |
2061 | | for (const auto *I : objType->quals()) |
2062 | | if (ObjCMethodDecl *method = I->lookupMethod(sel, isInstance)) |
2063 | | return method; |
2064 | | |
2065 | | return nullptr; |
2066 | | } |
2067 | | |
2068 | | /// LookupMethodInQualifiedType - Lookups up a method in protocol qualifier |
2069 | | /// list of a qualified objective pointer type. |
2070 | | ObjCMethodDecl *Sema::LookupMethodInQualifiedType(Selector Sel, |
2071 | | const ObjCObjectPointerType *OPT, |
2072 | | bool Instance) |
2073 | | { |
2074 | | ObjCMethodDecl *MD = nullptr; |
2075 | | for (const auto *PROTO : OPT->quals()) { |
2076 | | if ((MD = PROTO->lookupMethod(Sel, Instance))) { |
2077 | | return MD; |
2078 | | } |
2079 | | } |
2080 | | return nullptr; |
2081 | | } |
2082 | | |
2083 | | /// HandleExprPropertyRefExpr - Handle foo.bar where foo is a pointer to an |
2084 | | /// objective C interface. This is a property reference expression. |
2085 | | ExprResult Sema:: |
2086 | | HandleExprPropertyRefExpr(const ObjCObjectPointerType *OPT, |
2087 | | Expr *BaseExpr, SourceLocation OpLoc, |
2088 | | DeclarationName MemberName, |
2089 | | SourceLocation MemberLoc, |
2090 | | SourceLocation SuperLoc, QualType SuperType, |
2091 | | bool Super) { |
2092 | | const ObjCInterfaceType *IFaceT = OPT->getInterfaceType(); |
2093 | | ObjCInterfaceDecl *IFace = IFaceT->getDecl(); |
2094 | | |
2095 | | if (!MemberName.isIdentifier()) { |
2096 | | Diag(MemberLoc, diag::err_invalid_property_name) |
2097 | | << MemberName << QualType(OPT, 0); |
2098 | | return ExprError(); |
2099 | | } |
2100 | | |
2101 | | IdentifierInfo *Member = MemberName.getAsIdentifierInfo(); |
2102 | | |
2103 | | SourceRange BaseRange = Super? SourceRange(SuperLoc) |
2104 | | : BaseExpr->getSourceRange(); |
2105 | | if (RequireCompleteType(MemberLoc, OPT->getPointeeType(), |
2106 | | diag::err_property_not_found_forward_class, |
2107 | | MemberName, BaseRange)) |
2108 | | return ExprError(); |
2109 | | |
2110 | | // Search for a declared property first. |
2111 | | if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(Member)) { |
2112 | | // Check whether we can reference this property. |
2113 | | if (DiagnoseUseOfDecl(PD, MemberLoc)) |
2114 | | return ExprError(); |
2115 | | if (Super) |
2116 | | return new (Context) |
2117 | | ObjCPropertyRefExpr(PD, Context.PseudoObjectTy, VK_LValue, |
2118 | | OK_ObjCProperty, MemberLoc, SuperLoc, SuperType); |
2119 | | else |
2120 | | return new (Context) |
2121 | | ObjCPropertyRefExpr(PD, Context.PseudoObjectTy, VK_LValue, |
2122 | | OK_ObjCProperty, MemberLoc, BaseExpr); |
2123 | | } |
2124 | | // Check protocols on qualified interfaces. |
2125 | | for (const auto *I : OPT->quals()) |
2126 | | if (ObjCPropertyDecl *PD = I->FindPropertyDeclaration(Member)) { |
2127 | | // Check whether we can reference this property. |
2128 | | if (DiagnoseUseOfDecl(PD, MemberLoc)) |
2129 | | return ExprError(); |
2130 | | |
2131 | | if (Super) |
2132 | | return new (Context) ObjCPropertyRefExpr( |
2133 | | PD, Context.PseudoObjectTy, VK_LValue, OK_ObjCProperty, MemberLoc, |
2134 | | SuperLoc, SuperType); |
2135 | | else |
2136 | | return new (Context) |
2137 | | ObjCPropertyRefExpr(PD, Context.PseudoObjectTy, VK_LValue, |
2138 | | OK_ObjCProperty, MemberLoc, BaseExpr); |
2139 | | } |
2140 | | // If that failed, look for an "implicit" property by seeing if the nullary |
2141 | | // selector is implemented. |
2142 | | |
2143 | | // FIXME: The logic for looking up nullary and unary selectors should be |
2144 | | // shared with the code in ActOnInstanceMessage. |
2145 | | |
2146 | | Selector Sel = PP.getSelectorTable().getNullarySelector(Member); |
2147 | | ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel); |
2148 | | |
2149 | | // May be founf in property's qualified list. |
2150 | | if (!Getter) |
2151 | | Getter = LookupMethodInQualifiedType(Sel, OPT, true); |
2152 | | |
2153 | | // If this reference is in an @implementation, check for 'private' methods. |
2154 | | if (!Getter) |
2155 | | Getter = IFace->lookupPrivateMethod(Sel); |
2156 | | |
2157 | | if (Getter) { |
2158 | | // Check if we can reference this property. |
2159 | | if (DiagnoseUseOfDecl(Getter, MemberLoc)) |
2160 | | return ExprError(); |
2161 | | } |
2162 | | // If we found a getter then this may be a valid dot-reference, we |
2163 | | // will look for the matching setter, in case it is needed. |
2164 | | Selector SetterSel = |
2165 | | SelectorTable::constructSetterSelector(PP.getIdentifierTable(), |
2166 | | PP.getSelectorTable(), Member); |
2167 | | ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel); |
2168 | | |
2169 | | // May be founf in property's qualified list. |
2170 | | if (!Setter) |
2171 | | Setter = LookupMethodInQualifiedType(SetterSel, OPT, true); |
2172 | | |
2173 | | if (!Setter) { |
2174 | | // If this reference is in an @implementation, also check for 'private' |
2175 | | // methods. |
2176 | | Setter = IFace->lookupPrivateMethod(SetterSel); |
2177 | | } |
2178 | | |
2179 | | if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc)) |
2180 | | return ExprError(); |
2181 | | |
2182 | | // Special warning if member name used in a property-dot for a setter accessor |
2183 | | // does not use a property with same name; e.g. obj.X = ... for a property with |
2184 | | // name 'x'. |
2185 | | if (Setter && Setter->isImplicit() && Setter->isPropertyAccessor() |
2186 | | && !IFace->FindPropertyDeclaration(Member)) { |
2187 | | if (const ObjCPropertyDecl *PDecl = Setter->findPropertyDecl()) { |
2188 | | // Do not warn if user is using property-dot syntax to make call to |
2189 | | // user named setter. |
2190 | | if (!(PDecl->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter)) |
2191 | | Diag(MemberLoc, |
2192 | | diag::warn_property_access_suggest) |
2193 | | << MemberName << QualType(OPT, 0) << PDecl->getName() |
2194 | | << FixItHint::CreateReplacement(MemberLoc, PDecl->getName()); |
2195 | | } |
2196 | | } |
2197 | | |
2198 | | if (Getter || Setter) { |
2199 | | if (Super) |
2200 | | return new (Context) |
2201 | | ObjCPropertyRefExpr(Getter, Setter, Context.PseudoObjectTy, VK_LValue, |
2202 | | OK_ObjCProperty, MemberLoc, SuperLoc, SuperType); |
2203 | | else |
2204 | | return new (Context) |
2205 | | ObjCPropertyRefExpr(Getter, Setter, Context.PseudoObjectTy, VK_LValue, |
2206 | | OK_ObjCProperty, MemberLoc, BaseExpr); |
2207 | | |
2208 | | } |
2209 | | |
2210 | | // Attempt to correct for typos in property names. |
2211 | | if (TypoCorrection Corrected = |
2212 | | CorrectTypo(DeclarationNameInfo(MemberName, MemberLoc), |
2213 | | LookupOrdinaryName, nullptr, nullptr, |
2214 | | llvm::make_unique<DeclFilterCCC<ObjCPropertyDecl>>(), |
2215 | | CTK_ErrorRecovery, IFace, false, OPT)) { |
2216 | | diagnoseTypo(Corrected, PDiag(diag::err_property_not_found_suggest) |
2217 | | << MemberName << QualType(OPT, 0)); |
2218 | | DeclarationName TypoResult = Corrected.getCorrection(); |
2219 | | return HandleExprPropertyRefExpr(OPT, BaseExpr, OpLoc, |
2220 | | TypoResult, MemberLoc, |
2221 | | SuperLoc, SuperType, Super); |
2222 | | } |
2223 | | ObjCInterfaceDecl *ClassDeclared; |
2224 | | if (ObjCIvarDecl *Ivar = |
2225 | | IFace->lookupInstanceVariable(Member, ClassDeclared)) { |
2226 | | QualType T = Ivar->getType(); |
2227 | | if (const ObjCObjectPointerType * OBJPT = |
2228 | | T->getAsObjCInterfacePointerType()) { |
2229 | | if (RequireCompleteType(MemberLoc, OBJPT->getPointeeType(), |
2230 | | diag::err_property_not_as_forward_class, |
2231 | | MemberName, BaseExpr)) |
2232 | | return ExprError(); |
2233 | | } |
2234 | | Diag(MemberLoc, |
2235 | | diag::err_ivar_access_using_property_syntax_suggest) |
2236 | | << MemberName << QualType(OPT, 0) << Ivar->getDeclName() |
2237 | | << FixItHint::CreateReplacement(OpLoc, "->"); |
2238 | | return ExprError(); |
2239 | | } |
2240 | | |
2241 | | Diag(MemberLoc, diag::err_property_not_found) |
2242 | | << MemberName << QualType(OPT, 0); |
2243 | | if (Setter) |
2244 | | Diag(Setter->getLocation(), diag::note_getter_unavailable) |
2245 | | << MemberName << BaseExpr->getSourceRange(); |
2246 | | return ExprError(); |
2247 | | } |
2248 | | |
2249 | | |
2250 | | |
2251 | | ExprResult Sema:: |
2252 | | ActOnClassPropertyRefExpr(IdentifierInfo &receiverName, |
2253 | | IdentifierInfo &propertyName, |
2254 | | SourceLocation receiverNameLoc, |
2255 | | SourceLocation propertyNameLoc) { |
2256 | | |
2257 | | IdentifierInfo *receiverNamePtr = &receiverName; |
2258 | | ObjCInterfaceDecl *IFace = getObjCInterfaceDecl(receiverNamePtr, |
2259 | | receiverNameLoc); |
2260 | | |
2261 | | QualType SuperType; |
2262 | | if (!IFace) { |
2263 | | // If the "receiver" is 'super' in a method, handle it as an expression-like |
2264 | | // property reference. |
2265 | | if (receiverNamePtr->isStr("super")) { |
2266 | | if (ObjCMethodDecl *CurMethod = tryCaptureObjCSelf(receiverNameLoc)) { |
2267 | | if (auto classDecl = CurMethod->getClassInterface()) { |
2268 | | SuperType = QualType(classDecl->getSuperClassType(), 0); |
2269 | | if (CurMethod->isInstanceMethod()) { |
2270 | | if (SuperType.isNull()) { |
2271 | | // The current class does not have a superclass. |
2272 | | Diag(receiverNameLoc, diag::error_root_class_cannot_use_super) |
2273 | | << CurMethod->getClassInterface()->getIdentifier(); |
2274 | | return ExprError(); |
2275 | | } |
2276 | | QualType T = Context.getObjCObjectPointerType(SuperType); |
2277 | | |
2278 | | return HandleExprPropertyRefExpr(T->castAs<ObjCObjectPointerType>(), |
2279 | | /*BaseExpr*/nullptr, |
2280 | | SourceLocation()/*OpLoc*/, |
2281 | | &propertyName, |
2282 | | propertyNameLoc, |
2283 | | receiverNameLoc, T, true); |
2284 | | } |
2285 | | |
2286 | | // Otherwise, if this is a class method, try dispatching to our |
2287 | | // superclass. |
2288 | | IFace = CurMethod->getClassInterface()->getSuperClass(); |
2289 | | } |
2290 | | } |
2291 | | } |
2292 | | |
2293 | | if (!IFace) { |
2294 | | Diag(receiverNameLoc, diag::err_expected_either) << tok::identifier |
2295 | | << tok::l_paren; |
2296 | | return ExprError(); |
2297 | | } |
2298 | | } |
2299 | | |
2300 | | // Search for a declared property first. |
2301 | | Selector Sel = PP.getSelectorTable().getNullarySelector(&propertyName); |
2302 | | ObjCMethodDecl *Getter = IFace->lookupClassMethod(Sel); |
2303 | | |
2304 | | // If this reference is in an @implementation, check for 'private' methods. |
2305 | | if (!Getter) |
2306 | | Getter = IFace->lookupPrivateClassMethod(Sel); |
2307 | | |
2308 | | if (Getter) { |
2309 | | // FIXME: refactor/share with ActOnMemberReference(). |
2310 | | // Check if we can reference this property. |
2311 | | if (DiagnoseUseOfDecl(Getter, propertyNameLoc)) |
2312 | | return ExprError(); |
2313 | | } |
2314 | | |
2315 | | // Look for the matching setter, in case it is needed. |
2316 | | Selector SetterSel = |
2317 | | SelectorTable::constructSetterSelector(PP.getIdentifierTable(), |
2318 | | PP.getSelectorTable(), |
2319 | | &propertyName); |
2320 | | |
2321 | | ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel); |
2322 | | if (!Setter) { |
2323 | | // If this reference is in an @implementation, also check for 'private' |
2324 | | // methods. |
2325 | | Setter = IFace->lookupPrivateClassMethod(SetterSel); |
2326 | | } |
2327 | | // Look through local category implementations associated with the class. |
2328 | | if (!Setter) |
2329 | | Setter = IFace->getCategoryClassMethod(SetterSel); |
2330 | | |
2331 | | if (Setter && DiagnoseUseOfDecl(Setter, propertyNameLoc)) |
2332 | | return ExprError(); |
2333 | | |
2334 | | if (Getter || Setter) { |
2335 | | if (!SuperType.isNull()) |
2336 | | return new (Context) |
2337 | | ObjCPropertyRefExpr(Getter, Setter, Context.PseudoObjectTy, VK_LValue, |
2338 | | OK_ObjCProperty, propertyNameLoc, receiverNameLoc, |
2339 | | SuperType); |
2340 | | |
2341 | | return new (Context) ObjCPropertyRefExpr( |
2342 | | Getter, Setter, Context.PseudoObjectTy, VK_LValue, OK_ObjCProperty, |
2343 | | propertyNameLoc, receiverNameLoc, IFace); |
2344 | | } |
2345 | | return ExprError(Diag(propertyNameLoc, diag::err_property_not_found) |
2346 | | << &propertyName << Context.getObjCInterfaceType(IFace)); |
2347 | | } |
2348 | | |
2349 | | namespace { |
2350 | | |
2351 | | class ObjCInterfaceOrSuperCCC : public CorrectionCandidateCallback { |
2352 | | public: |
2353 | | ObjCInterfaceOrSuperCCC(ObjCMethodDecl *Method) { |
2354 | | // Determine whether "super" is acceptable in the current context. |
2355 | | if (Method && Method->getClassInterface()) |
2356 | | WantObjCSuper = Method->getClassInterface()->getSuperClass(); |
2357 | | } |
2358 | | |
2359 | | bool ValidateCandidate(const TypoCorrection &candidate) override { |
2360 | | return candidate.getCorrectionDeclAs<ObjCInterfaceDecl>() || |
2361 | | candidate.isKeyword("super"); |
2362 | | } |
2363 | | }; |
2364 | | |
2365 | | } |
2366 | | |
2367 | | Sema::ObjCMessageKind Sema::getObjCMessageKind(Scope *S, |
2368 | | IdentifierInfo *Name, |
2369 | | SourceLocation NameLoc, |
2370 | | bool IsSuper, |
2371 | | bool HasTrailingDot, |
2372 | | ParsedType &ReceiverType) { |
2373 | | ReceiverType = ParsedType(); |
2374 | | |
2375 | | // If the identifier is "super" and there is no trailing dot, we're |
2376 | | // messaging super. If the identifier is "super" and there is a |
2377 | | // trailing dot, it's an instance message. |
2378 | | if (IsSuper && S->isInObjcMethodScope()) |
2379 | | return HasTrailingDot? ObjCInstanceMessage : ObjCSuperMessage; |
2380 | | |
2381 | | LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName); |
2382 | | LookupName(Result, S); |
2383 | | |
2384 | | switch (Result.getResultKind()) { |
2385 | | case LookupResult::NotFound: |
2386 | | // Normal name lookup didn't find anything. If we're in an |
2387 | | // Objective-C method, look for ivars. If we find one, we're done! |
2388 | | // FIXME: This is a hack. Ivar lookup should be part of normal |
2389 | | // lookup. |
2390 | | if (ObjCMethodDecl *Method = getCurMethodDecl()) { |
2391 | | if (!Method->getClassInterface()) { |
2392 | | // Fall back: let the parser try to parse it as an instance message. |
2393 | | return ObjCInstanceMessage; |
2394 | | } |
2395 | | |
2396 | | ObjCInterfaceDecl *ClassDeclared; |
2397 | | if (Method->getClassInterface()->lookupInstanceVariable(Name, |
2398 | | ClassDeclared)) |
2399 | | return ObjCInstanceMessage; |
2400 | | } |
2401 | | |
2402 | | // Break out; we'll perform typo correction below. |
2403 | | break; |
2404 | | |
2405 | | case LookupResult::NotFoundInCurrentInstantiation: |
2406 | | case LookupResult::FoundOverloaded: |
2407 | | case LookupResult::FoundUnresolvedValue: |
2408 | | case LookupResult::Ambiguous: |
2409 | | Result.suppressDiagnostics(); |
2410 | | return ObjCInstanceMessage; |
2411 | | |
2412 | | case LookupResult::Found: { |
2413 | | // If the identifier is a class or not, and there is a trailing dot, |
2414 | | // it's an instance message. |
2415 | | if (HasTrailingDot) |
2416 | | return ObjCInstanceMessage; |
2417 | | // We found something. If it's a type, then we have a class |
2418 | | // message. Otherwise, it's an instance message. |
2419 | | NamedDecl *ND = Result.getFoundDecl(); |
2420 | | QualType T; |
2421 | | if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(ND)) |
2422 | | T = Context.getObjCInterfaceType(Class); |
2423 | | else if (TypeDecl *Type = dyn_cast<TypeDecl>(ND)) { |
2424 | | T = Context.getTypeDeclType(Type); |
2425 | | DiagnoseUseOfDecl(Type, NameLoc); |
2426 | | } |
2427 | | else |
2428 | | return ObjCInstanceMessage; |
2429 | | |
2430 | | // We have a class message, and T is the type we're |
2431 | | // messaging. Build source-location information for it. |
2432 | | TypeSourceInfo *TSInfo = Context.getTrivialTypeSourceInfo(T, NameLoc); |
2433 | | ReceiverType = CreateParsedType(T, TSInfo); |
2434 | | return ObjCClassMessage; |
2435 | | } |
2436 | | } |
2437 | | |
2438 | | if (TypoCorrection Corrected = CorrectTypo( |
2439 | | Result.getLookupNameInfo(), Result.getLookupKind(), S, nullptr, |
2440 | | llvm::make_unique<ObjCInterfaceOrSuperCCC>(getCurMethodDecl()), |
2441 | | CTK_ErrorRecovery, nullptr, false, nullptr, false)) { |
2442 | | if (Corrected.isKeyword()) { |
2443 | | // If we've found the keyword "super" (the only keyword that would be |
2444 | | // returned by CorrectTypo), this is a send to super. |
2445 | | diagnoseTypo(Corrected, |
2446 | | PDiag(diag::err_unknown_receiver_suggest) << Name); |
2447 | | return ObjCSuperMessage; |
2448 | | } else if (ObjCInterfaceDecl *Class = |
2449 | | Corrected.getCorrectionDeclAs<ObjCInterfaceDecl>()) { |
2450 | | // If we found a declaration, correct when it refers to an Objective-C |
2451 | | // class. |
2452 | | diagnoseTypo(Corrected, |
2453 | | PDiag(diag::err_unknown_receiver_suggest) << Name); |
2454 | | QualType T = Context.getObjCInterfaceType(Class); |
2455 | | TypeSourceInfo *TSInfo = Context.getTrivialTypeSourceInfo(T, NameLoc); |
2456 | | ReceiverType = CreateParsedType(T, TSInfo); |
2457 | | return ObjCClassMessage; |
2458 | | } |
2459 | | } |
2460 | | |
2461 | | // Fall back: let the parser try to parse it as an instance message. |
2462 | | return ObjCInstanceMessage; |
2463 | | } |
2464 | | |
2465 | | ExprResult Sema::ActOnSuperMessage(Scope *S, |
2466 | | SourceLocation SuperLoc, |
2467 | | Selector Sel, |
2468 | | SourceLocation LBracLoc, |
2469 | | ArrayRef<SourceLocation> SelectorLocs, |
2470 | | SourceLocation RBracLoc, |
2471 | | MultiExprArg Args) { |
2472 | | // Determine whether we are inside a method or not. |
2473 | | ObjCMethodDecl *Method = tryCaptureObjCSelf(SuperLoc); |
2474 | | if (!Method) { |
2475 | | Diag(SuperLoc, diag::err_invalid_receiver_to_message_super); |
2476 | | return ExprError(); |
2477 | | } |
2478 | | |
2479 | | ObjCInterfaceDecl *Class = Method->getClassInterface(); |
2480 | | if (!Class) { |
2481 | | Diag(SuperLoc, diag::error_no_super_class_message) |
2482 | | << Method->getDeclName(); |
2483 | | return ExprError(); |
2484 | | } |
2485 | | |
2486 | | QualType SuperTy(Class->getSuperClassType(), 0); |
2487 | | if (SuperTy.isNull()) { |
2488 | | // The current class does not have a superclass. |
2489 | | Diag(SuperLoc, diag::error_root_class_cannot_use_super) |
2490 | | << Class->getIdentifier(); |
2491 | | return ExprError(); |
2492 | | } |
2493 | | |
2494 | | // We are in a method whose class has a superclass, so 'super' |
2495 | | // is acting as a keyword. |
2496 | | if (Method->getSelector() == Sel) |
2497 | | getCurFunction()->ObjCShouldCallSuper = false; |
2498 | | |
2499 | | if (Method->isInstanceMethod()) { |
2500 | | // Since we are in an instance method, this is an instance |
2501 | | // message to the superclass instance. |
2502 | | SuperTy = Context.getObjCObjectPointerType(SuperTy); |
2503 | | return BuildInstanceMessage(nullptr, SuperTy, SuperLoc, |
2504 | | Sel, /*Method=*/nullptr, |
2505 | | LBracLoc, SelectorLocs, RBracLoc, Args); |
2506 | | } |
2507 | | |
2508 | | // Since we are in a class method, this is a class message to |
2509 | | // the superclass. |
2510 | | return BuildClassMessage(/*ReceiverTypeInfo=*/nullptr, |
2511 | | SuperTy, |
2512 | | SuperLoc, Sel, /*Method=*/nullptr, |
2513 | | LBracLoc, SelectorLocs, RBracLoc, Args); |
2514 | | } |
2515 | | |
2516 | | |
2517 | | ExprResult Sema::BuildClassMessageImplicit(QualType ReceiverType, |
2518 | | bool isSuperReceiver, |
2519 | | SourceLocation Loc, |
2520 | | Selector Sel, |
2521 | | ObjCMethodDecl *Method, |
2522 | | MultiExprArg Args) { |
2523 | | TypeSourceInfo *receiverTypeInfo = nullptr; |
2524 | | if (!ReceiverType.isNull()) |
2525 | | receiverTypeInfo = Context.getTrivialTypeSourceInfo(ReceiverType); |
2526 | | |
2527 | | return BuildClassMessage(receiverTypeInfo, ReceiverType, |
2528 | | /*SuperLoc=*/isSuperReceiver ? Loc : SourceLocation(), |
2529 | | Sel, Method, Loc, Loc, Loc, Args, |
2530 | | /*isImplicit=*/true); |
2531 | | |
2532 | | } |
2533 | | |
2534 | | static void applyCocoaAPICheck(Sema &S, const ObjCMessageExpr *Msg, |
2535 | | unsigned DiagID, |
2536 | | bool (*refactor)(const ObjCMessageExpr *, |
2537 | | const NSAPI &, edit::Commit &)) { |
2538 | | SourceLocation MsgLoc = Msg->getExprLoc(); |
2539 | | if (S.Diags.isIgnored(DiagID, MsgLoc)) |
2540 | | return; |
2541 | | |
2542 | | SourceManager &SM = S.SourceMgr; |
2543 | | edit::Commit ECommit(SM, S.LangOpts); |
2544 | | if (refactor(Msg,*S.NSAPIObj, ECommit)) { |
2545 | | DiagnosticBuilder Builder = S.Diag(MsgLoc, DiagID) |
2546 | | << Msg->getSelector() << Msg->getSourceRange(); |
2547 | | // FIXME: Don't emit diagnostic at all if fixits are non-commitable. |
2548 | | if (!ECommit.isCommitable()) |
2549 | | return; |
2550 | | for (edit::Commit::edit_iterator |
2551 | | I = ECommit.edit_begin(), E = ECommit.edit_end(); I != E; ++I) { |
2552 | | const edit::Commit::Edit &Edit = *I; |
2553 | | switch (Edit.Kind) { |
2554 | | case edit::Commit::Act_Insert: |
2555 | | Builder.AddFixItHint(FixItHint::CreateInsertion(Edit.OrigLoc, |
2556 | | Edit.Text, |
2557 | | Edit.BeforePrev)); |
2558 | | break; |
2559 | | case edit::Commit::Act_InsertFromRange: |
2560 | | Builder.AddFixItHint( |
2561 | | FixItHint::CreateInsertionFromRange(Edit.OrigLoc, |
2562 | | Edit.getInsertFromRange(SM), |
2563 | | Edit.BeforePrev)); |
2564 | | break; |
2565 | | case edit::Commit::Act_Remove: |
2566 | | Builder.AddFixItHint(FixItHint::CreateRemoval(Edit.getFileRange(SM))); |
2567 | | break; |
2568 | | } |
2569 | | } |
2570 | | } |
2571 | | } |
2572 | | |
2573 | | static void checkCocoaAPI(Sema &S, const ObjCMessageExpr *Msg) { |
2574 | | applyCocoaAPICheck(S, Msg, diag::warn_objc_redundant_literal_use, |
2575 | | edit::rewriteObjCRedundantCallWithLiteral); |
2576 | | } |
2577 | | |
2578 | | /// \brief Diagnose use of %s directive in an NSString which is being passed |
2579 | | /// as formatting string to formatting method. |
2580 | | static void |
2581 | | DiagnoseCStringFormatDirectiveInObjCAPI(Sema &S, |
2582 | | ObjCMethodDecl *Method, |
2583 | | Selector Sel, |
2584 | | Expr **Args, unsigned NumArgs) { |
2585 | | unsigned Idx = 0; |
2586 | | bool Format = false; |
2587 | | ObjCStringFormatFamily SFFamily = Sel.getStringFormatFamily(); |
2588 | | if (SFFamily == ObjCStringFormatFamily::SFF_NSString) { |
2589 | | Idx = 0; |
2590 | | Format = true; |
2591 | | } |
2592 | | else if (Method) { |
2593 | | for (const auto *I : Method->specific_attrs<FormatAttr>()) { |
2594 | | if (S.GetFormatNSStringIdx(I, Idx)) { |
2595 | | Format = true; |
2596 | | break; |
2597 | | } |
2598 | | } |
2599 | | } |
2600 | | if (!Format || NumArgs <= Idx) |
2601 | | return; |
2602 | | |
2603 | | Expr *FormatExpr = Args[Idx]; |
2604 | | if (ObjCStringLiteral *OSL = |
2605 | | dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts())) { |
2606 | | StringLiteral *FormatString = OSL->getString(); |
2607 | | if (S.FormatStringHasSArg(FormatString)) { |
2608 | | S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string) |
2609 | | << "%s" << 0 << 0; |
2610 | | if (Method) |
2611 | | S.Diag(Method->getLocation(), diag::note_method_declared_at) |
2612 | | << Method->getDeclName(); |
2613 | | } |
2614 | | } |
2615 | | } |
2616 | | |
2617 | | /// \brief Build an Objective-C class message expression. |
2618 | | /// |
2619 | | /// This routine takes care of both normal class messages and |
2620 | | /// class messages to the superclass. |
2621 | | /// |
2622 | | /// \param ReceiverTypeInfo Type source information that describes the |
2623 | | /// receiver of this message. This may be NULL, in which case we are |
2624 | | /// sending to the superclass and \p SuperLoc must be a valid source |
2625 | | /// location. |
2626 | | |
2627 | | /// \param ReceiverType The type of the object receiving the |
2628 | | /// message. When \p ReceiverTypeInfo is non-NULL, this is the same |
2629 | | /// type as that refers to. For a superclass send, this is the type of |
2630 | | /// the superclass. |
2631 | | /// |
2632 | | /// \param SuperLoc The location of the "super" keyword in a |
2633 | | /// superclass message. |
2634 | | /// |
2635 | | /// \param Sel The selector to which the message is being sent. |
2636 | | /// |
2637 | | /// \param Method The method that this class message is invoking, if |
2638 | | /// already known. |
2639 | | /// |
2640 | | /// \param LBracLoc The location of the opening square bracket ']'. |
2641 | | /// |
2642 | | /// \param RBracLoc The location of the closing square bracket ']'. |
2643 | | /// |
2644 | | /// \param ArgsIn The message arguments. |
2645 | | ExprResult Sema::BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo, |
2646 | | QualType ReceiverType, |
2647 | | SourceLocation SuperLoc, |
2648 | | Selector Sel, |
2649 | | ObjCMethodDecl *Method, |
2650 | | SourceLocation LBracLoc, |
2651 | | ArrayRef<SourceLocation> SelectorLocs, |
2652 | | SourceLocation RBracLoc, |
2653 | | MultiExprArg ArgsIn, |
2654 | | bool isImplicit) { |
2655 | | SourceLocation Loc = SuperLoc.isValid()? SuperLoc |
2656 | | : ReceiverTypeInfo->getTypeLoc().getSourceRange().getBegin(); |
2657 | | if (LBracLoc.isInvalid()) { |
2658 | | Diag(Loc, diag::err_missing_open_square_message_send) |
2659 | | << FixItHint::CreateInsertion(Loc, "["); |
2660 | | LBracLoc = Loc; |
2661 | | } |
2662 | | SourceLocation SelLoc; |
2663 | | if (!SelectorLocs.empty() && SelectorLocs.front().isValid()) |
2664 | | SelLoc = SelectorLocs.front(); |
2665 | | else |
2666 | | SelLoc = Loc; |
2667 | | |
2668 | | if (ReceiverType->isDependentType()) { |
2669 | | // If the receiver type is dependent, we can't type-check anything |
2670 | | // at this point. Build a dependent expression. |
2671 | | unsigned NumArgs = ArgsIn.size(); |
2672 | | Expr **Args = ArgsIn.data(); |
2673 | | assert(SuperLoc.isInvalid() && "Message to super with dependent type"); |
2674 | | return ObjCMessageExpr::Create( |
2675 | | Context, ReceiverType, VK_RValue, LBracLoc, ReceiverTypeInfo, Sel, |
2676 | | SelectorLocs, /*Method=*/nullptr, makeArrayRef(Args, NumArgs), RBracLoc, |
2677 | | isImplicit); |
2678 | | } |
2679 | | |
2680 | | // Find the class to which we are sending this message. |
2681 | | ObjCInterfaceDecl *Class = nullptr; |
2682 | | const ObjCObjectType *ClassType = ReceiverType->getAs<ObjCObjectType>(); |
2683 | | if (!ClassType || !(Class = ClassType->getInterface())) { |
2684 | | Diag(Loc, diag::err_invalid_receiver_class_message) |
2685 | | << ReceiverType; |
2686 | | return ExprError(); |
2687 | | } |
2688 | | assert(Class && "We don't know which class we're messaging?"); |
2689 | | // objc++ diagnoses during typename annotation. |
2690 | | if (!getLangOpts().CPlusPlus) |
2691 | | (void)DiagnoseUseOfDecl(Class, SelLoc); |
2692 | | // Find the method we are messaging. |
2693 | | if (!Method) { |
2694 | | SourceRange TypeRange |
2695 | | = SuperLoc.isValid()? SourceRange(SuperLoc) |
2696 | | : ReceiverTypeInfo->getTypeLoc().getSourceRange(); |
2697 | | if (RequireCompleteType(Loc, Context.getObjCInterfaceType(Class), |
2698 | | (getLangOpts().ObjCAutoRefCount |
2699 | | ? diag::err_arc_receiver_forward_class |
2700 | | : diag::warn_receiver_forward_class), |
2701 | | TypeRange)) { |
2702 | | // A forward class used in messaging is treated as a 'Class' |
2703 | | Method = LookupFactoryMethodInGlobalPool(Sel, |
2704 | | SourceRange(LBracLoc, RBracLoc)); |
2705 | | if (Method && !getLangOpts().ObjCAutoRefCount) |
2706 | | Diag(Method->getLocation(), diag::note_method_sent_forward_class) |
2707 | | << Method->getDeclName(); |
2708 | | } |
2709 | | if (!Method) |
2710 | | Method = Class->lookupClassMethod(Sel); |
2711 | | |
2712 | | // If we have an implementation in scope, check "private" methods. |
2713 | | if (!Method) |
2714 | | Method = Class->lookupPrivateClassMethod(Sel); |
2715 | | |
2716 | | if (Method && DiagnoseUseOfDecl(Method, SelLoc)) |
2717 | | return ExprError(); |
2718 | | } |
2719 | | |
2720 | | // Check the argument types and determine the result type. |
2721 | | QualType ReturnType; |
2722 | | ExprValueKind VK = VK_RValue; |
2723 | | |
2724 | | unsigned NumArgs = ArgsIn.size(); |
2725 | | Expr **Args = ArgsIn.data(); |
2726 | | if (CheckMessageArgumentTypes(ReceiverType, MultiExprArg(Args, NumArgs), |
2727 | | Sel, SelectorLocs, |
2728 | | Method, true, |
2729 | | SuperLoc.isValid(), LBracLoc, RBracLoc, |
2730 | | SourceRange(), |
2731 | | ReturnType, VK)) |
2732 | | return ExprError(); |
2733 | | |
2734 | | if (Method && !Method->getReturnType()->isVoidType() && |
2735 | | RequireCompleteType(LBracLoc, Method->getReturnType(), |
2736 | | diag::err_illegal_message_expr_incomplete_type)) |
2737 | | return ExprError(); |
2738 | | |
2739 | | // Warn about explicit call of +initialize on its own class. But not on 'super'. |
2740 | | if (Method && Method->getMethodFamily() == OMF_initialize) { |
2741 | | if (!SuperLoc.isValid()) { |
2742 | | const ObjCInterfaceDecl *ID = |
2743 | | dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()); |
2744 | | if (ID == Class) { |
2745 | | Diag(Loc, diag::warn_direct_initialize_call); |
2746 | | Diag(Method->getLocation(), diag::note_method_declared_at) |
2747 | | << Method->getDeclName(); |
2748 | | } |
2749 | | } |
2750 | | else if (ObjCMethodDecl *CurMeth = getCurMethodDecl()) { |
2751 | | // [super initialize] is allowed only within an +initialize implementation |
2752 | | if (CurMeth->getMethodFamily() != OMF_initialize) { |
2753 | | Diag(Loc, diag::warn_direct_super_initialize_call); |
2754 | | Diag(Method->getLocation(), diag::note_method_declared_at) |
2755 | | << Method->getDeclName(); |
2756 | | Diag(CurMeth->getLocation(), diag::note_method_declared_at) |
2757 | | << CurMeth->getDeclName(); |
2758 | | } |
2759 | | } |
2760 | | } |
2761 | | |
2762 | | DiagnoseCStringFormatDirectiveInObjCAPI(*this, Method, Sel, Args, NumArgs); |
2763 | | |
2764 | | // Construct the appropriate ObjCMessageExpr. |
2765 | | ObjCMessageExpr *Result; |
2766 | | if (SuperLoc.isValid()) |
2767 | | Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc, |
2768 | | SuperLoc, /*IsInstanceSuper=*/false, |
2769 | | ReceiverType, Sel, SelectorLocs, |
2770 | | Method, makeArrayRef(Args, NumArgs), |
2771 | | RBracLoc, isImplicit); |
2772 | | else { |
2773 | | Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc, |
2774 | | ReceiverTypeInfo, Sel, SelectorLocs, |
2775 | | Method, makeArrayRef(Args, NumArgs), |
2776 | | RBracLoc, isImplicit); |
2777 | | if (!isImplicit) |
2778 | | checkCocoaAPI(*this, Result); |
2779 | | } |
2780 | | return MaybeBindToTemporary(Result); |
2781 | | } |
2782 | | |
2783 | | // ActOnClassMessage - used for both unary and keyword messages. |
2784 | | // ArgExprs is optional - if it is present, the number of expressions |
2785 | | // is obtained from Sel.getNumArgs(). |
2786 | | ExprResult Sema::ActOnClassMessage(Scope *S, |
2787 | | ParsedType Receiver, |
2788 | | Selector Sel, |
2789 | | SourceLocation LBracLoc, |
2790 | | ArrayRef<SourceLocation> SelectorLocs, |
2791 | | SourceLocation RBracLoc, |
2792 | | MultiExprArg Args) { |
2793 | | TypeSourceInfo *ReceiverTypeInfo; |
2794 | | QualType ReceiverType = GetTypeFromParser(Receiver, &ReceiverTypeInfo); |
2795 | | if (ReceiverType.isNull()) |
2796 | | return ExprError(); |
2797 | | |
2798 | | |
2799 | | if (!ReceiverTypeInfo) |
2800 | | ReceiverTypeInfo = Context.getTrivialTypeSourceInfo(ReceiverType, LBracLoc); |
2801 | | |
2802 | | return BuildClassMessage(ReceiverTypeInfo, ReceiverType, |
2803 | | /*SuperLoc=*/SourceLocation(), Sel, |
2804 | | /*Method=*/nullptr, LBracLoc, SelectorLocs, RBracLoc, |
2805 | | Args); |
2806 | | } |
2807 | | |
2808 | | ExprResult Sema::BuildInstanceMessageImplicit(Expr *Receiver, |
2809 | | QualType ReceiverType, |
2810 | | SourceLocation Loc, |
2811 | | Selector Sel, |
2812 | | ObjCMethodDecl *Method, |
2813 | | MultiExprArg Args) { |
2814 | | return BuildInstanceMessage(Receiver, ReceiverType, |
2815 | | /*SuperLoc=*/!Receiver ? Loc : SourceLocation(), |
2816 | | Sel, Method, Loc, Loc, Loc, Args, |
2817 | | /*isImplicit=*/true); |
2818 | | } |
2819 | | |
2820 | | /// \brief Build an Objective-C instance message expression. |
2821 | | /// |
2822 | | /// This routine takes care of both normal instance messages and |
2823 | | /// instance messages to the superclass instance. |
2824 | | /// |
2825 | | /// \param Receiver The expression that computes the object that will |
2826 | | /// receive this message. This may be empty, in which case we are |
2827 | | /// sending to the superclass instance and \p SuperLoc must be a valid |
2828 | | /// source location. |
2829 | | /// |
2830 | | /// \param ReceiverType The (static) type of the object receiving the |
2831 | | /// message. When a \p Receiver expression is provided, this is the |
2832 | | /// same type as that expression. For a superclass instance send, this |
2833 | | /// is a pointer to the type of the superclass. |
2834 | | /// |
2835 | | /// \param SuperLoc The location of the "super" keyword in a |
2836 | | /// superclass instance message. |
2837 | | /// |
2838 | | /// \param Sel The selector to which the message is being sent. |
2839 | | /// |
2840 | | /// \param Method The method that this instance message is invoking, if |
2841 | | /// already known. |
2842 | | /// |
2843 | | /// \param LBracLoc The location of the opening square bracket ']'. |
2844 | | /// |
2845 | | /// \param RBracLoc The location of the closing square bracket ']'. |
2846 | | /// |
2847 | | /// \param ArgsIn The message arguments. |
2848 | | ExprResult Sema::BuildInstanceMessage(Expr *Receiver, |
2849 | | QualType ReceiverType, |
2850 | | SourceLocation SuperLoc, |
2851 | | Selector Sel, |
2852 | | ObjCMethodDecl *Method, |
2853 | | SourceLocation LBracLoc, |
2854 | | ArrayRef<SourceLocation> SelectorLocs, |
2855 | | SourceLocation RBracLoc, |
2856 | | MultiExprArg ArgsIn, |
2857 | | bool isImplicit) { |
2858 | | // The location of the receiver. |
2859 | | SourceLocation Loc = SuperLoc.isValid()? SuperLoc : Receiver->getLocStart(); |
2860 | | SourceRange RecRange = |
2861 | | SuperLoc.isValid()? SuperLoc : Receiver->getSourceRange(); |
2862 | | SourceLocation SelLoc; |
2863 | | if (!SelectorLocs.empty() && SelectorLocs.front().isValid()) |
2864 | | SelLoc = SelectorLocs.front(); |
2865 | | else |
2866 | | SelLoc = Loc; |
2867 | | |
2868 | | if (LBracLoc.isInvalid()) { |
2869 | | Diag(Loc, diag::err_missing_open_square_message_send) |
2870 | | << FixItHint::CreateInsertion(Loc, "["); |
2871 | | LBracLoc = Loc; |
2872 | | } |
2873 | | |
2874 | | // If we have a receiver expression, perform appropriate promotions |
2875 | | // and determine receiver type. |
2876 | | if (Receiver) { |
2877 | | if (Receiver->hasPlaceholderType()) { |
2878 | | ExprResult Result; |
2879 | | if (Receiver->getType() == Context.UnknownAnyTy) |
2880 | | Result = forceUnknownAnyToType(Receiver, Context.getObjCIdType()); |
2881 | | else |
2882 | | Result = CheckPlaceholderExpr(Receiver); |
2883 | | if (Result.isInvalid()) return ExprError(); |
2884 | | Receiver = Result.get(); |
2885 | | } |
2886 | | |
2887 | | if (Receiver->isTypeDependent()) { |
2888 | | // If the receiver is type-dependent, we can't type-check anything |
2889 | | // at this point. Build a dependent expression. |
2890 | | unsigned NumArgs = ArgsIn.size(); |
2891 | | Expr **Args = ArgsIn.data(); |
2892 | | assert(SuperLoc.isInvalid() && "Message to super with dependent type"); |
2893 | | return ObjCMessageExpr::Create( |
2894 | | Context, Context.DependentTy, VK_RValue, LBracLoc, Receiver, Sel, |
2895 | | SelectorLocs, /*Method=*/nullptr, makeArrayRef(Args, NumArgs), |
2896 | | RBracLoc, isImplicit); |
2897 | | } |
2898 | | |
2899 | | // If necessary, apply function/array conversion to the receiver. |
2900 | | // C99 6.7.5.3p[7,8]. |
2901 | | ExprResult Result = DefaultFunctionArrayLvalueConversion(Receiver); |
2902 | | if (Result.isInvalid()) |
2903 | | return ExprError(); |
2904 | | Receiver = Result.get(); |
2905 | | ReceiverType = Receiver->getType(); |
2906 | | |
2907 | | // If the receiver is an ObjC pointer, a block pointer, or an |
2908 | | // __attribute__((NSObject)) pointer, we don't need to do any |
2909 | | // special conversion in order to look up a receiver. |
2910 | | if (ReceiverType->isObjCRetainableType()) { |
2911 | | // do nothing |
2912 | | } else if (!getLangOpts().ObjCAutoRefCount && |
2913 | | !Context.getObjCIdType().isNull() && |
2914 | | (ReceiverType->isPointerType() || |
2915 | | ReceiverType->isIntegerType())) { |
2916 | | // Implicitly convert integers and pointers to 'id' but emit a warning. |
2917 | | // But not in ARC. |
2918 | | Diag(Loc, diag::warn_bad_receiver_type) |
2919 | | << ReceiverType |
2920 | | << Receiver->getSourceRange(); |
2921 | | if (ReceiverType->isPointerType()) { |
2922 | | Receiver = ImpCastExprToType(Receiver, Context.getObjCIdType(), |
2923 | | CK_CPointerToObjCPointerCast).get(); |
2924 | | } else { |
2925 | | // TODO: specialized warning on null receivers? |
2926 | | bool IsNull = Receiver->isNullPointerConstant(Context, |
2927 | | Expr::NPC_ValueDependentIsNull); |
2928 | | CastKind Kind = IsNull ? CK_NullToPointer : CK_IntegralToPointer; |
2929 | | Receiver = ImpCastExprToType(Receiver, Context.getObjCIdType(), |
2930 | | Kind).get(); |
2931 | | } |
2932 | | ReceiverType = Receiver->getType(); |
2933 | | } else if (getLangOpts().CPlusPlus) { |
2934 | | // The receiver must be a complete type. |
2935 | | if (RequireCompleteType(Loc, Receiver->getType(), |
2936 | | diag::err_incomplete_receiver_type)) |
2937 | | return ExprError(); |
2938 | | |
2939 | | ExprResult result = PerformContextuallyConvertToObjCPointer(Receiver); |
2940 | | if (result.isUsable()) { |
2941 | | Receiver = result.get(); |
2942 | | ReceiverType = Receiver->getType(); |
2943 | | } |
2944 | | } |
2945 | | } |
2946 | | |
2947 | | // There's a somewhat weird interaction here where we assume that we |
2948 | | // won't actually have a method unless we also don't need to do some |
2949 | | // of the more detailed type-checking on the receiver. |
2950 | | |
2951 | | if (!Method) { |
2952 | | // Handle messages to id and __kindof types (where we use the |
2953 | | // global method pool). |
2954 | | // FIXME: The type bound is currently ignored by lookup in the |
2955 | | // global pool. |
2956 | | const ObjCObjectType *typeBound = nullptr; |
2957 | | bool receiverIsIdLike = ReceiverType->isObjCIdOrObjectKindOfType(Context, |
2958 | | typeBound); |
2959 | | if (receiverIsIdLike || ReceiverType->isBlockPointerType() || |
2960 | | (Receiver && Context.isObjCNSObjectType(Receiver->getType()))) { |
2961 | | Method = LookupInstanceMethodInGlobalPool(Sel, |
2962 | | SourceRange(LBracLoc, RBracLoc), |
2963 | | receiverIsIdLike); |
2964 | | if (!Method) |
2965 | | Method = LookupFactoryMethodInGlobalPool(Sel, |
2966 | | SourceRange(LBracLoc,RBracLoc), |
2967 | | receiverIsIdLike); |
2968 | | if (Method) { |
2969 | | if (ObjCMethodDecl *BestMethod = |
2970 | | SelectBestMethod(Sel, ArgsIn, Method->isInstanceMethod())) |
2971 | | Method = BestMethod; |
2972 | | if (!AreMultipleMethodsInGlobalPool(Sel, Method, |
2973 | | SourceRange(LBracLoc, RBracLoc), |
2974 | | receiverIsIdLike)) { |
2975 | | DiagnoseUseOfDecl(Method, SelLoc); |
2976 | | } |
2977 | | } |
2978 | | } else if (ReceiverType->isObjCClassOrClassKindOfType() || |
2979 | | ReceiverType->isObjCQualifiedClassType()) { |
2980 | | // Handle messages to Class. |
2981 | | // We allow sending a message to a qualified Class ("Class<foo>"), which |
2982 | | // is ok as long as one of the protocols implements the selector (if not, |
2983 | | // warn). |
2984 | | if (!ReceiverType->isObjCClassOrClassKindOfType()) { |
2985 | | const ObjCObjectPointerType *QClassTy |
2986 | | = ReceiverType->getAsObjCQualifiedClassType(); |
2987 | | // Search protocols for class methods. |
2988 | | Method = LookupMethodInQualifiedType(Sel, QClassTy, false); |
2989 | | if (!Method) { |
2990 | | Method = LookupMethodInQualifiedType(Sel, QClassTy, true); |
2991 | | // warn if instance method found for a Class message. |
2992 | | if (Method) { |
2993 | | Diag(SelLoc, diag::warn_instance_method_on_class_found) |
2994 | | << Method->getSelector() << Sel; |
2995 | | Diag(Method->getLocation(), diag::note_method_declared_at) |
2996 | | << Method->getDeclName(); |
2997 | | } |
2998 | | } |
2999 | | } else { |
3000 | | if (ObjCMethodDecl *CurMeth = getCurMethodDecl()) { |
3001 | | if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface()) { |
3002 | | // First check the public methods in the class interface. |
3003 | | Method = ClassDecl->lookupClassMethod(Sel); |
3004 | | |
3005 | | if (!Method) |
3006 | | Method = ClassDecl->lookupPrivateClassMethod(Sel); |
3007 | | } |
3008 | | if (Method && DiagnoseUseOfDecl(Method, SelLoc)) |
3009 | | return ExprError(); |
3010 | | } |
3011 | | if (!Method) { |
3012 | | // If not messaging 'self', look for any factory method named 'Sel'. |
3013 | | if (!Receiver || !isSelfExpr(Receiver)) { |
3014 | | Method = LookupFactoryMethodInGlobalPool(Sel, |
3015 | | SourceRange(LBracLoc, RBracLoc)); |
3016 | | if (!Method) { |
3017 | | // If no class (factory) method was found, check if an _instance_ |
3018 | | // method of the same name exists in the root class only. |
3019 | | Method = LookupInstanceMethodInGlobalPool(Sel, |
3020 | | SourceRange(LBracLoc, RBracLoc)); |
3021 | | if (Method) |
3022 | | if (const ObjCInterfaceDecl *ID = |
3023 | | dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext())) { |
3024 | | if (ID->getSuperClass()) |
3025 | | Diag(SelLoc, diag::warn_root_inst_method_not_found) |
3026 | | << Sel << SourceRange(LBracLoc, RBracLoc); |
3027 | | } |
3028 | | } |
3029 | | if (Method) |
3030 | | if (ObjCMethodDecl *BestMethod = |
3031 | | SelectBestMethod(Sel, ArgsIn, Method->isInstanceMethod())) |
3032 | | Method = BestMethod; |
3033 | | } |
3034 | | } |
3035 | | } |
3036 | | } else { |
3037 | | ObjCInterfaceDecl *ClassDecl = nullptr; |
3038 | | |
3039 | | // We allow sending a message to a qualified ID ("id<foo>"), which is ok as |
3040 | | // long as one of the protocols implements the selector (if not, warn). |
3041 | | // And as long as message is not deprecated/unavailable (warn if it is). |
3042 | | if (const ObjCObjectPointerType *QIdTy |
3043 | | = ReceiverType->getAsObjCQualifiedIdType()) { |
3044 | | // Search protocols for instance methods. |
3045 | | Method = LookupMethodInQualifiedType(Sel, QIdTy, true); |
3046 | | if (!Method) |
3047 | | Method = LookupMethodInQualifiedType(Sel, QIdTy, false); |
3048 | | if (Method && DiagnoseUseOfDecl(Method, SelLoc)) |
3049 | | return ExprError(); |
3050 | | } else if (const ObjCObjectPointerType *OCIType |
3051 | | = ReceiverType->getAsObjCInterfacePointerType()) { |
3052 | | // We allow sending a message to a pointer to an interface (an object). |
3053 | | ClassDecl = OCIType->getInterfaceDecl(); |
3054 | | |
3055 | | // Try to complete the type. Under ARC, this is a hard error from which |
3056 | | // we don't try to recover. |
3057 | | const ObjCInterfaceDecl *forwardClass = nullptr; |
3058 | | if (RequireCompleteType(Loc, OCIType->getPointeeType(), |
3059 | | getLangOpts().ObjCAutoRefCount |
3060 | | ? diag::err_arc_receiver_forward_instance |
3061 | | : diag::warn_receiver_forward_instance, |
3062 | | Receiver? Receiver->getSourceRange() |
3063 | | : SourceRange(SuperLoc))) { |
3064 | | if (getLangOpts().ObjCAutoRefCount) |
3065 | | return ExprError(); |
3066 | | |
3067 | | forwardClass = OCIType->getInterfaceDecl(); |
3068 | | Diag(Receiver ? Receiver->getLocStart() |
3069 | | : SuperLoc, diag::note_receiver_is_id); |
3070 | | Method = nullptr; |
3071 | | } else { |
3072 | | Method = ClassDecl->lookupInstanceMethod(Sel); |
3073 | | } |
3074 | | |
3075 | | if (!Method) |
3076 | | // Search protocol qualifiers. |
3077 | | Method = LookupMethodInQualifiedType(Sel, OCIType, true); |
3078 | | |
3079 | | if (!Method) { |
3080 | | // If we have implementations in scope, check "private" methods. |
3081 | | Method = ClassDecl->lookupPrivateMethod(Sel); |
3082 | | |
3083 | | if (!Method && getLangOpts().ObjCAutoRefCount) { |
3084 | | Diag(SelLoc, diag::err_arc_may_not_respond) |
3085 | | << OCIType->getPointeeType() << Sel << RecRange |
3086 | | << SourceRange(SelectorLocs.front(), SelectorLocs.back()); |
3087 | | return ExprError(); |
3088 | | } |
3089 | | |
3090 | | if (!Method && (!Receiver || !isSelfExpr(Receiver))) { |
3091 | | // If we still haven't found a method, look in the global pool. This |
3092 | | // behavior isn't very desirable, however we need it for GCC |
3093 | | // compatibility. FIXME: should we deviate?? |
3094 | | if (OCIType->qual_empty()) { |
3095 | | Method = LookupInstanceMethodInGlobalPool(Sel, |
3096 | | SourceRange(LBracLoc, RBracLoc)); |
3097 | | if (Method) { |
3098 | | if (auto BestMethod = |
3099 | | SelectBestMethod(Sel, ArgsIn, Method->isInstanceMethod())) |
3100 | | Method = BestMethod; |
3101 | | AreMultipleMethodsInGlobalPool(Sel, Method, |
3102 | | SourceRange(LBracLoc, RBracLoc), |
3103 | | true); |
3104 | | } |
3105 | | if (Method && !forwardClass) |
3106 | | Diag(SelLoc, diag::warn_maynot_respond) |
3107 | | << OCIType->getInterfaceDecl()->getIdentifier() |
3108 | | << Sel << RecRange; |
3109 | | } |
3110 | | } |
3111 | | } |
3112 | | if (Method && DiagnoseUseOfDecl(Method, SelLoc, forwardClass)) |
3113 | | return ExprError(); |
3114 | | } else { |
3115 | | // Reject other random receiver types (e.g. structs). |
3116 | | Diag(Loc, diag::err_bad_receiver_type) |
3117 | | << ReceiverType << Receiver->getSourceRange(); |
3118 | | return ExprError(); |
3119 | | } |
3120 | | } |
3121 | | } |
3122 | | |
3123 | | FunctionScopeInfo *DIFunctionScopeInfo = |
3124 | | (Method && Method->getMethodFamily() == OMF_init) |
3125 | | ? getEnclosingFunction() : nullptr; |
3126 | | |
3127 | | if (DIFunctionScopeInfo && |
3128 | | DIFunctionScopeInfo->ObjCIsDesignatedInit && |
3129 | | (SuperLoc.isValid() || isSelfExpr(Receiver))) { |
3130 | | bool isDesignatedInitChain = false; |
3131 | | if (SuperLoc.isValid()) { |
3132 | | if (const ObjCObjectPointerType * |
3133 | | OCIType = ReceiverType->getAsObjCInterfacePointerType()) { |
3134 | | if (const ObjCInterfaceDecl *ID = OCIType->getInterfaceDecl()) { |
3135 | | // Either we know this is a designated initializer or we |
3136 | | // conservatively assume it because we don't know for sure. |
3137 | | if (!ID->declaresOrInheritsDesignatedInitializers() || |
3138 | | ID->isDesignatedInitializer(Sel)) { |
3139 | | isDesignatedInitChain = true; |
3140 | | DIFunctionScopeInfo->ObjCWarnForNoDesignatedInitChain = false; |
3141 | | } |
3142 | | } |
3143 | | } |
3144 | | } |
3145 | | if (!isDesignatedInitChain) { |
3146 | | const ObjCMethodDecl *InitMethod = nullptr; |
3147 | | bool isDesignated = |
3148 | | getCurMethodDecl()->isDesignatedInitializerForTheInterface(&InitMethod); |
3149 | | assert(isDesignated && InitMethod); |
3150 | | (void)isDesignated; |
3151 | | Diag(SelLoc, SuperLoc.isValid() ? |
3152 | | diag::warn_objc_designated_init_non_designated_init_call : |
3153 | | diag::warn_objc_designated_init_non_super_designated_init_call); |
3154 | | Diag(InitMethod->getLocation(), |
3155 | | diag::note_objc_designated_init_marked_here); |
3156 | | } |
3157 | | } |
3158 | | |
3159 | | if (DIFunctionScopeInfo && |
3160 | | DIFunctionScopeInfo->ObjCIsSecondaryInit && |
3161 | | (SuperLoc.isValid() || isSelfExpr(Receiver))) { |
3162 | | if (SuperLoc.isValid()) { |
3163 | | Diag(SelLoc, diag::warn_objc_secondary_init_super_init_call); |
3164 | | } else { |
3165 | | DIFunctionScopeInfo->ObjCWarnForNoInitDelegation = false; |
3166 | | } |
3167 | | } |
3168 | | |
3169 | | // Check the message arguments. |
3170 | | unsigned NumArgs = ArgsIn.size(); |
3171 | | Expr **Args = ArgsIn.data(); |
3172 | | QualType ReturnType; |
3173 | | ExprValueKind VK = VK_RValue; |
3174 | | bool ClassMessage = (ReceiverType->isObjCClassType() || |
3175 | | ReceiverType->isObjCQualifiedClassType()); |
3176 | | if (CheckMessageArgumentTypes(ReceiverType, MultiExprArg(Args, NumArgs), |
3177 | | Sel, SelectorLocs, Method, |
3178 | | ClassMessage, SuperLoc.isValid(), |
3179 | | LBracLoc, RBracLoc, RecRange, ReturnType, VK)) |
3180 | | return ExprError(); |
3181 | | |
3182 | | if (Method && !Method->getReturnType()->isVoidType() && |
3183 | | RequireCompleteType(LBracLoc, Method->getReturnType(), |
3184 | | diag::err_illegal_message_expr_incomplete_type)) |
3185 | | return ExprError(); |
3186 | | |
3187 | | // In ARC, forbid the user from sending messages to |
3188 | | // retain/release/autorelease/dealloc/retainCount explicitly. |
3189 | | if (getLangOpts().ObjCAutoRefCount) { |
3190 | | ObjCMethodFamily family = |
3191 | | (Method ? Method->getMethodFamily() : Sel.getMethodFamily()); |
3192 | | switch (family) { |
3193 | | case OMF_init: |
3194 | | if (Method) |
3195 | | checkInitMethod(Method, ReceiverType); |
3196 | | |
3197 | | case OMF_None: |
3198 | | case OMF_alloc: |
3199 | | case OMF_copy: |
3200 | | case OMF_finalize: |
3201 | | case OMF_mutableCopy: |
3202 | | case OMF_new: |
3203 | | case OMF_self: |
3204 | | case OMF_initialize: |
3205 | | break; |
3206 | | |
3207 | | case OMF_dealloc: |
3208 | | case OMF_retain: |
3209 | | case OMF_release: |
3210 | | case OMF_autorelease: |
3211 | | case OMF_retainCount: |
3212 | | Diag(SelLoc, diag::err_arc_illegal_explicit_message) |
3213 | | << Sel << RecRange; |
3214 | | break; |
3215 | | |
3216 | | case OMF_performSelector: |
3217 | | if (Method && NumArgs >= 1) { |
3218 | | if (ObjCSelectorExpr *SelExp = dyn_cast<ObjCSelectorExpr>(Args[0])) { |
3219 | | Selector ArgSel = SelExp->getSelector(); |
3220 | | ObjCMethodDecl *SelMethod = |
3221 | | LookupInstanceMethodInGlobalPool(ArgSel, |
3222 | | SelExp->getSourceRange()); |
3223 | | if (!SelMethod) |
3224 | | SelMethod = |
3225 | | LookupFactoryMethodInGlobalPool(ArgSel, |
3226 | | SelExp->getSourceRange()); |
3227 | | if (SelMethod) { |
3228 | | ObjCMethodFamily SelFamily = SelMethod->getMethodFamily(); |
3229 | | switch (SelFamily) { |
3230 | | case OMF_alloc: |
3231 | | case OMF_copy: |
3232 | | case OMF_mutableCopy: |
3233 | | case OMF_new: |
3234 | | case OMF_self: |
3235 | | case OMF_init: |
3236 | | // Issue error, unless ns_returns_not_retained. |
3237 | | if (!SelMethod->hasAttr<NSReturnsNotRetainedAttr>()) { |
3238 | | // selector names a +1 method |
3239 | | Diag(SelLoc, |
3240 | | diag::err_arc_perform_selector_retains); |
3241 | | Diag(SelMethod->getLocation(), diag::note_method_declared_at) |
3242 | | << SelMethod->getDeclName(); |
3243 | | } |
3244 | | break; |
3245 | | default: |
3246 | | // +0 call. OK. unless ns_returns_retained. |
3247 | | if (SelMethod->hasAttr<NSReturnsRetainedAttr>()) { |
3248 | | // selector names a +1 method |
3249 | | Diag(SelLoc, |
3250 | | diag::err_arc_perform_selector_retains); |
3251 | | Diag(SelMethod->getLocation(), diag::note_method_declared_at) |
3252 | | << SelMethod->getDeclName(); |
3253 | | } |
3254 | | break; |
3255 | | } |
3256 | | } |
3257 | | } else { |
3258 | | // error (may leak). |
3259 | | Diag(SelLoc, diag::warn_arc_perform_selector_leaks); |
3260 | | Diag(Args[0]->getExprLoc(), diag::note_used_here); |
3261 | | } |
3262 | | } |
3263 | | break; |
3264 | | } |
3265 | | } |
3266 | | |
3267 | | DiagnoseCStringFormatDirectiveInObjCAPI(*this, Method, Sel, Args, NumArgs); |
3268 | | |
3269 | | // Construct the appropriate ObjCMessageExpr instance. |
3270 | | ObjCMessageExpr *Result; |
3271 | | if (SuperLoc.isValid()) |
3272 | | Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc, |
3273 | | SuperLoc, /*IsInstanceSuper=*/true, |
3274 | | ReceiverType, Sel, SelectorLocs, Method, |
3275 | | makeArrayRef(Args, NumArgs), RBracLoc, |
3276 | | isImplicit); |
3277 | | else { |
3278 | | Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc, |
3279 | | Receiver, Sel, SelectorLocs, Method, |
3280 | | makeArrayRef(Args, NumArgs), RBracLoc, |
3281 | | isImplicit); |
3282 | | if (!isImplicit) |
3283 | | checkCocoaAPI(*this, Result); |
3284 | | } |
3285 | | |
3286 | | if (getLangOpts().ObjCAutoRefCount) { |
3287 | | // In ARC, annotate delegate init calls. |
3288 | | if (Result->getMethodFamily() == OMF_init && |
3289 | | (SuperLoc.isValid() || isSelfExpr(Receiver))) { |
3290 | | // Only consider init calls *directly* in init implementations, |
3291 | | // not within blocks. |
3292 | | ObjCMethodDecl *method = dyn_cast<ObjCMethodDecl>(CurContext); |
3293 | | if (method && method->getMethodFamily() == OMF_init) { |
3294 | | // The implicit assignment to self means we also don't want to |
3295 | | // consume the result. |
3296 | | Result->setDelegateInitCall(true); |
3297 | | return Result; |
3298 | | } |
3299 | | } |
3300 | | |
3301 | | // In ARC, check for message sends which are likely to introduce |
3302 | | // retain cycles. |
3303 | | checkRetainCycles(Result); |
3304 | | |
3305 | | if (!isImplicit && Method) { |
3306 | | if (const ObjCPropertyDecl *Prop = Method->findPropertyDecl()) { |
3307 | | bool IsWeak = |
3308 | | Prop->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_weak; |
3309 | | if (!IsWeak && Sel.isUnarySelector()) |
3310 | | IsWeak = ReturnType.getObjCLifetime() & Qualifiers::OCL_Weak; |
3311 | | if (IsWeak && |
3312 | | !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, LBracLoc)) |
3313 | | getCurFunction()->recordUseOfWeak(Result, Prop); |
3314 | | } |
3315 | | } |
3316 | | } |
3317 | | |
3318 | | CheckObjCCircularContainer(Result); |
3319 | | |
3320 | | return MaybeBindToTemporary(Result); |
3321 | | } |
3322 | | |
3323 | | static void RemoveSelectorFromWarningCache(Sema &S, Expr* Arg) { |
3324 | | if (ObjCSelectorExpr *OSE = |
3325 | | dyn_cast<ObjCSelectorExpr>(Arg->IgnoreParenCasts())) { |
3326 | | Selector Sel = OSE->getSelector(); |
3327 | | SourceLocation Loc = OSE->getAtLoc(); |
3328 | | auto Pos = S.ReferencedSelectors.find(Sel); |
3329 | | if (Pos != S.ReferencedSelectors.end() && Pos->second == Loc) |
3330 | | S.ReferencedSelectors.erase(Pos); |
3331 | | } |
3332 | | } |
3333 | | |
3334 | | // ActOnInstanceMessage - used for both unary and keyword messages. |
3335 | | // ArgExprs is optional - if it is present, the number of expressions |
3336 | | // is obtained from Sel.getNumArgs(). |
3337 | | ExprResult Sema::ActOnInstanceMessage(Scope *S, |
3338 | | Expr *Receiver, |
3339 | | Selector Sel, |
3340 | | SourceLocation LBracLoc, |
3341 | | ArrayRef<SourceLocation> SelectorLocs, |
3342 | | SourceLocation RBracLoc, |
3343 | | MultiExprArg Args) { |
3344 | | if (!Receiver) |
3345 | | return ExprError(); |
3346 | | |
3347 | | // A ParenListExpr can show up while doing error recovery with invalid code. |
3348 | | if (isa<ParenListExpr>(Receiver)) { |
3349 | | ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Receiver); |
3350 | | if (Result.isInvalid()) return ExprError(); |
3351 | | Receiver = Result.get(); |
3352 | | } |
3353 | | |
3354 | | if (RespondsToSelectorSel.isNull()) { |
3355 | | IdentifierInfo *SelectorId = &Context.Idents.get("respondsToSelector"); |
3356 | | RespondsToSelectorSel = Context.Selectors.getUnarySelector(SelectorId); |
3357 | | } |
3358 | | if (Sel == RespondsToSelectorSel) |
3359 | | RemoveSelectorFromWarningCache(*this, Args[0]); |
3360 | | |
3361 | | return BuildInstanceMessage(Receiver, Receiver->getType(), |
3362 | | /*SuperLoc=*/SourceLocation(), Sel, |
3363 | | /*Method=*/nullptr, LBracLoc, SelectorLocs, |
3364 | | RBracLoc, Args); |
3365 | | } |
3366 | | |
3367 | | enum ARCConversionTypeClass { |
3368 | | /// int, void, struct A |
3369 | | ACTC_none, |
3370 | | |
3371 | | /// id, void (^)() |
3372 | | ACTC_retainable, |
3373 | | |
3374 | | /// id*, id***, void (^*)(), |
3375 | | ACTC_indirectRetainable, |
3376 | | |
3377 | | /// void* might be a normal C type, or it might a CF type. |
3378 | | ACTC_voidPtr, |
3379 | | |
3380 | | /// struct A* |
3381 | | ACTC_coreFoundation |
3382 | | }; |
3383 | | static bool isAnyRetainable(ARCConversionTypeClass ACTC) { |
3384 | | return (ACTC == ACTC_retainable || |
3385 | | ACTC == ACTC_coreFoundation || |
3386 | | ACTC == ACTC_voidPtr); |
3387 | | } |
3388 | | static bool isAnyCLike(ARCConversionTypeClass ACTC) { |
3389 | | return ACTC == ACTC_none || |
3390 | | ACTC == ACTC_voidPtr || |
3391 | | ACTC == ACTC_coreFoundation; |
3392 | | } |
3393 | | |
3394 | | static ARCConversionTypeClass classifyTypeForARCConversion(QualType type) { |
3395 | | bool isIndirect = false; |
3396 | | |
3397 | | // Ignore an outermost reference type. |
3398 | | if (const ReferenceType *ref = type->getAs<ReferenceType>()) { |
3399 | | type = ref->getPointeeType(); |
3400 | | isIndirect = true; |
3401 | | } |
3402 | | |
3403 | | // Drill through pointers and arrays recursively. |
3404 | | while (true) { |
3405 | | if (const PointerType *ptr = type->getAs<PointerType>()) { |
3406 | | type = ptr->getPointeeType(); |
3407 | | |
3408 | | // The first level of pointer may be the innermost pointer on a CF type. |
3409 | | if (!isIndirect) { |
3410 | | if (type->isVoidType()) return ACTC_voidPtr; |
3411 | | if (type->isRecordType()) return ACTC_coreFoundation; |
3412 | | } |
3413 | | } else if (const ArrayType *array = type->getAsArrayTypeUnsafe()) { |
3414 | | type = QualType(array->getElementType()->getBaseElementTypeUnsafe(), 0); |
3415 | | } else { |
3416 | | break; |
3417 | | } |
3418 | | isIndirect = true; |
3419 | | } |
3420 | | |
3421 | | if (isIndirect) { |
3422 | | if (type->isObjCARCBridgableType()) |
3423 | | return ACTC_indirectRetainable; |
3424 | | return ACTC_none; |
3425 | | } |
3426 | | |
3427 | | if (type->isObjCARCBridgableType()) |
3428 | | return ACTC_retainable; |
3429 | | |
3430 | | return ACTC_none; |
3431 | | } |
3432 | | |
3433 | | namespace { |
3434 | | /// A result from the cast checker. |
3435 | | enum ACCResult { |
3436 | | /// Cannot be casted. |
3437 | | ACC_invalid, |
3438 | | |
3439 | | /// Can be safely retained or not retained. |
3440 | | ACC_bottom, |
3441 | | |
3442 | | /// Can be casted at +0. |
3443 | | ACC_plusZero, |
3444 | | |
3445 | | /// Can be casted at +1. |
3446 | | ACC_plusOne |
3447 | | }; |
3448 | | ACCResult merge(ACCResult left, ACCResult right) { |
3449 | | if (left == right) return left; |
3450 | | if (left == ACC_bottom) return right; |
3451 | | if (right == ACC_bottom) return left; |
3452 | | return ACC_invalid; |
3453 | | } |
3454 | | |
3455 | | /// A checker which white-lists certain expressions whose conversion |
3456 | | /// to or from retainable type would otherwise be forbidden in ARC. |
3457 | | class ARCCastChecker : public StmtVisitor<ARCCastChecker, ACCResult> { |
3458 | | typedef StmtVisitor<ARCCastChecker, ACCResult> super; |
3459 | | |
3460 | | ASTContext &Context; |
3461 | | ARCConversionTypeClass SourceClass; |
3462 | | ARCConversionTypeClass TargetClass; |
3463 | | bool Diagnose; |
3464 | | |
3465 | | static bool isCFType(QualType type) { |
3466 | | // Someday this can use ns_bridged. For now, it has to do this. |
3467 | | return type->isCARCBridgableType(); |
3468 | | } |
3469 | | |
3470 | | public: |
3471 | | ARCCastChecker(ASTContext &Context, ARCConversionTypeClass source, |
3472 | | ARCConversionTypeClass target, bool diagnose) |
3473 | | : Context(Context), SourceClass(source), TargetClass(target), |
3474 | | Diagnose(diagnose) {} |
3475 | | |
3476 | | using super::Visit; |
3477 | | ACCResult Visit(Expr *e) { |
3478 | | return super::Visit(e->IgnoreParens()); |
3479 | | } |
3480 | | |
3481 | | ACCResult VisitStmt(Stmt *s) { |
3482 | | return ACC_invalid; |
3483 | | } |
3484 | | |
3485 | | /// Null pointer constants can be casted however you please. |
3486 | | ACCResult VisitExpr(Expr *e) { |
3487 | | if (e->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull)) |
3488 | | return ACC_bottom; |
3489 | | return ACC_invalid; |
3490 | | } |
3491 | | |
3492 | | /// Objective-C string literals can be safely casted. |
3493 | | ACCResult VisitObjCStringLiteral(ObjCStringLiteral *e) { |
3494 | | // If we're casting to any retainable type, go ahead. Global |
3495 | | // strings are immune to retains, so this is bottom. |
3496 | | if (isAnyRetainable(TargetClass)) return ACC_bottom; |
3497 | | |
3498 | | return ACC_invalid; |
3499 | | } |
3500 | | |
3501 | | /// Look through certain implicit and explicit casts. |
3502 | | ACCResult VisitCastExpr(CastExpr *e) { |
3503 | | switch (e->getCastKind()) { |
3504 | | case CK_NullToPointer: |
3505 | | return ACC_bottom; |
3506 | | |
3507 | | case CK_NoOp: |
3508 | | case CK_LValueToRValue: |
3509 | | case CK_BitCast: |
3510 | | case CK_CPointerToObjCPointerCast: |
3511 | | case CK_BlockPointerToObjCPointerCast: |
3512 | | case CK_AnyPointerToBlockPointerCast: |
3513 | | return Visit(e->getSubExpr()); |
3514 | | |
3515 | | default: |
3516 | | return ACC_invalid; |
3517 | | } |
3518 | | } |
3519 | | |
3520 | | /// Look through unary extension. |
3521 | | ACCResult VisitUnaryExtension(UnaryOperator *e) { |
3522 | | return Visit(e->getSubExpr()); |
3523 | | } |
3524 | | |
3525 | | /// Ignore the LHS of a comma operator. |
3526 | | ACCResult VisitBinComma(BinaryOperator *e) { |
3527 | | return Visit(e->getRHS()); |
3528 | | } |
3529 | | |
3530 | | /// Conditional operators are okay if both sides are okay. |
3531 | | ACCResult VisitConditionalOperator(ConditionalOperator *e) { |
3532 | | ACCResult left = Visit(e->getTrueExpr()); |
3533 | | if (left == ACC_invalid) return ACC_invalid; |
3534 | | return merge(left, Visit(e->getFalseExpr())); |
3535 | | } |
3536 | | |
3537 | | /// Look through pseudo-objects. |
3538 | | ACCResult VisitPseudoObjectExpr(PseudoObjectExpr *e) { |
3539 | | // If we're getting here, we should always have a result. |
3540 | | return Visit(e->getResultExpr()); |
3541 | | } |
3542 | | |
3543 | | /// Statement expressions are okay if their result expression is okay. |
3544 | | ACCResult VisitStmtExpr(StmtExpr *e) { |
3545 | | return Visit(e->getSubStmt()->body_back()); |
3546 | | } |
3547 | | |
3548 | | /// Some declaration references are okay. |
3549 | | ACCResult VisitDeclRefExpr(DeclRefExpr *e) { |
3550 | | VarDecl *var = dyn_cast<VarDecl>(e->getDecl()); |
3551 | | // References to global constants are okay. |
3552 | | if (isAnyRetainable(TargetClass) && |
3553 | | isAnyRetainable(SourceClass) && |
3554 | | var && |
3555 | | var->getStorageClass() == SC_Extern && |
3556 | | var->getType().isConstQualified()) { |
3557 | | |
3558 | | // In system headers, they can also be assumed to be immune to retains. |
3559 | | // These are things like 'kCFStringTransformToLatin'. |
3560 | | if (Context.getSourceManager().isInSystemHeader(var->getLocation())) |
3561 | | return ACC_bottom; |
3562 | | |
3563 | | return ACC_plusZero; |
3564 | | } |
3565 | | |
3566 | | // Nothing else. |
3567 | | return ACC_invalid; |
3568 | | } |
3569 | | |
3570 | | /// Some calls are okay. |
3571 | | ACCResult VisitCallExpr(CallExpr *e) { |
3572 | | if (FunctionDecl *fn = e->getDirectCallee()) |
3573 | | if (ACCResult result = checkCallToFunction(fn)) |
3574 | | return result; |
3575 | | |
3576 | | return super::VisitCallExpr(e); |
3577 | | } |
3578 | | |
3579 | | ACCResult checkCallToFunction(FunctionDecl *fn) { |
3580 | | // Require a CF*Ref return type. |
3581 | | if (!isCFType(fn->getReturnType())) |
3582 | | return ACC_invalid; |
3583 | | |
3584 | | if (!isAnyRetainable(TargetClass)) |
3585 | | return ACC_invalid; |
3586 | | |
3587 | | // Honor an explicit 'not retained' attribute. |
3588 | | if (fn->hasAttr<CFReturnsNotRetainedAttr>()) |
3589 | | return ACC_plusZero; |
3590 | | |
3591 | | // Honor an explicit 'retained' attribute, except that for |
3592 | | // now we're not going to permit implicit handling of +1 results, |
3593 | | // because it's a bit frightening. |
3594 | | if (fn->hasAttr<CFReturnsRetainedAttr>()) |
3595 | | return Diagnose ? ACC_plusOne |
3596 | | : ACC_invalid; // ACC_plusOne if we start accepting this |
3597 | | |
3598 | | // Recognize this specific builtin function, which is used by CFSTR. |
3599 | | unsigned builtinID = fn->getBuiltinID(); |
3600 | | if (builtinID == Builtin::BI__builtin___CFStringMakeConstantString) |
3601 | | return ACC_bottom; |
3602 | | |
3603 | | // Otherwise, don't do anything implicit with an unaudited function. |
3604 | | if (!fn->hasAttr<CFAuditedTransferAttr>()) |
3605 | | return ACC_invalid; |
3606 | | |
3607 | | // Otherwise, it's +0 unless it follows the create convention. |
3608 | | if (ento::coreFoundation::followsCreateRule(fn)) |
3609 | | return Diagnose ? ACC_plusOne |
3610 | | : ACC_invalid; // ACC_plusOne if we start accepting this |
3611 | | |
3612 | | return ACC_plusZero; |
3613 | | } |
3614 | | |
3615 | | ACCResult VisitObjCMessageExpr(ObjCMessageExpr *e) { |
3616 | | return checkCallToMethod(e->getMethodDecl()); |
3617 | | } |
3618 | | |
3619 | | ACCResult VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *e) { |
3620 | | ObjCMethodDecl *method; |
3621 | | if (e->isExplicitProperty()) |
3622 | | method = e->getExplicitProperty()->getGetterMethodDecl(); |
3623 | | else |
3624 | | method = e->getImplicitPropertyGetter(); |
3625 | | return checkCallToMethod(method); |
3626 | | } |
3627 | | |
3628 | | ACCResult checkCallToMethod(ObjCMethodDecl *method) { |
3629 | | if (!method) return ACC_invalid; |
3630 | | |
3631 | | // Check for message sends to functions returning CF types. We |
3632 | | // just obey the Cocoa conventions with these, even though the |
3633 | | // return type is CF. |
3634 | | if (!isAnyRetainable(TargetClass) || !isCFType(method->getReturnType())) |
3635 | | return ACC_invalid; |
3636 | | |
3637 | | // If the method is explicitly marked not-retained, it's +0. |
3638 | | if (method->hasAttr<CFReturnsNotRetainedAttr>()) |
3639 | | return ACC_plusZero; |
3640 | | |
3641 | | // If the method is explicitly marked as returning retained, or its |
3642 | | // selector follows a +1 Cocoa convention, treat it as +1. |
3643 | | if (method->hasAttr<CFReturnsRetainedAttr>()) |
3644 | | return ACC_plusOne; |
3645 | | |
3646 | | switch (method->getSelector().getMethodFamily()) { |
3647 | | case OMF_alloc: |
3648 | | case OMF_copy: |
3649 | | case OMF_mutableCopy: |
3650 | | case OMF_new: |
3651 | | return ACC_plusOne; |
3652 | | |
3653 | | default: |
3654 | | // Otherwise, treat it as +0. |
3655 | | return ACC_plusZero; |
3656 | | } |
3657 | | } |
3658 | | }; |
3659 | | } |
3660 | | |
3661 | | bool Sema::isKnownName(StringRef name) { |
3662 | | if (name.empty()) |
3663 | | return false; |
3664 | | LookupResult R(*this, &Context.Idents.get(name), SourceLocation(), |
3665 | | Sema::LookupOrdinaryName); |
3666 | | return LookupName(R, TUScope, false); |
3667 | | } |
3668 | | |
3669 | | #if 0 // HLSL Change Start - No ObjC support |
3670 | | static void addFixitForObjCARCConversion(Sema &S, |
3671 | | DiagnosticBuilder &DiagB, |
3672 | | Sema::CheckedConversionKind CCK, |
3673 | | SourceLocation afterLParen, |
3674 | | QualType castType, |
3675 | | Expr *castExpr, |
3676 | | Expr *realCast, |
3677 | | const char *bridgeKeyword, |
3678 | | const char *CFBridgeName) { |
3679 | | // We handle C-style and implicit casts here. |
3680 | | switch (CCK) { |
3681 | | case Sema::CCK_ImplicitConversion: |
3682 | | case Sema::CCK_CStyleCast: |
3683 | | case Sema::CCK_OtherCast: |
3684 | | break; |
3685 | | case Sema::CCK_FunctionalCast: |
3686 | | return; |
3687 | | } |
3688 | | |
3689 | | if (CFBridgeName) { |
3690 | | if (CCK == Sema::CCK_OtherCast) { |
3691 | | if (const CXXNamedCastExpr *NCE = dyn_cast<CXXNamedCastExpr>(realCast)) { |
3692 | | SourceRange range(NCE->getOperatorLoc(), |
3693 | | NCE->getAngleBrackets().getEnd()); |
3694 | | SmallString<32> BridgeCall; |
3695 | | |
3696 | | SourceManager &SM = S.getSourceManager(); |
3697 | | char PrevChar = *SM.getCharacterData(range.getBegin().getLocWithOffset(-1)); |
3698 | | if (Lexer::isIdentifierBodyChar(PrevChar, S.getLangOpts())) |
3699 | | BridgeCall += ' '; |
3700 | | |
3701 | | BridgeCall += CFBridgeName; |
3702 | | DiagB.AddFixItHint(FixItHint::CreateReplacement(range, BridgeCall)); |
3703 | | } |
3704 | | return; |
3705 | | } |
3706 | | Expr *castedE = castExpr; |
3707 | | if (CStyleCastExpr *CCE = dyn_cast<CStyleCastExpr>(castedE)) |
3708 | | castedE = CCE->getSubExpr(); |
3709 | | castedE = castedE->IgnoreImpCasts(); |
3710 | | SourceRange range = castedE->getSourceRange(); |
3711 | | |
3712 | | SmallString<32> BridgeCall; |
3713 | | |
3714 | | SourceManager &SM = S.getSourceManager(); |
3715 | | char PrevChar = *SM.getCharacterData(range.getBegin().getLocWithOffset(-1)); |
3716 | | if (Lexer::isIdentifierBodyChar(PrevChar, S.getLangOpts())) |
3717 | | BridgeCall += ' '; |
3718 | | |
3719 | | BridgeCall += CFBridgeName; |
3720 | | |
3721 | | if (isa<ParenExpr>(castedE)) { |
3722 | | DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(), |
3723 | | BridgeCall)); |
3724 | | } else { |
3725 | | BridgeCall += '('; |
3726 | | DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(), |
3727 | | BridgeCall)); |
3728 | | DiagB.AddFixItHint(FixItHint::CreateInsertion( |
3729 | | S.PP.getLocForEndOfToken(range.getEnd()), |
3730 | | ")")); |
3731 | | } |
3732 | | return; |
3733 | | } |
3734 | | |
3735 | | if (CCK == Sema::CCK_CStyleCast) { |
3736 | | DiagB.AddFixItHint(FixItHint::CreateInsertion(afterLParen, bridgeKeyword)); |
3737 | | } else if (CCK == Sema::CCK_OtherCast) { |
3738 | | if (const CXXNamedCastExpr *NCE = dyn_cast<CXXNamedCastExpr>(realCast)) { |
3739 | | std::string castCode = "("; |
3740 | | castCode += bridgeKeyword; |
3741 | | castCode += castType.getAsString(); |
3742 | | castCode += ")"; |
3743 | | SourceRange Range(NCE->getOperatorLoc(), |
3744 | | NCE->getAngleBrackets().getEnd()); |
3745 | | DiagB.AddFixItHint(FixItHint::CreateReplacement(Range, castCode)); |
3746 | | } |
3747 | | } else { |
3748 | | std::string castCode = "("; |
3749 | | castCode += bridgeKeyword; |
3750 | | castCode += castType.getAsString(); |
3751 | | castCode += ")"; |
3752 | | Expr *castedE = castExpr->IgnoreImpCasts(); |
3753 | | SourceRange range = castedE->getSourceRange(); |
3754 | | if (isa<ParenExpr>(castedE)) { |
3755 | | DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(), |
3756 | | castCode)); |
3757 | | } else { |
3758 | | castCode += "("; |
3759 | | DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(), |
3760 | | castCode)); |
3761 | | DiagB.AddFixItHint(FixItHint::CreateInsertion( |
3762 | | S.PP.getLocForEndOfToken(range.getEnd()), |
3763 | | ")")); |
3764 | | } |
3765 | | } |
3766 | | } |
3767 | | #endif // HLSL change End - No ObjC support |
3768 | | |
3769 | | template <typename T> |
3770 | | static inline T *getObjCBridgeAttr(const TypedefType *TD) { |
3771 | | TypedefNameDecl *TDNDecl = TD->getDecl(); |
3772 | | QualType QT = TDNDecl->getUnderlyingType(); |
3773 | | if (QT->isPointerType()) { |
3774 | | QT = QT->getPointeeType(); |
3775 | | if (const RecordType *RT = QT->getAs<RecordType>()) |
3776 | | if (RecordDecl *RD = RT->getDecl()->getMostRecentDecl()) |
3777 | | return RD->getAttr<T>(); |
3778 | | } |
3779 | | return nullptr; |
3780 | | } |
3781 | | |
3782 | | static ObjCBridgeRelatedAttr *ObjCBridgeRelatedAttrFromType(QualType T, |
3783 | | TypedefNameDecl *&TDNDecl) { |
3784 | | while (const TypedefType *TD = dyn_cast<TypedefType>(T.getTypePtr())) { |
3785 | | TDNDecl = TD->getDecl(); |
3786 | | if (ObjCBridgeRelatedAttr *ObjCBAttr = |
3787 | | getObjCBridgeAttr<ObjCBridgeRelatedAttr>(TD)) |
3788 | | return ObjCBAttr; |
3789 | | T = TDNDecl->getUnderlyingType(); |
3790 | | } |
3791 | | return nullptr; |
3792 | | } |
3793 | | |
3794 | | static void |
3795 | | diagnoseObjCARCConversion(Sema &S, SourceRange castRange, |
3796 | | QualType castType, ARCConversionTypeClass castACTC, |
3797 | | Expr *castExpr, Expr *realCast, |
3798 | | ARCConversionTypeClass exprACTC, |
3799 | | Sema::CheckedConversionKind CCK) { |
3800 | | SourceLocation loc = |
3801 | | (castRange.isValid() ? castRange.getBegin() : castExpr->getExprLoc()); |
3802 | | |
3803 | | if (S.makeUnavailableInSystemHeader(loc, |
3804 | | "converts between Objective-C and C pointers in -fobjc-arc")) |
3805 | | return; |
3806 | | |
3807 | | QualType castExprType = castExpr->getType(); |
3808 | | TypedefNameDecl *TDNDecl = nullptr; |
3809 | | if ((castACTC == ACTC_coreFoundation && exprACTC == ACTC_retainable && |
3810 | | ObjCBridgeRelatedAttrFromType(castType, TDNDecl)) || |
3811 | | (exprACTC == ACTC_coreFoundation && castACTC == ACTC_retainable && |
3812 | | ObjCBridgeRelatedAttrFromType(castExprType, TDNDecl))) |
3813 | | return; |
3814 | | |
3815 | | unsigned srcKind = 0; |
3816 | | switch (exprACTC) { |
3817 | | case ACTC_none: |
3818 | | case ACTC_coreFoundation: |
3819 | | case ACTC_voidPtr: |
3820 | | srcKind = (castExprType->isPointerType() ? 1 : 0); |
3821 | | break; |
3822 | | case ACTC_retainable: |
3823 | | srcKind = (castExprType->isBlockPointerType() ? 2 : 3); |
3824 | | break; |
3825 | | case ACTC_indirectRetainable: |
3826 | | srcKind = 4; |
3827 | | break; |
3828 | | } |
3829 | | |
3830 | | // Check whether this could be fixed with a bridge cast. |
3831 | | SourceLocation afterLParen = S.PP.getLocForEndOfToken(castRange.getBegin()); |
3832 | | SourceLocation noteLoc = afterLParen.isValid() ? afterLParen : loc; |
3833 | | |
3834 | | // Bridge from an ARC type to a CF type. |
3835 | | if (castACTC == ACTC_retainable && isAnyRetainable(exprACTC)) { |
3836 | | |
3837 | | S.Diag(loc, diag::err_arc_cast_requires_bridge) |
3838 | | << unsigned(CCK == Sema::CCK_ImplicitConversion) // cast|implicit |
3839 | | << 2 // of C pointer type |
3840 | | << castExprType |
3841 | | << unsigned(castType->isBlockPointerType()) // to ObjC|block type |
3842 | | << castType |
3843 | | << castRange |
3844 | | << castExpr->getSourceRange(); |
3845 | | bool br = S.isKnownName("CFBridgingRelease"); |
3846 | | ACCResult CreateRule = |
3847 | | ARCCastChecker(S.Context, exprACTC, castACTC, true).Visit(castExpr); |
3848 | | assert(CreateRule != ACC_bottom && "This cast should already be accepted."); |
3849 | | if (CreateRule != ACC_plusOne) |
3850 | | { |
3851 | | DiagnosticBuilder DiagB = |
3852 | | (CCK != Sema::CCK_OtherCast) ? S.Diag(noteLoc, diag::note_arc_bridge) |
3853 | | : S.Diag(noteLoc, diag::note_arc_cstyle_bridge); |
3854 | | |
3855 | | addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen, |
3856 | | castType, castExpr, realCast, "__bridge ", |
3857 | | nullptr); |
3858 | | } |
3859 | | if (CreateRule != ACC_plusZero) |
3860 | | { |
3861 | | DiagnosticBuilder DiagB = |
3862 | | (CCK == Sema::CCK_OtherCast && !br) ? |
3863 | | S.Diag(noteLoc, diag::note_arc_cstyle_bridge_transfer) << castExprType : |
3864 | | S.Diag(br ? castExpr->getExprLoc() : noteLoc, |
3865 | | diag::note_arc_bridge_transfer) |
3866 | | << castExprType << br; |
3867 | | |
3868 | | addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen, |
3869 | | castType, castExpr, realCast, "__bridge_transfer ", |
3870 | | br ? "CFBridgingRelease" : nullptr); |
3871 | | } |
3872 | | |
3873 | | return; |
3874 | | } |
3875 | | |
3876 | | // Bridge from a CF type to an ARC type. |
3877 | | if (exprACTC == ACTC_retainable && isAnyRetainable(castACTC)) { |
3878 | | bool br = S.isKnownName("CFBridgingRetain"); |
3879 | | S.Diag(loc, diag::err_arc_cast_requires_bridge) |
3880 | | << unsigned(CCK == Sema::CCK_ImplicitConversion) // cast|implicit |
3881 | | << unsigned(castExprType->isBlockPointerType()) // of ObjC|block type |
3882 | | << castExprType |
3883 | | << 2 // to C pointer type |
3884 | | << castType |
3885 | | << castRange |
3886 | | << castExpr->getSourceRange(); |
3887 | | ACCResult CreateRule = |
3888 | | ARCCastChecker(S.Context, exprACTC, castACTC, true).Visit(castExpr); |
3889 | | assert(CreateRule != ACC_bottom && "This cast should already be accepted."); |
3890 | | if (CreateRule != ACC_plusOne) |
3891 | | { |
3892 | | DiagnosticBuilder DiagB = |
3893 | | (CCK != Sema::CCK_OtherCast) ? S.Diag(noteLoc, diag::note_arc_bridge) |
3894 | | : S.Diag(noteLoc, diag::note_arc_cstyle_bridge); |
3895 | | addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen, |
3896 | | castType, castExpr, realCast, "__bridge ", |
3897 | | nullptr); |
3898 | | } |
3899 | | if (CreateRule != ACC_plusZero) |
3900 | | { |
3901 | | DiagnosticBuilder DiagB = |
3902 | | (CCK == Sema::CCK_OtherCast && !br) ? |
3903 | | S.Diag(noteLoc, diag::note_arc_cstyle_bridge_retained) << castType : |
3904 | | S.Diag(br ? castExpr->getExprLoc() : noteLoc, |
3905 | | diag::note_arc_bridge_retained) |
3906 | | << castType << br; |
3907 | | |
3908 | | addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen, |
3909 | | castType, castExpr, realCast, "__bridge_retained ", |
3910 | | br ? "CFBridgingRetain" : nullptr); |
3911 | | } |
3912 | | |
3913 | | return; |
3914 | | } |
3915 | | |
3916 | | S.Diag(loc, diag::err_arc_mismatched_cast) |
3917 | | << (CCK != Sema::CCK_ImplicitConversion) |
3918 | | << srcKind << castExprType << castType |
3919 | | << castRange << castExpr->getSourceRange(); |
3920 | | } |
3921 | | |
3922 | | template <typename TB> |
3923 | | static bool CheckObjCBridgeNSCast(Sema &S, QualType castType, Expr *castExpr, |
3924 | | bool &HadTheAttribute, bool warn) { |
3925 | | QualType T = castExpr->getType(); |
3926 | | HadTheAttribute = false; |
3927 | | while (const TypedefType *TD = dyn_cast<TypedefType>(T.getTypePtr())) { |
3928 | | TypedefNameDecl *TDNDecl = TD->getDecl(); |
3929 | | if (TB *ObjCBAttr = getObjCBridgeAttr<TB>(TD)) { |
3930 | | if (IdentifierInfo *Parm = ObjCBAttr->getBridgedType()) { |
3931 | | HadTheAttribute = true; |
3932 | | if (Parm->isStr("id")) |
3933 | | return true; |
3934 | | |
3935 | | NamedDecl *Target = nullptr; |
3936 | | // Check for an existing type with this name. |
3937 | | LookupResult R(S, DeclarationName(Parm), SourceLocation(), |
3938 | | Sema::LookupOrdinaryName); |
3939 | | if (S.LookupName(R, S.TUScope)) { |
3940 | | Target = R.getFoundDecl(); |
3941 | | if (Target && isa<ObjCInterfaceDecl>(Target)) { |
3942 | | ObjCInterfaceDecl *ExprClass = cast<ObjCInterfaceDecl>(Target); |
3943 | | if (const ObjCObjectPointerType *InterfacePointerType = |
3944 | | castType->getAsObjCInterfacePointerType()) { |
3945 | | ObjCInterfaceDecl *CastClass |
3946 | | = InterfacePointerType->getObjectType()->getInterface(); |
3947 | | if ((CastClass == ExprClass) || |
3948 | | (CastClass && CastClass->isSuperClassOf(ExprClass))) |
3949 | | return true; |
3950 | | if (warn) |
3951 | | S.Diag(castExpr->getLocStart(), diag::warn_objc_invalid_bridge) |
3952 | | << T << Target->getName() << castType->getPointeeType(); |
3953 | | return false; |
3954 | | } else if (castType->isObjCIdType() || |
3955 | | (S.Context.ObjCObjectAdoptsQTypeProtocols( |
3956 | | castType, ExprClass))) |
3957 | | // ok to cast to 'id'. |
3958 | | // casting to id<p-list> is ok if bridge type adopts all of |
3959 | | // p-list protocols. |
3960 | | return true; |
3961 | | else { |
3962 | | if (warn) { |
3963 | | S.Diag(castExpr->getLocStart(), diag::warn_objc_invalid_bridge) |
3964 | | << T << Target->getName() << castType; |
3965 | | S.Diag(TDNDecl->getLocStart(), diag::note_declared_at); |
3966 | | S.Diag(Target->getLocStart(), diag::note_declared_at); |
3967 | | } |
3968 | | return false; |
3969 | | } |
3970 | | } |
3971 | | } else if (!castType->isObjCIdType()) { |
3972 | | S.Diag(castExpr->getLocStart(), diag::err_objc_cf_bridged_not_interface) |
3973 | | << castExpr->getType() << Parm; |
3974 | | S.Diag(TDNDecl->getLocStart(), diag::note_declared_at); |
3975 | | if (Target) |
3976 | | S.Diag(Target->getLocStart(), diag::note_declared_at); |
3977 | | } |
3978 | | return true; |
3979 | | } |
3980 | | return false; |
3981 | | } |
3982 | | T = TDNDecl->getUnderlyingType(); |
3983 | | } |
3984 | | return true; |
3985 | | } |
3986 | | |
3987 | | template <typename TB> |
3988 | | static bool CheckObjCBridgeCFCast(Sema &S, QualType castType, Expr *castExpr, |
3989 | | bool &HadTheAttribute, bool warn) { |
3990 | | QualType T = castType; |
3991 | | HadTheAttribute = false; |
3992 | | while (const TypedefType *TD = dyn_cast<TypedefType>(T.getTypePtr())) { |
3993 | | TypedefNameDecl *TDNDecl = TD->getDecl(); |
3994 | | if (TB *ObjCBAttr = getObjCBridgeAttr<TB>(TD)) { |
3995 | | if (IdentifierInfo *Parm = ObjCBAttr->getBridgedType()) { |
3996 | | HadTheAttribute = true; |
3997 | | if (Parm->isStr("id")) |
3998 | | return true; |
3999 | | |
4000 | | NamedDecl *Target = nullptr; |
4001 | | // Check for an existing type with this name. |
4002 | | LookupResult R(S, DeclarationName(Parm), SourceLocation(), |
4003 | | Sema::LookupOrdinaryName); |
4004 | | if (S.LookupName(R, S.TUScope)) { |
4005 | | Target = R.getFoundDecl(); |
4006 | | if (Target && isa<ObjCInterfaceDecl>(Target)) { |
4007 | | ObjCInterfaceDecl *CastClass = cast<ObjCInterfaceDecl>(Target); |
4008 | | if (const ObjCObjectPointerType *InterfacePointerType = |
4009 | | castExpr->getType()->getAsObjCInterfacePointerType()) { |
4010 | | ObjCInterfaceDecl *ExprClass |
4011 | | = InterfacePointerType->getObjectType()->getInterface(); |
4012 | | if ((CastClass == ExprClass) || |
4013 | | (ExprClass && CastClass->isSuperClassOf(ExprClass))) |
4014 | | return true; |
4015 | | if (warn) { |
4016 | | S.Diag(castExpr->getLocStart(), diag::warn_objc_invalid_bridge_to_cf) |
4017 | | << castExpr->getType()->getPointeeType() << T; |
4018 | | S.Diag(TDNDecl->getLocStart(), diag::note_declared_at); |
4019 | | } |
4020 | | return false; |
4021 | | } else if (castExpr->getType()->isObjCIdType() || |
4022 | | (S.Context.QIdProtocolsAdoptObjCObjectProtocols( |
4023 | | castExpr->getType(), CastClass))) |
4024 | | // ok to cast an 'id' expression to a CFtype. |
4025 | | // ok to cast an 'id<plist>' expression to CFtype provided plist |
4026 | | // adopts all of CFtype's ObjetiveC's class plist. |
4027 | | return true; |
4028 | | else { |
4029 | | if (warn) { |
4030 | | S.Diag(castExpr->getLocStart(), diag::warn_objc_invalid_bridge_to_cf) |
4031 | | << castExpr->getType() << castType; |
4032 | | S.Diag(TDNDecl->getLocStart(), diag::note_declared_at); |
4033 | | S.Diag(Target->getLocStart(), diag::note_declared_at); |
4034 | | } |
4035 | | return false; |
4036 | | } |
4037 | | } |
4038 | | } |
4039 | | S.Diag(castExpr->getLocStart(), diag::err_objc_ns_bridged_invalid_cfobject) |
4040 | | << castExpr->getType() << castType; |
4041 | | S.Diag(TDNDecl->getLocStart(), diag::note_declared_at); |
4042 | | if (Target) |
4043 | | S.Diag(Target->getLocStart(), diag::note_declared_at); |
4044 | | return true; |
4045 | | } |
4046 | | return false; |
4047 | | } |
4048 | | T = TDNDecl->getUnderlyingType(); |
4049 | | } |
4050 | | return true; |
4051 | | } |
4052 | | |
4053 | | void Sema::CheckTollFreeBridgeCast(QualType castType, Expr *castExpr) { |
4054 | | if (!getLangOpts().ObjC1) |
4055 | | return; |
4056 | | // warn in presence of __bridge casting to or from a toll free bridge cast. |
4057 | | ARCConversionTypeClass exprACTC = classifyTypeForARCConversion(castExpr->getType()); |
4058 | | ARCConversionTypeClass castACTC = classifyTypeForARCConversion(castType); |
4059 | | if (castACTC == ACTC_retainable && exprACTC == ACTC_coreFoundation) { |
4060 | | bool HasObjCBridgeAttr; |
4061 | | bool ObjCBridgeAttrWillNotWarn = |
4062 | | CheckObjCBridgeNSCast<ObjCBridgeAttr>(*this, castType, castExpr, HasObjCBridgeAttr, |
4063 | | false); |
4064 | | if (ObjCBridgeAttrWillNotWarn && HasObjCBridgeAttr) |
4065 | | return; |
4066 | | bool HasObjCBridgeMutableAttr; |
4067 | | bool ObjCBridgeMutableAttrWillNotWarn = |
4068 | | CheckObjCBridgeNSCast<ObjCBridgeMutableAttr>(*this, castType, castExpr, |
4069 | | HasObjCBridgeMutableAttr, false); |
4070 | | if (ObjCBridgeMutableAttrWillNotWarn && HasObjCBridgeMutableAttr) |
4071 | | return; |
4072 | | |
4073 | | if (HasObjCBridgeAttr) |
4074 | | CheckObjCBridgeNSCast<ObjCBridgeAttr>(*this, castType, castExpr, HasObjCBridgeAttr, |
4075 | | true); |
4076 | | else if (HasObjCBridgeMutableAttr) |
4077 | | CheckObjCBridgeNSCast<ObjCBridgeMutableAttr>(*this, castType, castExpr, |
4078 | | HasObjCBridgeMutableAttr, true); |
4079 | | } |
4080 | | else if (castACTC == ACTC_coreFoundation && exprACTC == ACTC_retainable) { |
4081 | | bool HasObjCBridgeAttr; |
4082 | | bool ObjCBridgeAttrWillNotWarn = |
4083 | | CheckObjCBridgeCFCast<ObjCBridgeAttr>(*this, castType, castExpr, HasObjCBridgeAttr, |
4084 | | false); |
4085 | | if (ObjCBridgeAttrWillNotWarn && HasObjCBridgeAttr) |
4086 | | return; |
4087 | | bool HasObjCBridgeMutableAttr; |
4088 | | bool ObjCBridgeMutableAttrWillNotWarn = |
4089 | | CheckObjCBridgeCFCast<ObjCBridgeMutableAttr>(*this, castType, castExpr, |
4090 | | HasObjCBridgeMutableAttr, false); |
4091 | | if (ObjCBridgeMutableAttrWillNotWarn && HasObjCBridgeMutableAttr) |
4092 | | return; |
4093 | | |
4094 | | if (HasObjCBridgeAttr) |
4095 | | CheckObjCBridgeCFCast<ObjCBridgeAttr>(*this, castType, castExpr, HasObjCBridgeAttr, |
4096 | | true); |
4097 | | else if (HasObjCBridgeMutableAttr) |
4098 | | CheckObjCBridgeCFCast<ObjCBridgeMutableAttr>(*this, castType, castExpr, |
4099 | | HasObjCBridgeMutableAttr, true); |
4100 | | } |
4101 | | } |
4102 | | |
4103 | | void Sema::CheckObjCBridgeRelatedCast(QualType castType, Expr *castExpr) { |
4104 | | QualType SrcType = castExpr->getType(); |
4105 | | if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(castExpr)) { |
4106 | | if (PRE->isExplicitProperty()) { |
4107 | | if (ObjCPropertyDecl *PDecl = PRE->getExplicitProperty()) |
4108 | | SrcType = PDecl->getType(); |
4109 | | } |
4110 | | else if (PRE->isImplicitProperty()) { |
4111 | | if (ObjCMethodDecl *Getter = PRE->getImplicitPropertyGetter()) |
4112 | | SrcType = Getter->getReturnType(); |
4113 | | |
4114 | | } |
4115 | | } |
4116 | | |
4117 | | ARCConversionTypeClass srcExprACTC = classifyTypeForARCConversion(SrcType); |
4118 | | ARCConversionTypeClass castExprACTC = classifyTypeForARCConversion(castType); |
4119 | | if (srcExprACTC != ACTC_retainable || castExprACTC != ACTC_coreFoundation) |
4120 | | return; |
4121 | | CheckObjCBridgeRelatedConversions(castExpr->getLocStart(), |
4122 | | castType, SrcType, castExpr); |
4123 | | return; |
4124 | | } |
4125 | | |
4126 | | bool Sema::CheckTollFreeBridgeStaticCast(QualType castType, Expr *castExpr, |
4127 | | CastKind &Kind) { |
4128 | | if (!getLangOpts().ObjC1) |
4129 | | return false; |
4130 | | ARCConversionTypeClass exprACTC = |
4131 | | classifyTypeForARCConversion(castExpr->getType()); |
4132 | | ARCConversionTypeClass castACTC = classifyTypeForARCConversion(castType); |
4133 | | if ((castACTC == ACTC_retainable && exprACTC == ACTC_coreFoundation) || |
4134 | | (castACTC == ACTC_coreFoundation && exprACTC == ACTC_retainable)) { |
4135 | | CheckTollFreeBridgeCast(castType, castExpr); |
4136 | | Kind = (castACTC == ACTC_coreFoundation) ? CK_BitCast |
4137 | | : CK_CPointerToObjCPointerCast; |
4138 | | return true; |
4139 | | } |
4140 | | return false; |
4141 | | } |
4142 | | |
4143 | | bool Sema::checkObjCBridgeRelatedComponents(SourceLocation Loc, |
4144 | | QualType DestType, QualType SrcType, |
4145 | | ObjCInterfaceDecl *&RelatedClass, |
4146 | | ObjCMethodDecl *&ClassMethod, |
4147 | | ObjCMethodDecl *&InstanceMethod, |
4148 | | TypedefNameDecl *&TDNDecl, |
4149 | | bool CfToNs) { |
4150 | | QualType T = CfToNs ? SrcType : DestType; |
4151 | | ObjCBridgeRelatedAttr *ObjCBAttr = ObjCBridgeRelatedAttrFromType(T, TDNDecl); |
4152 | | if (!ObjCBAttr) |
4153 | | return false; |
4154 | | |
4155 | | IdentifierInfo *RCId = ObjCBAttr->getRelatedClass(); |
4156 | | IdentifierInfo *CMId = ObjCBAttr->getClassMethod(); |
4157 | | IdentifierInfo *IMId = ObjCBAttr->getInstanceMethod(); |
4158 | | if (!RCId) |
4159 | | return false; |
4160 | | NamedDecl *Target = nullptr; |
4161 | | // Check for an existing type with this name. |
4162 | | LookupResult R(*this, DeclarationName(RCId), SourceLocation(), |
4163 | | Sema::LookupOrdinaryName); |
4164 | | if (!LookupName(R, TUScope)) { |
4165 | | Diag(Loc, diag::err_objc_bridged_related_invalid_class) << RCId |
4166 | | << SrcType << DestType; |
4167 | | Diag(TDNDecl->getLocStart(), diag::note_declared_at); |
4168 | | return false; |
4169 | | } |
4170 | | Target = R.getFoundDecl(); |
4171 | | if (Target && isa<ObjCInterfaceDecl>(Target)) |
4172 | | RelatedClass = cast<ObjCInterfaceDecl>(Target); |
4173 | | else { |
4174 | | Diag(Loc, diag::err_objc_bridged_related_invalid_class_name) << RCId |
4175 | | << SrcType << DestType; |
4176 | | Diag(TDNDecl->getLocStart(), diag::note_declared_at); |
4177 | | if (Target) |
4178 | | Diag(Target->getLocStart(), diag::note_declared_at); |
4179 | | return false; |
4180 | | } |
4181 | | |
4182 | | // Check for an existing class method with the given selector name. |
4183 | | if (CfToNs && CMId) { |
4184 | | Selector Sel = Context.Selectors.getUnarySelector(CMId); |
4185 | | ClassMethod = RelatedClass->lookupMethod(Sel, false); |
4186 | | if (!ClassMethod) { |
4187 | | Diag(Loc, diag::err_objc_bridged_related_known_method) |
4188 | | << SrcType << DestType << Sel << false; |
4189 | | Diag(TDNDecl->getLocStart(), diag::note_declared_at); |
4190 | | return false; |
4191 | | } |
4192 | | } |
4193 | | |
4194 | | // Check for an existing instance method with the given selector name. |
4195 | | if (!CfToNs && IMId) { |
4196 | | Selector Sel = Context.Selectors.getNullarySelector(IMId); |
4197 | | InstanceMethod = RelatedClass->lookupMethod(Sel, true); |
4198 | | if (!InstanceMethod) { |
4199 | | Diag(Loc, diag::err_objc_bridged_related_known_method) |
4200 | | << SrcType << DestType << Sel << true; |
4201 | | Diag(TDNDecl->getLocStart(), diag::note_declared_at); |
4202 | | return false; |
4203 | | } |
4204 | | } |
4205 | | return true; |
4206 | | } |
4207 | | |
4208 | | bool |
4209 | | Sema::CheckObjCBridgeRelatedConversions(SourceLocation Loc, |
4210 | | QualType DestType, QualType SrcType, |
4211 | | Expr *&SrcExpr) { |
4212 | | ARCConversionTypeClass rhsExprACTC = classifyTypeForARCConversion(SrcType); |
4213 | | ARCConversionTypeClass lhsExprACTC = classifyTypeForARCConversion(DestType); |
4214 | | bool CfToNs = (rhsExprACTC == ACTC_coreFoundation && lhsExprACTC == ACTC_retainable); |
4215 | | bool NsToCf = (rhsExprACTC == ACTC_retainable && lhsExprACTC == ACTC_coreFoundation); |
4216 | | if (!CfToNs && !NsToCf) |
4217 | | return false; |
4218 | | |
4219 | | ObjCInterfaceDecl *RelatedClass; |
4220 | | ObjCMethodDecl *ClassMethod = nullptr; |
4221 | | ObjCMethodDecl *InstanceMethod = nullptr; |
4222 | | TypedefNameDecl *TDNDecl = nullptr; |
4223 | | if (!checkObjCBridgeRelatedComponents(Loc, DestType, SrcType, RelatedClass, |
4224 | | ClassMethod, InstanceMethod, TDNDecl, CfToNs)) |
4225 | | return false; |
4226 | | |
4227 | | if (CfToNs) { |
4228 | | // Implicit conversion from CF to ObjC object is needed. |
4229 | | if (ClassMethod) { |
4230 | | std::string ExpressionString = "["; |
4231 | | ExpressionString += RelatedClass->getNameAsString(); |
4232 | | ExpressionString += " "; |
4233 | | ExpressionString += ClassMethod->getSelector().getAsString(); |
4234 | | SourceLocation SrcExprEndLoc = PP.getLocForEndOfToken(SrcExpr->getLocEnd()); |
4235 | | // Provide a fixit: [RelatedClass ClassMethod SrcExpr] |
4236 | | Diag(Loc, diag::err_objc_bridged_related_known_method) |
4237 | | << SrcType << DestType << ClassMethod->getSelector() << false |
4238 | | << FixItHint::CreateInsertion(SrcExpr->getLocStart(), ExpressionString) |
4239 | | << FixItHint::CreateInsertion(SrcExprEndLoc, "]"); |
4240 | | Diag(RelatedClass->getLocStart(), diag::note_declared_at); |
4241 | | Diag(TDNDecl->getLocStart(), diag::note_declared_at); |
4242 | | |
4243 | | QualType receiverType = |
4244 | | Context.getObjCInterfaceType(RelatedClass); |
4245 | | // Argument. |
4246 | | Expr *args[] = { SrcExpr }; |
4247 | | ExprResult msg = BuildClassMessageImplicit(receiverType, false, |
4248 | | ClassMethod->getLocation(), |
4249 | | ClassMethod->getSelector(), ClassMethod, |
4250 | | MultiExprArg(args, 1)); |
4251 | | SrcExpr = msg.get(); |
4252 | | return true; |
4253 | | } |
4254 | | } |
4255 | | else { |
4256 | | // Implicit conversion from ObjC type to CF object is needed. |
4257 | | if (InstanceMethod) { |
4258 | | std::string ExpressionString; |
4259 | | SourceLocation SrcExprEndLoc = PP.getLocForEndOfToken(SrcExpr->getLocEnd()); |
4260 | | if (InstanceMethod->isPropertyAccessor()) |
4261 | | if (const ObjCPropertyDecl *PDecl = InstanceMethod->findPropertyDecl()) { |
4262 | | // fixit: ObjectExpr.propertyname when it is aproperty accessor. |
4263 | | ExpressionString = "."; |
4264 | | ExpressionString += PDecl->getNameAsString(); |
4265 | | Diag(Loc, diag::err_objc_bridged_related_known_method) |
4266 | | << SrcType << DestType << InstanceMethod->getSelector() << true |
4267 | | << FixItHint::CreateInsertion(SrcExprEndLoc, ExpressionString); |
4268 | | } |
4269 | | if (ExpressionString.empty()) { |
4270 | | // Provide a fixit: [ObjectExpr InstanceMethod] |
4271 | | ExpressionString = " "; |
4272 | | ExpressionString += InstanceMethod->getSelector().getAsString(); |
4273 | | ExpressionString += "]"; |
4274 | | |
4275 | | Diag(Loc, diag::err_objc_bridged_related_known_method) |
4276 | | << SrcType << DestType << InstanceMethod->getSelector() << true |
4277 | | << FixItHint::CreateInsertion(SrcExpr->getLocStart(), "[") |
4278 | | << FixItHint::CreateInsertion(SrcExprEndLoc, ExpressionString); |
4279 | | } |
4280 | | Diag(RelatedClass->getLocStart(), diag::note_declared_at); |
4281 | | Diag(TDNDecl->getLocStart(), diag::note_declared_at); |
4282 | | |
4283 | | ExprResult msg = |
4284 | | BuildInstanceMessageImplicit(SrcExpr, SrcType, |
4285 | | InstanceMethod->getLocation(), |
4286 | | InstanceMethod->getSelector(), |
4287 | | InstanceMethod, None); |
4288 | | SrcExpr = msg.get(); |
4289 | | return true; |
4290 | | } |
4291 | | } |
4292 | | return false; |
4293 | | } |
4294 | | |
4295 | | Sema::ARCConversionResult |
4296 | | Sema::CheckObjCARCConversion(SourceRange castRange, QualType castType, |
4297 | | Expr *&castExpr, CheckedConversionKind CCK, |
4298 | | bool DiagnoseCFAudited, |
4299 | | BinaryOperatorKind Opc) { |
4300 | | QualType castExprType = castExpr->getType(); |
4301 | | |
4302 | | // For the purposes of the classification, we assume reference types |
4303 | | // will bind to temporaries. |
4304 | | QualType effCastType = castType; |
4305 | | if (const ReferenceType *ref = castType->getAs<ReferenceType>()) |
4306 | | effCastType = ref->getPointeeType(); |
4307 | | |
4308 | | ARCConversionTypeClass exprACTC = classifyTypeForARCConversion(castExprType); |
4309 | | ARCConversionTypeClass castACTC = classifyTypeForARCConversion(effCastType); |
4310 | | if (exprACTC == castACTC) { |
4311 | | // check for viablity and report error if casting an rvalue to a |
4312 | | // life-time qualifier. |
4313 | | if ((castACTC == ACTC_retainable) && |
4314 | | (CCK == CCK_CStyleCast || CCK == CCK_OtherCast) && |
4315 | | (castType != castExprType)) { |
4316 | | const Type *DT = castType.getTypePtr(); |
4317 | | QualType QDT = castType; |
4318 | | // We desugar some types but not others. We ignore those |
4319 | | // that cannot happen in a cast; i.e. auto, and those which |
4320 | | // should not be de-sugared; i.e typedef. |
4321 | | if (const ParenType *PT = dyn_cast<ParenType>(DT)) |
4322 | | QDT = PT->desugar(); |
4323 | | else if (const TypeOfType *TP = dyn_cast<TypeOfType>(DT)) |
4324 | | QDT = TP->desugar(); |
4325 | | else if (const AttributedType *AT = dyn_cast<AttributedType>(DT)) |
4326 | | QDT = AT->desugar(); |
4327 | | if (QDT != castType && |
4328 | | QDT.getObjCLifetime() != Qualifiers::OCL_None) { |
4329 | | SourceLocation loc = |
4330 | | (castRange.isValid() ? castRange.getBegin() |
4331 | | : castExpr->getExprLoc()); |
4332 | | Diag(loc, diag::err_arc_nolifetime_behavior); |
4333 | | } |
4334 | | } |
4335 | | return ACR_okay; |
4336 | | } |
4337 | | |
4338 | | if (isAnyCLike(exprACTC) && isAnyCLike(castACTC)) return ACR_okay; |
4339 | | |
4340 | | // Allow all of these types to be cast to integer types (but not |
4341 | | // vice-versa). |
4342 | | if (castACTC == ACTC_none && castType->isIntegralType(Context)) |
4343 | | return ACR_okay; |
4344 | | |
4345 | | // Allow casts between pointers to lifetime types (e.g., __strong id*) |
4346 | | // and pointers to void (e.g., cv void *). Casting from void* to lifetime* |
4347 | | // must be explicit. |
4348 | | if (exprACTC == ACTC_indirectRetainable && castACTC == ACTC_voidPtr) |
4349 | | return ACR_okay; |
4350 | | if (castACTC == ACTC_indirectRetainable && exprACTC == ACTC_voidPtr && |
4351 | | CCK != CCK_ImplicitConversion) |
4352 | | return ACR_okay; |
4353 | | |
4354 | | switch (ARCCastChecker(Context, exprACTC, castACTC, false).Visit(castExpr)) { |
4355 | | // For invalid casts, fall through. |
4356 | | case ACC_invalid: |
4357 | | break; |
4358 | | |
4359 | | // Do nothing for both bottom and +0. |
4360 | | case ACC_bottom: |
4361 | | case ACC_plusZero: |
4362 | | return ACR_okay; |
4363 | | |
4364 | | // If the result is +1, consume it here. |
4365 | | case ACC_plusOne: |
4366 | | castExpr = ImplicitCastExpr::Create(Context, castExpr->getType(), |
4367 | | CK_ARCConsumeObject, castExpr, |
4368 | | nullptr, VK_RValue); |
4369 | | ExprNeedsCleanups = true; |
4370 | | return ACR_okay; |
4371 | | } |
4372 | | |
4373 | | // If this is a non-implicit cast from id or block type to a |
4374 | | // CoreFoundation type, delay complaining in case the cast is used |
4375 | | // in an acceptable context. |
4376 | | if (exprACTC == ACTC_retainable && isAnyRetainable(castACTC) && |
4377 | | CCK != CCK_ImplicitConversion) |
4378 | | return ACR_unbridged; |
4379 | | |
4380 | | // Do not issue bridge cast" diagnostic when implicit casting a cstring |
4381 | | // to 'NSString *'. Let caller issue a normal mismatched diagnostic with |
4382 | | // suitable fix-it. |
4383 | | if (castACTC == ACTC_retainable && exprACTC == ACTC_none && |
4384 | | ConversionToObjCStringLiteralCheck(castType, castExpr)) |
4385 | | return ACR_okay; |
4386 | | |
4387 | | // Do not issue "bridge cast" diagnostic when implicit casting |
4388 | | // a retainable object to a CF type parameter belonging to an audited |
4389 | | // CF API function. Let caller issue a normal type mismatched diagnostic |
4390 | | // instead. |
4391 | | if (!DiagnoseCFAudited || exprACTC != ACTC_retainable || |
4392 | | castACTC != ACTC_coreFoundation) |
4393 | | if (!(exprACTC == ACTC_voidPtr && castACTC == ACTC_retainable && |
4394 | | (Opc == BO_NE || Opc == BO_EQ))) |
4395 | | diagnoseObjCARCConversion(*this, castRange, castType, castACTC, |
4396 | | castExpr, castExpr, exprACTC, CCK); |
4397 | | return ACR_okay; |
4398 | | } |
4399 | | |
4400 | | /// Given that we saw an expression with the ARCUnbridgedCastTy |
4401 | | /// placeholder type, complain bitterly. |
4402 | | void Sema::diagnoseARCUnbridgedCast(Expr *e) { |
4403 | | // We expect the spurious ImplicitCastExpr to already have been stripped. |
4404 | | assert(!e->hasPlaceholderType(BuiltinType::ARCUnbridgedCast)); |
4405 | | CastExpr *realCast = cast<CastExpr>(e->IgnoreParens()); |
4406 | | |
4407 | | SourceRange castRange; |
4408 | | QualType castType; |
4409 | | CheckedConversionKind CCK; |
4410 | | |
4411 | | if (CStyleCastExpr *cast = dyn_cast<CStyleCastExpr>(realCast)) { |
4412 | | castRange = SourceRange(cast->getLParenLoc(), cast->getRParenLoc()); |
4413 | | castType = cast->getTypeAsWritten(); |
4414 | | CCK = CCK_CStyleCast; |
4415 | | } else if (ExplicitCastExpr *cast = dyn_cast<ExplicitCastExpr>(realCast)) { |
4416 | | castRange = cast->getTypeInfoAsWritten()->getTypeLoc().getSourceRange(); |
4417 | | castType = cast->getTypeAsWritten(); |
4418 | | CCK = CCK_OtherCast; |
4419 | | } else { |
4420 | | castType = cast->getType(); |
4421 | | CCK = CCK_ImplicitConversion; |
4422 | | } |
4423 | | |
4424 | | ARCConversionTypeClass castACTC = |
4425 | | classifyTypeForARCConversion(castType.getNonReferenceType()); |
4426 | | |
4427 | | Expr *castExpr = realCast->getSubExpr(); |
4428 | | assert(classifyTypeForARCConversion(castExpr->getType()) == ACTC_retainable); |
4429 | | |
4430 | | diagnoseObjCARCConversion(*this, castRange, castType, castACTC, |
4431 | | castExpr, realCast, ACTC_retainable, CCK); |
4432 | | } |
4433 | | |
4434 | | /// stripARCUnbridgedCast - Given an expression of ARCUnbridgedCast |
4435 | | /// type, remove the placeholder cast. |
4436 | | Expr *Sema::stripARCUnbridgedCast(Expr *e) { |
4437 | | assert(e->hasPlaceholderType(BuiltinType::ARCUnbridgedCast)); |
4438 | | |
4439 | | if (ParenExpr *pe = dyn_cast<ParenExpr>(e)) { |
4440 | | Expr *sub = stripARCUnbridgedCast(pe->getSubExpr()); |
4441 | | return new (Context) ParenExpr(pe->getLParen(), pe->getRParen(), sub); |
4442 | | } else if (UnaryOperator *uo = dyn_cast<UnaryOperator>(e)) { |
4443 | | assert(uo->getOpcode() == UO_Extension); |
4444 | | Expr *sub = stripARCUnbridgedCast(uo->getSubExpr()); |
4445 | | return new (Context) UnaryOperator(sub, UO_Extension, sub->getType(), |
4446 | | sub->getValueKind(), sub->getObjectKind(), |
4447 | | uo->getOperatorLoc()); |
4448 | | } else if (GenericSelectionExpr *gse = dyn_cast<GenericSelectionExpr>(e)) { |
4449 | | assert(!gse->isResultDependent()); |
4450 | | |
4451 | | unsigned n = gse->getNumAssocs(); |
4452 | | SmallVector<Expr*, 4> subExprs(n); |
4453 | | SmallVector<TypeSourceInfo*, 4> subTypes(n); |
4454 | | for (unsigned i = 0; i != n; ++i) { |
4455 | | subTypes[i] = gse->getAssocTypeSourceInfo(i); |
4456 | | Expr *sub = gse->getAssocExpr(i); |
4457 | | if (i == gse->getResultIndex()) |
4458 | | sub = stripARCUnbridgedCast(sub); |
4459 | | subExprs[i] = sub; |
4460 | | } |
4461 | | |
4462 | | return new (Context) GenericSelectionExpr(Context, gse->getGenericLoc(), |
4463 | | gse->getControllingExpr(), |
4464 | | subTypes, subExprs, |
4465 | | gse->getDefaultLoc(), |
4466 | | gse->getRParenLoc(), |
4467 | | gse->containsUnexpandedParameterPack(), |
4468 | | gse->getResultIndex()); |
4469 | | } else { |
4470 | | assert(isa<ImplicitCastExpr>(e) && "bad form of unbridged cast!"); |
4471 | | return cast<ImplicitCastExpr>(e)->getSubExpr(); |
4472 | | } |
4473 | | } |
4474 | | |
4475 | | bool Sema::CheckObjCARCUnavailableWeakConversion(QualType castType, |
4476 | | QualType exprType) { |
4477 | | QualType canCastType = |
4478 | | Context.getCanonicalType(castType).getUnqualifiedType(); |
4479 | | QualType canExprType = |
4480 | | Context.getCanonicalType(exprType).getUnqualifiedType(); |
4481 | | if (isa<ObjCObjectPointerType>(canCastType) && |
4482 | | castType.getObjCLifetime() == Qualifiers::OCL_Weak && |
4483 | | canExprType->isObjCObjectPointerType()) { |
4484 | | if (const ObjCObjectPointerType *ObjT = |
4485 | | canExprType->getAs<ObjCObjectPointerType>()) |
4486 | | if (const ObjCInterfaceDecl *ObjI = ObjT->getInterfaceDecl()) |
4487 | | return !ObjI->isArcWeakrefUnavailable(); |
4488 | | } |
4489 | | return true; |
4490 | | } |
4491 | | |
4492 | | /// Look for an ObjCReclaimReturnedObject cast and destroy it. |
4493 | | static Expr *maybeUndoReclaimObject(Expr *e) { |
4494 | | // For now, we just undo operands that are *immediately* reclaim |
4495 | | // expressions, which prevents the vast majority of potential |
4496 | | // problems here. To catch them all, we'd need to rebuild arbitrary |
4497 | | // value-propagating subexpressions --- we can't reliably rebuild |
4498 | | // in-place because of expression sharing. |
4499 | | if (ImplicitCastExpr *ice = dyn_cast<ImplicitCastExpr>(e)) |
4500 | | if (ice->getCastKind() == CK_ARCReclaimReturnedObject) |
4501 | | return ice->getSubExpr(); |
4502 | | |
4503 | | return e; |
4504 | | } |
4505 | | |
4506 | | ExprResult Sema::BuildObjCBridgedCast(SourceLocation LParenLoc, |
4507 | | ObjCBridgeCastKind Kind, |
4508 | | SourceLocation BridgeKeywordLoc, |
4509 | | TypeSourceInfo *TSInfo, |
4510 | | Expr *SubExpr) { |
4511 | | ExprResult SubResult = UsualUnaryConversions(SubExpr); |
4512 | | if (SubResult.isInvalid()) return ExprError(); |
4513 | | SubExpr = SubResult.get(); |
4514 | | |
4515 | | QualType T = TSInfo->getType(); |
4516 | | QualType FromType = SubExpr->getType(); |
4517 | | |
4518 | | CastKind CK; |
4519 | | |
4520 | | bool MustConsume = false; |
4521 | | if (T->isDependentType() || SubExpr->isTypeDependent()) { |
4522 | | // Okay: we'll build a dependent expression type. |
4523 | | CK = CK_Dependent; |
4524 | | } else if (T->isObjCARCBridgableType() && FromType->isCARCBridgableType()) { |
4525 | | // Casting CF -> id |
4526 | | CK = (T->isBlockPointerType() ? CK_AnyPointerToBlockPointerCast |
4527 | | : CK_CPointerToObjCPointerCast); |
4528 | | switch (Kind) { |
4529 | | case OBC_Bridge: |
4530 | | break; |
4531 | | |
4532 | | case OBC_BridgeRetained: { |
4533 | | bool br = isKnownName("CFBridgingRelease"); |
4534 | | Diag(BridgeKeywordLoc, diag::err_arc_bridge_cast_wrong_kind) |
4535 | | << 2 |
4536 | | << FromType |
4537 | | << (T->isBlockPointerType()? 1 : 0) |
4538 | | << T |
4539 | | << SubExpr->getSourceRange() |
4540 | | << Kind; |
4541 | | Diag(BridgeKeywordLoc, diag::note_arc_bridge) |
4542 | | << FixItHint::CreateReplacement(BridgeKeywordLoc, "__bridge"); |
4543 | | Diag(BridgeKeywordLoc, diag::note_arc_bridge_transfer) |
4544 | | << FromType << br |
4545 | | << FixItHint::CreateReplacement(BridgeKeywordLoc, |
4546 | | br ? "CFBridgingRelease " |
4547 | | : "__bridge_transfer "); |
4548 | | |
4549 | | Kind = OBC_Bridge; |
4550 | | break; |
4551 | | } |
4552 | | |
4553 | | case OBC_BridgeTransfer: |
4554 | | // We must consume the Objective-C object produced by the cast. |
4555 | | MustConsume = true; |
4556 | | break; |
4557 | | } |
4558 | | } else if (T->isCARCBridgableType() && FromType->isObjCARCBridgableType()) { |
4559 | | // Okay: id -> CF |
4560 | | CK = CK_BitCast; |
4561 | | switch (Kind) { |
4562 | | case OBC_Bridge: |
4563 | | // Reclaiming a value that's going to be __bridge-casted to CF |
4564 | | // is very dangerous, so we don't do it. |
4565 | | SubExpr = maybeUndoReclaimObject(SubExpr); |
4566 | | break; |
4567 | | |
4568 | | case OBC_BridgeRetained: |
4569 | | // Produce the object before casting it. |
4570 | | SubExpr = ImplicitCastExpr::Create(Context, FromType, |
4571 | | CK_ARCProduceObject, |
4572 | | SubExpr, nullptr, VK_RValue); |
4573 | | break; |
4574 | | |
4575 | | case OBC_BridgeTransfer: { |
4576 | | bool br = isKnownName("CFBridgingRetain"); |
4577 | | Diag(BridgeKeywordLoc, diag::err_arc_bridge_cast_wrong_kind) |
4578 | | << (FromType->isBlockPointerType()? 1 : 0) |
4579 | | << FromType |
4580 | | << 2 |
4581 | | << T |
4582 | | << SubExpr->getSourceRange() |
4583 | | << Kind; |
4584 | | |
4585 | | Diag(BridgeKeywordLoc, diag::note_arc_bridge) |
4586 | | << FixItHint::CreateReplacement(BridgeKeywordLoc, "__bridge "); |
4587 | | Diag(BridgeKeywordLoc, diag::note_arc_bridge_retained) |
4588 | | << T << br |
4589 | | << FixItHint::CreateReplacement(BridgeKeywordLoc, |
4590 | | br ? "CFBridgingRetain " : "__bridge_retained"); |
4591 | | |
4592 | | Kind = OBC_Bridge; |
4593 | | break; |
4594 | | } |
4595 | | } |
4596 | | } else { |
4597 | | Diag(LParenLoc, diag::err_arc_bridge_cast_incompatible) |
4598 | | << FromType << T << Kind |
4599 | | << SubExpr->getSourceRange() |
4600 | | << TSInfo->getTypeLoc().getSourceRange(); |
4601 | | return ExprError(); |
4602 | | } |
4603 | | |
4604 | | Expr *Result = new (Context) ObjCBridgedCastExpr(LParenLoc, Kind, CK, |
4605 | | BridgeKeywordLoc, |
4606 | | TSInfo, SubExpr); |
4607 | | |
4608 | | if (MustConsume) { |
4609 | | ExprNeedsCleanups = true; |
4610 | | Result = ImplicitCastExpr::Create(Context, T, CK_ARCConsumeObject, Result, |
4611 | | nullptr, VK_RValue); |
4612 | | } |
4613 | | |
4614 | | return Result; |
4615 | | } |
4616 | | |
4617 | | ExprResult Sema::ActOnObjCBridgedCast(Scope *S, |
4618 | | SourceLocation LParenLoc, |
4619 | | ObjCBridgeCastKind Kind, |
4620 | | SourceLocation BridgeKeywordLoc, |
4621 | | ParsedType Type, |
4622 | | SourceLocation RParenLoc, |
4623 | | Expr *SubExpr) { |
4624 | | TypeSourceInfo *TSInfo = nullptr; |
4625 | | QualType T = GetTypeFromParser(Type, &TSInfo); |
4626 | | if (Kind == OBC_Bridge) |
4627 | | CheckTollFreeBridgeCast(T, SubExpr); |
4628 | | if (!TSInfo) |
4629 | | TSInfo = Context.getTrivialTypeSourceInfo(T, LParenLoc); |
4630 | | return BuildObjCBridgedCast(LParenLoc, Kind, BridgeKeywordLoc, TSInfo, |
4631 | | SubExpr); |
4632 | | } |
4633 | | |
4634 | | #endif // HLSL Change |