forked from swiftlang/swift
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ParseDecl.cpp
7875 lines (6892 loc) · 269 KB
/
ParseDecl.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
//===--- ParseDecl.cpp - Swift Language Parser for Declarations -----------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2019 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
//
//===----------------------------------------------------------------------===//
//
// Declaration Parsing and AST Building
//
//===----------------------------------------------------------------------===//
#include "swift/Parse/Parser.h"
#include "swift/Parse/CodeCompletionCallbacks.h"
#include "swift/Parse/ParsedSyntaxRecorder.h"
#include "swift/Parse/ParseSILSupport.h"
#include "swift/Parse/SyntaxParsingContext.h"
#include "swift/Syntax/SyntaxKind.h"
#include "swift/Subsystems.h"
#include "swift/AST/Attr.h"
#include "swift/AST/LazyResolver.h"
#include "swift/AST/DebuggerClient.h"
#include "swift/AST/DiagnosticsParse.h"
#include "swift/AST/Initializer.h"
#include "swift/AST/Module.h"
#include "swift/AST/ParameterList.h"
#include "swift/AST/ParseRequests.h"
#include "swift/AST/SourceFile.h"
#include "swift/Basic/Defer.h"
#include "swift/Basic/Statistic.h"
#include "swift/Basic/StringExtras.h"
#include "llvm/Support/Compiler.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/SaveAndRestore.h"
#include "llvm/ADT/PointerUnion.h"
#include "llvm/ADT/StringSwitch.h"
#include "llvm/ADT/Twine.h"
#include <algorithm>
using namespace swift;
using namespace syntax;
namespace {
/// A RAII object for deciding whether this DeclKind needs special
/// treatment when parsing in the "debugger context", and implementing
/// that treatment. The problem arises because, when lldb
/// uses swift to parse expressions, it needs to emulate the current
/// frame's scope. We do that, for instance, by making a class extension
/// and running the code in a function in that extension.
///
/// This causes two kinds of issues:
/// 1) Some DeclKinds require to be parsed in TopLevel contexts only.
/// 2) Sometimes the debugger wants a Decl to live beyond the current
/// function invocation, in which case it should be parsed at the
/// file scope level so it will be set up correctly for this purpose.
///
/// Creating an instance of this object will cause it to figure out
/// whether we are in the debugger function, whether it needs to swap
/// the Decl that is currently being parsed.
/// If you have created the object, instead of returning the result
/// with makeParserResult, use the object's fixupParserResult. If
/// no swap has occurred, these methods will work the same.
/// If the decl has been moved, then Parser::markWasHandled will be
/// called on the Decl, and you should call declWasHandledAlready
/// before you consume the Decl to see if you actually need to
/// consume it.
/// If you are making one of these objects to address issue 1, call
/// the constructor that only takes a DeclKind, and it will be moved
/// unconditionally. Otherwise pass in the Name and DeclKind and the
/// DebuggerClient will be asked whether to move it or not.
class DebuggerContextChange {
protected:
Parser &P;
Identifier Name;
SourceFile *SF;
Optional<Parser::ContextChange> CC;
public:
DebuggerContextChange (Parser &P)
: P(P), SF(nullptr) {
if (!inDebuggerContext())
return;
else
switchContext();
}
DebuggerContextChange (Parser &P, Identifier &Name, DeclKind Kind)
: P(P), Name(Name), SF(nullptr) {
if (!inDebuggerContext())
return;
bool globalize = false;
DebuggerClient *debug_client = getDebuggerClient();
if (!debug_client)
return;
globalize = debug_client->shouldGlobalize(Name, Kind);
if (globalize)
switchContext();
}
bool movedToTopLevel() {
return CC.hasValue();
}
template <typename T>
ParserResult<T>
fixupParserResult(ParserResult<T> &Result) {
ParserStatus Status = Result;
return fixupParserResult(Status, Result.getPtrOrNull());
}
template <typename T>
ParserResult<T>
fixupParserResult(T *D) {
if (CC.hasValue()) {
swapDecl(D);
}
return ParserResult<T>(D);
}
template <typename T>
ParserResult<T>
fixupParserResult(ParserStatus Status, T *D) {
if (CC.hasValue() && !Status.isError()) {
// If there is an error, don't do our splicing trick,
// just return the Decl and the status for reporting.
swapDecl(D);
}
return makeParserResult(Status, D);
}
// The destructor doesn't need to do anything, the CC's destructor will
// pop the context if we set it.
~DebuggerContextChange () {}
protected:
DebuggerClient *getDebuggerClient()
{
ModuleDecl *PM = P.CurDeclContext->getParentModule();
if (!PM)
return nullptr;
else
return PM->getDebugClient();
}
bool inDebuggerContext() {
if (!P.Context.LangOpts.DebuggerSupport)
return false;
if (!P.CurDeclContext)
return false;
auto *func_decl = dyn_cast<FuncDecl>(P.CurDeclContext);
if (!func_decl)
return false;
if (!func_decl->getAttrs().hasAttribute<LLDBDebuggerFunctionAttr>())
return false;
return true;
}
void switchContext () {
SF = P.CurDeclContext->getParentSourceFile();
CC.emplace (P, SF);
}
void swapDecl (Decl *D)
{
assert (SF);
DebuggerClient *debug_client = getDebuggerClient();
assert (debug_client);
debug_client->didGlobalize(D);
P.ContextSwitchedTopLevelDecls.push_back(D);
P.markWasHandled(D);
}
};
} // end anonymous namespace
/// Main entrypoint for the parser.
///
/// \verbatim
/// top-level:
/// stmt-brace-item*
/// decl-sil [[only in SIL mode]
/// decl-sil-stage [[only in SIL mode]
/// \endverbatim
void Parser::parseTopLevel(SmallVectorImpl<Decl *> &decls) {
// Prime the lexer.
if (Tok.is(tok::NUM_TOKENS))
consumeTokenWithoutFeedingReceiver();
// Parse the body of the file.
SmallVector<ASTNode, 128> items;
while (!Tok.is(tok::eof)) {
// If we run into a SIL decl, skip over until the next Swift decl. We need
// to delay parsing these, as SIL parsing currently requires type checking
// Swift decls.
if (isStartOfSILDecl()) {
assert(!isStartOfSwiftDecl() && "Start of both a Swift and SIL decl?");
skipSILUntilSwiftDecl();
continue;
}
parseBraceItems(items, allowTopLevelCode()
? BraceItemListKind::TopLevelCode
: BraceItemListKind::TopLevelLibrary);
// In the case of a catastrophic parse error, consume any trailing
// #else, #elseif, or #endif and move on to the next statement or
// declaration block.
if (Tok.is(tok::pound_else) || Tok.is(tok::pound_elseif) ||
Tok.is(tok::pound_endif)) {
diagnose(Tok.getLoc(),
diag::unexpected_conditional_compilation_block_terminator);
// Create 'UnknownDecl' for orphan directives.
SyntaxParsingContext itemCtxt(SyntaxContext, SyntaxKind::CodeBlockItem);
SyntaxParsingContext declCtxt(SyntaxContext, SyntaxContextKind::Decl);
consumeToken();
}
}
// First append any decls that LLDB requires be inserted at the top-level.
decls.append(ContextSwitchedTopLevelDecls.begin(),
ContextSwitchedTopLevelDecls.end());
// Then append the top-level decls we parsed.
for (auto item : items) {
auto *decl = item.get<Decl *>();
assert(!isa<AccessorDecl>(decl) && "accessors should not be added here");
decls.push_back(decl);
}
// Finalize the token receiver.
SyntaxContext->addToken(Tok, LeadingTrivia, TrailingTrivia);
TokReceiver->finalize();
}
void Parser::parseTopLevelSIL() {
assert(SIL && isInSILMode());
// Prime the lexer.
if (Tok.is(tok::NUM_TOKENS))
consumeTokenWithoutFeedingReceiver();
auto skipToNextSILDecl = [&]() {
while (!Tok.is(tok::eof) && !isStartOfSILDecl())
skipSingle();
};
while (!Tok.is(tok::eof)) {
// If we run into a Swift decl, skip over until we find the next SIL decl.
if (isStartOfSwiftDecl()) {
assert(!isStartOfSILDecl() && "Start of both a Swift and SIL decl?");
skipToNextSILDecl();
continue;
}
switch (Tok.getKind()) {
#define CASE_SIL(KW, NAME) \
case tok::kw_##KW: { \
/* If we failed to parse a SIL decl, move onto the next SIL decl to \
better help recovery. */ \
if (SIL->parse##NAME(*this)) { \
Lexer::SILBodyRAII sbr(*L); \
skipToNextSILDecl(); \
} \
break; \
}
CASE_SIL(sil, DeclSIL)
CASE_SIL(sil_stage, DeclSILStage)
CASE_SIL(sil_vtable, SILVTable)
CASE_SIL(sil_global, SILGlobal)
CASE_SIL(sil_witness_table, SILWitnessTable)
CASE_SIL(sil_default_witness_table, SILDefaultWitnessTable)
CASE_SIL(sil_differentiability_witness, SILDifferentiabilityWitness)
CASE_SIL(sil_coverage_map, SILCoverageMap)
CASE_SIL(sil_property, SILProperty)
CASE_SIL(sil_scope, SILScope)
#undef CASE_SIL
default:
// If we reached here, we have something malformed that isn't a Swift decl
// or a SIL decl. Emit an error and skip ahead to the next SIL decl.
diagnose(Tok, diag::expected_sil_keyword);
skipToNextSILDecl();
break;
}
}
}
ParserResult<AvailableAttr> Parser::parseExtendedAvailabilitySpecList(
SourceLoc AtLoc, SourceLoc AttrLoc, StringRef AttrName) {
// Check 'Tok', return false if ':' or '=' cannot be found.
// Complain if '=' is found and suggest replacing it with ": ".
auto findAttrValueDelimiter = [&]() -> bool {
if (!Tok.is(tok::colon)) {
if (!Tok.is(tok::equal))
return false;
diagnose(Tok.getLoc(), diag::replace_equal_with_colon_for_value)
.fixItReplace(Tok.getLoc(), ": ");
}
return true;
};
struct VersionArg {
llvm::VersionTuple Version;
SourceRange Range;
SourceLoc DelimiterLoc;
bool empty() const {
return Version.empty();
}
};
StringRef Platform = Tok.getText();
StringRef Message, Renamed;
VersionArg Introduced, Deprecated, Obsoleted;
auto PlatformAgnostic = PlatformAgnosticAvailabilityKind::None;
SyntaxParsingContext AvailabilitySpecContext(
SyntaxContext, SyntaxKind::AvailabilitySpecList);
bool HasUpcomingEntry = false;
{
SyntaxParsingContext EntryContext(SyntaxContext,
SyntaxKind::AvailabilityArgument);
consumeToken();
if (consumeIf(tok::comma)) {
HasUpcomingEntry = true;
}
}
bool AnyAnnotations = false;
bool AnyArgumentInvalid = false;
int ParamIndex = 0;
while (HasUpcomingEntry) {
SyntaxParsingContext EntryContext(SyntaxContext,
SyntaxKind::AvailabilityArgument);
auto ArgumentLoc = Tok.getLoc();
AnyAnnotations = true;
StringRef ArgumentKindStr = Tok.getText();
ParamIndex++;
enum {
IsMessage, IsRenamed,
IsIntroduced, IsDeprecated, IsObsoleted,
IsUnavailable,
IsInvalid
} ArgumentKind = IsInvalid;
if (Tok.is(tok::identifier)) {
ArgumentKind =
llvm::StringSwitch<decltype(ArgumentKind)>(ArgumentKindStr)
.Case("message", IsMessage)
.Case("renamed", IsRenamed)
.Case("introduced", IsIntroduced)
.Case("deprecated", IsDeprecated)
.Case("obsoleted", IsObsoleted)
.Case("unavailable", IsUnavailable)
.Default(IsInvalid);
}
if (ArgumentKind == IsInvalid) {
diagnose(ArgumentLoc, diag::attr_availability_expected_option, AttrName)
.highlight(SourceRange(ArgumentLoc));
if (Tok.is(tok::code_complete) && CodeCompletion) {
CodeCompletion->completeDeclAttrParam(DAK_Available, ParamIndex);
consumeToken(tok::code_complete);
} else {
consumeIf(tok::identifier);
}
return nullptr;
}
consumeToken();
auto diagnoseDuplicate = [&](bool WasEmpty) {
if (!WasEmpty) {
diagnose(ArgumentLoc, diag::attr_availability_invalid_duplicate,
ArgumentKindStr);
}
};
switch (ArgumentKind) {
case IsMessage:
case IsRenamed: {
// Items with string arguments.
if (findAttrValueDelimiter()) {
consumeToken();
} else {
diagnose(Tok, diag::attr_availability_expected_equal, AttrName,
ArgumentKindStr);
AnyArgumentInvalid = true;
if (peekToken().isAny(tok::r_paren, tok::comma))
consumeToken();
break;
}
if (!Tok.is(tok::string_literal)) {
diagnose(AttrLoc, diag::attr_expected_string_literal, AttrName);
AnyArgumentInvalid = true;
if (peekToken().isAny(tok::r_paren, tok::comma))
consumeToken();
break;
}
auto Value = getStringLiteralIfNotInterpolated(
AttrLoc, ("'" + ArgumentKindStr + "'").str());
consumeToken();
if (!Value) {
AnyArgumentInvalid = true;
break;
}
if (ArgumentKind == IsMessage) {
diagnoseDuplicate(Message.empty());
Message = Value.getValue();
} else {
ParsedDeclName parsedName = parseDeclName(Value.getValue());
if (!parsedName) {
diagnose(AttrLoc, diag::attr_availability_invalid_renamed, AttrName);
AnyArgumentInvalid = true;
break;
}
diagnoseDuplicate(Renamed.empty());
Renamed = Value.getValue();
}
SyntaxContext->createNodeInPlace(SyntaxKind::AvailabilityLabeledArgument);
break;
}
case IsDeprecated:
if (!findAttrValueDelimiter()) {
if (PlatformAgnostic != PlatformAgnosticAvailabilityKind::None) {
diagnose(Tok, diag::attr_availability_unavailable_deprecated,
AttrName);
}
PlatformAgnostic = PlatformAgnosticAvailabilityKind::Deprecated;
break;
}
LLVM_FALLTHROUGH;
case IsIntroduced:
case IsObsoleted: {
// Items with version arguments.
SourceLoc DelimiterLoc;
if (findAttrValueDelimiter()) {
DelimiterLoc = Tok.getLoc();
consumeToken();
} else {
diagnose(Tok, diag::attr_availability_expected_equal, AttrName,
ArgumentKindStr);
AnyArgumentInvalid = true;
if (peekToken().isAny(tok::r_paren, tok::comma))
consumeToken();
break;
}
auto &VerArg =
(ArgumentKind == IsIntroduced)
? Introduced
: (ArgumentKind == IsDeprecated) ? Deprecated : Obsoleted;
bool VerArgWasEmpty = VerArg.empty();
if (parseVersionTuple(
VerArg.Version, VerArg.Range,
Diagnostic(diag::attr_availability_expected_version, AttrName))) {
AnyArgumentInvalid = true;
if (peekToken().isAny(tok::r_paren, tok::comma))
consumeToken();
}
VerArg.DelimiterLoc = DelimiterLoc;
diagnoseDuplicate(VerArgWasEmpty);
SyntaxContext->createNodeInPlace(SyntaxKind::AvailabilityLabeledArgument);
break;
}
case IsUnavailable:
if (PlatformAgnostic != PlatformAgnosticAvailabilityKind::None) {
diagnose(Tok, diag::attr_availability_unavailable_deprecated, AttrName);
}
PlatformAgnostic = PlatformAgnosticAvailabilityKind::Unavailable;
break;
case IsInvalid:
llvm_unreachable("handled above");
}
// Parse the trailing comma
if (consumeIf(tok::comma)) {
HasUpcomingEntry = true;
} else {
HasUpcomingEntry = false;
}
}
if (!AnyAnnotations) {
diagnose(Tok.getLoc(), diag::attr_expected_comma, AttrName,
/*isDeclModifier*/ false);
}
auto PlatformKind = platformFromString(Platform);
// Treat 'swift' as a valid version-qualifying token, when
// at least some versions were mentioned and no other
// platform-agnostic availability spec has been provided.
bool SomeVersion = (!Introduced.empty() ||
!Deprecated.empty() ||
!Obsoleted.empty());
if (!PlatformKind.hasValue() &&
(Platform == "swift" || Platform == "_PackageDescription")) {
if (PlatformAgnostic == PlatformAgnosticAvailabilityKind::Deprecated) {
diagnose(AttrLoc,
diag::attr_availability_platform_agnostic_expected_deprecated_version,
AttrName, Platform);
return nullptr;
}
if (PlatformAgnostic == PlatformAgnosticAvailabilityKind::Unavailable) {
diagnose(AttrLoc, diag::attr_availability_platform_agnostic_infeasible_option,
"unavailable", AttrName, Platform);
return nullptr;
}
assert(PlatformAgnostic == PlatformAgnosticAvailabilityKind::None);
if (!SomeVersion) {
diagnose(AttrLoc, diag::attr_availability_platform_agnostic_expected_option,
AttrName, Platform);
return nullptr;
}
PlatformKind = PlatformKind::none;
PlatformAgnostic = (Platform == "swift") ?
PlatformAgnosticAvailabilityKind::SwiftVersionSpecific :
PlatformAgnosticAvailabilityKind::PackageDescriptionVersionSpecific;
}
if (AnyArgumentInvalid)
return nullptr;
if (!PlatformKind.hasValue()) {
diagnose(AttrLoc, diag::attr_availability_unknown_platform,
Platform, AttrName);
return nullptr;
}
// Warn if any version is specified for non-specific platform '*'.
if (Platform == "*" && SomeVersion) {
auto diag = diagnose(AttrLoc,
diag::attr_availability_nonspecific_platform_unexpected_version,
AttrName);
if (!Introduced.empty())
diag.fixItRemove(SourceRange(Introduced.DelimiterLoc,
Introduced.Range.End));
if (!Deprecated.empty())
diag.fixItRemove(SourceRange(Deprecated.DelimiterLoc,
Deprecated.Range.End));
if (!Obsoleted.empty())
diag.fixItRemove(SourceRange(Obsoleted.DelimiterLoc,
Obsoleted.Range.End));
return nullptr;
}
auto Attr = new (Context)
AvailableAttr(AtLoc, SourceRange(AttrLoc, Tok.getLoc()),
PlatformKind.getValue(),
Message, Renamed,
Introduced.Version, Introduced.Range,
Deprecated.Version, Deprecated.Range,
Obsoleted.Version, Obsoleted.Range,
PlatformAgnostic,
/*Implicit=*/false);
return makeParserResult(Attr);
}
bool Parser::parseSpecializeAttributeArguments(
swift::tok ClosingBrace, bool &DiscardAttribute, Optional<bool> &Exported,
Optional<SpecializeAttr::SpecializationKind> &Kind,
swift::TrailingWhereClause *&TrailingWhereClause) {
SyntaxParsingContext ContentContext(SyntaxContext,
SyntaxKind::SpecializeAttributeSpecList);
// Parse optional "exported" and "kind" labeled parameters.
while (!Tok.is(tok::kw_where)) {
SyntaxParsingContext ArgumentContext(SyntaxContext,
SyntaxKind::LabeledSpecializeEntry);
if (Tok.is(tok::identifier)) {
auto ParamLabel = Tok.getText();
if (ParamLabel != "exported" && ParamLabel != "kind") {
diagnose(Tok.getLoc(), diag::attr_specialize_unknown_parameter_name,
ParamLabel);
}
consumeToken();
if (!consumeIf(tok::colon)) {
diagnose(Tok.getLoc(), diag::attr_specialize_missing_colon, ParamLabel);
skipUntil(tok::comma, tok::kw_where);
if (Tok.is(ClosingBrace))
break;
if (Tok.is(tok::kw_where)) {
continue;
}
if (Tok.is(tok::comma)) {
consumeToken();
continue;
}
DiscardAttribute = true;
return false;
}
if ((ParamLabel == "exported" && Exported.hasValue()) ||
(ParamLabel == "kind" && Kind.hasValue())) {
diagnose(Tok.getLoc(), diag::attr_specialize_parameter_already_defined,
ParamLabel);
}
if (ParamLabel == "exported") {
bool isTrue = consumeIf(tok::kw_true);
bool isFalse = consumeIf(tok::kw_false);
if (!isTrue && !isFalse) {
diagnose(Tok.getLoc(), diag::attr_specialize_expected_bool_value);
skipUntil(tok::comma, tok::kw_where);
if (Tok.is(ClosingBrace))
break;
if (Tok.is(tok::kw_where)) {
continue;
}
if (Tok.is(tok::comma)) {
consumeToken();
continue;
}
DiscardAttribute = true;
return false;
}
if (ParamLabel == "exported") {
Exported = isTrue;
}
}
if (ParamLabel == "kind") {
SourceLoc paramValueLoc;
if (Tok.is(tok::identifier)) {
if (Tok.getText() == "partial") {
Kind = SpecializeAttr::SpecializationKind::Partial;
} else if (Tok.getText() == "full") {
Kind = SpecializeAttr::SpecializationKind::Full;
} else {
diagnose(Tok.getLoc(),
diag::attr_specialize_expected_partial_or_full);
}
consumeToken();
} else if (consumeIf(tok::kw_true, paramValueLoc) ||
consumeIf(tok::kw_false, paramValueLoc)) {
diagnose(paramValueLoc,
diag::attr_specialize_expected_partial_or_full);
}
}
if (!consumeIf(tok::comma)) {
diagnose(Tok.getLoc(), diag::attr_specialize_missing_comma);
skipUntil(tok::comma, tok::kw_where);
if (Tok.is(ClosingBrace))
break;
if (Tok.is(tok::kw_where)) {
continue;
}
if (Tok.is(tok::comma)) {
consumeToken();
continue;
}
DiscardAttribute = true;
return false;
}
continue;
}
diagnose(Tok.getLoc(),
diag::attr_specialize_missing_parameter_label_or_where_clause);
DiscardAttribute = true;
return false;
};
// Parse the where clause.
if (Tok.is(tok::kw_where)) {
SourceLoc whereLoc;
SmallVector<RequirementRepr, 4> requirements;
bool firstTypeInComplete;
parseGenericWhereClause(whereLoc, requirements, firstTypeInComplete,
/* AllowLayoutConstraints */ true);
TrailingWhereClause =
TrailingWhereClause::create(Context, whereLoc, requirements);
}
return true;
}
bool Parser::parseSpecializeAttribute(swift::tok ClosingBrace, SourceLoc AtLoc,
SourceLoc Loc, SpecializeAttr *&Attr) {
assert(ClosingBrace == tok::r_paren || ClosingBrace == tok::r_square);
SourceLoc lParenLoc = consumeToken();
bool DiscardAttribute = false;
StringRef AttrName = "_specialize";
Optional<bool> exported;
Optional<SpecializeAttr::SpecializationKind> kind;
TrailingWhereClause *trailingWhereClause = nullptr;
if (!parseSpecializeAttributeArguments(ClosingBrace, DiscardAttribute,
exported, kind, trailingWhereClause)) {
return false;
}
// Parse the closing ')' or ']'.
SourceLoc rParenLoc;
if (!consumeIf(ClosingBrace, rParenLoc)) {
if (ClosingBrace == tok::r_paren)
diagnose(lParenLoc, diag::attr_expected_rparen, AttrName,
/*DeclModifier=*/false);
else if (ClosingBrace == tok::r_square)
diagnose(lParenLoc, diag::attr_expected_rparen, AttrName,
/*DeclModifier=*/false);
return false;
}
// Not exported by default.
if (!exported.hasValue())
exported = false;
// Full specialization by default.
if (!kind.hasValue())
kind = SpecializeAttr::SpecializationKind::Full;
if (DiscardAttribute) {
Attr = nullptr;
return false;
}
// Store the attribute.
Attr = SpecializeAttr::create(Context, AtLoc, SourceRange(Loc, rParenLoc),
trailingWhereClause, exported.getValue(),
kind.getValue());
return true;
}
ParserResult<ImplementsAttr>
Parser::parseImplementsAttribute(SourceLoc AtLoc, SourceLoc Loc) {
StringRef AttrName = "_implements";
ParserStatus Status;
if (Tok.isNot(tok::l_paren)) {
diagnose(Loc, diag::attr_expected_lparen, AttrName,
/*DeclModifier=*/false);
Status.setIsParseError();
return Status;
}
SourceLoc lParenLoc = consumeToken();
DeclNameLoc MemberNameLoc;
DeclNameRef MemberName;
ParserResult<TypeRepr> ProtocolType;
{
SyntaxParsingContext ContentContext(
SyntaxContext, SyntaxKind::ImplementsAttributeArguments);
ProtocolType = parseType();
Status |= ProtocolType;
if (!(Status.shouldStopParsing() || consumeIf(tok::comma))) {
diagnose(Tok.getLoc(), diag::attr_expected_comma, AttrName,
/*DeclModifier=*/false);
Status.setIsParseError();
}
if (!Status.shouldStopParsing()) {
MemberName = parseDeclNameRef(MemberNameLoc,
diag::attr_implements_expected_member_name,
DeclNameFlag::AllowZeroArgCompoundNames |
DeclNameFlag::AllowOperators);
if (!MemberName) {
Status.setIsParseError();
}
}
}
if (Status.isError()) {
skipUntil(tok::r_paren);
}
SourceLoc rParenLoc;
if (!consumeIf(tok::r_paren, rParenLoc)) {
diagnose(lParenLoc, diag::attr_expected_rparen, AttrName,
/*DeclModifier=*/false);
Status.setIsParseError();
}
if (Status.isError()) {
return Status;
}
// FIXME(ModQual): Reject module qualification on MemberName.
return ParserResult<ImplementsAttr>(
ImplementsAttr::create(Context, AtLoc, SourceRange(Loc, rParenLoc),
ProtocolType.get(), MemberName.getFullName(),
MemberNameLoc));
}
/// Parse a `@differentiable` attribute, returning true on error.
///
/// \verbatim
/// differentiable-attribute-arguments:
/// '(' (differentiability-params-clause ',')?
/// where-clause?
/// ')'
/// \endverbatim
ParserResult<DifferentiableAttr>
Parser::parseDifferentiableAttribute(SourceLoc atLoc, SourceLoc loc) {
StringRef AttrName = "differentiable";
SourceLoc lParenLoc = loc, rParenLoc = loc;
bool linear = false;
SmallVector<ParsedAutoDiffParameter, 8> parameters;
TrailingWhereClause *whereClause = nullptr;
// Parse '('.
if (consumeIf(tok::l_paren, lParenLoc)) {
// Parse @differentiable attribute arguments.
if (parseDifferentiableAttributeArguments(linear, parameters, whereClause))
return makeParserError();
// Parse ')'.
if (!consumeIf(tok::r_paren, rParenLoc)) {
diagnose(getEndOfPreviousLoc(), diag::attr_expected_rparen, AttrName,
/*DeclModifier=*/false);
return makeParserError();
}
}
return ParserResult<DifferentiableAttr>(DifferentiableAttr::create(
Context, /*implicit*/ false, atLoc, SourceRange(loc, rParenLoc), linear,
parameters, whereClause));
}
// Attribute parsing error helper.
// For the given parentheses depth, skip until ')' and consume it if possible.
// If no ')' is found, produce error.
// Always returns true to indicate a parsing error has occurred.
static bool errorAndSkipUntilConsumeRightParen(Parser &P, StringRef attrName,
int parenDepth = 1) {
for (int i = 0; i < parenDepth; ++i) {
P.skipUntil(tok::r_paren);
if (!P.consumeIf(tok::r_paren)) {
P.diagnose(P.Tok, diag::attr_expected_rparen, attrName,
/*DeclModifier=*/false);
return true;
}
}
return true;
};
/// Parse a differentiability parameters 'wrt:' clause, returning true on error.
/// If `allowNamedParameters` is false, allow only index parameters and 'self'.
///
/// \verbatim
/// differentiability-params-clause:
/// 'wrt' ':' (differentiability-param | differentiability-params)
/// differentiability-params:
/// '(' differentiability-param (',' differentiability-param)* ')'
/// differentiability-param:
/// 'self' | identifier | [0-9]+
/// \endverbatim
bool Parser::parseDifferentiabilityParametersClause(
SmallVectorImpl<ParsedAutoDiffParameter> ¶meters, StringRef attrName,
bool allowNamedParameters) {
SyntaxParsingContext DiffParamsClauseContext(
SyntaxContext, SyntaxKind::DifferentiationParamsClause);
consumeToken(tok::identifier);
if (!consumeIf(tok::colon)) {
diagnose(Tok, diag::expected_colon_after_label, "wrt");
return errorAndSkipUntilConsumeRightParen(*this, attrName);
}
// Function that parses a parameter into `parameters`. Returns true if error
// occurred.
auto parseParam = [&](bool parseTrailingComma = true) -> bool {
SyntaxParsingContext DiffParamContext(
SyntaxContext, SyntaxKind::DifferentiationParam);
SourceLoc paramLoc;
switch (Tok.getKind()) {
case tok::identifier: {
// If named parameters are not allowed, diagnose.
if (!allowNamedParameters) {
diagnose(Tok, diag::diff_params_clause_expected_parameter_unnamed);
return true;
}
Identifier paramName;
if (parseIdentifier(paramName, paramLoc,
diag::diff_params_clause_expected_parameter))
return true;
parameters.push_back(
ParsedAutoDiffParameter::getNamedParameter(paramLoc, paramName));
break;
}
case tok::integer_literal: {
unsigned paramNum;
if (parseUnsignedInteger(
paramNum, paramLoc,
diag::diff_params_clause_expected_parameter))
return true;
parameters.push_back(
ParsedAutoDiffParameter::getOrderedParameter(paramLoc, paramNum));
break;
}
case tok::kw_self: {
paramLoc = consumeToken(tok::kw_self);
parameters.push_back(ParsedAutoDiffParameter::getSelfParameter(paramLoc));
break;
}
default:
diagnose(Tok, diag::diff_params_clause_expected_parameter);
return true;
}
if (parseTrailingComma && Tok.isNot(tok::r_paren))
return parseToken(tok::comma, diag::attr_expected_comma, attrName,
/*isDeclModifier=*/false);
return false;
};
// Parse opening '(' of the parameter list.
if (Tok.is(tok::l_paren)) {
SyntaxParsingContext DiffParamsContext(
SyntaxContext, SyntaxKind::DifferentiationParams);
consumeToken(tok::l_paren);
// Parse first parameter. At least one is required.
if (parseParam())
return errorAndSkipUntilConsumeRightParen(*this, attrName, 2);
// Parse remaining parameters until ')'.
while (Tok.isNot(tok::r_paren))
if (parseParam())
return errorAndSkipUntilConsumeRightParen(*this, attrName, 2);
SyntaxContext->collectNodesInPlace(SyntaxKind::DifferentiationParamList);
// Parse closing ')' of the parameter list.
consumeToken(tok::r_paren);
}
// If no opening '(' for parameter list, parse a single parameter.
else {
if (parseParam(/*parseTrailingComma*/ false))
return errorAndSkipUntilConsumeRightParen(*this, attrName);
}
return false;
}
bool Parser::parseDifferentiableAttributeArguments(
bool &linear, SmallVectorImpl<ParsedAutoDiffParameter> ¶meters,
TrailingWhereClause *&whereClause) {
StringRef AttrName = "differentiable";
// Parse trailing comma, if it exists, and check for errors.
auto consumeIfTrailingComma = [&]() -> bool {
if (!consumeIf(tok::comma)) return false;
// Diagnose trailing comma before 'where' or ')'.
if (Tok.is(tok::kw_where) || Tok.is(tok::r_paren)) {
diagnose(Tok, diag::unexpected_separator, ",");
return true;
}
// Check that token after comma is 'wrt'.
if (isIdentifier(Tok, "wrt")) {
return false;
}
diagnose(Tok, diag::attr_differentiable_expected_label);
return true;
};
// Store starting parser position.
auto startingLoc = Tok.getLoc();
SyntaxParsingContext ContentContext(
SyntaxContext, SyntaxKind::DifferentiableAttributeArguments);
// Parse optional differentiability parameters.
// Parse 'linear' label (optional).
linear = false;
if (isIdentifier(Tok, "linear")) {
linear = true;
consumeToken(tok::identifier);
// If no trailing comma or 'where' clause, terminate parsing arguments.
if (Tok.isNot(tok::comma, tok::kw_where))
return false;
if (consumeIfTrailingComma())
return errorAndSkipUntilConsumeRightParen(*this, AttrName);
}
// If 'withRespectTo' is used, make the user change it to 'wrt'.
if (isIdentifier(Tok, "withRespectTo")) {
SourceRange withRespectToRange(Tok.getLoc(), peekToken().getLoc());
diagnose(Tok, diag::attr_differentiable_use_wrt_not_withrespectto)
.highlight(withRespectToRange)