forked from llvm-mirror/clang
-
Notifications
You must be signed in to change notification settings - Fork 19
/
SemaExprObjC.cpp
4489 lines (4007 loc) · 175 KB
/
SemaExprObjC.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//===--- SemaExprObjC.cpp - Semantic Analysis for ObjC Expressions --------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements semantic analysis for Objective-C expressions.
//
//===----------------------------------------------------------------------===//
#include "clang/Sema/SemaInternal.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/DeclObjC.h"
#include "clang/AST/ExprObjC.h"
#include "clang/AST/StmtVisitor.h"
#include "clang/AST/TypeLoc.h"
#include "clang/Analysis/DomainSpecific/CocoaConventions.h"
#include "clang/Edit/Commit.h"
#include "clang/Edit/Rewriters.h"
#include "clang/Lex/Preprocessor.h"
#include "clang/Sema/Initialization.h"
#include "clang/Sema/Lookup.h"
#include "clang/Sema/Scope.h"
#include "clang/Sema/ScopeInfo.h"
#include "llvm/ADT/SmallString.h"
using namespace clang;
using namespace sema;
using llvm::makeArrayRef;
ExprResult Sema::ParseObjCStringLiteral(SourceLocation *AtLocs,
ArrayRef<Expr *> Strings) {
// Most ObjC strings are formed out of a single piece. However, we *can*
// have strings formed out of multiple @ strings with multiple pptokens in
// each one, e.g. @"foo" "bar" @"baz" "qux" which need to be turned into one
// StringLiteral for ObjCStringLiteral to hold onto.
StringLiteral *S = cast<StringLiteral>(Strings[0]);
// If we have a multi-part string, merge it all together.
if (Strings.size() != 1) {
// Concatenate objc strings.
SmallString<128> StrBuf;
SmallVector<SourceLocation, 8> StrLocs;
for (Expr *E : Strings) {
S = cast<StringLiteral>(E);
// ObjC strings can't be wide or UTF.
if (!S->isAscii()) {
Diag(S->getLocStart(), diag::err_cfstring_literal_not_string_constant)
<< S->getSourceRange();
return true;
}
// Append the string.
StrBuf += S->getString();
// Get the locations of the string tokens.
StrLocs.append(S->tokloc_begin(), S->tokloc_end());
}
// Create the aggregate string with the appropriate content and location
// information.
const ConstantArrayType *CAT = Context.getAsConstantArrayType(S->getType());
assert(CAT && "String literal not of constant array type!");
QualType StrTy = Context.getConstantArrayType(
CAT->getElementType(), llvm::APInt(32, StrBuf.size() + 1),
CAT->getSizeModifier(), CAT->getIndexTypeCVRQualifiers());
S = StringLiteral::Create(Context, StrBuf, StringLiteral::Ascii,
/*Pascal=*/false, StrTy, &StrLocs[0],
StrLocs.size());
}
return BuildObjCStringLiteral(AtLocs[0], S);
}
ExprResult Sema::BuildObjCStringLiteral(SourceLocation AtLoc, StringLiteral *S){
// Verify that this composite string is acceptable for ObjC strings.
if (CheckObjCString(S))
return true;
// Initialize the constant string interface lazily. This assumes
// the NSString interface is seen in this translation unit. Note: We
// don't use NSConstantString, since the runtime team considers this
// interface private (even though it appears in the header files).
QualType Ty = Context.getObjCConstantStringInterface();
if (!Ty.isNull()) {
Ty = Context.getObjCObjectPointerType(Ty);
} else if (getLangOpts().NoConstantCFStrings) {
IdentifierInfo *NSIdent=nullptr;
std::string StringClass(getLangOpts().ObjCConstantStringClass);
if (StringClass.empty())
NSIdent = &Context.Idents.get("NSConstantString");
else
NSIdent = &Context.Idents.get(StringClass);
NamedDecl *IF = LookupSingleName(TUScope, NSIdent, AtLoc,
LookupOrdinaryName);
if (ObjCInterfaceDecl *StrIF = dyn_cast_or_null<ObjCInterfaceDecl>(IF)) {
Context.setObjCConstantStringInterface(StrIF);
Ty = Context.getObjCConstantStringInterface();
Ty = Context.getObjCObjectPointerType(Ty);
} else {
// If there is no NSConstantString interface defined then treat this
// as error and recover from it.
Diag(S->getLocStart(), diag::err_no_nsconstant_string_class) << NSIdent
<< S->getSourceRange();
Ty = Context.getObjCIdType();
}
} else {
IdentifierInfo *NSIdent = NSAPIObj->getNSClassId(NSAPI::ClassId_NSString);
NamedDecl *IF = LookupSingleName(TUScope, NSIdent, AtLoc,
LookupOrdinaryName);
if (ObjCInterfaceDecl *StrIF = dyn_cast_or_null<ObjCInterfaceDecl>(IF)) {
Context.setObjCConstantStringInterface(StrIF);
Ty = Context.getObjCConstantStringInterface();
Ty = Context.getObjCObjectPointerType(Ty);
} else {
// If there is no NSString interface defined, implicitly declare
// a @class NSString; and use that instead. This is to make sure
// type of an NSString literal is represented correctly, instead of
// being an 'id' type.
Ty = Context.getObjCNSStringType();
if (Ty.isNull()) {
ObjCInterfaceDecl *NSStringIDecl =
ObjCInterfaceDecl::Create (Context,
Context.getTranslationUnitDecl(),
SourceLocation(), NSIdent,
nullptr, nullptr, SourceLocation());
Ty = Context.getObjCInterfaceType(NSStringIDecl);
Context.setObjCNSStringType(Ty);
}
Ty = Context.getObjCObjectPointerType(Ty);
}
}
return new (Context) ObjCStringLiteral(S, Ty, AtLoc);
}
/// \brief Emits an error if the given method does not exist, or if the return
/// type is not an Objective-C object.
static bool validateBoxingMethod(Sema &S, SourceLocation Loc,
const ObjCInterfaceDecl *Class,
Selector Sel, const ObjCMethodDecl *Method) {
if (!Method) {
// FIXME: Is there a better way to avoid quotes than using getName()?
S.Diag(Loc, diag::err_undeclared_boxing_method) << Sel << Class->getName();
return false;
}
// Make sure the return type is reasonable.
QualType ReturnType = Method->getReturnType();
if (!ReturnType->isObjCObjectPointerType()) {
S.Diag(Loc, diag::err_objc_literal_method_sig)
<< Sel;
S.Diag(Method->getLocation(), diag::note_objc_literal_method_return)
<< ReturnType;
return false;
}
return true;
}
/// \brief Maps ObjCLiteralKind to NSClassIdKindKind
static NSAPI::NSClassIdKindKind ClassKindFromLiteralKind(
Sema::ObjCLiteralKind LiteralKind) {
switch (LiteralKind) {
case Sema::LK_Array:
return NSAPI::ClassId_NSArray;
case Sema::LK_Dictionary:
return NSAPI::ClassId_NSDictionary;
case Sema::LK_Numeric:
return NSAPI::ClassId_NSNumber;
case Sema::LK_String:
return NSAPI::ClassId_NSString;
case Sema::LK_Boxed:
return NSAPI::ClassId_NSValue;
// there is no corresponding matching
// between LK_None/LK_Block and NSClassIdKindKind
case Sema::LK_Block:
case Sema::LK_None:
break;
}
llvm_unreachable("LiteralKind can't be converted into a ClassKind");
}
/// \brief Validates ObjCInterfaceDecl availability.
/// ObjCInterfaceDecl, used to create ObjC literals, should be defined
/// if clang not in a debugger mode.
static bool ValidateObjCLiteralInterfaceDecl(Sema &S, ObjCInterfaceDecl *Decl,
SourceLocation Loc,
Sema::ObjCLiteralKind LiteralKind) {
if (!Decl) {
NSAPI::NSClassIdKindKind Kind = ClassKindFromLiteralKind(LiteralKind);
IdentifierInfo *II = S.NSAPIObj->getNSClassId(Kind);
S.Diag(Loc, diag::err_undeclared_objc_literal_class)
<< II->getName() << LiteralKind;
return false;
} else if (!Decl->hasDefinition() && !S.getLangOpts().DebuggerObjCLiteral) {
S.Diag(Loc, diag::err_undeclared_objc_literal_class)
<< Decl->getName() << LiteralKind;
S.Diag(Decl->getLocation(), diag::note_forward_class);
return false;
}
return true;
}
/// \brief Looks up ObjCInterfaceDecl of a given NSClassIdKindKind.
/// Used to create ObjC literals, such as NSDictionary (@{}),
/// NSArray (@[]) and Boxed Expressions (@())
static ObjCInterfaceDecl *LookupObjCInterfaceDeclForLiteral(Sema &S,
SourceLocation Loc,
Sema::ObjCLiteralKind LiteralKind) {
NSAPI::NSClassIdKindKind ClassKind = ClassKindFromLiteralKind(LiteralKind);
IdentifierInfo *II = S.NSAPIObj->getNSClassId(ClassKind);
NamedDecl *IF = S.LookupSingleName(S.TUScope, II, Loc,
Sema::LookupOrdinaryName);
ObjCInterfaceDecl *ID = dyn_cast_or_null<ObjCInterfaceDecl>(IF);
if (!ID && S.getLangOpts().DebuggerObjCLiteral) {
ASTContext &Context = S.Context;
TranslationUnitDecl *TU = Context.getTranslationUnitDecl();
ID = ObjCInterfaceDecl::Create (Context, TU, SourceLocation(), II,
nullptr, nullptr, SourceLocation());
}
if (!ValidateObjCLiteralInterfaceDecl(S, ID, Loc, LiteralKind)) {
ID = nullptr;
}
return ID;
}
/// \brief Retrieve the NSNumber factory method that should be used to create
/// an Objective-C literal for the given type.
static ObjCMethodDecl *getNSNumberFactoryMethod(Sema &S, SourceLocation Loc,
QualType NumberType,
bool isLiteral = false,
SourceRange R = SourceRange()) {
Optional<NSAPI::NSNumberLiteralMethodKind> Kind =
S.NSAPIObj->getNSNumberFactoryMethodKind(NumberType);
if (!Kind) {
if (isLiteral) {
S.Diag(Loc, diag::err_invalid_nsnumber_type)
<< NumberType << R;
}
return nullptr;
}
// If we already looked up this method, we're done.
if (S.NSNumberLiteralMethods[*Kind])
return S.NSNumberLiteralMethods[*Kind];
Selector Sel = S.NSAPIObj->getNSNumberLiteralSelector(*Kind,
/*Instance=*/false);
ASTContext &CX = S.Context;
// Look up the NSNumber class, if we haven't done so already. It's cached
// in the Sema instance.
if (!S.NSNumberDecl) {
S.NSNumberDecl = LookupObjCInterfaceDeclForLiteral(S, Loc,
Sema::LK_Numeric);
if (!S.NSNumberDecl) {
return nullptr;
}
}
if (S.NSNumberPointer.isNull()) {
// generate the pointer to NSNumber type.
QualType NSNumberObject = CX.getObjCInterfaceType(S.NSNumberDecl);
S.NSNumberPointer = CX.getObjCObjectPointerType(NSNumberObject);
}
// Look for the appropriate method within NSNumber.
ObjCMethodDecl *Method = S.NSNumberDecl->lookupClassMethod(Sel);
if (!Method && S.getLangOpts().DebuggerObjCLiteral) {
// create a stub definition this NSNumber factory method.
TypeSourceInfo *ReturnTInfo = nullptr;
Method =
ObjCMethodDecl::Create(CX, SourceLocation(), SourceLocation(), Sel,
S.NSNumberPointer, ReturnTInfo, S.NSNumberDecl,
/*isInstance=*/false, /*isVariadic=*/false,
/*isPropertyAccessor=*/false,
/*isImplicitlyDeclared=*/true,
/*isDefined=*/false, ObjCMethodDecl::Required,
/*HasRelatedResultType=*/false);
ParmVarDecl *value = ParmVarDecl::Create(S.Context, Method,
SourceLocation(), SourceLocation(),
&CX.Idents.get("value"),
NumberType, /*TInfo=*/nullptr,
SC_None, nullptr);
Method->setMethodParams(S.Context, value, None);
}
if (!validateBoxingMethod(S, Loc, S.NSNumberDecl, Sel, Method))
return nullptr;
// Note: if the parameter type is out-of-line, we'll catch it later in the
// implicit conversion.
S.NSNumberLiteralMethods[*Kind] = Method;
return Method;
}
/// BuildObjCNumericLiteral - builds an ObjCBoxedExpr AST node for the
/// numeric literal expression. Type of the expression will be "NSNumber *".
ExprResult Sema::BuildObjCNumericLiteral(SourceLocation AtLoc, Expr *Number) {
// Determine the type of the literal.
QualType NumberType = Number->getType();
if (CharacterLiteral *Char = dyn_cast<CharacterLiteral>(Number)) {
// In C, character literals have type 'int'. That's not the type we want
// to use to determine the Objective-c literal kind.
switch (Char->getKind()) {
case CharacterLiteral::Ascii:
case CharacterLiteral::UTF8:
NumberType = Context.CharTy;
break;
case CharacterLiteral::Wide:
NumberType = Context.getWideCharType();
break;
case CharacterLiteral::UTF16:
NumberType = Context.Char16Ty;
break;
case CharacterLiteral::UTF32:
NumberType = Context.Char32Ty;
break;
}
}
// Look for the appropriate method within NSNumber.
// Construct the literal.
SourceRange NR(Number->getSourceRange());
ObjCMethodDecl *Method = getNSNumberFactoryMethod(*this, AtLoc, NumberType,
true, NR);
if (!Method)
return ExprError();
// Convert the number to the type that the parameter expects.
ParmVarDecl *ParamDecl = Method->parameters()[0];
InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
ParamDecl);
ExprResult ConvertedNumber = PerformCopyInitialization(Entity,
SourceLocation(),
Number);
if (ConvertedNumber.isInvalid())
return ExprError();
Number = ConvertedNumber.get();
// Use the effective source range of the literal, including the leading '@'.
return MaybeBindToTemporary(
new (Context) ObjCBoxedExpr(Number, NSNumberPointer, Method,
SourceRange(AtLoc, NR.getEnd())));
}
ExprResult Sema::ActOnObjCBoolLiteral(SourceLocation AtLoc,
SourceLocation ValueLoc,
bool Value) {
ExprResult Inner;
if (getLangOpts().CPlusPlus) {
Inner = ActOnCXXBoolLiteral(ValueLoc, Value? tok::kw_true : tok::kw_false);
} else {
// C doesn't actually have a way to represent literal values of type
// _Bool. So, we'll use 0/1 and implicit cast to _Bool.
Inner = ActOnIntegerConstant(ValueLoc, Value? 1 : 0);
Inner = ImpCastExprToType(Inner.get(), Context.BoolTy,
CK_IntegralToBoolean);
}
return BuildObjCNumericLiteral(AtLoc, Inner.get());
}
/// \brief Check that the given expression is a valid element of an Objective-C
/// collection literal.
static ExprResult CheckObjCCollectionLiteralElement(Sema &S, Expr *Element,
QualType T,
bool ArrayLiteral = false) {
// If the expression is type-dependent, there's nothing for us to do.
if (Element->isTypeDependent())
return Element;
ExprResult Result = S.CheckPlaceholderExpr(Element);
if (Result.isInvalid())
return ExprError();
Element = Result.get();
// In C++, check for an implicit conversion to an Objective-C object pointer
// type.
if (S.getLangOpts().CPlusPlus && Element->getType()->isRecordType()) {
InitializedEntity Entity
= InitializedEntity::InitializeParameter(S.Context, T,
/*Consumed=*/false);
InitializationKind Kind
= InitializationKind::CreateCopy(Element->getLocStart(),
SourceLocation());
InitializationSequence Seq(S, Entity, Kind, Element);
if (!Seq.Failed())
return Seq.Perform(S, Entity, Kind, Element);
}
Expr *OrigElement = Element;
// Perform lvalue-to-rvalue conversion.
Result = S.DefaultLvalueConversion(Element);
if (Result.isInvalid())
return ExprError();
Element = Result.get();
// Make sure that we have an Objective-C pointer type or block.
if (!Element->getType()->isObjCObjectPointerType() &&
!Element->getType()->isBlockPointerType()) {
bool Recovered = false;
// If this is potentially an Objective-C numeric literal, add the '@'.
if (isa<IntegerLiteral>(OrigElement) ||
isa<CharacterLiteral>(OrigElement) ||
isa<FloatingLiteral>(OrigElement) ||
isa<ObjCBoolLiteralExpr>(OrigElement) ||
isa<CXXBoolLiteralExpr>(OrigElement)) {
if (S.NSAPIObj->getNSNumberFactoryMethodKind(OrigElement->getType())) {
int Which = isa<CharacterLiteral>(OrigElement) ? 1
: (isa<CXXBoolLiteralExpr>(OrigElement) ||
isa<ObjCBoolLiteralExpr>(OrigElement)) ? 2
: 3;
S.Diag(OrigElement->getLocStart(), diag::err_box_literal_collection)
<< Which << OrigElement->getSourceRange()
<< FixItHint::CreateInsertion(OrigElement->getLocStart(), "@");
Result = S.BuildObjCNumericLiteral(OrigElement->getLocStart(),
OrigElement);
if (Result.isInvalid())
return ExprError();
Element = Result.get();
Recovered = true;
}
}
// If this is potentially an Objective-C string literal, add the '@'.
else if (StringLiteral *String = dyn_cast<StringLiteral>(OrigElement)) {
if (String->isAscii()) {
S.Diag(OrigElement->getLocStart(), diag::err_box_literal_collection)
<< 0 << OrigElement->getSourceRange()
<< FixItHint::CreateInsertion(OrigElement->getLocStart(), "@");
Result = S.BuildObjCStringLiteral(OrigElement->getLocStart(), String);
if (Result.isInvalid())
return ExprError();
Element = Result.get();
Recovered = true;
}
}
if (!Recovered) {
S.Diag(Element->getLocStart(), diag::err_invalid_collection_element)
<< Element->getType();
return ExprError();
}
}
if (ArrayLiteral)
if (ObjCStringLiteral *getString =
dyn_cast<ObjCStringLiteral>(OrigElement)) {
if (StringLiteral *SL = getString->getString()) {
unsigned numConcat = SL->getNumConcatenated();
if (numConcat > 1) {
// Only warn if the concatenated string doesn't come from a macro.
bool hasMacro = false;
for (unsigned i = 0; i < numConcat ; ++i)
if (SL->getStrTokenLoc(i).isMacroID()) {
hasMacro = true;
break;
}
if (!hasMacro)
S.Diag(Element->getLocStart(),
diag::warn_concatenated_nsarray_literal)
<< Element->getType();
}
}
}
// Make sure that the element has the type that the container factory
// function expects.
return S.PerformCopyInitialization(
InitializedEntity::InitializeParameter(S.Context, T,
/*Consumed=*/false),
Element->getLocStart(), Element);
}
ExprResult Sema::BuildObjCBoxedExpr(SourceRange SR, Expr *ValueExpr) {
if (ValueExpr->isTypeDependent()) {
ObjCBoxedExpr *BoxedExpr =
new (Context) ObjCBoxedExpr(ValueExpr, Context.DependentTy, nullptr, SR);
return BoxedExpr;
}
ObjCMethodDecl *BoxingMethod = nullptr;
QualType BoxedType;
// Convert the expression to an RValue, so we can check for pointer types...
ExprResult RValue = DefaultFunctionArrayLvalueConversion(ValueExpr);
if (RValue.isInvalid()) {
return ExprError();
}
SourceLocation Loc = SR.getBegin();
ValueExpr = RValue.get();
QualType ValueType(ValueExpr->getType());
if (const PointerType *PT = ValueType->getAs<PointerType>()) {
QualType PointeeType = PT->getPointeeType();
if (Context.hasSameUnqualifiedType(PointeeType, Context.CharTy)) {
if (!NSStringDecl) {
NSStringDecl = LookupObjCInterfaceDeclForLiteral(*this, Loc,
Sema::LK_String);
if (!NSStringDecl) {
return ExprError();
}
QualType NSStringObject = Context.getObjCInterfaceType(NSStringDecl);
NSStringPointer = Context.getObjCObjectPointerType(NSStringObject);
}
if (!StringWithUTF8StringMethod) {
IdentifierInfo *II = &Context.Idents.get("stringWithUTF8String");
Selector stringWithUTF8String = Context.Selectors.getUnarySelector(II);
// Look for the appropriate method within NSString.
BoxingMethod = NSStringDecl->lookupClassMethod(stringWithUTF8String);
if (!BoxingMethod && getLangOpts().DebuggerObjCLiteral) {
// Debugger needs to work even if NSString hasn't been defined.
TypeSourceInfo *ReturnTInfo = nullptr;
ObjCMethodDecl *M = ObjCMethodDecl::Create(
Context, SourceLocation(), SourceLocation(), stringWithUTF8String,
NSStringPointer, ReturnTInfo, NSStringDecl,
/*isInstance=*/false, /*isVariadic=*/false,
/*isPropertyAccessor=*/false,
/*isImplicitlyDeclared=*/true,
/*isDefined=*/false, ObjCMethodDecl::Required,
/*HasRelatedResultType=*/false);
QualType ConstCharType = Context.CharTy.withConst();
ParmVarDecl *value =
ParmVarDecl::Create(Context, M,
SourceLocation(), SourceLocation(),
&Context.Idents.get("value"),
Context.getPointerType(ConstCharType),
/*TInfo=*/nullptr,
SC_None, nullptr);
M->setMethodParams(Context, value, None);
BoxingMethod = M;
}
if (!validateBoxingMethod(*this, Loc, NSStringDecl,
stringWithUTF8String, BoxingMethod))
return ExprError();
StringWithUTF8StringMethod = BoxingMethod;
}
BoxingMethod = StringWithUTF8StringMethod;
BoxedType = NSStringPointer;
// Transfer the nullability from method's return type.
Optional<NullabilityKind> Nullability =
BoxingMethod->getReturnType()->getNullability(Context);
if (Nullability)
BoxedType = Context.getAttributedType(
AttributedType::getNullabilityAttrKind(*Nullability), BoxedType,
BoxedType);
}
} else if (ValueType->isBuiltinType()) {
// The other types we support are numeric, char and BOOL/bool. We could also
// provide limited support for structure types, such as NSRange, NSRect, and
// NSSize. See NSValue (NSValueGeometryExtensions) in <Foundation/NSGeometry.h>
// for more details.
// Check for a top-level character literal.
if (const CharacterLiteral *Char =
dyn_cast<CharacterLiteral>(ValueExpr->IgnoreParens())) {
// In C, character literals have type 'int'. That's not the type we want
// to use to determine the Objective-c literal kind.
switch (Char->getKind()) {
case CharacterLiteral::Ascii:
case CharacterLiteral::UTF8:
ValueType = Context.CharTy;
break;
case CharacterLiteral::Wide:
ValueType = Context.getWideCharType();
break;
case CharacterLiteral::UTF16:
ValueType = Context.Char16Ty;
break;
case CharacterLiteral::UTF32:
ValueType = Context.Char32Ty;
break;
}
}
// FIXME: Do I need to do anything special with BoolTy expressions?
// Look for the appropriate method within NSNumber.
BoxingMethod = getNSNumberFactoryMethod(*this, Loc, ValueType);
BoxedType = NSNumberPointer;
} else if (const EnumType *ET = ValueType->getAs<EnumType>()) {
if (!ET->getDecl()->isComplete()) {
Diag(Loc, diag::err_objc_incomplete_boxed_expression_type)
<< ValueType << ValueExpr->getSourceRange();
return ExprError();
}
BoxingMethod = getNSNumberFactoryMethod(*this, Loc,
ET->getDecl()->getIntegerType());
BoxedType = NSNumberPointer;
} else if (ValueType->isObjCBoxableRecordType()) {
// Support for structure types, that marked as objc_boxable
// struct __attribute__((objc_boxable)) s { ... };
// Look up the NSValue class, if we haven't done so already. It's cached
// in the Sema instance.
if (!NSValueDecl) {
NSValueDecl = LookupObjCInterfaceDeclForLiteral(*this, Loc,
Sema::LK_Boxed);
if (!NSValueDecl) {
return ExprError();
}
// generate the pointer to NSValue type.
QualType NSValueObject = Context.getObjCInterfaceType(NSValueDecl);
NSValuePointer = Context.getObjCObjectPointerType(NSValueObject);
}
if (!ValueWithBytesObjCTypeMethod) {
IdentifierInfo *II[] = {
&Context.Idents.get("valueWithBytes"),
&Context.Idents.get("objCType")
};
Selector ValueWithBytesObjCType = Context.Selectors.getSelector(2, II);
// Look for the appropriate method within NSValue.
BoxingMethod = NSValueDecl->lookupClassMethod(ValueWithBytesObjCType);
if (!BoxingMethod && getLangOpts().DebuggerObjCLiteral) {
// Debugger needs to work even if NSValue hasn't been defined.
TypeSourceInfo *ReturnTInfo = nullptr;
ObjCMethodDecl *M = ObjCMethodDecl::Create(
Context,
SourceLocation(),
SourceLocation(),
ValueWithBytesObjCType,
NSValuePointer,
ReturnTInfo,
NSValueDecl,
/*isInstance=*/false,
/*isVariadic=*/false,
/*isPropertyAccessor=*/false,
/*isImplicitlyDeclared=*/true,
/*isDefined=*/false,
ObjCMethodDecl::Required,
/*HasRelatedResultType=*/false);
SmallVector<ParmVarDecl *, 2> Params;
ParmVarDecl *bytes =
ParmVarDecl::Create(Context, M,
SourceLocation(), SourceLocation(),
&Context.Idents.get("bytes"),
Context.VoidPtrTy.withConst(),
/*TInfo=*/nullptr,
SC_None, nullptr);
Params.push_back(bytes);
QualType ConstCharType = Context.CharTy.withConst();
ParmVarDecl *type =
ParmVarDecl::Create(Context, M,
SourceLocation(), SourceLocation(),
&Context.Idents.get("type"),
Context.getPointerType(ConstCharType),
/*TInfo=*/nullptr,
SC_None, nullptr);
Params.push_back(type);
M->setMethodParams(Context, Params, None);
BoxingMethod = M;
}
if (!validateBoxingMethod(*this, Loc, NSValueDecl,
ValueWithBytesObjCType, BoxingMethod))
return ExprError();
ValueWithBytesObjCTypeMethod = BoxingMethod;
}
if (!ValueType.isTriviallyCopyableType(Context)) {
Diag(Loc, diag::err_objc_non_trivially_copyable_boxed_expression_type)
<< ValueType << ValueExpr->getSourceRange();
return ExprError();
}
BoxingMethod = ValueWithBytesObjCTypeMethod;
BoxedType = NSValuePointer;
}
if (!BoxingMethod) {
Diag(Loc, diag::err_objc_illegal_boxed_expression_type)
<< ValueType << ValueExpr->getSourceRange();
return ExprError();
}
DiagnoseUseOfDecl(BoxingMethod, Loc);
ExprResult ConvertedValueExpr;
if (ValueType->isObjCBoxableRecordType()) {
InitializedEntity IE = InitializedEntity::InitializeTemporary(ValueType);
ConvertedValueExpr = PerformCopyInitialization(IE, ValueExpr->getExprLoc(),
ValueExpr);
} else {
// Convert the expression to the type that the parameter requires.
ParmVarDecl *ParamDecl = BoxingMethod->parameters()[0];
InitializedEntity IE = InitializedEntity::InitializeParameter(Context,
ParamDecl);
ConvertedValueExpr = PerformCopyInitialization(IE, SourceLocation(),
ValueExpr);
}
if (ConvertedValueExpr.isInvalid())
return ExprError();
ValueExpr = ConvertedValueExpr.get();
ObjCBoxedExpr *BoxedExpr =
new (Context) ObjCBoxedExpr(ValueExpr, BoxedType,
BoxingMethod, SR);
return MaybeBindToTemporary(BoxedExpr);
}
/// Build an ObjC subscript pseudo-object expression, given that
/// that's supported by the runtime.
ExprResult Sema::BuildObjCSubscriptExpression(SourceLocation RB, Expr *BaseExpr,
Expr *IndexExpr,
ObjCMethodDecl *getterMethod,
ObjCMethodDecl *setterMethod) {
assert(!LangOpts.isSubscriptPointerArithmetic());
// We can't get dependent types here; our callers should have
// filtered them out.
assert((!BaseExpr->isTypeDependent() && !IndexExpr->isTypeDependent()) &&
"base or index cannot have dependent type here");
// Filter out placeholders in the index. In theory, overloads could
// be preserved here, although that might not actually work correctly.
ExprResult Result = CheckPlaceholderExpr(IndexExpr);
if (Result.isInvalid())
return ExprError();
IndexExpr = Result.get();
// Perform lvalue-to-rvalue conversion on the base.
Result = DefaultLvalueConversion(BaseExpr);
if (Result.isInvalid())
return ExprError();
BaseExpr = Result.get();
// Build the pseudo-object expression.
return new (Context) ObjCSubscriptRefExpr(
BaseExpr, IndexExpr, Context.PseudoObjectTy, VK_LValue, OK_ObjCSubscript,
getterMethod, setterMethod, RB);
}
ExprResult Sema::BuildObjCArrayLiteral(SourceRange SR, MultiExprArg Elements) {
SourceLocation Loc = SR.getBegin();
if (!NSArrayDecl) {
NSArrayDecl = LookupObjCInterfaceDeclForLiteral(*this, Loc,
Sema::LK_Array);
if (!NSArrayDecl) {
return ExprError();
}
}
// Find the arrayWithObjects:count: method, if we haven't done so already.
QualType IdT = Context.getObjCIdType();
if (!ArrayWithObjectsMethod) {
Selector
Sel = NSAPIObj->getNSArraySelector(NSAPI::NSArr_arrayWithObjectsCount);
ObjCMethodDecl *Method = NSArrayDecl->lookupClassMethod(Sel);
if (!Method && getLangOpts().DebuggerObjCLiteral) {
TypeSourceInfo *ReturnTInfo = nullptr;
Method = ObjCMethodDecl::Create(
Context, SourceLocation(), SourceLocation(), Sel, IdT, ReturnTInfo,
Context.getTranslationUnitDecl(), false /*Instance*/,
false /*isVariadic*/,
/*isPropertyAccessor=*/false,
/*isImplicitlyDeclared=*/true, /*isDefined=*/false,
ObjCMethodDecl::Required, false);
SmallVector<ParmVarDecl *, 2> Params;
ParmVarDecl *objects = ParmVarDecl::Create(Context, Method,
SourceLocation(),
SourceLocation(),
&Context.Idents.get("objects"),
Context.getPointerType(IdT),
/*TInfo=*/nullptr,
SC_None, nullptr);
Params.push_back(objects);
ParmVarDecl *cnt = ParmVarDecl::Create(Context, Method,
SourceLocation(),
SourceLocation(),
&Context.Idents.get("cnt"),
Context.UnsignedLongTy,
/*TInfo=*/nullptr, SC_None,
nullptr);
Params.push_back(cnt);
Method->setMethodParams(Context, Params, None);
}
if (!validateBoxingMethod(*this, Loc, NSArrayDecl, Sel, Method))
return ExprError();
// Dig out the type that all elements should be converted to.
QualType T = Method->parameters()[0]->getType();
const PointerType *PtrT = T->getAs<PointerType>();
if (!PtrT ||
!Context.hasSameUnqualifiedType(PtrT->getPointeeType(), IdT)) {
Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
<< Sel;
Diag(Method->parameters()[0]->getLocation(),
diag::note_objc_literal_method_param)
<< 0 << T
<< Context.getPointerType(IdT.withConst());
return ExprError();
}
// Check that the 'count' parameter is integral.
if (!Method->parameters()[1]->getType()->isIntegerType()) {
Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
<< Sel;
Diag(Method->parameters()[1]->getLocation(),
diag::note_objc_literal_method_param)
<< 1
<< Method->parameters()[1]->getType()
<< "integral";
return ExprError();
}
// We've found a good +arrayWithObjects:count: method. Save it!
ArrayWithObjectsMethod = Method;
}
QualType ObjectsType = ArrayWithObjectsMethod->parameters()[0]->getType();
QualType RequiredType = ObjectsType->castAs<PointerType>()->getPointeeType();
// Check that each of the elements provided is valid in a collection literal,
// performing conversions as necessary.
Expr **ElementsBuffer = Elements.data();
for (unsigned I = 0, N = Elements.size(); I != N; ++I) {
ExprResult Converted = CheckObjCCollectionLiteralElement(*this,
ElementsBuffer[I],
RequiredType, true);
if (Converted.isInvalid())
return ExprError();
ElementsBuffer[I] = Converted.get();
}
QualType Ty
= Context.getObjCObjectPointerType(
Context.getObjCInterfaceType(NSArrayDecl));
return MaybeBindToTemporary(
ObjCArrayLiteral::Create(Context, Elements, Ty,
ArrayWithObjectsMethod, SR));
}
ExprResult Sema::BuildObjCDictionaryLiteral(SourceRange SR,
MutableArrayRef<ObjCDictionaryElement> Elements) {
SourceLocation Loc = SR.getBegin();
if (!NSDictionaryDecl) {
NSDictionaryDecl = LookupObjCInterfaceDeclForLiteral(*this, Loc,
Sema::LK_Dictionary);
if (!NSDictionaryDecl) {
return ExprError();
}
}
// Find the dictionaryWithObjects:forKeys:count: method, if we haven't done
// so already.
QualType IdT = Context.getObjCIdType();
if (!DictionaryWithObjectsMethod) {
Selector Sel = NSAPIObj->getNSDictionarySelector(
NSAPI::NSDict_dictionaryWithObjectsForKeysCount);
ObjCMethodDecl *Method = NSDictionaryDecl->lookupClassMethod(Sel);
if (!Method && getLangOpts().DebuggerObjCLiteral) {
Method = ObjCMethodDecl::Create(Context,
SourceLocation(), SourceLocation(), Sel,
IdT,
nullptr /*TypeSourceInfo */,
Context.getTranslationUnitDecl(),
false /*Instance*/, false/*isVariadic*/,
/*isPropertyAccessor=*/false,
/*isImplicitlyDeclared=*/true, /*isDefined=*/false,
ObjCMethodDecl::Required,
false);
SmallVector<ParmVarDecl *, 3> Params;
ParmVarDecl *objects = ParmVarDecl::Create(Context, Method,
SourceLocation(),
SourceLocation(),
&Context.Idents.get("objects"),
Context.getPointerType(IdT),
/*TInfo=*/nullptr, SC_None,
nullptr);
Params.push_back(objects);
ParmVarDecl *keys = ParmVarDecl::Create(Context, Method,
SourceLocation(),
SourceLocation(),
&Context.Idents.get("keys"),
Context.getPointerType(IdT),
/*TInfo=*/nullptr, SC_None,
nullptr);
Params.push_back(keys);
ParmVarDecl *cnt = ParmVarDecl::Create(Context, Method,
SourceLocation(),
SourceLocation(),
&Context.Idents.get("cnt"),
Context.UnsignedLongTy,
/*TInfo=*/nullptr, SC_None,
nullptr);
Params.push_back(cnt);
Method->setMethodParams(Context, Params, None);
}
if (!validateBoxingMethod(*this, SR.getBegin(), NSDictionaryDecl, Sel,
Method))
return ExprError();
// Dig out the type that all values should be converted to.
QualType ValueT = Method->parameters()[0]->getType();
const PointerType *PtrValue = ValueT->getAs<PointerType>();
if (!PtrValue ||
!Context.hasSameUnqualifiedType(PtrValue->getPointeeType(), IdT)) {
Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
<< Sel;
Diag(Method->parameters()[0]->getLocation(),
diag::note_objc_literal_method_param)
<< 0 << ValueT
<< Context.getPointerType(IdT.withConst());
return ExprError();
}
// Dig out the type that all keys should be converted to.
QualType KeyT = Method->parameters()[1]->getType();
const PointerType *PtrKey = KeyT->getAs<PointerType>();
if (!PtrKey ||
!Context.hasSameUnqualifiedType(PtrKey->getPointeeType(),
IdT)) {
bool err = true;
if (PtrKey) {
if (QIDNSCopying.isNull()) {
// key argument of selector is id<NSCopying>?
if (ObjCProtocolDecl *NSCopyingPDecl =
LookupProtocol(&Context.Idents.get("NSCopying"), SR.getBegin())) {
ObjCProtocolDecl *PQ[] = {NSCopyingPDecl};
QIDNSCopying =
Context.getObjCObjectType(Context.ObjCBuiltinIdTy, { },
llvm::makeArrayRef(
(ObjCProtocolDecl**) PQ,
1),
false);
QIDNSCopying = Context.getObjCObjectPointerType(QIDNSCopying);
}
}
if (!QIDNSCopying.isNull())
err = !Context.hasSameUnqualifiedType(PtrKey->getPointeeType(),
QIDNSCopying);
}
if (err) {
Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
<< Sel;
Diag(Method->parameters()[1]->getLocation(),
diag::note_objc_literal_method_param)
<< 1 << KeyT
<< Context.getPointerType(IdT.withConst());
return ExprError();
}
}
// Check that the 'count' parameter is integral.
QualType CountType = Method->parameters()[2]->getType();
if (!CountType->isIntegerType()) {
Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
<< Sel;
Diag(Method->parameters()[2]->getLocation(),
diag::note_objc_literal_method_param)
<< 2 << CountType
<< "integral";
return ExprError();
}