Unreachable code path optimization hint for Swift

Overview

Unreachable

Platform Language: Swift CocoaPods - Unreachable Carthage codebeat badge License

Unreachable is a Swift µframework that allows for letting the compiler know when a code path is unreachable.

Build Status

Branch Status
master Build Status

Installation

Compatibility

  • Platforms:
    • macOS 10.9+
    • iOS 8.0+
    • watchOS 2.0+
    • tvOS 9.0+
    • Linux
  • Xcode 8.0+
  • Swift 3.0+ & 4.0

Install Using Swift Package Manager

The Swift Package Manager is a decentralized dependency manager for Swift.

  1. Add the project to your Package.swift.

    import PackageDescription
    
    let package = Package(
        name: "MyAwesomeProject",
        dependencies: [
            .Package(url: "https://github.com/nvzqz/Unreachable.git",
                     majorVersion: 1)
        ]
    )
  2. Import the Unreachable module.

    import Unreachable

Install Using CocoaPods

CocoaPods is a centralized dependency manager for Objective-C and Swift. Go here to learn more.

  1. Add the project to your Podfile.

    use_frameworks!
    
    pod 'Unreachable', '~> 1.2.0'

    If you want to be on the bleeding edge, replace the last line with:

    pod 'Unreachable', :git => 'https://github.com/nvzqz/Unreachable.git'
  2. Run pod install and open the .xcworkspace file to launch Xcode.

  3. Import the Unreachable framework.

    import Unreachable

Install Using Carthage

Carthage is a decentralized dependency manager for Objective-C and Swift.

  1. Add the project to your Cartfile.

    github "nvzqz/Unreachable"
    
  2. Run carthage update and follow the additional steps in order to add Unreachable to your project.

  3. Import the Unreachable framework.

    import Unreachable

Install Manually

Simply add Unreachable.swift into your project.

Usage

Try it out for yourself! Download the repo and open 'Unreachable.playground'.

Dynamic Loop Exit

In some cases, the only way a function returns a value is from within a loop, but the compiler may not have enough information to know that.

func getValue() -> Int {
    for i in 0... {
        if i == 20 {
            return i
        }
    }
    assertUnreachable()
}

Switch Conditions

A switch statement may have conditions applied to its branches that make it exhaustive, but that may not obvious to the compiler.

func sign(of value: Double?) -> FloatingPointSign? {
    switch value {
    case let x? where x >= 0:
        return .plus
    case let x? where x < 0:
        return .minus
    case .some:
        assertUnreachable()
    case .none:
        return nil
    }
}

Safety

It is undefined behavior for unreachable() to be called. To protect against this, it is recommended to use assertUnreachable() instead.

With assertUnreachable(), debug builds will exit via a fatal error if the function is called. In optimized builds, it's no different than calling unreachable().

Unreachable vs fatalError()

The assertUnreachable() function can be used as somewhat of a drop-in replacement for fatalError(). In debug mode, they emit similar instructions. However, when compiling with optimizations, assertUnreachable() allows its parent to emit very few instructions.

Here we're checking whether a UnicodeScalar has a value in the lower or upper range. Because we know that these are the only valid ranges, we can let the compiler know that the third branch is unreachable. If at some point x has a value that's not within either range, it will emit an assertion failure in unoptimized builds.

With Unreachable

func isLowerRange(_ x: UnicodeScalar) -> Bool {
    switch x.value {
    case 0...0xD7FF:
        return true
    case 0xE000...0x10FFFF:
        return false
    default:
        assertUnreachable()
    }
}

Assembly output:

        .globl  __T011Unreachable12isLowerRangeSbs7UnicodeO6ScalarVF
        .p2align        4, 0x90
__T011Unreachable12isLowerRangeSbs7UnicodeO6ScalarVF:
        pushq   %rbp
        movq    %rsp, %rbp
        cmpl    $55296, %edi
        setb    %al
        popq    %rbp
        retq

With fatalError()

func isLowerRange(_ x: UnicodeScalar) -> Bool {
    switch x.value {
    case 0...0xD7FF:
        return true
    case 0xE000...0x10FFFF:
        return false
    default:
        fatalError("Unreachable")
    }
}

Assembly output:

        .globl  __T011Unreachable12isLowerRangeSbs7UnicodeO6ScalarVF
        .p2align        4, 0x90
__T011Unreachable12isLowerRangeSbs7UnicodeO6ScalarVF:
        .cfi_startproc
        movb    $1, %al
        cmpl    $55296, %edi
        jb      LBB4_3
        addl    $-57344, %edi
        cmpl    $1056768, %edi
        jae     LBB4_4
        xorl    %eax, %eax
LBB4_3:
        retq
LBB4_4:
        pushq   %rbp
Lcfi0:
        .cfi_def_cfa_offset 16
Lcfi1:
        .cfi_offset %rbp, -16
        movq    %rsp, %rbp
Lcfi2:
        .cfi_def_cfa_register %rbp
        subq    $48, %rsp
        leaq    L___unnamed_2(%rip), %rax
        movq    %rax, (%rsp)
        movl    $0, 32(%rsp)
        movq    $56, 24(%rsp)
        movl    $2, 16(%rsp)
        movq    $69, 8(%rsp)
        leaq    L___unnamed_3(%rip), %rdi
        leaq    L___unnamed_4(%rip), %rcx
        movl    $11, %esi
        movl    $2, %edx
        movl    $11, %r8d
        xorl    %r9d, %r9d
        callq   __T0s17_assertionFailures5NeverOs12StaticStringV_SSAE4fileSu4lines6UInt32V5flagstFTfq4nxnnn_n
        subq    $40, %rsp
        .cfi_endproc

License

All source code for Unreachable is released under the MIT License.

Assets for Unreachable are released under the CC BY-SA 4.0 License and can be found in the assets branch.

You might also like...
A framework for building fast genetic algorithms in Swift.
A framework for building fast genetic algorithms in Swift.

Revolver is a framework for building fast genetic algorithms in Swift 3.0. Features Chromosomes: strings, trees Genetic operators: reproduction, mutat

A Swift deep learning library with Accelerate and Metal support.
A Swift deep learning library with Accelerate and Metal support.

Serrano Aiming to offering popular and cutting edge techs in deep learning area on iOS devices, Serrano is developed as a tool for developers & resear

A lightweight library to calculate tensors in Swift, which has similar APIs to TensorFlow's
A lightweight library to calculate tensors in Swift, which has similar APIs to TensorFlow's

TensorSwift TensorSwift is a lightweight library to calculate tensors, which has similar APIs to TensorFlow's. TensorSwift is useful to simulate calcu

Running Swift automatic differentiation on iOS
Running Swift automatic differentiation on iOS

Differentiation Demo This is an example of Swift's automatic differentiation running on iOS. It is a modified version of the game from ARHeadsetKit tu

Track List Detail App With Swift

TrackListDetailApp TrackListDetailApp is master-detail application that containsa a list of items obtained from a iTunes Search API and show a detaile

A Swift package for working with probability-driven randomness

ControlledChaos ControlledChaos is a simple Swift package for working with proba

This repo contains beginner examples to advanced in swift. Aim to create this for learning native iOS development.

iOS-learning-with-swift-22 This repo contains beginner examples to advanced in swift. Aim to create this for learning native iOS development. Oh, you

NGram: a Swift implementation to generate N-grams (all word combinations) from an input string

nGram nGram is a Swift implementation to generate N-grams (all word combinations

TensorFlow C API Class Wrapper in Server Side Swift.
TensorFlow C API Class Wrapper in Server Side Swift.

Perfect TensorFlow 简体中文 This project is an experimental wrapper of TensorFlow C API which enables Machine Learning in Server Side Swift. This package

Releases(v1.2.0)
Owner
Nikolai Vazquez
conducts curses, breaks things, and uses the oxford comma
Nikolai Vazquez
The source code of 'Visual Attribute Transfer through Deep Image Analogy'.

Deep Image Analogy The major contributors of this repository include Jing Liao, Yuan Yao, Lu Yuan, Gang Hua and Sing Bing Kang at Microsoft Research.

MSRA CVer 1.4k Jan 6, 2023
A Swift library for creating and exporting CoreML Models in Swift

SwiftCoreMLTools A Swift Library for creating CoreML models in Swift. Work in progress This library expose a (function builder based) DSL as well as a

Jacopo Mangiavacchi 140 Dec 5, 2022
Accelerated tensor operations and dynamic neural networks based on reverse mode automatic differentiation for every device that can run Swift - from watchOS to Linux

DL4S provides a high-level API for many accelerated operations common in neural networks and deep learning. It furthermore has automatic differentiati

Palle 87 Dec 29, 2022
The Swift machine learning library.

Swift AI is a high-performance deep learning library written entirely in Swift. We currently offer support for all Apple platforms, with Linux support

Swift AI 5.9k Jan 2, 2023
BrainCore is a simple but fast neural network framework written in Swift.

BrainCore is a simple but fast neural network framework written in Swift. It uses Metal which makes it screamin' fast. If you want to see it

Alejandro Isaza 377 Jun 29, 2022
MLKit is a simple machine learning framework written in Swift.

MLKit (a.k.a Machine Learning Kit) ?? MLKit is a simple machine learning framework written in Swift. Currently MLKit features machine learning algorit

Guled 152 Nov 17, 2022
Matft is Numpy-like library in Swift. Function name and usage is similar to Numpy.

Numpy-like library in swift. (Multi-dimensional Array, ndarray, matrix and vector library)

null 80 Dec 21, 2022
A simple Swift package which acts as an OpenAI client for the GPT-3 API.

SwiftyGPT3 A simple Swift package which acts as an OpenAI client for GPT-3 brought to you by the Airgift Crew. Supports GPT-3 Codex! Requirements iOS

Airgift 23 Dec 25, 2022
Artificial intelligence/machine learning data structures and Swift algorithms for future iOS development. bayes theorem, neural networks, and more AI.

Swift Brain The first neural network / machine learning library written in Swift. This is a project for AI algorithms in Swift for iOS and OS X develo

Vishal 331 Oct 14, 2022
A toolbox of AI modules written in Swift: Graphs/Trees, Support Vector Machines, Neural Networks, PCA, K-Means, Genetic Algorithms

AIToolbox A toolbox of AI modules written in Swift: Graphs/Trees, Linear Regression, Support Vector Machines, Neural Networks, PCA, KMeans, Genetic Al

Kevin Coble 776 Dec 18, 2022