Supplement #file, #line, and #function with #context

I'd like to see a #context keyword for the compiler that expands in to a compiler generated struct:

struct Context {
    let file: StaticString
    let line: UInt
    let column: UInt
    let function: StaticString
    let dsohandle: UnsafeRawPointer
}

This would make it much easier to capture the context in which some code is executed rather than having to put file: StaticString = #file, line: UInt = #line parameters everywhere. A context: Context = #context would be much easier.

32 Likes

Pretty sure we've touched on this before. In any case, please add let fileName: StaticString, which is equivalent to lastPathComponent without having to import Foundation.

See also:

SR-198 requested the coalescing of existing identifiers. A structured #sourcelocation identifier could be added as a follow-on if and when the Swift team decides to tackle a standardized source location type, which would provide individual field or keyword access.

In support of summaries, Remy Demerest writes, "[I] love the idea that source location would be one object that you can print to get the full story while still retaining the possibility to use each individual components as needed, which is probably the rarer case. I never find myself wanting only some of properties and usually don't include them simply because it takes longer to write the format properly, if I can get them all in one go it's certainly a win."

Should such a type be adopted, I'd recommend support for common output summary representations suitably differentiated for debug and release logging. Alternatively #context, #releasecontext, and #debugcontext summaries could be added independently of the adoption of #sourcelocation.

Instead of using the last path component, this should be a module-relative path.

4 Likes

This sounds neat. Do you have any examples that want to use the context as a value in general, other than forwarding it on to the callee for debugging/logging?

For me, I've wanted this for debugging/backtracking/diagnosing. There might be other use cases for this, just as there might be other valid cases for using #file and #line in a release build.

I also want this to make up for some shortcomings in the compiler's handling of default arguments: [SR-6913] Default arguments are not evaluated correctly in larger expression · Issue #49462 · apple/swift · GitHub

1 Like

I would love this as well. This would of course save a lot of code but would also do wonders for discoverability via autocomplete.

What is dsohandle?

1 Like

I would also add let module: StaticString into the bucket. And the struct should also provide a StaticString version of line and column properties.

2 Likes

https://mobile.twitter.com/chriseidhof/status/722352741767639040