Add test case for crash triggered in swift::DynamicSelfType::get(swift::Type, swift::ASTContext const&)

// RUN: not --crash %target-swift-frontend %s -parse

// Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing

if{func b:a protocol a{{}typealias d:d
func b->Self


// RUN: %target-run-simple-swift | FileCheck %s

import Foundation

let opaqueNil: COpaquePointer = nil
if opaqueNil == nil {
  println("ok opaqueNil == nil")
  // CHECK: ok opaqueNil == nil
}

let unsafeNil: UnsafePointer<Int> = nil
if unsafeNil == (nil as UnsafePointer<Int>) {
  println("ok unsafeNil == (nil as UnsafePointer<Int>)")
  // CHECK: ok unsafeNil == (nil as UnsafePointer<Int>)
}

let removed = NSFileManager.defaultManager().removeItemAtURL(NSURL(string:"/this/file/does/not/exist"), error:nil)
if !removed {
  println("ok !removed")
  // CHECK: ok !removed
}

var selNil: Selector = nil
if selNil == nil {
  println("ok selNil == nil")
  // CHECK: ok selNil == nil
}
selNil = nil
if selNil == nil {
  println("ok selNil == nil")
  // CHECK: ok selNil == nil
}

Add a test for != comparison of COpaquePointer and nil

// RUN: %target-run-simple-swift | FileCheck %s

import Foundation

let opaqueNil: COpaquePointer = nil
if opaqueNil == nil {
  println("ok opaqueNil == nil")
  // CHECK: ok opaqueNil == nil
}

if opaqueNil != nil {
} else {
  println("ok opaqueNil != nil is false")
  // CHECK: ok opaqueNil != nil is false
}

let unsafeNil: UnsafePointer<Int> = nil
if unsafeNil == (nil as UnsafePointer<Int>) {
  println("ok unsafeNil == (nil as UnsafePointer<Int>)")
  // CHECK: ok unsafeNil == (nil as UnsafePointer<Int>)
}

let removed = NSFileManager.defaultManager().removeItemAtURL(NSURL(string:"/this/file/does/not/exist"), error:nil)
if !removed {
  println("ok !removed")
  // CHECK: ok !removed
}

var selNil: Selector = nil
if selNil == nil {
  println("ok selNil == nil")
  // CHECK: ok selNil == nil
}
selNil = nil
if selNil == nil {
  println("ok selNil == nil")
  // CHECK: ok selNil == nil
}


/**
 * Question Link: https://leetcode.com/problems/count-primes/
 * Primary idea: Create a boolean array to determine prime or not,
 *               filter numbers are times of previous ones
 *
 * Time Complexity: O(n), Space Complexity: O(n)
 */

class CountPrimes {
    func countPrimes(_ n: Int) -> Int {
        guard n > 2 else {
            return 0
        }

        var isPrime = [Bool](repeating: true, count: n)

        for i in 2 ..< n {
            if isPrime[i] {
                for j in stride(from: 2 * i, to: n, by: i) {
                    isPrime[j] = false
                }
            }
        }

        var count = 1
        for i in stride(from: 3, to: n, by: 2) {
            count += isPrime[i] ? 1 : 0
        }

        return count
    }
}


Add a flag to enable library-style parsing/name-binding. Add a test for library-style parsing.

// RUN: %swift %s -parse-as-library -verify

// Name lookup is global in a library.
var x : x_ty
typealias x_ty : Int

// Name lookup is global in a library.
// This case requires doing semantic analysis (conversion checking) after
// parsing.
var y : y_ty = 4
typealias y_ty : (Int)

// Verify that never-defined types are caught.
var z : z_ty  // expected-error {{use of undeclared type 'z_ty'}}


// Copyright (c) 2014 - 2017 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
//
//===----------------------------------------------------------------------===//
//
// RUN: %empty-directory(%t)
// RUN: %target-build-swift -swift-version 4 %s -o %t/TestData_Swift4
// RUN: %target-run %t/TestData_Swift4
// REQUIRES: executable_test
// REQUIRES: objc_interop

import Foundation
import StdlibUnittest

var DataTests = TestSuite("TestDataSwift4")

DataTests.test("functional map init usage") {
	let res1 = [[UInt8(0), UInt8(1), UInt8(2)]].map(Data.init) // previously this could be done without being ambiguous (however in swift 4.2 an overload was added that makes it ambiguous as a function ref)
	// the following two strategies are preferred to the previous version
	let res2 = [[UInt8(0), UInt8(1), UInt8(2)]].map(Data.init(_:))
	let res3 = [[UInt8(0), UInt8(1), UInt8(2)]].map { Data($0) }

	expectEqual(res1.count, 1)
	expectEqual(res2.count, 1)
	expectEqual(res3.count, 1)

	expectEqual(res1[0], res2[0])
	expectEqual(res2[0], res3[0])
}

runAllTests()


Add test case for crash triggered in swift::LValueType::get(swift::Type)

// RUN: not --crash %target-swift-frontend %s -parse
// REQUIRES: asserts

// Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing

var d:d=struct d<h:let{d


// RUN: %swift -target x86_64-apple-macosx10.9 %s -emit-ir -g -o - | FileCheck %s
func main() {
  // CHECK: call void @llvm.dbg.declare(metadata !{%"protocol<>"* {{.*}}}, metadata ![[S:.*]]), !dbg ![[DBG:.*]]
  // CHECK: ![[S]] ={{.*}}[ DW_TAG_auto_variable ] [s] [line [[@LINE+3]]]
  // CHECK: ![[SCOPE:.*]] = {{.*}}i32 2, i32 13, i32 0, i32 {{[0-9]+}}} ; [ DW_TAG_lexical_block ]
  // CHECK: ![[DBG]] = metadata !{i32 [[@LINE+1]], i32 6, metadata ![[SCOPE]], null}
	var s : Any = "hello world"
	var n : Any = 12
	var t : Any = (1,2)
	println("hello world")
}

main()

Update tests for a change in debug info metadata format

// RUN: %swift -target x86_64-apple-macosx10.9 %s -emit-ir -g -o - | FileCheck %s
func main() {
  // CHECK: call void @llvm.dbg.declare(metadata !{%"protocol<>"* {{.*}}}, metadata ![[S:.*]]), !dbg ![[DBG:.*]]
  // CHECK: ![[S]] ={{.*}}[ DW_TAG_auto_variable ] [s] [line [[@LINE+3]]]
  // CHECK: ![[SCOPE:.*]] = {{.*}}i32 2, i32 13, i32 0} ; [ DW_TAG_lexical_block ]
  // CHECK: ![[DBG]] = metadata !{i32 [[@LINE+1]], i32 6, metadata ![[SCOPE]], null}
	var s : Any = "hello world"
	var n : Any = 12
	var t : Any = (1,2)
	println("hello world")
}

main()


Add tests for firstMatchingString(in string:)

import XCTest
@testable import Danger

class NSRegularExpressionExtensionsTests: XCTestCase {

    static var allTests = [
        ("test_firstMatchingString_passingRegex", test_firstMatchingString_passingRegex),
        ("test_firstMatchingString_failingRegex", test_firstMatchingString_failingRegex)
    ]

    let string = "Dogs and cats were wearing hats"

    func test_firstMatchingString_passingRegex() {
        let pattern = "(cats|hats)$"
        let expectedMatch = "hats"

        guard
            let expression = try? NSRegularExpression(pattern: pattern),
            let testMatch = expression.firstMatchingString(in: string)
        else {
            XCTFail(); return
        }

        XCTAssertEqual(testMatch, expectedMatch)
    }

    func test_firstMatchingString_failingRegex() {
        let pattern = "^(cats|hats)"

        guard let expression = try? NSRegularExpression(pattern: pattern) else {
                XCTFail(); return
        }

        let testMatch = expression.firstMatchingString(in: string)

        XCTAssertNil(testMatch)
    }

}


Add missing test for "Horrific simulation of Swift 3 bug with argument labels for Swift 3 mode"

// RUN: %target-typecheck-verify-swift -swift-version 4

// SR-2505: "Call arguments did not match up" assertion

func sr_2505(_ a: Any) {} // expected-note {{}}
sr_2505()          // expected-error {{missing argument for parameter #1 in call}}
sr_2505(a: 1)      // expected-error {{extraneous argument label 'a:' in call}}
sr_2505(1, 2)      // expected-error {{extra argument in call}}
sr_2505(a: 1, 2)   // expected-error {{extra argument in call}}

struct C_2505 {
  init(_ arg: Any) {
  }
}

protocol P_2505 {
}

extension C_2505 {
  init<T>(from: [T]) where T: P_2505 {
  }
}

class C2_2505: P_2505 {
}

let c_2505 = C_2505(arg: [C2_2505()]) // expected-error {{argument labels '(arg:)' do not match any available overloads}} expected-note {{overloads for 'C_2505' exist}}


Add test case for crash triggered in swift::VarDecl::emitLetToVarNoteIfSimple(swift::DeclContext*) const

// RUN: not --crash %target-swift-ide-test -code-completion -code-completion-token=A -source-filename=%s
class l{func a=let A{class Q{var _=a={#^A^#


Add test case for crash triggered in swift::ValueDecl::isInstanceMember() const

// RUN: not --crash %target-swift-frontend %s -parse
// REQUIRES: asserts

// Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing

protocol A{let i:Bool,b}let a{struct S<>:A{let i:Bool


Add test case for crash triggered in swift::ValueDecl::getInterfaceType() const

// This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors

// RUN: not --crash %target-swift-frontend %s -parse
{class A{typealias B<T where B:T>:v


Add test case for crash triggered in swift::ArchetypeBuilder::addGenericParameter(swift::GenericTypeParamType*)

// RUN: not --crash %target-swift-ide-test -code-completion -code-completion-token=A -source-filename=%s
var a{protocol A{struct a{func d<T{class B:T a{#^A^#


Add test case for crash triggered in swift::TypeChecker::addImplicitConstructors(swift::NominalTypeDecl*)

// RUN: not --crash %target-swift-frontend %s -parse
// REQUIRES: asserts

// Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing

enum w{class d:a
var d=[[]a
class a:d


Add a solution to Shortest Word Distance

/**
 * Question Link: https://leetcode.com/problems/shortest-word-distance/
 * Primary idea: Iterate and update index and distance when encounter word1 or word2
 * Time Complexity: O(n), Space Complexity: O(1)
 */

class ShortestWordDistance {
    func shortestDistance(_ words: [String], _ word1: String, _ word2: String) -> Int {
        var distance = Int.max
        var firstIndex: Int?
        var secondIndex: Int?

        for (i, word) in words.enumerated() {
            if word == word1 {
                if let sec = secondIndex {
                    distance = min(distance, i - sec)
                }
                firstIndex = i
            } else if word == word2 {
                if let fir = firstIndex {
                    distance = min(distance, i - fir)
                }
                secondIndex = i
            }
        }

        return distance
    }
}


//
// Copyright 2022 The Matrix.org Foundation C.I.C
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//

import Foundation

import XCTest
@testable import MatrixSDK

class MXLocationServiceTests: XCTestCase {

    private var testData: MatrixSDKTestsData!

    override func setUp() {
        testData = MatrixSDKTestsData()
        MXSDKOptions.sharedInstance().enableThreads = true
    }

    override func tearDown() {
        testData = nil
    }

    /// Test: Expect the location service is initialized after creating a session
    /// - Create a Bob session
    /// - Expect location service is initialized
    func testInitialization() {
        testData.doMXSessionTest(withBob: self) { bobSession, expectation in
            guard let bobSession = bobSession,
                  let expectation = expectation else {
                XCTFail("Failed to setup test conditions")
                return
            }

            XCTAssertNotNil(bobSession.locationService, "Location service must be created")

            expectation.fulfill()
        }
    }

    /// Test: Expect beacon info state event is created after user has started to share is location
    /// - Create a Bob session
    /// - Create an initial room
    /// - Start location sharing
    /// - Expect a beacon info state event created in the room
    func testStartingThread() {
        let store = MXMemoryStore()
        testData.doMXSessionTest(withBobAndARoom: self, andStore: store) { bobSession, initialRoom, expectation in
            guard let bobSession = bobSession,
                  let initialRoom = initialRoom,
                  let expectation = expectation else {
                XCTFail("Failed to setup test conditions")
                return
            }

            let locationService: MXLocationService = bobSession.locationService

            let expectedBeaconInfoDescription = "Live location description"
            let expectedBeaconInfoTimeout: TimeInterval = 600000
            let expectedBeaconInfoIsLive = true

            locationService.startUserLocationSharing(withRoomId: initialRoom.roomId, description: expectedBeaconInfoDescription, timeout: expectedBeaconInfoTimeout) { response in

                switch response {
                case .success(let eventId):

                    initialRoom.state { roomState in

                        let beaconInfo = roomState?.beaconInfoEvents.last

                        let beaconInfoStateEvent = roomState?.stateEvents.first(where: { event in
                            event.eventId == eventId
                        })

                        XCTAssertNotNil(beaconInfoStateEvent)

                        XCTAssertNotNil(beaconInfo)

                        if let beaconInfo = beaconInfo {

                            XCTAssertEqual(beaconInfo.desc, expectedBeaconInfoDescription)
                            XCTAssertEqual(beaconInfo.timeout, expectedBeaconInfoTimeout)
                            XCTAssertEqual(beaconInfo.isLive, expectedBeaconInfoIsLive)
                        }

                        expectation.fulfill()
                    }
                case .failure(let error):
                    XCTFail("Start location sharing fails with error: \(error)")
                    expectation.fulfill()
                }
            }
        }
    }
}


//
//  CodableTransform.swift
//  ObjectMapper
//
//  Created by Jari Kalinainen on 10/10/2018.
//
//  The MIT License (MIT)
//
//  Copyright (c) 2014-2016 Hearst
//
//  Permission is hereby granted, free of charge, to any person obtaining a copy
//  of this software and associated documentation files (the "Software"), to deal
//  in the Software without restriction, including without limitation the rights
//  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//  copies of the Software, and to permit persons to whom the Software is
//  furnished to do so, subject to the following conditions:
//
//  The above copyright notice and this permission notice shall be included in
//  all copies or substantial portions of the Software.
//
//  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
//  THE SOFTWARE.

import Foundation

/// Transforms JSON dictionary to Codable type T and back
open class CodableTransform<T: Codable>: TransformType {

    public typealias Object = T
    public typealias JSON = Any

    public init() {}

    open func transformFromJSON(_ value: Any?) -> Object? {
        guard let dict = value as? [String: Any], let data = try? JSONSerialization.data(withJSONObject: dict, options: []) else {
            return nil
        }
        do {
            let decoder = JSONDecoder()
            let item = try decoder.decode(T.self, from: data)
            return item
        } catch {
            return nil
        }
    }

    open func transformToJSON(_ value: T?) -> JSON? {
        guard let item = value else {
            return nil
        }
        do {
            let encoder = JSONEncoder()
            let data = try encoder.encode(item)
            let dictionary = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [String: Any]
            return dictionary
        } catch {
            return nil
        }
    }
}


//
//  SpelledPitch.swift
//  PitchSpellingTools
//
//  Created by James Bean on 5/1/16.
//
//

import Foundation
import Pitch

public struct SpelledPitch {

    public let pitch: Pitch
    public let spelling: PitchSpelling

    public init(pitch: Pitch, spelling: PitchSpelling) {
        self.pitch = pitch
        self.spelling = spelling
    }
}


Add Swift 4 version of Package description

// swift-tools-version:4.0

import PackageDescription

let package = Package(
    name: "JWTKeychain",
    products: [
        .library(name: "JWTKeychain", targets: ["JWTKeychain"])
    ],
    dependencies: [
        .package(url: "https://github.com/harlanhaskins/Punctual.swift.git", .upToNextMajor(from: "1.0.0")),
        .package(url: "https://github.com/nodes-vapor/flash.git", .upToNextMajor(from: "1.0.0")),
        .package(url: "https://github.com/nodes-vapor/forms.git", .upToNextMinor(from: "0.4.0")),
        .package(url: "https://github.com/nodes-vapor/sugar.git", .upToNextMajor(from: "2.0.0")),
        .package(url: "https://github.com/vapor/fluent-provider.git", .upToNextMajor(from: "1.0.0")),
        .package(url: "https://github.com/vapor/jwt-provider.git", .upToNextMajor(from: "1.0.0")),
        .package(url: "https://github.com/vapor/leaf-provider.git", .upToNextMajor(from: "1.0.0")),
        .package(url: "https://github.com/vapor/vapor.git", .upToNextMajor(from: "2.0.0")),
        .package(url: "https://github.com/vapor/validation.git", .upToNextMajor(from: "1.0.0")),
    ],
    targets: [
        .target(name: "JWTKeychain", dependencies: ["Punctual", "Flash", "Forms", "Sugar", "FluentProvider", "JWTProvider", "LeafProvider", "Vapor", "Validation"]),
        .testTarget(name: "JWTKeychainTests", dependencies: ["JWTKeychain"])
    ]
)


Add test case for crash triggered in swift::getTypeOfCompletionContextExpr(swift::ASTContext&, swift::DeclContext*, swift::CompletionTypeCheckKind, swift::Expr*&, swift::ConcreteDeclRef&)

// RUN: not --crash %target-swift-ide-test -code-completion -code-completion-token=A -source-filename=%s
// REQUIRES: asserts
{let:e(var d#^A^#


/**
 * Copyright IBM Corporation 2016
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 **/

import XCTest

@testable import net
@testable import router

XCTMain([
    TestContentType(),
    TestErrors(),
    TestResponse(),
    ClientTests(),
    ParserTests()
])


Add type checker performance tests using description(with:) and count(where:).

// RUN: %target-typecheck-verify-swift -solver-expression-time-threshold=1 -solver-disable-shrink
// REQUIRES: tools-release,no_asan

struct Date {
  var description: String
  func description(with: Int) -> String { "" }
}

struct DatabaseLog {
  let string: String
  let values: [String]
  let date: Date

  var description: String {
    return "[" + string + "] [" + date.description + "] " + string + " [" + values.joined(separator: ", ") + "]"
  }
}

extension Sequence {
  public func count(
    where predicate: (Element) throws -> Bool
  ) rethrows -> Int { 0 }
}

func rdar47742750(arr1: [Int], arr2: [Int]?) {
  let _ = {
    assert(arr1.count == arr1.count + (arr2 == nil ? 0 : 1 + arr2!.count + arr2!.count + arr2!.count))
  }
}


Add test case for crash triggered in swift::ConstructorDecl::getResultType() const

// RUN: not --crash %target-swift-ide-test -code-completion -code-completion-token=A -source-filename=%s
typealias f=B{func a{f#^A^#}}struct B{let d


Add 💥 case (😢 → 55, 😀 → 5098) triggered in swift::GenericFunctionType::get(…)

// This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors

// RUN: not --crash %target-swift-frontend %s -parse
// REQUIRES: asserts
class A<c{
func p{enum b<T{
func p(T:c
let a{{
let a=p{


Add test case for crash triggered in swift::TypeChecker::applyUnboundGenericArguments(swift::UnboundGenericType*, swift::SourceLoc, swift::DeclContext*, llvm::MutableArrayRef<swift::TypeLoc>, bool, swift::GenericTypeResolver*)

// RUN: not --crash %target-swift-frontend %s -parse
// REQUIRES: asserts

// Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing

class B<T{func a{{func g:A}protocol A{typealias e=c<T>struct c<a]typealias d:e


import SpriteKit

class GameScene: SKScene {
    // Play button node
    let playButton = SKSpriteNode(imageNamed: "play")

    override func didMoveToView(view: SKView) {
        // Position the play button in the middle of the screen
        // It position the button in the middle of the frame.
        self.playButton.position = CGPointMake(CGRectGetMidX(self.frame), CGRectGetMidY(self.frame))

        // Add the button to the screen
        self.addChild(self.playButton)

        // Set the background color
        self.backgroundColor = UIColor(hex: 0x809DFF)
    }

    override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
        for touch:AnyObject in touches{
            // Grab the touch location
            let location = touch.locationInNode(self)
            // Retrieve the sprite in that location
            // If the sprite at that location is matching play button, the do something!
            if( self.nodeAtPoint(location) == self.playButton){
                // Create a new PlayScene with the same size
                let playScene = PlayScene(size:self.size)
                let view = self.view as SKView
                // Ignore sibling order
                view.ignoresSiblingOrder = true
            }
        }
    }

    override func update(currentTime: CFTimeInterval) {
        /* Called before each frame is rendered */
    }
}

Update the play scene with a new scale mode: .ResizeFill

import SpriteKit

class GameScene: SKScene {
    // Play button node
    let playButton = SKSpriteNode(imageNamed: "play")

    override func didMoveToView(view: SKView) {
        // Position the play button in the middle of the screen
        // It position the button in the middle of the frame.
        self.playButton.position = CGPointMake(CGRectGetMidX(self.frame), CGRectGetMidY(self.frame))

        // Add the button to the screen
        self.addChild(self.playButton)

        // Set the background color
        self.backgroundColor = UIColor(hex: 0x809DFF)
    }

    override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
        for touch:AnyObject in touches{
            // Grab the touch location
            let location = touch.locationInNode(self)
            // Retrieve the sprite in that location
            // If the sprite at that location is matching play button, the do something!
            if( self.nodeAtPoint(location) == self.playButton){
                // Create a new PlayScene with the same size
                let playScene = PlayScene(size:self.size)
                let view = self.view as SKView
                // Ignore sibling order
                view.ignoresSiblingOrder = true

                // Scale mode for the new PlayScene
                scene.scaleMode = .ResizeFill

            }
        }
    }

    override func update(currentTime: CFTimeInterval) {
        /* Called before each frame is rendered */
    }
}


// swift-tools-version:4.2
import PackageDescription

let package = Package(
    name: "AlignedCollectionViewFlowLayout",
    products: [
        .library(name: "AlignedCollectionViewFlowLayout", targets: ["AlignedCollectionViewFlowLayout"])
    ],
    targets: [
        .target(
            name: "AlignedCollectionViewFlowLayout"
        )
    ]
)


Add test case for crash triggered in swift::TypeChecker::typeCheckTopLevelCodeDecl(swift::TopLevelCodeDecl*)

// RUN: not --crash %target-swift-ide-test -code-completion -code-completion-token=A -source-filename=%s
// REQUIRES: asserts
if c={func b:#^A^#


Add test case for crash triggered in swift::constraints::Solution::resolveLocatorToDecl(swift::constraints::ConstraintLocator*) const

// RUN: not --crash %target-swift-ide-test -code-completion -code-completion-token=A -source-filename=%s
// REQUIRES: asserts
protocol b
func b{b#^A^#


Add test case for crash triggered in swift::TypeChecker::validateGenericFuncSignature(swift::AbstractFunctionDecl*)

// RUN: not --crash %target-swift-frontend %s -parse
// REQUIRES: asserts

// Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing

class S<T:S{func g:T.g
func g


Add test case for crasher that's already fixed on master

// RUN: %target-swift-frontend %s -emit-ir

protocol X {
  associatedtype R : Y
}

protocol Y {
  associatedtype Q : X where Q.R == Self
}

struct B : Y {
  typealias Q = L<B>
}

struct L<V : Y> : X {
  typealias R = V
}


// RUN: not --crash %target-swift-frontend %s -parse
// REQUIRES: asserts

// Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing

enum w{class d:a
var d=[[]a
class a:d


// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//

import CoreFoundation

extension CFKeyedArchiverUID : _NSBridgeable {
    typealias NSType = _NSKeyedArchiverUID

    internal var _nsObject: NSType { return unsafeBitCast(self, to: NSType.self) }
}

internal class _NSKeyedArchiverUID : NSObject {
    typealias CFType = CFKeyedArchiverUID
    internal var _base = _CFInfo(typeID: _CFKeyedArchiverUIDGetTypeID())
    internal var value : UInt32 = 0

    internal var _cfObject : CFType {
        return unsafeBitCast(self, to: CFType.self)
    }

    override open var _cfTypeID: CFTypeID {
        return _CFKeyedArchiverUIDGetTypeID()
    }

    open override var hash: Int {
        return Int(bitPattern: CFHash(_cfObject as CFTypeRef!))
    }

    open override func isEqual(_ object: Any?) -> Bool {
        // no need to compare these?
        return false
    }

    init(value : UInt32) {
        self.value = value
    }

    deinit {
        _CFDeinit(self)
    }
}

Fix cast that is disallowed by SE-0054.

// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//

import CoreFoundation

extension CFKeyedArchiverUID : _NSBridgeable {
    typealias NSType = _NSKeyedArchiverUID

    internal var _nsObject: NSType { return unsafeBitCast(self, to: NSType.self) }
}

internal class _NSKeyedArchiverUID : NSObject {
    typealias CFType = CFKeyedArchiverUID
    internal var _base = _CFInfo(typeID: _CFKeyedArchiverUIDGetTypeID())
    internal var value : UInt32 = 0

    internal var _cfObject : CFType {
        return unsafeBitCast(self, to: CFType.self)
    }

    override open var _cfTypeID: CFTypeID {
        return _CFKeyedArchiverUIDGetTypeID()
    }

    open override var hash: Int {
        return Int(bitPattern: CFHash(_cfObject as CFTypeRef?))
    }

    open override func isEqual(_ object: Any?) -> Bool {
        // no need to compare these?
        return false
    }

    init(value : UInt32) {
        self.value = value
    }

    deinit {
        _CFDeinit(self)
    }
}


var (initCount, deinitCount) = (0, 0)

class Person {
    var name: String
    var boss: Person?
    var assistant: Person?
    init(name: String, boss: Person? = nil) {
        initCount += 1
        self.name = name
        self.boss = boss
    }
    deinit {
        deinitCount += 1
    }
}

func main() {
    let alice = Person(name: "Alice")
    let bob = Person(name: "Bob", boss: alice)
    alice.assistant = bob
}

main()
print(initCount, deinitCount)
assert(initCount == 2 && deinitCount == 0)


Add test case for crash triggered in swift::TypeChecker::performTypoCorrection(swift::DeclContext*, swift::DeclRefKind, swift::Type, swift::DeclName, swift::SourceLoc, swift::OptionSet<swift::NameLookupFlags, unsigned int>, swift::LookupResult&, unsigned int)

// RUN: not --crash %target-swift-ide-test -code-completion -code-completion-token=A -source-filename=%s
// REQUIRES: asserts
let a{enum S{var f=A.a class A:A#^A^#


Add a testcase for <rdar://problem/18444716> Return locations may have smaller line numbers than cleanup locations

// RUN: %target-build-swift %s -g -emit-ir -o - | FileCheck %s
class X {
  init (i : Int) { x = i }
  var x : Int
}

// CHECK: define {{.*}}ifelseexpr
func ifelseexpr() -> Int {
  var x = X(i:0);
  if true {
    // CHECK:  @swift_release
    x.x++;
  } else {
    x.x--;
  }
  // CHECK:  @swift_release {{.*}}1X{{.*}}, !dbg ![[CLEANUP:.*]]
  // CHECK:  ret{{.*}}, !dbg ![[RET:.*]]
  // CHECK: ![[CLEANUP]] = metadata !{i32 [[@LINE+1]],
  return x.x; // CHECK: ![[RET]] = metadata !{i32 [[@LINE]],
}


Add 💥 case (😢 → 43, 😀 → 5089) triggered in swift::TypeChecker::resolveTypeInContext(…)

// This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors

// RUN: not --crash %target-swift-frontend %s -parse
// REQUIRES: asserts
protocol a{struct A}func a{var:A{}protocol A:a{{}typealias d:A


Add test case for crash triggered in swift::GenericParamList::getSubstitutionMap(llvm::ArrayRef<swift::Substitution>) const

// This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors

// RUN: not --crash %target-swift-frontend %s -parse
// REQUIRES: asserts
protocol A{
typealias B<a>:A
enum S<T where B<Int>:d
typealias d


Add custom font and line height extension

//
//  Font.swift
//  ZamzamUI
//
//  Created by Basem Emara on 2021-03-02.
//  Copyright © 2021 Zamzam Inc. All rights reserved.
//

import SwiftUI

public extension View {
    /// Create a custom font with the given name and size that scales relative to the given `textStyle` and sets the line height.
    func font(
        _ name: String,
        size: CGFloat,
        relativeTo textStyle: Font.TextStyle,
        lineHeight: CGFloat,
        isMonospacedDigit: Bool = false
    ) -> some View {
        var custom: Font = .custom(name, size: size, relativeTo: textStyle)

        if isMonospacedDigit {
            custom = custom.monospacedDigit()
        }

        return self
            .font(custom)
            .modifier(if: lineHeight > size) { content in
                // https://stackoverflow.com/q/61705184
                content.lineSpacing((lineHeight - size) / 2)
            }
    }
}


// This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors

// RUN: not --crash %target-swift-frontend %s -parse
// REQUIRES: asserts
struct d=typealias f=B)typealias B<T>:d typealias B<T>:B<T>


Add safe area compatibility extension for older systems

import UIKit

@available(iOS 9.0, *)
extension UIViewController {
    private enum Keys {
        static var safeArea: UInt8 = 0
    }

    /// Layout guide compatibility extension for iOS 11 safe area
    ///
    /// On iOS 11+ is the same as `view.safeAreaLayoutGuide`.
    ///
    /// On older systems it fallbacks to `topLayoutGuide.bottom` and `bottomLayoutGuide.top`, side constraints are equal to superview.
    var safeArea: UILayoutGuide {
        if #available(iOS 11.0, *) {
            return view.safeAreaLayoutGuide
        } else {
            if let layoutGuide = objc_getAssociatedObject(self, &Keys.safeArea) as? UILayoutGuide { return layoutGuide }

            let layoutGuide = UILayoutGuide()
            view.addLayoutGuide(layoutGuide)
            layoutGuide.topAnchor.constraint(equalTo: topLayoutGuide.bottomAnchor).isActive = true
            layoutGuide.bottomAnchor.constraint(equalTo: bottomLayoutGuide.topAnchor).isActive = true
            layoutGuide.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
            layoutGuide.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true
            objc_setAssociatedObject(self, &Keys.safeArea, layoutGuide, .OBJC_ASSOCIATION_ASSIGN)
            return layoutGuide
        }
    }
}


Add test case for crash triggered in swift::constraints::ConstraintSystem::assignFixedType(swift::TypeVariableType*, swift::Type, bool)

// RUN: not --crash %target-swift-frontend %s -parse
// REQUIRES: asserts

// Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing

{println(""""?struct{


//
//  Created by Pierluigi Cifani on 28/04/16.
//  Copyright © 2016 Blurred Software SL. All rights reserved.
//

import SDWebImage

extension UIImageView {

    public func bsw_setImageFromURLString(url: String) {
        if let url = NSURL(string: url) {
            sd_setImageWithURL(url)
        }
    }

    public func bsw_setImageFromURL(url: NSURL) {
        sd_setImageWithURL(url)
    }

    public func bsw_cancelImageLoadFromURL() {
        sd_cancelCurrentImageLoad()
    }
}


Put ProfilePageView in an UIViewController

//
//  ProfileViewController.swift
//  Markit
//
//  Created by rrao on 10/13/16.
//  Copyright © 2016 Victor Frolov. All rights reserved.
//

import Foundation


// RUN: %target-swift-frontend %s -emit-ir -g -o - | %FileCheck %s
// REQUIRES: CPU=i386
class Obj {}

enum MyError : Error {
  case Simple
  case WithObj(Obj)
}

// i386 does not pass swifterror in a register. To support debugging of the
// thrown error we create a shadow stack location holding the address of the
// location that holds the pointer to the error instead.
func simple(_ placeholder: Int64) throws -> () {
  // CHECK: define {{.*}}void @_T06Errors6simpleys5Int64VKF(i64, %swift.refcounted* swiftself, %swift.error**)
  // CHECK: call void @llvm.dbg.declare
  // CHECK: call void @llvm.dbg.declare({{.*}}, metadata ![[ERROR:[0-9]+]], metadata ![[DEREF:[0-9]+]])
  // CHECK: ![[ERROR]] = !DILocalVariable(name: "$error", arg: 2,
  // CHECK-SAME:              type: ![[ERRTY:.*]], flags: DIFlagArtificial)
  // CHECK: ![[ERRTY]] = !DICompositeType({{.*}}identifier: "_T0s5Error_pD"
  // CHECK: ![[DEREF]] = !DIExpression(DW_OP_deref)
  throw MyError.Simple
}

func obj() throws -> () {
  throw MyError.WithObj(Obj())
}

public func foo() {
  do {
    try simple(1)
    try obj()
  }
  catch {}
}

Fix mangled name for renamed test.

// RUN: %target-swift-frontend %s -emit-ir -g -o - | %FileCheck %s
// REQUIRES: CPU=i386
class Obj {}

enum MyError : Error {
  case Simple
  case WithObj(Obj)
}

// i386 does not pass swifterror in a register. To support debugging of the
// thrown error we create a shadow stack location holding the address of the
// location that holds the pointer to the error instead.
func simple(_ placeholder: Int64) throws -> () {
  // CHECK: define {{.*}}void @_T08ErrorVar6simpleys5Int64VKF(i64, %swift.refcounted* swiftself, %swift.error**)
  // CHECK: call void @llvm.dbg.declare
  // CHECK: call void @llvm.dbg.declare({{.*}}, metadata ![[ERROR:[0-9]+]], metadata ![[DEREF:[0-9]+]])
  // CHECK: ![[ERROR]] = !DILocalVariable(name: "$error", arg: 2,
  // CHECK-SAME:              type: ![[ERRTY:.*]], flags: DIFlagArtificial)
  // CHECK: ![[ERRTY]] = !DICompositeType({{.*}}identifier: "_T0s5Error_pD"
  // CHECK: ![[DEREF]] = !DIExpression(DW_OP_deref)
  throw MyError.Simple
}

func obj() throws -> () {
  throw MyError.WithObj(Obj())
}

public func foo() {
  do {
    try simple(1)
    try obj()
  }
  catch {}
}


Add a test to check if OptionSet literals are fully folded

// RUN: %target-swift-frontend  -parse-as-library -primary-file %s -O -sil-verify-all -module-name=test -emit-sil | %FileCheck %s
// RUN: %target-swift-frontend  -parse-as-library -primary-file %s -Osize -sil-verify-all -module-name=test -emit-sil | %FileCheck %s
// REQUIRES: swift_stdlib_no_asserts,optimized_stdlib

public struct TestOptions: OptionSet {
    public let rawValue: Int
    public init(rawValue: Int) { self.rawValue = rawValue }

    static let first    = TestOptions(rawValue: 1 << 0)
    static let second  = TestOptions(rawValue: 1 << 1)
    static let third   = TestOptions(rawValue: 1 << 2)
    static let fourth   = TestOptions(rawValue: 1 << 3)
}

// CHECK:      sil @{{.*}}returnTestOptions{{.*}}
// CHECK-NEXT: bb0:
// CHECK-NEXT:   integer_literal {{.*}}, 15
// CHECK-NEXT:   struct $Int
// CHECK-NEXT:   struct $TestOptions
// CHECK-NEXT:   return
public func returnTestOptions() -> TestOptions {
    return [.first, .second, .third, .fourth]
}

// CHECK:        alloc_global @{{.*}}globalTestOptions{{.*}}
// CHECK-NEXT:   global_addr
// CHECK-NEXT:   integer_literal {{.*}}, 15
// CHECK-NEXT:   struct $Int
// CHECK-NEXT:   struct $TestOptions
// CHECK-NEXT:   store
// CHECK-NEXT:   tuple
// CHECK-NEXT:   return
let globalTestOptions: TestOptions = [.first, .second, .third, .fourth]


Add sort by keypath extension to sequences

//
//  Sequence.swift
//  ZamzamCore
//
//  Created by Basem Emara on 2021-09-10.
//  Copyright © 2016 Zamzam Inc. All rights reserved.
//

public extension Sequence {
    /// Returns the elements of the sequence, sorted using the keypath and given predicate as the comparison between elements.
    func sorted<T>(by keyPath: KeyPath<Element, T>, _ comparator: (T, T) throws -> Bool) rethrows -> [Element] {
        try sorted { try comparator($0[keyPath: keyPath], $1[keyPath: keyPath]) }
    }

    /// Returns the elements of the sequence, sorted using the keypath and given predicate as the comparison between elements.
    func sorted<T: Comparable>(by keyPath: KeyPath<Element, T>) -> [Element] {
        sorted(by: keyPath, <)
    }
}


Add test for deprecated range definition

//
//  DeprecationTests.swift
//  BridgeAppSDK
//
//  Copyright © 2016 Sage Bionetworks. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// 1.  Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// 2.  Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation and/or
// other materials provided with the distribution.
//
// 3.  Neither the name of the copyright holder(s) nor the names of any contributors
// may be used to endorse or promote products derived from this software without
// specific prior written permission. No license is granted to the trademarks of
// the copyright holders even if such marks are included in this software.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//

import XCTest

/**
 * Swift is a young language that is constantly changing. Things get deprecated and sometimes
 * it is unclear how to update your code.
 */

class DeprecationTests: XCTestCase {

    override func setUp() {
        super.setUp()
        // Put setup code here. This method is called before the invocation of each test method in the class.
    }

    override func tearDown() {
        // Put teardown code here. This method is called after the invocation of each test method in the class.
        super.tearDown()
    }

    func testRange() {

        let string = "abcdefghijklmnopqrstuvwxyz"
        let range = string.rangeOfString("defg")!
        let deprecatedRange = Range(start: range.endIndex, end: string.endIndex)
        let spliceRange = range.endIndex ..< string.endIndex

        let deprecatedRangeString = string.substringWithRange(deprecatedRange)
        let spliceRangeString = string.substringWithRange(spliceRange)
        XCTAssertEqual(deprecatedRangeString, "hijklmnopqrstuvwxyz")
        XCTAssertEqual(spliceRangeString, deprecatedRangeString)

    }

}


// RUN: %target-run-simple-swift | FileCheck %s

import Foundation

class Foo : NSObject {
  val foo: Int

  init(foo: Int) {
    self.foo = foo
    super.init()
  }

  @objc func applyBlock(f: @objc_block Int -> ()) withInt(x: Int) {
    f(foo)
    f(x)
  }

  @objc func applyBlock(f: @objc_block Int -> ()) withFoo(x: Foo) {
    f(foo)
    f(x.foo)
  }
}

// CHECK: 123
// CHECK: 22
Foo(123).applyBlock { println($0) } withInt(22)
// CHECK: 321
// CHECK: 44
Foo(321).applyBlock { println($0) } withFoo(Foo(44))


Add test for SR-4016 / rdar://problem/30677848, which is now fixed.

// RUN: %target-swift-frontend -emit-ir %s

public enum Event<Element, Error: Swift.Error> {
  case next(Element)
  case failed(Error)
  case completed
}

public typealias Observer<Element, Error: Swift.Error> = (Event<Element, Error>) -> Void

public protocol Disposable {

  func dispose()

  var isDisposed: Bool { get }
}

public protocol SignalProtocol {

  /// The type of elements generated by the signal.
  associatedtype Element

  /// The type of error that can terminate the signal.
  associatedtype Error: Swift.Error

  /// Register an observer that will receive events from a signal.
  /// This actually triggers event production. Use the returned disposable
  /// to unsubscribe and cancel event production.
  func observe(with observer: @escaping Observer<Element, Error>) -> Disposable
}

public protocol ObserverProtocol {

  /// Type of elements being received.
  associatedtype Element

  /// Type of error that can be received.
  associatedtype Error: Swift.Error

  /// Send the event to the observer.
  func on(_ event: Event<Element, Error>)
}

/// A type that is both a signal and an observer.
public protocol SubjectProtocol: SignalProtocol, ObserverProtocol {
}

public final class AnySubject<Element, Error: Swift.Error>: SubjectProtocol {
  private let baseObserve: (@escaping Observer<Element, Error>) -> Disposable
  private let baseOn: Observer<Element, Error>

  public init<S: SubjectProtocol>(base: S) where S.Element == Element, S.Error == Error {
    baseObserve = base.observe
    baseOn = base.on
  }

  public func on(_ event: Event<Element, Error>) {
    return baseOn(event)
  }

  public func observe(with observer: @escaping Observer<Element, Error>) -> Disposable {
    return baseObserve(observer)
  }
}


struct S {
  let count = 1
}

public class CC {
  func foo(_ s : S) -> Int {
    if s.count > 0 {
      return 1
    } else {
      return 0
    }
  }
}

// RUN: %target-swift-ide-test -range -pos=7:8 -end-pos=7:19 -source-filename %s | %FileCheck %s -check-prefix=CHECK-BOOL
// CHECK-BOOL: <Type>Bool</Type>


// RUN: %sourcekitd-test -req=cursor -pos=5:16 %s -- %s | %FileCheck %s

protocol View {}
struct MyView: View {}
func indicator<T>(_ a: T) -> some View {
  MyView()
}

// CHECK: source.lang.swift.decl.generic_type_param


Add regression test for array lookup error

import string;

// THIS-TEST-SHOULD-NOT-RUN
// Regression test for array lookup not failing correctly

main {
  string toks[];

  toks = split("a,b,c", ",");

  trace(toks[3]); // Doesn't exist, so we should get nice error
}


Create another class for managing Giphy functionality

//
//  GiphyManager.swift
//  PlayingWithUserNotifications
//
//  Created by Sam Agnew on 2/7/17.
//  Copyright © 2017 Sam Agnew. All rights reserved.
//

import UIKit
import Alamofire
import SwiftyJSON

class GiphyManager: NSObject {

    let giphyBaseURL = "https://api.giphy.com/v1/gifs/search"
    let apiKey: String
    let imageLimit: UInt32

    override init() {
        self.apiKey = "dc6zaTOxFJmzC"
        self.imageLimit = 50
        super.init()
    }

    init(apiKey: String, imageLimit: UInt32) {
        self.apiKey = apiKey
        self.imageLimit = imageLimit
        super.init()
    }

    func fetchRandomGifUrl(forSearchQuery query: String, completionHandler: @escaping (_ forImageUrl: String) -> Void) {

        Alamofire.request(self.giphyBaseURL, parameters: ["api_key": self.apiKey, "q": query, "limit": "\(self.imageLimit)"])
            .responseJSON { response in
                if let result = response.result.value {
                    let json = JSON(result)
                    let randomNum:Int = Int(arc4random_uniform(self.imageLimit))

                    if let imageUrlString = json["data"][randomNum]["images"]["downsized"]["url"].string {
                        print(imageUrlString)
                        completionHandler(imageUrlString)
                    }

                }
        }
    }
}


//
//  ColumnsCollectionViewFlowLayout.swift
//  ZamzamKit iOS
//
//  Created by Basem Emara on 2019-03-17.
//  Copyright © 2019 Zamzam. All rights reserved.
//

import UIKit

/// A flow layout organizes items into a grid dynamically obeying different trait size.
open class ColumnsCollectionViewFlowLayout: UICollectionViewFlowLayout {

    /// Number of columns in portrait orientation.
    @IBInspectable open var portraitColumns: Int = 2

    /// Number of columns in landscape orientation.
    @IBInspectable open var landscapeColumns: Int = 3

    /// Increase columns for larger screens.
    ///
    /// Portrait and landscape columns will be multiplied with this number for regular size class devices.
    @IBInspectable open var multiplierForRegularTrait: CGFloat = 1.5

    /// The ratio between width and height while obeying number of columns.
    @IBInspectable open var aspectRatio: CGFloat = 1

    open override func prepare() {
        super.prepare()

        var cellsPerRow = UIDevice.current.orientation.isLandscape && landscapeColumns > 0
            ? landscapeColumns : portraitColumns

        if UIScreen.main.traitCollection.horizontalSizeClass == .regular && multiplierForRegularTrait > 1 {
            cellsPerRow = Int(round(CGFloat(cellsPerRow) * multiplierForRegularTrait))
        }

        guard let collectionView = collectionView, cellsPerRow > 0 else { return }

        let marginsAndInsets: CGFloat = {
            var output = sectionInset.left + sectionInset.right

            if #available(iOS 11.0, *) {
                switch sectionInsetReference {
                case .fromContentInset:
                    output += collectionView.contentInset.left + collectionView.contentInset.right
                case .fromLayoutMargins:
                    output += collectionView.layoutMargins.left + collectionView.layoutMargins.right
                case .fromSafeArea:
                    output += collectionView.safeAreaInsets.left + collectionView.safeAreaInsets.right
                }
            }

            output += max(minimumInteritemSpacing, 1) * CGFloat(cellsPerRow - 1)
            return output
        }()

        let itemWidth = ((collectionView.bounds.size.width - marginsAndInsets) / CGFloat(cellsPerRow)).rounded(.down)
        let itemHeight = itemWidth / aspectRatio

        itemSize = CGSize(width: itemWidth, height: itemHeight)
    }

    open override func shouldInvalidateLayout(forBoundsChange newBounds: CGRect) -> Bool {
        return newBounds != collectionView?.bounds
    }
}


Add tests for the available operations of std::iterator

// RUN: %target-run-simple-swift(-I %S/Inputs -Xfrontend -enable-experimental-cxx-interop)
//
// REQUIRES: executable_test
//
// Enable this everywhere once we have a solution for modularizing libstdc++: rdar://87654514
// REQUIRES: OS=macosx

import StdlibUnittest
import StdVector
import std.vector

var StdIteratorTestSuite = TestSuite("StdIterator")

StdIteratorTestSuite.test("init") {
    var vector = Vector()
    var _1: CInt = 1
    //There seems to be an issue when importing this method, where the const_ref is mapped with
    //the correct typealias to be able to pass immutable values. related to: https://github.com/apple/swift/pull/41611
    vector.push_back(&_1)
    //ideally we should call vector.begin(), however we need to prevent a copy of self before vector.begin() is invoked
    //current workaround is to use beginMutating()
    let it = vector.beginMutating()
    expectEqual(it[0], 1)
}

StdIteratorTestSuite.test("advance") {
    var vector = Vector()
    var _1: CInt = 1, _2: CInt = 2, _3: CInt = 3
    vector.push_back(&_1)
    vector.push_back(&_2)
    vector.push_back(&_3)
    var it = vector.beginMutating()
    std.__1.advance(&it, 2)
    expectEqual(it[0], 3)
}

runAllTests()


Add tostring for booleans, test tostring

import assert;

assertEqual(toString(true), "true", "true");
assertEqual(toString(false), "false", "false");

assertEqual(toString(-12), "-12", "-12");

assertEqual(toString(1.234), "1.234", "1.234");


Add interpreter test for archetype and existential casts.

// CHECK: %swift -i %s | FileCheck %s

func allToInt<T>(x:T) -> Int {
  return x as! Int
}

func anyToInt(x:protocol<>) -> Int {
  return x as! Int
}

protocol [class_protocol] Class {}

class C : Class {
  func print() { println("C!") }
}
class D : C {
  func print() { println("D!") }
}

func allClassesToC<T:Class>(x:T) -> C {
  return x as! C
}

func anyClassToC(x:protocol<Class>) -> C {
  return x as! C
}

println(allToInt(22)) // CHECK: 22
println(anyToInt(44)) // CHECK: 44
allClassesToC(C()).print() // CHECK: C!
allClassesToC(D()).print() // CHECK: D!
anyClassToC(C()).print() // CHECK: C!
anyClassToC(D()).print() // CHECK: D!


Add an execution test for extensions to CF types.

// RUN: %target-run-simple-swift | FileCheck %s

import Foundation

#if os(OSX)
import AppKit
#endif

#if os(iOS)
import UIKit
#endif

extension CGColorSpace {
  class func deviceRGB() -> CGColorSpace {
    return CGColorSpaceCreateDeviceRGB()
  }
}

extension CGColor {
  class func create(#colorSpace: CGColorSpace, #components: [CGFloat])
      -> CGColor {
    return CGColorCreate(colorSpace, components)
  }

  var r: CGFloat { return CGColorGetComponents(self)[0] }
  var g: CGFloat { return CGColorGetComponents(self)[1] }
  var b: CGFloat { return CGColorGetComponents(self)[2] }
}

let pink = CGColor.create(colorSpace: .deviceRGB(),
                          components: [1.0, 0.5, 0.25, 1.0])

// CHECK: 1.0
println(pink.r)
// CHECK-NEXT: 0.5
println(pink.g)
// CHECK-NEXT: 0.25
println(pink.b)


Add 💥 (😢 → 65, 😀 → 5108) in swift::Expr::walk(…)

// This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors

// RUN: not --crash %target-swift-frontend %s -parse
// REQUIRES: asserts
class A
enum A<A{
func a
case c
let a=c


// swift-tools-version:4.2
import PackageDescription

let package = Package(
    name: "BadgeSwift",
    products: [
        .library(name: "BadgeSwift", targets: ["BadgeSwift"]),
    ],
    dependencies: [
    ],
    targets: [
        .target(name: "BadgeSwift", dependencies: [], path: "BadgeSwift"),
        .testTarget(
            name: "BadgeSwiftTests",
            dependencies: ["BadgeSwift"]
        )
    ]
)


Add test for error recovery improvements in r14369.

// RUN: %swift -parse -verify %s

class C {

#if os(iOS)
	func foo() {}
} // expected-error{{expected declaration}} expected-error{{expected #else or #endif at end of configuration block}}
#else
	func bar() {}
	func baz() {}
} // expected-error{{expected declaration}}
#endif
// expected-error@+1{{expected declaration}}


import UIKit
import WMF

// TODO
final class TalkPageCellCommentDepthIndicator: SetupView {

    let depth: Int
    let label = UILabel()

    required init(depth: Int) {
        self.depth = depth
        super.init(frame: .zero)
        setup()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError()
    }

    override func setup() {
        label.translatesAutoresizingMaskIntoConstraints = false
        label.setContentCompressionResistancePriority(.required, for: .horizontal)
        label.setContentHuggingPriority(.required, for: .horizontal)
        label.font = UIFont.wmf_font(.body)
        label.adjustsFontForContentSizeCategory = true
        label.text = " \(depth) "
        addSubview(label)

        NSLayoutConstraint.activate([
            label.leadingAnchor.constraint(equalTo: leadingAnchor),
            label.trailingAnchor.constraint(equalTo: trailingAnchor),
            label.topAnchor.constraint(equalTo: topAnchor),
            label.bottomAnchor.constraint(equalTo: bottomAnchor)
        ])
    }

}

extension TalkPageCellCommentDepthIndicator: Themeable {

    func apply(theme: Theme) {
        label.textColor = theme.colors.paperBackground
        label.backgroundColor = theme.colors.link
    }

}


Add activity view representable for SwiftUI

//
//  SwiftUIView.swift
//  SwiftUIView
//
//  Created by Basem Emara on 2021-08-29.
//

import SwiftUI

public struct ActivityView: UIViewControllerRepresentable {
    let activityItems: [Any]
    let applicationActivities: [UIActivity]?

    public init(activityItems: [Any], applicationActivities: [UIActivity]? = nil) {
        self.activityItems = activityItems
        self.applicationActivities = applicationActivities
    }

    public func makeUIViewController(context: Context) -> UIActivityViewController {
        UIActivityViewController(
            activityItems: activityItems,
            applicationActivities: applicationActivities
        )
    }

    public func updateUIViewController(_ uiViewController: UIActivityViewController, context: Context) {}
}


Create predicates with operators on NSExpressions

//
//  NSExpression+Extensions.swift
//  SnapStack
//
//  Created by Fredrik Sjöberg on 22/09/15.
//  Copyright © 2015 Fredrik Sjöberg. All rights reserved.
//

import Foundation

public func == (left: NSExpression, right: NSExpression) -> NSPredicate {
    return NSComparisonPredicate(leftExpression: left, rightExpression: right, modifier: .DirectPredicateModifier, type: .EqualToPredicateOperatorType, options: NSComparisonPredicateOptions(rawValue: 0))
}

public func != (left: NSExpression, right: NSExpression) -> NSPredicate {
    return NSComparisonPredicate(leftExpression: left, rightExpression: right, modifier: .DirectPredicateModifier, type: .NotEqualToPredicateOperatorType, options: NSComparisonPredicateOptions(rawValue: 0))
}

public func < (left: NSExpression, right: NSExpression) -> NSPredicate {
    return NSComparisonPredicate(leftExpression: left, rightExpression: right, modifier: .DirectPredicateModifier, type: .LessThanPredicateOperatorType, options: NSComparisonPredicateOptions(rawValue: 0))
}

public func <= (left: NSExpression, right: NSExpression) -> NSPredicate {
    return NSComparisonPredicate(leftExpression: left, rightExpression: right, modifier: .DirectPredicateModifier, type: .LessThanOrEqualToPredicateOperatorType, options: NSComparisonPredicateOptions(rawValue: 0))
}

public func > (left: NSExpression, right: NSExpression) -> NSPredicate {
    return NSComparisonPredicate(leftExpression: left, rightExpression: right, modifier: .DirectPredicateModifier, type: .GreaterThanPredicateOperatorType, options: NSComparisonPredicateOptions(rawValue: 0))
}

public func >= (left: NSExpression, right: NSExpression) -> NSPredicate {
    return NSComparisonPredicate(leftExpression: left, rightExpression: right, modifier: .DirectPredicateModifier, type: .GreaterThanOrEqualToPredicateOperatorType, options: NSComparisonPredicateOptions(rawValue: 0))
}


// RUN: %target-build-swift -target arm64-apple-ios8.0 -target-cpu cyclone \
// RUN:                          -O -S %s -parse-as-library | \
// RUN:   FileCheck --check-prefix=BOTH --check-prefix=TBI %s

// RUN: %target-build-swift -target arm64-apple-ios8.0 -target-cpu cyclone \
// RUN:     -target-feature -tbi -O -S %s -parse-as-library | \
// RUN:   FileCheck --check-prefix=BOTH --check-prefix=NO_TBI %s

// REQUIRES: CPU=arm64, OS=ios

// Verify that TBI is on by default in Swift.

func f(i: Int) -> Int8 {
  let j = i & 0xff_ffff_ffff_ffff
// TBI-NOT: and
// NO_TBI: and
  let p = UnsafeMutablePointer<Int8>(bitPattern: j)
  return p[0]
}

Fix test that explicitly wants to turn off TBI on arm64.

// RUN: %target-build-swift -target arm64-apple-ios8.0 -target-cpu cyclone \
// RUN:                          -O -emit-ir %s -parse-as-library | \
// RUN:   FileCheck --check-prefix=BOTH --check-prefix=TBI %s

// RUN: %target-build-swift -target arm64-apple-ios8.0 -target-cpu cyclone \
// RUN:     -Xcc -Xclang -Xcc -target-feature -Xcc -Xclang -Xcc +tbi \
// RUN:     -O -emit-ir %s -parse-as-library | \
// RUN:   FileCheck --check-prefix=BOTH --check-prefix=NO_TBI %s

// REQUIRES: CPU=arm64, OS=ios

// Verify that TBI is on by default in Swift.

func f(i: Int) -> Int8 {
  let j = i & 0xff_ffff_ffff_ffff
// TBI-NOT: and
// NO_TBI: and
  let p = UnsafeMutablePointer<Int8>(bitPattern: j)
  return p[0]
}


Add test case for crash triggered in swift::DeclContext::lookupQualified(swift::Type, swift::DeclName, unsigned int, swift::LazyResolver*, llvm::SmallVectorImpl<swift::ValueDecl*>&) const

// RUN: not --crash %target-swift-frontend %s -parse
// REQUIRES: asserts

// Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing

for in.f=Swift.dynamicType.e.n


// RUN: %target-run-simple-swift | FileCheck %s

// Generate all possible permutes.
func _permuteInternal(elem: Int, size : Int, perm : Int[], visited : Bool[], verify : (Int[]) -> ()) {
  if (elem == size) {
    verify(perm)
    return
  }

  for i in 0..size {
    if (visited[i]) {
      continue
    }
    visited[i] = true
    perm[elem] = i
    _permuteInternal(elem + 1, size, perm, visited, verify)
    visited[i] = false
  }
}

// Convenience wrapper for the permute method.
func permute(size : Int, verify : (Int[]) -> ()) {
  var perm : Int[] = []
  var visited : Bool[] = []
  for i in 0..size {
    visited.append(false)
    perm.append(0)
  }
  _permuteInternal(0, size, perm, visited, verify)
}

// Verify the permute method itself:
let printer : (Int[]) -> () = {
    print("[")
    for i in $0 {
      print("\(i) ")
    }
    print("]\n")
}
//CHECK: [0 1 2 ]
//CHECK: [0 2 1 ]
//CHECK: [1 0 2 ]
//CHECK: [1 2 0 ]
//CHECK: [2 0 1 ]
//CHECK: [2 1 0 ]
permute(3, printer)

// Now, let's verify the sort.
let verifier : (Int[]) -> () = {
    var y = $0.copy()
    sort(y)
    for i in 0..y.count - 1 {
      if (y[i] > y[i+1]) {
        print("Error!")
        return
      }
    }
}

//CHECK-NOT: Error!
permute(2, verifier)
permute(5, verifier)
permute(6, verifier)
permute(7, verifier)
//CHECK: Done
println("Done")


Move multiple trailing closures tests into a separate file

// RUN: %target-typecheck-verify-swift

func foo<T, U>(a: () -> T, b: () -> U) {}

foo {
  a: { 42 }
  b: { "" }
}

foo { a: { 42 } b: { "" } }

foo {
  a: { 42 }, // expected-error {{unexpected ',' separator}} {{12-13=}}
  b: { "" }
}

func when<T>(_ condition: @autoclosure () -> Bool,
             `then` trueBranch: () -> T,
             `else` falseBranch: () -> T) -> T {
  return condition() ? trueBranch() : falseBranch()
}

let _ = when (2 < 3) {
  then: { 3 }
  else: { 4 }
}

struct S {
  static func foo(a: Int = 42, b: (inout Int) -> Void) -> S {
    return S()
  }

  subscript(v v: () -> Int) -> Int {
    get { return v() }
  }

  subscript(cond: Bool, v v: () -> Int) -> Int {
    get { return cond ? 0 : v() }
  }
}

let _: S = .foo {
  b: { $0 = $0 + 1 }
}

func bar(_ s: S) {
  _ = s[] {
    v: { 42 }
  }

  _ = s[true] {
    v: { 42 }
  }
}

func multiple_trailing_with_defaults(
  duration: Int,
  animations: (() -> Void)? = nil,
  completion: (() -> Void)? = nil) {}

multiple_trailing_with_defaults(duration: 42) {
  animations: {}
}

multiple_trailing_with_defaults(duration: 42) {
  completion: {}
}

multiple_trailing_with_defaults(duration: 42) {
  animations: {}
  completion: {}
}


class Foo {
  var x: Int
  var y: Int
  func fooMethod() {}
}
struct Bar {
  var a: Int
  var b: Int
  func barMethod() {}
}
func foo(arg: Foo) {
  _ = arg.
}
func bar(arg: Bar) {
  _ = arg.
}

// NOTE: Tests for 'key.codecomplete.reuseastcontex' option.

// RUN: %sourcekitd-test \
// RUN:   -req=track-compiles == \
// RUN:   -req=complete -pos=12:11 %s -- %s == \
// RUN:   -req=complete -pos=15:11 %s -- %s > %t.response
// RUN: %FileCheck --check-prefix=RESULT %s < %t.response
// RUN: %FileCheck --check-prefix=TRACE_NORMAL %s < %t.response

// RUN: %sourcekitd-test \
// RUN:   -req=track-compiles == \
// RUN:   -req=complete -req-opts=reuseastcontext=1 -pos=12:11 %s -- %s == \
// RUN:   -req=complete -req-opts=reuseastcontext=1 -pos=15:11 %s -- %s > %t.response.reuseastcontext
// RUN: %FileCheck --check-prefix=RESULT  %s < %t.response.reuseastcontext
// RUN: %FileCheck --check-prefix=TRACE_REUSEAST  %s < %t.response.reuseastcontext

// RESULT-LABEL: key.results: [
// RESULT-DAG: key.name: "fooMethod()"
// RESULT-DAG: key.name: "self"
// RESULT-DAG: key.name: "x"
// RESULT-DAG: key.name: "y"
// RESULT: ]
// RESULT-LABEL: key.results: [
// RESULT-DAG: key.name: "barMethod()"
// RESULT-DAG: key.name: "self"
// RESULT-DAG: key.name: "a"
// RESULT-DAG: key.name: "b"
// RESULT: ]

// TRACE_NORMAL-LABEL: key.notification: source.notification.compile-did-finish,
// TRACE_NORMAL-NOT: key.description: "completion reusing previous ASTContext (benign diagnostic)"
// TRACE_NORMAL-LABEL: key.notification: source.notification.compile-did-finish,
// TRACE_NORMAL-NOT: key.description: "completion reusing previous ASTContext (benign diagnostic)"

// TRACE_REUSEAST-LABEL: key.notification: source.notification.compile-did-finish,
// TRACE_REUSEAST-NOT: key.description: "completion reusing previous ASTContext (benign diagnostic)"
// TRACE_REUSEAST-LABEL: key.notification: source.notification.compile-did-finish,
// TRACE_REUSEAST: key.description: "completion reusing previous ASTContext (benign diagnostic)"


Put advertising data into its own object for easier maintenance and printing

//
//  Advertisement.swift
//  MoBetterBluetooth
//
//  Created by Robert Vaessen on 4/14/17.
//  Copyright © 2017 Verticon. All rights reserved.
//

import Foundation


Add test case for crash triggered in swift::constraints::ConstraintSystem::matchDeepEqualityTypes(swift::Type, swift::Type, swift::constraints::ConstraintLocatorBuilder)

// RUN: not --crash %target-swift-frontend %s -parse
// REQUIRES: asserts

// Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing

class A{let h=B<
protocol A{
extension{
struct A{
var b={}
class A:b{
protocol C{func<


Add UIGestureRecognizer property for isEnabled.

/*
 Copyright 2016-present The Material Motion Authors. All Rights Reserved.

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

 http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
 */

import UIKit

/** Retrieve a scoped property builder for the given UIGestureRecognizer. */
public func propertyOf(_ view: UIGestureRecognizer) -> UIGestureRecognizerReactivePropertyBuilder {
  return UIGestureRecognizerReactivePropertyBuilder(view)
}

/** A scoped property builder for UIGestureRecognizer instances. */
public class UIGestureRecognizerReactivePropertyBuilder {

  /** A property representing the view's .isEnabled value. */
  public var isEnabled: ReactiveProperty<Bool> {
    let gestureRecognizer = self.gestureRecognizer
    return ReactiveProperty(read: { gestureRecognizer.isEnabled },
                            write: { gestureRecognizer.isEnabled = $0 })
  }

  private let gestureRecognizer: UIGestureRecognizer
  fileprivate init(_ gestureRecognizer: UIGestureRecognizer) {
    self.gestureRecognizer = gestureRecognizer
  }
}


Add an additional test-case for rdar://46713933 with literal arguments

// RUN: %target-typecheck-verify-swift -solver-expression-time-threshold=1
// REQUIRES: tools-release,no_asan

func wrap<T>(_ key: String, _ value: T) -> T { return value }
func wrap<T: ExpressibleByIntegerLiteral>(_ key: String, _ value: T) -> T { return value }
func wrap<T: ExpressibleByFloatLiteral>(_ key: String, _ value: T) -> T { return value }
func wrap<T: ExpressibleByStringLiteral>(_ key: String, _ value: T) -> T { return value }

func wrapped() -> Int {
  return wrap("1", 1) + wrap("1", 1) + wrap("1", 1) + wrap("1", 1)
  // expected-error@-1 {{the compiler is unable to type-check this expression in reasonable time}}
}


// RUN: %target-swift-frontend -emit-ir %s

public protocol SomeProto {
    associatedtype ThingType
	func getThing() -> ThingType
}

public protocol SpecialThing: RandomAccessCollection {
}

public protocol Castable {
	associatedtype Source
	static func cast(from: Source) -> Self
}

public struct ThingGetter<P: SomeProto, T> {
	public let thing: P
}

extension ThingGetter where P.ThingType: SpecialThing, T: Castable, P.ThingType.Iterator.Element == T.Source {

	public func getView() -> ThingView {
		return ThingView(thing: thing.getThing())
	}

	public struct ThingView: SpecialThing {
		let thing: P.ThingType

		public typealias Index = P.ThingType.Index
		public var startIndex: Index    { return thing.startIndex }
		public var endIndex:   Index    { return thing.startIndex }
		public var count: Int           { return thing.count }
		public func index(after i: Index) -> Index {
			return thing.index(after: i)
		}
		public func index(before i: Index) -> Index {
			return thing.index(before: i)
		}
		public subscript(i: Index) -> T {
			return T.cast(from: thing[i])
		}
	}
}


Add non-fuzzing crash case submitted by @kiliankoe

// This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors

// Credits: https://twitter.com/kiliankoe/status/752090953977036800

// RUN: not --crash %target-swift-frontend %s -parse
extension Dictionary {
    func a<b: Sequence where Value: Sequence>() -> Dictionary<Key, b> {
    }
}


Add a test for referencing a type nested in a generic class from a derived class

// RUN: %target-typecheck-verify-swift

enum E { case A }

class C<T> {
  struct Nested {
    var value: T
  }
}

class D: C<E> {
  func test() {
    _ = Nested(value: .A)
  }
}


Add test case for crash triggered in swift::TypeChecker::checkGenericParamList(swift::ArchetypeBuilder*, swift::GenericParamList*, swift::GenericSignature*, bool, swift::GenericTypeResolver*)

// This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors

// RUN: not --crash %target-swift-frontend %s -parse
// REQUIRES: asserts
let w{class c:A.b:class A{func b where h=c


// swift-tools-version:4.2
import PackageDescription

let package = Package(
    name: "Motion",
    // platforms: [.iOS("8.0")],
    products: [
        .library(name: "Motion", targets: ["Motion"])
    ],
    targets: [
        .target(
            name: "Motion",
            path: "Sources"
        )
    ]
)


Add regression test for scicolsim bug with arrays and for loops


Add test case for crash triggered in swift::constraints::ConstraintGraphNode::getMemberType(swift::Identifier, std::function<swift::TypeVariableType* ()>)

// RUN: not --crash %target-swift-frontend %s -parse

// Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing

protocol A{func<
typealias f:A
protocol A{
class a
typealias f:a


Add test case for crash triggered in swift::SpecializedProtocolConformance::getTypeWitnessSubstAndDecl(swift::AssociatedTypeDecl*, swift::LazyResolver*) const

// RUN: not --crash %target-swift-ide-test -code-completion -code-completion-token=A -source-filename=%s
struct A<c{class a<A{enum S:CollectionType
#^A^#


Add test case for crash triggered in swift::Mangle::Mangler::mangleNominalType(swift::NominalTypeDecl const*, swift::ResilienceExpansion, swift::Mangle::Mangler::BindGenerics, swift::CanGenericSignature, swift::GenericParamList const*)

// RUN: not --crash %target-swift-ide-test -code-completion -code-completion-token=A -source-filename=%s
let a{struct S<T{var f=a#^A^#let a{func l{init(={struct S{enum a{struct B{var _=


Add test case for crash triggered in swift::constraints::ConstraintSystem::openGeneric(swift::DeclContext*, swift::DeclContext*, llvm::ArrayRef<swift::GenericTypeParamType*>, llvm::ArrayRef<swift::Requirement>, bool, swift::constraints::ConstraintLocatorBuilder, llvm::DenseMap<swift::CanType, swift::TypeVariableType*, llvm::DenseMapInfo<swift::CanType>, llvm::detail::DenseMapPair<swift::CanType, swift::TypeVariableType*> >&)

// RUN: not --crash %target-swift-ide-test -code-completion -code-completion-token=A -source-filename=%s
// REQUIRES: asserts
e{protocol c{
class A{let a{
let a=B
struct B<T{let b=#^A^#


/// Test -emit-imported-modules with module aliasing.
///

// RUN: %empty-directory(%t)
// RUN: %{python} %utils/split_file.py -o %t %s

/// Create AppleLogging.swiftmodule by aliasing XLogging
// RUN: %target-swift-frontend -module-name AppleLogging -module-alias XLogging=AppleLogging %t/FileLogging.swift -emit-module -emit-module-path %t/AppleLogging.swiftmodule
// RUN: test -f %t/AppleLogging.swiftmodule

/// Verify emitted imported modules contains AppleLogging as a module name
// RUN: %target-swift-frontend -emit-imported-modules %t/FileLib.swift -module-alias XLogging=AppleLogging -I %t > %t/result.output

// RUN: %FileCheck %s -input-file %t/result.output -check-prefix CHECK-AST
// CHECK-AST: AppleLogging
// RUN: not %FileCheck %s -input-file %t/result.output -check-prefix CHECK-NOT-AST
// CHECK-NOT-AST: XLogging

// BEGIN FileLogging.swift
public struct Logger {
  public init() {}
}
public func setup() -> XLogging.Logger? {
  return Logger()
}

// BEGIN FileLib.swift
import XLogging

public func start() -> XLogging.Logger? {
  return XLogging.setup()
}

public func end(_ arg: XLogging.Logger) {
}


// Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
// RUN: %swift -parse %s -verify

func b((Any, e))(e: (Any) -> <d>(()-> d) -> f // expected-error{{use of undeclared type}}
// expected-error@-1{{expected ',' separator}}
// expected-error@-2{{expected ',' separator}}
// expected-error@-3{{expected parameter typ}}

Update validation test for diagnostic drift.

// Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
// RUN: %swift -parse %s -verify

func b((Any, e))(e: (Any) -> <d>(()-> d) -> f // expected-error{{type annotation missing in pattern}} expected-error{{expected type for function result}} expected-error{{use of undeclared type 'e'}}
// expected-error@-1{{expected ',' separator}}
// expected-error@-2{{expected ',' separator}}
// expected-error@-3{{expected parameter typ}}


Add 💥 case (😢 → 44, 😀 → 5089) triggered in swift::TypeBase::getString(…) const

// This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors

// RUN: not --crash %target-swift-frontend %s -parse
// REQUIRES: asserts
{protocol e{typealias e enum b{case func a{{enum B:e


Add test case for crash triggered in swift::TypeBase::getDesugaredType()

// RUN: not --crash %target-swift-ide-test -code-completion -code-completion-token=A -source-filename=%s
class#^A^#class B{class B:a{}let a=B{


Add test to check handling of nested array insertions

#include <builtins.swift>
#include <assert.swift>
#include <sys.swift>

main {
    // Regression test for nested arrays to check
    // that closing works properly
    // Run with -O0

    //
    int A[][][];

    // Try to delay insert
    A[id(0)][id_sleep(0)][0] = 1;
    A[id(0)][id(0)][id_sleep(1)] = 2;
    A[id(0)][id(0)][2] = 3;
    A[id(1)][id(0)][0] = 4;
    A[id(0)][id(1)][0] = 5;
    A[id(0)][id(1)][1] = 6;

    //assertEqual(size(A[0]), 1, "size of A[0]");
    foreach x, i in A[0] {
        trace("Elem", i);
        foreach y,j in x {
            trace("A[0][" + fromint(i) + "][" + fromint(j) + "] = "
                          + fromint(y));
        }
    }
    wait(A) {
        trace("A closed");
    }
    wait (A[0]) {
        trace("A[0] closed");
    }
    wait (A[0][0]) {
        trace("A[0][0] closed");
    }
    wait (A[0][1]) {
        trace("A[0][1] closed");
    }

    int B[][][];
    // Test nested loops
    foreach i in [0:3] {
        foreach j in [0:3] {
            foreach k in [0:3] {
                // Delay insert to force dataflow eval
                B[id_sleep(i)][id_sleep(j)][id_sleep(k)] = i + j + k;
            }
        }
    }
}

(int o) id_sleep (int i) {
    wait (sleep(0.05)) {
        o = i;
    }
}

(int o) id (int i) {
    o = i;
}


Add new Swift compiler crash with extension of generic type with type alias

import Foundation;

public protocol HasReflect {
    typealias T : HasReflect
    static func reflect() -> Type<T>
}
public protocol JsonSerializable : HasReflect, StringSerializable {
}
public protocol StringSerializable {
    typealias T
    static func fromString(string:String) -> T?
}
public class TypeAccessor {}

public class Type<T : HasReflect> : TypeAccessor {
}

public class QueryResponse<T : JsonSerializable> {}

extension QueryResponse : JsonSerializable
{
    public static func reflect() -> Type<QueryResponse<T>> {
        return Type<QueryResponse<T>>()
    }
    public static func fromString(string:String) -> QueryResponse<T>? {
        return nil
    }
}


Add a struct to prevent array decoding to fail if some item is not there

import Foundation

public struct FailableCodableArray<Element : Decodable> : Decodable {

    public var elements: [Element]

    public init(from decoder: Decoder) throws {
        let container = try decoder.singleValueContainer()
        let elements = try container.decode([FailableDecodable<Element>].self)
        self.elements = elements.compactMap { $0.base }
    }
}

private struct FailableDecodable<Base : Decodable> : Decodable {

    let base: Base?

    init(from decoder: Decoder) throws {
        let container = try decoder.singleValueContainer()
        self.base = try? container.decode(Base.self)
    }
}


Add 💥 case (😢 → 48, 😀 → 5090) triggered in swift::TypeBase::getDesugaredType(…)

// This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors

// RUN: not --crash %target-swift-frontend %s -parse
let a{extension{enum k:String{{{}}case


Add test case for crash triggered in swift::ValueDecl::getInterfaceType() const

// RUN: not --crash %target-swift-frontend %s -parse
// REQUIRES: asserts

// Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing

protocol c{typealias e:a:protocol a{typealias a}func b:e.c


//
//  EventDetailViewController.swift
//  motified
//
//  Created by Giancarlo Anemone on 3/25/15.
//  Copyright (c) 2015 Giancarlo Anemone. All rights reserved.
//

import UIKit

class EventDetailViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepareForSegue(segue: UIStoryboardSegue!, sender: AnyObject!) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}


Add test case for crash triggered in swift::TypeChecker::resolveWitness(swift::NormalProtocolConformance const*, swift::ValueDecl*)

// This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors

// RUN: not --crash %target-swift-frontend %s -parse
// REQUIRES: asserts
{protocol A{
func b
typealias e
}
struct Q<d{
var:{struct B:A{
typealias e:d
var a{
b


Add test case for crash triggered in swift::DeclContext::lookupQualified(swift::Type, swift::DeclName, unsigned int, swift::LazyResolver*, llvm::SmallVectorImpl<swift::ValueDecl*>&) const

// RUN: not --crash %target-swift-frontend %s -parse
// REQUIRES: asserts

// Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing

for in.f=Swift.dynamicType.e.n


Add test case for crash triggered in swift::TypeChecker::resolveTypeWitness(swift::NormalProtocolConformance const*, swift::AssociatedTypeDecl*)

// RUN: not --crash %target-swift-frontend %s -parse

// Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing

protocol A{
class A:a{
}
typealias e:a
protocol a{
typealias r
}
typealias e:A


type arrays {
  int X[];
  float Y[];
  string Z[];
}

main {
  arrays x;

  # Check storing array at struct subscript
  x.X = [1,2,3];

  f(x);

  x.Y = [3.142];
  x.Z = ["a", "b", "c"];
}

f (arrays s) {
  print_arrays(s.X, s.Y, s.Z);
}

print_arrays (int a1[], float a2[], string a3[]) "turbine" "0.0.1" [
    "puts [ list <<a1>> <<a2>> <<a3>> ] "
];


// RUN: not %target-swift-frontend -typecheck  %s

public struct {
    @UserDefault()
    public static var region: String
}

@propertyWrapper
public struct UserDefault {
    init() {}
    public var wrappedValue: String
}


Add test case for crash triggered in swift::Mangle::Mangler::mangleGenericSignatureParts(llvm::ArrayRef<swift::GenericTypeParamType*>, unsigned int, llvm::ArrayRef<swift::Requirement>, swift::ResilienceExpansion)

// RUN: not --crash %target-swift-ide-test -code-completion -code-completion-token=A -source-filename=%s
// REQUIRES: asserts
var b{class d<A{
func a{struct S<T
{func a{
func b<i{let h:St
class a{var _=#^A^#


//
//  IconGenerator.swift
//  IGIdenticonExample
//
//  Created by Evgeniy Yurtaev on 19/11/2016.
//  Copyright © 2016 Evgeniy Yurtaev. All rights reserved.
//

import CoreGraphics
#if os(iOS) || os(watchOS) || os(tvOS)
import UIKit
#elseif os(macOS)
import AppKit
#endif

public protocol IconGenerator {
    func icon(from number: UInt32, size: CGSize) -> CGImage
}

#if os(iOS) || os(watchOS) || os(tvOS)
public extension IconGenerator {
    func icon(from number: UInt32, size: CGSize, scale: CGFloat = UIScreen.main.scale) -> UIImage {
        let scaledSize = CGSize(width: size.width * scale, height: size.height * scale)
        let cgImage: CGImage = icon(from: number, size: scaledSize)

        return UIImage(cgImage: cgImage, scale: scale, orientation: UIImageOrientation.up)
    }
}
#endif

#if os(macOS)
public extension IconGenerator {
    func icon(from number: UInt32, size: CGSize, scale: CGFloat) -> NSImage {
        let scaledSize = CGSize(width: size.width * scale, height: size.height * scale)
        let cgImage: CGImage = icon(from: number, size: scaledSize)

        return NSImage(cgImage: cgImage, size: size)
    }
}
#endif


Add test case for crash triggered in swift::TypeChecker::typeCheckFunctionBodyUntil(swift::FuncDecl*, swift::SourceLoc)

// RUN: not --crash %target-swift-frontend %s -parse
// REQUIRES: asserts

// Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing

func a(.,Int={}){


Add test case for crash triggered in swift::constraints::ConstraintSystem::solveSimplified(llvm::SmallVectorImpl<swift::constraints::Solution>&, swift::FreeTypeVariableBinding)

// RUN: not --crash %target-swift-frontend %s -parse

// Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing

{func a(a)class a{deinit{a(a{


Add test case for crash triggered in swift::DependentGenericTypeResolver::resolveSelfAssociatedType(swift::Type, swift::DeclContext*, swift::AssociatedTypeDecl*)

// RUN: not --crash %target-swift-frontend %s -parse
// REQUIRES: asserts

// Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing

struct g
struct c{}protocol c{typealias e:d
class d<T where g:e.T


// RUN: %empty-directory(%t)
// RUN: cd %t && %target-swift-frontend -interpret %S/../Inputs/empty.swift
// RUN: not ls %t/*

Add Requires line to test.

// REQUIRES: swift_interpreter
// RUN: %empty-directory(%t)
// RUN: cd %t && %target-swift-frontend -interpret %S/../Inputs/empty.swift
// RUN: not ls %t/*


Add tests for occurrences, uniques and duplicates

import XCTest
@testable import SequenceExtensions

class SequenceTests: XCTestCase {
  func testShouldReturnCorrectValue () {
    XCTAssertEqual([Int]().occurrences, [Int: Int]())
    XCTAssertEqual([0, 1, 1, 2, 2, 2].occurrences, [0: 1, 1: 2, 2: 3])

    XCTAssertEqual([Int]().uniques, [Int]())
    XCTAssertEqual([0, 1, 1, 2, 2, 2].uniques, [0, 1, 2])

    XCTAssertEqual([Int]().duplicates, [Int]())
    XCTAssertEqual([0, 1, 1, 2, 2, 2].duplicates, [1, 2, 2])

    XCTAssertEqual([Int]().duplicates.uniques, [Int]())
    XCTAssertEqual([0, 1, 1, 2, 2, 2].duplicates.uniques, [1, 2])
  }
}


Add test case for crash triggered in swift::SpecializedProtocolConformance::getTypeWitnessSubstAndDecl(swift::AssociatedTypeDecl*, swift::LazyResolver*) const

// RUN: not --crash %target-swift-ide-test -code-completion -code-completion-token=A -source-filename=%s
struct A<c{class a<A{enum S:CollectionType
#^A^#


import Foundation
import StoreKit

extension MStoreKit
{
    //MARK: storekit

    func request(
        _ request:SKRequest,
        didFailWithError error:Error)
    {
        model?.statusError(error:error.localizedDescription)
    }

    func paymentQueue(
        _ queue:SKPaymentQueue,
        updatedTransactions transactions:[SKPaymentTransaction])
    {

    }

    func productsRequest(
        _ request:SKProductsRequest,
        didReceive response:SKProductsResponse)
    {
    }
}


Add 'asserts' as a REQUIRES feature for lit tests.

// REQUIRES: asserts

// RUN: %swift -emit-llvm %S/Inputs/single_int.swift -o /dev/null -print-stats 2>&1 | FileCheck %s -check-prefix=STATS
// STATS: Statistics Collected
// Only print statistics once
// STATS-NOT: Statistics Collected


Index a String with a Range to get a sub String.

// RUN: %swift %s -i | FileCheck %s

func test(s : String)
{
    println(s)
    var s2 = s[2..4]
    println(s2)
}

test("some text")

// CHECK: some text
// CHECK: me


Add mathmatical calculation uses variable

import Foundation

var num1 = 62
var num2 = 10

print("\(num1) + \(num2) = \(num1 + num2)")
print("\(num1) - \(num2) = \(num1 - num2)")
print("\(num1) * \(num2) = \(num1 * num2)")
print("\(num1) / \(num2) = \(num1 / num2)")
print("\(num1) % \(num2) = \(num1 % num2)")


Add recent crasher test case from swift-compiler-crashes.

// RUN: not --crash %swift %s -emit-ir
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// http://www.openradar.me/17317691

func f() {
    ({})
}


Add test case for crash triggered in swift::ValueDecl::setType(swift::Type)

// RUN: not --crash %target-swift-frontend %s -parse
// REQUIRES: asserts

// Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing

func f{{for b{}{String($0


Add a test-case for a fixed SourceKit crasher

// RUN: %target-swift-ide-test -code-completion -code-completion-token=A -source-filename=%s

enum E1 {
  case X
  case Y
}
enum E2 {
  case A
  case B
  case C
}

func foo() -> ([E1], [E2]) {
  return ([.X], [.A, .B, .#^A^#])
}


Test that tag construction is injective.

//  Copyright © 2015 Rob Rix. All rights reserved.

final class TagTests: XCTestCase {
	func testConstructsOneTagPerLabel() {
		assert(Tag.tags([ "a", "b", "c" ]).count, ==, 3)
	}
}

import Assertions
@testable import Manifold
import XCTest


// RUN: %target-swift-frontend -typecheck %s

protocol AuthenticationFlowStateMachine {
    associatedtype StartState: AuthenticationFlowStateMachineStartState where StartState.StateMachine == Self
    associatedtype NonFinalState: AuthenticationFlowStateMachineNonFinalState where NonFinalState.StateMachine == Self
    associatedtype FlowError: AuthenticationFlowStateMachineFlowError where FlowError.StateMachine == Self
}

protocol AuthenticationFlowStateMachineFlowError: Error {
    associatedtype StateMachine: AuthenticationFlowStateMachine where StateMachine.FlowError == Self
}

protocol AuthenticationFlowStateMachineStartState {
    associatedtype StateMachine: AuthenticationFlowStateMachine where StateMachine.StartState == Self
    var nonFinalState: StateMachine.NonFinalState { get }
}

protocol AuthenticationFlowStateMachineNonFinalState {
    associatedtype StateMachine: AuthenticationFlowStateMachine where StateMachine.NonFinalState == Self
}


import Foundation

struct Town {

    static let region = "South"
    var population = 5422 {
        didSet(oldPopulation) {

            // BRONZE CHALLENGE
            //
            //  - only print population change if population is less than old population
            //
            if population < oldPopulation {
                print("The population has changed to \(population) from \(oldPopulation).")
            }

        }
    }
    var numberOfStoplights = 4

    enum Size {
        case Small
        case Medium
        case Large
    }

    var townSize: Size {
        get {
            switch self.population {
            case 0...10_000:
                return Size.Small

            case 10_001...100_000:
                return Size.Medium

            default:
                return Size.Large
            }
        }
    }

    func printTownDescription() {
        print("Population: \(population); number of stoplights: \(numberOfStoplights)")
    }

    mutating func changePopulation(amount: Int) {
        population += amount
    }
}


Add test case for crash triggered in swift::PrintOptions::setArchetypeTransform(swift::Type, swift::DeclContext*)

// RUN: not --crash %target-swift-ide-test -code-completion -code-completion-token=A -source-filename=%s
// REQUIRES: asserts
var b{class d<a{enum S<a>:C{#^A^#


Add a test for long input-path bug (0e5b982d)

// REQUIRES: OS=macosx
// RUN: rm -rf %t && mkdir -p %t
// RUN: mkdir -p %t/very-long-directory-name-that-contains-over-128-characters-which-is-not-enough-to-be-illegal-on-its-own-but-presents
// RUN: cp %s %t/very-long-directory-name-that-contains-over-128-characters-which-is-not-enough-to-be-illegal-on-its-own-but-presents/a-problem-when-combined-with-other-long-path-elements-and-filenames-to-exceed-256-characters-combined-because-yay-arbitrary-limits-amirite.swift
// RUN: touch %t/main.swift
// RUN: %target-swiftc_driver -o %t/main -module-name main -stats-output-dir %t %t/main.swift %t/very-long-directory-name-that-contains-over-128-characters-which-is-not-enough-to-be-illegal-on-its-own-but-presents/a-problem-when-combined-with-other-long-path-elements-and-filenames-to-exceed-256-characters-combined-because-yay-arbitrary-limits-amirite.swift
// RUN: %utils/process-stats-dir.py --set-csv-baseline %t/frontend.csv %t
// RUN: %FileCheck -input-file %t/frontend.csv %s

// CHECK: {{"AST.NumSourceLines"	[1-9][0-9]*$}}
// CHECK: {{"IRModule.NumIRFunctions"	[1-9][0-9]*$}}
// CHECK: {{"LLVM.NumLLVMBytesOutput"	[1-9][0-9]*$}}

public func foo() {
    print("hello")
}


Add a test to check if OptionSet literals are fully folded

// RUN: %target-swift-frontend  -parse-as-library -primary-file %s -O -sil-verify-all -module-name=test -emit-sil | %FileCheck %s
// RUN: %target-swift-frontend  -parse-as-library -primary-file %s -Osize -sil-verify-all -module-name=test -emit-sil | %FileCheck %s
// REQUIRES: swift_stdlib_no_asserts,optimized_stdlib

public struct TestOptions: OptionSet {
    public let rawValue: Int
    public init(rawValue: Int) { self.rawValue = rawValue }

    static let first    = TestOptions(rawValue: 1 << 0)
    static let second  = TestOptions(rawValue: 1 << 1)
    static let third   = TestOptions(rawValue: 1 << 2)
    static let fourth   = TestOptions(rawValue: 1 << 3)
}

// CHECK:      sil @{{.*}}returnTestOptions{{.*}}
// CHECK-NEXT: bb0:
// CHECK-NEXT:   integer_literal {{.*}}, 15
// CHECK-NEXT:   struct $Int
// CHECK-NEXT:   struct $TestOptions
// CHECK-NEXT:   return
public func returnTestOptions() -> TestOptions {
    return [.first, .second, .third, .fourth]
}

// CHECK:        alloc_global @{{.*}}globalTestOptions{{.*}}
// CHECK-NEXT:   global_addr
// CHECK-NEXT:   integer_literal {{.*}}, 15
// CHECK-NEXT:   struct $Int
// CHECK-NEXT:   struct $TestOptions
// CHECK-NEXT:   store
// CHECK-NEXT:   tuple
// CHECK-NEXT:   return
let globalTestOptions: TestOptions = [.first, .second, .third, .fourth]


Add a solution to Longest Valid Parentheses

/**
 * Question Link: https://leetcode.com/problems/longest-valid-parentheses/
 * Primary idea: Push index to a stack and pop encountering ")"
 * Time Complexity: O(n), Space Complexity: O(n)
 */

class LongestValidParentheses {
    func longestValidParentheses(_ s: String) -> Int {
        let sChars = Array(s.characters)
        var stack = [Int]()
        var longest = 0

        for (i, char) in sChars.enumerated() {
            if char == "(" || stack.isEmpty || sChars[stack.last!] == ")" {
                stack.append(i)
            } else {
                let _ = stack.removeLast()
                if stack.isEmpty {
                    longest = max(longest, i + 1)
                } else {
                    longest = max(longest, i - stack.last!)
                }
            }
        }

        return longest
    }
}


import UIKit
import MapKit

class ViewController: UIViewController, MKMapViewDelegate {

    override func viewDidLoad() {
        super.viewDidLoad()

        // Add the longitude and latitude
        var longitude:CLLocationDegrees = 98.3
        var latitude:CLLocationDegrees = 21.44

        // Latitude delta: The map will look more zoom-in
        var latDelta:CLLocationDegrees = 0.01
        // Longitude delta
        var longDelta:CLLocationDegrees = 0.01

        // It defines the latitude and longitude directions to show on a map.
        var spanCoordinate: MKCoordinateSpan = MKCoordinateSpanMake(latDelta, longDelta)

    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}

Set the location for the m map using CLLocationCoordinate2D

import UIKit
import MapKit

class ViewController: UIViewController, MKMapViewDelegate {

    override func viewDidLoad() {
        super.viewDidLoad()

        // Add the longitude and latitude
        var longitude:CLLocationDegrees = 98.3
        var latitude:CLLocationDegrees = 21.44

        // Latitude delta: The map will look more zoom-in
        var latDelta:CLLocationDegrees = 0.01
        // Longitude delta
        var longDelta:CLLocationDegrees = 0.01

        // It defines the latitude and longitude directions to show on a map.
        var spanCoordinate: MKCoordinateSpan = MKCoordinateSpanMake(latDelta, longDelta)

        // Set the location
        var myLocation:CLLocationCoordinate2D = CLLocationCoordinate2DMake(latitude, longitude)

    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}


Add test case for crash triggered in swift::TypeBase::getSuperclass(swift::LazyResolver*)

// RUN: not --crash %target-swift-ide-test -code-completion -code-completion-token=A -source-filename=%s
(){extension{class b<e{class d:d{extension{var b{class a:c#^A^#


Add test case for crash triggered in swift::TypeChecker::resolveTypeInContext(swift::TypeDecl*, swift::DeclContext*, swift::OptionSet<swift::TypeResolutionFlags, unsigned int>, bool, swift::GenericTypeResolver*, llvm::function_ref<bool (swift::TypeCheckRequest)>*)

// RUN: not --crash %target-swift-ide-test -code-completion -code-completion-token=A -source-filename=%s
// REQUIRES: asserts
A{extension{
class A{func c
var d=c let t{#^A^#


// RUN: %target-swift-emit-silgen %s | %FileCheck %s

// REQUIRES: objc_interop

import Foundation
import CoreGraphics

let _: (CFURL) -> CGDataProvider? = CGDataProvider.init

// CHECK-LABEL: sil private [ossa] @$s15cf_curried_initSo17CGDataProviderRefaSgSo8CFURLRefacfu_ : $@convention(thin) (@guaranteed CFURL) -> @owned Optional<CGDataProvider>
// CHECK-LABEL: sil [available 10.0] [clang CGDataProvider.init] @CGDataProviderCreateWithURL : $@convention(c) (CFURL) -> @owned Optional<CGDataProvider>