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
|
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2023 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
//
//===----------------------------------------------------------------------===//
// This test file has been translated from swift/test/Parse/foreach.swift
import XCTest
final class ForeachTests: ParserTestCase {
func testForeach1() {
assertParse(
"""
struct IntRange<Int> : Sequence, IteratorProtocol {
typealias Element = (Int, Int)
func next() -> (Int, Int)? {}
typealias Iterator = IntRange<Int>
func makeIterator() -> IntRange<Int> { return self }
}
"""
)
}
func testForeach2() {
// Simple foreach loop, using the variable in the body
assertParse(
"""
func for_each(r: Range<Int>, iir: IntRange<Int>) {
var sum = 0
for i in r {
sum = sum + i
}
}
"""
)
// Check scoping of variable introduced with foreach loop
// For-each loops with two variables and varying degrees of typedness
assertParse(
"""
func for_each(r: Range<Int>, iir: IntRange<Int>) {
var sum = 0
for (i, j) in iir {
sum = sum + i + j
}
}
"""
)
assertParse(
"""
func for_each(r: Range<Int>, iir: IntRange<Int>) {
var sum = 0
for (i, j) : (Int, Int) in iir {
sum = sum + i + j
}
}
"""
)
}
// Parse errors
func testForeach3() {
assertParse(
"""
func for_each(r: Range<Int>, iir: IntRange<Int>) {
var sum = 0
for i 1️⃣r {
}
}
""",
diagnostics: [
DiagnosticSpec(message: "expected 'in' in 'for' statement", fixIts: ["insert 'in'"])
],
fixedSource: """
func for_each(r: Range<Int>, iir: IntRange<Int>) {
var sum = 0
for i in r {
}
}
"""
)
assertParse(
"""
func for_each(r: Range<Int>, iir: IntRange<Int>) {
var sum = 0
for i in r 1️⃣sum = sum + i;2️⃣
}
""",
diagnostics: [
DiagnosticSpec(locationMarker: "1️⃣", message: "expected '{' in 'for' statement", fixIts: ["insert '{'"]),
DiagnosticSpec(locationMarker: "2️⃣", message: "expected '}' to end 'for' statement", fixIts: ["insert '}'"]),
],
fixedSource: """
func for_each(r: Range<Int>, iir: IntRange<Int>) {
var sum = 0
for i in r { sum = sum + i;
}
}
"""
)
}
}
|