xref: /aosp_15_r20/external/bazelbuild-kotlin-rules/kotlin/jvm_import.bzl (revision 3a22c0a33dd99bcca39a024d43e6fbcc55c2806e)
1# Copyright 2022 Google LLC. All rights reserved.
2#
3# Licensed under the Apache License, Version 2.0 (the License);
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7#     http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14
15"""Kotlin kt_jvm_import rule."""
16
17load("//:visibility.bzl", "RULES_KOTLIN")
18load("//toolchains/kotlin_jvm:java_toolchains.bzl", "java_toolchains")
19load("//toolchains/kotlin_jvm:kt_jvm_toolchains.bzl", "kt_jvm_toolchains")
20load("@bazel_skylib//lib:dicts.bzl", "dicts")
21load(":common.bzl", "common")
22load(":compiler_plugin.bzl", "KtCompilerPluginInfo")
23load(":traverse_exports.bzl", "kt_traverse_exports")
24
25visibility(RULES_KOTLIN)
26
27def _kt_jvm_import_impl(ctx):
28    kt_jvm_toolchain = kt_jvm_toolchains.get(ctx)
29
30    runtime_deps_java_infos = []
31    for runtime_dep in ctx.attr.runtime_deps:
32        if JavaInfo in runtime_dep:
33            runtime_deps_java_infos.append(runtime_dep[JavaInfo])
34        elif CcInfo not in runtime_dep:
35            fail("Unexpected runtime dependency (must provide JavaInfo or CcInfo): %" % runtime_dep.label)
36
37    result = common.kt_jvm_import(
38        ctx,
39        kt_toolchain = kt_jvm_toolchain,
40        jars = ctx.files.jars,
41        srcjar = ctx.file.srcjar,
42        deps = common.collect_providers(JavaInfo, ctx.attr.deps),
43        runtime_deps = runtime_deps_java_infos,
44        neverlink = ctx.attr.neverlink,
45        java_toolchain = java_toolchains.get(ctx),
46        deps_checker = ctx.executable._deps_checker,
47    )
48
49    # Collect runfiles from deps unless neverlink
50    runfiles = None
51    if not ctx.attr.neverlink:
52        transitive_runfiles = []
53        for p in common.collect_providers(DefaultInfo, ctx.attr.deps):
54            transitive_runfiles.append(p.data_runfiles.files)
55            transitive_runfiles.append(p.default_runfiles.files)
56        runfiles = ctx.runfiles(
57            files = ctx.files.jars,
58            transitive_files = depset(transitive = transitive_runfiles),
59            collect_default = True,  # handles data attribute
60        )
61
62    return [
63        result.java_info,
64        ProguardSpecProvider(common.collect_proguard_specs(
65            ctx,
66            ctx.files.proguard_specs,
67            ctx.attr.deps,
68            kt_jvm_toolchain.proguard_whitelister,
69        )),
70        OutputGroupInfo(_validation = depset(result.validations)),
71        DefaultInfo(runfiles = runfiles),  # rule doesn't build any files
72    ]
73
74_KT_JVM_IMPORT_ATTRS = dicts.add(
75    java_toolchains.attrs,
76    kt_jvm_toolchains.attrs,
77    deps = attr.label_list(
78        aspects = [kt_traverse_exports.aspect],
79        providers = [
80            # Each provider-set expands on allow_rules
81            [JavaInfo],  # We allow android rule deps to make importing android JARs easier.
82        ],
83        doc = """The list of libraries this library directly depends on at compile-time. For Java
84                 and Kotlin libraries listed, the Jars they build as well as the transitive closure
85                 of their `deps` and `exports` will be on the compile-time classpath for this rule;
86                 also, the transitive closure of their `deps`, `runtime_deps`, and `exports` will be
87                 on the runtime classpath (excluding dependencies only depended on as `neverlink`).
88
89                 Note on strict_deps: any Java type explicitly or implicitly referred to in `srcs`
90                 must be included here. This is a stronger requirement than what is enforced for
91                 `java_library`. Any build failures resulting from this requirement will include the
92                 missing dependencies and a command to fix the rule.""",
93    ),
94    exported_plugins = attr.label_list(
95        providers = [[KtCompilerPluginInfo]],
96        cfg = "exec",
97        doc = """JVM plugins to export to users.
98
99
100                 Every plugin listed will run during compliations that depend on this target, as
101                 if it were listed directly in that target's `plugins` attribute. `java_*` targets
102                 will not run kotlinc plugins""",
103    ),
104    jars = attr.label_list(
105        allow_files = common.JAR_FILE_TYPE,
106        allow_empty = False,
107        doc = """The list of Java and/or Kotlin JAR files provided to targets that depend on this
108                 target (required).  Currently only a single Jar is supported.""",
109    ),
110    neverlink = attr.bool(
111        default = False,
112        doc = """Only use this library for compilation and not at runtime.""",
113    ),
114    proguard_specs = attr.label_list(
115        allow_files = True,
116        doc = """Proguard specifications to go along with this library.""",
117    ),
118    runtime_deps = attr.label_list(
119        providers = [
120            # Each provider-set expands on allow_rules
121            [JavaInfo],
122            [CcInfo],  # for JNI / native dependencies
123        ],
124        aspects = [kt_traverse_exports.aspect],
125        doc = """Runtime-only dependencies.""",
126    ),
127    srcjar = attr.label(
128        allow_single_file = common.SRCJAR_FILE_TYPES,
129        doc = """A JAR file that contains source code for the compiled JAR files.""",
130    ),
131    _deps_checker = attr.label(
132        default = "@bazel_tools//tools/android:aar_import_deps_checker",
133        executable = True,
134        cfg = "exec",
135    ),
136)
137
138kt_jvm_import = rule(
139    attrs = _KT_JVM_IMPORT_ATTRS,
140    fragments = ["java"],
141    provides = [JavaInfo],
142    implementation = _kt_jvm_import_impl,
143    toolchains = [kt_jvm_toolchains.type, "@bazel_tools//tools/jdk:toolchain_type"],
144    doc = """Allows the use of precompiled Kotlin `.jar` files as deps of `kt_*` targets.
145
146             Prefer this rule to `java_import` for Kotlin Jars. Most Java-like libraries
147             and binaries can depend on this rule, and this rule can in turn depend on Kotlin and
148             Java libraries. This rule supports a subset of attributes supported by `java_import`.
149
150             In addition to documentation provided as part of this rule, please also refer to their
151             documentation as part of `java_import`.
152          """,
153)
154