C#, D and Haxe allow to define functions that receive information about the caller as parameters like the source file path, line number or member name via parameter attributes.
This is useful in several scenarios:
Scenario 1: Logging with position information without relying on stacktraces, without the overhead and reliably working on all the targets
Scenario 2: Another possible scenario in addition to class/method/file/linenumber, is providing something like call id or node id (a unique identifier in the caller function per call) we could implement Compose/React-like patterns without external plugins by being able to differentiate call places.
Proposed syntax:
fun logInternal(
message: String,
className: String?,
line: Int,
file: String
) {
println("$file:$line:$className: $message")
}
fun log(
message: String,
className: String? = intrinsicCallerClassName,
line: Int = intrinsicCallerLine,
file: String = intrinsicCallerSourceFile
) {
logInternal(message, className, line, file) // normal parameters, so we can propagate them
}
object MyClass {
fun sample() {
log("Hello World")
// replaced internally by the compiler with:
log("Hello World", className = "MyClass", line = 5, file = "MyClass.kt")
}
}
fun Scope.Text(text: String, uid: Int = intrinsicCallerNodeId) {
// ...
}
fun Scope.Demo() {
Text("hello"); Text("world")
if (something) {
Text("text")
} else {
Text("other")
}
}
// internally replaced with
fun Scope.Demo() {
Text("hello", uid = 1); Text("world", uid = 2)
if (something) {
Text("text", uid = 3)
} else {
Text("other", uid = 4)
}
}
Since it uses default parameters, you can propagate to other functions or replace those values as required.
This is tracked as KT-34553 "Provide source location information through compiler intrinsics" and depends on the support for KT-50113 "Inline default parameters for functions". I've added a link to your comments there.
C#, D and Haxe allow to define functions that receive information about the caller as parameters like the source file path, line number or member name via parameter attributes.
This is useful in several scenarios:
call id
ornode id
(a unique identifier in the caller function per call) we could implement Compose/React-like patterns without external plugins by being able to differentiate call places.Proposed syntax:
Since it uses default parameters, you can propagate to other functions or replace those values as required.