Skip to content

[5.9][Parse] Accept 'self' after 'each' #67232

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
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
4 changes: 4 additions & 0 deletions include/swift/AST/DiagnosticsParse.def
Original file line number Diff line number Diff line change
Expand Up @@ -1398,6 +1398,10 @@ ERROR(expected_expr_after_copy, none,
"expected expression after 'copy'", ())
ERROR(expected_expr_after_borrow, none,
"expected expression after '_borrow'", ())
ERROR(expected_expr_after_each, none,
"expected expression after 'each'", ())
ERROR(expected_expr_after_repeat, none,
"expected expression after 'repeat'", ())

WARNING(move_consume_final_spelling, none,
"'_move' has been renamed to 'consume', and the '_move' spelling will be removed shortly", ())
Expand Down
73 changes: 38 additions & 35 deletions lib/Parse/ParseExpr.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -465,6 +465,44 @@ ParserResult<Expr> Parser::parseExprSequenceElement(Diag<> message,
}
}

// '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);
Optional<Token> trySuffix;
Expand Down Expand Up @@ -546,19 +584,6 @@ ParserResult<Expr> Parser::parseExprUnary(Diag<> Message, bool isExprBasic) {
// First check to see if we have the start of a regex literal `/.../`.
tryLexRegexLiteral(/*forUnappliedOperator*/ false);

// 'repeat' as an expression prefix is a pack expansion expression.
if (Tok.is(tok::kw_repeat)) {
SourceLoc repeatLoc = consumeToken();
auto patternExpr = parseExpr(Message);
if (patternExpr.isNull())
return patternExpr;

auto *expansion =
PackExpansionExpr::create(Context, repeatLoc, patternExpr.get(),
/*genericEnv*/ nullptr);
return makeParserResult(expansion);
}

// Try parse an 'if' or 'switch' as an expression. 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
Expand Down Expand Up @@ -1703,28 +1728,6 @@ ParserResult<Expr> Parser::parseExprPrimary(Diag<> ID, bool isExprBasic) {
return makeParserResult(new (Context) UnresolvedPatternExpr(pattern));
}

// '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);
}

// 'each' followed by another identifier is a pack element expr.
if (Tok.isContextualKeyword("each") &&
peekToken().is(tok::identifier) &&
!peekToken().isAtStartOfLine()) {
SourceLoc loc = consumeToken();
ParserResult<Expr> ref = parseExpr(ID);
if (ref.isNull())
return ref;

auto *packRef = PackElementExpr::create(Context, loc, ref.get());
return makeParserResult(packRef);
}

LLVM_FALLTHROUGH;
}
case tok::kw_Self: // Self
Expand Down
65 changes: 65 additions & 0 deletions test/Interpreter/Inputs/variadic_generic_library.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
public struct Key: Hashable {
static var index = 0

public let id: Int

init() {
self.id = Self.index
Self.index += 1
}
}

public struct Variable<Value> {
public let key = Key()
}

public struct Bindings {
private var storage: [Key : Any] = [:]

public init<each T>(
_ value: repeat (Variable<each T>, each T)
) {
_ = (repeat storage[(each value).0.key] = (each value).1)
}
}

public protocol Expression<Result> {
associatedtype Result
func evaluate(_ bindings: Bindings) throws -> Result
}

public struct True: Expression {
public init() {}

public func evaluate(_ bindings: Bindings) throws -> Bool {
true
}
}

public struct Predicate<each Input> {
var variables: (repeat Variable<each Input>)
var expression: any Expression<Bool>

public init<Expr>(
builder: (repeat Variable<each Input>) -> Expr
) where Expr: Expression<Bool> {
self.variables = (repeat Variable<each Input>())
self.expression = builder(repeat each self.variables)
}

public func evaluate(
_ input: repeat each Input
) throws -> Bool {
return try expression.evaluate(
.init(repeat (each self.variables, each input))
)
}
}

extension Sequence {
public func filter(_ predicate: Predicate<Element>) throws -> [Element] {
try self.filter {
try predicate.evaluate($0)
}
}
}
52 changes: 52 additions & 0 deletions test/Interpreter/import_parameter_pack_library.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
// RUN: %empty-directory(%t)

// RUN: %target-build-swift-dylib(%t/%target-library-name(variadic_generic_library)) -Xfrontend -disable-availability-checking -enable-library-evolution %S/Inputs/variadic_generic_library.swift -emit-module -emit-module-path %t/variadic_generic_library.swiftmodule -module-name variadic_generic_library
// RUN: %target-codesign %t/%target-library-name(variadic_generic_library)

// RUN: %target-build-swift %s -Xfrontend -disable-availability-checking -lvariadic_generic_library -I %t -L %t -o %t/main %target-rpath(%t)
// RUN: %target-codesign %t/main

// RUN: %target-run %t/main %t/%target-library-name(variadic_generic_library)

// REQUIRES: executable_test

// UNSUPPORTED: use_os_stdlib
// UNSUPPORTED: back_deployment_runtime

import variadic_generic_library
import StdlibUnittest

var ImportParameterPackTests = TestSuite("ImportParameterPackTests")

ImportParameterPackTests.test("basic") {
let closure: (Variable<Int>) -> _ = { a in
True()
}

let predicate = Predicate.init(builder: closure)
let result = try! predicate.evaluate(1)
expectEqual(result, true)
}

ImportParameterPackTests.test("no inputs") {
let closure: () -> _ = {
True()
}

let predicate = Predicate.init(builder: closure)
let result = try! predicate.evaluate()
expectEqual(result, true)
}


ImportParameterPackTests.test("multi-input") {
let closure: (Variable<Int>, Variable<String>, Variable<Bool>) -> _ = { a, b, c in
True()
}

let predicate = Predicate<Int, String, Bool>(builder: closure)
let result = try! predicate.evaluate(1, "hello", true)
expectEqual(result, true)
}

runAllTests()
19 changes: 19 additions & 0 deletions test/Parse/type_parameter_packs_executable.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
// REQUIRES: executable_test
// RUN: %target-run-simple-swift

import StdlibUnittest

var suite = TestSuite("ParameterPackTestSuite")

suite.test("operator precedence") {
// Test 'a * each b + c' is parsed and operator-folded as '(a * (each b)) + c'
func _test<each T: Numeric>(args arg: repeat each T) -> (repeat each T) {
(repeat 2 * each arg + 3)
}

let result = _test(args: 12, 12.3)
expectEqual(result.0, 2 * 12 + 3)
expectEqual(result.1, 2 * 12.3 + 3)
}

runAllTests()