Skip to content
rn2kmpPublic

About

Compiler core, annotations, frontends and backends

Topics

Resources

Stars

2 stars

Watchers

0 watching

Forks

Repository files navigation

rn2kmp compiler

rn2kmp lets a React Native app use Kotlin Multiplatform code, so the app can move from React Native to KMP one component at a time. The compiler reads annotated Kotlin declarations and generates everything that connects them to React Native:

  • a React Native package (TypeScript API, TurboModule and Fabric specs, Android library, iOS pod);
  • Kotlin view hosts in the KMP project, which put each @Composable component inside an Android or iOS view.

The generated code uses the React Native New Architecture (TurboModules and Fabric) and RN codegen. On iOS it calls the Objective-C API that Kotlin/Native exports, and on Android it calls the Kotlin artifact.

Most projects should not use the compiler directly: the rn2kmp Gradle plugin runs it in a KMP project and explains how to set up an app.

How it works

Kotlin sources ──► frontend-ksp ──► registry.json (IR) ──► backends ──► generated files
 (annotated)        (KSP processor)                      TypeScript     React Native package
                                                          Android        + KMP androidMain / iosMain
                                                          iOS
  1. Frontend. frontend-ksp is a KSP processor. It reads the declarations annotated with annotations, checks that they can be bridged, and writes them to rn2kmp/registry.json in the KSP resources output.

  2. IR. ir holds the registry model (declarations, callables, types) and the shared binding model (dev.rn2kmp.ir.bindings). The binding model decides, once for all backends, the name of every method, event, type and parameter that crosses the bridge, so the TypeScript, Kotlin and Objective-C sides always agree.

  3. Backends. Each backend implements Backend<C>.generate(registry, configuration) and returns GeneratedFiles, each with a FileDestination:

    Destination Content
    REACT_NATIVE_PACKAGE The generated npm package
    KMP_ANDROID_MAIN, KMP_IOS_MAIN Kotlin view hosts and the rn2kmp runtime, compiled with the KMP project
    KMP_PROJECT Files written next to the KMP build script, never cleaned (the package.json of the KMP pod)
    KMP_COMMON_MAIN Not used: KSP reads the common source set to build the registry

Modules

Module Role
annotations @ReactNativeFunction, @ReactNativeProperty, @ReactNativeClass, @ReactNativeType, @ReactNativeComponent (multiplatform)
frontend-ksp KSP processor writing the registry
ir Registry model, backend API, shared binding model and generated Kotlin runtime
backend-typescript package.json, TurboModule spec, Fabric component specs, typed API (src/types.ts, src/index.ts)
backend-android Android library: TurboModule, view managers, build.gradle.kts; Compose view hosts in androidMain
backend-ios Pod: TurboModule and Fabric views in Objective-C++, podspec; ComposeUIViewController hosts in iosMain

What gets generated

For a KMP project exposing a sayHello function and a GreetingView composable, under the default names:

package/
├── .gitignore                        ignores the whole folder: it is regenerated, never committed
├── package.json                      codegenConfig, dependency on the KMP pod package
├── react-native-kmp.podspec
├── src/
│   ├── NativeKmp.ts                  TurboModule spec
│   ├── GreetingViewNativeComponent.ts  Fabric component spec
│   ├── types.ts                      enums, value types, classes, conversions
│   └── index.ts                      public API: functions and React components
├── android/
│   ├── build.gradle.kts              builds and publishes the KMP Android artifact, then depends on it
│   └── src/main/java/…/              NativeKmpModule.kt, NativeKmpPackage.kt, GreetingViewManager.kt
└── ios/                              RCTNativeKmp.mm, RCTGreetingViewView.mm, conversions

Paths from the package to the KMP project are relative, so the package can be written anywhere. In practice it has to be inside the React Native app, as explained in the Gradle plugin README.

The KMP project gets a GreetingViewHost in androidMain (a ComposeView) and in iosMain (a ComposeUIViewController). React Native sets the props on the host, and the host recomposes the composable.

How Kotlin maps to JavaScript

Kotlin JavaScript
Boolean, String, Char boolean, string
Int, Double, Float, Long, unsigned numbers… number (Long and unsigned values lose precision above 2^53)
T? T | null
List, Set, Array, varargs arrays
Map<String, V> Record<string, V>
@ReactNativeType class (data class by default) a plain object, copied across the bridge
@ReactNativeType enum a union of the entry names
@ReactNativeClass class or interface a JS class holding a handle to the Kotlin object; call release() when done
@ReactNativeClass object a constant with its members
suspend fun a function returning a Promise
Lambda parameter a JS callback, called through a TurboModule event
@ReactNativeComponent composable a React component; props from parameters, events from () -> Unit style callbacks

Kotlin objects referenced from JavaScript stay alive in a handle registry (Rn2KmpHandles) until the JS side releases them.

Annotations

Exposure

  • @ReactNativeFunction exports a public function or an eligible constructor. @ReactNativeProperty exports a public property. Function and property annotations can be used on members of otherwise unexported types. Reference and singleton types include only annotated methods and properties.
  • @ReactNativeClass exports a class or interface by reference, or an object as a singleton. An exported concrete reference type also includes its public primary constructor, if present. Annotate secondary constructors to expose them and give them distinct names when needed.
  • @ReactNativeType exports a class by value or an enum by its entries. A value type needs a public primary constructor whose parameters are public val or var properties. Constructor bindings use Kotlin field names. Fields can be renamed on the exported surface using @ReactNativeProperty.
  • An unannotated dependency is still available. Data classes and value classes default to value representation, and ordinary classes and interfaces default to reference representation. Annotating a data class with @ReactNativeClass overrides that default.
  • @ReactNativeComponent requires a public androidx.compose.runtime.Composable function returning Unit. Top-level and singleton methods are supported. Ordinary parameters are props. Non-suspending, receiverless callbacks that return Unit are events. Compose Modifier and composable slots must have Kotlin defaults: React Native does not set them.

Every annotation takes an optional name to rename the export. Public names must match [A-Za-z_$][A-Za-z0-9_$]*. Top-level exports share a namespace, and member names are checked within their owner. Rename Kotlin overloads individually to export them together.

Registry boundaries

The registry covers the sources visible to a single KSP invocation, which is the common source set in a KMP project. It does not merge KMP source sets or reconcile separately annotated expect/actual declarations: select one export site per expect/actual pair. When source is unavailable, reference types from dependencies are recorded without their classpath members or supertypes.

Use-site projections, declaration-site variance, reified type parameters, platform types, specialized primitive arrays and inner classes produce diagnostics. Type aliases are expanded with their arguments. Callable context parameters are not supported.

Limitations

  • Generic declarations, recursive value types and function types outside parameters are rejected by the backends.
  • Kotlin default parameter values must be passed from JavaScript (except Modifier and slots of components).
  • Callbacks registered from JavaScript are never released.
  • iOS rejects Char in nullable, collection or lambda positions, value classes, extension properties and unsigned varargs, which Kotlin/Native exports as opaque types.
  • Two exported classes with the same name in different packages get the same Objective-C name.
  • An uncaught Kotlin exception in a synchronous iOS call crashes the app; suspend functions reject their promise.

Development

./gradlew test                 # frontend and backend tests
./gradlew publishToMavenLocal  # to use a local build from the Gradle plugin

The backend tests generate a sample package under backend-*/build/test-output, which is useful to read or to compile against React Native.

About

Compiler core, annotations, frontends and backends

Topics

Resources

Stars

2 stars

Watchers

0 watching

Forks

Releases

Sponsor this project

Packages

Contributors

Languages