forked from swiftlang/swift
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ParseType.cpp
1376 lines (1206 loc) · 43 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/Parse/Parser.h"
#include "swift/AST/Attr.h"
#include "swift/AST/TypeLoc.h"
#include "swift/Parse/Lexer.h"
#include "swift/Parse/CodeCompletionCallbacks.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::applyAttributeToType(TypeRepr *ty,
const TypeAttributes &attrs,
VarDecl::Specifier specifier,
SourceLoc specifierLoc) {
// Apply those attributes that do apply.
if (!attrs.empty())
ty = new (Context) AttributedTypeRepr(attrs, ty);
// Apply 'inout' or '__shared'
if (specifierLoc.isValid()) {
if (auto *fnTR = dyn_cast<FunctionTypeRepr>(ty)) {
// If the input to the function isn't parenthesized, apply the inout
// to the first (only) parameter, as we would in Swift 2. (This
// syntax is deprecated in Swift 3.)
TypeRepr *argsTR = fnTR->getArgsTypeRepr();
if (!isa<TupleTypeRepr>(argsTR)) {
auto *newArgsTR =
new (Context) InOutTypeRepr(argsTR, specifierLoc);
auto *newTR =
new (Context) FunctionTypeRepr(fnTR->getGenericParams(),
newArgsTR,
fnTR->getThrowsLoc(),
fnTR->getArrowLoc(),
fnTR->getResultTypeRepr());
newTR->setGenericEnvironment(fnTR->getGenericEnvironment());
return newTR;
}
}
switch (specifier) {
case VarDecl::Specifier::Owned:
break;
case VarDecl::Specifier::InOut:
ty = new (Context) InOutTypeRepr(ty, specifierLoc);
break;
case VarDecl::Specifier::Shared:
ty = new (Context) SharedTypeRepr(ty, specifierLoc);
break;
case VarDecl::Specifier::Var:
llvm_unreachable("cannot have var as specifier");
break;
}
}
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);
}
ParserResult<TypeRepr> Parser::parseTypeSimple() {
return parseTypeSimple(diag::expected_type);
}
/// parseTypeSimple
/// type-simple:
/// type-identifier
/// type-tuple
/// type-composition-deprecated
/// 'Any'
/// type-simple '.Type'
/// type-simple '.Protocol'
/// type-simple '?'
/// type-simple '!'
/// type-collection
/// type-array
ParserResult<TypeRepr> Parser::parseTypeSimple(Diag<> MessageID,
bool HandleCodeCompletion) {
ParserResult<TypeRepr> ty;
// If this is an "inout" marker for an identifier type, consume the inout.
SourceLoc SpecifierLoc;
VarDecl::Specifier TypeSpecifier;
if (Tok.is(tok::kw_inout)) {
SpecifierLoc = consumeToken();
TypeSpecifier = VarDecl::Specifier::InOut;
} else if (Tok.is(tok::kw___shared)) {
SpecifierLoc = consumeToken();
TypeSpecifier = VarDecl::Specifier::Shared;
} else if (Tok.is(tok::kw___owned)) {
SpecifierLoc = consumeToken();
TypeSpecifier = VarDecl::Specifier::Owned;
}
switch (Tok.getKind()) {
case tok::kw_Self:
case tok::kw_Any:
case tok::identifier:
ty = parseTypeIdentifier();
break;
case tok::l_paren:
ty = parseTypeTupleBody();
break;
case tok::code_complete:
if (!HandleCodeCompletion)
break;
if (CodeCompletion)
CodeCompletion->completeTypeSimpleBeginning();
// Eat the code completion token because we handled it.
consumeToken(tok::code_complete);
return makeParserCodeCompletionResult<TypeRepr>();
case tok::kw_super:
case tok::kw_self:
// These keywords don't start a decl or a statement, and thus should be
// safe to skip over.
diagnose(Tok, MessageID);
ty = makeParserErrorResult(new (Context) ErrorTypeRepr(Tok.getLoc()));
consumeToken();
// FIXME: we could try to continue to parse.
return ty;
case tok::l_square:
ty = parseTypeCollection();
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(new (Context) ErrorTypeRepr(Tok.getLoc()));
consumeToken();
return ty;
}
checkForInputIncomplete();
return nullptr;
}
// '.Type', '.Protocol', '?', '!', and '[]' still leave us with type-simple.
while (ty.isNonNull()) {
if ((Tok.is(tok::period) || Tok.is(tok::period_prefix))) {
if (peekToken().isContextualKeyword("Type")) {
consumeToken();
SourceLoc metatypeLoc = consumeToken(tok::identifier);
ty = makeParserResult(ty,
new (Context) MetatypeTypeRepr(ty.get(), metatypeLoc));
continue;
}
if (peekToken().isContextualKeyword("Protocol")) {
consumeToken();
SourceLoc protocolLoc = consumeToken(tok::identifier);
ty = makeParserResult(ty,
new (Context) ProtocolTypeRepr(ty.get(), protocolLoc));
continue;
}
}
if (!Tok.isAtStartOfLine()) {
if (isOptionalToken(Tok)) {
ty = parseTypeOptional(ty.get());
continue;
}
if (isImplicitlyUnwrappedOptionalToken(Tok)) {
ty = parseTypeImplicitlyUnwrappedOptional(ty.get());
continue;
}
// Parse legacy array types for migration.
if (Tok.is(tok::l_square)) {
ty = parseTypeArray(ty.get());
continue;
}
}
break;
}
// If we parsed any specifier, prepend it.
if (SpecifierLoc.isValid() && ty.isNonNull()) {
TypeRepr *repr = ty.get();
switch (TypeSpecifier) {
case VarDecl::Specifier::InOut:
repr = new (Context) InOutTypeRepr(repr, SpecifierLoc);
break;
case VarDecl::Specifier::Shared:
repr = new (Context) SharedTypeRepr(repr, SpecifierLoc);
break;
case VarDecl::Specifier::Owned:
break;
case VarDecl::Specifier::Var:
llvm_unreachable("tried to create var type specifier?");
}
ty = makeParserResult(repr);
}
return ty;
}
ParserResult<TypeRepr> Parser::parseType() {
return parseType(diag::expected_type);
}
ParserResult<TypeRepr> Parser::parseSILBoxType(GenericParamList *generics,
const TypeAttributes &attrs,
Optional<Scope> &GenericsScope) {
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))
continue;
break;
}
}
if (!Tok.is(tok::r_brace)) {
diagnose(Tok, diag::sil_box_expected_r_brace);
return makeParserError();
}
auto RBraceLoc = consumeToken(tok::r_brace);
// The generic arguments are taken from the enclosing scope. Pop the
// box layout's scope now.
GenericsScope.reset();
SourceLoc LAngleLoc, RAngleLoc;
SmallVector<TypeRepr*, 4> Args;
if (Tok.isContextualPunctuator("<")) {
LAngleLoc = consumeToken();
for (;;) {
auto argTy = parseType();
if (!argTy.getPtrOrNull())
return makeParserError();
Args.push_back(argTy.get());
if (consumeIf(tok::comma))
continue;
break;
}
if (!Tok.isContextualPunctuator(">")) {
diagnose(Tok, diag::sil_box_expected_r_angle);
return makeParserError();
}
RAngleLoc = consumeToken();
}
auto repr = SILBoxTypeRepr::create(Context, generics,
LBraceLoc, Fields, RBraceLoc,
LAngleLoc, Args, RAngleLoc);
return makeParserResult(applyAttributeToType(repr, attrs,
VarDecl::Specifier::Owned,
SourceLoc()));
}
/// parseType
/// type:
/// attribute-list type-composition
/// attribute-list type-function
///
/// type-function:
/// type-composition '->' type
/// type-composition 'throws' '->' type
///
ParserResult<TypeRepr> Parser::parseType(Diag<> MessageID,
bool HandleCodeCompletion,
bool IsSILFuncDecl) {
// Parse attributes.
VarDecl::Specifier specifier;
SourceLoc specifierLoc;
TypeAttributes attrs;
parseTypeAttributeList(specifier, specifierLoc, attrs);
Optional<Scope> GenericsScope;
// Parse generic parameters in SIL mode.
GenericParamList *generics = nullptr;
if (isInSILMode()) {
// If this is part of a sil function decl, generic parameters are visible in
// the function body; otherwise, they are visible when parsing the type.
if (!IsSILFuncDecl)
GenericsScope.emplace(this, ScopeKind::Generics);
generics = maybeParseGenericParams().getPtrOrNull();
}
// In SIL mode, parse box types { ... }.
if (isInSILMode() && Tok.is(tok::l_brace)) {
return parseSILBoxType(generics, attrs, GenericsScope);
}
ParserResult<TypeRepr> ty =
parseTypeSimpleOrComposition(MessageID, HandleCodeCompletion);
if (ty.hasCodeCompletion())
return makeParserCodeCompletionResult<TypeRepr>();
if (ty.isNull())
return nullptr;
auto tyR = ty.get();
// Parse a throws specifier.
// Don't consume 'throws', if the next token is not '->', so we can emit a
// more useful diagnostic when parsing a function decl.
SourceLoc throwsLoc;
if (Tok.isAny(tok::kw_throws, tok::kw_rethrows, tok::kw_throw) &&
peekToken().is(tok::arrow)) {
if (Tok.isNot(tok::kw_throws)) {
// 'rethrows' is only allowed on function declarations for now.
// 'throw' is probably a typo for 'throws'.
Diag<> DiagID = Tok.is(tok::kw_rethrows) ?
diag::rethrowing_function_type : diag::throw_in_function_type;
diagnose(Tok.getLoc(), DiagID)
.fixItReplace(Tok.getLoc(), "throws");
}
throwsLoc = consumeToken();
}
if (Tok.is(tok::arrow)) {
// Handle type-function if we have an arrow.
SourceLoc arrowLoc = consumeToken();
ParserResult<TypeRepr> SecondHalf =
parseType(diag::expected_type_function_result);
if (SecondHalf.hasCodeCompletion())
return makeParserCodeCompletionResult<TypeRepr>();
if (SecondHalf.isNull())
return nullptr;
tyR = new (Context) FunctionTypeRepr(generics, tyR, throwsLoc, arrowLoc,
SecondHalf.get());
} else if (generics) {
// Only function types may be generic.
auto brackets = generics->getSourceRange();
diagnose(brackets.Start, diag::generic_non_function);
GenericsScope.reset();
// Forget any generic parameters we saw in the type.
class EraseTypeParamWalker : public ASTWalker {
public:
bool walkToTypeReprPre(TypeRepr *T) override {
if (auto ident = dyn_cast<ComponentIdentTypeRepr>(T)) {
if (auto decl = ident->getBoundDecl()) {
if (auto genericParam = dyn_cast<GenericTypeParamDecl>(decl))
ident->overwriteIdentifier(genericParam->getName());
}
}
return true;
}
} walker;
if (tyR)
tyR->walk(walker);
}
return makeParserResult(applyAttributeToType(tyR, attrs, specifier,
specifierLoc));
}
bool Parser::parseGenericArguments(SmallVectorImpl<TypeRepr*> &Args,
SourceLoc &LAngleLoc,
SourceLoc &RAngleLoc) {
// Parse the opening '<'.
assert(startsWithLess(Tok) && "Generic parameter list must start with '<'");
LAngleLoc = consumeStartingLess();
do {
ParserResult<TypeRepr> Ty = parseType(diag::expected_type);
if (Ty.isNull() || Ty.hasCodeCompletion()) {
// Skip until we hit the '>'.
RAngleLoc = skipUntilGreaterInTypeList();
return true;
}
Args.push_back(Ty.get());
// Parse the comma, if the list continues.
} while (consumeIf(tok::comma));
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 true;
} else {
RAngleLoc = consumeStartingGreater();
}
return false;
}
/// parseTypeIdentifier
///
/// type-identifier:
/// identifier generic-args? ('.' identifier generic-args?)*
///
ParserResult<TypeRepr> Parser::parseTypeIdentifier() {
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 (CodeCompletion)
CodeCompletion->completeTypeSimpleBeginning();
// Eat the code completion token because we handled it.
consumeToken(tok::code_complete);
return makeParserCodeCompletionResult<IdentTypeRepr>();
}
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;
SmallVector<ComponentIdentTypeRepr *, 4> ComponentsR;
SourceLoc EndLoc;
while (true) {
SourceLoc Loc;
Identifier Name;
if (Tok.is(tok::kw_Self)) {
Loc = consumeIdentifier(&Name);
} else {
// FIXME: specialize diagnostic for 'Type': type cannot start with
// 'metatype'
// FIXME: offer a fixit: 'self' -> 'Self'
if (parseIdentifier(Name, Loc, diag::expected_identifier_in_dotted_type))
Status.setIsParseError();
}
if (Loc.isValid()) {
SourceLoc LAngle, RAngle;
SmallVector<TypeRepr*, 8> GenericArgs;
if (startsWithLess(Tok)) {
if (parseGenericArguments(GenericArgs, LAngle, RAngle))
return nullptr;
}
EndLoc = Loc;
ComponentIdentTypeRepr *CompT;
if (!GenericArgs.empty())
CompT = new (Context) GenericIdentTypeRepr(Loc, Name,
Context.AllocateCopy(GenericArgs),
SourceRange(LAngle, RAngle));
else
CompT = new (Context) SimpleIdentTypeRepr(Loc, Name);
ComponentsR.push_back(CompT);
}
// 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.setHasCodeCompletion();
break;
}
if (!peekToken().isContextualKeyword("Type")
&& !peekToken().isContextualKeyword("Protocol")) {
consumeToken();
continue;
}
} else if (Tok.is(tok::code_complete)) {
if (!Tok.isAtStartOfLine())
Status.setHasCodeCompletion();
break;
}
break;
}
IdentTypeRepr *ITR = nullptr;
if (!ComponentsR.empty()) {
// Lookup element #0 through our current scope chains in case it is some
// thing local (this returns null if nothing is found).
if (auto Entry = lookupInScope(ComponentsR[0]->getIdentifier()))
if (auto *TD = dyn_cast<TypeDecl>(Entry))
ComponentsR[0]->setValue(TD, nullptr);
ITR = IdentTypeRepr::create(Context, ComponentsR);
}
if (Status.hasCodeCompletion() && CodeCompletion) {
if (Tok.isNot(tok::code_complete)) {
// We have a dot.
consumeToken();
CodeCompletion->completeTypeIdentifierWithDot(ITR);
} else {
CodeCompletion->completeTypeIdentifierWithoutDot(ITR);
}
// Eat the code completion token because we handled it.
consumeToken(tok::code_complete);
}
return makeParserResult(Status, ITR);
}
ParserResult<TypeRepr> Parser::parseTypeSimpleOrComposition() {
return parseTypeSimpleOrComposition(diag::expected_identifier_for_type);
}
/// parseTypeSimpleOrComposition
///
/// type-composition:
/// type-simple
/// type-composition '&' type-simple
ParserResult<TypeRepr>
Parser::parseTypeSimpleOrComposition(Diag<> MessageID,
bool HandleCodeCompletion) {
// Parse the first type
ParserResult<TypeRepr> FirstType = parseTypeSimple(MessageID,
HandleCodeCompletion);
if (FirstType.hasCodeCompletion())
return makeParserCodeCompletionResult<TypeRepr>();
if (FirstType.isNull() || !Tok.isContextualPunctuator("&"))
return FirstType;
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());
while (Tok.isContextualPunctuator("&")) {
consumeToken(); // consume '&'
ParserResult<TypeRepr> ty =
parseTypeSimple(diag::expected_identifier_for_type, HandleCodeCompletion);
if (ty.hasCodeCompletion())
return makeParserCodeCompletionResult<TypeRepr>();
Status |= ty;
addType(ty.getPtrOrNull());
};
return makeParserResult(Status, CompositionTypeRepr::create(
Context, Types, FirstTypeLoc, {FirstAmpersandLoc, PreviousLoc}));
}
ParserResult<CompositionTypeRepr> Parser::parseAnyType() {
return makeParserResult(CompositionTypeRepr
::createEmptyComposition(Context, consumeToken(tok::kw_Any)));
}
/// parseOldStyleProtocolComposition
/// type-composition-deprecated:
/// 'protocol' '<' '>'
/// 'protocol' '<' type-composition-list-deprecated '>'
///
/// type-composition-list-deprecated:
/// type-identifier
/// type-composition-list-deprecated ',' type-identifier
ParserResult<TypeRepr> Parser::parseOldStyleProtocolComposition() {
assert(Tok.is(tok::kw_protocol) && startsWithLess(peekToken()));
SourceLoc ProtocolLoc = consumeToken();
SourceLoc LAngleLoc = consumeStartingLess();
// Parse the type-composition-list.
ParserStatus Status;
SmallVector<TypeRepr *, 4> Protocols;
bool IsEmpty = startsWithGreater(Tok);
if (!IsEmpty) {
do {
// Parse the type-identifier.
ParserResult<TypeRepr> Protocol = parseTypeIdentifier();
Status |= Protocol;
if (auto *ident =
dyn_cast_or_null<IdentTypeRepr>(Protocol.getPtrOrNull()))
Protocols.push_back(ident);
} while (consumeIf(tok::comma));
}
// Check for the terminating '>'.
SourceLoc RAngleLoc = PreviousLoc;
if (startsWithGreater(Tok)) {
RAngleLoc = consumeStartingGreater();
} else {
if (Status.isSuccess()) {
diagnose(Tok, diag::expected_rangle_protocol);
diagnose(LAngleLoc, diag::opening_angle);
Status.setIsParseError();
}
// Skip until we hit the '>'.
RAngleLoc = skipUntilGreaterInTypeList(/*protocolComposition=*/true);
}
auto composition = CompositionTypeRepr::create(
Context, Protocols, ProtocolLoc, {LAngleLoc, RAngleLoc});
if (Status.isSuccess()) {
// Only if we have complete protocol<...> construct, diagnose deprecated.
SmallString<32> replacement;
if (Protocols.empty()) {
replacement = "Any";
} else {
auto extractText = [&](TypeRepr *Ty) -> StringRef {
auto SourceRange = Ty->getSourceRange();
return SourceMgr.extractText(
Lexer::getCharSourceRangeFromSourceRange(SourceMgr, SourceRange));
};
auto Begin = Protocols.begin();
replacement += extractText(*Begin);
while (++Begin != Protocols.end()) {
replacement += " & ";
replacement += extractText(*Begin);
}
}
if (Protocols.size() > 1) {
// Need parenthesis if the next token looks like postfix TypeRepr.
// i.e. '?', '!', '.Type', '.Protocol'
bool needParen = false;
needParen |= !Tok.isAtStartOfLine() &&
(isOptionalToken(Tok) || isImplicitlyUnwrappedOptionalToken(Tok));
needParen |= Tok.isAny(tok::period, tok::period_prefix);
if (needParen) {
replacement.insert(replacement.begin(), '(');
replacement += ")";
}
}
// Copy split token after '>' to the replacement string.
// FIXME: lexer should smartly separate '>' and trailing contents like '?'.
StringRef TrailingContent = L->getTokenAt(RAngleLoc).getRange().str().
substr(1);
if (!TrailingContent.empty()) {
replacement += TrailingContent;
}
auto isThree = Context.isSwiftVersion3();
#define THREEIFY(MESSAGE) (isThree ? diag::swift3_##MESSAGE : diag::MESSAGE)
// Replace 'protocol<T1, T2>' with 'T1 & T2'
diagnose(ProtocolLoc,
IsEmpty ? THREEIFY(deprecated_any_composition) :
Protocols.size() > 1 ? THREEIFY(deprecated_protocol_composition) :
THREEIFY(deprecated_protocol_composition_single))
.highlight(composition->getSourceRange())
.fixItReplace(composition->getSourceRange(), replacement);
#undef THREEIFY
}
return makeParserResult(Status, composition);
}
/// parseTypeTupleBody
/// type-tuple:
/// '(' type-tuple-body? ')'
/// type-tuple-body:
/// type-tuple-element (',' type-tuple-element)* '...'?
/// type-tuple-element:
/// identifier ':' type
/// type
ParserResult<TupleTypeRepr> Parser::parseTypeTupleBody() {
Parser::StructureMarkerRAII ParsingTypeTuple(*this, Tok);
SourceLoc RPLoc, LPLoc = consumeToken(tok::l_paren);
SourceLoc EllipsisLoc;
unsigned EllipsisIdx;
SmallVector<TupleTypeReprElement, 8> ElementsR;
ParserStatus Status = parseList(tok::r_paren, LPLoc, RPLoc,
/*AllowSepAfterLast=*/false,
diag::expected_rparen_tuple_type_list,
[&] () -> ParserStatus {
TupleTypeReprElement element;
// If this is a deprecated use of the inout marker in an argument list,
// consume the inout.
SourceLoc SpecifierLoc;
consumeIf(tok::kw_inout, SpecifierLoc);
// If the tuple element starts with a potential argument label followed by a
// ':' or another potential argument label, then the identifier is an
// element tag, and it is followed by a type annotation.
if (Tok.canBeArgumentLabel() &&
(peekToken().is(tok::colon) || peekToken().canBeArgumentLabel())) {
// Consume the name
if (!Tok.is(tok::kw__))
element.Name = Context.getIdentifier(Tok.getText());
element.NameLoc = consumeToken();
// If there is a second name, consume it as well.
if (Tok.canBeArgumentLabel()) {
if (!Tok.is(tok::kw__))
element.SecondName = Context.getIdentifier(Tok.getText());
element.SecondNameLoc = consumeToken();
}
// Consume the ':'.
SourceLoc colonLoc;
if (Tok.is(tok::colon)) {
colonLoc = consumeToken();
} else {
diagnose(Tok, diag::expected_parameter_colon);
}
SourceLoc postColonLoc = Tok.getLoc();
// Parse the type annotation.
auto type = parseType(diag::expected_type);
if (type.hasCodeCompletion())
return makeParserCodeCompletionStatus();
if (type.isNull())
return makeParserError();
element.Type = type.get();
// Complain obsoleted 'inout' position; (inout name: Ty)
if (SpecifierLoc.isValid() && !isa<InOutTypeRepr>(element.Type))
diagnose(Tok.getLoc(), diag::inout_as_attr_disallowed, "'inout'")
.fixItRemove(SpecifierLoc)
.fixItInsert(postColonLoc, "inout ");
} else {
// Otherwise, this has to be a type.
auto type = parseType();
if (type.hasCodeCompletion())
return makeParserCodeCompletionStatus();
if (type.isNull())
return makeParserError();
element.Type = type.get();
}
// If an 'inout' marker was specified, build inout type.
// Note that we bury the inout locator within the named locator.
// This is weird but required by Sema apparently.
if (SpecifierLoc.isValid()) {
if (isa<InOutTypeRepr>(element.Type) || isa<SharedTypeRepr>(element.Type))
diagnose(Tok, diag::parameter_specifier_repeated)
.fixItRemove(SpecifierLoc);
else
element.Type = new (Context) InOutTypeRepr(element.Type, SpecifierLoc);
}
ElementsR.push_back(element);
// Parse '= expr' here so we can complain about it directly, rather
// than dying when we see it.
if (Tok.is(tok::equal)) {
SourceLoc equalLoc = consumeToken(tok::equal);
auto init = parseExpr(diag::expected_init_value);
auto inFlight = diagnose(equalLoc, diag::tuple_type_init);
if (init.isNonNull())
inFlight.fixItRemove(SourceRange(equalLoc, init.get()->getEndLoc()));
}
if (Tok.isEllipsis()) {
if (EllipsisLoc.isValid()) {
diagnose(Tok, diag::multiple_ellipsis_in_tuple)
.highlight(EllipsisLoc)
.fixItRemove(Tok.getLoc());
(void)consumeToken();
} else {
EllipsisLoc = consumeToken();
EllipsisIdx = ElementsR.size() - 1;
}
}
if (Tok.is(tok::comma)) {
element.TrailingCommaLoc = Tok.getLoc();
}
return makeParserSuccess();
});
if (EllipsisLoc.isValid() && ElementsR.empty()) {
EllipsisLoc = SourceLoc();
}
if (EllipsisLoc.isInvalid())
EllipsisIdx = ElementsR.size();
// If there were any labels, figure out which labels should go into the type
// representation.
bool isFunctionType = Tok.isAny(tok::arrow, tok::kw_throws,
tok::kw_rethrows);
for (auto &element : ElementsR) {
// True tuples have labels.
if (!isFunctionType) {
// If there were two names, complain.
if (element.NameLoc.isValid() && element.SecondNameLoc.isValid()) {
auto diag = diagnose(element.NameLoc, diag::tuple_type_multiple_labels);
if (element.Name.empty()) {
diag.fixItRemoveChars(element.NameLoc,
element.Type->getStartLoc());
} else {
diag.fixItRemove(
SourceRange(Lexer::getLocForEndOfToken(SourceMgr, element.NameLoc),
element.SecondNameLoc));
}
}
continue;
}
// If there was a first name, complain; arguments in function types are
// always unlabeled.
if (element.NameLoc.isValid() && !element.Name.empty()) {
auto diag = diagnose(element.NameLoc, diag::function_type_argument_label,
element.Name);
if (element.SecondNameLoc.isInvalid())
diag.fixItInsert(element.NameLoc, "_ ");
else if (element.SecondName.empty())
diag.fixItRemoveChars(element.NameLoc,
element.Type->getStartLoc());
else
diag.fixItReplace(SourceRange(element.NameLoc), "_");
}
if (element.NameLoc.isValid() || element.SecondNameLoc.isValid()) {
// Form the named parameter type representation.
element.Name = element.SecondName;
element.NameLoc = element.SecondNameLoc;
element.UnderscoreLoc = element.NameLoc;
}
}
return makeParserResult(Status,
TupleTypeRepr::create(Context, ElementsR,
SourceRange(LPLoc, RPLoc),
EllipsisLoc, EllipsisIdx));
}
/// parseTypeArray - Parse the type-array production, given that we
/// are looking at the initial l_square. Note that this index
/// clause is actually the outermost (first-indexed) clause.
///
/// type-array:
/// type-simple
/// type-array '[' ']'
/// type-array '[' expr ']'
///
ParserResult<TypeRepr> Parser::parseTypeArray(TypeRepr *Base) {
assert(Tok.isFollowingLSquare());
Parser::StructureMarkerRAII ParsingArrayBound(*this, Tok);
SourceLoc lsquareLoc = consumeToken();
ArrayTypeRepr *ATR = nullptr;
// Handle a postfix [] production, a common typo for a C-like array.
// If we have something that might be an array size expression, parse it as
// such, for better error recovery.
if (Tok.isNot(tok::r_square)) {
auto sizeEx = parseExprBasic(diag::expected_expr);
if (sizeEx.hasCodeCompletion())
return makeParserCodeCompletionStatus();
if (sizeEx.isNull())
return makeParserErrorResult(Base);
}
SourceLoc rsquareLoc;
if (parseMatchingToken(tok::r_square, rsquareLoc,
diag::expected_rbracket_array_type, lsquareLoc))
return makeParserErrorResult(Base);
// If we parsed something valid, diagnose it with a fixit to rewrite it to
// Swift syntax.
diagnose(lsquareLoc, diag::new_array_syntax)
.fixItInsert(Base->getStartLoc(), "[")
.fixItRemove(lsquareLoc);
// Build a normal array slice type for recovery.
ATR = new (Context) ArrayTypeRepr(Base,
SourceRange(Base->getStartLoc(), rsquareLoc));
return makeParserResult(ATR);
}
ParserResult<TypeRepr> Parser::parseTypeCollection() {
// Parse the leading '['.
assert(Tok.is(tok::l_square));
Parser::StructureMarkerRAII parsingCollection(*this, Tok);
SourceLoc lsquareLoc = consumeToken();