What's the usage and scenes to be used of sourceLocation?

#sourceLocation(file:"myfile.swift", line:10)
print("myfile.swift")
#sourceLocation()

You usually use #sourceLocation() when you're generating code and want errors to be attributed to the original location. For example, imagine you write a SwiftTemplate tool which takes a .swift-template file like this:

greeting(for name: String) = """
    Hello, \(name)!
    """

And spits out a .swift file like this:

func greeting(for name: String) -> (inout String) -> Void { return {
    $0 += """
    Hello, \(name)!
    """
} }

If there's an error in the string literal, you probably want the error message to point at the original .swift-template file, not the generated .swift file. You could do that with #sourceLocation():

func greeting(for name: String) -> (inout String) -> Void { return {
    #sourceLocation(file: "greeting.swiftTemplate", line: 1)
    $0 += """
    Hello, \(name)!
    """
    #sourceLocation()
} }
2 Likes