Skip to content

Commit 423bd6b

Browse files
committed
Revert "Revert "Merge pull request swiftlang#27416 from rintaro/syntaxparse-declassociatedtype""
This reverts commit fbc7c6c.
1 parent 3dbe39c commit 423bd6b

14 files changed

+446
-220
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"
@@ -46,6 +47,30 @@ class ASTGen {
4647

4748
SourceLoc generate(const syntax::TokenSyntax &Tok, const SourceLoc Loc);
4849

50+
SourceLoc generateIdentifierDeclName(const syntax::TokenSyntax &Tok,
51+
const SourceLoc, Identifier &Identifier);
52+
53+
public:
54+
//===--------------------------------------------------------------------===//
55+
// Decls.
56+
57+
Decl *generate(const syntax::DeclSyntax &Decl, const SourceLoc Loc);
58+
TypeDecl *generate(const syntax::AssociatedtypeDeclSyntax &Decl,
59+
const SourceLoc Loc);
60+
61+
TrailingWhereClause *generate(const syntax::GenericWhereClauseSyntax &syntax,
62+
const SourceLoc Loc);
63+
MutableArrayRef<TypeLoc>
64+
generate(const syntax::TypeInheritanceClauseSyntax &syntax,
65+
const SourceLoc Loc, bool allowClassRequirement);
66+
67+
private:
68+
DeclAttributes
69+
generateDeclAttributes(const syntax::DeclSyntax &D,
70+
const Optional<syntax::AttributeListSyntax> &attrs,
71+
const Optional<syntax::ModifierListSyntax> &modifiers,
72+
SourceLoc Loc, bool includeComments);
73+
4974
public:
5075
//===--------------------------------------------------------------------===//
5176
// Expressions.
@@ -100,6 +125,8 @@ class ASTGen {
100125
const SourceLoc Loc);
101126
TypeRepr *generate(const syntax::ImplicitlyUnwrappedOptionalTypeSyntax &Type,
102127
const SourceLoc Loc);
128+
TypeRepr *generate(const syntax::ClassRestrictionTypeSyntax &Type,
129+
const SourceLoc Loc);
103130
TypeRepr *generate(const syntax::CodeCompletionTypeSyntax &Type,
104131
const SourceLoc Loc);
105132
TypeRepr *generate(const syntax::UnknownTypeSyntax &Type,

include/swift/Parse/LibSyntaxGenerator.h

+4-3
Original file line numberDiff line numberDiff line change
@@ -38,13 +38,14 @@ 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

4545
auto Recorded = Recorder.recordToken(Kind, Range, LeadingTriviaPieces,
4646
TrailingTriviaPieces);
47-
auto Raw = static_cast<RawSyntax *>(Recorded.takeOpaqueNode());
47+
RC<RawSyntax> Raw{static_cast<RawSyntax *>(Recorded.takeOpaqueNode())};
48+
Raw->Release(); // -1 since it's transfer of ownership.
4849
return make<TokenSyntax>(Raw);
4950
}
5051

@@ -55,7 +56,7 @@ class LibSyntaxGenerator {
5556
auto Children = Node.getDeferredChildren();
5657

5758
auto Recorded = Recorder.recordRawSyntax(Kind, Children);
58-
RC<RawSyntax> Raw {static_cast<RawSyntax *>(Recorded.takeOpaqueNode()) };
59+
RC<RawSyntax> Raw{static_cast<RawSyntax *>(Recorded.takeOpaqueNode())};
5960
Raw->Release(); // -1 since it's transfer of ownership.
6061
return make<SyntaxNode>(Raw);
6162
}

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
@@ -14,6 +14,7 @@
1414
#include "swift/AST/TypeRepr.h"
1515
#include "swift/Basic/SourceManager.h"
1616

17+
#include "DebuggerContextChange.h"
1718
#include "swift/Basic/SourceManager.h"
1819
#include "swift/Parse/CodeCompletionCallbacks.h"
1920
#include "swift/Parse/Parser.h"
@@ -25,6 +26,132 @@ SourceLoc ASTGen::generate(const TokenSyntax &Tok, const SourceLoc Loc) {
2526
return advanceLocBegin(Loc, Tok);
2627
}
2728

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

395519
return generateSimpleOrMemberIdentifier(Type, Loc);
396520
}
@@ -450,6 +574,13 @@ TypeRepr *ASTGen::generate(const ImplicitlyUnwrappedOptionalTypeSyntax &Type,
450574
ImplicitlyUnwrappedOptionalTypeRepr(WrappedType, ExclamationLoc);
451575
}
452576

577+
TypeRepr *
578+
ASTGen::generate(const ClassRestrictionTypeSyntax &Type, const SourceLoc Loc) {
579+
auto classLoc = advanceLocBegin(Loc, Type);
580+
return new (Context)
581+
SimpleIdentTypeRepr(classLoc, Context.getIdentifier("AnyObject"));
582+
}
583+
453584
TypeRepr *ASTGen::generate(const CodeCompletionTypeSyntax &Type,
454585
const SourceLoc Loc) {
455586
auto base = Type.getBase();
@@ -594,7 +725,7 @@ GenericParamList *ASTGen::generate(const GenericParameterClauseSyntax &clause,
594725

595726
if (auto inherited = elem.getInheritedType()) {
596727
if (auto ty = generate(*inherited, Loc)) {
597-
SmallVector<TypeLoc, 1> constraints = {generate(*inherited, Loc)};
728+
SmallVector<TypeLoc, 1> constraints = {ty};
598729
param->setInherited(Context.AllocateCopy(constraints));
599730
}
600731
}

0 commit comments

Comments
 (0)