Skip to content

[libSyntax] Support parsing several type kinds #13143

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Nov 30, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 6 additions & 4 deletions include/swift/Parse/Parser.h
Original file line number Diff line number Diff line change
Expand Up @@ -963,11 +963,13 @@ class Parser {
/// type-simple:
/// '[' type ']'
/// '[' type ':' type ']'
ParserResult<TypeRepr> parseTypeCollection();
ParserResult<OptionalTypeRepr> parseTypeOptional(TypeRepr *Base);
SyntaxParserResult<syntax::TypeSyntax, TypeRepr> parseTypeCollection();

ParserResult<ImplicitlyUnwrappedOptionalTypeRepr>
parseTypeImplicitlyUnwrappedOptional(TypeRepr *Base);
SyntaxParserResult<syntax::TypeSyntax, OptionalTypeRepr>
parseTypeOptional(TypeRepr *Base);

SyntaxParserResult<syntax::TypeSyntax, ImplicitlyUnwrappedOptionalTypeRepr>
parseTypeImplicitlyUnwrappedOptional(TypeRepr *Base);

bool isOptionalToken(const Token &T) const;
SourceLoc consumeOptionalToken();
Expand Down
2 changes: 2 additions & 0 deletions include/swift/Parse/SyntaxParserResult.h
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@ template <typename Syntax, typename AST> class SyntaxParserResult {
public:
SyntaxParserResult(std::nullptr_t = nullptr)
: SyntaxNode(None), ASTResult(nullptr) {}
SyntaxParserResult(ParserStatus Status)
: SyntaxNode(None), ASTResult(Status) {}
SyntaxParserResult(llvm::Optional<Syntax> SyntaxNode, AST *ASTNode)
: SyntaxNode(SyntaxNode), ASTResult(ASTNode) {}
SyntaxParserResult(ParserStatus Status, llvm::Optional<Syntax> SyntaxNode,
Expand Down
126 changes: 96 additions & 30 deletions lib/Parse/ParseType.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -215,9 +215,13 @@ ParserResult<TypeRepr> Parser::parseTypeSimple(Diag<> MessageID,
// Eat the code completion token because we handled it.
consumeToken(tok::code_complete);
return makeParserCodeCompletionResult<TypeRepr>();
case tok::l_square:
ty = parseTypeCollection();
case tok::l_square: {
auto Result = parseTypeCollection();
if (Result.hasSyntax())
SyntaxContext->addSyntax(Result.getSyntax());
ty = Result.getASTResult();
break;
}
case tok::kw_protocol:
if (startsWithLess(peekToken())) {
ty = parseOldStyleProtocolComposition();
Expand All @@ -240,6 +244,17 @@ ParserResult<TypeRepr> Parser::parseTypeSimple(Diag<> MessageID,
checkForInputIncomplete();
return nullptr;
}

auto makeMetatypeTypeSyntax = [&]() {
if (!SyntaxContext->isEnabled())
return;
MetatypeTypeSyntaxBuilder Builder;
Builder
.useTypeOrProtocol(SyntaxContext->popToken())
.usePeriod(SyntaxContext->popToken())
.useBaseType(SyntaxContext->popIf<TypeSyntax>().getValue());
SyntaxContext->addSyntax(Builder.build());
};

// '.Type', '.Protocol', '?', '!', and '[]' still leave us with type-simple.
while (ty.isNonNull()) {
Expand All @@ -249,24 +264,32 @@ ParserResult<TypeRepr> Parser::parseTypeSimple(Diag<> MessageID,
SourceLoc metatypeLoc = consumeToken(tok::identifier);
ty = makeParserResult(ty,
new (Context) MetatypeTypeRepr(ty.get(), metatypeLoc));
makeMetatypeTypeSyntax();
continue;
}
if (peekToken().isContextualKeyword("Protocol")) {
consumeToken();
SourceLoc protocolLoc = consumeToken(tok::identifier);
ty = makeParserResult(ty,
new (Context) ProtocolTypeRepr(ty.get(), protocolLoc));
makeMetatypeTypeSyntax();
continue;
}
}

if (!Tok.isAtStartOfLine()) {
if (isOptionalToken(Tok)) {
ty = parseTypeOptional(ty.get());
auto Result = parseTypeOptional(ty.get());
if (Result.hasSyntax())
SyntaxContext->addSyntax(Result.getSyntax());
ty = Result.getASTResult();
continue;
}
if (isImplicitlyUnwrappedOptionalToken(Tok)) {
ty = parseTypeImplicitlyUnwrappedOptional(ty.get());
auto Result = parseTypeImplicitlyUnwrappedOptional(ty.get());
if (Result.hasSyntax())
SyntaxContext->addSyntax(Result.getSyntax());
ty = Result.getASTResult();
continue;
}
// Parse legacy array types for migration.
Expand Down Expand Up @@ -730,6 +753,7 @@ Parser::parseAnyType() {
/// type-identifier
/// type-composition-list-deprecated ',' type-identifier
ParserResult<TypeRepr> Parser::parseOldStyleProtocolComposition() {
SyntaxParsingContext TypeContext(SyntaxContext, SyntaxContextKind::Type);
assert(Tok.is(tok::kw_protocol) && startsWithLess(peekToken()));

// Start a context for creating type syntax.
Expand Down Expand Up @@ -839,6 +863,7 @@ ParserResult<TypeRepr> Parser::parseOldStyleProtocolComposition() {
/// identifier ':' type
/// type
ParserResult<TupleTypeRepr> Parser::parseTypeTupleBody() {
SyntaxParsingContext TypeContext(SyntaxContext, SyntaxContextKind::Type);
Parser::StructureMarkerRAII ParsingTypeTuple(*this, Tok);
SourceLoc RPLoc, LPLoc = consumeToken(tok::l_paren);
SourceLoc EllipsisLoc;
Expand Down Expand Up @@ -1051,14 +1076,16 @@ ParserResult<TypeRepr> Parser::parseTypeArray(TypeRepr *Base) {
return makeParserResult(ATR);
}

ParserResult<TypeRepr> Parser::parseTypeCollection() {
SyntaxParserResult<TypeSyntax, TypeRepr> Parser::parseTypeCollection() {
ParserStatus Status;
// Parse the leading '['.
assert(Tok.is(tok::l_square));
Parser::StructureMarkerRAII parsingCollection(*this, Tok);
SourceLoc lsquareLoc = consumeToken();

// Parse the element type.
ParserResult<TypeRepr> firstTy = parseType(diag::expected_element_type);
Status |= firstTy;

// If there is a ':', this is a dictionary type.
SourceLoc colonLoc;
Expand All @@ -1068,36 +1095,57 @@ ParserResult<TypeRepr> Parser::parseTypeCollection() {

// Parse the second type.
secondTy = parseType(diag::expected_dictionary_value_type);
Status |= secondTy;
}

// Parse the closing ']'.
SourceLoc rsquareLoc;
parseMatchingToken(tok::r_square, rsquareLoc,
colonLoc.isValid()
? diag::expected_rbracket_dictionary_type
: diag::expected_rbracket_array_type,
lsquareLoc);
if (parseMatchingToken(tok::r_square, rsquareLoc,
colonLoc.isValid()
? diag::expected_rbracket_dictionary_type
: diag::expected_rbracket_array_type,
lsquareLoc))
Status.setIsParseError();

if (firstTy.hasCodeCompletion() || secondTy.hasCodeCompletion())
return makeParserCodeCompletionStatus();
if (Status.hasCodeCompletion())
return Status;

// If we couldn't parse anything for one of the types, propagate the error.
if (firstTy.isNull() || (colonLoc.isValid() && secondTy.isNull()))
if (Status.isError())
return makeParserError();

// Form the dictionary type.
TypeRepr *TyR;
llvm::Optional<TypeSyntax> SyntaxNode;

SourceRange brackets(lsquareLoc, rsquareLoc);
if (colonLoc.isValid())
return makeParserResult(ParserStatus(firstTy) | ParserStatus(secondTy),
new (Context) DictionaryTypeRepr(firstTy.get(),
secondTy.get(),
colonLoc,
brackets));
if (colonLoc.isValid()) {
// Form the dictionary type.
TyR = new (Context)
DictionaryTypeRepr(firstTy.get(), secondTy.get(), colonLoc, brackets);
if (SyntaxContext->isEnabled()) {
DictionaryTypeSyntaxBuilder Builder;
Builder
.useRightSquareBracket(SyntaxContext->popToken())
.useValueType(SyntaxContext->popIf<TypeSyntax>().getValue())
.useColon(SyntaxContext->popToken())
.useKeyType(SyntaxContext->popIf<TypeSyntax>().getValue())
.useLeftSquareBracket(SyntaxContext->popToken());
SyntaxNode.emplace(Builder.build());
}
} else {
// Form the array type.
TyR = new (Context) ArrayTypeRepr(firstTy.get(), brackets);
if (SyntaxContext->isEnabled()) {
ArrayTypeSyntaxBuilder Builder;
Builder
.useRightSquareBracket(SyntaxContext->popToken())
.useElementType(SyntaxContext->popIf<TypeSyntax>().getValue())
.useLeftSquareBracket(SyntaxContext->popToken());
SyntaxNode.emplace(Builder.build());
}
}

// Form the array type.
return makeParserResult(firstTy,
new (Context) ArrayTypeRepr(firstTy.get(),
brackets));
return makeSyntaxResult(Status, SyntaxNode, TyR);
}

bool Parser::isOptionalToken(const Token &T) const {
Expand Down Expand Up @@ -1142,19 +1190,37 @@ SourceLoc Parser::consumeImplicitlyUnwrappedOptionalToken() {

/// Parse a single optional suffix, given that we are looking at the
/// question mark.
ParserResult<OptionalTypeRepr> Parser::parseTypeOptional(TypeRepr *base) {
SyntaxParserResult<TypeSyntax, OptionalTypeRepr>
Parser::parseTypeOptional(TypeRepr *base) {
SourceLoc questionLoc = consumeOptionalToken();
return makeParserResult(new (Context) OptionalTypeRepr(base, questionLoc));
auto TyR = new (Context) OptionalTypeRepr(base, questionLoc);
llvm::Optional<TypeSyntax> SyntaxNode;
if (SyntaxContext->isEnabled()) {
OptionalTypeSyntaxBuilder Builder;
Builder
.useQuestionMark(SyntaxContext->popToken())
.useWrappedType(SyntaxContext->popIf<TypeSyntax>().getValue());
SyntaxNode.emplace(Builder.build());
}
return makeSyntaxResult(SyntaxNode, TyR);
}

/// Parse a single implicitly unwrapped optional suffix, given that we
/// are looking at the exclamation mark.
ParserResult<ImplicitlyUnwrappedOptionalTypeRepr>
SyntaxParserResult<TypeSyntax, ImplicitlyUnwrappedOptionalTypeRepr>
Parser::parseTypeImplicitlyUnwrappedOptional(TypeRepr *base) {
SourceLoc exclamationLoc = consumeImplicitlyUnwrappedOptionalToken();
return makeParserResult(
new (Context) ImplicitlyUnwrappedOptionalTypeRepr(
base, exclamationLoc));
auto TyR =
new (Context) ImplicitlyUnwrappedOptionalTypeRepr(base, exclamationLoc);
llvm::Optional<TypeSyntax> SyntaxNode;
if (SyntaxContext->isEnabled()) {
ImplicitlyUnwrappedOptionalTypeSyntaxBuilder Builder;
Builder
.useExclamationMark(SyntaxContext->popToken())
.useWrappedType(SyntaxContext->popIf<TypeSyntax>().getValue());
SyntaxNode.emplace(Builder.build());
}
return makeSyntaxResult(SyntaxNode, TyR);
}

//===----------------------------------------------------------------------===//
Expand Down
4 changes: 4 additions & 0 deletions test/Syntax/Outputs/round_trip_parse_gen.swift.withkinds
Original file line number Diff line number Diff line change
Expand Up @@ -58,3 +58,7 @@ class C {

typealias A = <SimpleTypeIdentifier>Any</SimpleTypeIdentifier>
typealias B = (<MemberTypeIdentifier><SimpleTypeIdentifier>Array<GenericArgumentClause><<GenericArgument><SimpleTypeIdentifier>Array<GenericArgumentClause><<GenericArgument><SimpleTypeIdentifier>Any</SimpleTypeIdentifier></GenericArgument>></GenericArgumentClause></SimpleTypeIdentifier></GenericArgument>></GenericArgumentClause></SimpleTypeIdentifier>.Element</MemberTypeIdentifier>)
typealias C = <ArrayType>[<SimpleTypeIdentifier>Int</SimpleTypeIdentifier>]</ArrayType>
typealias D = <DictionaryType>[<SimpleTypeIdentifier>Int</SimpleTypeIdentifier>: <SimpleTypeIdentifier>String</SimpleTypeIdentifier>]</DictionaryType>
typealias E = <MetatypeType><OptionalType><SimpleTypeIdentifier>Int</SimpleTypeIdentifier>?</OptionalType>.Protocol</MetatypeType>
typealias F = <MetatypeType><ImplicitlyUnwrappedOptionalType><ArrayType>[<SimpleTypeIdentifier>Int</SimpleTypeIdentifier>]</ArrayType>!</ImplicitlyUnwrappedOptionalType>.Type</MetatypeType>
4 changes: 4 additions & 0 deletions test/Syntax/round_trip_parse_gen.swift
Original file line number Diff line number Diff line change
Expand Up @@ -58,3 +58,7 @@ class C {

typealias A = Any
typealias B = (Array<Array<Any>>.Element)
typealias C = [Int]
typealias D = [Int: String]
typealias E = Int?.Protocol
typealias F = [Int]!.Type
4 changes: 2 additions & 2 deletions unittests/Syntax/TypeSyntaxTests.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -313,7 +313,7 @@ TEST(TypeSyntaxTests, OptionalTypeWithAPIs) {
auto StringType = SyntaxFactory::makeTypeIdentifier("String",
Trivia::spaces(1), {});
SyntaxFactory::makeBlankOptionalType()
.withValueType(StringType)
.withWrappedType(StringType)
.withQuestionMark(SyntaxFactory::makePostfixQuestionMarkToken({}, {}))
.print(OS);
ASSERT_EQ(OS.str(), " String?");
Expand Down Expand Up @@ -341,7 +341,7 @@ TEST(TypeSyntaxTests, ImplicitlyUnwrappedOptionalTypeWithAPIs) {
{ Trivia::spaces(1) },
{});
SyntaxFactory::makeBlankImplicitlyUnwrappedOptionalType()
.withValueType(StringType)
.withWrappedType(StringType)
.withExclamationMark(SyntaxFactory::makeExclamationMarkToken({}, {}))
.print(OS);
ASSERT_EQ(OS.str(), " String!");
Expand Down
57 changes: 28 additions & 29 deletions utils/gyb_syntax_support/TypeNodes.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,23 @@
is_optional=True),
]),

# array-type -> '[' type ']'
Node('ArrayType', kind='Type',
children=[
Child('LeftSquareBracket', kind='LeftSquareBracketToken'),
Child('ElementType', kind='Type'),
Child('RightSquareBracket', kind='RightSquareBracketToken'),
]),

# dictionary-type -> '[' type ':' type ']'
Node('DictionaryType', kind='Type',
children=[
Child('LeftSquareBracket', kind='LeftSquareBracketToken'),
Child('KeyType', kind='Type'),
Child('Colon', kind='ColonToken'),
Child('ValueType', kind='Type'),
Child('RightSquareBracket', kind='RightSquareBracketToken'),
]),

# metatype-type -> type '.' 'Type'
# | type '.' 'Protocol
Expand All @@ -48,14 +65,18 @@
]),
]),

# dictionary-type -> '[' type ':' type ']'
Node('DictionaryType', kind='Type',
# optional-type -> type '?'
Node('OptionalType', kind='Type',
children=[
Child('LeftSquareBracket', kind='LeftSquareBracketToken'),
Child('KeyType', kind='Type'),
Child('Colon', kind='ColonToken'),
Child('ValueType', kind='Type'),
Child('RightSquareBracket', kind='RightSquareBracketToken'),
Child('WrappedType', kind='Type'),
Child('QuestionMark', kind='PostfixQuestionMarkToken'),
]),

# implicitly-unwrapped-optional-type -> type '!'
Node('ImplicitlyUnwrappedOptionalType', kind='Type',
children=[
Child('WrappedType', kind='Type'),
Child('ExclamationMark', kind='ExclamationMarkToken'),
]),

# throwing-specifier -> 'throws' | 'rethrows'
Expand Down Expand Up @@ -99,14 +120,6 @@
is_optional=True),
]),

# array-type -> '[' type ']'
Node('ArrayType', kind='Type',
children=[
Child('LeftSquareBracket', kind='LeftSquareBracketToken'),
Child('ElementType', kind='Type'),
Child('RightSquareBracket', kind='RightSquareBracketToken'),
]),

# type-annotation -> attribute-list 'inout'? type
Node('TypeAnnotation', kind='Syntax',
children=[
Expand All @@ -125,13 +138,6 @@
Node('TupleTypeElementList', kind='SyntaxCollection',
element='TupleTypeElement'),

# implicitly-unwrapped-optional-type -> type '!'
Node('ImplicitlyUnwrappedOptionalType', kind='Type',
children=[
Child('ValueType', kind='Type'),
Child('ExclamationMark', kind='ExclamationMarkToken'),
]),

# protocol-composition-element -> type-identifier '&'
Node('ProtocolCompositionElement', kind='Syntax',
children=[
Expand Down Expand Up @@ -177,13 +183,6 @@
is_optional=True),
]),

# optional-type -> type '?'
Node('OptionalType', kind='Type',
children=[
Child('ValueType', kind='Type'),
Child('QuestionMark', kind='PostfixQuestionMarkToken'),
]),

# function-type-argument-list -> function-type-argument
# function-type-argument-list?
Node('FunctionTypeArgumentList', kind='SyntaxCollection',
Expand Down