-
Notifications
You must be signed in to change notification settings - Fork 10.4k
/
Copy pathParseExpr.cpp
3823 lines (3325 loc) · 135 KB
/
ParseExpr.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
//===--- ParseExpr.cpp - Swift Language Parser for Expressions ------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2018 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
//
//===----------------------------------------------------------------------===//
//
// Expression Parsing and AST Building
//
//===----------------------------------------------------------------------===//
#include "swift/Parse/Parser.h"
#include "swift/AST/ASTWalker.h"
#include "swift/AST/Attr.h"
#include "swift/AST/DiagnosticsParse.h"
#include "swift/AST/TypeRepr.h"
#include "swift/Basic/EditorPlaceholder.h"
#include "swift/Parse/IDEInspectionCallbacks.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/ADT/StringSwitch.h"
#include "llvm/ADT/Twine.h"
#include "swift/Basic/Defer.h"
#include "swift/Basic/StringExtras.h"
#include "llvm/Support/Compiler.h"
#include "llvm/Support/SaveAndRestore.h"
#include "llvm/Support/raw_ostream.h"
using namespace swift;
/// parseExpr
///
/// expr:
/// expr-sequence(basic | trailing-closure)
///
/// \param isExprBasic Whether we're only parsing an expr-basic.
ParserResult<Expr> Parser::parseExprImpl(Diag<> Message,
bool isExprBasic) {
// If we are parsing a refutable pattern, check to see if this is the start
// of a let/var/is pattern. If so, parse it as an UnresolvedPatternExpr and
// let pattern type checking determine its final form.
//
// Only do this if we're parsing a pattern, to improve QoI on malformed
// expressions followed by (e.g.) let/var decls.
//
if (InBindingPattern && isOnlyStartOfMatchingPattern()) {
ParserResult<Pattern> pattern = parseMatchingPattern(/*isExprBasic*/false);
if (pattern.hasCodeCompletion())
return makeParserCodeCompletionResult<Expr>();
if (pattern.isNull())
return nullptr;
return makeParserResult(new (Context) UnresolvedPatternExpr(pattern.get()));
}
return parseExprSequence(Message, isExprBasic,
/*forConditionalDirective*/false);
}
/// parseExprIs
/// expr-is:
/// 'is' type
ParserResult<Expr> Parser::parseExprIs() {
SourceLoc isLoc;
{
isLoc = consumeToken(tok::kw_is);
}
ParserResult<TypeRepr> type = parseType(diag::expected_type_after_is);
if (type.hasCodeCompletion())
return makeParserCodeCompletionResult<Expr>();
if (type.isNull())
return nullptr;
return makeParserResult(IsExpr::create(Context, isLoc, type.get()));
}
/// parseExprAs
/// expr-as:
/// 'as' type
/// 'as?' type
/// 'as!' type
ParserResult<Expr> Parser::parseExprAs() {
SourceLoc asLoc;
SourceLoc questionLoc;
SourceLoc exclaimLoc;
{
// Parse the 'as'.
asLoc = consumeToken(tok::kw_as);
// Parse the postfix '?'.
if (Tok.is(tok::question_postfix)) {
questionLoc = consumeToken(tok::question_postfix);
} else if (Tok.is(tok::exclaim_postfix)) {
exclaimLoc = consumeToken(tok::exclaim_postfix);
}
}
ParserResult<TypeRepr> type = parseType(diag::expected_type_after_as);
if (type.hasCodeCompletion())
return makeParserCodeCompletionResult<Expr>();
if (type.isNull())
return nullptr;
Expr *parsed;
if (questionLoc.isValid()) {
parsed = ConditionalCheckedCastExpr::create(Context, asLoc, questionLoc,
type.get());
} else if (exclaimLoc.isValid()) {
parsed = ForcedCheckedCastExpr::create(Context, asLoc, exclaimLoc,
type.get());
} else {
parsed = CoerceExpr::create(Context, asLoc, type.get());
}
return makeParserResult(parsed);
}
/// parseExprArrow
///
/// expr-arrow:
/// 'async'? ('throws' ('(' type ')')?)? '->'
ParserResult<Expr> Parser::parseExprArrow() {
SourceLoc asyncLoc, throwsLoc, arrowLoc;
ParserStatus status;
TypeRepr *thrownTyRepr = nullptr;
status |= parseEffectsSpecifiers(SourceLoc(),
asyncLoc, /*reasync=*/nullptr,
throwsLoc, /*rethrows=*/nullptr,
thrownTyRepr);
if (status.hasCodeCompletion() && !CodeCompletionCallbacks) {
// Trigger delayed parsing, no need to continue.
return status;
}
if (Tok.isNot(tok::arrow)) {
assert(throwsLoc.isValid() || asyncLoc.isValid());
diagnose(throwsLoc.isValid() ? throwsLoc : asyncLoc,
diag::async_or_throws_in_wrong_position,
throwsLoc.isValid() ? "throws" : "async");
return nullptr;
}
arrowLoc = consumeToken(tok::arrow);
parseEffectsSpecifiers(arrowLoc,
asyncLoc, /*reasync=*/nullptr,
throwsLoc, /*rethrows=*/nullptr,
thrownTyRepr);
Expr *thrownTy = nullptr;
if (thrownTyRepr) {
thrownTy = new (Context) TypeExpr(thrownTyRepr);
}
auto arrow = new (Context) ArrowExpr(asyncLoc, throwsLoc, thrownTy, arrowLoc);
return makeParserResult(arrow);
}
/// parseExprSequence
///
/// expr-sequence(Mode):
/// expr-sequence-element(Mode) expr-binary(Mode)*
/// expr-binary(Mode):
/// operator-binary expr-sequence-element(Mode)
/// '?' expr-sequence(Mode) ':' expr-sequence-element(Mode)
/// '=' expr-unary
/// expr-is
/// expr-as
///
/// The sequencing for binary exprs is not structural, i.e., binary operators
/// are not inherently right-associative. If present, '?' and ':' tokens must
/// match.
///
/// Similarly, the parsing of 'try' as part of expr-sequence-element
/// is not structural. 'try' is not permitted at arbitrary points in
/// a sequence; in the places it's permitted, it's hoisted out to
/// apply to everything to its right.
ParserResult<Expr> Parser::parseExprSequence(Diag<> Message,
bool isExprBasic,
bool isForConditionalDirective) {
SmallVector<Expr*, 8> SequencedExprs;
SourceLoc startLoc = Tok.getLoc();
ParserStatus SequenceStatus;
while (true) {
if (isForConditionalDirective && Tok.isAtStartOfLine())
break;
// Parse a unary expression.
ParserResult<Expr> Primary =
parseExprSequenceElement(Message, isExprBasic);
SequenceStatus |= Primary;
if (SequenceStatus.hasCodeCompletion() && CodeCompletionCallbacks)
CodeCompletionCallbacks->setLeadingSequenceExprs(SequencedExprs);
if (Primary.isNull()) {
if (SequenceStatus.hasCodeCompletion()) {
SequencedExprs.push_back(new (Context) CodeCompletionExpr(PreviousLoc));
break;
}
return nullptr;
}
SequencedExprs.push_back(Primary.get());
if (SequenceStatus.isError() && !SequenceStatus.hasCodeCompletion())
break;
if (isForConditionalDirective && Tok.isAtStartOfLine())
break;
parse_operator:
switch (Tok.getKind()) {
case tok::oper_binary_spaced:
case tok::oper_binary_unspaced: {
// If this is an "&& #available()" expression (or related things that
// show up in a stmt-condition production), then don't eat it.
//
// These are not general expressions, and && is an infix operator,
// so the code is invalid. We get better recovery if we bail out from
// this, because then we can produce a fixit to rewrite the && into a ,
// if we're in a stmt-condition.
if (Tok.getText() == "&&" &&
(peekToken().isAny(tok::pound_available, tok::pound_unavailable,
tok::pound__hasSymbol, tok::kw_let, tok::kw_var,
tok::kw_case) ||
(Context.LangOpts.hasFeature(Feature::ReferenceBindings) &&
peekToken().isAny(tok::kw_inout))))
goto done;
// Parse the operator.
Expr *Operator = parseExprOperator();
SequencedExprs.push_back(Operator);
// The message is only valid for the first subexpr.
Message = diag::expected_expr_after_operator;
break;
}
case tok::question_infix: {
// Save the '?'.
SourceLoc questionLoc = consumeToken();
// Parse the middle expression of the ternary.
ParserResult<Expr> middle = parseExprSequence(
diag::expected_expr_after_ternary_question, isExprBasic);
SequenceStatus |= middle;
ParserStatus Status = middle;
if (middle.isNull())
return nullptr;
// Make sure there's a matching ':' after the middle expr.
if (!Tok.is(tok::colon)) {
if (middle.hasCodeCompletion()) {
SequencedExprs.push_back(new (Context) TernaryExpr(
questionLoc, middle.get(), PreviousLoc));
SequencedExprs.push_back(new (Context) CodeCompletionExpr(PreviousLoc));
goto done;
}
diagnose(questionLoc, diag::expected_colon_after_ternary_question);
Status.setIsParseError();
return makeParserResult(Status, new (Context) ErrorExpr(
{startLoc, middle.get()->getSourceRange().End}));
}
SourceLoc colonLoc = consumeToken();
auto *unresolvedTernary =
new (Context) TernaryExpr(questionLoc, middle.get(), colonLoc);
SequencedExprs.push_back(unresolvedTernary);
Message = diag::expected_expr_after_ternary_colon;
break;
}
case tok::equal: {
// If we're parsing an expression as the body of a refutable var/let
// pattern, then an assignment doesn't make sense. In a "if let"
// statement the equals is the start of the condition, so don't parse it
// as a binary operator.
if (InBindingPattern)
goto done;
SourceLoc equalsLoc = consumeToken();
auto *assign = new (Context) AssignExpr(equalsLoc);
SequencedExprs.push_back(assign);
Message = diag::expected_expr_assignment;
break;
}
case tok::kw_is: {
// Parse a type after the 'is' token instead of an expression.
ParserResult<Expr> is = parseExprIs();
if (is.isNull() || is.hasCodeCompletion())
return is;
// Store the expr itself as a placeholder RHS. The real RHS is the
// type parameter stored in the node itself.
SequenceStatus |= is;
SequencedExprs.push_back(is.get());
SequencedExprs.push_back(is.get());
// We already parsed the right operand as part of the 'is' production.
// Jump directly to parsing another operator.
goto parse_operator;
}
case tok::kw_as: {
ParserResult<Expr> as = parseExprAs();
if (as.isNull() || as.hasCodeCompletion())
return as;
// Store the expr itself as a placeholder RHS. The real RHS is the
// type parameter stored in the node itself.
SequenceStatus |= as;
SequencedExprs.push_back(as.get());
SequencedExprs.push_back(as.get());
// We already parsed the right operand as part of the 'is' production.
// Jump directly to parsing another operator.
goto parse_operator;
}
case tok::identifier: {
// 'async' followed by 'throws' or '->' implies that we have an arrow
// expression.
if (!(Tok.isContextualKeyword("async") &&
peekToken().isAny(tok::arrow, tok::kw_throws)))
goto done;
LLVM_FALLTHROUGH;
}
case tok::arrow:
case tok::kw_throws: {
ParserResult<Expr> arrow = parseExprArrow();
if (arrow.isNull() || arrow.hasCodeCompletion())
return arrow;
SequenceStatus |= arrow;
SequencedExprs.push_back(arrow.get());
break;
}
default:
// If the next token is not a binary operator, we're done.
goto done;
}
}
done:
// For conditional directives, we stop parsing after a line break.
if (isForConditionalDirective && (SequencedExprs.size() & 1) == 0) {
diagnose(getEndOfPreviousLoc(),
diag::incomplete_conditional_compilation_directive);
return makeParserError();
}
// If we had semantic errors, just fail here.
assert(!SequencedExprs.empty());
// If we saw no operators, don't build a sequence.
if (SequencedExprs.size() == 1)
return makeParserResult(SequenceStatus, SequencedExprs[0]);
return makeParserResult(SequenceStatus,
SequenceExpr::create(Context, SequencedExprs));
}
/// parseExprSequenceElement
///
/// expr-sequence-element(Mode):
/// 'await' expr-sequence-element(Mode)
/// 'try' expr-sequence-element(Mode)
/// 'try' '?' expr-sequence-element(Mode)
/// 'try' '!' expr-sequence-element(Mode)
/// '_move' expr-sequence-element(Mode)
/// 'borrow' expr-sequence-element(Mode)
/// expr-unary(Mode)
///
/// 'try' is not actually allowed at an arbitrary position of a
/// sequence, but this isn't enforced until sequence-folding.
ParserResult<Expr> Parser::parseExprSequenceElement(Diag<> message,
bool isExprBasic) {
// Check whether the user mistyped "async" for "await", but only in cases
// where we are sure that "async" would be ill-formed as an identifier.
bool isReplaceableAsync = Tok.isContextualKeyword("async") &&
!peekToken().isAtStartOfLine() &&
(peekToken().is(tok::identifier) || peekToken().is(tok::kw_try));
if (Tok.isContextualKeyword("await") || isReplaceableAsync) {
// Error on a replaceable async
if (isReplaceableAsync) {
diagnose(Tok.getLoc(), diag::expected_await_not_async)
.fixItReplace(Tok.getLoc(), "await");
}
Tok.setKind(tok::contextual_keyword);
SourceLoc awaitLoc = consumeToken();
ParserResult<Expr> sub =
parseExprSequenceElement(diag::expected_expr_after_await, isExprBasic);
if (!sub.hasCodeCompletion() && !sub.isNull()) {
if (auto anyTry = dyn_cast<AnyTryExpr>(sub.get())) {
// "try" must precede "await".
diagnose(awaitLoc, diag::await_before_try)
.fixItRemove(awaitLoc)
.fixItInsert(anyTry->getSubExpr()->getStartLoc(), "await ");
}
sub = makeParserResult(new (Context) AwaitExpr(awaitLoc, sub.get()));
}
return sub;
}
if (Tok.isContextualKeyword("consume")
&& peekToken().isAny(tok::identifier, tok::kw_self, tok::dollarident,
tok::code_complete)
&& !peekToken().isAtStartOfLine()) {
Tok.setKind(tok::contextual_keyword);
SourceLoc consumeLoc = consumeToken();
ParserResult<Expr> sub =
parseExprSequenceElement(diag::expected_expr_after_move, isExprBasic);
if (!sub.isNull()) {
sub = makeParserResult(new (Context) ConsumeExpr(consumeLoc, sub.get()));
}
return sub;
}
if (Tok.isContextualKeyword("copy") &&
peekToken().isAny(tok::identifier, tok::kw_self, tok::dollarident,
tok::code_complete) &&
!peekToken().isAtStartOfLine()) {
Tok.setKind(tok::contextual_keyword);
SourceLoc copyLoc = consumeToken();
ParserResult<Expr> sub =
parseExprSequenceElement(diag::expected_expr_after_copy, isExprBasic);
if (!sub.isNull()) {
sub = makeParserResult(new (Context) CopyExpr(copyLoc, sub.get()));
}
return sub;
}
if (Context.LangOpts.hasFeature(Feature::OldOwnershipOperatorSpellings)) {
if (Tok.isContextualKeyword("_move")) {
Tok.setKind(tok::contextual_keyword);
SourceLoc awaitLoc = consumeToken();
diagnose(Tok, diag::move_consume_final_spelling)
.fixItReplace(awaitLoc, "consume");
ParserResult<Expr> sub =
parseExprSequenceElement(diag::expected_expr_after_move, isExprBasic);
if (!sub.hasCodeCompletion() && !sub.isNull()) {
sub = makeParserResult(new (Context) ConsumeExpr(awaitLoc, sub.get()));
}
return sub;
}
if (Tok.isContextualKeyword("_borrow")) {
Tok.setKind(tok::contextual_keyword);
SourceLoc awaitLoc = consumeToken();
ParserResult<Expr> sub = parseExprSequenceElement(
diag::expected_expr_after_borrow, isExprBasic);
if (!sub.hasCodeCompletion() && !sub.isNull()) {
sub = makeParserResult(new (Context) BorrowExpr(awaitLoc, sub.get()));
}
return sub;
}
}
// 'any' followed by another identifier is an existential type.
if (Tok.isContextualKeyword("any") &&
peekToken().is(tok::identifier) &&
!peekToken().isAtStartOfLine()) {
ParserResult<TypeRepr> ty = parseType();
auto *typeExpr = new (Context) TypeExpr(ty.get());
return makeParserResult(typeExpr);
}
// 'repeat' as an expression prefix is a pack expansion expression.
if (Tok.is(tok::kw_repeat)) {
SourceLoc repeatLoc = consumeToken();
auto patternExpr = parseExprImpl(
diag::expected_expr_after_repeat, isExprBasic);
if (patternExpr.isNull())
return patternExpr;
auto *expansion =
PackExpansionExpr::create(Context, repeatLoc, patternExpr.get(),
/*genericEnv*/ nullptr);
return makeParserResult(expansion);
}
// 'each' followed by another identifier is a pack element expr.
if (Tok.isContextualKeyword("each") &&
peekToken().isAny(tok::identifier, tok::kw_self, tok::dollarident,
tok::code_complete) &&
!peekToken().isAtStartOfLine()) {
SourceLoc loc = consumeToken();
ParserResult<Expr> ref =
parseExprSequenceElement(diag::expected_expr_after_each, isExprBasic);
if (ref.isNull())
return ref;
auto *packRef = PackElementExpr::create(Context, loc, ref.get());
return makeParserResult(packRef);
}
SourceLoc tryLoc;
bool hadTry = consumeIf(tok::kw_try, tryLoc);
llvm::Optional<Token> trySuffix;
if (hadTry && Tok.isAny(tok::exclaim_postfix, tok::question_postfix)) {
trySuffix = Tok;
consumeToken();
}
// Try to parse '@' sign or 'inout' as a attributed typerepr.
if (Tok.isAny(tok::at_sign, tok::kw_inout)) {
bool isType = false;
{
BacktrackingScope backtrack(*this);
isType = canParseType();
}
if (isType) {
ParserResult<TypeRepr> ty = parseType();
if (ty.isNonNull())
return makeParserResult(
new (Context) TypeExpr(ty.get()));
checkForInputIncomplete();
return nullptr;
}
}
ParserResult<Expr> sub = hadTry
? parseExprSequenceElement(message, isExprBasic)
: parseExprUnary(message, isExprBasic);
if (hadTry && !sub.hasCodeCompletion() && !sub.isNull()) {
switch (trySuffix ? trySuffix->getKind() : tok::NUM_TOKENS) {
case tok::exclaim_postfix:
sub = makeParserResult(
new (Context) ForceTryExpr(tryLoc, sub.get(), trySuffix->getLoc()));
break;
case tok::question_postfix:
sub = makeParserResult(
new (Context) OptionalTryExpr(tryLoc, sub.get(),
trySuffix->getLoc()));
break;
default:
// If this is a simple "try expr" situation, where the expr is a closure
// literal, and the next token is a 'catch', then the user wrote
// try/catch instead of do/catch. Emit a fixit hint to rewrite to the
// correct do/catch construct.
if (Tok.is(tok::kw_catch) && isa<ClosureExpr>(sub.get())) {
diagnose(tryLoc, diag::docatch_not_trycatch)
.fixItReplace(tryLoc, "do");
// Eat all of the catch clauses, so we don't trip over them in error
// recovery.
while (Tok.is(tok::kw_catch)) {
ParserResult<CaseStmt> clause = parseStmtCatch();
if (clause.hasCodeCompletion() && clause.isNull())
break;
}
return makeParserResult(new (Context) ErrorExpr(tryLoc));
}
sub = makeParserResult(new (Context) TryExpr(tryLoc, sub.get()));
break;
}
}
return sub;
}
/// parseExprUnary
///
/// expr-unary(Mode):
/// expr-postfix(Mode)
/// operator-prefix expr-unary(Mode)
/// '&' expr-unary(Mode)
///
ParserResult<Expr> Parser::parseExprUnary(Diag<> Message, bool isExprBasic) {
UnresolvedDeclRefExpr *Operator;
// First check to see if we have the start of a regex literal `/.../`.
tryLexRegexLiteral(/*forUnappliedOperator*/ false);
// Try parse 'if', 'switch', and 'do' as expressions. Note we do this here
// in parseExprUnary as we don't allow postfix syntax to hang off such
// expressions to avoid ambiguities such as postfix '.member', which can
// currently be parsed as a static dot member for a result builder.
if (Tok.isAny(tok::kw_if, tok::kw_switch) ||
(Tok.is(tok::kw_do) &&
Context.LangOpts.hasFeature(Feature::DoExpressions))) {
auto Result = parseStmt();
Expr *E = nullptr;
if (Result.isNonNull()) {
E = SingleValueStmtExpr::createWithWrappedBranches(
Context, Result.get(), CurDeclContext, /*mustBeExpr*/ true);
}
return makeParserResult(ParserStatus(Result), E);
}
switch (Tok.getKind()) {
default:
// If the next token is not an operator, just parse this as expr-postfix.
return parseExprPostfix(Message, isExprBasic);
case tok::amp_prefix: {
SourceLoc Loc = consumeToken(tok::amp_prefix);
ParserResult<Expr> SubExpr = parseExprUnary(Message, isExprBasic);
if (SubExpr.hasCodeCompletion())
return makeParserCodeCompletionResult<Expr>(SubExpr.getPtrOrNull());
if (SubExpr.isNull())
return nullptr;
return makeParserResult(
new (Context) InOutExpr(Loc, SubExpr.get(), Type()));
}
case tok::backslash:
return parseExprKeyPath();
case tok::oper_postfix: {
// Postfix operators cannot start a subexpression, but can happen
// syntactically because the operator may just follow whatever precedes this
// expression (and that may not always be an expression).
diagnose(Tok, diag::invalid_postfix_operator);
Tok.setKind(tok::oper_prefix);
Operator = parseExprOperator();
break;
}
case tok::oper_prefix: {
Operator = parseExprOperator();
break;
}
case tok::oper_binary_spaced:
case tok::oper_binary_unspaced: {
// For recovery purposes, accept an oper_binary here.
SourceLoc OperEndLoc = Tok.getLoc().getAdvancedLoc(Tok.getLength());
Tok.setKind(tok::oper_prefix);
Operator = parseExprOperator();
if (OperEndLoc == Tok.getLoc())
diagnose(PreviousLoc, diag::expected_expr_after_unary_operator);
else
diagnose(PreviousLoc, diag::expected_prefix_operator)
.fixItRemoveChars(OperEndLoc, Tok.getLoc());
break;
}
}
ParserResult<Expr> SubExpr = parseExprUnary(Message, isExprBasic);
ParserStatus Status = SubExpr;
if (SubExpr.isNull())
return Status;
// Check if we have a unary '-' with number literal sub-expression, for
// example, "-42" or "-1.25".
if (auto *LE = dyn_cast<NumberLiteralExpr>(SubExpr.get())) {
if (Operator->hasName() && Operator->getName().getBaseName() == "-") {
LE->setNegative(Operator->getLoc());
return makeParserResult(Status, LE);
}
}
auto *opCall = PrefixUnaryExpr::create(Context, Operator, SubExpr.get());
return makeParserResult(Status, opCall);
}
/// expr-keypath-swift:
/// \ type? . initial-key-path-component key-path-components
///
/// key-path-components:
// key-path-component*
/// <empty>
///
/// key-path-component:
/// .identifier
/// ?
/// !
/// [ expression ]
///
/// initial-key-path-component:
/// identifier
/// ?
/// !
/// [ expression ]
ParserResult<Expr> Parser::parseExprKeyPath() {
// Consume '\'.
SourceLoc backslashLoc = consumeToken(tok::backslash);
llvm::SaveAndRestore<bool> S(InSwiftKeyPath, true);
// FIXME: diagnostics
ParserResult<Expr> rootResult, pathResult;
ParserStatus parseStatus;
if (!startsWithSymbol(Tok, '.')) {
rootResult = parseExprPostfix(diag::expr_keypath_expected_expr,
/*isBasic=*/true);
parseStatus = rootResult;
if (rootResult.isParseErrorOrHasCompletion())
return rootResult;
}
bool hasLeadingDot = startsWithSymbol(Tok, '.');
if (hasLeadingDot) {
auto dotLoc = Tok.getLoc();
// For uniformity, \.foo is parsed as if it were MAGIC.foo, so we need to
// make sure the . is there, but parsing the ? in \.? as .? doesn't make
// sense. This is all made more complicated by .?. being considered an
// operator token. Since keypath allows '.!' '.?' and '.[', consume '.'
// the token is a operator starts with '.', or the following token is '['.
if ((Tok.isAnyOperator() && Tok.getLength() != 1) ||
peekToken().is(tok::l_square)) {
consumeStartingCharacterOfCurrentToken(tok::period);
}
auto inner = makeParserResult(new (Context) KeyPathDotExpr(dotLoc));
bool unusedHasBindOptional = false;
// Inside a keypath's path, the period always behaves normally: the key path
// behavior is only the separation between type and path.
pathResult = parseExprPostfixSuffix(inner, /*isExprBasic=*/true,
/*periodHasKeyPathBehavior=*/false,
unusedHasBindOptional);
parseStatus |= pathResult;
}
if (rootResult.isNull() && pathResult.isNull())
return nullptr;
// Handle code completion.
if ((Tok.is(tok::code_complete) && !Tok.isAtStartOfLine()) ||
(Tok.is(tok::period) && peekToken().isAny(tok::code_complete))) {
SourceLoc DotLoc;
consumeIf(tok::period, DotLoc);
// Add the code completion expression to the path result.
CodeCompletionExpr *CC = new (Context)
CodeCompletionExpr(pathResult.getPtrOrNull(), Tok.getLoc());
auto *keypath = KeyPathExpr::createParsed(
Context, backslashLoc, rootResult.getPtrOrNull(), CC, hasLeadingDot);
if (this->CodeCompletionCallbacks)
this->CodeCompletionCallbacks->completeExprKeyPath(keypath, DotLoc);
consumeToken(tok::code_complete);
return makeParserCodeCompletionResult(keypath);
}
auto *keypath = KeyPathExpr::createParsed(
Context, backslashLoc, rootResult.getPtrOrNull(),
pathResult.getPtrOrNull(), hasLeadingDot);
return makeParserResult(parseStatus, keypath);
}
/// expr-keypath-objc:
/// '#keyPath' '(' unqualified-name ('.' unqualified-name) * ')'
///
ParserResult<Expr> Parser::parseExprKeyPathObjC() {
// Consume '#keyPath'.
SourceLoc keywordLoc = consumeToken(tok::pound_keyPath);
// Parse the leading '('.
if (!Tok.is(tok::l_paren)) {
diagnose(Tok, diag::expr_keypath_expected_lparen);
return makeParserError();
}
SourceLoc lParenLoc = consumeToken(tok::l_paren);
SmallVector<KeyPathExpr::Component, 4> components;
/// Handler for code completion.
auto handleCodeCompletion = [&](SourceLoc DotLoc) -> ParserResult<Expr> {
KeyPathExpr *expr = nullptr;
if (!components.empty()) {
expr = KeyPathExpr::createParsedPoundKeyPath(
Context, keywordLoc, lParenLoc, components, Tok.getLoc());
}
if (this->CodeCompletionCallbacks)
this->CodeCompletionCallbacks->completeExprKeyPath(expr, DotLoc);
// Eat the code completion token because we handled it.
consumeToken(tok::code_complete);
return makeParserCodeCompletionResult(expr);
};
// Parse the sequence of unqualified-names.
ParserStatus status;
SourceLoc LastDotLoc;
DeclNameOptions flags = DeclNameFlag::AllowCompoundNames |
DeclNameFlag::AllowLowercaseAndUppercaseSelf;
while (true) {
// Handle code completion.
if (Tok.is(tok::code_complete))
return handleCodeCompletion(LastDotLoc);
// Parse the next name.
DeclNameLoc nameLoc;
DeclNameRef name = parseDeclNameRef(nameLoc,
diag::expr_keypath_expected_property_or_type, flags);
if (!name) {
status.setIsParseError();
break;
}
// Record the name we parsed.
auto component = KeyPathExpr::Component::forUnresolvedProperty(name,
nameLoc.getBaseNameLoc());
components.push_back(component);
// After the first component, we can start parsing keywords.
flags |= DeclNameFlag::AllowKeywords;
// Handle code completion.
if (Tok.is(tok::code_complete))
return handleCodeCompletion(SourceLoc());
// Parse the next period to continue the path.
if (consumeIf(tok::period, LastDotLoc))
continue;
break;
}
// Parse the closing ')'.
SourceLoc rParenLoc;
if (status.isErrorOrHasCompletion()) {
skipUntilDeclStmtRBrace(tok::r_paren);
if (Tok.is(tok::r_paren))
rParenLoc = consumeToken();
else
rParenLoc = PreviousLoc;
} else {
parseMatchingToken(tok::r_paren, rParenLoc,
diag::expr_keypath_expected_rparen, lParenLoc);
}
// If we cannot build a useful expression, just return an error
// expression.
if (components.empty() || status.isErrorOrHasCompletion()) {
return makeParserResult<Expr>(
new (Context) ErrorExpr(SourceRange(keywordLoc, rParenLoc)));
}
// We're done: create the key-path expression.
return makeParserResult<Expr>(KeyPathExpr::createParsedPoundKeyPath(
Context, keywordLoc, lParenLoc, components, rParenLoc));
}
/// parseExprSelector
///
/// expr-selector:
/// '#selector' '(' expr ')'
/// '#selector' '(' 'getter' ':' expr ')'
/// '#selector' '(' 'setter' ':' expr ')'
///
ParserResult<Expr> Parser::parseExprSelector() {
// Consume '#selector'.
SourceLoc keywordLoc = consumeToken(tok::pound_selector);
// Parse the leading '('.
if (!Tok.is(tok::l_paren)) {
diagnose(Tok, diag::expr_selector_expected_lparen);
return makeParserError();
}
SourceLoc lParenLoc = consumeToken(tok::l_paren);
SourceLoc modifierLoc;
// Parse possible 'getter:' or 'setter:' modifiers, and determine
// the kind of selector we're working with.
ObjCSelectorExpr::ObjCSelectorKind selectorKind;
if (peekToken().is(tok::colon) &&
(Tok.isContextualKeyword("getter") ||
Tok.isContextualKeyword("setter"))) {
// Parse the modifier.
if (Tok.isContextualKeyword("getter"))
selectorKind = ObjCSelectorExpr::Getter;
else
selectorKind = ObjCSelectorExpr::Setter;
Tok.setKind(tok::contextual_keyword);
modifierLoc = consumeToken();
(void)consumeToken(tok::colon);
} else {
selectorKind = ObjCSelectorExpr::Method;
}
ObjCSelectorContext selectorContext;
switch (selectorKind) {
case ObjCSelectorExpr::Getter:
selectorContext = ObjCSelectorContext::GetterSelector;
break;
case ObjCSelectorExpr::Setter:
selectorContext = ObjCSelectorContext::SetterSelector;
break;
case ObjCSelectorExpr::Method:
selectorContext = ObjCSelectorContext::MethodSelector;
}
// Parse the subexpression.
CodeCompletionCallbacks::InObjCSelectorExprRAII InObjCSelectorExpr(
CodeCompletionCallbacks, selectorContext);
ParserResult<Expr> subExpr =
parseExpr(selectorKind == ObjCSelectorExpr::Method
? diag::expr_selector_expected_method_expr
: diag::expr_selector_expected_property_expr);
// Parse the closing ')'.
SourceLoc rParenLoc;
if (subExpr.isParseErrorOrHasCompletion()) {
skipUntilDeclStmtRBrace(tok::r_paren);
if (Tok.is(tok::r_paren))
rParenLoc = consumeToken();
else
rParenLoc = PreviousLoc;
} else {
parseMatchingToken(tok::r_paren, rParenLoc,
diag::expr_selector_expected_rparen, lParenLoc);
}
// If the subexpression was in error, just propagate the error.
if (subExpr.isParseErrorOrHasCompletion() && !subExpr.hasCodeCompletion())
return makeParserResult<Expr>(
new (Context) ErrorExpr(SourceRange(keywordLoc, rParenLoc)));
return makeParserResult<Expr>(
new (Context) ObjCSelectorExpr(selectorKind, keywordLoc, lParenLoc,
modifierLoc, subExpr.get(), rParenLoc));
}
static DeclRefKind getDeclRefKindForOperator(tok kind) {
switch (kind) {
case tok::oper_binary_spaced:
case tok::oper_binary_unspaced: return DeclRefKind::BinaryOperator;
case tok::oper_postfix: return DeclRefKind::PostfixOperator;
case tok::oper_prefix: return DeclRefKind::PrefixOperator;
default: llvm_unreachable("bad operator token kind");
}
}
/// parseExprOperator - Parse an operator reference expression. These
/// are not "proper" expressions; they can only appear in binary/unary
/// operators.
UnresolvedDeclRefExpr *Parser::parseExprOperator() {
assert(Tok.isAnyOperator());
DeclRefKind refKind = getDeclRefKindForOperator(Tok.getKind());
SourceLoc loc = Tok.getLoc();
DeclNameRef name(Context.getIdentifier(Tok.getText()));
consumeToken();
// Bypass local lookup.
return new (Context) UnresolvedDeclRefExpr(name, refKind, DeclNameLoc(loc));
}
void Parser::tryLexRegexLiteral(bool forUnappliedOperator) {
if (!Context.LangOpts.hasFeature(Feature::BareSlashRegexLiterals) ||
!Context.LangOpts.EnableExperimentalStringProcessing)
return;
// Check to see if we have a regex literal `/.../`, optionally with a prefix
// operator e.g `!/.../`.
// NOTE: If you change this logic you must also change the logic in
// isPotentialUnskippableBareSlashRegexLiteral.
bool mustBeRegex = false;
switch (Tok.getKind()) {
case tok::oper_prefix:
// Prefix operators may contain `/` characters, so this may not be a regex,
// and as such need to make sure we have a closing `/`.
break;
case tok::oper_binary_spaced:
case tok::oper_binary_unspaced:
// When re-lexing for a unary expression, binary operators are always
// invalid, so we can be confident in always lexing a regex literal.
mustBeRegex = !forUnappliedOperator;
break;
default:
// We only re-lex regex literals for operator tokens.
return;
}
// Check to see if we have an operator containing '/'.
auto slashIdx = Tok.getText().find("/");
if (slashIdx == StringRef::npos)
return;
CancellableBacktrackingScope backtrack(*this);
{
llvm::Optional<Lexer::ForwardSlashRegexRAII> regexScope;
regexScope.emplace(*L, mustBeRegex);
// Try re-lex as a `/.../` regex literal, this will split an operator if
// necessary.
L->restoreState(getParserPosition().LS, /*enableDiagnostics*/ true);