Fix analysis tests for experimental_prune_transitive_deps (#1418) * Add example analysis_test with configuration * Fix analysis tests for experimental_prune_transitive_deps Revive PR #1343 by rbeazleyspot which adds analysis tests for the experimental_prune_transitive_deps feature. The original tests failed because config_settings creates a configuration transition, causing output paths to include a hash suffix (e.g., k8-fastbuild-ST-xxx). Fixed by comparing file basenames instead of full paths using matching.file_basename_equals() predicates. * Migrate from KSP1 (compiler plugin) to KSP2 (standalone tool) (#1405) * Migrate from KSP1 (compiler plugin) to KSP2 (standalone tool) KSP2 is a standalone program that runs separately from the Kotlin compiler, unlike KSP1 which was a compiler plugin. This migration required: - Add KSP2 tool definition in kotlin/compiler/ksp.bzl and BUILD.bazel - Implement _run_ksp_builder_actions in compile.bzl to invoke KSP2 as a separate action that produces tree artifacts for generated sources - Add tree_artifact_packager worker to package KSP2 output directories into srcjars for downstream compilation - Fix source-roots handling: KSP2 expects directory paths, not file paths - Update examples/ksp to use bzlmod (MODULE.bazel) instead of WORKSPACE - Expand KSP test coverage with Dagger-based coffee example demonstrating mixed Kotlin/Java code generation scenarios Key changes: - KSP now runs as a pre-compilation step producing generated sources - Generated sources are packaged into srcjars and compiled with main sources - Removed KSP1-specific code from KotlinToolchain and InternalCompilerPlugins * WIP * WIP * Fix * Fix * Move staging to the builder * Add tests, remove unused code * Fix test * Update KSP to 2.3.3 * Remove the note about KSP multiplex workers support * Address code review issues * Revert unnecessary change * compile against the ksp concrete classes * Bump bazel version on CI * Bump RBE ubuntu version to support bazel 7.7.1 * Bump bazel version on CI to 8.4.2 * Fix stardoc generation --------- Co-authored-by: Corbin McNeely-Smith <58151731+restingbull@users.noreply.github.com> * Fix post-merge error (#1420) * Document x_lambdas and x_sam_conversions defaults (#1419) * Document x_lambdas and x_sam_conversions defaults Explain that rules_kotlin defaults to "class" for x_lambdas and x_sam_conversions, differing from Kotlin 2.x/Gradle's "indy" default. Add README section with configuration examples for Gradle-compatible bytecode generation. Update API docs in opts.kotlinc.bzl to clarify the default behavior and compatibility implications. Closes #1417 * Simplify README lambda bytecode documentation Reduce the documentation to a concise note within the existing "Kotlin and Java compiler flags" section, with a single code example showing how to configure for invokedynamic behavior. --------- Co-authored-by: Ross Beazley <rbeazley@spotify.com> Co-authored-by: Corbin McNeely-Smith <58151731+restingbull@users.noreply.github.com> Co-authored-by: Jonathan Mohrbacher <johnnymo87@gmail.com>
For more information about release and changelogs please see Changelog or refer to the Github Releases page.
rules_kotlin Bazel Compatibility6, 76, 75, 64, 5, 6rules_kotlin supports the basic paradigm of *_binary, *_library, *_test of other Bazel language rules. It also supports jvm, android, and js flavors, with the prefix kt_jvm and kt_android typically applied to the rules.
Support for kotlin's -Xfriend-paths via the associates= attribute in the jvm allow access to internal members.
Also, kt_jvm_* rules support the following standard java_* rules attributes:
dataresource_jarsruntime_depsresourcesresources_strip_prefixexportsAdditionally, kt_jvm_binary and kt_jvm_test support environment variable configuration:
env - Dictionary of environment variables to set when the target is executed with bazel run or bazel testenv_inherit - List of environment variable names to inherit from the shell environmentAndroid rules also support custom_package for R.java generation, manifest=, resource_files, etc.
Other features:
Javascript is reported to work, but is not as well maintained (at present)
Generated API documentation is available at https://bazelbuild.github.io/rules_kotlin/kotlin.
Copy from the release you wish to use either the Bzlmod or WORKSPACE snippet into your MODULE.bazel or WORKSPACE file respectively.
WORKSPACEIn the project's WORKSPACE, declare the external repository and initialize the toolchains, like this:
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive") rules_kotlin_version = "1.9.0" rules_kotlin_sha = "5766f1e599acf551aa56f49dab9ab9108269b03c557496c54acaf41f98e2b8d6" http_archive( name = "rules_kotlin", urls = ["https://github.com/bazelbuild/rules_kotlin/releases/download/v%s/rules_kotlin-v%s.tar.gz" % (rules_kotlin_version, rules_kotlin_version)], sha256 = rules_kotlin_sha, ) load("@rules_kotlin//kotlin:repositories.bzl", "kotlin_repositories") kotlin_repositories() # if you want the default. Otherwise see custom kotlinc distribution below load("@rules_kotlin//kotlin:core.bzl", "kt_register_toolchains") kt_register_toolchains() # to use the default toolchain, otherwise see toolchains below
BUILD filesIn your project's BUILD files, load the Kotlin rules and use them like so:
load("@rules_kotlin//kotlin:jvm.bzl", "kt_jvm_library") kt_jvm_library( name = "package_name", srcs = glob(["*.kt"]), deps = [ "//path/to/dependency", ], )
To enable a custom toolchain (to configure language level, etc.) do the following. In a <workspace>/BUILD.bazel file define the following:
load("@rules_kotlin//kotlin:core.bzl", "define_kt_toolchain") define_kt_toolchain( name = "kotlin_toolchain", api_version = KOTLIN_LANGUAGE_LEVEL, # "1.9", "2.0", "2.1", "2.2", or "2.3" jvm_target = JAVA_LANGUAGE_LEVEL, # "1.8", "9", "10", "11", "12", "13", "15", "16", "17", "18", "19", "20", "21", or "22" language_version = KOTLIN_LANGUAGE_LEVEL, # "1.9", "2.0", "2.1", "2.2", or "2.3" )
and then in your WORKSPACE file, instead of kt_register_toolchains() do
register_toolchains("//:kotlin_toolchain")
kotlinc distribution (and version)To choose a different kotlinc distribution (1.3 and 1.4 variants supported), do the following in your WORKSPACE file (or import from a .bzl file:
MODULE.bazelrules_kotlin_extensions = use_extension("@rules_kotlin//src/main/starlark/core/repositories:bzlmod_setup.bzl", "rules_kotlin_extensions") rules_kotlin_extensions.kotlinc_version( version = "2.1.20", sha256 = "a118197b0de55ffab2bc8d5cd03a5e39033cfb53383d6931bc761dec0784891a" ) use_repo(rules_kotlin_extensions, "com_github_google_ksp", "com_github_jetbrains_kotlin", "com_github_jetbrains_kotlin_git", "com_github_pinterest_ktlint", "kotlinx_serialization_core_jvm", "kotlinx_serialization_json", "kotlinx_serialization_json_jvm")
WORKSPACEload("@rules_kotlin//kotlin:repositories.bzl", "kotlin_repositories", "kotlinc_version") kotlin_repositories( compiler_release = kotlinc_version( release = "2.1.20", sha256 = "a118197b0de55ffab2bc8d5cd03a5e39033cfb53383d6931bc761dec0784891a" ) )
(e.g. Maven artifacts)
Third party (external) artifacts can be brought in with systems such as rules_jvm_external or bazel_maven_repository or bazel-deps, but make sure the version you use doesn't naively use java_import, as this will cause bazel to make an interface-only (ijar), or ABI jar, and the native ijar tool does not know about kotlin metadata with respect to inlined functions, and will remove method bodies inappropriately. Recent versions of rules_jvm_external and bazel_maven_repository are known to work with Kotlin.
For local development of rules_kotlin:
local_path_override( module_name = "rules_kotlin", path = "../path/to/rules_kotlin_clone/", )
_RULES_KOTLIN_COMMIT = "HEAD_COMMIT_SHA" archive_override( module_name = "rules_kotlin", integrity = "sha256-...", strip_prefix = "rules_kotlin-%s" % _RULES_KOTLIN_COMMIT, urls = ["https://github.com/bazelbuild/rules_kotlin/archive/%s.tar.gz" % _RULES_KOTLIN_COMMIT], )
To attach debugger and step through native action code when using local checkout of rules_kotlin repo :
rules_kotlin project in Android Studio, using existing .bazelproject file as project view.bazel build //lib/mylib:main_kt -s. You can also use bazel aquery to get this info.KotlinCompile. Note: If you don’t see it, target rebuild may have been skipped (in this case touch one of the source .kt file to trigger rebuild).REPOSITORY_NAME as specified in action env, ex : export REPOSITORY_NAME=rules_kotlinbazel-out/darwin_arm64-opt-exec-2B5CBBC6/bin/external/rules_kotlin/src/main/kotlin/build '--flagfile=bazel-out/darwin_arm64-fastbuild/bin/lib/mylib/main_kt-kt.jar-0.params'bazel-MYPROJECT, available via bazel info | grep execution_root.--debug=5005 to command line to make the action wait for a debugger to attach, ex: bazel-out/darwin_arm64-opt-exec-2B5CBBC6/bin/external/rules_kotlin/src/main/kotlin/build --debug=5005 '--flagfile=bazel-out/darwin_arm64-fastbuild/bin/lib/mylib/main_kt-kt.jar-0.params'. Note: if command invokes java toolchain directly, use -agentlib:jdwp=transport=dt_socket,server=y,suspend=y,address=5005 instead.Remote JVM Debug configuration in Android Studio, set breakpoint in kotlin action java/kt code, and attach debugger. Breakpoints should be hit.The kt_kotlinc_options and kt_javac_options rules allows passing compiler flags to kotlinc and javac.
Note: Not all compiler flags are supported in all language versions. When this happens, the rules will fail.
For example you can define global compiler flags by doing:
load("@rules_kotlin//kotlin:core.bzl", "kt_kotlinc_options", "kt_javac_options", "define_kt_toolchain") kt_kotlinc_options( name = "kt_kotlinc_options", x_no_param_assertions = True, jvm_target = "1.8", ) kt_javac_options( name = "kt_javac_options", warn = "off", ) define_kt_toolchain( name = "kotlin_toolchain", kotlinc_options = "//:kt_kotlinc_options", javac_options = "//:kt_javac_options", )
You can optionally override compiler flags at the target level by providing an alternative set of kt_kotlinc_options or kt_javac_options in your target definitions.
Compiler flags that are passed to the rule definitions will be taken over the toolchain definition.
Example:
load("@rules_kotlin//kotlin:core.bzl", "kt_kotlinc_options", "kt_javac_options") load("@rules_kotlin//kotlin:jvm.bzl", "kt_jvm_library") kt_kotlinc_options( name = "kt_kotlinc_options_for_package_name", x_no_param_assertions = True, x_optin = [ "kotlin.Experimental", "kotlin.ExperimentalStdlibApi", ], ) kt_javac_options( name = "kt_javac_options_for_package_name", warn = "off" ) kt_jvm_library( name = "package_name", srcs = glob(["*.kt"]), kotlinc_opts = "//:kt_kotlinc_options_for_package_name", javac_opts = "//:kt_javac_options_for_package_name", deps = ["//path/to/dependency"], )
Note: kt_kotlinc_options defaults x_lambdas and x_sam_conversions to "class", which differs from Kotlin 2.x and Gradle's default of "indy" (invokedynamic). If you encounter issues with bytecode analysis tools expecting invokedynamic-based lambdas, configure these options:
kt_kotlinc_options( name = "kt_kotlinc_options", x_lambdas = "indy", x_sam_conversions = "indy", )
Additionally, you can add options for both tracing and timing of the bazel build using the kt_trace and kt_timings flags, for example:
bazel build --define=kt_trace=1bazel build --define=kt_timings=1kt_trace=1 will allow you to inspect the full kotlinc commandline invocation, while kt_timings=1 will report the high level time taken for each step.
The Build Tools API is a modern compilation interface provided by JetBrains for invoking the Kotlin compiler. It offers better integration and is required for incremental compilation support.
This feature is enabled by default.
To disable the Build Tools API and use the legacy compilation approach, add the following flag to your build:
bazel build --@rules_kotlin//kotlin/settings:experimental_build_tools_api=false //your:target
Or add it to your .bazelrc file:
build --@rules_kotlin//kotlin/settings:experimental_build_tools_api=false
KSP is officially supported as of rules_kotlin 1.8 and can be declared using the new kt_ksp_plugin rule.
load("@rules_kotlin//kotlin:core.bzl", "kt_ksp_plugin") load("@rules_kotlin//kotlin:jvm.bzl", "kt_jvm_library") kt_ksp_plugin( name = "moshi-kotlin-codegen", processor_class = "com.squareup.moshi.kotlin.codegen.ksp.JsonClassSymbolProcessorProvider", deps = [ "@maven//:com_squareup_moshi_moshi", "@maven//:com_squareup_moshi_moshi_kotlin", "@maven//:com_squareup_moshi_moshi_kotlin_codegen", ], ) kt_jvm_library( name = "lib", srcs = glob(["*.kt"]), plugins = ["//:moshi-kotlin-codegen"], )
To choose a different ksp_version distribution, do the following in your repository.
MODULE.bazelrules_kotlin_extensions = use_extension("@rules_kotlin//src/main/starlark/core/repositories:bzlmod_setup.bzl", "rules_kotlin_extensions") rules_kotlin_extensions.ksp_version( version = "1.8.22-1.0.11", sha256 = "2ce5a08fddd20ef07ac051615905453fe08c3ba3ce5afa5dc43a9b77aa64507d", ) use_repo(rules_kotlin_extensions, "com_github_google_ksp", "com_github_jetbrains_kotlin", "com_github_jetbrains_kotlin_git", "com_github_pinterest_ktlint", "kotlinx_serialization_core_jvm", "kotlinx_serialization_json", "kotlinx_serialization_json_jvm")
WORKSPACE (or import from a .bzl file):load("@rules_kotlin//kotlin:repositories.bzl", "kotlin_repositories", "ksp_version") kotlin_repositories( ksp_compiler_release = ksp_version( release = "1.8.22-1.0.11", sha256 = "2ce5a08fddd20ef07ac051615905453fe08c3ba3ce5afa5dc43a9b77aa64507d", ), )
The kt_compiler_plugin rule allows running Kotlin compiler plugins, such as no-arg, sam-with-receiver and allopen.
For example, you can add allopen to your project like this:
load("@rules_kotlin//kotlin:core.bzl", "kt_compiler_plugin") load("@rules_kotlin//kotlin:jvm.bzl", "kt_jvm_library") kt_compiler_plugin( name = "open_for_testing_plugin", id = "org.jetbrains.kotlin.allopen", options = { "annotation": "plugin.allopen.OpenForTesting", }, deps = [ "//kotlin/compiler:allopen-compiler-plugin", ], ) kt_jvm_library( name = "user", srcs = ["User.kt"], # The User class is annotated with OpenForTesting plugins = [ ":open_for_testing_plugin", ], deps = [ ":open_for_testing", # This contains the annotation (plugin.allopen.OpenForTesting) ], )
Full examples of using compiler plugins can be found here.
A new release can be published by just pushing a tag.
Once the tag is pushed, GitHub Actions will build, test, and publish a release to both GitHub releases and the BCR.
A tag can be created and pushed by doing the following:
git tag v4.13 git push origin v4.13
Examples can be found in the examples directory, including usage with Android, Dagger, Node-JS, Kotlin compiler plugins, etc.
These rules were initially forked from pubref/rules_kotlin, and then re-forked from bazelbuild/rules_kotlin. They were merged back into this repository in October, 2019.
This project is licensed under the Apache 2.0 license, as are all contributions
See the CONTRIBUTING doc for information about how to contribute to this project.