Kotlin / KEEP

Kotlin Evolution and Enhancement Process
Apache License 2.0
3.3k stars 356 forks source link

Intrinsics to get information about caller positions #305

Closed soywiz closed 1 year ago

soywiz commented 1 year ago

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:

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.

elizarov commented 1 year ago

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.