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