Swift compiler segmentation fault with String.fromCString and pipe-forward operator

Originator:kristopherdjohnson
Number:rdar://19204410 Date Originated:10-Dec-2014 09:24 AM
Status:Open Resolved:
Product:Developer Tools Product Version:6.1.1 (6A2008a)
Classification:Crash/Hang/Data Loss Reproducible:Always
 
Summary:
Defined an F#-style pipe-forward operator, which is intended to allow the notation "x |> f" be equivalent to "f(x)"

Expected code like this:

    let aCString: [CChar] = createACString()
    return aCString |> String.fromCString

to work as if it had been written like this:

    let aCString: [CChar] = createACString()
    return String.fromCString(aCString)

However, the compiler has a segmentation fault when it encounters the expression containing the pipe-forward operator.

The pipe-forward operator works as expected with many other expressions, so this seems to be an issue specific to String.fromCString or with the mechanism of treating an Array<T> like an UnsafePointer<T>.

Steps to Reproduce:
Paste the following into a Swift playground, and a compiler segmentation fault will occur:


import Foundation


// Pipe-forward operator

infix operator |> { associativity left }

public func |> <T,U>(lhs: T, rhs: T -> U) -> U {
    return rhs(lhs)
}


let data = Array("Hello, world!".utf8)

// Create a null-terminated string
func CStringAtAddress(index: Int, length: Int) -> [CChar] {
    var result = Array<CChar>(count: length + 1, repeatedValue: 0)
    for i in 0..<length {
        result[i] = CChar(data[index + i])
    }
    return result
}

// Create null-terminated string "Hello"
let cstring = CStringAtAddress(0, 5)
println("cstring = \(cstring)")


// Create a Swift String
func stringAtIndex(index: Int, length: Int) -> String? {
    // This is safe
    //return String.fromCString(CStringAtAddress(index, length))

    // This causes compiler segmentation fault
    return CStringAtAddress(index, length) |> String.fromCString
}

// Create Swift string "Hello"
let s = stringAtIndex(0, 5)
println("s = \(s)")

Expected Results:
Code should run and provide expected results, or compiler should indicate error

Actual Results:
Segmentation fault in compiler with no indication of anything wrong with the code

Version:
Xcode Version 6.1.1 (6A2008a)
OS X 10.10.1

Notes:
In the example code, uncomment the line under "// This is safe" and comment the line under "// This causes compiler segmentation fault" to verify that the code works as expected when the pipe-forward operator is not used.

Comments


Please note: Reports posted here will not necessarily be seen by Apple. All problems should be submitted at bugreport.apple.com before they are posted here. Please only post information for Radars that you have filed yourself, and please do not include Apple confidential information in your posts. Thank you!