Skip to content

Commit 9f1ce1b

Browse files
authored
Merge pull request #27301 from rintaro/syntaxparse-associatedtype
[SyntaxParse] Parse associatedtype decl
2 parents 2736d53 + fc8a2e6 commit 9f1ce1b

File tree

13 files changed

+438
-217
lines changed

13 files changed

+438
-217
lines changed

include/swift/Parse/ASTGen.h

+27
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@
1616
#include "swift/AST/ASTContext.h"
1717
#include "swift/AST/Decl.h"
1818
#include "swift/AST/Expr.h"
19+
#include "swift/AST/TypeRepr.h"
1920
#include "swift/Parse/PersistentParserState.h"
2021
#include "swift/Syntax/SyntaxNodes.h"
2122
#include "llvm/ADT/DenseMap.h"
@@ -43,6 +44,30 @@ class ASTGen {
4344

4445
SourceLoc generate(const syntax::TokenSyntax &Tok, const SourceLoc Loc);
4546

47+
SourceLoc generateIdentifierDeclName(const syntax::TokenSyntax &Tok,
48+
const SourceLoc, Identifier &Identifier);
49+
50+
public:
51+
//===--------------------------------------------------------------------===//
52+
// Decls.
53+
54+
Decl *generate(const syntax::DeclSyntax &Decl, const SourceLoc Loc);
55+
TypeDecl *generate(const syntax::AssociatedtypeDeclSyntax &Decl,
56+
const SourceLoc Loc);
57+
58+
TrailingWhereClause *generate(const syntax::GenericWhereClauseSyntax &syntax,
59+
const SourceLoc Loc);
60+
MutableArrayRef<TypeLoc>
61+
generate(const syntax::TypeInheritanceClauseSyntax &syntax,
62+
const SourceLoc Loc, bool allowClassRequirement);
63+
64+
private:
65+
DeclAttributes
66+
generateDeclAttributes(const syntax::DeclSyntax &D,
67+
const Optional<syntax::AttributeListSyntax> &attrs,
68+
const Optional<syntax::ModifierListSyntax> &modifiers,
69+
SourceLoc Loc, bool includeComments);
70+
4671
public:
4772
//===--------------------------------------------------------------------===//
4873
// Expressions.
@@ -97,6 +122,8 @@ class ASTGen {
97122
const SourceLoc Loc);
98123
TypeRepr *generate(const syntax::ImplicitlyUnwrappedOptionalTypeSyntax &Type,
99124
const SourceLoc Loc);
125+
TypeRepr *generate(const syntax::ClassRestrictionTypeSyntax &Type,
126+
const SourceLoc Loc);
100127
TypeRepr *generate(const syntax::CodeCompletionTypeSyntax &Type,
101128
const SourceLoc Loc);
102129
TypeRepr *generate(const syntax::UnknownTypeSyntax &Type,

include/swift/Parse/LibSyntaxGenerator.h

+1-1
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,7 @@ class LibSyntaxGenerator {
3838
assert(Node.isDeferredToken());
3939

4040
auto Kind = Node.getTokenKind();
41-
auto Range = Node.getDeferredTokenRangeWithTrivia();
41+
auto Range = Node.getDeferredTokenRange();
4242
auto LeadingTriviaPieces = Node.getDeferredLeadingTriviaPieces();
4343
auto TrailingTriviaPieces = Node.getDeferredTrailingTriviaPieces();
4444

include/swift/Parse/Parser.h

+15-4
Original file line numberDiff line numberDiff line change
@@ -1004,12 +1004,23 @@ class Parser {
10041004
bool delayParsingDeclList(SourceLoc LBLoc, SourceLoc &RBLoc,
10051005
IterableDeclContext *IDC);
10061006

1007+
ParsedSyntaxResult<ParsedTypeInheritanceClauseSyntax>
1008+
parseTypeInheritanceClauseSyntax(bool allowClassRequirement,
1009+
bool allowAnyObject);
1010+
1011+
ParsedSyntaxResult<ParsedDeclSyntax>
1012+
parseDeclAssociatedTypeSyntax(ParseDeclOptions flags,
1013+
Optional<ParsedAttributeListSyntax> attrs,
1014+
Optional<ParsedModifierListSyntax> modifiers);
1015+
10071016
ParserResult<TypeDecl> parseDeclTypeAlias(ParseDeclOptions Flags,
1008-
DeclAttributes &Attributes);
1017+
DeclAttributes &Attributes,
1018+
SourceLoc leadingLoc);
10091019

10101020
ParserResult<TypeDecl> parseDeclAssociatedType(ParseDeclOptions Flags,
1011-
DeclAttributes &Attributes);
1012-
1021+
DeclAttributes &Attributes,
1022+
SourceLoc leadingLoc);
1023+
10131024
/// Parse a #if ... #endif directive.
10141025
/// Delegate callback function to parse elements in the blocks.
10151026
ParserResult<IfConfigDecl> parseIfConfig(
@@ -1091,7 +1102,7 @@ class Parser {
10911102

10921103
ParserResult<ImportDecl> parseDeclImport(ParseDeclOptions Flags,
10931104
DeclAttributes &Attributes);
1094-
ParserStatus parseInheritance(SmallVectorImpl<TypeLoc> &Inherited,
1105+
ParserStatus parseInheritance(MutableArrayRef<TypeLoc> &Inherited,
10951106
bool allowClassRequirement,
10961107
bool allowAnyObject);
10971108
ParserStatus parseDeclItem(bool &PreviousHadSemi,

include/swift/Parse/SyntaxParsingContext.h

+21-10
Original file line numberDiff line numberDiff line change
@@ -279,17 +279,9 @@ class alignas(1 << SyntaxAlignInBits) SyntaxParsingContext {
279279
}
280280

281281
/// Returns the topmost Syntax node.
282-
template <typename SyntaxNode> SyntaxNode topNode() {
283-
ParsedRawSyntaxNode &TopNode = getStorage().back();
284-
if (TopNode.isRecorded()) {
285-
OpaqueSyntaxNode OpaqueNode = TopNode.getOpaqueNode();
286-
return getSyntaxCreator().getLibSyntaxNodeFor<SyntaxNode>(OpaqueNode);
287-
}
288-
return getSyntaxCreator().createNode<SyntaxNode>(TopNode.copyDeferred());
289-
}
282+
template <typename SyntaxNode> SyntaxNode topNode();
290283

291-
template <typename SyntaxNode>
292-
llvm::Optional<SyntaxNode> popIf() {
284+
template <typename SyntaxNode> llvm::Optional<SyntaxNode> popIf() {
293285
auto &Storage = getStorage();
294286
if (Storage.size() <= Offset)
295287
return llvm::None;
@@ -376,5 +368,24 @@ class alignas(1 << SyntaxAlignInBits) SyntaxParsingContext {
376368
"Only meant for use in the debugger");
377369
};
378370

371+
template <typename SyntaxNode>
372+
inline SyntaxNode SyntaxParsingContext::topNode() {
373+
ParsedRawSyntaxNode &TopNode = getStorage().back();
374+
if (TopNode.isRecorded()) {
375+
OpaqueSyntaxNode OpaqueNode = TopNode.getOpaqueNode();
376+
return getSyntaxCreator().getLibSyntaxNodeFor<SyntaxNode>(OpaqueNode);
377+
}
378+
return getSyntaxCreator().createNode<SyntaxNode>(TopNode.copyDeferred());
379+
}
380+
381+
template <> inline TokenSyntax SyntaxParsingContext::topNode<TokenSyntax>() {
382+
ParsedRawSyntaxNode &TopNode = getStorage().back();
383+
if (TopNode.isRecorded()) {
384+
OpaqueSyntaxNode OpaqueNode = TopNode.getOpaqueNode();
385+
return getSyntaxCreator().getLibSyntaxNodeFor<TokenSyntax>(OpaqueNode);
386+
}
387+
return getSyntaxCreator().createToken(TopNode.copyDeferred());
388+
}
389+
379390
} // namespace swift
380391
#endif // SWIFT_SYNTAX_PARSING_CONTEXT_H

include/swift/Syntax/Syntax.h

+1-1
Original file line numberDiff line numberDiff line change
@@ -83,7 +83,7 @@ class Syntax {
8383
SyntaxKind getKind() const;
8484

8585
/// Get the shared raw syntax.
86-
RC<RawSyntax> getRaw() const;
86+
const RC<RawSyntax> &getRaw() const;
8787

8888
/// Get an ID for this node that is stable across incremental parses
8989
SyntaxNodeId getId() const { return getRaw()->getId(); }

include/swift/Syntax/SyntaxData.h

+1-1
Original file line numberDiff line numberDiff line change
@@ -186,7 +186,7 @@ class SyntaxData final
186186
CursorIndex IndexInParent = 0);
187187

188188
/// Returns the raw syntax node for this syntax node.
189-
const RC<RawSyntax> getRaw() const {
189+
const RC<RawSyntax> &getRaw() const {
190190
return Raw;
191191
}
192192

lib/Parse/ASTGen.cpp

+137-6
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212

1313
#include "swift/Parse/ASTGen.h"
1414

15+
#include "DebuggerContextChange.h"
1516
#include "swift/Basic/SourceManager.h"
1617
#include "swift/Parse/CodeCompletionCallbacks.h"
1718
#include "swift/Parse/Parser.h"
@@ -23,6 +24,132 @@ SourceLoc ASTGen::generate(const TokenSyntax &Tok, const SourceLoc Loc) {
2324
return advanceLocBegin(Loc, Tok);
2425
}
2526

27+
SourceLoc ASTGen::generateIdentifierDeclName(const syntax::TokenSyntax &Tok,
28+
const SourceLoc Loc,
29+
Identifier &Id) {
30+
StringRef text;
31+
if (Tok.getText() == "Any")
32+
// Special handle 'Any' because we don't want to accidantaly declare 'Any'
33+
// type in any way.
34+
text = "#Any";
35+
else
36+
text = Tok.getIdentifierText();
37+
38+
Id = Context.getIdentifier(text);
39+
return advanceLocBegin(Loc, Tok);
40+
}
41+
42+
Decl *ASTGen::generate(const DeclSyntax &D, const SourceLoc Loc) {
43+
Decl *DeclAST = nullptr;
44+
45+
if (auto associatedTypeDecl = D.getAs<AssociatedtypeDeclSyntax>()) {
46+
DeclAST = generate(*associatedTypeDecl, Loc);
47+
} else {
48+
llvm_unreachable("unsupported decl kind");
49+
}
50+
51+
return DeclAST;
52+
}
53+
54+
DeclAttributes
55+
ASTGen::generateDeclAttributes(const DeclSyntax &D,
56+
const Optional<AttributeListSyntax> &attrs,
57+
const Optional<ModifierListSyntax> &modifiers,
58+
SourceLoc Loc, bool includeComments) {
59+
SourceLoc attrsLoc;
60+
if (attrs) {
61+
attrsLoc = advanceLocBegin(Loc, *attrs->getFirstToken());
62+
} else if (modifiers) {
63+
attrsLoc = advanceLocBegin(Loc, *modifiers->getFirstToken());
64+
} else {
65+
// We might have comment attributes.
66+
attrsLoc = advanceLocBegin(Loc, *D.getFirstToken());
67+
}
68+
if (hasDeclAttributes(attrsLoc))
69+
return getDeclAttributes(attrsLoc);
70+
return DeclAttributes();
71+
}
72+
73+
MutableArrayRef<TypeLoc>
74+
ASTGen::generate(const TypeInheritanceClauseSyntax &clause, SourceLoc Loc,
75+
bool allowClassRequirement) {
76+
SmallVector<TypeLoc, 2> inherited;
77+
78+
bool hasClass = false;
79+
for (const auto elem : clause.getInheritedTypeCollection()) {
80+
const auto &tySyntax = elem.getTypeName();
81+
if (tySyntax.is<ClassRestrictionTypeSyntax>()) {
82+
// Accept 'class' only if it's allowed and it's the first one.
83+
if (!allowClassRequirement || hasClass)
84+
continue;
85+
hasClass = true;
86+
}
87+
if (auto ty = generate(tySyntax, Loc))
88+
inherited.emplace_back(ty);
89+
}
90+
91+
return Context.AllocateCopy(inherited);
92+
}
93+
94+
TypeDecl *ASTGen::generate(const AssociatedtypeDeclSyntax &D,
95+
const SourceLoc Loc) {
96+
if (!isa<ProtocolDecl>(P.CurDeclContext)) {
97+
// This is already diagnosed in Parser.
98+
return nullptr;
99+
}
100+
101+
auto idToken = D.getIdentifier();
102+
if (idToken.isMissing())
103+
return nullptr;
104+
105+
auto keywordLoc = advanceLocBegin(Loc, D.getAssociatedtypeKeyword());
106+
auto name = Context.getIdentifier(idToken.getIdentifierText());
107+
auto nameLoc = advanceLocBegin(Loc, idToken);
108+
109+
DeclAttributes attrs =
110+
generateDeclAttributes(D, D.getAttributes(), D.getModifiers(), Loc, true);
111+
112+
DebuggerContextChange DCC(P, name, DeclKind::AssociatedType);
113+
114+
ArrayRef<TypeLoc> inherited;
115+
if (const auto inheritanceClause = D.getInheritanceClause())
116+
inherited =
117+
generate(*inheritanceClause, Loc, /*allowClassRequirement=*/true);
118+
119+
TypeRepr *defaultTy = nullptr;
120+
if (const auto init = D.getInitializer())
121+
defaultTy = generate(init->getValue(), Loc);
122+
123+
TrailingWhereClause *trailingWhere = nullptr;
124+
if (auto whereClause = D.getGenericWhereClause())
125+
trailingWhere = generate(*whereClause, Loc);
126+
127+
auto assocType = new (Context)
128+
AssociatedTypeDecl(P.CurDeclContext, keywordLoc, name, nameLoc, defaultTy,
129+
trailingWhere);
130+
assocType->getAttrs() = attrs;
131+
if (!inherited.empty())
132+
assocType->setInherited(Context.AllocateCopy(inherited));
133+
addToScope(assocType);
134+
return assocType;
135+
}
136+
137+
TrailingWhereClause *ASTGen::generate(const GenericWhereClauseSyntax &syntax,
138+
const SourceLoc Loc) {
139+
SourceLoc whereLoc = advanceLocBegin(Loc, syntax.getWhereKeyword());
140+
141+
SmallVector<RequirementRepr, 4> requirements;
142+
requirements.reserve(syntax.getRequirementList().size());
143+
for (auto elem : syntax.getRequirementList()) {
144+
if (auto req = generate(elem, Loc))
145+
requirements.push_back(*req);
146+
}
147+
148+
if (requirements.empty())
149+
return nullptr;
150+
return TrailingWhereClause::create(Context, whereLoc, requirements);
151+
}
152+
26153
Expr *ASTGen::generate(const IntegerLiteralExprSyntax &Expr,
27154
const SourceLoc Loc) {
28155
auto Digits = Expr.getDigits();
@@ -124,6 +251,8 @@ TypeRepr *ASTGen::generate(const TypeSyntax &Type, const SourceLoc Loc) {
124251
TypeAST = generate(*Unwrapped, Loc);
125252
else if (auto Attributed = Type.getAs<AttributedTypeSyntax>())
126253
TypeAST = generate(*Attributed, Loc);
254+
else if (auto ClassRestriction = Type.getAs<ClassRestrictionTypeSyntax>())
255+
TypeAST = generate(*ClassRestriction, Loc);
127256
else if (auto CompletionTy = Type.getAs<CodeCompletionTypeSyntax>())
128257
TypeAST = generate(*CompletionTy, Loc);
129258
else if (auto Unknown = Type.getAs<UnknownTypeSyntax>())
@@ -384,11 +513,6 @@ TypeRepr *ASTGen::generate(const SimpleTypeIdentifierSyntax &Type,
384513
auto AnyLoc = advanceLocBegin(Loc, Type.getName());
385514
return CompositionTypeRepr::createEmptyComposition(Context, AnyLoc);
386515
}
387-
if (Type.getName().getText() == "class") {
388-
auto classLoc = advanceLocBegin(Loc, Type.getName());
389-
return new (Context)
390-
SimpleIdentTypeRepr(classLoc, Context.getIdentifier("AnyObject"));
391-
}
392516

393517
return generateSimpleOrMemberIdentifier(Type, Loc);
394518
}
@@ -448,6 +572,13 @@ TypeRepr *ASTGen::generate(const ImplicitlyUnwrappedOptionalTypeSyntax &Type,
448572
ImplicitlyUnwrappedOptionalTypeRepr(WrappedType, ExclamationLoc);
449573
}
450574

575+
TypeRepr *
576+
ASTGen::generate(const ClassRestrictionTypeSyntax &Type, const SourceLoc Loc) {
577+
auto classLoc = advanceLocBegin(Loc, Type);
578+
return new (Context)
579+
SimpleIdentTypeRepr(classLoc, Context.getIdentifier("AnyObject"));
580+
}
581+
451582
TypeRepr *ASTGen::generate(const CodeCompletionTypeSyntax &Type,
452583
const SourceLoc Loc) {
453584
auto base = Type.getBase();
@@ -589,7 +720,7 @@ GenericParamList *ASTGen::generate(const GenericParameterClauseSyntax &clause,
589720

590721
if (auto inherited = elem.getInheritedType()) {
591722
if (auto ty = generate(*inherited, Loc)) {
592-
SmallVector<TypeLoc, 1> constraints = {generate(*inherited, Loc)};
723+
SmallVector<TypeLoc, 1> constraints = {ty};
593724
param->setInherited(Context.AllocateCopy(constraints));
594725
}
595726
}

0 commit comments

Comments
 (0)