-
Notifications
You must be signed in to change notification settings - Fork 10.4k
/
Copy pathParseType.cpp
1858 lines (1606 loc) · 58 KB
/
ParseType.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
//===--- ParseType.cpp - Swift Language Parser for Types ------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// Type Parsing and AST Building
//
//===----------------------------------------------------------------------===//
#include "swift/AST/ASTWalker.h"
#include "swift/AST/Attr.h"
#include "swift/AST/DiagnosticsParse.h"
#include "swift/AST/GenericParamList.h"
#include "swift/AST/SourceFile.h" // only for isMacroSignatureFile
#include "swift/AST/TypeRepr.h"
#include "swift/Basic/Assertions.h"
#include "swift/Basic/Nullability.h"
#include "swift/Parse/IDEInspectionCallbacks.h"
#include "swift/Parse/Lexer.h"
#include "swift/Parse/Parser.h"
#include "llvm/ADT/APInt.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/ADT/Twine.h"
#include "llvm/Support/Compiler.h"
#include "llvm/Support/SaveAndRestore.h"
using namespace swift;
TypeRepr *
Parser::ParsedTypeAttributeList::applyAttributesToType(Parser &p,
TypeRepr *ty) const {
// Apply those attributes that do apply.
if (!Attributes.empty()) {
ty = AttributedTypeRepr::create(p.Context, Attributes, ty);
}
// Apply 'inout', 'consuming', or 'borrowing' modifiers.
if (SpecifierLoc.isValid() && Specifier != ParamDecl::Specifier::Default) {
ty = new (p.Context) OwnershipTypeRepr(ty, Specifier, SpecifierLoc);
}
// Apply 'isolated'.
if (IsolatedLoc.isValid()) {
ty = new (p.Context) IsolatedTypeRepr(ty, IsolatedLoc);
}
if (ConstLoc.isValid()) {
ty = new (p.Context) CompileTimeLiteralTypeRepr(ty, ConstLoc);
}
if (SendingLoc.isValid()) {
ty = new (p.Context) SendingTypeRepr(ty, SendingLoc);
}
if (lifetimeEntry) {
ty = LifetimeDependentTypeRepr::create(p.Context, ty, lifetimeEntry);
}
return ty;
}
LayoutConstraint Parser::parseLayoutConstraint(Identifier LayoutConstraintID) {
LayoutConstraint layoutConstraint =
getLayoutConstraint(LayoutConstraintID, Context);
assert(layoutConstraint->isKnownLayout() &&
"Expected layout constraint definition");
if (!layoutConstraint->isTrivial())
return layoutConstraint;
SourceLoc LParenLoc;
if (!consumeIf(tok::l_paren, LParenLoc)) {
// It is a trivial without any size constraints.
return LayoutConstraint::getLayoutConstraint(LayoutConstraintKind::Trivial,
Context);
}
int size = 0;
int alignment = 0;
auto ParseTrivialLayoutConstraintBody = [&] () -> bool {
// Parse the size and alignment.
if (Tok.is(tok::integer_literal)) {
if (Tok.getText().getAsInteger(10, size)) {
diagnose(Tok.getLoc(), diag::layout_size_should_be_positive);
return true;
}
consumeToken();
if (consumeIf(tok::comma)) {
// parse alignment.
if (Tok.is(tok::integer_literal)) {
if (Tok.getText().getAsInteger(10, alignment)) {
diagnose(Tok.getLoc(), diag::layout_alignment_should_be_positive);
return true;
}
consumeToken();
} else {
diagnose(Tok.getLoc(), diag::layout_alignment_should_be_positive);
return true;
}
}
} else {
diagnose(Tok.getLoc(), diag::layout_size_should_be_positive);
return true;
}
return false;
};
if (ParseTrivialLayoutConstraintBody()) {
// There was an error during parsing.
skipUntil(tok::r_paren);
consumeIf(tok::r_paren);
return LayoutConstraint::getUnknownLayout();
}
if (!consumeIf(tok::r_paren)) {
// Expected a closing r_paren.
diagnose(Tok.getLoc(), diag::expected_rparen_layout_constraint);
consumeToken();
return LayoutConstraint::getUnknownLayout();
}
if (size < 0) {
diagnose(Tok.getLoc(), diag::layout_size_should_be_positive);
return LayoutConstraint::getUnknownLayout();
}
if (alignment < 0) {
diagnose(Tok.getLoc(), diag::layout_alignment_should_be_positive);
return LayoutConstraint::getUnknownLayout();
}
// Otherwise it is a trivial layout constraint with
// provided size and alignment.
return LayoutConstraint::getLayoutConstraint(layoutConstraint->getKind(), size,
alignment, Context);
}
/// parseTypeSimple
/// type-simple:
/// type-identifier
/// type-tuple
/// type-composition-deprecated
/// 'Any'
/// type-simple '.Type'
/// type-simple '.Protocol'
/// type-simple '?'
/// type-simple '!'
/// '~' type-simple
/// type-collection
/// type-array
/// '_'
/// integer-literal
/// '-' integer-literal
/// 'Pack' '{' (type (',' type)*)? '}' (only in SIL files)a
ParserResult<TypeRepr> Parser::parseTypeSimple(
Diag<> MessageID, ParseTypeReason reason) {
ParserResult<TypeRepr> ty;
if (isParameterSpecifier() &&
!(!Context.LangOpts.hasFeature(Feature::IsolatedConformances) &&
Tok.isContextualKeyword("isolated"))) {
// Type specifier should already be parsed before here. This only happens
// for construct like 'P1 & inout P2'.
diagnose(Tok.getLoc(), diag::attr_only_on_parameters, Tok.getRawText());
skipParameterSpecifier();
}
// Eat any '~' preceding the type.
SourceLoc tildeLoc;
if (Tok.isTilde()) {
tildeLoc = consumeToken();
}
switch (Tok.getKind()) {
case tok::kw_Self:
case tok::identifier:
// In SIL files (not just when parsing SIL types), accept the
// Pack{} syntax for spelling variadic type packs.
if (isInSILMode() && Tok.isContextualKeyword("Pack") &&
peekToken().is(tok::l_brace)) {
TokReceiver->registerTokenKindChange(Tok.getLoc(),
tok::contextual_keyword);
SourceLoc keywordLoc = consumeToken(tok::identifier);
SourceLoc lbLoc = consumeToken(tok::l_brace);
SourceLoc rbLoc;
SmallVector<TypeRepr *, 8> elements;
auto status = parseList(tok::r_brace, lbLoc, rbLoc,
/*AllowSepAfterLast=*/false,
diag::expected_rbrace_pack_type_list,
[&] () -> ParserStatus {
auto element = parseType(diag::expected_type);
if (element.hasCodeCompletion())
return makeParserCodeCompletionStatus();
if (element.isNull())
return makeParserError();
elements.push_back(element.get());
return makeParserSuccess();
});
ty = makeParserResult(
status, PackTypeRepr::create(Context, keywordLoc,
SourceRange(lbLoc, rbLoc), elements));
} else {
ty = parseTypeIdentifier(/*Base=*/nullptr);
if (auto *repr = ty.getPtrOrNull()) {
if (Tok.is(tok::code_complete) && !Tok.isAtStartOfLine()) {
if (CodeCompletionCallbacks) {
CodeCompletionCallbacks->completeTypeSimpleWithoutDot(repr);
}
ty.setHasCodeCompletionAndIsError();
consumeToken(tok::code_complete);
return ty;
}
}
}
break;
case tok::kw_Any:
ty = parseAnyType();
break;
case tok::l_paren:
ty = parseTypeTupleBody();
break;
case tok::code_complete:
if (CodeCompletionCallbacks) {
if (tildeLoc.isValid()) {
CodeCompletionCallbacks->completeTypeSimpleInverted();
} else {
CodeCompletionCallbacks->completeTypeSimpleBeginning();
}
}
return makeParserCodeCompletionResult<TypeRepr>(
ErrorTypeRepr::create(Context, consumeToken(tok::code_complete)));
case tok::l_square: {
ty = parseTypeCollection();
break;
}
case tok::kw__:
ty = makeParserResult(new (Context) PlaceholderTypeRepr(consumeToken()));
break;
case tok::kw_protocol:
if (startsWithLess(peekToken())) {
ty = parseOldStyleProtocolComposition();
break;
}
LLVM_FALLTHROUGH;
default:
{
auto diag = diagnose(Tok, MessageID);
// If the next token is closing or separating, the type was likely forgotten
if (Tok.isAny(tok::r_paren, tok::r_brace, tok::r_square, tok::arrow,
tok::equal, tok::comma, tok::semi))
diag.fixItInsert(getEndOfPreviousLoc(), " <#type#>");
}
if (Tok.isKeyword() && !Tok.isAtStartOfLine()) {
ty = makeParserErrorResult(ErrorTypeRepr::create(Context, Tok.getLoc()));
consumeToken();
return ty;
}
checkForInputIncomplete();
return nullptr;
}
// '.X', '.Type', '.Protocol', '?', '!', '[]'.
while (ty.isNonNull()) {
if (Tok.isAny(tok::period, tok::period_prefix)) {
if (peekToken().is(tok::code_complete)) {
consumeToken();
if (CodeCompletionCallbacks) {
CodeCompletionCallbacks->completeTypeSimpleWithDot(ty.get());
}
ty.setHasCodeCompletionAndIsError();
consumeToken(tok::code_complete);
break;
}
ty = parseTypeDotted(ty);
continue;
}
if (!Tok.isAtStartOfLine()) {
if (isOptionalToken(Tok)) {
ty = parseTypeOptional(ty);
continue;
}
if (isImplicitlyUnwrappedOptionalToken(Tok)) {
ty = parseTypeImplicitlyUnwrappedOptional(ty);
continue;
}
// Parse legacy array types for migration.
if (Tok.is(tok::l_square) && reason != ParseTypeReason::CustomAttribute) {
ty = parseTypeArray(ty);
continue;
}
}
if (Tok.is(tok::code_complete) && !Tok.isAtStartOfLine()) {
if (CodeCompletionCallbacks) {
CodeCompletionCallbacks->completeTypeSimpleWithoutDot(ty.get());
}
ty.setHasCodeCompletionAndIsError();
consumeToken(tok::code_complete);
}
break;
}
// Wrap in an InverseTypeRepr if needed.
if (tildeLoc) {
TypeRepr *repr = new (Context) InverseTypeRepr(tildeLoc, ty.get());
ty = makeParserResult(ty, repr);
}
return ty;
}
ParserResult<TypeRepr> Parser::parseType() {
return parseType(diag::expected_type);
}
ParserResult<TypeRepr> Parser::parseSILBoxType(GenericParamList *generics,
ParsedTypeAttributeList &attrs) {
auto LBraceLoc = consumeToken(tok::l_brace);
SmallVector<SILBoxTypeRepr::Field, 4> Fields;
if (!Tok.is(tok::r_brace)) {
for (;;) {
bool Mutable;
if (Tok.is(tok::kw_var)) {
Mutable = true;
} else if (Tok.is(tok::kw_let)) {
Mutable = false;
} else {
diagnose(Tok, diag::sil_box_expected_var_or_let);
return makeParserError();
}
SourceLoc VarOrLetLoc = consumeToken();
auto fieldTy = parseType();
if (!fieldTy.getPtrOrNull())
return makeParserError();
Fields.push_back({VarOrLetLoc, Mutable, fieldTy.get()});
if (!consumeIf(tok::comma))
break;
}
}
if (!Tok.is(tok::r_brace)) {
diagnose(Tok, diag::sil_box_expected_r_brace);
return makeParserError();
}
auto RBraceLoc = consumeToken(tok::r_brace);
SourceLoc LAngleLoc, RAngleLoc;
SmallVector<TypeRepr*, 4> Args;
if (startsWithLess(Tok)) {
LAngleLoc = consumeStartingLess();
for (;;) {
auto argTy = parseType();
if (!argTy.getPtrOrNull())
return makeParserError();
Args.push_back(argTy.get());
if (!consumeIf(tok::comma))
break;
}
if (!startsWithGreater(Tok)) {
diagnose(Tok, diag::sil_box_expected_r_angle);
return makeParserError();
}
RAngleLoc = consumeStartingGreater();
}
auto repr = SILBoxTypeRepr::create(Context, generics,
LBraceLoc, Fields, RBraceLoc,
LAngleLoc, Args, RAngleLoc);
attrs.Specifier = ParamDecl::Specifier::LegacyOwned;
return makeParserResult(attrs.applyAttributesToType(*this, repr));
}
/// parseTypeScalar
/// type-scalar:
/// attribute-list type-composition
/// attribute-list type-function
///
/// type-function:
/// type-composition 'async'? 'throws'? '->' type-scalar
///
ParserResult<TypeRepr> Parser::parseTypeScalar(
Diag<> MessageID, ParseTypeReason reason) {
// Start a context for creating type syntax.
ParserStatus status;
// Parse attributes.
ParsedTypeAttributeList parsedAttributeList(reason);
status |= parsedAttributeList.parse(*this);
// If we have a completion, create an ErrorType.
if (status.hasCodeCompletion()) {
auto *ET = ErrorTypeRepr::create(Context, PreviousLoc);
return makeParserCodeCompletionResult<TypeRepr>(ET);
}
// "nonisolated" for attribute lists.
if (reason == ParseTypeReason::InheritanceClause &&
Tok.isContextualKeyword("nonisolated")) {
SourceLoc nonisolatedLoc = consumeToken();
parsedAttributeList.Attributes.push_back(
TypeAttribute::createSimple(Context, TypeAttrKind::Nonisolated,
SourceLoc(), nonisolatedLoc));
}
// Parse generic parameters in SIL mode.
GenericParamList *generics = nullptr;
SourceLoc substitutedLoc;
GenericParamList *patternGenerics = nullptr;
if (isInSILMode()) {
generics = maybeParseGenericParams().getPtrOrNull();
if (Tok.is(tok::at_sign) && peekToken().getText() == "substituted") {
consumeToken(tok::at_sign);
substitutedLoc = consumeToken(tok::identifier);
patternGenerics = maybeParseGenericParams().getPtrOrNull();
if (!patternGenerics) {
diagnose(Tok.getLoc(), diag::sil_function_subst_expected_generics);
}
}
}
// In SIL mode, parse box types { ... }.
if (isInSILMode() && Tok.is(tok::l_brace)) {
if (patternGenerics) {
diagnose(Tok.getLoc(), diag::sil_function_subst_expected_function);
}
return parseSILBoxType(generics, parsedAttributeList);
}
ParserResult<TypeRepr> ty = parseTypeSimpleOrComposition(MessageID, reason);
status |= ParserStatus(ty);
if (ty.isNull())
return status;
auto tyR = ty.get();
// Parse effects specifiers.
// Don't consume them, if there's no following '->', so we can emit a more
// useful diagnostic when parsing a function decl.
SourceLoc asyncLoc;
SourceLoc throwsLoc;
TypeRepr *thrownTy = nullptr;
if (isAtFunctionTypeArrow()) {
status |= parseEffectsSpecifiers(SourceLoc(),
asyncLoc, /*reasync=*/nullptr,
throwsLoc, /*rethrows=*/nullptr,
thrownTy);
}
// Handle type-function if we have an arrow.
if (Tok.is(tok::arrow)) {
SourceLoc arrowLoc = consumeToken();
// Handle async/throws in the wrong place.
parseEffectsSpecifiers(arrowLoc,
asyncLoc, /*reasync=*/nullptr,
throwsLoc, /*rethrows=*/nullptr,
thrownTy);
ParserResult<TypeRepr> SecondHalf =
parseTypeScalar(diag::expected_type_function_result,
ParseTypeReason::Unspecified);
status |= SecondHalf;
if (SecondHalf.isNull()) {
status.setIsParseError();
return status;
}
TupleTypeRepr *argsTyR = nullptr;
if (auto *TTArgs = dyn_cast<TupleTypeRepr>(tyR)) {
argsTyR = TTArgs;
} else if (tyR->isSimpleUnqualifiedIdentifier(Context.Id_Void)) {
diagnose(tyR->getStartLoc(), diag::function_type_no_parens)
.fixItReplace(tyR->getStartLoc(), "()");
argsTyR = TupleTypeRepr::createEmpty(Context, tyR->getSourceRange());
} else {
diagnose(tyR->getStartLoc(), diag::function_type_no_parens)
.highlight(tyR->getSourceRange())
.fixItInsert(tyR->getStartLoc(), "(")
.fixItInsertAfter(tyR->getEndLoc(), ")");
argsTyR = TupleTypeRepr::create(Context, {tyR}, tyR->getSourceRange());
}
// Parse substitutions for substituted SIL types.
MutableArrayRef<TypeRepr *> invocationSubsTypes;
MutableArrayRef<TypeRepr *> patternSubsTypes;
if (isInSILMode()) {
auto parseSubstitutions =
[&](MutableArrayRef<TypeRepr *> &subs) -> std::optional<bool> {
if (!consumeIf(tok::kw_for))
return std::nullopt;
if (!startsWithLess(Tok)) {
diagnose(Tok, diag::sil_function_subst_expected_l_angle);
return false;
}
consumeStartingLess();
SmallVector<TypeRepr*, 4> SubsTypesVec;
for (;;) {
auto argTy = parseType();
if (!argTy.getPtrOrNull())
return false;
SubsTypesVec.push_back(argTy.get());
if (!consumeIf(tok::comma))
break;
}
if (!startsWithGreater(Tok)) {
diagnose(Tok, diag::sil_function_subst_expected_r_angle);
return false;
}
consumeStartingGreater();
subs = Context.AllocateCopy(SubsTypesVec);
return true;
};
// Parse pattern substitutions. These must exist if we had pattern
// generics above.
if (patternGenerics) {
auto result = parseSubstitutions(patternSubsTypes);
if (!result || patternSubsTypes.empty()) {
diagnose(Tok, diag::sil_function_subst_expected_subs);
patternGenerics = nullptr;
} else if (!*result) {
return makeParserError();
}
}
if (generics) {
if (auto result = parseSubstitutions(invocationSubsTypes))
if (!*result) return makeParserError();
}
if (Tok.is(tok::kw_for)) {
diagnose(Tok, diag::sil_function_subs_without_generics);
return makeParserError();
}
}
tyR = new (Context) FunctionTypeRepr(generics, argsTyR, asyncLoc, throwsLoc,
thrownTy, arrowLoc, SecondHalf.get(),
patternGenerics, patternSubsTypes,
invocationSubsTypes);
} else if (auto firstGenerics = generics ? generics : patternGenerics) {
// Only function types may be generic.
auto brackets = firstGenerics->getSourceRange();
diagnose(brackets.Start, diag::generic_non_function);
// Forget any generic parameters we saw in the type.
class EraseTypeParamWalker : public ASTWalker {
public:
MacroWalking getMacroWalkingBehavior() const override {
return MacroWalking::Arguments;
}
PreWalkAction walkToTypeReprPre(TypeRepr *T) override {
// Only unqualified identifiers can reference generic parameters.
auto *unqualIdentTR = dyn_cast<UnqualifiedIdentTypeRepr>(T);
if (unqualIdentTR && !unqualIdentTR->hasGenericArgList()) {
if (auto *genericParam = dyn_cast_or_null<GenericTypeParamDecl>(
unqualIdentTR->getBoundDecl())) {
unqualIdentTR->overwriteNameRef(genericParam->createNameRef());
}
}
return Action::Continue();
}
} walker;
if (tyR)
tyR->walk(walker);
}
return makeParserResult(
status, parsedAttributeList.applyAttributesToType(*this, tyR));
}
/// parseType
/// type:
/// type-scalar
/// pack-expansion-type
///
/// pack-expansion-type:
/// type-scalar '...'
///
ParserResult<TypeRepr> Parser::parseType(Diag<> MessageID,
ParseTypeReason reason) {
ParserResult<TypeRepr> ty;
// Parse pack expansion 'repeat T'
if (Tok.is(tok::kw_repeat)) {
SourceLoc repeatLoc = consumeToken(tok::kw_repeat);
auto ty = parseTypeScalar(MessageID, reason);
if (ty.isNull())
return ty;
return makeParserResult(ty,
new (Context) PackExpansionTypeRepr(repeatLoc, ty.get()));
} else if (Tok.is(tok::code_complete)) {
if (CodeCompletionCallbacks) {
CodeCompletionCallbacks->completeTypeBeginning();
}
return makeParserCodeCompletionResult<TypeRepr>(
ErrorTypeRepr::create(Context, consumeToken(tok::code_complete)));
}
ty = parseTypeScalar(MessageID, reason);
if (ty.isNull())
return ty;
// Parse vararg type 'T...'.
if (Tok.isEllipsis()) {
Tok.setKind(tok::ellipsis);
SourceLoc ellipsisLoc = consumeToken();
ty = makeParserResult(ty,
new (Context) VarargTypeRepr(ty.get(), ellipsisLoc));
}
return ty;
}
ParserResult<TypeRepr> Parser::parseTypeWithOpaqueParams(Diag<> MessageID) {
GenericParamList *genericParams = nullptr;
if (Context.LangOpts.hasFeature(Feature::NamedOpaqueTypes)) {
auto result = maybeParseGenericParams();
genericParams = result.getPtrOrNull();
if (result.hasCodeCompletion())
return makeParserCodeCompletionStatus();
}
auto typeResult = parseType(MessageID);
if (auto type = typeResult.getPtrOrNull()) {
return makeParserResult(
ParserStatus(typeResult),
genericParams ? new (Context)
NamedOpaqueReturnTypeRepr(type, genericParams)
: type);
} else {
return typeResult;
}
}
ParserResult<TypeRepr> Parser::parseDeclResultType(Diag<> MessageID) {
auto codeCompleteResult = [&]() {
// Synthesize an ErrorTypeRepr here to ensure we extend the result type of
// a decl up to the code completion token, allowing the ASTScope to cover
// it.
return makeParserCodeCompletionResult(
ErrorTypeRepr::create(Context, getTypeErrorLoc()));
};
if (Tok.is(tok::code_complete)) {
if (CodeCompletionCallbacks) {
CodeCompletionCallbacks->completeTypeDeclResultBeginning();
}
consumeToken(tok::code_complete);
return codeCompleteResult();
}
auto result = parseTypeWithOpaqueParams(MessageID);
if (result.hasCodeCompletion())
return codeCompleteResult();
if (!result.isParseErrorOrHasCompletion()) {
if (Tok.is(tok::r_square)) {
auto diag = diagnose(Tok, diag::extra_rbracket);
diag.fixItInsert(result.get()->getStartLoc(), getTokenText(tok::l_square));
consumeToken();
return makeParserErrorResult(ErrorTypeRepr::create(Context,
getTypeErrorLoc()));
}
if (Tok.is(tok::colon)) {
auto colonTok = consumeToken();
auto secondType = parseType(diag::expected_dictionary_value_type);
auto diag = diagnose(colonTok, diag::extra_colon);
diag.fixItInsert(result.get()->getStartLoc(), getTokenText(tok::l_square));
if (!secondType.isParseErrorOrHasCompletion()) {
if (Tok.is(tok::r_square)) {
consumeToken();
} else {
diag.fixItInsertAfter(secondType.get()->getEndLoc(), getTokenText(tok::r_square));
}
}
return makeParserErrorResult(ErrorTypeRepr::create(Context,
getTypeErrorLoc()));
}
}
return result;
}
SourceLoc Parser::getTypeErrorLoc() const {
// Use the same location as a missing close brace, etc.
return getErrorOrMissingLoc();
}
ParserStatus Parser::parseGenericArguments(SmallVectorImpl<TypeRepr *> &Args,
SourceLoc &LAngleLoc,
SourceLoc &RAngleLoc) {
// Parse the opening '<'.
assert(startsWithLess(Tok) && "Generic parameter list must start with '<'");
LAngleLoc = consumeStartingLess();
// Allow an empty generic parameter list, since this is meaningful with
// variadic generic types.
if (!startsWithGreater(Tok)) {
while (true) {
// Note: This can be a value type, e.g. 'InlineArray<3, Int>'.
ParserResult<TypeRepr> Ty = parseTypeOrValue(diag::expected_type);
if (Ty.isNull() || Ty.hasCodeCompletion()) {
// Skip until we hit the '>'.
RAngleLoc = skipUntilGreaterInTypeList();
return ParserStatus(Ty);
}
Args.push_back(Ty.get());
// Parse the comma, if the list continues.
if (!consumeIf(tok::comma))
break;
}
}
if (!startsWithGreater(Tok)) {
checkForInputIncomplete();
diagnose(Tok, diag::expected_rangle_generic_arg_list);
diagnose(LAngleLoc, diag::opening_angle);
// Skip until we hit the '>'.
RAngleLoc = skipUntilGreaterInTypeList();
return makeParserError();
} else {
RAngleLoc = consumeStartingGreater();
}
return makeParserSuccess();
}
ParserResult<TypeRepr> Parser::parseQualifiedDeclNameBaseType() {
if (!canParseBaseTypeForQualifiedDeclName())
return makeParserError();
if (Tok.isNot(tok::identifier) && Tok.isNot(tok::kw_Self)) {
// is this the 'Any' type
if (Tok.is(tok::kw_Any)) {
return parseAnyType();
} else if (Tok.is(tok::code_complete)) {
if (CodeCompletionCallbacks) {
CodeCompletionCallbacks->completeTypeSimpleBeginning();
}
// Eat the code completion token because we handled it.
consumeToken(tok::code_complete);
return makeParserCodeCompletionResult<DeclRefTypeRepr>();
}
diagnose(Tok, diag::expected_identifier_for_type);
// If there is a keyword at the start of a new line, we won't want to
// skip it as a recovery but rather keep it.
if (Tok.isKeyword() && !Tok.isAtStartOfLine())
consumeToken();
return nullptr;
}
ParserStatus Status;
DeclRefTypeRepr *Result = nullptr;
SourceLoc EndLoc;
while (true) {
auto PartialResult = parseTypeIdentifier(/*Base=*/Result);
if (PartialResult.isParseErrorOrHasCompletion())
return PartialResult;
Result = PartialResult.get();
// Treat 'Foo.<anything>' as an attempt to write a dotted type
// unless <anything> is 'Type'.
if ((Tok.is(tok::period) || Tok.is(tok::period_prefix))) {
if (peekToken().is(tok::code_complete)) {
Status.setHasCodeCompletionAndIsError();
break;
}
if (peekToken().isContextualKeyword("Type") ||
peekToken().isContextualKeyword("Protocol"))
break;
// Break before parsing the period before the final declaration
// name component.
{
// If qualified name base type cannot be parsed from the current
// point (i.e. the next type identifier is not followed by a '.'),
// then the next identifier is the final declaration name component.
BacktrackingScope backtrack(*this);
consumeStartingCharacterOfCurrentToken(tok::period);
if (!canParseBaseTypeForQualifiedDeclName())
break;
}
// Consume the period.
consumeToken();
continue;
}
if (Tok.is(tok::code_complete) && !Tok.isAtStartOfLine())
Status.setHasCodeCompletionAndIsError();
break;
}
if (Status.hasCodeCompletion()) {
if (Tok.isNot(tok::code_complete)) {
// We have a dot.
consumeToken();
if (CodeCompletionCallbacks) {
CodeCompletionCallbacks->completeTypeSimpleWithDot(Result);
}
} else {
if (CodeCompletionCallbacks) {
CodeCompletionCallbacks->completeTypeSimpleWithoutDot(Result);
}
}
// Eat the code completion token because we handled it.
consumeToken(tok::code_complete);
}
return makeParserResult(Status, Result);
}
ParserResult<DeclRefTypeRepr> Parser::parseTypeIdentifier(TypeRepr *Base) {
// FIXME: We should parse e.g. 'X.var'. Almost any keyword is a valid member
// component.
DeclNameLoc Loc;
DeclNameRef Name =
parseDeclNameRef(Loc, diag::expected_identifier_in_dotted_type,
DeclNameFlag::AllowLowercaseAndUppercaseSelf);
if (!Name)
return makeParserError();
ParserStatus Status;
DeclRefTypeRepr *Result;
if (startsWithLess(Tok)) {
SourceLoc LAngle, RAngle;
SmallVector<TypeRepr *, 8> GenericArgs;
auto ArgsStatus = parseGenericArguments(GenericArgs, LAngle, RAngle);
if (ArgsStatus.isErrorOrHasCompletion())
return ArgsStatus;
Result = DeclRefTypeRepr::create(Context, Base, Loc, Name, GenericArgs,
SourceRange(LAngle, RAngle));
} else {
Result = DeclRefTypeRepr::create(Context, Base, Loc, Name);
}
return makeParserResult(Result);
}
ParserResult<TypeRepr> Parser::parseTypeDotted(ParserResult<TypeRepr> Base) {
assert(Base.isNonNull());
assert(Tok.isAny(tok::period, tok::period_prefix));
TypeRepr *Result = Base.get();
while (Tok.isAny(tok::period, tok::period_prefix)) {
if (peekToken().is(tok::code_complete)) {
// Code completion for "type-simple '.'" is handled in 'parseTypeSimple'.
break;
}
// Consume the period.
consumeToken();
if (Tok.isContextualKeyword("Type") ||
Tok.isContextualKeyword("Protocol")) {
if (Tok.getRawText() == "Type") {
Result = new (Context)
MetatypeTypeRepr(Result, consumeToken(tok::identifier));
} else {
Result = new (Context)
ProtocolTypeRepr(Result, consumeToken(tok::identifier));
}
continue;
}
auto PartialResult = parseTypeIdentifier(/*Base=*/Result);
if (PartialResult.isParseErrorOrHasCompletion())
return PartialResult | ParserStatus(Base);
Result = PartialResult.get();
}
return makeParserResult(Base, Result);
}
/// parseTypeSimpleOrComposition
///
/// type-composition:
/// 'some'? type-simple
/// 'any'? type-simple
/// type-composition '&' type-simple
ParserResult<TypeRepr>
Parser::parseTypeSimpleOrComposition(Diag<> MessageID, ParseTypeReason reason) {
// Check for the contextual keyword modifiers on types.
// These are only semantically allowed in certain contexts, but we parse it
// generally for diagnostics and recovery.
SourceLoc opaqueLoc;
SourceLoc anyLoc;
if (Tok.isContextualKeyword("some")) {
// Treat some as a keyword.
TokReceiver->registerTokenKindChange(Tok.getLoc(), tok::contextual_keyword);
opaqueLoc = consumeToken();
} else if (Tok.isContextualKeyword("any")) {
// Treat any as a keyword.
TokReceiver->registerTokenKindChange(Tok.getLoc(), tok::contextual_keyword);
anyLoc = consumeToken();
} else if (Tok.isContextualKeyword("each")) {
// Treat 'each' as a keyword.
TokReceiver->registerTokenKindChange(Tok.getLoc(), tok::contextual_keyword);
SourceLoc eachLoc = consumeToken();
ParserResult<TypeRepr> packElt = parseTypeSimple(MessageID, reason);
if (packElt.isNull())
return packElt;
auto *typeRepr = new (Context) PackElementTypeRepr(eachLoc, packElt.get());
return makeParserResult(ParserStatus(packElt), typeRepr);
} else if (Tok.is(tok::code_complete)) {
if (CodeCompletionCallbacks) {
CodeCompletionCallbacks->completeTypeSimpleOrComposition();
}
return makeParserCodeCompletionResult<TypeRepr>(
ErrorTypeRepr::create(Context, consumeToken(tok::code_complete)));
}
auto applyOpaque = [&](TypeRepr *type) -> TypeRepr * {
if (opaqueLoc.isValid() &&
(anyLoc.isInvalid() || SourceMgr.isBeforeInBuffer(opaqueLoc, anyLoc))) {
type = new (Context) OpaqueReturnTypeRepr(opaqueLoc, type);
} else if (anyLoc.isValid()) {
type = new (Context) ExistentialTypeRepr(anyLoc, type);
}
return type;
};
// Parse the first type
ParserResult<TypeRepr> FirstType = parseTypeSimple(MessageID, reason);
if (FirstType.isNull())
return FirstType;
if (!Tok.isContextualPunctuator("&")) {
return makeParserResult(ParserStatus(FirstType),
applyOpaque(FirstType.get()));
}
SmallVector<TypeRepr *, 4> Types;
ParserStatus Status(FirstType);
SourceLoc FirstTypeLoc = FirstType.get()->getStartLoc();
SourceLoc FirstAmpersandLoc = Tok.getLoc();
auto addType = [&](TypeRepr *T) {
if (!T) return;
if (auto Comp = dyn_cast<CompositionTypeRepr>(T)) {
// Accept protocol<P1, P2> & P3; explode it.
auto TyRs = Comp->getTypes();
if (!TyRs.empty()) // If empty, is 'Any'; ignore.
Types.append(TyRs.begin(), TyRs.end());
return;
}
Types.push_back(T);
};
addType(FirstType.get());
assert(Tok.isContextualPunctuator("&"));
do {
consumeToken(); // consume '&'
// Diagnose invalid `some` or `any` after an ampersand.
if (Tok.isContextualKeyword("some") ||
Tok.isContextualKeyword("any")) {
auto keyword = Tok.getText();
auto badLoc = consumeToken();