Mandatory method mangling when compiling to JS

The reason for mangling is the ability in Kotlin to overload function by parameter types. E.g. it’s possible to declare foo(x: Int) and foo(x: String) in the same scope, and these are different functions in terms of Kotlin. On a call site of foo compiler checks types and determines which of the functions called (or reports that none of the functions can be called with given parameters). It’s possible in JVM, since in JVM bytecode most of the calls to are encoded with invokevirtual or invokestatic opcodes, which require to specify both name and signature. However, there’s no such thing to JavaScript, so compiler has to invent the way to pass signature. The common technique is to calculate some unique suffix for each set of parameters.

Note that it’s impossible to declare large unmangled function that analyses parameter on run time and calls particular implementation, since run time loses some important information available to compiler. For example:

fun main(args: Array<String>) {
    foo("bar")
    foo("baz" as Any)
}

fun foo(x: String) {
    println("string");
}

fun foo(x: Any) {
    println("any");
}

is impossible to express via runtime resolution. Also, runtime resolution would be very slow, especially in some cases with generics.

Kotlin is not the only language which uses mangling. C++ generates mangled symbols in object files, so it’s impossible to call these functions from pure C. Moreoever, there’s no single standard mangling scheme for C++, so each compiler uses its own mangling algorithm. There’s extern "C" directive in C++ syntax that has effect more or less similar to JsName annotation in Kotlin.

1 Like