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

(Dave DeLong) #1

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.

Should we add more mutating methods to `StaticString`?
Add #self, #Self to #function, #file, #line, #column
(Erica Sadun) #2

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.

(Ben Rimmington) #3

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

(Michael Ilseman) #4

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?

(Dave DeLong) #5

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:

(Tanner) #6

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

(Kenny Leung) #7

What is dsohandle?

(Adrian Zubarev) #8

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

(Tomáš Znamenáček) #9