From eae9d4d019ca8d01bd3db5a8549b7f0e3505db61 Mon Sep 17 00:00:00 2001 From: Googler Date: Wed, 4 Dec 2024 04:30:45 -0800 Subject: [PATCH] Cleanup unused java rules code PiperOrigin-RevId: 702674779 Change-Id: I837984c08fac0e1090161bb4652e29eab45928c9 --- .../lib/rules/java/BootClassPathInfo.java | 14 - .../build/lib/rules/java/JavaInfo.java | 103 +- .../JavaPackageConfigurationProvider.java | 19 +- .../build/lib/rules/java/JavaPluginInfo.java | 41 +- .../rules/java/JavaPluginsFlagAliasRule.java | 12 +- .../build/lib/rules/java/JavaRuntimeInfo.java | 13 - .../lib/rules/java/JavaToolchainProvider.java | 13 - .../common/java/boot_class_path_info.bzl | 63 -- .../builtins_bzl/common/java/java_common.bzl | 326 +----- .../java_common_internal_for_builtins.bzl | 452 -------- .../builtins_bzl/common/java/java_helper.bzl | 486 --------- .../builtins_bzl/common/java/java_info.bzl | 971 ------------------ .../java/java_package_configuration.bzl | 124 --- .../builtins_bzl/common/java/java_runtime.bzl | 258 ----- .../common/java/java_semantics.bzl | 111 -- .../common/java/java_toolchain.bzl | 609 ----------- .../common/java/message_bundle_info.bzl | 24 - .../starlark/StarlarkSubruleTest.java | 8 +- .../lib/rules/java/JavaInfoCodecTest.java | 13 - .../rules/java/JavaInfoStarlarkApiTest.java | 4 +- .../rules/java/JavaPluginsFlagAliasTest.java | 5 +- 21 files changed, 25 insertions(+), 3644 deletions(-) delete mode 100644 src/main/starlark/builtins_bzl/common/java/boot_class_path_info.bzl delete mode 100644 src/main/starlark/builtins_bzl/common/java/java_common_internal_for_builtins.bzl delete mode 100644 src/main/starlark/builtins_bzl/common/java/java_helper.bzl delete mode 100644 src/main/starlark/builtins_bzl/common/java/java_info.bzl delete mode 100644 src/main/starlark/builtins_bzl/common/java/java_package_configuration.bzl delete mode 100644 src/main/starlark/builtins_bzl/common/java/java_runtime.bzl delete mode 100644 src/main/starlark/builtins_bzl/common/java/java_semantics.bzl delete mode 100644 src/main/starlark/builtins_bzl/common/java/java_toolchain.bzl delete mode 100644 src/main/starlark/builtins_bzl/common/java/message_bundle_info.bzl diff --git a/src/main/java/com/google/devtools/build/lib/rules/java/BootClassPathInfo.java b/src/main/java/com/google/devtools/build/lib/rules/java/BootClassPathInfo.java index a95cde4c74b923..16245990f9787b 100644 --- a/src/main/java/com/google/devtools/build/lib/rules/java/BootClassPathInfo.java +++ b/src/main/java/com/google/devtools/build/lib/rules/java/BootClassPathInfo.java @@ -14,7 +14,6 @@ package com.google.devtools.build.lib.rules.java; import static com.google.devtools.build.lib.skyframe.BzlLoadValue.keyForBuild; -import static com.google.devtools.build.lib.skyframe.BzlLoadValue.keyForBuiltins; import com.google.devtools.build.lib.actions.Artifact; import com.google.devtools.build.lib.cmdline.Label; @@ -38,9 +37,6 @@ public class BootClassPathInfo extends StarlarkInfoWrapper { /** Provider singleton constant. */ - public static final StarlarkProviderWrapper LEGACY_BUILTINS_PROVIDER = - new BuiltinsProvider(); - public static final StarlarkProviderWrapper PROVIDER = new Provider(); public static final StarlarkProviderWrapper RULES_JAVA_PROVIDER = new RulesJavaProvider(); @@ -87,8 +83,6 @@ public static BootClassPathInfo wrap(Info info) throws RuleErrorException { com.google.devtools.build.lib.packages.Provider.Key key = info.getProvider().getKey(); if (key.equals(PROVIDER.getKey())) { return PROVIDER.wrap(info); - } else if (key.equals(LEGACY_BUILTINS_PROVIDER.getKey())) { - return LEGACY_BUILTINS_PROVIDER.wrap(info); } else if (key.equals(RULES_JAVA_PROVIDER.getKey())) { return RULES_JAVA_PROVIDER.wrap(info); } else if (key.equals(WORKSPACE_PROVIDER.getKey())) { @@ -129,14 +123,6 @@ && systemInputs().isEmpty() && systemPath().isEmpty(); } - private static class BuiltinsProvider extends Provider { - private BuiltinsProvider() { - super( - keyForBuiltins( - Label.parseCanonicalUnchecked("@_builtins//:common/java/boot_class_path_info.bzl"))); - } - } - private static class RulesJavaProvider extends Provider { private RulesJavaProvider() { super(keyForBuild(Label.parseCanonicalUnchecked("//java/private:boot_class_path_info.bzl"))); diff --git a/src/main/java/com/google/devtools/build/lib/rules/java/JavaInfo.java b/src/main/java/com/google/devtools/build/lib/rules/java/JavaInfo.java index 2f6ff384587d7a..1b2bb581f495b9 100644 --- a/src/main/java/com/google/devtools/build/lib/rules/java/JavaInfo.java +++ b/src/main/java/com/google/devtools/build/lib/rules/java/JavaInfo.java @@ -14,7 +14,6 @@ package com.google.devtools.build.lib.rules.java; import static com.google.devtools.build.lib.skyframe.BzlLoadValue.keyForBuild; -import static com.google.devtools.build.lib.skyframe.BzlLoadValue.keyForBuiltins; import static com.google.devtools.build.lib.unsafe.UnsafeProvider.unsafe; import com.google.common.annotations.VisibleForTesting; @@ -69,13 +68,10 @@ @Immutable public sealed class JavaInfo extends NativeInfo implements JavaInfoApi - permits JavaInfo.BuiltinsJavaInfo, JavaInfo.RulesJavaJavaInfo, JavaInfo.WorkspaceJavaInfo { + permits JavaInfo.RulesJavaJavaInfo, JavaInfo.WorkspaceJavaInfo { public static final String STARLARK_NAME = "JavaInfo"; - @SerializationConstant - public static final JavaInfoProvider LEGACY_BUILTINS_PROVIDER = new BuiltinsJavaInfoProvider(); - // Not serialized public static final JavaInfoProvider RULES_JAVA_PROVIDER = new RulesJavaJavaInfoProvider(); // Not serialized @@ -146,8 +142,6 @@ static T nullIfNone(Object object, Class type) { } static final JavaInfo EMPTY_JAVA_INFO_FOR_TESTING = Builder.create().build(); - static final BuiltinsJavaInfo EMPTY_BUILTINS_JAVA_INFO_FOR_TESTING = - (BuiltinsJavaInfo) new Builder().setProvider(LEGACY_BUILTINS_PROVIDER).build(); private final JavaCompilationArgsProvider providerJavaCompilationArgs; private final JavaSourceJarsProvider providerJavaSourceJars; @@ -218,9 +212,6 @@ public static T getProvider( public static JavaInfo getJavaInfo(TransitiveInfoCollection target) throws RuleErrorException { JavaInfo info = target.get(PROVIDER); - if (info == null) { - info = target.get(LEGACY_BUILTINS_PROVIDER); - } if (info == null) { info = target.get(RULES_JAVA_PROVIDER); } @@ -232,9 +223,7 @@ public static JavaInfo getJavaInfo(TransitiveInfoCollection target) throws RuleE public static JavaInfo wrap(Info info) throws RuleErrorException { Provider.Key key = info.getProvider().getKey(); - if (key.equals(LEGACY_BUILTINS_PROVIDER.getKey())) { - return LEGACY_BUILTINS_PROVIDER.wrap(info); - } else if (key.equals(RULES_JAVA_PROVIDER.getKey())) { + if (key.equals(RULES_JAVA_PROVIDER.getKey())) { return RULES_JAVA_PROVIDER.wrap(info); } else if (key.equals(WORKSPACE_PROVIDER.getKey())) { return WORKSPACE_PROVIDER.wrap(info); @@ -516,48 +505,6 @@ public int hashCode() { providerJavaPlugin); } - @VisibleForTesting // package-private for testing. - static final class BuiltinsJavaInfo extends JavaInfo { - - private BuiltinsJavaInfo(StructImpl javaInfo) - throws EvalException, TypeException, RuleErrorException { - super(javaInfo); - } - - private BuiltinsJavaInfo( - JavaCcInfoProvider javaCcInfoProvider, - JavaCompilationArgsProvider javaCompilationArgsProvider, - JavaCompilationInfoProvider javaCompilationInfoProvider, - JavaGenJarsProvider javaGenJarsProvider, - JavaModuleFlagsProvider javaModuleFlagsProvider, - JavaPluginInfo javaPluginInfo, - JavaRuleOutputJarsProvider javaRuleOutputJarsProvider, - JavaSourceJarsProvider javaSourceJarsProvider, - ImmutableList directRuntimeJars, - boolean neverlink, - ImmutableList javaConstraints, - Location creationLocation) { - super( - javaCcInfoProvider, - javaCompilationArgsProvider, - javaCompilationInfoProvider, - javaGenJarsProvider, - javaModuleFlagsProvider, - javaPluginInfo, - javaRuleOutputJarsProvider, - javaSourceJarsProvider, - directRuntimeJars, - neverlink, - javaConstraints, - creationLocation); - } - - @Override - public JavaInfoProvider getProvider() { - return LEGACY_BUILTINS_PROVIDER; - } - } - static final class RulesJavaJavaInfo extends JavaInfo { private RulesJavaJavaInfo(StructImpl javaInfo) @@ -612,20 +559,6 @@ public JavaInfoProvider getProvider() { } } - /** Legacy Provider class for {@link JavaInfo} objects. */ - public static final class BuiltinsJavaInfoProvider extends JavaInfoProvider { - private BuiltinsJavaInfoProvider() { - super( - keyForBuiltins(Label.parseCanonicalUnchecked("@_builtins//:common/java/java_info.bzl"))); - } - - @Override - protected JavaInfo makeNewInstance(StructImpl info) - throws RuleErrorException, TypeException, EvalException { - return new BuiltinsJavaInfo(info); - } - } - /** Legacy Provider class for {@link JavaInfo} objects. */ public static final class RulesJavaJavaInfoProvider extends JavaInfoProvider { private RulesJavaJavaInfoProvider() { @@ -654,8 +587,7 @@ protected JavaInfo makeNewInstance(StructImpl info) /** Provider class for {@link JavaInfo} objects. */ public static sealed class JavaInfoProvider extends StarlarkProviderWrapper - implements Provider - permits BuiltinsJavaInfoProvider, RulesJavaJavaInfoProvider, WorkspaceJavaInfoProvider { + implements Provider permits RulesJavaJavaInfoProvider, WorkspaceJavaInfoProvider { private JavaInfoProvider() { this( keyForBuild( @@ -778,21 +710,7 @@ public Builder setProvider(Provider provider) { } public JavaInfo build() { - if (provider.getKey().equals(LEGACY_BUILTINS_PROVIDER.getKey())) { - return new BuiltinsJavaInfo( - /* javaCcInfoProvider= */ null, - providerJavaCompilationArgs, - providerJavaCompilationInfo, - /* javaGenJarsProvider= */ null, - /* javaModuleFlagsProvider= */ null, - /* javaPluginInfo= */ null, - providerJavaRuleOutputJars, - providerJavaSourceJars, - runtimeJars, - neverlink, - javaConstraints, - creationLocation); - } else if (provider.getKey().equals(WORKSPACE_PROVIDER.getKey())) { + if (provider.getKey().equals(WORKSPACE_PROVIDER.getKey())) { return new WorkspaceJavaInfo( /* javaCcInfoProvider= */ null, providerJavaCompilationArgs, @@ -877,14 +795,6 @@ public Class getEncodedClass() { @Override public void serialize(SerializationContext context, JavaInfo obj, CodedOutputStream codedOut) throws SerializationException, IOException { - switch (obj.getProvider()) { - case BuiltinsJavaInfoProvider unused -> codedOut.writeBoolNoTag(true); - case RulesJavaJavaInfoProvider unused -> - throw new UnsupportedOperationException("not implemented"); - case WorkspaceJavaInfoProvider unused -> - throw new UnsupportedOperationException("not implemented"); - case JavaInfoProvider unused -> codedOut.writeBoolNoTag(false); - } for (FieldHandler handler : handlers) { handler.serialize(context, codedOut, obj); } @@ -898,10 +808,7 @@ public DeferredValue deserializeDeferred( JavaInfo obj; try { - obj = - codedIn.readBool() - ? (BuiltinsJavaInfo) unsafe().allocateInstance(BuiltinsJavaInfo.class) - : (JavaInfo) unsafe().allocateInstance(JavaInfo.class); + obj = (JavaInfo) unsafe().allocateInstance(JavaInfo.class); } catch (InstantiationException e) { throw new SerializationException("Could not instantiate JavaInfo with Unsafe", e); } diff --git a/src/main/java/com/google/devtools/build/lib/rules/java/JavaPackageConfigurationProvider.java b/src/main/java/com/google/devtools/build/lib/rules/java/JavaPackageConfigurationProvider.java index c34fab31afcc60..43107f86394f1b 100644 --- a/src/main/java/com/google/devtools/build/lib/rules/java/JavaPackageConfigurationProvider.java +++ b/src/main/java/com/google/devtools/build/lib/rules/java/JavaPackageConfigurationProvider.java @@ -15,7 +15,6 @@ package com.google.devtools.build.lib.rules.java; import static com.google.devtools.build.lib.skyframe.BzlLoadValue.keyForBuild; -import static com.google.devtools.build.lib.skyframe.BzlLoadValue.keyForBuiltins; import com.google.common.annotations.VisibleForTesting; import com.google.common.collect.ImmutableList; @@ -43,8 +42,6 @@ public final class JavaPackageConfigurationProvider implements StarlarkValue { private static final StarlarkProviderWrapper PROVIDER = new Provider(); - private static final StarlarkProviderWrapper BUILTINS_PROVIDER = - new BuiltinsProvider(); private final StructImpl underlying; @@ -55,11 +52,7 @@ private JavaPackageConfigurationProvider(StructImpl underlying) { @VisibleForTesting public static JavaPackageConfigurationProvider get(ConfiguredTarget target) throws RuleErrorException { - JavaPackageConfigurationProvider info = target.get(PROVIDER); - if (info == null) { - info = target.get(BUILTINS_PROVIDER); - } - return info; + return target.get(PROVIDER); } /** Package specifications for which the configuration should be applied. */ @@ -135,16 +128,6 @@ public JavaPackageConfigurationProvider wrap(Info value) throws RuleErrorExcepti } } - private static class BuiltinsProvider extends JavaPackageConfigurationProvider.Provider { - - private BuiltinsProvider() { - super( - keyForBuiltins( - Label.parseCanonicalUnchecked( - "@_builtins//:common/java/java_package_configuration.bzl"))); - } - } - static ImmutableList wrapSequence(Sequence sequence) throws RuleErrorException { ImmutableList.Builder builder = ImmutableList.builder(); diff --git a/src/main/java/com/google/devtools/build/lib/rules/java/JavaPluginInfo.java b/src/main/java/com/google/devtools/build/lib/rules/java/JavaPluginInfo.java index 4652ea8d512e93..33b469de70115d 100644 --- a/src/main/java/com/google/devtools/build/lib/rules/java/JavaPluginInfo.java +++ b/src/main/java/com/google/devtools/build/lib/rules/java/JavaPluginInfo.java @@ -15,7 +15,6 @@ package com.google.devtools.build.lib.rules.java; import static com.google.devtools.build.lib.skyframe.BzlLoadValue.keyForBuild; -import static com.google.devtools.build.lib.skyframe.BzlLoadValue.keyForBuiltins; import com.google.auto.value.AutoValue; import com.google.common.annotations.VisibleForTesting; @@ -50,18 +49,10 @@ public abstract class JavaPluginInfo extends NativeInfo implements JavaPluginInfoApi { public static final String PROVIDER_NAME = "JavaPluginInfo"; - public static final Provider LEGACY_BUILTINS_PROVIDER = new BuiltinsProvider(); public static final Provider PROVIDER = new Provider(); public static final Provider RULES_JAVA_PROVIDER = new RulesJavaProvider(); public static final Provider WORKSPACE_PROVIDER = new WorkspaceProvider(); - private static final JavaPluginInfo EMPTY_BUILTIN = - new AutoValue_JavaPluginInfo( - ImmutableList.of(), - JavaPluginData.empty(), - JavaPluginData.empty(), - LEGACY_BUILTINS_PROVIDER); - private static final JavaPluginInfo EMPTY = new AutoValue_JavaPluginInfo( ImmutableList.of(), JavaPluginData.empty(), JavaPluginData.empty(), PROVIDER); @@ -75,27 +66,15 @@ public abstract class JavaPluginInfo extends NativeInfo ImmutableList.of(), JavaPluginData.empty(), JavaPluginData.empty(), WORKSPACE_PROVIDER); public static JavaPluginInfo wrap(Info info) throws RuleErrorException { - com.google.devtools.build.lib.packages.Provider.Key key = info.getProvider().getKey(); // this wrapped instance is not propagated back to Starlark, so we don't need every type - // we just use the two types that are checked for in tests - if (key.equals(LEGACY_BUILTINS_PROVIDER.getKey())) { - return LEGACY_BUILTINS_PROVIDER.wrap(info); - } else { - return PROVIDER.wrap(info); - } + // we just use the single type that is checked for in tests + return PROVIDER.wrap(info); } @VisibleForTesting public static JavaPluginInfo get(ConfiguredTarget target) throws RuleErrorException { - // we just use the two types that are checked for in tests - JavaPluginInfo info = target.get(PROVIDER); - JavaPluginInfo builtinInfo = target.get(LEGACY_BUILTINS_PROVIDER); - if (info == null) { - return builtinInfo; - } else if (builtinInfo == null) { - return info; - } - return mergeWithoutJavaOutputs(info, builtinInfo); + // we just use the single type that is checked for in tests + return target.get(PROVIDER); } @Override @@ -103,14 +82,6 @@ public com.google.devtools.build.lib.packages.Provider getProvider() { return providerType(); } - /** Legacy Provider class for {@link JavaPluginInfo} objects. */ - public static class BuiltinsProvider extends Provider { - private BuiltinsProvider() { - super( - keyForBuiltins(Label.parseCanonicalUnchecked("@_builtins//:common/java/java_info.bzl"))); - } - } - /** Provider class for {@link JavaPluginInfo} objects in rules_java itself. */ public static class RulesJavaProvider extends Provider { private RulesJavaProvider() { @@ -290,9 +261,7 @@ public static JavaPluginInfo mergeWithoutJavaOutputs( } public static JavaPluginInfo empty(com.google.devtools.build.lib.packages.Provider providerType) { - if (providerType.equals(LEGACY_BUILTINS_PROVIDER)) { - return EMPTY_BUILTIN; - } else if (providerType.equals(RULES_JAVA_PROVIDER)) { + if (providerType.equals(RULES_JAVA_PROVIDER)) { return EMPTY_RULES_JAVA; } else if (providerType.equals(WORKSPACE_PROVIDER)) { return EMPTY_WORKSPACE; diff --git a/src/main/java/com/google/devtools/build/lib/rules/java/JavaPluginsFlagAliasRule.java b/src/main/java/com/google/devtools/build/lib/rules/java/JavaPluginsFlagAliasRule.java index 6690d848d64cee..26f0454983686a 100644 --- a/src/main/java/com/google/devtools/build/lib/rules/java/JavaPluginsFlagAliasRule.java +++ b/src/main/java/com/google/devtools/build/lib/rules/java/JavaPluginsFlagAliasRule.java @@ -54,8 +54,7 @@ public RuleClass build(RuleClass.Builder builder, RuleDefinitionEnvironment envi ImmutableList.of( ImmutableList.of(JavaPluginInfo.PROVIDER.id()), ImmutableList.of(JavaPluginInfo.RULES_JAVA_PROVIDER.id()), - ImmutableList.of(JavaPluginInfo.WORKSPACE_PROVIDER.id()), - ImmutableList.of(JavaPluginInfo.LEGACY_BUILTINS_PROVIDER.id()))) + ImmutableList.of(JavaPluginInfo.WORKSPACE_PROVIDER.id()))) .silentRuleClassFilter() .value(JavaSemantics.JAVA_PLUGINS)) .build(); @@ -88,12 +87,6 @@ public ConfiguredTarget create(RuleContext ruleContext) ruleContext .getRulePrerequisitesCollection() .getPrerequisites(":java_plugins", JavaPluginInfo.PROVIDER); - if (plugins.isEmpty()) { - plugins = - ruleContext - .getRulePrerequisitesCollection() - .getPrerequisites(":java_plugins", JavaPluginInfo.LEGACY_BUILTINS_PROVIDER); - } if (plugins.isEmpty()) { plugins = ruleContext @@ -108,8 +101,6 @@ public ConfiguredTarget create(RuleContext ruleContext) } JavaPluginInfo javaPluginInfo = JavaPluginInfo.mergeWithoutJavaOutputs(plugins, JavaPluginInfo.PROVIDER); - JavaPluginInfo builtinsProviderInfo = - JavaPluginInfo.mergeWithoutJavaOutputs(plugins, JavaPluginInfo.LEGACY_BUILTINS_PROVIDER); JavaPluginInfo rulesJavaProviderInfo = JavaPluginInfo.mergeWithoutJavaOutputs(plugins, JavaPluginInfo.RULES_JAVA_PROVIDER); JavaPluginInfo workspaceProviderInfo = @@ -117,7 +108,6 @@ public ConfiguredTarget create(RuleContext ruleContext) return new RuleConfiguredTargetBuilder(ruleContext) .addStarlarkDeclaredProvider(javaPluginInfo) - .addStarlarkDeclaredProvider(builtinsProviderInfo) .addStarlarkDeclaredProvider(rulesJavaProviderInfo) .addStarlarkDeclaredProvider(workspaceProviderInfo) .addProvider(RunfilesProvider.class, RunfilesProvider.EMPTY) diff --git a/src/main/java/com/google/devtools/build/lib/rules/java/JavaRuntimeInfo.java b/src/main/java/com/google/devtools/build/lib/rules/java/JavaRuntimeInfo.java index cd4208d186eaed..40aef644e4ef95 100644 --- a/src/main/java/com/google/devtools/build/lib/rules/java/JavaRuntimeInfo.java +++ b/src/main/java/com/google/devtools/build/lib/rules/java/JavaRuntimeInfo.java @@ -16,7 +16,6 @@ import static com.google.devtools.build.lib.packages.BuildType.LABEL; import static com.google.devtools.build.lib.skyframe.BzlLoadValue.keyForBuild; -import static com.google.devtools.build.lib.skyframe.BzlLoadValue.keyForBuiltins; import com.google.common.annotations.VisibleForTesting; import com.google.common.collect.ImmutableList; @@ -46,8 +45,6 @@ @Immutable public final class JavaRuntimeInfo extends StarlarkInfoWrapper { - public static final StarlarkProviderWrapper LEGACY_BUILTINS_PROVIDER = - new BuiltinsProvider(); public static final StarlarkProviderWrapper RULES_JAVA_PROVIDER = new RulesJavaProvider(); public static final StarlarkProviderWrapper WORKSPACE_PROVIDER = @@ -104,8 +101,6 @@ public static JavaRuntimeInfo wrap(Info info) throws RuleErrorException { com.google.devtools.build.lib.packages.Provider.Key key = info.getProvider().getKey(); if (key.equals(PROVIDER.getKey())) { return PROVIDER.wrap(info); - } else if (key.equals(LEGACY_BUILTINS_PROVIDER.getKey())) { - return LEGACY_BUILTINS_PROVIDER.wrap(info); } else if (key.equals(RULES_JAVA_PROVIDER.getKey())) { return RULES_JAVA_PROVIDER.wrap(info); } else if (key.equals(WORKSPACE_PROVIDER.getKey())) { @@ -150,14 +145,6 @@ public int version() throws RuleErrorException { return getUnderlyingValue("version", StarlarkInt.class).toIntUnchecked(); } - private static class BuiltinsProvider extends Provider { - private BuiltinsProvider() { - super( - keyForBuiltins( - Label.parseCanonicalUnchecked("@_builtins//:common/java/java_runtime.bzl"))); - } - } - private static class RulesJavaProvider extends Provider { private RulesJavaProvider() { super(keyForBuild(Label.parseCanonicalUnchecked("//java/common/rules:java_runtime.bzl"))); diff --git a/src/main/java/com/google/devtools/build/lib/rules/java/JavaToolchainProvider.java b/src/main/java/com/google/devtools/build/lib/rules/java/JavaToolchainProvider.java index 08c5880563c0a8..c81b81fdda1e26 100644 --- a/src/main/java/com/google/devtools/build/lib/rules/java/JavaToolchainProvider.java +++ b/src/main/java/com/google/devtools/build/lib/rules/java/JavaToolchainProvider.java @@ -14,7 +14,6 @@ package com.google.devtools.build.lib.rules.java; import static com.google.devtools.build.lib.skyframe.BzlLoadValue.keyForBuild; -import static com.google.devtools.build.lib.skyframe.BzlLoadValue.keyForBuiltins; import static java.util.Objects.requireNonNull; import com.google.common.annotations.VisibleForTesting; @@ -51,8 +50,6 @@ @Immutable public final class JavaToolchainProvider extends StarlarkInfoWrapper { - public static final StarlarkProviderWrapper LEGACY_BUILTINS_PROVIDER = - new BuiltinsProvider(); public static final StarlarkProviderWrapper RULES_JAVA_PROVIDER = new RulesJavaProvider(); public static final StarlarkProviderWrapper WORKSPACE_PROVIDER = @@ -67,8 +64,6 @@ public static JavaToolchainProvider wrap(Info info) throws RuleErrorException { com.google.devtools.build.lib.packages.Provider.Key key = info.getProvider().getKey(); if (key.equals(PROVIDER.getKey())) { return PROVIDER.wrap(info); - } else if (key.equals(LEGACY_BUILTINS_PROVIDER.getKey())) { - return LEGACY_BUILTINS_PROVIDER.wrap(info); } else if (key.equals(RULES_JAVA_PROVIDER.getKey())) { return RULES_JAVA_PROVIDER.wrap(info); } else if (key.equals(WORKSPACE_PROVIDER.getKey())) { @@ -322,14 +317,6 @@ static JspecifyInfo fromStarlark(@Nullable StarlarkValue value) throws RuleError } } - private static class BuiltinsProvider extends Provider { - private BuiltinsProvider() { - super( - keyForBuiltins( - Label.parseCanonicalUnchecked("@_builtins//:common/java/java_toolchain.bzl"))); - } - } - private static class RulesJavaProvider extends Provider { private RulesJavaProvider() { super(keyForBuild(Label.parseCanonicalUnchecked("//java/common/rules:java_toolchain.bzl"))); diff --git a/src/main/starlark/builtins_bzl/common/java/boot_class_path_info.bzl b/src/main/starlark/builtins_bzl/common/java/boot_class_path_info.bzl deleted file mode 100644 index fe7b63c1ff5ee5..00000000000000 --- a/src/main/starlark/builtins_bzl/common/java/boot_class_path_info.bzl +++ /dev/null @@ -1,63 +0,0 @@ -# Copyright 2023 The Bazel Authors. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -""" -Definition of the BootClassPathInfo provider. -""" - -load(":common/paths.bzl", "paths") - -def _init(bootclasspath = [], auxiliary = [], system = None): - """The BootClassPathInfo constructor. - - Args: - bootclasspath: ([File]) - auxiliary: ([File]) - system: ([File]|File|None) - """ - if not system: # None or [] - system_inputs = depset() - system_path = None - elif type(system) == "File": - system_inputs = depset([system]) - if not system.is_directory: - fail("for system,", system, "is not a directory") - system_path = system.path - elif type(system) == type([]): - system_inputs = depset(system) - system_paths = [input.path for input in system if input.basename == "release"] - if not system_paths: - fail("for system, expected inputs to contain 'release'") - system_path = paths.dirname(system_paths[0]) - else: - fail("for system, got", type(system), ", want File, sequence, or None") - - return { - "bootclasspath": depset(bootclasspath), - "_auxiliary": depset(auxiliary), - "_system_inputs": system_inputs, - "_system_path": system_path, - } - -BootClassPathInfo, _new_bootclasspathinfo = provider( - doc = "Information about the system APIs for a Java compilation.", - fields = [ - "bootclasspath", - # private - "_auxiliary", - "_system_inputs", - "_system_path", - ], - init = _init, -) diff --git a/src/main/starlark/builtins_bzl/common/java/java_common.bzl b/src/main/starlark/builtins_bzl/common/java/java_common.bzl index fb06d309d0ed27..e9eb6802382318 100644 --- a/src/main/starlark/builtins_bzl/common/java/java_common.bzl +++ b/src/main/starlark/builtins_bzl/common/java/java_common.bzl @@ -14,281 +14,7 @@ """ Utilities for Java compilation support in Starlark. """ -load(":common/java/boot_class_path_info.bzl", "BootClassPathInfo") -load(":common/java/java_common_internal_for_builtins.bzl", "compile", "run_ijar") -load(":common/java/java_helper.bzl", "helper") -load( - ":common/java/java_info.bzl", - "JavaCompilationInfo", - "JavaInfo", - "JavaPluginDataInfo", - "JavaPluginInfo", - "to_java_binary_info", - _java_info_add_constraints = "add_constraints", - _java_info_make_non_strict = "make_non_strict", - _java_info_merge = "merge", - _java_info_set_annotation_processing = "set_annotation_processing", -) -load(":common/java/java_runtime.bzl", "JavaRuntimeInfo") -load(":common/java/java_semantics.bzl", "semantics") -load(":common/java/java_toolchain.bzl", "JavaToolchainInfo") -load(":common/java/message_bundle_info.bzl", "MessageBundleInfo") -load(":common/paths.bzl", "paths") - _java_common_internal = _builtins.internal.java_common_internal_do_not_use -JavaRuntimeClasspathInfo = provider( - "Provider for the runtime classpath contributions of a Java binary.", - fields = ["runtime_classpath"], -) - -def _compile( - ctx, - output, - java_toolchain, - source_jars = [], - source_files = [], - output_source_jar = None, - javac_opts = [], - deps = [], - runtime_deps = [], - exports = [], - plugins = [], - exported_plugins = [], - native_libraries = [], - annotation_processor_additional_inputs = [], - annotation_processor_additional_outputs = [], - strict_deps = "ERROR", - bootclasspath = None, - sourcepath = [], - resources = [], - neverlink = False, - enable_annotation_processing = True, - add_exports = [], - add_opens = []): - return compile( - ctx, - output, - java_toolchain, - source_jars = source_jars, - source_files = source_files, - output_source_jar = output_source_jar, - javac_opts = javac_opts, - deps = deps, - runtime_deps = runtime_deps, - exports = exports, - plugins = plugins, - exported_plugins = exported_plugins, - native_libraries = native_libraries, - annotation_processor_additional_inputs = annotation_processor_additional_inputs, - annotation_processor_additional_outputs = annotation_processor_additional_outputs, - strict_deps = strict_deps, - bootclasspath = bootclasspath, - sourcepath = sourcepath, - resources = resources, - neverlink = neverlink, - enable_annotation_processing = enable_annotation_processing, - add_exports = add_exports, - add_opens = add_opens, - ) - -def _run_ijar(actions, jar, java_toolchain, target_label = None): - _java_common_internal._check_java_toolchain_is_declared_on_rule(actions) - return run_ijar( - actions = actions, - jar = jar, - java_toolchain = java_toolchain, - target_label = target_label, - ) - -def _stamp_jar(actions, jar, java_toolchain, target_label): - """Stamps a jar with a target label for add_dep support. - - The return value is typically passed to `JavaInfo.compile_jar`. Prefer to use `run_ijar` when - possible. - - Args: - actions: (actions) ctx.actions - jar: (File) The jar to run stamp_jar on. - java_toolchain: (JavaToolchainInfo) The toolchain to used to find the stamp_jar tool. - target_label: (Label) A target label to stamp the jar with. Used for `add_dep` support. - Typically, you would pass `ctx.label` to stamp the jar with the current rule's label. - - Returns: - (File) The output artifact - - """ - _java_common_internal._check_java_toolchain_is_declared_on_rule(actions) - output = actions.declare_file(paths.replace_extension(jar.basename, "-stamped.jar"), sibling = jar) - args = actions.args() - args.add(jar) - args.add(output) - args.add("--nostrip_jar") - args.add("--target_label", target_label) - actions.run( - mnemonic = "JavaIjar", - inputs = [jar], - outputs = [output], - executable = java_toolchain.ijar, # ijar doubles as a stamping tool - arguments = [args], - progress_message = "Stamping target label into jar %{input}", - toolchain = semantics.JAVA_TOOLCHAIN_TYPE, - use_default_shell_env = True, - ) - return output - -def _pack_sources( - actions, - java_toolchain, - output_source_jar, - sources = [], - source_jars = []): - """Packs sources and source jars into a single source jar file. - - The return value is typically passed to `JavaInfo.source_jar`. - - Args: - actions: (actions) ctx.actions - java_toolchain: (JavaToolchainInfo) The toolchain used to find the ijar tool. - output_source_jar: (File) The output source jar. - sources: ([File]) A list of Java source files to be packed into the source jar. - source_jars: ([File]) A list of source jars to be packed into the source jar. - - Returns: - (File) The output artifact - """ - _java_common_internal._check_java_toolchain_is_declared_on_rule(actions) - return helper.create_single_jar( - actions, - toolchain = java_toolchain, - output = output_source_jar, - sources = depset(source_jars), - resources = depset(sources), - progress_message = "Building source jar %{output}", - mnemonic = "JavaSourceJar", - ) - -# TODO: b/78512644 - migrate callers to passing explicit javacopts or using custom toolchains, and delete -def _default_javac_opts(java_toolchain): - """Experimental! Get default javacopts from a java toolchain - - Args: - java_toolchain: (JavaToolchainInfo) the toolchain from which to get the javac options. - - Returns: - ([str]) A list of javac options - """ - return java_toolchain._javacopts_list - -# temporary for migration -def _default_javac_opts_depset(java_toolchain): - """Experimental! Get default javacopts from a java toolchain - - Args: - java_toolchain: (JavaToolchainInfo) the toolchain from which to get the javac options. - - Returns: - (depset[str]) A depset of javac options that should be tokenized before passing to javac - """ - return java_toolchain._javacopts - -def _merge(providers): - """Merges the given providers into a single JavaInfo. - - Args: - providers: ([JavaInfo]) The list of providers to merge. - - Returns: - (JavaInfo) The merged JavaInfo - """ - return _java_info_merge(providers) - -def _make_non_strict(java_info): - """Returns a new JavaInfo instance whose direct-jars part is the union of both the direct and indirect jars of the given Java provider. - - Args: - java_info: (JavaInfo) The java info to make non-strict. - - Returns: - (JavaInfo) - """ - return _java_info_make_non_strict(java_info) - -def _get_message_bundle_info(): - return None if semantics.IS_BAZEL else MessageBundleInfo - -def _add_constraints(java_info, constraints = []): - """Returns a copy of the given JavaInfo with the given constraints added. - - Args: - java_info: (JavaInfo) The JavaInfo to enhance - constraints: ([str]) Constraints to add - - Returns: - (JavaInfo) - """ - if semantics.IS_BAZEL: - return java_info - - return _java_info_add_constraints(java_info, constraints = constraints) - -def _get_constraints(java_info): - """Returns a set of constraints added. - - Args: - java_info: (JavaInfo) The JavaInfo to get constraints from. - - Returns: - ([str]) The constraints set on the supplied JavaInfo - """ - return [] if semantics.IS_BAZEL else java_info._constraints - -def _set_annotation_processing( - java_info, - enabled = False, - processor_classnames = [], - processor_classpath = None, - class_jar = None, - source_jar = None): - """Returns a copy of the given JavaInfo with the given annotation_processing info. - - Args: - java_info: (JavaInfo) The JavaInfo to enhance. - enabled: (bool) Whether the rule uses annotation processing. - processor_classnames: ([str]) Class names of annotation processors applied. - processor_classpath: (depset[File]) Class names of annotation processors applied. - class_jar: (File) Optional. Jar that is the result of annotation processing. - source_jar: (File) Optional. Source archive resulting from annotation processing. - - Returns: - (JavaInfo) - """ - if semantics.IS_BAZEL: - return None - - return _java_info_set_annotation_processing( - java_info, - enabled = enabled, - processor_classnames = processor_classnames, - processor_classpath = processor_classpath, - class_jar = class_jar, - source_jar = source_jar, - ) - -def _java_toolchain_label(java_toolchain): - """Returns the toolchain's label. - - Args: - java_toolchain: (JavaToolchainInfo) The toolchain. - Returns: - (Label) - """ - if semantics.IS_BAZEL: - # No implementation in Bazel. This method is not callable in Starlark except through - # (discouraged) use of --experimental_google_legacy_api. - return None - - _java_common_internal.check_provider_instances([java_toolchain], "java_toolchain", JavaToolchainInfo) - return java_toolchain.label def _internal_exports(): _builtins.internal.cc_common.check_private_api(allowlist = [ @@ -297,55 +23,21 @@ def _internal_exports(): ("rules_java", ""), ]) return struct( - incompatible_disable_non_executable_java_binary = _java_common_internal.incompatible_disable_non_executable_java_binary, - target_kind = _java_common_internal.target_kind, - compile = compile, - JavaCompilationInfo = JavaCompilationInfo, + create_compilation_action = _java_common_internal.create_compilation_action, + create_header_compilation_action = _java_common_internal.create_header_compilation_action, + check_java_toolchain_is_declared_on_rule = _java_common_internal._check_java_toolchain_is_declared_on_rule, + check_provider_instances = _java_common_internal.check_provider_instances, collect_native_deps_dirs = _java_common_internal.collect_native_deps_dirs, - get_runtime_classpath_for_archive = _java_common_internal.get_runtime_classpath_for_archive, - to_java_binary_info = to_java_binary_info, - run_ijar_private_for_builtins = run_ijar, expand_java_opts = _java_common_internal.expand_java_opts, - JavaPluginDataInfo = JavaPluginDataInfo, + get_runtime_classpath_for_archive = _java_common_internal.get_runtime_classpath_for_archive, google_legacy_api_enabled = _java_common_internal._google_legacy_api_enabled, - wrap_java_info = _java_common_internal.wrap_java_info, - check_provider_instances = _java_common_internal.check_provider_instances, + incompatible_disable_non_executable_java_binary = _java_common_internal.incompatible_disable_non_executable_java_binary, incompatible_java_info_merge_runtime_module_flags = _java_common_internal._incompatible_java_info_merge_runtime_module_flags, - check_java_toolchain_is_declared_on_rule = _java_common_internal._check_java_toolchain_is_declared_on_rule, - create_header_compilation_action = _java_common_internal.create_header_compilation_action, - create_compilation_action = _java_common_internal.create_compilation_action, - tokenize_javacopts = _java_common_internal.tokenize_javacopts, + target_kind = _java_common_internal.target_kind, + wrap_java_info = _java_common_internal.wrap_java_info, ) -def _make_java_common(): - methods = { - "provider": JavaInfo, - "compile": _compile, - "run_ijar": _run_ijar, - "stamp_jar": _stamp_jar, - "pack_sources": _pack_sources, - "default_javac_opts": _default_javac_opts, - "default_javac_opts_depset": _default_javac_opts_depset, - "merge": _merge, - "make_non_strict": _make_non_strict, - "JavaPluginInfo": JavaPluginInfo, - "JavaToolchainInfo": JavaToolchainInfo, - "JavaRuntimeInfo": JavaRuntimeInfo, - "BootClassPathInfo": BootClassPathInfo, - "JavaRuntimeClasspathInfo": JavaRuntimeClasspathInfo, - "internal_DO_NOT_USE": _internal_exports, - } - if _java_common_internal._google_legacy_api_enabled(): - methods.update( - MessageBundleInfo = _get_message_bundle_info(), # struct field that is None in bazel - add_constraints = _add_constraints, - get_constraints = _get_constraints, - set_annotation_processing = _set_annotation_processing, - java_toolchain_label = _java_toolchain_label, - ) - return struct(**methods) - -java_common = _make_java_common() +java_common = struct(internal_DO_NOT_USE = _internal_exports) _FakeJavaInfo = provider() # buildifier: disable=provider-params _FakeJavaPluginInfo = provider() # buildifier: disable=provider-params diff --git a/src/main/starlark/builtins_bzl/common/java/java_common_internal_for_builtins.bzl b/src/main/starlark/builtins_bzl/common/java/java_common_internal_for_builtins.bzl deleted file mode 100644 index e9115d85643863..00000000000000 --- a/src/main/starlark/builtins_bzl/common/java/java_common_internal_for_builtins.bzl +++ /dev/null @@ -1,452 +0,0 @@ -# Copyright 2023 The Bazel Authors. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -""" Private utilities for Java compilation support in Starlark. """ - -load(":common/java/java_helper.bzl", "helper") -load( - ":common/java/java_info.bzl", - "JavaPluginInfo", - "disable_plugin_info_annotation_processing", - "java_info_for_compilation", - "merge_plugin_info_without_outputs", -) -load(":common/java/java_semantics.bzl", "semantics") -load(":common/java/java_toolchain.bzl", "JavaToolchainInfo") -load(":common/paths.bzl", "paths") - -_java_common_internal = _builtins.internal.java_common_internal_do_not_use - -def compile( - ctx, - output, - java_toolchain, - source_jars = [], - source_files = [], - output_source_jar = None, - javac_opts = [], - deps = [], - runtime_deps = [], - exports = [], - plugins = [], - exported_plugins = [], - native_libraries = [], - annotation_processor_additional_inputs = [], - annotation_processor_additional_outputs = [], - strict_deps = "ERROR", - bootclasspath = None, - javabuilder_jvm_flags = None, - sourcepath = [], - resources = [], - add_exports = [], - add_opens = [], - neverlink = False, - enable_annotation_processing = True, - # private to @_builtins: - enable_compile_jar_action = True, - enable_jspecify = True, - include_compilation_info = True, - classpath_resources = [], - resource_jars = [], - injecting_rule_kind = None): - """Compiles Java source files/jars from the implementation of a Starlark rule - - The result is a provider that represents the results of the compilation and can be added to the - set of providers emitted by this rule. - - Args: - ctx: (RuleContext) The rule context - output: (File) The output of compilation - java_toolchain: (JavaToolchainInfo) Toolchain to be used for this compilation. Mandatory. - source_jars: ([File]) A list of the jars to be compiled. At least one of source_jars or - source_files should be specified. - source_files: ([File]) A list of the Java source files to be compiled. At least one of - source_jars or source_files should be specified. - output_source_jar: (File) The output source jar. Optional. Defaults to - `{output_jar}-src.jar` if unset. - javac_opts: ([str]|depset[str]) A list of the desired javac options. Optional. - deps: ([JavaInfo]) A list of dependencies. Optional. - runtime_deps: ([JavaInfo]) A list of runtime dependencies. Optional. - exports: ([JavaInfo]) A list of exports. Optional. - plugins: ([JavaPluginInfo|JavaInfo]) A list of plugins. Optional. - exported_plugins: ([JavaPluginInfo|JavaInfo]) A list of exported plugins. Optional. - native_libraries: ([CcInfo]) CC library dependencies that are needed for this library. - annotation_processor_additional_inputs: ([File]) A list of inputs that the Java compilation - action will take in addition to the Java sources for annotation processing. - annotation_processor_additional_outputs: ([File]) A list of outputs that the Java - compilation action will output in addition to the class jar from annotation processing. - strict_deps: (str) A string that specifies how to handle strict deps. Possible values: - 'OFF', 'ERROR', 'WARN' and 'DEFAULT'. - bootclasspath: (BootClassPathInfo) If present, overrides the bootclasspath associated with - the provided java_toolchain. Optional. - javabuilder_jvm_flags: (list[str]) Additional JVM flags to pass to JavaBuilder. - sourcepath: ([File]) - resources: ([File]) - resource_jars: ([File]) - classpath_resources: ([File]) - neverlink: (bool) - enable_annotation_processing: (bool) Disables annotation processing in this compilation, - causing any annotation processors provided in plugins or in exported_plugins of deps to - be ignored. - enable_compile_jar_action: (bool) Enables header compilation or ijar creation. If set to - False, it forces use of the full class jar in the compilation classpaths of any - dependants. Doing so is intended for use by non-library targets such as binaries that - do not have dependants. - enable_jspecify: (bool) - include_compilation_info: (bool) - injecting_rule_kind: (str|None) - add_exports: ([str]) Allow this library to access the given /. Optional. - add_opens: ([str]) Allow this library to reflectively access the given /. - Optional. - - Returns: - (JavaInfo) - """ - _java_common_internal.check_provider_instances([java_toolchain], "java_toolchain", JavaToolchainInfo) - _java_common_internal.check_provider_instances(plugins, "plugins", JavaPluginInfo) - - plugin_info = merge_plugin_info_without_outputs(plugins + deps) - - all_javac_opts = [] # [depset[str]] - all_javac_opts.append(java_toolchain._javacopts) - - all_javac_opts.append(ctx.fragments.java.default_javac_flags_depset) - all_javac_opts.append(semantics.compatible_javac_options( - ctx, - java_toolchain, - _java_common_internal, - )) - - if ("com.google.devtools.build.runfiles.AutoBazelRepositoryProcessor" in - plugin_info.plugins.processor_classes.to_list()): - all_javac_opts.append(depset( - ["-Abazel.repository=" + ctx.label.workspace_name], - order = "preorder", - )) - system_bootclasspath = None - for package_config in java_toolchain._package_configuration: - if package_config.matches(ctx.label): - all_javac_opts.append(package_config.javac_opts) - if package_config.system: - if system_bootclasspath: - fail("Multiple system package configurations found for %s" % ctx.label) - system_bootclasspath = package_config.system - if not bootclasspath: - bootclasspath = system_bootclasspath - - all_javac_opts.append(depset( - ["--add-exports=%s=ALL-UNNAMED" % x for x in add_exports], - order = "preorder", - )) - - if type(javac_opts) == type([]): - # detokenize target's javacopts, it will be tokenized before compilation - all_javac_opts.append(helper.detokenize_javacopts(helper.tokenize_javacopts(ctx, javac_opts))) - elif type(javac_opts) == type(depset()): - all_javac_opts.append(javac_opts) - else: - fail("Expected javac_opts to be a list or depset, got:", type(javac_opts)) - - # we reverse the list of javacopts depsets, so that we keep the right-most set - # in case it's deduped. When this depset is flattened, we will reverse again, - # and then tokenize before passing to javac. This way, right-most javacopts will - # be retained and "win out". - all_javac_opts = depset(order = "preorder", transitive = reversed(all_javac_opts)) - - # Optimization: skip this if there are no annotation processors, to avoid unnecessarily - # disabling the direct classpath optimization if `enable_annotation_processor = False` - # but there aren't any annotation processors. - enable_direct_classpath = True - if not enable_annotation_processing and plugin_info.plugins.processor_classes: - plugin_info = disable_plugin_info_annotation_processing(plugin_info) - enable_direct_classpath = False - - all_javac_opts_list = helper.tokenize_javacopts(ctx, all_javac_opts) - uses_annotation_processing = False - if "-processor" in all_javac_opts_list or plugin_info.plugins.processor_classes: - uses_annotation_processing = True - - has_sources = source_files or source_jars - has_resources = resources or resource_jars - - is_strict_mode = strict_deps != "OFF" - classpath_mode = ctx.fragments.java.reduce_java_classpath() - - direct_jars = depset() - if is_strict_mode: - direct_jars = depset(order = "preorder", transitive = [dep.compile_jars for dep in deps]) - compilation_classpath = depset( - order = "preorder", - transitive = [direct_jars] + [dep.transitive_compile_time_jars for dep in deps], - ) - compile_time_java_deps = depset() - if is_strict_mode and classpath_mode != "OFF": - compile_time_java_deps = depset(transitive = [dep._compile_time_java_dependencies for dep in deps]) - - # create compile time jar action - if not has_sources: - compile_jar = None - compile_deps_proto = None - elif not enable_compile_jar_action: - compile_jar = output - compile_deps_proto = None - elif _should_use_header_compilation(ctx, java_toolchain): - compile_jar = helper.derive_output_file(ctx, output, name_suffix = "-hjar", extension = "jar") - compile_deps_proto = helper.derive_output_file(ctx, output, name_suffix = "-hjar", extension = "jdeps") - _java_common_internal.create_header_compilation_action( - ctx, - java_toolchain, - compile_jar, - compile_deps_proto, - plugin_info, - depset(source_files), - source_jars, - compilation_classpath, - direct_jars, - bootclasspath, - compile_time_java_deps, - all_javac_opts, - strict_deps, - ctx.label, - injecting_rule_kind, - enable_direct_classpath, - annotation_processor_additional_inputs, - ) - elif ctx.fragments.java.use_ijars(): - compile_jar = run_ijar( - ctx.actions, - output, - java_toolchain, - target_label = ctx.label, - injecting_rule_kind = injecting_rule_kind, - ) - compile_deps_proto = None - else: - compile_jar = output - compile_deps_proto = None - - native_headers_jar = helper.derive_output_file(ctx, output, name_suffix = "-native-header") - manifest_proto = helper.derive_output_file(ctx, output, extension_suffix = "_manifest_proto") - deps_proto = None - if ctx.fragments.java.generate_java_deps() and has_sources: - deps_proto = helper.derive_output_file(ctx, output, extension = "jdeps") - generated_class_jar = None - generated_source_jar = None - if uses_annotation_processing: - generated_class_jar = helper.derive_output_file(ctx, output, name_suffix = "-gen") - generated_source_jar = helper.derive_output_file(ctx, output, name_suffix = "-gensrc") - _java_common_internal.create_compilation_action( - ctx, - java_toolchain, - output, - manifest_proto, - plugin_info, - compilation_classpath, - direct_jars, - bootclasspath, - depset(javabuilder_jvm_flags), - compile_time_java_deps, - all_javac_opts, - strict_deps, - ctx.label, - deps_proto, - generated_class_jar, - generated_source_jar, - native_headers_jar, - depset(source_files), - source_jars, - resources, - depset(resource_jars), - classpath_resources, - sourcepath, - injecting_rule_kind, - enable_jspecify, - enable_direct_classpath, - annotation_processor_additional_inputs, - annotation_processor_additional_outputs, - ) - - create_output_source_jar = len(source_files) > 0 or source_jars != [output_source_jar] - if not output_source_jar: - output_source_jar = helper.derive_output_file(ctx, output, name_suffix = "-src", extension = "jar") - if create_output_source_jar: - helper.create_single_jar( - ctx.actions, - toolchain = java_toolchain, - output = output_source_jar, - sources = depset(source_jars + ([generated_source_jar] if generated_source_jar else [])), - resources = depset(source_files), - progress_message = "Building source jar %{output}", - mnemonic = "JavaSourceJar", - ) - - if has_sources or has_resources: - direct_runtime_jars = [output] - else: - direct_runtime_jars = [] - - compilation_info = struct( - javac_options = all_javac_opts, - # needs to be flattened because the public API is a list - boot_classpath = (bootclasspath.bootclasspath if bootclasspath else java_toolchain.bootclasspath).to_list(), - # we only add compile time jars from deps, and not exports - compilation_classpath = compilation_classpath, - runtime_classpath = depset( - order = "preorder", - direct = direct_runtime_jars, - transitive = [dep.transitive_runtime_jars for dep in runtime_deps + deps], - ), - uses_annotation_processing = uses_annotation_processing, - ) if include_compilation_info else None - - return java_info_for_compilation( - output_jar = output, - compile_jar = compile_jar, - source_jar = output_source_jar, - generated_class_jar = generated_class_jar, - generated_source_jar = generated_source_jar, - plugin_info = plugin_info, - deps = deps, - runtime_deps = runtime_deps, - exports = exports, - exported_plugins = exported_plugins, - compile_jdeps = compile_deps_proto if compile_deps_proto else deps_proto, - jdeps = deps_proto if include_compilation_info else None, - native_headers_jar = native_headers_jar, - manifest_proto = manifest_proto, - native_libraries = native_libraries, - neverlink = neverlink, - add_exports = add_exports, - add_opens = add_opens, - direct_runtime_jars = direct_runtime_jars, - compilation_info = compilation_info, - ) - -def _should_use_header_compilation(ctx, toolchain): - if not ctx.fragments.java.use_header_compilation(): - return False - if toolchain._forcibly_disable_header_compilation: - return False - if not toolchain._header_compiler: - fail( - "header compilation was requested but it is not supported by the " + - "current Java toolchain '" + str(toolchain.label) + - "'; see the java_toolchain.header_compiler attribute", - ) - if not toolchain._header_compiler_direct: - fail( - "header compilation was requested but it is not supported by the " + - "current Java toolchain '" + str(toolchain.label) + - "'; see the java_toolchain.header_compiler_direct attribute", - ) - return True - -def run_ijar( - actions, - jar, - java_toolchain, - target_label = None, - # private to @_builtins: - output = None, - injecting_rule_kind = None): - """Runs ijar on a jar, stripping it of its method bodies. - - This helps reduce rebuilding of dependent jars during any recompiles consisting only of simple - changes to method implementations. The return value is typically passed to JavaInfo.compile_jar - - Args: - actions: (actions) ctx.actions - jar: (File) The jar to run ijar on. - java_toolchain: (JavaToolchainInfo) The toolchain to used to find the ijar tool. - target_label: (Label|None) A target label to stamp the jar with. Used for `add_dep` support. - Typically, you would pass `ctx.label` to stamp the jar with the current rule's label. - output: (File) Optional. - injecting_rule_kind: (str) the rule class of the current target - Returns: - (File) The output artifact - """ - if not output: - output = actions.declare_file(paths.replace_extension(jar.basename, "-ijar.jar"), sibling = jar) - args = actions.args() - args.add(jar) - args.add(output) - if target_label != None: - args.add("--target_label", target_label) - if injecting_rule_kind != None: - args.add("--injecting_rule_kind", injecting_rule_kind) - - actions.run( - mnemonic = "JavaIjar", - inputs = [jar], - outputs = [output], - executable = java_toolchain.ijar, - arguments = [args], - progress_message = "Extracting interface for jar %{input}", - toolchain = semantics.JAVA_TOOLCHAIN_TYPE, - use_default_shell_env = True, - ) - return output - -def target_kind(target): - """Get the rule class string for a target - - Args: - target: (Target) - - Returns: - (str) The rule class string of the target - """ - return _java_common_internal.target_kind(target) - -def collect_native_deps_dirs(libraries): - """Collect the set of root-relative paths containing native libraries - - Args: - libraries: (depset[LibraryToLink]) set of native libraries - - Returns: - ([String]) A set of root-relative paths as a list - """ - return _java_common_internal.collect_native_deps_dirs(libraries) - -def get_runtime_classpath_for_archive(jars, excluded_jars): - """Filters a classpath to remove certain entries - - Args - jars: (depset[File]) The classpath to filter - excluded_jars: (depset[File]) The files to remove - - Returns: - (depset[File]) The filtered classpath - """ - return _java_common_internal.get_runtime_classpath_for_archive( - jars, - excluded_jars, - ) - -def filter_protos_for_generated_extension_registry(runtime_jars, deploy_env): - """Get proto artifacts from runtime_jars excluding those in deploy_env - - Args: - runtime_jars: (depset[File]) the artifacts to scan - deploy_env: (depset[File]) the artifacts to exclude - - Returns - (depset[File], bool) A tuple of the filtered protos and whether all protos are 'lite' - flavored - """ - return _java_common_internal.filter_protos_for_generated_extension_registry( - runtime_jars, - deploy_env, - ) diff --git a/src/main/starlark/builtins_bzl/common/java/java_helper.bzl b/src/main/starlark/builtins_bzl/common/java/java_helper.bzl deleted file mode 100644 index 3b31e0c96e188e..00000000000000 --- a/src/main/starlark/builtins_bzl/common/java/java_helper.bzl +++ /dev/null @@ -1,486 +0,0 @@ -# Copyright 2022 The Bazel Authors. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Common util functions for java_* rules""" - -load(":common/cc/cc_common.bzl", "cc_common") -load(":common/cc/cc_helper.bzl", "cc_helper") -load(":common/java/java_semantics.bzl", "semantics") -load(":common/paths.bzl", "paths") - -testing = _builtins.toplevel.testing -_java_common_internal = _builtins.internal.java_common_internal_do_not_use - -def _collect_all_targets_as_deps(ctx, classpath_type = "all"): - deps = [] - if not classpath_type == "compile_only": - if hasattr(ctx.attr, "runtime_deps"): - deps.extend(ctx.attr.runtime_deps) - if hasattr(ctx.attr, "exports"): - deps.extend(ctx.attr.exports) - - deps.extend(ctx.attr.deps or []) - - launcher = _filter_launcher_for_target(ctx) - if launcher: - deps.append(launcher) - - return deps - -def _filter_launcher_for_target(ctx): - # create_executable=0 disables the launcher - if hasattr(ctx.attr, "create_executable") and not ctx.attr.create_executable: - return None - - # use_launcher=False disables the launcher - if hasattr(ctx.attr, "use_launcher") and not ctx.attr.use_launcher: - return None - - # BUILD rule "launcher" attribute - if ctx.attr.launcher and cc_common.launcher_provider in ctx.attr.launcher: - return ctx.attr.launcher - - return None - -def _launcher_artifact_for_target(ctx): - launcher = _filter_launcher_for_target(ctx) - if not launcher: - return None - files = launcher[DefaultInfo].files.to_list() - if len(files) != 1: - fail("%s expected a single artifact in %s" % (ctx.label, launcher)) - return files[0] - -def _check_and_get_main_class(ctx): - create_executable = ctx.attr.create_executable - use_testrunner = ctx.attr.use_testrunner - main_class = ctx.attr.main_class - - if not create_executable and use_testrunner: - fail("cannot have use_testrunner without creating an executable") - if not create_executable and main_class: - fail("main class must not be specified when executable is not created") - if create_executable and not use_testrunner: - if not main_class: - if not ctx.attr.srcs: - fail("need at least one of 'main_class', 'use_testrunner' or Java source files") - main_class = _primary_class(ctx) - if main_class == None: - fail("main_class was not provided and cannot be inferred: " + - "source path doesn't include a known root (java, javatests, src, testsrc)") - if not create_executable: - return None - if not main_class: - if use_testrunner: - main_class = "com.google.testing.junit.runner.GoogleTestRunner" - else: - main_class = _primary_class(ctx) - return main_class - -def _primary_class(ctx): - if ctx.attr.srcs: - main = ctx.label.name + ".java" - for src in ctx.files.srcs: - if src.basename == main: - return _full_classname(_strip_extension(src)) - return _full_classname(paths.get_relative(ctx.label.package, ctx.label.name)) - -def _strip_extension(file): - return file.dirname + "/" + ( - file.basename[:-(1 + len(file.extension))] if file.extension else file.basename - ) - -# TODO(b/193629418): once out of builtins, create a canonical implementation and remove duplicates in depot -def _full_classname(path): - java_segments = _java_segments(path) - return ".".join(java_segments) if java_segments != None else None - -def _java_segments(path): - if path.startswith("/"): - fail("path must not be absolute: '%s'" % path) - segments = path.split("/") - root_idx = -1 - for idx, segment in enumerate(segments): - if segment in ["java", "javatests", "src", "testsrc"]: - root_idx = idx - break - if root_idx < 0: - return None - is_src = "src" == segments[root_idx] - check_mvn_idx = root_idx if is_src else -1 - if (root_idx == 0 or is_src): - for i in range(root_idx + 1, len(segments) - 1): - segment = segments[i] - if "src" == segment or (is_src and (segment in ["java", "javatests"])): - next = segments[i + 1] - if next in ["com", "org", "net"]: - root_idx = i - elif "src" == segment: - check_mvn_idx = i - break - - if check_mvn_idx >= 0 and check_mvn_idx < len(segments) - 2: - next = segments[check_mvn_idx + 1] - if next in ["main", "test"]: - next = segments[check_mvn_idx + 2] - if next in ["java", "resources"]: - root_idx = check_mvn_idx + 2 - return segments[(root_idx + 1):] - -def _concat(*lists): - result = [] - for list in lists: - result.extend(list) - return result - -def _get_shared_native_deps_path( - linker_inputs, - link_opts, - linkstamps, - build_info_artifacts, - features, - is_test_target_partially_disabled_thin_lto): - """ - Returns the path of the shared native library. - - The name must be generated based on the rule-specific inputs to the link actions. At this point - this includes order-sensitive list of linker inputs and options collected from the transitive - closure and linkstamp-related artifacts that are compiled during linking. All those inputs can - be affected by modifying target attributes (srcs/deps/stamp/etc). However, target build - configuration can be ignored since it will either change output directory (in case of different - configuration instances) or will not affect anything (if two targets use same configuration). - Final goal is for all native libraries that use identical linker command to use same output - name. - -

TODO(bazel-team): (2010) Currently process of identifying parameters that can affect native - library name is manual and should be kept in sync with the code in the - CppLinkAction.Builder/CppLinkAction/Link classes which are responsible for generating linker - command line. Ideally we should reuse generated command line for both purposes - selecting a - name of the native library and using it as link action payload. For now, correctness of the - method below is only ensured by validations in the CppLinkAction.Builder.build() method. - """ - - fp = "" - for artifact in linker_inputs: - fp += artifact.short_path - fp += str(len(link_opts)) - for opt in link_opts: - fp += opt - for artifact in linkstamps: - fp += artifact.short_path - for artifact in build_info_artifacts: - fp += artifact.short_path - for feature in features: - fp += feature - - # Sharing of native dependencies may cause an ActionConflictException when ThinLTO is - # disabled for test and test-only targets that are statically linked, but enabled for other - # statically linked targets. This happens in case the artifacts for the shared native - # dependency are output by actions owned by the non-test and test targets both. To fix - # this, we allow creation of multiple artifacts for the shared native library - one shared - # among the test and test-only targets where ThinLTO is disabled, and the other shared among - # other targets where ThinLTO is enabled. - fp += "1" if is_test_target_partially_disabled_thin_lto else "0" - - fingerprint = "%x" % hash(fp) - return "_nativedeps/" + fingerprint - -def _check_and_get_one_version_attribute(ctx, attr): - value = getattr(semantics.find_java_toolchain(ctx), attr) - return value - -def _jar_and_target_arg_mapper(jar): - # Emit pretty labels for targets in the main repository. - label = str(jar.owner) - if label.startswith("@@//"): - label = label.lstrip("@") - return jar.path + "," + label - -def _get_feature_config(ctx): - cc_toolchain = cc_helper.find_cpp_toolchain(ctx, mandatory = False) - if not cc_toolchain: - return None - feature_config = cc_common.configure_features( - ctx = ctx, - cc_toolchain = cc_toolchain, - requested_features = ctx.features + ["java_launcher_link", "static_linking_mode"], - unsupported_features = ctx.disabled_features, - ) - return feature_config - -def _should_strip_as_default(ctx, feature_config): - fission_is_active = ctx.fragments.cpp.fission_active_for_current_compilation_mode() - create_per_obj_debug_info = fission_is_active and cc_common.is_enabled( - feature_name = "per_object_debug_info", - feature_configuration = feature_config, - ) - compilation_mode = ctx.var["COMPILATION_MODE"] - strip_as_default = create_per_obj_debug_info and compilation_mode == "opt" - - return strip_as_default - -def _get_coverage_config(ctx, runner): - toolchain = semantics.find_java_toolchain(ctx) - if not ctx.configuration.coverage_enabled: - return None - runner = runner if ctx.attr.create_executable else None - manifest = ctx.actions.declare_file("runtime_classpath_for_coverage/%s/runtime_classpath.txt" % ctx.label.name) - singlejar = toolchain.single_jar - return struct( - runner = runner, - main_class = "com.google.testing.coverage.JacocoCoverageRunner", - manifest = manifest, - env = { - "JAVA_RUNTIME_CLASSPATH_FOR_COVERAGE": manifest.path, - "SINGLE_JAR_TOOL": singlejar.executable.path, - }, - support_files = [manifest, singlejar.executable], - ) - -def _get_java_executable(ctx, java_runtime_toolchain, launcher): - java_executable = launcher.short_path if launcher else java_runtime_toolchain.java_executable_runfiles_path - if not _is_absolute_target_platform_path(ctx, java_executable): - java_executable = ctx.workspace_name + "/" + java_executable - return paths.normalize(java_executable) - -def _is_target_platform_windows(ctx): - return cc_helper.has_target_constraints(ctx, ctx.attr._windows_constraints) - -def _is_absolute_target_platform_path(ctx, path): - if _is_target_platform_windows(ctx): - return len(path) > 2 and path[1] == ":" - return path.startswith("/") - -def _runfiles_enabled(ctx): - return ctx.configuration.runfiles_enabled() - -def _get_test_support(ctx): - if ctx.attr.create_executable and ctx.attr.use_testrunner: - return ctx.attr._test_support - return None - -def _test_providers(ctx): - test_providers = [] - if cc_helper.has_target_constraints(ctx, ctx.attr._apple_constraints): - test_providers.append(testing.ExecutionInfo({"requires-darwin": ""})) - - test_env = {} - test_env.update(cc_helper.get_expanded_env(ctx, {})) - - coverage_config = _get_coverage_config( - ctx, - runner = None, # we only need the environment - ) - if coverage_config: - test_env.update(coverage_config.env) - test_providers.append(testing.TestEnvironment( - environment = test_env, - inherited_environment = ctx.attr.env_inherit, - )) - - return test_providers - -def _executable_providers(ctx): - if ctx.attr.create_executable: - return [_builtins.toplevel.RunEnvironmentInfo(cc_helper.get_expanded_env(ctx, {}))] - return [] - -def _resource_mapper(file): - root_relative_path = paths.relativize( - path = file.path, - start = paths.join(file.root.path, file.owner.workspace_root), - ) - return "%s:%s" % ( - file.path, - semantics.get_default_resource_path(root_relative_path, segment_extractor = _java_segments), - ) - -def _create_single_jar( - actions, - toolchain, - output, - sources = depset(), - resources = depset(), - mnemonic = "JavaSingleJar", - progress_message = "Building singlejar jar %{output}", - build_target = None, - output_creator = None): - """Register singlejar action for the output jar. - - Args: - actions: (actions) ctx.actions - toolchain: (JavaToolchainInfo) The java toolchain - output: (File) Output file of the action. - sources: (depset[File]) The jar files to merge into the output jar. - resources: (depset[File]) The files to add to the output jar. - mnemonic: (str) The action identifier - progress_message: (str) The action progress message - build_target: (Label) The target label to stamp in the manifest. Optional. - output_creator: (str) The name of the tool to stamp in the manifest. Optional, - defaults to 'singlejar' - Returns: - (File) Output file which was used for registering the action. - """ - args = actions.args() - args.set_param_file_format("shell").use_param_file("@%s", use_always = True) - args.add("--output", output) - args.add_all( - [ - "--compression", - "--normalize", - "--exclude_build_data", - "--warn_duplicate_resources", - ], - ) - args.add_all("--sources", sources) - args.add_all("--resources", resources, map_each = _resource_mapper) - - args.add("--build_target", build_target) - args.add("--output_jar_creator", output_creator) - - actions.run( - mnemonic = mnemonic, - progress_message = progress_message, - executable = toolchain.single_jar, - toolchain = semantics.JAVA_TOOLCHAIN_TYPE, - inputs = depset(transitive = [resources, sources]), - tools = [toolchain.single_jar], - outputs = [output], - arguments = [args], - ) - return output - -# TODO(hvd): use skylib shell.quote() -def _shell_escape(s): - """Shell-escape a string - - Quotes a word so that it can be used, without further quoting, as an argument - (or part of an argument) in a shell command. - - Args: - s: (str) the string to escape - - Returns: - (str) the shell-escaped string - """ - if not s: - # Empty string is a special case: needs to be quoted to ensure that it - # gets treated as a separate argument. - return "''" - for c in s.elems(): - # We do this positively so as to be sure we don't inadvertently forget - # any unsafe characters. - if not c.isalnum() and c not in "@%-_+:,./": - return "'" + s.replace("'", "'\\''") + "'" - return s - -def _tokenize_javacopts(ctx = None, opts = []): - """Tokenizes a list or depset of options to a list. - - Iff opts is a depset, we reverse the flattened list to ensure right-most - duplicates are preserved in their correct position. - - If the ctx parameter is omitted, a slow, but pure Starlark, implementation - of shell tokenization is used. Otherwise, tokenization is performed using - ctx.tokenize() which has significantly better performance (up to 100x for - large options lists). - - Args: - ctx: (RuleContext|None) the rule context - opts: (depset[str]|[str]) the javac options to tokenize - Returns: - [str] list of tokenized options - """ - if hasattr(opts, "to_list"): - opts = reversed(opts.to_list()) - if ctx: - return [ - token - for opt in opts - for token in ctx.tokenize(opt) - ] - else: - # TODO: optimize and use the pure Starlark implementation in cc_helper - return _java_common_internal.tokenize_javacopts(opts) - -def _detokenize_javacopts(opts): - """Detokenizes a list of options to a depset. - - Args: - opts: ([str]) the javac options to detokenize - - Returns: - (depset[str]) depset of detokenized options - """ - return depset( - [" ".join([_shell_escape(opt) for opt in opts])], - order = "preorder", - ) - -def _derive_output_file(ctx, base_file, *, name_suffix = "", extension = None, extension_suffix = ""): - """Declares a new file whose name is derived from the given file - - This method allows appending a suffix to the name (before extension), changing - the extension or appending a suffix after the extension. The new file is declared - as a sibling of the given base file. At least one of the three options must be - specified. It is an error to specify both `extension` and `extension_suffix`. - - Args: - ctx: (RuleContext) the rule context. - base_file: (File) the file from which to derive the resultant file. - name_suffix: (str) Optional. The suffix to append to the name before the - extension. - extension: (str) Optional. The new extension to use (without '.'). By default, - the base_file's extension is used. - extension_suffix: (str) Optional. The suffix to append to the base_file's extension - - Returns: - (File) the derived file - """ - if not name_suffix and not extension_suffix and not extension: - fail("At least one of name_suffix, extension or extension_suffix is required") - if extension and extension_suffix: - fail("only one of extension or extension_suffix can be specified") - if extension == None: - extension = base_file.extension - new_basename = paths.replace_extension(base_file.basename, name_suffix + "." + extension + extension_suffix) - return ctx.actions.declare_file(new_basename, sibling = base_file) - -helper = struct( - collect_all_targets_as_deps = _collect_all_targets_as_deps, - filter_launcher_for_target = _filter_launcher_for_target, - launcher_artifact_for_target = _launcher_artifact_for_target, - check_and_get_main_class = _check_and_get_main_class, - primary_class = _primary_class, - strip_extension = _strip_extension, - concat = _concat, - get_shared_native_deps_path = _get_shared_native_deps_path, - check_and_get_one_version_attribute = _check_and_get_one_version_attribute, - jar_and_target_arg_mapper = _jar_and_target_arg_mapper, - get_feature_config = _get_feature_config, - should_strip_as_default = _should_strip_as_default, - get_coverage_config = _get_coverage_config, - get_java_executable = _get_java_executable, - is_absolute_target_platform_path = _is_absolute_target_platform_path, - is_target_platform_windows = _is_target_platform_windows, - runfiles_enabled = _runfiles_enabled, - get_test_support = _get_test_support, - test_providers = _test_providers, - executable_providers = _executable_providers, - create_single_jar = _create_single_jar, - shell_escape = _shell_escape, - tokenize_javacopts = _tokenize_javacopts, - detokenize_javacopts = _detokenize_javacopts, - derive_output_file = _derive_output_file, -) diff --git a/src/main/starlark/builtins_bzl/common/java/java_info.bzl b/src/main/starlark/builtins_bzl/common/java/java_info.bzl deleted file mode 100644 index 45919989ea2e2c..00000000000000 --- a/src/main/starlark/builtins_bzl/common/java/java_info.bzl +++ /dev/null @@ -1,971 +0,0 @@ -# Copyright 2023 The Bazel Authors. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -""" -Definition of JavaInfo and JavaPluginInfo provider. -""" - -load(":common/cc/cc_common.bzl", "cc_common") -load(":common/cc/cc_info.bzl", "CcInfo") -load(":common/java/java_semantics.bzl", "semantics") - -# TODO(hvd): remove this when: -# - we have a general provider-type checking API -# - no longer need to check for --experimental_google_legacy_api -_java_common_internal = _builtins.internal.java_common_internal_do_not_use - -_JavaOutputInfo = provider( - doc = "The outputs of Java compilation.", - fields = { - "class_jar": "(File) A classes jar file.", - "compile_jar": "(File) An interface jar file.", - "ijar": "Deprecated: Please use compile_jar.", - "compile_jdeps": "(File) Compile time dependencies information (deps.proto file).", - "generated_class_jar": "(File) A jar containing classes generated via annotation processing.", - "generated_source_jar": "(File) The source jar created as a result of annotation processing.", - "native_headers_jar": "(File) A jar of CC header files supporting native method implementation.", - "manifest_proto": "(File) The manifest protobuf file of the manifest generated from JavaBuilder.", - "jdeps": "(File) The jdeps protobuf file of the manifest generated from JavaBuilder.", - "source_jars": "(depset[File]) A depset of sources archive files.", - "source_jar": "Deprecated: Please use source_jars instead.", - }, -) -_ModuleFlagsInfo = provider( - doc = "Provider for the runtime classpath contributions of a Java binary.", - fields = { - "add_exports": "(depset[str]) Add-Exports configuration.", - "add_opens": "(depset[str]) Add-Opens configuration.", - }, -) -_EMPTY_MODULE_FLAGS_INFO = _ModuleFlagsInfo(add_exports = depset(), add_opens = depset()) - -def _create_module_flags_info(*, add_exports, add_opens): - if add_exports or add_opens: - return _ModuleFlagsInfo(add_exports = add_exports, add_opens = add_opens) - return _EMPTY_MODULE_FLAGS_INFO - -_JavaRuleOutputJarsInfo = provider( - doc = "Deprecated: use java_info.java_outputs. Information about outputs of a Java rule.", - fields = { - "jdeps": "Deprecated: Use java_info.java_outputs.", - "native_headers": "Deprecated: Use java_info.java_outputs[i].jdeps.", - "jars": "Deprecated: Use java_info.java_outputs[i].native_headers_jar.", - }, -) -_JavaGenJarsInfo = provider( - doc = "Deprecated: Information about jars that are a result of annotation processing for a Java rule.", - fields = { - "enabled": "Deprecated. Returns true if annotation processing was applied on this target.", - "class_jar": "Deprecated: Please use JavaInfo.java_outputs.generated_class_jar instead.", - "source_jar": "Deprecated: Please use JavaInfo.java_outputs.generated_source_jar instead.", - "transitive_class_jars": "Deprecated. A transitive set of class file jars from annotation " + - "processing of this rule and its dependencies.", - "transitive_source_jars": "Deprecated. A transitive set of source archives from annotation " + - "processing of this rule and its dependencies.", - "processor_classpath": "Deprecated: Please use JavaInfo.plugins instead.", - "processor_classnames": "Deprecated: Please use JavaInfo.plugins instead.", - }, -) - -JavaCompilationInfo = provider( - doc = "Compilation information in Java rules, for perusal of aspects and tools.", - fields = { - "boot_classpath": "Boot classpath for this Java target.", - "javac_options": """Depset of options to the java compiler. To get the - exact list of options passed to javac in the correct order, use the - tokenize_javacopts utility in rules_java""", - "compilation_classpath": "Compilation classpath for this Java target.", - "runtime_classpath": "Run-time classpath for this Java target.", - }, -) - -def merge( - providers, - # private to @_builtins: - merge_java_outputs = True, - merge_source_jars = True): - """Merges the given providers into a single JavaInfo. - - Args: - providers: ([JavaInfo]) The list of providers to merge. - merge_java_outputs: (bool) - merge_source_jars: (bool) - - Returns: - (JavaInfo) The merged JavaInfo - """ - _validate_provider_list(providers, "providers", JavaInfo) - - plugin_info = merge_plugin_info_without_outputs(providers) - - source_jars = [] # [File] - transitive_source_jars = [] # [depset[File]] - java_outputs = [] # [_JavaOutputInfo] - runtime_output_jars = [] # [File] - transitive_runtime_jars = [] # [depset[File]] - transitive_compile_time_jars = [] # [depset[File]] - compile_jars = [] # [depset[File]] - full_compile_jars = [] # [depset[File]] - _transitive_full_compile_time_jars = [] # [depset[File]] - _compile_time_java_dependencies = [] # [depset[File]] - add_exports = [] # [depset[str]] - add_opens = [] # [depset[str]] - _neverlink = False - _constraints = [] # [str] - for p in providers: - if merge_source_jars: - source_jars.extend(p.source_jars) - transitive_source_jars.append(p.transitive_source_jars) - if merge_java_outputs: - java_outputs.extend(p.java_outputs) - runtime_output_jars.extend(p.runtime_output_jars) - transitive_runtime_jars.append(p.transitive_runtime_jars) - transitive_compile_time_jars.append(p.transitive_compile_time_jars) - compile_jars.append(p.compile_jars) - full_compile_jars.append(p.full_compile_jars) - _transitive_full_compile_time_jars.append(p._transitive_full_compile_time_jars) - _compile_time_java_dependencies.append(p._compile_time_java_dependencies) - add_exports.append(p.module_flags_info.add_exports) - add_opens.append(p.module_flags_info.add_opens) - _neverlink = _neverlink or p._neverlink - _constraints.extend(p._constraints) - - transitive_runtime_jars = depset(order = "preorder", transitive = transitive_runtime_jars) - transitive_compile_time_jars = depset(order = "preorder", transitive = transitive_compile_time_jars) - - # java_outputs is a list so we uniquify to avoid https://github.com/bazelbuild/bazel/issues/17170 - java_outputs = depset(java_outputs).to_list() - result = { - "transitive_runtime_jars": transitive_runtime_jars, - "transitive_compile_time_jars": transitive_compile_time_jars, - "compile_jars": depset(order = "preorder", transitive = compile_jars), - "full_compile_jars": depset(order = "preorder", transitive = full_compile_jars), - "_transitive_full_compile_time_jars": depset(order = "preorder", transitive = _transitive_full_compile_time_jars), - "_compile_time_java_dependencies": depset(order = "preorder", transitive = _compile_time_java_dependencies), - # runtime_output_jars is a list so we uniquify to avoid https://github.com/bazelbuild/bazel/issues/17170 - "runtime_output_jars": depset(runtime_output_jars).to_list(), - # source_jars is a list so we uniquify to avoid https://github.com/bazelbuild/bazel/issues/17170 - "source_jars": depset(source_jars).to_list(), - "transitive_source_jars": depset(transitive = transitive_source_jars), - "java_outputs": java_outputs, - "outputs": _JavaRuleOutputJarsInfo(jars = java_outputs, jdeps = None, native_headers = None), - "module_flags_info": _create_module_flags_info( - add_exports = depset(transitive = add_exports), - add_opens = depset(transitive = add_opens), - ), - "plugins": plugin_info.plugins, - "api_generating_plugins": plugin_info.api_generating_plugins, - "_neverlink": bool(_neverlink), - "_constraints": depset(_constraints).to_list(), - "annotation_processing": None, - "compilation_info": None, - } - - if _java_common_internal._google_legacy_api_enabled(): - cc_info = semantics.minimize_cc_info(cc_common.merge_cc_infos(cc_infos = [p.cc_link_params_info for p in providers])) - result.update( - cc_link_params_info = cc_info, - transitive_native_libraries = cc_info.transitive_native_libraries(), - ) - else: - result.update( - transitive_native_libraries = depset( - order = "topological", - transitive = [p.transitive_native_libraries for p in providers], - ), - ) - return _java_common_internal.wrap_java_info(_new_javainfo(**result)) - -def to_java_binary_info(java_info, compilation_info): - """Get a copy of the given JavaInfo with minimal info returned by a java_binary - - Args: - java_info: (JavaInfo) A JavaInfo provider instance - compilation_info: (JavaCompilationInfo) - Returns: - (JavaInfo) A JavaInfo instance representing a java_binary target - """ - result = { - "transitive_runtime_jars": depset(), - "transitive_compile_time_jars": depset(), - "compile_jars": depset(), - "full_compile_jars": depset(), - "_transitive_full_compile_time_jars": depset(), - "_compile_time_java_dependencies": depset(), - "runtime_output_jars": [], - "plugins": _EMPTY_PLUGIN_DATA, - "api_generating_plugins": _EMPTY_PLUGIN_DATA, - "module_flags_info": _EMPTY_MODULE_FLAGS_INFO, - "_neverlink": False, - "_constraints": [], - "annotation_processing": java_info.annotation_processing, - "transitive_native_libraries": java_info.transitive_native_libraries, - "source_jars": java_info.source_jars, - "transitive_source_jars": java_info.transitive_source_jars, - } - if hasattr(java_info, "cc_link_params_info"): - result.update(cc_link_params_info = java_info.cc_link_params_info) - - result["compilation_info"] = compilation_info - - java_outputs = [ - _JavaOutputInfo( - compile_jar = None, - ijar = None, # deprecated - compile_jdeps = None, - class_jar = output.class_jar, - generated_class_jar = output.generated_class_jar, - generated_source_jar = output.generated_source_jar, - native_headers_jar = output.native_headers_jar, - manifest_proto = output.manifest_proto, - jdeps = output.jdeps, - source_jars = output.source_jars, - source_jar = output.source_jar, # deprecated - ) - for output in java_info.java_outputs - ] - all_jdeps = [output.jdeps for output in java_info.java_outputs if output.jdeps] - all_native_headers = [output.native_headers_jar for output in java_info.java_outputs if output.native_headers_jar] - result.update( - java_outputs = java_outputs, - outputs = _JavaRuleOutputJarsInfo( - jars = java_outputs, - jdeps = all_jdeps[0] if len(all_jdeps) == 1 else None, - native_headers = all_native_headers[0] if len(all_native_headers) == 1 else None, - ), - ) - - # so that translation into native JavaInfo does not add JavaCompilationArgsProvider - result.update(_is_binary = True) - return _new_javainfo(**result) - -def _to_mutable_dict(java_info): - return { - key: getattr(java_info, key) - for key in dir(java_info) - if key not in ["to_json", "to_proto"] - } - -def add_constraints(java_info, constraints = []): - """Returns a copy of the given JavaInfo with the given constraints added. - - Args: - java_info: (JavaInfo) The JavaInfo to enhance - constraints: ([str]) Constraints to add - - Returns: - (JavaInfo) - """ - result = _to_mutable_dict(java_info) - old_constraints = java_info._constraints if java_info._constraints else [] - result.update( - _constraints = depset(constraints + old_constraints).to_list(), - ) - return _new_javainfo(**result) - -def make_non_strict(java_info): - """Returns a new JavaInfo instance whose direct-jars part is the union of both the direct and indirect jars of the given Java provider. - - Args: - java_info: (JavaInfo) The java info to make non-strict. - - Returns: - (JavaInfo) - """ - result = _to_mutable_dict(java_info) - result.update( - compile_jars = java_info.transitive_compile_time_jars, - full_compile_jars = java_info._transitive_full_compile_time_jars, - ) - - # Omit jdeps, which aren't available transitively and aren't useful for reduced classpath - # pruning for non-strict targets: the direct classpath and transitive classpath are the same, - # so there's nothing to prune, and reading jdeps at compile-time isn't free. - result.update( - _compile_time_java_dependencies = depset(), - ) - return _new_javainfo(**result) - -def add_module_flags(java_info, add_exports = [], add_opens = []): - """Returns a new JavaInfo instance with the additional add_exports/add_opens - - Args: - java_info: (JavaInfo) The java info to enhance. - add_exports: ([str]) The /s given access to. - add_opens: ([str]) The /s given reflective access to. - Returns: - (JavaInfo) - """ - if not add_exports and not add_opens: - return java_info - - result = _to_mutable_dict(java_info) - result.update( - module_flags_info = _create_module_flags_info( - add_exports = depset(add_exports, transitive = [java_info.module_flags_info.add_exports]), - add_opens = depset(add_opens, transitive = [java_info.module_flags_info.add_opens]), - ), - ) - return _new_javainfo(**result) - -def set_annotation_processing( - java_info, - enabled = False, - processor_classnames = [], - processor_classpath = None, - class_jar = None, - source_jar = None): - """Returns a copy of the given JavaInfo with the given annotation_processing info. - - Args: - java_info: (JavaInfo) The JavaInfo to enhance. - enabled: (bool) Whether the rule uses annotation processing. - processor_classnames: ([str]) Class names of annotation processors applied. - processor_classpath: (depset[File]) Class names of annotation processors applied. - class_jar: (File) Optional. Jar that is the result of annotation processing. - source_jar: (File) Optional. Source archive resulting from annotation processing. - - Returns: - (JavaInfo) - """ - gen_jars_info = java_info.annotation_processing - if gen_jars_info: - # Existing Jars would be a problem b/c we can't remove them from transitiveXxx sets - if gen_jars_info.class_jar and gen_jars_info.class_jar != class_jar: - fail("Existing gen_class_jar:", gen_jars_info.class_jar) - if gen_jars_info.source_jar and gen_jars_info.source_jar != source_jar: - fail("Existing gen_source_jar:", gen_jars_info.class_jar) - transitive_class_jars = depset([class_jar] if class_jar else [], transitive = [gen_jars_info.transitive_class_jars]) - transitive_source_jars = depset([source_jar] if source_jar else [], transitive = [gen_jars_info.transitive_source_jars]) - else: - transitive_class_jars = depset([class_jar] if class_jar else []) - transitive_source_jars = depset([source_jar] if source_jar else []) - - result = _to_mutable_dict(java_info) - result.update( - annotation_processing = _JavaGenJarsInfo( - enabled = enabled, - class_jar = class_jar, - source_jar = source_jar, - processor_classnames = processor_classnames, - processor_classpath = processor_classpath if processor_classpath else depset(), - transitive_class_jars = transitive_class_jars, - transitive_source_jars = transitive_source_jars, - ), - ) - return _new_javainfo(**result) - -def java_info_for_compilation( - output_jar, - compile_jar, - source_jar, - generated_class_jar, - generated_source_jar, - plugin_info, - deps, - runtime_deps, - exports, - exported_plugins, - compile_jdeps, - jdeps, - native_headers_jar, - manifest_proto, - native_libraries, - neverlink, - add_exports, - add_opens, - direct_runtime_jars, - compilation_info): - """Creates a JavaInfo instance represiting the result of java compilation. - - Args: - output_jar: (File) The jar that was created as a result of a compilation. - compile_jar: (File) A jar that is the compile-time dependency in lieu of `output_jar`. - source_jar: (File) The source jar that was used to create the output jar. - generated_class_jar: (File) A jar file containing class files compiled from sources - generated during annotation processing. - generated_source_jar: (File) The source jar that was created as a result of annotation - processing. - plugin_info: (JavaPluginInfo) Information about annotation processing. - deps: ([JavaInfo]) Compile time dependencies that were used to create the output jar. - runtime_deps: ([JavaInfo]) Runtime dependencies that are needed for this library. - exports: ([JavaInfo]) Libraries to make available for users of this library. - exported_plugins: ([JavaPluginInfo]) A list of exported plugins. - compile_jdeps: (File) jdeps information about compile time dependencies to be consumed by - JavaCompileAction. This should be a binary proto encoded using the deps.proto protobuf - included with Bazel. If available this file is typically produced by a header compiler. - jdeps: (File) jdeps information for the rule output (if available). This should be a binary - proto encoded using the deps.proto protobuf included with Bazel. If available this file - is typically produced by a compiler. IDEs and other tools can use this information for - more efficient processing. - native_headers_jar: (File) A jar containing CC header files supporting native method - implementation (typically output of javac -h). - manifest_proto: (File) Manifest information for the rule output (if available). This should - be a binary proto encoded using the manifest.proto protobuf included with Bazel. IDEs - and other tools can use this information for more efficient processing. - native_libraries: ([CcInfo]) Native library dependencies that are needed for this library. - neverlink: (bool) If true, only use this library for compilation and not at runtime. - add_exports: ([str]) The /s this library was given access to. - add_opens: ([str]) The /s this library was given reflective access to. - direct_runtime_jars: ([File]) The class jars needed directly by this library at runtime. - This is usually just the output_jar or empty if there were no sources/resources. - compilation_info: (struct) Information for IDE/tools - - Returns: - (JavaInfo) the JavaInfo instance - """ - result, concatenated_deps = _javainfo_init_base( - output_jar, - compile_jar, - source_jar, - deps, - runtime_deps, - exports, - exported_plugins, - jdeps, - compile_jdeps, - native_headers_jar, - manifest_proto, - generated_class_jar, - generated_source_jar, - native_libraries, - neverlink, - ) - - # this differs ever so slightly from the usual JavaInfo in that direct_runtime_jars - # does not contain the output_jar is there were no sources/resources - transitive_runtime_jars = depset() if neverlink else depset( - order = "preorder", - direct = direct_runtime_jars, - transitive = [dep.transitive_runtime_jars for dep in concatenated_deps.exports_deps + runtime_deps], - ) - result.update( - runtime_output_jars = direct_runtime_jars, - transitive_runtime_jars = transitive_runtime_jars, - transitive_source_jars = depset( - direct = [source_jar], - # only differs from the usual java_info.transitive_source_jars in the order of deps - transitive = [dep.transitive_source_jars for dep in concatenated_deps.runtimedeps_exports_deps], - ), - # the JavaInfo constructor does not add flags from runtime_deps - module_flags_info = _create_module_flags_info( - add_exports = depset(add_exports, transitive = [ - dep.module_flags_info.add_exports - for dep in concatenated_deps.runtimedeps_exports_deps - ]), - add_opens = depset(add_opens, transitive = [ - dep.module_flags_info.add_opens - for dep in concatenated_deps.runtimedeps_exports_deps - ]), - ), - ) - if compilation_info: - result.update( - compilation_info = JavaCompilationInfo( - javac_options = compilation_info.javac_options, - boot_classpath = compilation_info.boot_classpath, - compilation_classpath = compilation_info.compilation_classpath, - runtime_classpath = compilation_info.runtime_classpath, - ), - annotation_processing = _JavaGenJarsInfo( - enabled = compilation_info.uses_annotation_processing, - class_jar = result["annotation_processing"].class_jar, - source_jar = result["annotation_processing"].source_jar, - processor_classnames = plugin_info.plugins.processor_classes.to_list(), - processor_classpath = plugin_info.plugins.processor_jars, - transitive_class_jars = result["annotation_processing"].transitive_class_jars, - transitive_source_jars = result["annotation_processing"].transitive_source_jars, - ), - ) - else: - result.update( - compilation_info = None, - annotation_processing = None, - ) - return _java_common_internal.wrap_java_info(_new_javainfo(**result)) - -def _validate_provider_list(provider_list, what, expected_provider_type): - _java_common_internal.check_provider_instances(provider_list, what, expected_provider_type) - -def _compute_concatenated_deps(deps, runtime_deps, exports): - deps_exports = [] - deps_exports.extend(deps) - deps_exports.extend(exports) - - exports_deps = [] - exports_deps.extend(exports) - exports_deps.extend(deps) - - runtimedeps_exports_deps = [] - runtimedeps_exports_deps.extend(runtime_deps) - runtimedeps_exports_deps.extend(exports_deps) - - return struct( - deps_exports = deps_exports, - exports_deps = exports_deps, - runtimedeps_exports_deps = runtimedeps_exports_deps, - ) - -def _javainfo_init_base( - output_jar, - compile_jar, - source_jar, - deps, - runtime_deps, - exports, - exported_plugins, - jdeps, - compile_jdeps, - native_headers_jar, - manifest_proto, - generated_class_jar, - generated_source_jar, - native_libraries, - neverlink): - _validate_provider_list(deps, "deps", JavaInfo) - _validate_provider_list(runtime_deps, "runtime_deps", JavaInfo) - _validate_provider_list(exports, "exports", JavaInfo) - _validate_provider_list(native_libraries, "native_libraries", CcInfo) - - concatenated_deps = _compute_concatenated_deps(deps, runtime_deps, exports) - - source_jars = [source_jar] if source_jar else [] - plugin_info = merge_plugin_info_without_outputs(exported_plugins + exports) - transitive_compile_time_jars = depset( - order = "preorder", - direct = [compile_jar] if compile_jar else [], - transitive = [dep.transitive_compile_time_jars for dep in concatenated_deps.exports_deps], - ) - java_outputs = [_JavaOutputInfo( - class_jar = output_jar, - compile_jar = compile_jar, - ijar = compile_jar, # deprecated - compile_jdeps = compile_jdeps, - generated_class_jar = generated_class_jar, - generated_source_jar = generated_source_jar, - native_headers_jar = native_headers_jar, - manifest_proto = manifest_proto, - jdeps = jdeps, - source_jars = depset(source_jars), - source_jar = source_jar, # deprecated - )] - result = { - "transitive_compile_time_jars": transitive_compile_time_jars, - "compile_jars": depset( - order = "preorder", - direct = [compile_jar] if compile_jar else [], - transitive = [dep.compile_jars for dep in exports], - ), - "full_compile_jars": depset( - order = "preorder", - direct = [output_jar], - transitive = [ - dep.full_compile_jars - for dep in exports - ], - ), - "source_jars": source_jars, - "runtime_output_jars": [output_jar], - "plugins": plugin_info.plugins, - "api_generating_plugins": plugin_info.api_generating_plugins, - "java_outputs": java_outputs, - # deprecated - "outputs": _JavaRuleOutputJarsInfo( - jars = java_outputs, - jdeps = jdeps, - native_headers = native_headers_jar, - ), - "annotation_processing": _JavaGenJarsInfo( - enabled = False, - class_jar = generated_class_jar, - source_jar = generated_source_jar, - transitive_class_jars = depset( - direct = [generated_class_jar] if generated_class_jar else [], - transitive = [ - dep.annotation_processing.transitive_class_jars - for dep in concatenated_deps.deps_exports - if dep.annotation_processing - ], - ), - transitive_source_jars = depset( - direct = [generated_source_jar] if generated_source_jar else [], - transitive = [ - dep.annotation_processing.transitive_source_jars - for dep in concatenated_deps.deps_exports - if dep.annotation_processing - ], - ), - processor_classnames = [], - processor_classpath = depset(), - ), - "_transitive_full_compile_time_jars": depset( - order = "preorder", - direct = [output_jar], - transitive = [dep._transitive_full_compile_time_jars for dep in concatenated_deps.exports_deps], - ), - "_compile_time_java_dependencies": depset( - order = "preorder", - transitive = [dep._compile_time_java_dependencies for dep in exports] + - ([depset([compile_jdeps])] if compile_jdeps else []), - ), - "_neverlink": bool(neverlink), - "compilation_info": None, - "_constraints": [], - } - - if _java_common_internal._google_legacy_api_enabled(): - transitive_cc_infos = [dep.cc_link_params_info for dep in concatenated_deps.runtimedeps_exports_deps] - transitive_cc_infos.extend(native_libraries) - cc_info = semantics.minimize_cc_info(cc_common.merge_cc_infos(cc_infos = transitive_cc_infos)) - result.update( - cc_link_params_info = cc_info, - transitive_native_libraries = cc_info.transitive_native_libraries(), - ) - else: - result.update( - transitive_native_libraries = depset( - order = "topological", - transitive = [dep.transitive_native_libraries for dep in concatenated_deps.runtimedeps_exports_deps] + - ([cc_common.merge_cc_infos(cc_infos = native_libraries).transitive_native_libraries()] if native_libraries else []), - ), - ) - return result, concatenated_deps - -def _javainfo_init( - output_jar, - compile_jar, - source_jar = None, - compile_jdeps = None, - generated_class_jar = None, - generated_source_jar = None, - native_headers_jar = None, - manifest_proto = None, - neverlink = False, - deps = [], - runtime_deps = [], - exports = [], - exported_plugins = [], - jdeps = None, - native_libraries = [], - add_exports = [], - add_opens = []): - """The JavaInfo constructor - - Args: - output_jar: (File) The jar that was created as a result of a compilation. - compile_jar: (File) A jar that is the compile-time dependency in lieu of `output_jar`. - source_jar: (File) The source jar that was used to create the output jar. Optional. - compile_jdeps: (File) jdeps information about compile time dependencies to be consumed by - JavaCompileAction. This should be a binary proto encoded using the deps.proto protobuf - included with Bazel. If available this file is typically produced by a header compiler. - Optional. - generated_class_jar: (File) A jar file containing class files compiled from sources - generated during annotation processing. Optional. - generated_source_jar: (File) The source jar that was created as a result of annotation - processing. Optional. - native_headers_jar: (File) A jar containing CC header files supporting native method - implementation (typically output of javac -h). Optional. - manifest_proto: (File) Manifest information for the rule output (if available). This should - be a binary proto encoded using the manifest.proto protobuf included with Bazel. IDEs - and other tools can use this information for more efficient processing. Optional. - neverlink: (bool) If true, only use this library for compilation and not at runtime. - deps: ([JavaInfo]) Compile time dependencies that were used to create the output jar. - runtime_deps: ([JavaInfo]) Runtime dependencies that are needed for this library. - exports: ([JavaInfo]) Libraries to make available for users of this library. - exported_plugins: ([JavaPluginInfo]) Optional. A list of exported plugins. - jdeps: (File) jdeps information for the rule output (if available). This should be a binary - proto encoded using the deps.proto protobuf included with Bazel. If available this file - is typically produced by a compiler. IDEs and other tools can use this information for - more efficient processing. Optional. - native_libraries: ([CcInfo]) Native library dependencies that are needed for this library. - add_exports: ([str]) The /s this library was given access to. - add_opens: ([str]) The /s this library was given reflective access to. - - Returns: - (dict) arguments to the JavaInfo provider constructor - """ - if add_exports or add_opens: - semantics.check_java_info_opens_exports() - - result, concatenated_deps = _javainfo_init_base( - output_jar, - compile_jar, - source_jar, - deps, - runtime_deps, - exports, - exported_plugins, - jdeps, - compile_jdeps, - native_headers_jar, - manifest_proto, - generated_class_jar, - generated_source_jar, - native_libraries, - neverlink, - ) - - if neverlink: - transitive_runtime_jars = depset() - else: - transitive_runtime_jars = depset( - order = "preorder", - direct = [output_jar], - transitive = [dep.transitive_runtime_jars for dep in concatenated_deps.exports_deps + runtime_deps], - ) - - # For backward compatibility, we use deps_exports for add_exports/add_opens - # for the JavaInfo constructor rather than runtimedeps_exports_deps (used - # by java_info_for_compilation). However, runtimedeps_exports_deps makes - # more sense, since add_exports/add_opens from runtime_deps are needed at - # runtime anyway. - # - # TODO: When this flag is removed, move this logic into _javainfo_init_base - # and remove the special case from java_info_for_compilation. - module_flags_deps = concatenated_deps.deps_exports - if _java_common_internal._incompatible_java_info_merge_runtime_module_flags(): - module_flags_deps = concatenated_deps.runtimedeps_exports_deps - - result.update( - transitive_runtime_jars = transitive_runtime_jars, - transitive_source_jars = depset( - direct = [source_jar] if source_jar else [], - # TODO(hvd): native also adds source jars from deps, but this should be unnecessary - transitive = [ - dep.transitive_source_jars - for dep in deps + runtime_deps + exports - ], - ), - module_flags_info = _create_module_flags_info( - add_exports = depset(add_exports, transitive = [ - dep.module_flags_info.add_exports - for dep in module_flags_deps - ]), - add_opens = depset(add_opens, transitive = [ - dep.module_flags_info.add_opens - for dep in module_flags_deps - ]), - ), - ) - return result - -JavaInfo, _new_javainfo = provider( - doc = "Info object encapsulating all information by java rules.", - fields = { - "transitive_runtime_jars": """(depset[File]) A transitive set of jars required on the - runtime classpath. -

Note: for binary targets (such as java_binary and java_test), this is empty, since such - targets are not intended to be dependencies of other Java targets. - """, - "transitive_compile_time_jars": """(depset[File]) The transitive set of jars required to - build the target. -

Note: for binary targets (such as java_binary and java_test), this is empty, since such - targets are not intended to be dependencies of other Java targets. - """, - "compile_jars": """(depset[File]) The jars required directly at compile time. They can be interface jars - (ijar or hjar), regular jars or both, depending on whether rule - implementations chose to create interface jars or not.""", - "full_compile_jars": """(depset[File]) The regular, full compile time Jars required by this target directly. - They can be: - - the corresponding regular Jars of the interface Jars returned by JavaInfo.compile_jars - - the regular (full) Jars returned by JavaInfo.compile_jars - - Note: JavaInfo.compile_jars can return a mix of interface Jars and - regular Jars.

Only use this method if interface Jars don't work with - your rule set(s) (e.g. some Scala targets) If you're working with - Java-only targets it's preferable to use interface Jars via - JavaInfo.compile_jars""", - "source_jars": """([File]) A list of Jars with all the source files (including those generated by - annotations) of the target itself, i.e. NOT including the sources of the - transitive dependencies.""", - "outputs": "Deprecated: use java_outputs.", - "annotation_processing": "Deprecated: Please use plugins instead.", - "runtime_output_jars": "([File]) A list of runtime Jars created by this Java/Java-like target.", - "transitive_source_jars": "(depset[File]) The Jars of all source files in the transitive closure.", - "transitive_native_libraries": """(depset[LibraryToLink]) The transitive set of CC native - libraries required by the target.""", - "cc_link_params_info": "Deprecated. Do not use. C++ libraries to be linked into Java targets.", - "module_flags_info": "(_ModuleFlagsInfo) The Java module flag configuration.", - "plugins": """(_JavaPluginDataInfo) Data about all plugins that a consuming target should - apply. - This is typically either a `java_plugin` itself or a `java_library` exporting - one or more plugins. - A `java_library` runs annotation processing with all plugins from this field - appearing in deps and `plugins` attributes.""", - "api_generating_plugins": """"(_JavaPluginDataInfo) Data about API generating plugins - defined or exported by this target. - Those annotation processors are applied to a Java target before - producing its header jars (which contain method signatures). When - no API plugins are present, header jars are generated from the - sources, reducing critical path. - The `api_generating_plugins` is a subset of `plugins`.""", - "java_outputs": "(_JavaOutputInfo) Information about outputs of this Java/Java-like target.", - "compilation_info": """(java_compilation_info) Compilation information for this - Java/Java-like target.""", - "_transitive_full_compile_time_jars": "internal API, do not use", - "_compile_time_java_dependencies": "internal API, do not use", - "_neverlink": "internal API, do not use", - "_constraints": "internal API, do not use", - "_is_binary": "internal API, do not use", - }, - init = _javainfo_init, -) - -JavaPluginDataInfo = provider( - doc = "Provider encapsulating information about a Java compatible plugin.", - fields = { - "processor_classes": "depset(str) The fully qualified classnames of entry points for the compiler", - "processor_jars": "depset(file) Deps containing an annotation processor", - "processor_data": "depset(file) Files needed during execution", - }, -) - -_EMPTY_PLUGIN_DATA = JavaPluginDataInfo( - processor_classes = depset(), - processor_jars = depset(), - processor_data = depset(), -) - -def _create_plugin_data_info(*, processor_classes, processor_jars, processor_data): - if processor_classes or processor_jars or processor_data: - return JavaPluginDataInfo( - processor_classes = processor_classes, - processor_jars = processor_jars, - processor_data = processor_data, - ) - else: - return _EMPTY_PLUGIN_DATA - -def disable_plugin_info_annotation_processing(plugin_info): - """Returns a copy of the provided JavaPluginInfo without annotation processing info - - Args: - plugin_info: (JavaPluginInfo) the instance to transform - - Returns: - (JavaPluginInfo) a new, transformed instance. - """ - return _new_javaplugininfo( - plugins = _create_plugin_data_info( - processor_classes = depset(order = "preorder"), - # Preserve the processor path, since it may contain Error Prone plugins - # which will be service-loaded by JavaBuilder. - processor_jars = plugin_info.plugins.processor_jars, - # Preserve data, which may be used by Error Prone plugins. - processor_data = plugin_info.plugins.processor_data, - ), - api_generating_plugins = _EMPTY_PLUGIN_DATA, - java_outputs = plugin_info.java_outputs, - ) - -def merge_plugin_info_without_outputs(infos): - """ Merge plugin information from a list of JavaPluginInfo or JavaInfo - - Args: - infos: ([JavaPluginInfo|JavaInfo]) list of providers to merge - - Returns: - (JavaPluginInfo) - """ - plugins = [] - api_generating_plugins = [] - for info in infos: - if _has_plugin_data(info.plugins): - plugins.append(info.plugins) - if _has_plugin_data(info.api_generating_plugins): - api_generating_plugins.append(info.api_generating_plugins) - return _new_javaplugininfo( - plugins = _merge_plugin_data(plugins), - api_generating_plugins = _merge_plugin_data(api_generating_plugins), - java_outputs = [], - ) - -def _has_plugin_data(plugin_data): - return plugin_data and ( - plugin_data.processor_classes or - plugin_data.processor_jars or - plugin_data.processor_data - ) - -def _merge_plugin_data(datas): - return _create_plugin_data_info( - processor_classes = depset(transitive = [p.processor_classes for p in datas]), - processor_jars = depset(transitive = [p.processor_jars for p in datas]), - processor_data = depset(transitive = [p.processor_data for p in datas]), - ) - -def _javaplugininfo_init( - runtime_deps, - processor_class, - data = [], - generates_api = False): - """ Constructs JavaPluginInfo - - Args: - runtime_deps: ([JavaInfo]) list of deps containing an annotation - processor. - processor_class: (String) The fully qualified class name that the Java - compiler uses as an entry point to the annotation processor. - data: (depset[File]) The files needed by this annotation - processor during execution. - generates_api: (boolean) Set to true when this annotation processor - generates API code. Such an annotation processor is applied to a - Java target before producing its header jars (which contains method - signatures). When no API plugins are present, header jars are - generated from the sources, reducing the critical path. - WARNING: This parameter affects build performance, use it only if - necessary. - - Returns: - (JavaPluginInfo) - """ - - java_infos = merge(runtime_deps) - processor_data = data if type(data) == "depset" else depset(data) - plugins = _create_plugin_data_info( - processor_classes = depset([processor_class]) if processor_class else depset(), - processor_jars = java_infos.transitive_runtime_jars, - processor_data = processor_data, - ) - return { - "plugins": plugins, - "api_generating_plugins": plugins if generates_api else _EMPTY_PLUGIN_DATA, - "java_outputs": java_infos.java_outputs, - } - -JavaPluginInfo, _new_javaplugininfo = provider( - doc = "Provider encapsulating information about Java plugins.", - fields = { - "plugins": """ - Returns data about all plugins that a consuming target should apply. - This is typically either a java_plugin itself or a - java_library exporting one or more plugins. - A java_library runs annotation processing with all - plugins from this field appearing in deps and - plugins attributes.""", - "api_generating_plugins": """ - Returns data about API generating plugins defined or exported by - this target. - Those annotation processors are applied to a Java target before - producing its header jars (which contain method signatures). When - no API plugins are present, header jars are generated from the - sources, reducing critical path. - The api_generating_plugins is a subset of - plugins.""", - "java_outputs": """ - Returns information about outputs of this Java/Java-like target. - """, - }, - init = _javaplugininfo_init, -) diff --git a/src/main/starlark/builtins_bzl/common/java/java_package_configuration.bzl b/src/main/starlark/builtins_bzl/common/java/java_package_configuration.bzl deleted file mode 100644 index 7a7e5a09e56a5d..00000000000000 --- a/src/main/starlark/builtins_bzl/common/java/java_package_configuration.bzl +++ /dev/null @@ -1,124 +0,0 @@ -# Copyright 2023 The Bazel Authors. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Implementation for the java_package_configuration rule""" - -load(":common/java/boot_class_path_info.bzl", "BootClassPathInfo") -load(":common/java/java_helper.bzl", "helper") - -_java_common_internal = _builtins.internal.java_common_internal_do_not_use - -PackageSpecificationInfo = _builtins.toplevel.PackageSpecificationInfo - -JavaPackageConfigurationInfo = provider( - "A provider for Java per-package configuration", - fields = [ - "data", - "javac_opts", - "matches", - "package_specs", - "system", - ], -) - -def _matches(package_specs, label): - for spec in package_specs: - if spec.contains(label): - return True - return False - -def _rule_impl(ctx): - javacopts = _java_common_internal.expand_java_opts(ctx, "javacopts", tokenize = True) - javacopts_depset = helper.detokenize_javacopts(javacopts) - package_specs = [package[PackageSpecificationInfo] for package in ctx.attr.packages] - system = ctx.attr.system[BootClassPathInfo] if ctx.attr.system else None - return [ - DefaultInfo(), - JavaPackageConfigurationInfo( - data = depset(ctx.files.data), - javac_opts = javacopts_depset, - matches = lambda label: _matches(package_specs, label), - package_specs = package_specs, - system = system, - ), - ] - -java_package_configuration = rule( - implementation = _rule_impl, - doc = """ -

-Configuration to apply to a set of packages. -Configurations can be added to -java_toolchain.javacoptss. -

- -

Example:

- -
-
-
-java_package_configuration(
-    name = "my_configuration",
-    packages = [":my_packages"],
-    javacopts = ["-Werror"],
-)
-
-package_group(
-    name = "my_packages",
-    packages = [
-        "//com/my/project/...",
-        "-//com/my/project/testing/...",
-    ],
-)
-
-java_toolchain(
-    ...,
-    package_configuration = [
-        ":my_configuration",
-    ]
-)
-
-
-
- """, - attrs = { - "packages": attr.label_list( - cfg = "exec", - providers = [PackageSpecificationInfo], - doc = """ -The set of package_groups -the configuration should be applied to. - """, - ), - "javacopts": attr.string_list( - doc = """ -Java compiler flags. - """, - ), - "data": attr.label_list( - cfg = "exec", - allow_files = True, - doc = """ -The list of files needed by this configuration at runtime. - """, - ), - "system": attr.label( - providers = [BootClassPathInfo], - doc = """ -Corresponds to javac's --system flag. -""", - ), - "output_licenses": attr.license() if hasattr(attr, "license") else attr.string_list(), - }, -) diff --git a/src/main/starlark/builtins_bzl/common/java/java_runtime.bzl b/src/main/starlark/builtins_bzl/common/java/java_runtime.bzl deleted file mode 100644 index a0c22d11686470..00000000000000 --- a/src/main/starlark/builtins_bzl/common/java/java_runtime.bzl +++ /dev/null @@ -1,258 +0,0 @@ -# Copyright 2023 The Bazel Authors. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -""" -Definition of java_runtime rule and JavaRuntimeInfo provider. -""" - -load(":common/cc/cc_info.bzl", "CcInfo") -load(":common/cc/semantics.bzl", cc_semantics = "semantics") -load(":common/java/java_helper.bzl", "helper") -load(":common/paths.bzl", "paths") - -platform_common = _builtins.toplevel.platform_common -ToolchainInfo = _builtins.toplevel.platform_common.ToolchainInfo - -_java_common_internal = _builtins.internal.java_common_internal_do_not_use - -def _init_java_runtime_info(**_kwargs): - fail("instantiating JavaRuntimeInfo is a private API") - -JavaRuntimeInfo, _new_javaruntimeinfo = provider( - doc = "Information about the Java runtime used by the java rules.", - fields = { - "default_cds": "Returns the JDK default CDS archive.", - "files": "Returns the files in the Java runtime.", - "hermetic_files": "Returns the files in the Java runtime needed for hermetic deployments.", - "hermetic_static_libs": "Returns the JDK static libraries.", - "java_executable_exec_path": "Returns the execpath of the Java executable.", - "java_executable_runfiles_path": """Returns the path of the Java executable in - runfiles trees. This should only be used when one needs to access the - JVM during the execution of a binary or a test built by Bazel. In particular, - when one needs to invoke the JVM during an action, java_executable_exec_path - should be used instead.""", - "java_home": "Returns the execpath of the root of the Java installation.", - "java_home_runfiles_path": """Returns the path of the Java installation in runfiles trees. - This should only be used when one needs to access the JDK during the execution - of a binary or a test built by Bazel. In particular, when one needs the JDK - during an action, java_home should be used instead.""", - "lib_ct_sym": "Returns the lib/ct.sym file.", - "lib_modules": "Returns the lib/modules file.", - "version": "The Java feature version of the runtime. This is 0 if the version is unknown.", - }, - init = _init_java_runtime_info, -) - -def _is_main_repo(label): - return label.workspace_name == "" - -def _default_java_home(label): - if _is_main_repo(label): - return label.package - else: - return paths.get_relative(label.workspace_root, label.package) - -def _get_bin_java(ctx): - is_windows = helper.is_target_platform_windows(ctx) - return "bin/java.exe" if is_windows else "bin/java" - -def _get_runfiles_java_executable(ctx, java_home, label): - if paths.is_absolute(java_home) or _is_main_repo(label): - return paths.get_relative(java_home, _get_bin_java(ctx)) - else: - repo_runfiles_path = "" if _is_main_repo(label) else paths.get_relative("..", label.workspace_name) - return paths.get_relative(repo_runfiles_path, _get_bin_java(ctx)) - -def _is_java_binary(path): - return path.endswith("bin/java") or path.endswith("bin/java.exe") - -def _get_lib_ct_sym(srcs, explicit_lib_ct_sym): - if explicit_lib_ct_sym: - return explicit_lib_ct_sym - candidates = [src for src in srcs if src.path.endswith("/lib/ct.sym")] - if len(candidates) == 1: - return candidates[0] - else: - return None - -def _java_runtime_rule_impl(ctx): - all_files = [] # [depset[File]] - all_files.append(depset(ctx.files.srcs)) - - java_home = _default_java_home(ctx.label) - if ctx.attr.java_home: - java_home_attr = ctx.expand_make_variables("java_home", ctx.attr.java_home, {}) - if ctx.files.srcs and paths.is_absolute(java_home_attr): - fail("'java_home' with an absolute path requires 'srcs' to be empty.") - java_home = paths.get_relative(java_home, java_home_attr) - - java_binary_exec_path = paths.get_relative(java_home, _get_bin_java(ctx)) - java_binary_runfiles_path = _get_runfiles_java_executable(ctx, java_home, ctx.label) - - java = ctx.file.java - if java: - if paths.is_absolute(java_home): - fail("'java_home' with an absolute path requires 'java' to be empty.") - java_binary_exec_path = java.path - java_binary_runfiles_path = java.short_path - if not _is_java_binary(java_binary_exec_path): - fail("the path to 'java' must end in 'bin/java'.") - java_home = paths.dirname(paths.dirname(java_binary_exec_path)) - all_files.append(depset([java])) - - java_home_runfiles_path = paths.dirname(paths.dirname(java_binary_runfiles_path)) - - hermetic_inputs = depset(ctx.files.hermetic_srcs) - all_files.append(hermetic_inputs) - - lib_ct_sym = _get_lib_ct_sym(ctx.files.srcs, ctx.file.lib_ct_sym) - lib_modules = ctx.file.lib_modules - hermetic_static_libs = [dep[CcInfo] for dep in ctx.attr.hermetic_static_libs] - - # If a runtime does not set default_cds in hermetic mode, it is not fatal. - # We can skip the default CDS in the check below. - default_cds = ctx.file.default_cds - - if (hermetic_inputs or lib_modules or hermetic_static_libs) and ( - not hermetic_inputs or not lib_modules or not hermetic_static_libs - ): - fail("hermetic specified, all of java_runtime.lib_modules, java_runtime.hermetic_srcs and java_runtime.hermetic_static_libs must be specified") - - files = depset(transitive = all_files) - - java_runtime_info = _new_javaruntimeinfo( - default_cds = default_cds, - files = files, - hermetic_files = hermetic_inputs, - hermetic_static_libs = hermetic_static_libs, - java_executable_exec_path = java_binary_exec_path, - java_executable_runfiles_path = java_binary_runfiles_path, - java_home = java_home, - java_home_runfiles_path = java_home_runfiles_path, - lib_ct_sym = lib_ct_sym, - lib_modules = lib_modules, - version = ctx.attr.version, - ) - return [ - DefaultInfo( - files = files, - runfiles = ctx.runfiles(transitive_files = files), - ), - java_runtime_info, - platform_common.TemplateVariableInfo({ - "JAVA": java_binary_exec_path, - "JAVABASE": java_home, - }), - ToolchainInfo(java_runtime = java_runtime_info), - ] - -java_runtime = rule( - implementation = _java_runtime_rule_impl, - doc = """ -

-Specifies the configuration for a Java runtime. -

- -

Example:

- -
-
-
-java_runtime(
-    name = "jdk-9-ea+153",
-    srcs = glob(["jdk9-ea+153/**"]),
-    java_home = "jdk9-ea+153",
-)
-
-
-
- """, - attrs = { - "default_cds": attr.label( - allow_single_file = True, - executable = True, - cfg = "target", - doc = """ -Default CDS archive for hermetic java_runtime. When hermetic -is enabled for a java_binary target the java_runtime -default CDS is packaged in the hermetic deploy JAR. - """, - ), - "hermetic_srcs": attr.label_list( - allow_files = True, - doc = """ -Files in the runtime needed for hermetic deployments. - """, - ), - "hermetic_static_libs": attr.label_list( - providers = [CcInfo], - doc = """ -The libraries that are statically linked with the launcher for hermetic deployments - """, - ), - "java": attr.label( - allow_single_file = True, - executable = True, - cfg = "target", - doc = """ -The path to the java executable. - """, - ), - "java_home": attr.string( - doc = """ -The path to the root of the runtime. -Subject to "Make" variable substitution. -If this path is absolute, the rule denotes a non-hermetic Java runtime with a well-known -path. In that case, the srcs and java attributes must be empty. - """, - ), - "lib_ct_sym": attr.label( - allow_single_file = True, - doc = """ -The lib/ct.sym file needed for compilation with --release. If not specified and -there is exactly one file in srcs whose path ends with -/lib/ct.sym, that file is used. - """, - ), - "lib_modules": attr.label( - allow_single_file = True, - executable = True, - cfg = "target", - doc = """ -The lib/modules file needed for hermetic deployments. - """, - ), - "srcs": attr.label_list( - allow_files = True, - doc = """ -All files in the runtime. - """, - ), - "version": attr.int( - doc = """ -The feature version of the Java runtime. I.e., the integer returned by -Runtime.version().feature(). - """, - ), - "output_licenses": attr.license() if hasattr(attr, "license") else attr.string_list(), - "_windows_constraints": attr.label_list( - default = ["@" + paths.join(cc_semantics.get_platforms_root(), "os:windows")], - ), - }, - fragments = ["java"], - provides = [ - JavaRuntimeInfo, - platform_common.TemplateVariableInfo, - ], -) diff --git a/src/main/starlark/builtins_bzl/common/java/java_semantics.bzl b/src/main/starlark/builtins_bzl/common/java/java_semantics.bzl deleted file mode 100644 index 73c10ef1b5c298..00000000000000 --- a/src/main/starlark/builtins_bzl/common/java/java_semantics.bzl +++ /dev/null @@ -1,111 +0,0 @@ -# Copyright 2021 The Bazel Authors. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -""" -Java Semantics -""" - -def _postprocess(ctx, base_info): - return base_info.java_info - -def _find_java_toolchain(ctx): - return ctx.toolchains["@bazel_tools//tools/jdk:toolchain_type"].java - -def _find_java_runtime_toolchain(ctx): - return ctx.toolchains["@bazel_tools//tools/jdk:runtime_toolchain_type"].java_runtime - -def _get_default_resource_path(path, segment_extractor): - # Look for src/.../resources to match Maven repository structure. - segments = path.split("/") - for idx in range(0, len(segments) - 2): - if segments[idx] == "src" and segments[idx + 2] == "resources": - return "/".join(segments[idx + 3:]) - java_segments = segment_extractor(path) - return "/".join(java_segments) if java_segments != None else path - -def _compatible_javac_options(*_args): - return depset() - -def _check_java_info_opens_exports(): - pass - -def _minimize_cc_info(cc_info): - return cc_info - -_DOCS = struct( - ATTRS = { - "resources": """ -

-If resources are specified, they will be bundled in the jar along with the usual -.class files produced by compilation. The location of the resources inside -of the jar file is determined by the project structure. Bazel first looks for Maven's -standard directory layout, -(a "src" directory followed by a "resources" directory grandchild). If that is not -found, Bazel then looks for the topmost directory named "java" or "javatests" (so, for -example, if a resource is at <workspace root>/x/java/y/java/z, the -path of the resource will be y/java/z. This heuristic cannot be overridden, -however, the resource_strip_prefix attribute can be used to specify a -specific alternative directory for resource files. - """, - "use_testrunner": """ -Use the test runner (by default -com.google.testing.junit.runner.BazelTestRunner) class as the -main entry point for a Java program, and provide the test class -to the test runner as a value of bazel.test_suite -system property. - """, - }, -) - -semantics = struct( - JAVA_TOOLCHAIN_LABEL = "@bazel_tools//tools/jdk:current_java_toolchain", - JAVA_TOOLCHAIN_TYPE = "@bazel_tools//tools/jdk:toolchain_type", - JAVA_TOOLCHAIN = _builtins.toplevel.config_common.toolchain_type("@bazel_tools//tools/jdk:toolchain_type", mandatory = True), - find_java_toolchain = _find_java_toolchain, - JAVA_RUNTIME_TOOLCHAIN_TYPE = "@bazel_tools//tools/jdk:runtime_toolchain_type", - JAVA_RUNTIME_TOOLCHAIN = _builtins.toplevel.config_common.toolchain_type("@bazel_tools//tools/jdk:runtime_toolchain_type", mandatory = True), - find_java_runtime_toolchain = _find_java_runtime_toolchain, - JAVA_PLUGINS_FLAG_ALIAS_LABEL = "@bazel_tools//tools/jdk:java_plugins_flag_alias", - EXTRA_SRCS_TYPES = [], - ALLOWED_RULES_IN_DEPS = [ - "cc_binary", # NB: linkshared=1 - "cc_library", - "genrule", - "genproto", # TODO(bazel-team): we should filter using providers instead (starlark rule). - "java_import", - "java_library", - "java_proto_library", - "java_lite_proto_library", - "proto_library", - "sh_binary", - "sh_library", - ], - ALLOWED_RULES_IN_DEPS_WITH_WARNING = [], - LINT_PROGRESS_MESSAGE = "Running Android Lint for: %{label}", - JAVA_STUB_TEMPLATE_LABEL = "@bazel_tools//tools/jdk:java_stub_template.txt", - BUILD_INFO_TRANSLATOR_LABEL = "@bazel_tools//tools/build_defs/build_info:java_build_info", - JAVA_TEST_RUNNER_LABEL = "@bazel_tools//tools/jdk:TestRunner", - IS_BAZEL = True, - get_default_resource_path = _get_default_resource_path, - compatible_javac_options = _compatible_javac_options, - LAUNCHER_FLAG_LABEL = Label("@bazel_tools//tools/jdk:launcher_flag_alias"), - JAVA_PROTO_TOOLCHAIN = "@rules_java//java/proto:toolchain_type", - JAVA_LITE_PROTO_TOOLCHAIN = "@rules_java//java/proto:lite_toolchain_type", - PROGUARD_ALLOWLISTER_LABEL = "@bazel_tools//tools/jdk:proguard_whitelister", - check_java_info_opens_exports = _check_java_info_opens_exports, - DOCS = struct( - for_attribute = lambda name: _DOCS.ATTRS.get(name, ""), - ), - minimize_cc_info = _minimize_cc_info, -) diff --git a/src/main/starlark/builtins_bzl/common/java/java_toolchain.bzl b/src/main/starlark/builtins_bzl/common/java/java_toolchain.bzl deleted file mode 100644 index 0be3f477ea0489..00000000000000 --- a/src/main/starlark/builtins_bzl/common/java/java_toolchain.bzl +++ /dev/null @@ -1,609 +0,0 @@ -# Copyright 2023 The Bazel Authors. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -""" -Definition of java_toolchain rule and JavaToolchainInfo provider. -""" - -load(":common/java/boot_class_path_info.bzl", "BootClassPathInfo") -load(":common/java/java_helper.bzl", "helper") -load(":common/java/java_info.bzl", "JavaPluginDataInfo") -load(":common/java/java_package_configuration.bzl", "JavaPackageConfigurationInfo") -load(":common/java/java_runtime.bzl", "JavaRuntimeInfo") -load(":common/java/java_semantics.bzl", "semantics") - -_java_common_internal = _builtins.internal.java_common_internal_do_not_use -ToolchainInfo = _builtins.toplevel.platform_common.ToolchainInfo -PackageSpecificationInfo = _builtins.toplevel.PackageSpecificationInfo - -def _java_toolchain_info_init(**_kwargs): - fail("JavaToolchainInfo instantiation is a private API") - -_PRIVATE_API_DOC_STRING = "internal API, DO NOT USE!" - -JavaToolchainInfo, _new_javatoolchaininfo = provider( - doc = "Information about the JDK used by the java_* rules.", - fields = { - "bootclasspath": "(depset[File]) The Java target bootclasspath entries. Corresponds to javac's -bootclasspath flag.", - "ijar": "(FilesToRunProvider) The ijar executable.", - "jacocorunner": "(FilesToRunProvider) The jacocorunner used by the toolchain.", - "java_runtime": "(JavaRuntimeInfo) The java runtime information.", - "jvm_opt": "(depset[str]) The default options for the JVM running the java compiler and associated tools.", - "label": "(label) The toolchain label.", - "proguard_allowlister": "(FilesToRunProvider) The binary to validate proguard configuration.", - "single_jar": "(FilesToRunProvider) The SingleJar deploy jar.", - "source_version": "(str) The java source version.", - "target_version": "(str) The java target version.", - "tools": "(depset[File]) The compilation tools.", - # private - "_android_linter": _PRIVATE_API_DOC_STRING, - "_bootclasspath_info": _PRIVATE_API_DOC_STRING, - "_bytecode_optimizer": _PRIVATE_API_DOC_STRING, - "_compatible_javacopts": _PRIVATE_API_DOC_STRING, - "_deps_checker": _PRIVATE_API_DOC_STRING, - "_forcibly_disable_header_compilation": _PRIVATE_API_DOC_STRING, - "_gen_class": _PRIVATE_API_DOC_STRING, - "_header_compiler": _PRIVATE_API_DOC_STRING, - "_header_compiler_builtin_processors": _PRIVATE_API_DOC_STRING, - "_header_compiler_direct": _PRIVATE_API_DOC_STRING, - "_javabuilder": _PRIVATE_API_DOC_STRING, - "_javacopts": _PRIVATE_API_DOC_STRING, - "_javacopts_list": _PRIVATE_API_DOC_STRING, - "_javac_supports_workers": _PRIVATE_API_DOC_STRING, - "_javac_supports_multiplex_workers": _PRIVATE_API_DOC_STRING, - "_javac_supports_worker_cancellation": _PRIVATE_API_DOC_STRING, - "_javac_supports_worker_multiplex_sandboxing": _PRIVATE_API_DOC_STRING, - "_jspecify_info": _PRIVATE_API_DOC_STRING, - "_local_java_optimization_config": _PRIVATE_API_DOC_STRING, - "_one_version_tool": _PRIVATE_API_DOC_STRING, - "_one_version_allowlist": _PRIVATE_API_DOC_STRING, - "_one_version_allowlist_for_tests": _PRIVATE_API_DOC_STRING, - "_package_configuration": _PRIVATE_API_DOC_STRING, - "_reduced_classpath_incompatible_processors": _PRIVATE_API_DOC_STRING, - "_timezone_data": _PRIVATE_API_DOC_STRING, - }, - init = _java_toolchain_info_init, -) - -def _java_toolchain_impl(ctx): - javac_opts_list = _get_javac_opts(ctx) - bootclasspath_info = _get_bootclasspath_info(ctx) - java_runtime = _get_java_runtime(ctx) - if java_runtime and java_runtime.lib_ct_sym: - header_compiler_direct_data = [java_runtime.lib_ct_sym] - header_compiler_direct_jvm_opts = ["-Dturbine.ctSymPath=" + java_runtime.lib_ct_sym.path] - elif java_runtime and java_runtime.java_home: - # Turbine finds ct.sym relative to java.home. - header_compiler_direct_data = [] - header_compiler_direct_jvm_opts = ["-Djava.home=" + java_runtime.java_home] - else: - header_compiler_direct_data = [] - header_compiler_direct_jvm_opts = [] - if ctx.attr.oneversion_allowlist and ctx.attr.oneversion_whitelist: - fail("oneversion_allowlist and oneversion_whitelist are mutually exclusive") - oneversion_allowlist = ctx.file.oneversion_allowlist if ctx.file.oneversion_allowlist else ctx.file.oneversion_whitelist - java_toolchain_info = _new_javatoolchaininfo( - bootclasspath = bootclasspath_info.bootclasspath, - ijar = ctx.attr.ijar.files_to_run if ctx.attr.ijar else None, - jacocorunner = ctx.attr.jacocorunner.files_to_run if ctx.attr.jacocorunner else None, - java_runtime = java_runtime, - jvm_opt = depset(_java_common_internal.expand_java_opts(ctx, "jvm_opts", tokenize = False, exec_paths = True)), - label = ctx.label, - proguard_allowlister = ctx.attr.proguard_allowlister.files_to_run if ctx.attr.proguard_allowlister else None, - single_jar = ctx.attr.singlejar.files_to_run, - source_version = ctx.attr.source_version, - target_version = ctx.attr.target_version, - tools = depset(ctx.files.tools), - # private - _android_linter = _get_android_lint_tool(ctx), - _bootclasspath_info = bootclasspath_info, - _bytecode_optimizer = _get_tool_from_executable(ctx, "_bytecode_optimizer"), - _compatible_javacopts = _get_compatible_javacopts(ctx), - _deps_checker = ctx.file.deps_checker, - _forcibly_disable_header_compilation = ctx.attr.forcibly_disable_header_compilation, - _gen_class = ctx.file.genclass, - _header_compiler = _get_tool_from_ctx(ctx, "header_compiler", "turbine_data", "turbine_jvm_opts"), - _header_compiler_builtin_processors = depset(ctx.attr.header_compiler_builtin_processors), - _header_compiler_direct = _get_tool_from_executable( - ctx, - "header_compiler_direct", - data = header_compiler_direct_data, - jvm_opts = header_compiler_direct_jvm_opts, - ), - _javabuilder = _get_tool_from_ctx(ctx, "javabuilder", "javabuilder_data", "javabuilder_jvm_opts"), - _javacopts = helper.detokenize_javacopts(javac_opts_list), - _javacopts_list = javac_opts_list, - _javac_supports_workers = ctx.attr.javac_supports_workers, - _javac_supports_multiplex_workers = ctx.attr.javac_supports_multiplex_workers, - _javac_supports_worker_cancellation = ctx.attr.javac_supports_worker_cancellation, - _javac_supports_worker_multiplex_sandboxing = ctx.attr.javac_supports_worker_multiplex_sandboxing, - _jspecify_info = _get_jspecify_info(ctx), - _local_java_optimization_config = ctx.files._local_java_optimization_configuration, - _one_version_tool = ctx.attr.oneversion.files_to_run if ctx.attr.oneversion else None, - _one_version_allowlist = oneversion_allowlist, - _one_version_allowlist_for_tests = ctx.file.oneversion_allowlist_for_tests, - _package_configuration = [dep[JavaPackageConfigurationInfo] for dep in ctx.attr.package_configuration], - _reduced_classpath_incompatible_processors = depset(ctx.attr.reduced_classpath_incompatible_processors, order = "preorder"), - _timezone_data = ctx.file.timezone_data, - ) - toolchain_info = ToolchainInfo(java = java_toolchain_info) - return [java_toolchain_info, toolchain_info, DefaultInfo()] - -def _get_bootclasspath_info(ctx): - bootclasspath_infos = [dep[BootClassPathInfo] for dep in ctx.attr.bootclasspath if BootClassPathInfo in dep] - if bootclasspath_infos: - if len(bootclasspath_infos) != 1: - fail("in attribute 'bootclasspath': expected exactly one entry with a BootClassPathInfo provider") - else: - return bootclasspath_infos[0] - else: - return BootClassPathInfo(bootclasspath = ctx.files.bootclasspath) - -def _get_java_runtime(ctx): - if not ctx.attr.java_runtime: - return None - return ctx.attr.java_runtime[ToolchainInfo].java_runtime - -def _get_javac_opts(ctx): - opts = [] - if ctx.attr.source_version: - opts.extend(["-source", ctx.attr.source_version]) - if ctx.attr.target_version: - opts.extend(["-target", ctx.attr.target_version]) - if ctx.attr.xlint: - opts.append("-Xlint:" + ",".join(ctx.attr.xlint)) - opts.extend(_java_common_internal.expand_java_opts(ctx, "misc", tokenize = True)) - opts.extend(_java_common_internal.expand_java_opts(ctx, "javacopts", tokenize = True)) - return opts - -def _get_android_lint_tool(ctx): - if not ctx.attr.android_lint_runner: - return None - files_to_run = ctx.attr.android_lint_runner.files_to_run - if not files_to_run or not files_to_run.executable: - fail(ctx.attr.android_lint_runner.label, "does not refer to a valid executable target") - return struct( - tool = files_to_run, - data = depset(ctx.files.android_lint_data), - jvm_opts = depset([ctx.expand_location(opt, ctx.attr.android_lint_data) for opt in ctx.attr.android_lint_jvm_opts]), - lint_opts = [ctx.expand_location(opt, ctx.attr.android_lint_data) for opt in ctx.attr.android_lint_opts], - package_config = [dep[JavaPackageConfigurationInfo] for dep in ctx.attr.android_lint_package_configuration], - ) - -def _get_tool_from_ctx(ctx, tool_attr, data_attr, opts_attr): - dep = getattr(ctx.attr, tool_attr) - if not dep: - return None - files_to_run = dep.files_to_run - if not files_to_run or not files_to_run.executable: - fail(dep.label, "does not refer to a valid executable target") - data = getattr(ctx.attr, data_attr) - return struct( - tool = files_to_run, - data = depset(getattr(ctx.files, data_attr)), - jvm_opts = depset([ctx.expand_location(opt, data) for opt in getattr(ctx.attr, opts_attr)]), - ) - -def _get_tool_from_executable(ctx, attr_name, data = [], jvm_opts = []): - dep = getattr(ctx.attr, attr_name) - if not dep: - return None - files_to_run = dep.files_to_run - if not files_to_run or not files_to_run.executable: - fail(dep.label, "does not refer to a valid executable target") - return struct(tool = files_to_run, data = depset(data), jvm_opts = depset(jvm_opts)) - -def _get_compatible_javacopts(ctx): - result = {} - for key, opt_list in ctx.attr.compatible_javacopts.items(): - result[key] = helper.detokenize_javacopts([token for opt in opt_list for token in ctx.tokenize(opt)]) - return result - -def _get_jspecify_info(ctx): - if not ctx.attr.jspecify_processor_class: - return None - stubs = ctx.files.jspecify_stubs - javacopts = [] - javacopts.extend(ctx.attr.jspecify_javacopts) - if stubs: - javacopts.append("-Astubs=" + ":".join([file.path for file in stubs])) - return struct( - processor = JavaPluginDataInfo( - processor_classes = depset([ctx.attr.jspecify_processor_class]), - processor_jars = depset([ctx.file.jspecify_processor]), - processor_data = depset(stubs), - ), - implicit_deps = depset([ctx.file.jspecify_implicit_deps]), - javacopts = javacopts, - packages = [target[PackageSpecificationInfo] for target in ctx.attr.jspecify_packages], - ) - -def _extract_singleton_list_value(dict, key): - if key in dict and type(dict[key]) == type([]): - list = dict[key] - if len(list) > 1: - fail("expected a single value for:", key, "got: ", list) - elif len(list) == 1: - dict[key] = dict[key][0] - else: - dict[key] = None - -_LEGACY_ANY_TYPE_ATTRS = [ - "genclass", - "deps_checker", - "header_compiler", - "header_compiler_direct", - "ijar", - "javabuilder", - "singlejar", -] - -def _java_toolchain_initializer(**kwargs): - # these attributes are defined as executable `label_list`s in native but are - # expected to be singleton values. Since this is not supported in Starlark, - # we just inline the value from the list (if present) before invoking the - # rule. - for attr in _LEGACY_ANY_TYPE_ATTRS: - _extract_singleton_list_value(kwargs, attr) - - return kwargs - -java_toolchain = rule( - implementation = _java_toolchain_impl, - initializer = _java_toolchain_initializer, - doc = """ -

-Specifies the configuration for the Java compiler. Which toolchain to be used can be changed through -the --java_toolchain argument. Normally you should not write those kind of rules unless you want to -tune your Java compiler. -

- -

Examples

- -

A simple example would be: -

- -
-
-
-java_toolchain(
-    name = "toolchain",
-    source_version = "7",
-    target_version = "7",
-    bootclasspath = ["//tools/jdk:bootclasspath"],
-    xlint = [ "classfile", "divzero", "empty", "options", "path" ],
-    javacopts = [ "-g" ],
-    javabuilder = ":JavaBuilder_deploy.jar",
-)
-
-
- """, - attrs = { - "android_lint_data": attr.label_list( - cfg = "exec", - allow_files = True, - doc = """ -Labels of tools available for label-expansion in android_lint_jvm_opts. - """, - ), - "android_lint_opts": attr.string_list( - default = [], - doc = """ -The list of Android Lint arguments. - """, - ), - "android_lint_jvm_opts": attr.string_list( - default = [], - doc = """ -The list of arguments for the JVM when invoking Android Lint. - """, - ), - "android_lint_package_configuration": attr.label_list( - cfg = "exec", - providers = [JavaPackageConfigurationInfo], - allow_files = True, - doc = """ -Android Lint Configuration that should be applied to the specified package groups. - """, - ), - "android_lint_runner": attr.label( - cfg = "exec", - executable = True, - allow_single_file = True, - doc = """ -Label of the Android Lint runner, if any. - """, - ), - "bootclasspath": attr.label_list( - default = [], - allow_files = True, - doc = """ -The Java target bootclasspath entries. Corresponds to javac's -bootclasspath flag. - """, - ), - "compatible_javacopts": attr.string_list_dict( - doc = """Internal API, do not use!""", - ), - "deps_checker": attr.label( - allow_single_file = True, - cfg = "exec", - executable = True, - doc = """ -Label of the ImportDepsChecker deploy jar. - """, - ), - "forcibly_disable_header_compilation": attr.bool( - default = False, - doc = """ -Overrides --java_header_compilation to disable header compilation on platforms that do not -support it, e.g. JDK 7 Bazel. - """, - ), - "genclass": attr.label( - allow_single_file = True, - cfg = "exec", - executable = True, - doc = """ -Label of the GenClass deploy jar. - """, - ), - "header_compiler": attr.label( - allow_single_file = True, - cfg = "exec", - executable = True, - doc = """ -Label of the header compiler. Required if --java_header_compilation is enabled. - """, - ), - "header_compiler_direct": attr.label( - allow_single_file = True, - cfg = "exec", - executable = True, - doc = """ -Optional label of the header compiler to use for direct classpath actions that do not -include any API-generating annotation processors. - -

This tool does not support annotation processing. - """, - ), - "header_compiler_builtin_processors": attr.string_list( - doc = """Internal API, do not use!""", - ), - "ijar": attr.label( - cfg = "exec", - allow_files = True, - executable = True, - doc = """ -Label of the ijar executable. - """, - ), - "jacocorunner": attr.label( - cfg = "exec", - allow_single_file = True, - executable = True, - doc = """ -Label of the JacocoCoverageRunner deploy jar. - """, - ), - "javabuilder": attr.label( - cfg = "exec", - allow_single_file = True, - executable = True, - doc = """ -Label of the JavaBuilder deploy jar. - """, - ), - "javabuilder_data": attr.label_list( - cfg = "exec", - allow_files = True, - doc = """ -Labels of data available for label-expansion in javabuilder_jvm_opts. - """, - ), - "javabuilder_jvm_opts": attr.string_list( - doc = """ -The list of arguments for the JVM when invoking JavaBuilder. - """, - ), - "java_runtime": attr.label( - cfg = "exec", - providers = [JavaRuntimeInfo], - doc = """ -The java_runtime to use with this toolchain. It defaults to java_runtime -in execution configuration. - """, - ), - "javac_supports_workers": attr.bool( - default = True, - doc = """ -True if JavaBuilder supports running as a persistent worker, false if it doesn't. - """, - ), - "javac_supports_multiplex_workers": attr.bool( - default = True, - doc = """ -True if JavaBuilder supports running as a multiplex persistent worker, false if it doesn't. - """, - ), - "javac_supports_worker_cancellation": attr.bool( - default = True, - doc = """ -True if JavaBuilder supports cancellation of persistent workers, false if it doesn't. - """, - ), - "javac_supports_worker_multiplex_sandboxing": attr.bool( - default = False, - doc = """ -True if JavaBuilder supports running as a multiplex persistent worker with sandboxing, false if it doesn't. - """, - ), - "javacopts": attr.string_list( - default = [], - doc = """ -The list of extra arguments for the Java compiler. Please refer to the Java compiler -documentation for the extensive list of possible Java compiler flags. - """, - ), - "jspecify_implicit_deps": attr.label( - cfg = "exec", - allow_single_file = True, - executable = True, - doc = """Experimental, do not use!""", - ), - "jspecify_javacopts": attr.string_list( - doc = """Experimental, do not use!""", - ), - "jspecify_packages": attr.label_list( - cfg = "exec", - allow_files = True, - providers = [PackageSpecificationInfo], - doc = """Experimental, do not use!""", - ), - "jspecify_processor": attr.label( - cfg = "exec", - allow_single_file = True, - executable = True, - doc = """Experimental, do not use!""", - ), - "jspecify_processor_class": attr.string( - doc = """Experimental, do not use!""", - ), - "jspecify_stubs": attr.label_list( - cfg = "exec", - allow_files = True, - doc = """Experimental, do not use!""", - ), - "jvm_opts": attr.string_list( - default = [], - doc = """ -The list of arguments for the JVM when invoking the Java compiler. Please refer to the Java -virtual machine documentation for the extensive list of possible flags for this option. - """, - ), - "misc": attr.string_list( - default = [], - doc = """Deprecated: use javacopts instead""", - ), - "oneversion": attr.label( - cfg = "exec", - allow_files = True, - executable = True, - doc = """ -Label of the one-version enforcement binary. - """, - ), - "oneversion_whitelist": attr.label( - allow_single_file = True, - doc = """Deprecated: use oneversion_allowlist instead""", - ), - "oneversion_allowlist": attr.label( - allow_single_file = True, - doc = """ -Label of the one-version allowlist. - """, - ), - "oneversion_allowlist_for_tests": attr.label( - allow_single_file = True, - doc = """ -Label of the one-version allowlist for tests. - """, - ), - "package_configuration": attr.label_list( - cfg = "target", - providers = [JavaPackageConfigurationInfo], - doc = """ -Configuration that should be applied to the specified package groups. - """, - ), - "proguard_allowlister": attr.label( - cfg = "exec", - executable = True, - allow_files = True, - default = semantics.PROGUARD_ALLOWLISTER_LABEL, - doc = """ -Label of the Proguard allowlister. - """, - ), - "reduced_classpath_incompatible_processors": attr.string_list( - doc = """Internal API, do not use!""", - ), - "singlejar": attr.label( - cfg = "exec", - allow_files = True, - executable = True, - doc = """ -Label of the SingleJar deploy jar. - """, - ), - "source_version": attr.string( - doc = """ -The Java source version (e.g., '6' or '7'). It specifies which set of code structures -are allowed in the Java source code. - """, - ), - "target_version": attr.string( - doc = """ -The Java target version (e.g., '6' or '7'). It specifies for which Java runtime the class -should be build. - """, - ), - "timezone_data": attr.label( - cfg = "exec", - allow_single_file = True, - doc = """ -Label of a resource jar containing timezone data. If set, the timezone data is added as an -implicitly runtime dependency of all java_binary rules. - """, - ), - "tools": attr.label_list( - cfg = "exec", - allow_files = True, - doc = """ -Labels of tools available for label-expansion in jvm_opts. - """, - ), - "turbine_data": attr.label_list( - cfg = "exec", - allow_files = True, - doc = """ -Labels of data available for label-expansion in turbine_jvm_opts. - """, - ), - "turbine_jvm_opts": attr.string_list( - doc = """ -The list of arguments for the JVM when invoking turbine. - """, - ), - "xlint": attr.string_list( - default = [], - doc = """ -The list of warning to add or removes from default list. Precedes it with a dash to -removes it. Please see the Javac documentation on the -Xlint options for more information. - """, - ), - "licenses": attr.license() if hasattr(attr, "license") else attr.string_list(), - "_bytecode_optimizer": attr.label( - cfg = "exec", - executable = True, - default = configuration_field(fragment = "java", name = "java_toolchain_bytecode_optimizer"), - ), - "_local_java_optimization_configuration": attr.label( - cfg = "exec", - default = configuration_field(fragment = "java", name = "local_java_optimization_configuration"), - allow_files = True, - ), - "_legacy_any_type_attrs": attr.string_list(default = _LEGACY_ANY_TYPE_ATTRS), - }, - fragments = ["java"], -) diff --git a/src/main/starlark/builtins_bzl/common/java/message_bundle_info.bzl b/src/main/starlark/builtins_bzl/common/java/message_bundle_info.bzl deleted file mode 100644 index 49948fa42d57ec..00000000000000 --- a/src/main/starlark/builtins_bzl/common/java/message_bundle_info.bzl +++ /dev/null @@ -1,24 +0,0 @@ -# Copyright 2023 The Bazel Authors. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -""" -Definition of MessageBundleInfo provider. -""" - -MessageBundleInfo = provider( - doc = "Marks configured targets that are able to supply message bundles to their dependents.", - fields = { - "messages": "Sequence of message bundles", - }, -) diff --git a/src/test/java/com/google/devtools/build/lib/analysis/starlark/StarlarkSubruleTest.java b/src/test/java/com/google/devtools/build/lib/analysis/starlark/StarlarkSubruleTest.java index 3bc78375906d12..fc02fc6dc45db8 100644 --- a/src/test/java/com/google/devtools/build/lib/analysis/starlark/StarlarkSubruleTest.java +++ b/src/test/java/com/google/devtools/build/lib/analysis/starlark/StarlarkSubruleTest.java @@ -1319,9 +1319,7 @@ public void testSubruleToolchains_requestedToolchainIsResolved_inRule() throws E assertThat(toolchainInfo).isNotNull(); assertThat(toolchainInfo.getValue("java", StarlarkInfo.class).getProvider().getKey()) - .isAnyOf( - JavaToolchainProvider.PROVIDER.getKey(), - JavaToolchainProvider.LEGACY_BUILTINS_PROVIDER.getKey()); + .isEqualTo(JavaToolchainProvider.PROVIDER.getKey()); } @Test @@ -1363,9 +1361,7 @@ public void testSubruleToolchains_requstedToolchainIsResolved_inAspect() throws assertThat(toolchainInfo).isNotNull(); assertThat(toolchainInfo.getValue("java", StarlarkInfo.class).getProvider().getKey()) - .isAnyOf( - JavaToolchainProvider.PROVIDER.getKey(), - JavaToolchainProvider.LEGACY_BUILTINS_PROVIDER.getKey()); + .isEqualTo(JavaToolchainProvider.PROVIDER.getKey()); } @Test diff --git a/src/test/java/com/google/devtools/build/lib/rules/java/JavaInfoCodecTest.java b/src/test/java/com/google/devtools/build/lib/rules/java/JavaInfoCodecTest.java index 1e641394be9c6e..5a64f5ebaf1369 100644 --- a/src/test/java/com/google/devtools/build/lib/rules/java/JavaInfoCodecTest.java +++ b/src/test/java/com/google/devtools/build/lib/rules/java/JavaInfoCodecTest.java @@ -19,7 +19,6 @@ import com.google.devtools.build.lib.analysis.config.BuildOptions.MapBackedChecksumCache; import com.google.devtools.build.lib.analysis.config.BuildOptions.OptionsChecksumCache; import com.google.devtools.build.lib.analysis.util.BuildViewTestCase; -import com.google.devtools.build.lib.rules.java.JavaInfo.BuiltinsJavaInfo; import com.google.devtools.build.lib.skyframe.serialization.testutils.Dumper; import com.google.devtools.build.lib.skyframe.serialization.testutils.SerializationDepsUtils; import com.google.devtools.build.lib.skyframe.serialization.testutils.SerializationTester; @@ -40,18 +39,6 @@ public void emptyJavaInfo_canBeSerializedAndDeserialized() throws Exception { .runTests(); } - @Test - public void emptyBuiltinJavaInfo_canBeSerializedAndDeserialized() throws Exception { - new SerializationTester(JavaInfo.EMPTY_BUILTINS_JAVA_INFO_FOR_TESTING) - .makeMemoizingAndAllowFutureBlocking(/* allowFutureBlocking= */ true) - .setVerificationFunction( - (in, out) -> { - assertThat(in).isEqualTo(out); - assertThat(out.getClass()).isEqualTo(BuiltinsJavaInfo.class); - }) - .runTests(); - } - @Test public void javaInfo_canBeSerializedAndDeserialized() throws Exception { scratch.file( diff --git a/src/test/java/com/google/devtools/build/lib/rules/java/JavaInfoStarlarkApiTest.java b/src/test/java/com/google/devtools/build/lib/rules/java/JavaInfoStarlarkApiTest.java index 5b0ef546ca65b5..e2a533e8b64434 100644 --- a/src/test/java/com/google/devtools/build/lib/rules/java/JavaInfoStarlarkApiTest.java +++ b/src/test/java/com/google/devtools/build/lib/rules/java/JavaInfoStarlarkApiTest.java @@ -1348,9 +1348,7 @@ public void translateStarlarkJavaInfo_minimal() throws Exception { assertThat(javaInfo.getCompilationInfoProvider()).isNull(); assertThat(javaInfo.getJavaModuleFlagsInfo()).isEqualTo(JavaModuleFlagsProvider.EMPTY); assertThat(javaInfo.getJavaPluginInfo()) - .isAnyOf( - JavaPluginInfo.empty(JavaPluginInfo.LEGACY_BUILTINS_PROVIDER), - JavaPluginInfo.empty(JavaPluginInfo.PROVIDER)); + .isEqualTo(JavaPluginInfo.empty(JavaPluginInfo.PROVIDER)); } @Test diff --git a/src/test/java/com/google/devtools/build/lib/rules/java/JavaPluginsFlagAliasTest.java b/src/test/java/com/google/devtools/build/lib/rules/java/JavaPluginsFlagAliasTest.java index 375327a12488d2..b0c8fd9d12eb76 100644 --- a/src/test/java/com/google/devtools/build/lib/rules/java/JavaPluginsFlagAliasTest.java +++ b/src/test/java/com/google/devtools/build/lib/rules/java/JavaPluginsFlagAliasTest.java @@ -45,10 +45,7 @@ public void javaPluginFlagAlias_noFlagSet() throws Exception { ConfiguredTarget target = getConfiguredTarget(TestConstants.TOOLS_REPOSITORY + "//tools/jdk:java_plugins_flag_alias"); - assertThat(JavaPluginInfo.get(target)) - .isAnyOf( - JavaPluginInfo.empty(JavaPluginInfo.PROVIDER), - JavaPluginInfo.empty(JavaPluginInfo.LEGACY_BUILTINS_PROVIDER)); + assertThat(JavaPluginInfo.get(target)).isEqualTo(JavaPluginInfo.empty(JavaPluginInfo.PROVIDER)); } /** Tests that a single plugin passed by a flag is returned by java_plugins_flag_alias. */