forked from llvm-mirror/clang
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathParseObjc.cpp
3690 lines (3247 loc) · 129 KB
/
ParseObjc.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
//===--- ParseObjC.cpp - Objective C Parsing ------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the Objective-C portions of the Parser interface.
//
//===----------------------------------------------------------------------===//
#include "clang/Parse/Parser.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/PrettyDeclStackTrace.h"
#include "clang/Basic/CharInfo.h"
#include "clang/Parse/ParseDiagnostic.h"
#include "clang/Parse/RAIIObjectsForParser.h"
#include "clang/Sema/DeclSpec.h"
#include "clang/Sema/Scope.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/StringExtras.h"
using namespace clang;
/// Skips attributes after an Objective-C @ directive. Emits a diagnostic.
void Parser::MaybeSkipAttributes(tok::ObjCKeywordKind Kind) {
ParsedAttributes attrs(AttrFactory);
if (Tok.is(tok::kw___attribute)) {
if (Kind == tok::objc_interface || Kind == tok::objc_protocol)
Diag(Tok, diag::err_objc_postfix_attribute_hint)
<< (Kind == tok::objc_protocol);
else
Diag(Tok, diag::err_objc_postfix_attribute);
ParseGNUAttributes(attrs);
}
}
/// ParseObjCAtDirectives - Handle parts of the external-declaration production:
/// external-declaration: [C99 6.9]
/// [OBJC] objc-class-definition
/// [OBJC] objc-class-declaration
/// [OBJC] objc-alias-declaration
/// [OBJC] objc-protocol-definition
/// [OBJC] objc-method-definition
/// [OBJC] '@' 'end'
Parser::DeclGroupPtrTy
Parser::ParseObjCAtDirectives(ParsedAttributesWithRange &Attrs) {
SourceLocation AtLoc = ConsumeToken(); // the "@"
if (Tok.is(tok::code_completion)) {
Actions.CodeCompleteObjCAtDirective(getCurScope());
cutOffParsing();
return nullptr;
}
Decl *SingleDecl = nullptr;
switch (Tok.getObjCKeywordID()) {
case tok::objc_class:
return ParseObjCAtClassDeclaration(AtLoc);
case tok::objc_interface:
SingleDecl = ParseObjCAtInterfaceDeclaration(AtLoc, Attrs);
break;
case tok::objc_protocol:
return ParseObjCAtProtocolDeclaration(AtLoc, Attrs);
case tok::objc_implementation:
return ParseObjCAtImplementationDeclaration(AtLoc);
case tok::objc_end:
return ParseObjCAtEndDeclaration(AtLoc);
case tok::objc_compatibility_alias:
SingleDecl = ParseObjCAtAliasDeclaration(AtLoc);
break;
case tok::objc_synthesize:
SingleDecl = ParseObjCPropertySynthesize(AtLoc);
break;
case tok::objc_dynamic:
SingleDecl = ParseObjCPropertyDynamic(AtLoc);
break;
case tok::objc_import:
if (getLangOpts().Modules || getLangOpts().DebuggerSupport) {
SingleDecl = ParseModuleImport(AtLoc);
break;
}
Diag(AtLoc, diag::err_atimport);
SkipUntil(tok::semi);
return Actions.ConvertDeclToDeclGroup(nullptr);
default:
Diag(AtLoc, diag::err_unexpected_at);
SkipUntil(tok::semi);
SingleDecl = nullptr;
break;
}
return Actions.ConvertDeclToDeclGroup(SingleDecl);
}
/// Class to handle popping type parameters when leaving the scope.
class Parser::ObjCTypeParamListScope {
Sema &Actions;
Scope *S;
ObjCTypeParamList *Params;
public:
ObjCTypeParamListScope(Sema &Actions, Scope *S)
: Actions(Actions), S(S), Params(nullptr) {}
~ObjCTypeParamListScope() {
leave();
}
void enter(ObjCTypeParamList *P) {
assert(!Params);
Params = P;
}
void leave() {
if (Params)
Actions.popObjCTypeParamList(S, Params);
Params = nullptr;
}
};
///
/// objc-class-declaration:
/// '@' 'class' objc-class-forward-decl (',' objc-class-forward-decl)* ';'
///
/// objc-class-forward-decl:
/// identifier objc-type-parameter-list[opt]
///
Parser::DeclGroupPtrTy
Parser::ParseObjCAtClassDeclaration(SourceLocation atLoc) {
ConsumeToken(); // the identifier "class"
SmallVector<IdentifierInfo *, 8> ClassNames;
SmallVector<SourceLocation, 8> ClassLocs;
SmallVector<ObjCTypeParamList *, 8> ClassTypeParams;
while (1) {
MaybeSkipAttributes(tok::objc_class);
if (expectIdentifier()) {
SkipUntil(tok::semi);
return Actions.ConvertDeclToDeclGroup(nullptr);
}
ClassNames.push_back(Tok.getIdentifierInfo());
ClassLocs.push_back(Tok.getLocation());
ConsumeToken();
// Parse the optional objc-type-parameter-list.
ObjCTypeParamList *TypeParams = nullptr;
if (Tok.is(tok::less))
TypeParams = parseObjCTypeParamList();
ClassTypeParams.push_back(TypeParams);
if (!TryConsumeToken(tok::comma))
break;
}
// Consume the ';'.
if (ExpectAndConsume(tok::semi, diag::err_expected_after, "@class"))
return Actions.ConvertDeclToDeclGroup(nullptr);
return Actions.ActOnForwardClassDeclaration(atLoc, ClassNames.data(),
ClassLocs.data(),
ClassTypeParams,
ClassNames.size());
}
void Parser::CheckNestedObjCContexts(SourceLocation AtLoc)
{
Sema::ObjCContainerKind ock = Actions.getObjCContainerKind();
if (ock == Sema::OCK_None)
return;
Decl *Decl = Actions.getObjCDeclContext();
if (CurParsedObjCImpl) {
CurParsedObjCImpl->finish(AtLoc);
} else {
Actions.ActOnAtEnd(getCurScope(), AtLoc);
}
Diag(AtLoc, diag::err_objc_missing_end)
<< FixItHint::CreateInsertion(AtLoc, "@end\n");
if (Decl)
Diag(Decl->getLocStart(), diag::note_objc_container_start)
<< (int) ock;
}
///
/// objc-interface:
/// objc-class-interface-attributes[opt] objc-class-interface
/// objc-category-interface
///
/// objc-class-interface:
/// '@' 'interface' identifier objc-type-parameter-list[opt]
/// objc-superclass[opt] objc-protocol-refs[opt]
/// objc-class-instance-variables[opt]
/// objc-interface-decl-list
/// @end
///
/// objc-category-interface:
/// '@' 'interface' identifier objc-type-parameter-list[opt]
/// '(' identifier[opt] ')' objc-protocol-refs[opt]
/// objc-interface-decl-list
/// @end
///
/// objc-superclass:
/// ':' identifier objc-type-arguments[opt]
///
/// objc-class-interface-attributes:
/// __attribute__((visibility("default")))
/// __attribute__((visibility("hidden")))
/// __attribute__((deprecated))
/// __attribute__((unavailable))
/// __attribute__((objc_exception)) - used by NSException on 64-bit
/// __attribute__((objc_root_class))
///
Decl *Parser::ParseObjCAtInterfaceDeclaration(SourceLocation AtLoc,
ParsedAttributes &attrs) {
assert(Tok.isObjCAtKeyword(tok::objc_interface) &&
"ParseObjCAtInterfaceDeclaration(): Expected @interface");
CheckNestedObjCContexts(AtLoc);
ConsumeToken(); // the "interface" identifier
// Code completion after '@interface'.
if (Tok.is(tok::code_completion)) {
Actions.CodeCompleteObjCInterfaceDecl(getCurScope());
cutOffParsing();
return nullptr;
}
MaybeSkipAttributes(tok::objc_interface);
if (expectIdentifier())
return nullptr; // missing class or category name.
// We have a class or category name - consume it.
IdentifierInfo *nameId = Tok.getIdentifierInfo();
SourceLocation nameLoc = ConsumeToken();
// Parse the objc-type-parameter-list or objc-protocol-refs. For the latter
// case, LAngleLoc will be valid and ProtocolIdents will capture the
// protocol references (that have not yet been resolved).
SourceLocation LAngleLoc, EndProtoLoc;
SmallVector<IdentifierLocPair, 8> ProtocolIdents;
ObjCTypeParamList *typeParameterList = nullptr;
ObjCTypeParamListScope typeParamScope(Actions, getCurScope());
if (Tok.is(tok::less))
typeParameterList = parseObjCTypeParamListOrProtocolRefs(
typeParamScope, LAngleLoc, ProtocolIdents, EndProtoLoc);
if (Tok.is(tok::l_paren) &&
!isKnownToBeTypeSpecifier(GetLookAheadToken(1))) { // we have a category.
BalancedDelimiterTracker T(*this, tok::l_paren);
T.consumeOpen();
SourceLocation categoryLoc;
IdentifierInfo *categoryId = nullptr;
if (Tok.is(tok::code_completion)) {
Actions.CodeCompleteObjCInterfaceCategory(getCurScope(), nameId, nameLoc);
cutOffParsing();
return nullptr;
}
// For ObjC2, the category name is optional (not an error).
if (Tok.is(tok::identifier)) {
categoryId = Tok.getIdentifierInfo();
categoryLoc = ConsumeToken();
}
else if (!getLangOpts().ObjC2) {
Diag(Tok, diag::err_expected)
<< tok::identifier; // missing category name.
return nullptr;
}
T.consumeClose();
if (T.getCloseLocation().isInvalid())
return nullptr;
// Next, we need to check for any protocol references.
assert(LAngleLoc.isInvalid() && "Cannot have already parsed protocols");
SmallVector<Decl *, 8> ProtocolRefs;
SmallVector<SourceLocation, 8> ProtocolLocs;
if (Tok.is(tok::less) &&
ParseObjCProtocolReferences(ProtocolRefs, ProtocolLocs, true, true,
LAngleLoc, EndProtoLoc,
/*consumeLastToken=*/true))
return nullptr;
Decl *CategoryType = Actions.ActOnStartCategoryInterface(
AtLoc, nameId, nameLoc, typeParameterList, categoryId, categoryLoc,
ProtocolRefs.data(), ProtocolRefs.size(), ProtocolLocs.data(),
EndProtoLoc, attrs.getList());
if (Tok.is(tok::l_brace))
ParseObjCClassInstanceVariables(CategoryType, tok::objc_private, AtLoc);
ParseObjCInterfaceDeclList(tok::objc_not_keyword, CategoryType);
return CategoryType;
}
// Parse a class interface.
IdentifierInfo *superClassId = nullptr;
SourceLocation superClassLoc;
SourceLocation typeArgsLAngleLoc;
SmallVector<ParsedType, 4> typeArgs;
SourceLocation typeArgsRAngleLoc;
SmallVector<Decl *, 4> protocols;
SmallVector<SourceLocation, 4> protocolLocs;
if (Tok.is(tok::colon)) { // a super class is specified.
ConsumeToken();
// Code completion of superclass names.
if (Tok.is(tok::code_completion)) {
Actions.CodeCompleteObjCSuperclass(getCurScope(), nameId, nameLoc);
cutOffParsing();
return nullptr;
}
if (expectIdentifier())
return nullptr; // missing super class name.
superClassId = Tok.getIdentifierInfo();
superClassLoc = ConsumeToken();
// Type arguments for the superclass or protocol conformances.
if (Tok.is(tok::less)) {
parseObjCTypeArgsOrProtocolQualifiers(
nullptr, typeArgsLAngleLoc, typeArgs, typeArgsRAngleLoc, LAngleLoc,
protocols, protocolLocs, EndProtoLoc,
/*consumeLastToken=*/true,
/*warnOnIncompleteProtocols=*/true);
if (Tok.is(tok::eof))
return nullptr;
}
}
// Next, we need to check for any protocol references.
if (LAngleLoc.isValid()) {
if (!ProtocolIdents.empty()) {
// We already parsed the protocols named when we thought we had a
// type parameter list. Translate them into actual protocol references.
for (const auto &pair : ProtocolIdents) {
protocolLocs.push_back(pair.second);
}
Actions.FindProtocolDeclaration(/*WarnOnDeclarations=*/true,
/*ForObjCContainer=*/true,
ProtocolIdents, protocols);
}
} else if (protocols.empty() && Tok.is(tok::less) &&
ParseObjCProtocolReferences(protocols, protocolLocs, true, true,
LAngleLoc, EndProtoLoc,
/*consumeLastToken=*/true)) {
return nullptr;
}
if (Tok.isNot(tok::less))
Actions.ActOnTypedefedProtocols(protocols, protocolLocs,
superClassId, superClassLoc);
Decl *ClsType =
Actions.ActOnStartClassInterface(getCurScope(), AtLoc, nameId, nameLoc,
typeParameterList, superClassId,
superClassLoc,
typeArgs,
SourceRange(typeArgsLAngleLoc,
typeArgsRAngleLoc),
protocols.data(), protocols.size(),
protocolLocs.data(),
EndProtoLoc, attrs.getList());
if (Tok.is(tok::l_brace))
ParseObjCClassInstanceVariables(ClsType, tok::objc_protected, AtLoc);
ParseObjCInterfaceDeclList(tok::objc_interface, ClsType);
return ClsType;
}
/// Add an attribute for a context-sensitive type nullability to the given
/// declarator.
static void addContextSensitiveTypeNullability(Parser &P,
Declarator &D,
NullabilityKind nullability,
SourceLocation nullabilityLoc,
bool &addedToDeclSpec) {
// Create the attribute.
auto getNullabilityAttr = [&]() -> AttributeList * {
return D.getAttributePool().create(
P.getNullabilityKeyword(nullability),
SourceRange(nullabilityLoc),
nullptr, SourceLocation(),
nullptr, 0,
AttributeList::AS_ContextSensitiveKeyword);
};
if (D.getNumTypeObjects() > 0) {
// Add the attribute to the declarator chunk nearest the declarator.
auto nullabilityAttr = getNullabilityAttr();
DeclaratorChunk &chunk = D.getTypeObject(0);
nullabilityAttr->setNext(chunk.getAttrListRef());
chunk.getAttrListRef() = nullabilityAttr;
} else if (!addedToDeclSpec) {
// Otherwise, just put it on the declaration specifiers (if one
// isn't there already).
D.getMutableDeclSpec().addAttributes(getNullabilityAttr());
addedToDeclSpec = true;
}
}
/// Parse an Objective-C type parameter list, if present, or capture
/// the locations of the protocol identifiers for a list of protocol
/// references.
///
/// objc-type-parameter-list:
/// '<' objc-type-parameter (',' objc-type-parameter)* '>'
///
/// objc-type-parameter:
/// objc-type-parameter-variance? identifier objc-type-parameter-bound[opt]
///
/// objc-type-parameter-bound:
/// ':' type-name
///
/// objc-type-parameter-variance:
/// '__covariant'
/// '__contravariant'
///
/// \param lAngleLoc The location of the starting '<'.
///
/// \param protocolIdents Will capture the list of identifiers, if the
/// angle brackets contain a list of protocol references rather than a
/// type parameter list.
///
/// \param rAngleLoc The location of the ending '>'.
ObjCTypeParamList *Parser::parseObjCTypeParamListOrProtocolRefs(
ObjCTypeParamListScope &Scope, SourceLocation &lAngleLoc,
SmallVectorImpl<IdentifierLocPair> &protocolIdents,
SourceLocation &rAngleLoc, bool mayBeProtocolList) {
assert(Tok.is(tok::less) && "Not at the beginning of a type parameter list");
// Within the type parameter list, don't treat '>' as an operator.
GreaterThanIsOperatorScope G(GreaterThanIsOperator, false);
// Local function to "flush" the protocol identifiers, turning them into
// type parameters.
SmallVector<Decl *, 4> typeParams;
auto makeProtocolIdentsIntoTypeParameters = [&]() {
unsigned index = 0;
for (const auto &pair : protocolIdents) {
DeclResult typeParam = Actions.actOnObjCTypeParam(
getCurScope(), ObjCTypeParamVariance::Invariant, SourceLocation(),
index++, pair.first, pair.second, SourceLocation(), nullptr);
if (typeParam.isUsable())
typeParams.push_back(typeParam.get());
}
protocolIdents.clear();
mayBeProtocolList = false;
};
bool invalid = false;
lAngleLoc = ConsumeToken();
do {
// Parse the variance, if any.
SourceLocation varianceLoc;
ObjCTypeParamVariance variance = ObjCTypeParamVariance::Invariant;
if (Tok.is(tok::kw___covariant) || Tok.is(tok::kw___contravariant)) {
variance = Tok.is(tok::kw___covariant)
? ObjCTypeParamVariance::Covariant
: ObjCTypeParamVariance::Contravariant;
varianceLoc = ConsumeToken();
// Once we've seen a variance specific , we know this is not a
// list of protocol references.
if (mayBeProtocolList) {
// Up until now, we have been queuing up parameters because they
// might be protocol references. Turn them into parameters now.
makeProtocolIdentsIntoTypeParameters();
}
}
// Parse the identifier.
if (!Tok.is(tok::identifier)) {
// Code completion.
if (Tok.is(tok::code_completion)) {
// FIXME: If these aren't protocol references, we'll need different
// completions.
Actions.CodeCompleteObjCProtocolReferences(protocolIdents);
cutOffParsing();
// FIXME: Better recovery here?.
return nullptr;
}
Diag(Tok, diag::err_objc_expected_type_parameter);
invalid = true;
break;
}
IdentifierInfo *paramName = Tok.getIdentifierInfo();
SourceLocation paramLoc = ConsumeToken();
// If there is a bound, parse it.
SourceLocation colonLoc;
TypeResult boundType;
if (TryConsumeToken(tok::colon, colonLoc)) {
// Once we've seen a bound, we know this is not a list of protocol
// references.
if (mayBeProtocolList) {
// Up until now, we have been queuing up parameters because they
// might be protocol references. Turn them into parameters now.
makeProtocolIdentsIntoTypeParameters();
}
// type-name
boundType = ParseTypeName();
if (boundType.isInvalid())
invalid = true;
} else if (mayBeProtocolList) {
// If this could still be a protocol list, just capture the identifier.
// We don't want to turn it into a parameter.
protocolIdents.push_back(std::make_pair(paramName, paramLoc));
continue;
}
// Create the type parameter.
DeclResult typeParam = Actions.actOnObjCTypeParam(
getCurScope(), variance, varianceLoc, typeParams.size(), paramName,
paramLoc, colonLoc, boundType.isUsable() ? boundType.get() : nullptr);
if (typeParam.isUsable())
typeParams.push_back(typeParam.get());
} while (TryConsumeToken(tok::comma));
// Parse the '>'.
if (invalid) {
SkipUntil(tok::greater, tok::at, StopBeforeMatch);
if (Tok.is(tok::greater))
ConsumeToken();
} else if (ParseGreaterThanInTemplateList(rAngleLoc,
/*ConsumeLastToken=*/true,
/*ObjCGenericList=*/true)) {
Diag(lAngleLoc, diag::note_matching) << "'<'";
SkipUntil({tok::greater, tok::greaterequal, tok::at, tok::minus,
tok::minus, tok::plus, tok::colon, tok::l_paren, tok::l_brace,
tok::comma, tok::semi },
StopBeforeMatch);
if (Tok.is(tok::greater))
ConsumeToken();
}
if (mayBeProtocolList) {
// A type parameter list must be followed by either a ':' (indicating the
// presence of a superclass) or a '(' (indicating that this is a category
// or extension). This disambiguates between an objc-type-parameter-list
// and a objc-protocol-refs.
if (Tok.isNot(tok::colon) && Tok.isNot(tok::l_paren)) {
// Returning null indicates that we don't have a type parameter list.
// The results the caller needs to handle the protocol references are
// captured in the reference parameters already.
return nullptr;
}
// We have a type parameter list that looks like a list of protocol
// references. Turn that parameter list into type parameters.
makeProtocolIdentsIntoTypeParameters();
}
// Form the type parameter list and enter its scope.
ObjCTypeParamList *list = Actions.actOnObjCTypeParamList(
getCurScope(),
lAngleLoc,
typeParams,
rAngleLoc);
Scope.enter(list);
// Clear out the angle locations; they're used by the caller to indicate
// whether there are any protocol references.
lAngleLoc = SourceLocation();
rAngleLoc = SourceLocation();
return invalid ? nullptr : list;
}
/// Parse an objc-type-parameter-list.
ObjCTypeParamList *Parser::parseObjCTypeParamList() {
SourceLocation lAngleLoc;
SmallVector<IdentifierLocPair, 1> protocolIdents;
SourceLocation rAngleLoc;
ObjCTypeParamListScope Scope(Actions, getCurScope());
return parseObjCTypeParamListOrProtocolRefs(Scope, lAngleLoc, protocolIdents,
rAngleLoc,
/*mayBeProtocolList=*/false);
}
/// objc-interface-decl-list:
/// empty
/// objc-interface-decl-list objc-property-decl [OBJC2]
/// objc-interface-decl-list objc-method-requirement [OBJC2]
/// objc-interface-decl-list objc-method-proto ';'
/// objc-interface-decl-list declaration
/// objc-interface-decl-list ';'
///
/// objc-method-requirement: [OBJC2]
/// @required
/// @optional
///
void Parser::ParseObjCInterfaceDeclList(tok::ObjCKeywordKind contextKey,
Decl *CDecl) {
SmallVector<Decl *, 32> allMethods;
SmallVector<DeclGroupPtrTy, 8> allTUVariables;
tok::ObjCKeywordKind MethodImplKind = tok::objc_not_keyword;
SourceRange AtEnd;
while (1) {
// If this is a method prototype, parse it.
if (Tok.isOneOf(tok::minus, tok::plus)) {
if (Decl *methodPrototype =
ParseObjCMethodPrototype(MethodImplKind, false))
allMethods.push_back(methodPrototype);
// Consume the ';' here, since ParseObjCMethodPrototype() is re-used for
// method definitions.
if (ExpectAndConsumeSemi(diag::err_expected_semi_after_method_proto)) {
// We didn't find a semi and we error'ed out. Skip until a ';' or '@'.
SkipUntil(tok::at, StopAtSemi | StopBeforeMatch);
if (Tok.is(tok::semi))
ConsumeToken();
}
continue;
}
if (Tok.is(tok::l_paren)) {
Diag(Tok, diag::err_expected_minus_or_plus);
ParseObjCMethodDecl(Tok.getLocation(),
tok::minus,
MethodImplKind, false);
continue;
}
// Ignore excess semicolons.
if (Tok.is(tok::semi)) {
ConsumeToken();
continue;
}
// If we got to the end of the file, exit the loop.
if (isEofOrEom())
break;
// Code completion within an Objective-C interface.
if (Tok.is(tok::code_completion)) {
Actions.CodeCompleteOrdinaryName(getCurScope(),
CurParsedObjCImpl? Sema::PCC_ObjCImplementation
: Sema::PCC_ObjCInterface);
return cutOffParsing();
}
// If we don't have an @ directive, parse it as a function definition.
if (Tok.isNot(tok::at)) {
// The code below does not consume '}'s because it is afraid of eating the
// end of a namespace. Because of the way this code is structured, an
// erroneous r_brace would cause an infinite loop if not handled here.
if (Tok.is(tok::r_brace))
break;
ParsedAttributesWithRange attrs(AttrFactory);
allTUVariables.push_back(ParseDeclarationOrFunctionDefinition(attrs));
continue;
}
// Otherwise, we have an @ directive, eat the @.
SourceLocation AtLoc = ConsumeToken(); // the "@"
if (Tok.is(tok::code_completion)) {
Actions.CodeCompleteObjCAtDirective(getCurScope());
return cutOffParsing();
}
tok::ObjCKeywordKind DirectiveKind = Tok.getObjCKeywordID();
if (DirectiveKind == tok::objc_end) { // @end -> terminate list
AtEnd.setBegin(AtLoc);
AtEnd.setEnd(Tok.getLocation());
break;
} else if (DirectiveKind == tok::objc_not_keyword) {
Diag(Tok, diag::err_objc_unknown_at);
SkipUntil(tok::semi);
continue;
}
// Eat the identifier.
ConsumeToken();
switch (DirectiveKind) {
default:
// FIXME: If someone forgets an @end on a protocol, this loop will
// continue to eat up tons of stuff and spew lots of nonsense errors. It
// would probably be better to bail out if we saw an @class or @interface
// or something like that.
Diag(AtLoc, diag::err_objc_illegal_interface_qual);
// Skip until we see an '@' or '}' or ';'.
SkipUntil(tok::r_brace, tok::at, StopAtSemi);
break;
case tok::objc_implementation:
case tok::objc_interface:
Diag(AtLoc, diag::err_objc_missing_end)
<< FixItHint::CreateInsertion(AtLoc, "@end\n");
Diag(CDecl->getLocStart(), diag::note_objc_container_start)
<< (int) Actions.getObjCContainerKind();
ConsumeToken();
break;
case tok::objc_required:
case tok::objc_optional:
// This is only valid on protocols.
// FIXME: Should this check for ObjC2 being enabled?
if (contextKey != tok::objc_protocol)
Diag(AtLoc, diag::err_objc_directive_only_in_protocol);
else
MethodImplKind = DirectiveKind;
break;
case tok::objc_property:
if (!getLangOpts().ObjC2)
Diag(AtLoc, diag::err_objc_properties_require_objc2);
ObjCDeclSpec OCDS;
SourceLocation LParenLoc;
// Parse property attribute list, if any.
if (Tok.is(tok::l_paren)) {
LParenLoc = Tok.getLocation();
ParseObjCPropertyAttribute(OCDS);
}
bool addedToDeclSpec = false;
auto ObjCPropertyCallback = [&](ParsingFieldDeclarator &FD) {
if (FD.D.getIdentifier() == nullptr) {
Diag(AtLoc, diag::err_objc_property_requires_field_name)
<< FD.D.getSourceRange();
return;
}
if (FD.BitfieldSize) {
Diag(AtLoc, diag::err_objc_property_bitfield)
<< FD.D.getSourceRange();
return;
}
// Map a nullability property attribute to a context-sensitive keyword
// attribute.
if (OCDS.getPropertyAttributes() & ObjCDeclSpec::DQ_PR_nullability)
addContextSensitiveTypeNullability(*this, FD.D, OCDS.getNullability(),
OCDS.getNullabilityLoc(),
addedToDeclSpec);
// Install the property declarator into interfaceDecl.
IdentifierInfo *SelName =
OCDS.getGetterName() ? OCDS.getGetterName() : FD.D.getIdentifier();
Selector GetterSel = PP.getSelectorTable().getNullarySelector(SelName);
IdentifierInfo *SetterName = OCDS.getSetterName();
Selector SetterSel;
if (SetterName)
SetterSel = PP.getSelectorTable().getSelector(1, &SetterName);
else
SetterSel = SelectorTable::constructSetterSelector(
PP.getIdentifierTable(), PP.getSelectorTable(),
FD.D.getIdentifier());
Decl *Property = Actions.ActOnProperty(
getCurScope(), AtLoc, LParenLoc, FD, OCDS, GetterSel, SetterSel,
MethodImplKind);
FD.complete(Property);
};
// Parse all the comma separated declarators.
ParsingDeclSpec DS(*this);
ParseStructDeclaration(DS, ObjCPropertyCallback);
ExpectAndConsume(tok::semi, diag::err_expected_semi_decl_list);
break;
}
}
// We break out of the big loop in two cases: when we see @end or when we see
// EOF. In the former case, eat the @end. In the later case, emit an error.
if (Tok.is(tok::code_completion)) {
Actions.CodeCompleteObjCAtDirective(getCurScope());
return cutOffParsing();
} else if (Tok.isObjCAtKeyword(tok::objc_end)) {
ConsumeToken(); // the "end" identifier
} else {
Diag(Tok, diag::err_objc_missing_end)
<< FixItHint::CreateInsertion(Tok.getLocation(), "\n@end\n");
Diag(CDecl->getLocStart(), diag::note_objc_container_start)
<< (int) Actions.getObjCContainerKind();
AtEnd.setBegin(Tok.getLocation());
AtEnd.setEnd(Tok.getLocation());
}
// Insert collected methods declarations into the @interface object.
// This passes in an invalid SourceLocation for AtEndLoc when EOF is hit.
Actions.ActOnAtEnd(getCurScope(), AtEnd, allMethods, allTUVariables);
}
/// Diagnose redundant or conflicting nullability information.
static void diagnoseRedundantPropertyNullability(Parser &P,
ObjCDeclSpec &DS,
NullabilityKind nullability,
SourceLocation nullabilityLoc){
if (DS.getNullability() == nullability) {
P.Diag(nullabilityLoc, diag::warn_nullability_duplicate)
<< DiagNullabilityKind(nullability, true)
<< SourceRange(DS.getNullabilityLoc());
return;
}
P.Diag(nullabilityLoc, diag::err_nullability_conflicting)
<< DiagNullabilityKind(nullability, true)
<< DiagNullabilityKind(DS.getNullability(), true)
<< SourceRange(DS.getNullabilityLoc());
}
/// Parse property attribute declarations.
///
/// property-attr-decl: '(' property-attrlist ')'
/// property-attrlist:
/// property-attribute
/// property-attrlist ',' property-attribute
/// property-attribute:
/// getter '=' identifier
/// setter '=' identifier ':'
/// readonly
/// readwrite
/// assign
/// retain
/// copy
/// nonatomic
/// atomic
/// strong
/// weak
/// unsafe_unretained
/// nonnull
/// nullable
/// null_unspecified
/// null_resettable
/// class
///
void Parser::ParseObjCPropertyAttribute(ObjCDeclSpec &DS) {
assert(Tok.getKind() == tok::l_paren);
BalancedDelimiterTracker T(*this, tok::l_paren);
T.consumeOpen();
while (1) {
if (Tok.is(tok::code_completion)) {
Actions.CodeCompleteObjCPropertyFlags(getCurScope(), DS);
return cutOffParsing();
}
const IdentifierInfo *II = Tok.getIdentifierInfo();
// If this is not an identifier at all, bail out early.
if (!II) {
T.consumeClose();
return;
}
SourceLocation AttrName = ConsumeToken(); // consume last attribute name
if (II->isStr("readonly"))
DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_readonly);
else if (II->isStr("assign"))
DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_assign);
else if (II->isStr("unsafe_unretained"))
DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_unsafe_unretained);
else if (II->isStr("readwrite"))
DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_readwrite);
else if (II->isStr("retain"))
DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_retain);
else if (II->isStr("strong"))
DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_strong);
else if (II->isStr("copy"))
DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_copy);
else if (II->isStr("nonatomic"))
DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_nonatomic);
else if (II->isStr("atomic"))
DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_atomic);
else if (II->isStr("weak"))
DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_weak);
else if (II->isStr("getter") || II->isStr("setter")) {
bool IsSetter = II->getNameStart()[0] == 's';
// getter/setter require extra treatment.
unsigned DiagID = IsSetter ? diag::err_objc_expected_equal_for_setter :
diag::err_objc_expected_equal_for_getter;
if (ExpectAndConsume(tok::equal, DiagID)) {
SkipUntil(tok::r_paren, StopAtSemi);
return;
}
if (Tok.is(tok::code_completion)) {
if (IsSetter)
Actions.CodeCompleteObjCPropertySetter(getCurScope());
else
Actions.CodeCompleteObjCPropertyGetter(getCurScope());
return cutOffParsing();
}
SourceLocation SelLoc;
IdentifierInfo *SelIdent = ParseObjCSelectorPiece(SelLoc);
if (!SelIdent) {
Diag(Tok, diag::err_objc_expected_selector_for_getter_setter)
<< IsSetter;
SkipUntil(tok::r_paren, StopAtSemi);
return;
}
if (IsSetter) {
DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_setter);
DS.setSetterName(SelIdent, SelLoc);
if (ExpectAndConsume(tok::colon,
diag::err_expected_colon_after_setter_name)) {
SkipUntil(tok::r_paren, StopAtSemi);
return;
}
} else {
DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_getter);
DS.setGetterName(SelIdent, SelLoc);
}
} else if (II->isStr("nonnull")) {
if (DS.getPropertyAttributes() & ObjCDeclSpec::DQ_PR_nullability)
diagnoseRedundantPropertyNullability(*this, DS,
NullabilityKind::NonNull,
Tok.getLocation());
DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_nullability);
DS.setNullability(Tok.getLocation(), NullabilityKind::NonNull);
} else if (II->isStr("nullable")) {
if (DS.getPropertyAttributes() & ObjCDeclSpec::DQ_PR_nullability)
diagnoseRedundantPropertyNullability(*this, DS,
NullabilityKind::Nullable,
Tok.getLocation());
DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_nullability);
DS.setNullability(Tok.getLocation(), NullabilityKind::Nullable);
} else if (II->isStr("null_unspecified")) {
if (DS.getPropertyAttributes() & ObjCDeclSpec::DQ_PR_nullability)
diagnoseRedundantPropertyNullability(*this, DS,
NullabilityKind::Unspecified,
Tok.getLocation());
DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_nullability);
DS.setNullability(Tok.getLocation(), NullabilityKind::Unspecified);
} else if (II->isStr("null_resettable")) {
if (DS.getPropertyAttributes() & ObjCDeclSpec::DQ_PR_nullability)
diagnoseRedundantPropertyNullability(*this, DS,
NullabilityKind::Unspecified,
Tok.getLocation());
DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_nullability);
DS.setNullability(Tok.getLocation(), NullabilityKind::Unspecified);
// Also set the null_resettable bit.
DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_null_resettable);
} else if (II->isStr("class")) {
DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_class);
} else {
Diag(AttrName, diag::err_objc_expected_property_attr) << II;
SkipUntil(tok::r_paren, StopAtSemi);
return;
}
if (Tok.isNot(tok::comma))
break;
ConsumeToken();
}
T.consumeClose();
}
/// objc-method-proto:
/// objc-instance-method objc-method-decl objc-method-attributes[opt]
/// objc-class-method objc-method-decl objc-method-attributes[opt]
///
/// objc-instance-method: '-'
/// objc-class-method: '+'
///
/// objc-method-attributes: [OBJC2]
/// __attribute__((deprecated))
///
Decl *Parser::ParseObjCMethodPrototype(tok::ObjCKeywordKind MethodImplKind,
bool MethodDefinition) {
assert(Tok.isOneOf(tok::minus, tok::plus) && "expected +/-");
tok::TokenKind methodType = Tok.getKind();
SourceLocation mLoc = ConsumeToken();
Decl *MDecl = ParseObjCMethodDecl(mLoc, methodType, MethodImplKind,
MethodDefinition);
// Since this rule is used for both method declarations and definitions,
// the caller is (optionally) responsible for consuming the ';'.
return MDecl;
}
/// objc-selector:
/// identifier
/// one of
/// enum struct union if else while do for switch case default
/// break continue return goto asm sizeof typeof __alignof