From 36d2e2b5e2396ba0ec5ab789b93b655e901c1215 Mon Sep 17 00:00:00 2001 From: Googler Date: Tue, 5 Nov 2024 11:58:48 +0100 Subject: [PATCH 01/15] Update rules_java v8.3.0 Closes #24143. PiperOrigin-RevId: 693275804 Change-Id: I052d7472beebafb1ca6c021ac4aafceb6b2aa6b7 (cherry picked from commit 8ce16617150c0db24c492567b18d537f30f56732) --- MODULE.bazel | 2 +- src/MODULE.tools | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/MODULE.bazel b/MODULE.bazel index e2dfea6d1d2d3b..039dbf258e7efc 100644 --- a/MODULE.bazel +++ b/MODULE.bazel @@ -25,7 +25,7 @@ bazel_dep(name = "zstd-jni", version = "1.5.2-3.bcr.1") bazel_dep(name = "blake3", version = "1.5.1.bcr.1") bazel_dep(name = "zlib", version = "1.3.1.bcr.3") bazel_dep(name = "rules_cc", version = "0.0.16") -bazel_dep(name = "rules_java", version = "8.3.2") +bazel_dep(name = "rules_java", version = "8.3.0") bazel_dep(name = "rules_graalvm", version = "0.11.1") bazel_dep(name = "rules_proto", version = "7.0.2") bazel_dep(name = "rules_jvm_external", version = "6.0") diff --git a/src/MODULE.tools b/src/MODULE.tools index fbb33b41eff0af..7fa7b912544341 100644 --- a/src/MODULE.tools +++ b/src/MODULE.tools @@ -39,7 +39,7 @@ use_repo(buildozer_binary, "buildozer_binary") # Dependencies used to auto-load removed symbols and rules from Bazel (due to Starlarkification) # See also: --incompatible_autoload_externally, AutoloadSymbols bazel_dep(name = "protobuf", version = "29.0-rc3", repo_name = "com_google_protobuf") -bazel_dep(name = "rules_java", version = "8.3.2") +bazel_dep(name = "rules_java", version = "8.3.0") bazel_dep(name = "rules_cc", version = "0.0.16") bazel_dep(name = "rules_python", version = "0.40.0") bazel_dep(name = "rules_shell", version = "0.2.0") From 966f05a8e618314d24aada37ccc2f2b5e6d76d9d Mon Sep 17 00:00:00 2001 From: Googler Date: Mon, 11 Nov 2024 05:11:56 -0800 Subject: [PATCH 02/15] Prepare for moving the java providers out of builtins PiperOrigin-RevId: 695293041 Change-Id: I06c293ee1c8ef119d37c3c2188763914041d55fd (cherry picked from commit da1aba957d71153ec6904ef872b4b8ffd33488fe) --- .../rules/android/AndroidStarlarkCommon.java | 5 +- .../lib/rules/java/BootClassPathInfo.java | 36 ++++- .../build/lib/rules/java/JavaInfo.java | 143 +++++++++++++++--- .../build/lib/rules/java/JavaPluginInfo.java | 99 +++++++++--- .../rules/java/JavaPluginsFlagAliasRule.java | 24 ++- .../build/lib/rules/java/JavaRuleClasses.java | 10 -- .../build/lib/rules/java/JavaRuntimeInfo.java | 38 ++++- .../lib/rules/java/JavaStarlarkCommon.java | 16 +- .../lib/rules/java/JavaTargetAttributes.java | 2 +- .../lib/rules/java/JavaToolchainProvider.java | 42 ++++- .../lib/analysis/AutoExecGroupsTest.java | 4 +- .../starlark/StarlarkSubruleTest.java | 8 +- .../android/AndroidStarlarkCommonTest.java | 4 +- .../lib/rules/java/JavaInfoCodecTest.java | 2 +- .../rules/java/JavaInfoStarlarkApiTest.java | 21 ++- .../rules/java/JavaPluginsFlagAliasTest.java | 9 +- .../build/lib/rules/java/JavaRuntimeTest.java | 2 +- .../lib/rules/java/JavaStarlarkApiTest.java | 65 ++++---- .../java/JavaImportConfiguredTargetTest.java | 2 +- .../java/JavaPluginConfiguredTargetTest.java | 21 +-- 20 files changed, 395 insertions(+), 158 deletions(-) diff --git a/src/main/java/com/google/devtools/build/lib/rules/android/AndroidStarlarkCommon.java b/src/main/java/com/google/devtools/build/lib/rules/android/AndroidStarlarkCommon.java index 7955990013ed20..33f9208795e6a6 100644 --- a/src/main/java/com/google/devtools/build/lib/rules/android/AndroidStarlarkCommon.java +++ b/src/main/java/com/google/devtools/build/lib/rules/android/AndroidStarlarkCommon.java @@ -65,14 +65,13 @@ public JavaInfo enableImplicitSourcelessDepsExportsCompatibility(Info javaInfo, ? JavaCompilationArgsProvider.ClasspathType.COMPILE_ONLY : JavaCompilationArgsProvider.ClasspathType.BOTH; JavaInfo.Builder builder = JavaInfo.Builder.create(); - JavaInfo.PROVIDER - .wrap(javaInfo) + JavaInfo.wrap(javaInfo) .compilationArgsProvider() .ifPresent( args -> builder.javaCompilationArgs( JavaCompilationArgsProvider.builder().addExports(args, type).build())); - return builder.setNeverlink(neverlink).build(); + return builder.setProvider(javaInfo.getProvider()).setNeverlink(neverlink).build(); } @Override 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 af9a0cb5ca4461..c9da2546e56995 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 @@ -13,6 +13,7 @@ // limitations under the License. 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; @@ -27,6 +28,7 @@ import com.google.devtools.build.lib.packages.StarlarkInfoWithSchema; import com.google.devtools.build.lib.packages.StarlarkProviderWrapper; import com.google.devtools.build.lib.packages.StructImpl; +import com.google.devtools.build.lib.skyframe.BzlLoadValue; import com.google.devtools.build.lib.vfs.PathFragment; import java.util.Optional; import net.starlark.java.eval.Starlark; @@ -36,6 +38,9 @@ public class BootClassPathInfo extends StarlarkInfoWrapper { /** Provider singleton constant. */ + public static final StarlarkProviderWrapper LEGACY_BUILTINS_PROVIDER = + new BuiltinsProvider(); + public static final StarlarkProviderWrapper PROVIDER = new Provider(); private static final BootClassPathInfo EMPTY = @@ -74,6 +79,17 @@ private BootClassPathInfo(StructImpl underlying) { super(underlying); } + 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 { + throw new RuleErrorException("expected BootClassPathInfo, got: " + key); + } + } + /** The jar files containing classes for system APIs, i.e. a Java <= 8 bootclasspath. */ public NestedSet bootclasspath() throws RuleErrorException { return getUnderlyingNestedSet("bootclasspath", Artifact.class); @@ -105,12 +121,24 @@ && systemInputs().isEmpty() && systemPath().isEmpty(); } - private static class Provider extends StarlarkProviderWrapper { - private Provider() { + private static class BuiltinsProvider extends Provider { + private BuiltinsProvider() { super( keyForBuiltins( - Label.parseCanonicalUnchecked("@_builtins//:common/java/boot_class_path_info.bzl")), - "BootClassPathInfo"); + Label.parseCanonicalUnchecked("@_builtins//:common/java/boot_class_path_info.bzl"))); + } + } + + private static class Provider extends StarlarkProviderWrapper { + private Provider() { + this( + keyForBuild( + Label.parseCanonicalUnchecked( + "@rules_java//java/private:boot_class_path_info.bzl"))); + } + + private Provider(BzlLoadValue.Key key) { + super(key, "BootClassPathInfo"); } @Override 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 fb2d46f3a85e8d..1116741684e20d 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 @@ -13,6 +13,7 @@ // limitations under the License. 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; @@ -29,6 +30,7 @@ import com.google.devtools.build.lib.concurrent.ThreadSafety.Immutable; import com.google.devtools.build.lib.packages.Info; import com.google.devtools.build.lib.packages.NativeInfo; +import com.google.devtools.build.lib.packages.Provider; import com.google.devtools.build.lib.packages.RuleClass.ConfiguredTargetFactory.RuleErrorException; import com.google.devtools.build.lib.packages.StarlarkProviderWrapper; import com.google.devtools.build.lib.packages.StructImpl; @@ -36,6 +38,7 @@ import com.google.devtools.build.lib.rules.cpp.LibraryToLink; import com.google.devtools.build.lib.rules.java.JavaPluginInfo.JavaPluginData; import com.google.devtools.build.lib.rules.java.JavaRuleOutputJarsProvider.JavaOutput; +import com.google.devtools.build.lib.skyframe.BzlLoadValue; import com.google.devtools.build.lib.skyframe.serialization.AsyncDeserializationContext; import com.google.devtools.build.lib.skyframe.serialization.DeferredObjectCodec; import com.google.devtools.build.lib.skyframe.serialization.DynamicCodec; @@ -63,11 +66,12 @@ /** A Starlark declared provider that encapsulates all providers that are needed by Java rules. */ @Immutable -public final class JavaInfo extends NativeInfo +public class JavaInfo extends NativeInfo implements JavaInfoApi { public static final String STARLARK_NAME = "JavaInfo"; + public static final JavaInfoProvider LEGACY_BUILTINS_PROVIDER = new BuiltinsJavaInfoProvider(); public static final JavaInfoProvider PROVIDER = new JavaInfoProvider(); // Ideally we would check if the target has a JavaInfo, but this check predates the Starlark @@ -202,7 +206,20 @@ public static T getProvider( } public static JavaInfo getJavaInfo(TransitiveInfoCollection target) throws RuleErrorException { - return target.get(JavaInfo.PROVIDER); + JavaInfo info = target.get(PROVIDER); + if (info == null) { + info = target.get(LEGACY_BUILTINS_PROVIDER); + } + return info; + } + + 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 { + return JavaInfo.PROVIDER.wrap(info); + } } private JavaInfo( @@ -481,13 +498,73 @@ public int hashCode() { providerJavaPlugin); } + private static 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; + } + } + + /** Legacy Provider class for {@link JavaInfo} objects. */ + public static 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); + } + } + /** Provider class for {@link JavaInfo} objects. */ public static class JavaInfoProvider extends StarlarkProviderWrapper implements com.google.devtools.build.lib.packages.Provider { private JavaInfoProvider() { - super( - keyForBuiltins(Label.parseCanonicalUnchecked("@_builtins//:common/java/java_info.bzl")), - STARLARK_NAME); + this( + keyForBuild( + Label.parseCanonicalUnchecked( + "@rules_java//java/private:java_info.bzl"))); + } + + public JavaInfoProvider(BzlLoadValue.Key key) { + super(key, STARLARK_NAME); } @Override @@ -496,7 +573,7 @@ public JavaInfo wrap(Info info) throws RuleErrorException { return javaInfo; } else if (info instanceof StructImpl) { try { - return new JavaInfo((StructImpl) info); + return makeNewInstance((StructImpl) info); } catch (EvalException | TypeException e) { throw new RuleErrorException(e); } @@ -504,6 +581,11 @@ public JavaInfo wrap(Info info) throws RuleErrorException { throw new RuleErrorException("got " + Starlark.type(info) + ", wanted JavaInfo"); } + protected JavaInfo makeNewInstance(StructImpl info) + throws RuleErrorException, TypeException, EvalException { + return new JavaInfo(info); + } + @Override public boolean isExported() { return true; @@ -531,6 +613,7 @@ public static class Builder { private ImmutableList javaConstraints; private boolean neverlink; private Location creationLocation = Location.BUILTIN; + private Provider provider = PROVIDER; private Builder() {} @@ -588,20 +671,42 @@ public Builder javaSourceJars(JavaSourceJarsProvider provider) { return this; } + @CanIgnoreReturnValue + public Builder setProvider(Provider provider) { + this.provider = provider; + return this; + } + public JavaInfo build() { - return new JavaInfo( - /* javaCcInfoProvider= */ null, - providerJavaCompilationArgs, - providerJavaCompilationInfo, - /* javaGenJarsProvider= */ null, - /* javaModuleFlagsProvider= */ null, - /* javaPluginInfo= */ null, - providerJavaRuleOutputJars, - providerJavaSourceJars, - runtimeJars, - neverlink, - javaConstraints, - creationLocation); + 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 { + return new JavaInfo( + /* javaCcInfoProvider= */ null, + providerJavaCompilationArgs, + providerJavaCompilationInfo, + /* javaGenJarsProvider= */ null, + /* javaModuleFlagsProvider= */ null, + /* javaPluginInfo= */ null, + providerJavaRuleOutputJars, + providerJavaSourceJars, + runtimeJars, + neverlink, + javaConstraints, + creationLocation); + } } } 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 70f4787bdea046..b167a007917abc 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 @@ -14,11 +14,14 @@ 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; import com.google.common.collect.ImmutableList; import com.google.devtools.build.lib.actions.Artifact; +import com.google.devtools.build.lib.analysis.ConfiguredTarget; import com.google.devtools.build.lib.cmdline.Label; import com.google.devtools.build.lib.collect.nestedset.Depset; import com.google.devtools.build.lib.collect.nestedset.NestedSet; @@ -32,6 +35,7 @@ import com.google.devtools.build.lib.packages.StructImpl; import com.google.devtools.build.lib.rules.java.JavaPluginInfo.JavaPluginData; import com.google.devtools.build.lib.rules.java.JavaRuleOutputJarsProvider.JavaOutput; +import com.google.devtools.build.lib.skyframe.BzlLoadValue; import com.google.devtools.build.lib.starlarkbuildapi.java.JavaPluginInfoApi; import java.util.ArrayList; import java.util.List; @@ -46,24 +50,68 @@ 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(); + private static final JavaPluginInfo EMPTY_BUILTIN = + new AutoValue_JavaPluginInfo( + ImmutableList.of(), JavaPluginData.empty(), JavaPluginData.empty(), true); + private static final JavaPluginInfo EMPTY = new AutoValue_JavaPluginInfo( - ImmutableList.of(), JavaPluginData.empty(), JavaPluginData.empty()); + ImmutableList.of(), JavaPluginData.empty(), JavaPluginData.empty(), false); + + public static JavaPluginInfo wrap(Info info) throws RuleErrorException { + com.google.devtools.build.lib.packages.Provider.Key key = info.getProvider().getKey(); + if (key.equals(LEGACY_BUILTINS_PROVIDER.getKey())) { + return LEGACY_BUILTINS_PROVIDER.wrap(info); + } else { + return PROVIDER.wrap(info); + } + } + + @VisibleForTesting + public static JavaPluginInfo get(ConfiguredTarget target) throws RuleErrorException { + 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); + } @Override public Provider getProvider() { - return PROVIDER; + return builtin() ? LEGACY_BUILTINS_PROVIDER : PROVIDER; + } + + /** 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"))); + } + + @Override + protected boolean isBuiltin() { + return true; + } } /** Provider class for {@link JavaPluginInfo} objects. */ public static class Provider extends StarlarkProviderWrapper implements com.google.devtools.build.lib.packages.Provider { private Provider() { - super( - keyForBuiltins(Label.parseCanonicalUnchecked("@_builtins//:common/java/java_info.bzl")), - PROVIDER_NAME); + this( + keyForBuild( + Label.parseCanonicalUnchecked( + "@rules_java//java/private:java_info.bzl"))); + } + + private Provider(BzlLoadValue.Key key) { + super(key, PROVIDER_NAME); } @Override @@ -95,7 +143,8 @@ public JavaPluginInfo wrap(Info value) throws RuleErrorException { JavaOutput.wrapSequence( Sequence.cast(info.getValue("java_outputs"), Object.class, "java_outputs")), JavaPluginData.wrap(info.getValue("plugins")), - JavaPluginData.wrap(info.getValue("api_generating_plugins"))); + JavaPluginData.wrap(info.getValue("api_generating_plugins")), + isBuiltin()); } catch (EvalException e) { throw new RuleErrorException(e); } @@ -104,6 +153,10 @@ public JavaPluginInfo wrap(Info value) throws RuleErrorException { "got element of type " + Starlark.type(value) + ", want JavaPluginInfo"); } } + + protected boolean isBuiltin() { + return false; + } } /** Information about a Java plugin, except for whether it generates API. */ @@ -187,10 +240,15 @@ public boolean isEmpty() { } public static JavaPluginInfo mergeWithoutJavaOutputs(JavaPluginInfo a, JavaPluginInfo b) { - return a.isEmpty() ? b : b.isEmpty() ? a : mergeWithoutJavaOutputs(ImmutableList.of(a, b)); + return a.isEmpty() + ? b + : b.isEmpty() + ? a + : mergeWithoutJavaOutputs(ImmutableList.of(a, b), a.builtin() && b.builtin()); } - public static JavaPluginInfo mergeWithoutJavaOutputs(Iterable providers) { + public static JavaPluginInfo mergeWithoutJavaOutputs( + Iterable providers, boolean builtin) { List plugins = new ArrayList<>(); List apiGeneratingPlugins = new ArrayList<>(); for (JavaPluginInfo provider : providers) { @@ -200,24 +258,20 @@ public static JavaPluginInfo mergeWithoutJavaOutputs(Iterable pr if (!provider.apiGeneratingPlugins().isEmpty()) { apiGeneratingPlugins.add(provider.apiGeneratingPlugins()); } + builtin = builtin && provider.builtin(); } if (plugins.isEmpty() && apiGeneratingPlugins.isEmpty()) { - return JavaPluginInfo.empty(); + return JavaPluginInfo.empty(builtin); } return new AutoValue_JavaPluginInfo( ImmutableList.of(), JavaPluginData.merge(plugins), - JavaPluginData.merge(apiGeneratingPlugins)); - } - - public static JavaPluginInfo create( - JavaPluginData javaPluginData, boolean generatesApi, ImmutableList javaOutputs) { - return new AutoValue_JavaPluginInfo( - javaOutputs, javaPluginData, generatesApi ? javaPluginData : JavaPluginData.empty()); + JavaPluginData.merge(apiGeneratingPlugins), + builtin); } - public static JavaPluginInfo empty() { - return EMPTY; + public static JavaPluginInfo empty(boolean builtin) { + return builtin ? EMPTY_BUILTIN : EMPTY; } @Override @@ -226,6 +280,8 @@ public static JavaPluginInfo empty() { @Override public abstract JavaPluginData apiGeneratingPlugins(); + protected abstract boolean builtin(); + /** Returns true if the provider has no associated data. */ public boolean isEmpty() { // apiGeneratingPlugins is a subset of plugins, so checking if plugins is empty is sufficient @@ -252,12 +308,15 @@ public boolean hasProcessors() { */ static JavaPluginInfo fromStarlarkJavaInfo(StructImpl javaInfo) throws EvalException, RuleErrorException { + boolean builtin = + javaInfo.getProvider().getKey().equals(JavaInfo.LEGACY_BUILTINS_PROVIDER.getKey()); JavaPluginData plugins = JavaPluginData.wrap(javaInfo.getValue("plugins")); JavaPluginData apiGeneratingPlugins = JavaPluginData.wrap(javaInfo.getValue("api_generating_plugins")); if (plugins.isEmpty() && apiGeneratingPlugins.isEmpty()) { - return JavaPluginInfo.empty(); + return JavaPluginInfo.empty(builtin); } - return new AutoValue_JavaPluginInfo(ImmutableList.of(), plugins, apiGeneratingPlugins); + return new AutoValue_JavaPluginInfo( + ImmutableList.of(), plugins, apiGeneratingPlugins, /* builtin= */ builtin); } } 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 2304e52666b47f..b4a31cb0a4fa08 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 @@ -16,6 +16,7 @@ import static com.google.devtools.build.lib.packages.Attribute.attr; import static com.google.devtools.build.lib.packages.BuildType.LABEL_LIST; +import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.google.devtools.build.lib.actions.ActionConflictException; import com.google.devtools.build.lib.analysis.BaseRuleClasses; @@ -49,7 +50,10 @@ public RuleClass build(RuleClass.Builder builder, RuleDefinitionEnvironment envi .add( attr(":java_plugins", LABEL_LIST) .cfg(ExecutionTransitionFactory.createFactory()) - .mandatoryProviders(JavaPluginInfo.PROVIDER.id()) + .mandatoryProvidersList( + ImmutableList.of( + ImmutableList.of(JavaPluginInfo.PROVIDER.id()), + ImmutableList.of(JavaPluginInfo.LEGACY_BUILTINS_PROVIDER.id()))) .silentRuleClassFilter() .value(JavaSemantics.JAVA_PLUGINS)) .build(); @@ -78,14 +82,22 @@ public ConfiguredTarget create(RuleContext ruleContext) return null; } - JavaPluginInfo javaPluginInfo = - JavaPluginInfo.mergeWithoutJavaOutputs( - ruleContext - .getRulePrerequisitesCollection() - .getPrerequisites(":java_plugins", JavaPluginInfo.PROVIDER)); + ImmutableList plugins = + ruleContext + .getRulePrerequisitesCollection() + .getPrerequisites(":java_plugins", JavaPluginInfo.PROVIDER); + // try builtin provider as well + ImmutableList builtinsProviderPlugins = + ruleContext + .getRulePrerequisitesCollection() + .getPrerequisites(":java_plugins", JavaPluginInfo.LEGACY_BUILTINS_PROVIDER); + JavaPluginInfo javaPluginInfo = JavaPluginInfo.mergeWithoutJavaOutputs(plugins, false); + JavaPluginInfo builtinsProviderInfo = + JavaPluginInfo.mergeWithoutJavaOutputs(builtinsProviderPlugins, true); return new RuleConfiguredTargetBuilder(ruleContext) .addStarlarkDeclaredProvider(javaPluginInfo) + .addStarlarkDeclaredProvider(builtinsProviderInfo) .addProvider(RunfilesProvider.class, RunfilesProvider.EMPTY) .build(); } diff --git a/src/main/java/com/google/devtools/build/lib/rules/java/JavaRuleClasses.java b/src/main/java/com/google/devtools/build/lib/rules/java/JavaRuleClasses.java index 37f6ee4890ed71..7059db1a11cda8 100644 --- a/src/main/java/com/google/devtools/build/lib/rules/java/JavaRuleClasses.java +++ b/src/main/java/com/google/devtools/build/lib/rules/java/JavaRuleClasses.java @@ -17,14 +17,12 @@ import static com.google.devtools.build.lib.packages.Attribute.attr; import static com.google.devtools.build.lib.packages.BuildType.LABEL; -import com.google.common.collect.ImmutableList; import com.google.devtools.build.lib.analysis.RuleDefinition; import com.google.devtools.build.lib.analysis.RuleDefinitionEnvironment; import com.google.devtools.build.lib.analysis.config.ToolchainTypeRequirement; import com.google.devtools.build.lib.analysis.platform.ToolchainInfo; import com.google.devtools.build.lib.packages.RuleClass; import com.google.devtools.build.lib.packages.RuleClass.Builder.RuleClassType; -import com.google.devtools.build.lib.packages.StarlarkProviderIdentifier; /** Common rule class definitions for Java rules. */ public class JavaRuleClasses { @@ -92,12 +90,4 @@ public Metadata getMetadata() { .build(); } } - - /** - * Meant to be an element of {@code mandatoryProvidersLists} in order to accept rules providing a - * {@link JavaInfo} through an attribute. Other providers can be included in {@code - * mandatoryProvidersLists} as well. - */ - public static final ImmutableList CONTAINS_JAVA_PROVIDER = - ImmutableList.of(StarlarkProviderIdentifier.forKey(JavaInfo.PROVIDER.getKey())); } 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 3960ad2666cbd0..890b4fc978878f 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 @@ -15,6 +15,7 @@ package com.google.devtools.build.lib.rules.java; 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; @@ -34,6 +35,7 @@ import com.google.devtools.build.lib.packages.StarlarkProviderWrapper; import com.google.devtools.build.lib.rules.cpp.CcInfo; import com.google.devtools.build.lib.rules.cpp.LibraryToLink; +import com.google.devtools.build.lib.skyframe.BzlLoadValue; import com.google.devtools.build.lib.vfs.PathFragment; import javax.annotation.Nullable; import net.starlark.java.eval.EvalException; @@ -44,6 +46,8 @@ @Immutable public final class JavaRuntimeInfo extends StarlarkInfoWrapper { + public static final StarlarkProviderWrapper LEGACY_BUILTINS_PROVIDER = + new BuiltinsProvider(); public static final StarlarkProviderWrapper PROVIDER = new Provider(); // Helper methods to access an instance of JavaRuntimeInfo. @@ -75,7 +79,7 @@ public static JavaRuntimeInfo from(RuleContext ruleContext, String attributeName private static JavaRuntimeInfo from(RuleContext ruleContext, ToolchainInfo toolchainInfo) { if (toolchainInfo != null) { try { - JavaRuntimeInfo result = PROVIDER.wrap(toolchainInfo.getValue("java_runtime", Info.class)); + JavaRuntimeInfo result = wrap(toolchainInfo.getValue("java_runtime", Info.class)); if (result != null) { return result; } @@ -92,6 +96,17 @@ private JavaRuntimeInfo(StarlarkInfo underlying) { super(underlying); } + 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 { + throw new RuleErrorException("expected JavaRuntimeInfo, got: " + key); + } + } + /** All input artifacts in the javabase. */ public NestedSet javaBaseInputs() throws RuleErrorException { return getUnderlyingNestedSet("files", Artifact.class); @@ -127,13 +142,26 @@ public int version() throws RuleErrorException { return getUnderlyingValue("version", StarlarkInt.class).toIntUnchecked(); } - private static class Provider extends StarlarkProviderWrapper { + private static class BuiltinsProvider extends Provider { - private Provider() { + private BuiltinsProvider() { super( keyForBuiltins( - Label.parseCanonicalUnchecked("@_builtins//:common/java/java_runtime.bzl")), - "JavaRuntimeInfo"); + Label.parseCanonicalUnchecked("@_builtins//:common/java/java_runtime.bzl"))); + } + } + + private static class Provider extends StarlarkProviderWrapper { + + private Provider() { + this( + keyForBuild( + Label.parseCanonicalUnchecked( + "@rules_java//java/common/rules:java_runtime.bzl"))); + } + + private Provider(BzlLoadValue.Key key) { + super(key, "JavaRuntimeInfo"); } @Override diff --git a/src/main/java/com/google/devtools/build/lib/rules/java/JavaStarlarkCommon.java b/src/main/java/com/google/devtools/build/lib/rules/java/JavaStarlarkCommon.java index eb2bec90b9be47..27263bb7b9a59a 100644 --- a/src/main/java/com/google/devtools/build/lib/rules/java/JavaStarlarkCommon.java +++ b/src/main/java/com/google/devtools/build/lib/rules/java/JavaStarlarkCommon.java @@ -147,11 +147,10 @@ public void createHeaderCompilationAction( .setTargetLabel(targetLabel) .setInjectingRuleKind( injectingRuleKind == Starlark.NONE ? null : (String) injectingRuleKind) - .addPlugin(JavaPluginInfo.PROVIDER.wrap(pluginInfo)) + .addPlugin(JavaPluginInfo.wrap(pluginInfo)) .addCompileTimeDependencyArtifacts(compileTimeJavaDeps.getSet(Artifact.class)); if (bootClassPathUnchecked instanceof Info) { - BootClassPathInfo bootClassPathInfo = - BootClassPathInfo.PROVIDER.wrap((Info) bootClassPathUnchecked); + BootClassPathInfo bootClassPathInfo = BootClassPathInfo.wrap((Info) bootClassPathUnchecked); if (!bootClassPathInfo.isEmpty()) { attributesBuilder.setBootClassPath(bootClassPathInfo); } @@ -162,7 +161,7 @@ public void createHeaderCompilationAction( javaSemantics, JavaHelper.tokenizeJavaOptions(Depset.cast(javacOpts, String.class, "javac_opts")), attributesBuilder, - JavaToolchainProvider.PROVIDER.wrap(toolchain), + JavaToolchainProvider.wrap(toolchain), Sequence.cast(additionalInputs, Artifact.class, "additional_inputs") .getImmutableList()); compilationHelper.enableDirectClasspath(enableDirectClasspath); @@ -229,12 +228,11 @@ public void createCompilationAction( injectingRuleKind == Starlark.NONE ? null : (String) injectingRuleKind) .setSourcePath( Sequence.cast(sourcepath, Artifact.class, "source_path").getImmutableList()) - .addPlugin(JavaPluginInfo.PROVIDER.wrap(pluginInfo)) + .addPlugin(JavaPluginInfo.wrap(pluginInfo)) .addAdditionalOutputs( Sequence.cast(additionalOutputs, Artifact.class, "additional_outputs")); if (bootClassPathUnchecked instanceof Info) { - BootClassPathInfo bootClassPathInfo = - BootClassPathInfo.PROVIDER.wrap((Info) bootClassPathUnchecked); + BootClassPathInfo bootClassPathInfo = BootClassPathInfo.wrap((Info) bootClassPathUnchecked); if (!bootClassPathInfo.isEmpty()) { attributesBuilder.setBootClassPath(bootClassPathInfo); } @@ -252,7 +250,7 @@ public void createCompilationAction( javaSemantics, JavaHelper.tokenizeJavaOptions(Depset.cast(javacOpts, String.class, "javac_opts")), attributesBuilder, - JavaToolchainProvider.PROVIDER.wrap(javaToolchain), + JavaToolchainProvider.wrap(javaToolchain), Sequence.cast(additionalInputs, Artifact.class, "additional_inputs") .getImmutableList()); compilationHelper.javaBuilderJvmFlags( @@ -374,7 +372,7 @@ public boolean isJavaInfoMergeRuntimeModuleFlagsEnabled(StarlarkThread thread) public JavaInfo wrapJavaInfo(Info javaInfo, StarlarkThread thread) throws EvalException, RuleErrorException { checkPrivateAccess(thread); - return JavaInfo.PROVIDER.wrap(javaInfo); + return JavaInfo.wrap(javaInfo); } @Override diff --git a/src/main/java/com/google/devtools/build/lib/rules/java/JavaTargetAttributes.java b/src/main/java/com/google/devtools/build/lib/rules/java/JavaTargetAttributes.java index 313169e52973ae..38270c6cafbb97 100644 --- a/src/main/java/com/google/devtools/build/lib/rules/java/JavaTargetAttributes.java +++ b/src/main/java/com/google/devtools/build/lib/rules/java/JavaTargetAttributes.java @@ -63,7 +63,7 @@ public static class Builder { private ImmutableList sourcePath = ImmutableList.of(); private final ImmutableList.Builder nativeLibraries = ImmutableList.builder(); - private JavaPluginInfo plugins = JavaPluginInfo.empty(); + private JavaPluginInfo plugins = JavaPluginInfo.empty(false); private final Map resources = new LinkedHashMap<>(); private final NestedSetBuilder resourceJars = NestedSetBuilder.stableOrder(); 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 c98ef9e3117e17..d176f62802cd36 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 @@ -13,6 +13,7 @@ // limitations under the License. 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; @@ -39,6 +40,7 @@ import com.google.devtools.build.lib.packages.StarlarkProviderWrapper; import com.google.devtools.build.lib.packages.StructImpl; import com.google.devtools.build.lib.rules.java.JavaPluginInfo.JavaPluginData; +import com.google.devtools.build.lib.skyframe.BzlLoadValue; import javax.annotation.Nullable; import net.starlark.java.eval.EvalException; import net.starlark.java.eval.Sequence; @@ -49,12 +51,25 @@ @Immutable public final class JavaToolchainProvider extends StarlarkInfoWrapper { + public static final StarlarkProviderWrapper LEGACY_BUILTINS_PROVIDER = + new BuiltinsProvider(); public static final StarlarkProviderWrapper PROVIDER = new Provider(); private JavaToolchainProvider(StarlarkInfo underlying) { super(underlying); } + 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 { + throw new RuleErrorException("expected JavaToolchainInfo, got: " + key); + } + } + @Override public int hashCode() { try { @@ -98,7 +113,7 @@ private static JavaToolchainProvider from( if (toolchainInfo != null) { try { JavaToolchainProvider provider = - JavaToolchainProvider.PROVIDER.wrap(toolchainInfo.getValue("java", Info.class)); + JavaToolchainProvider.wrap(toolchainInfo.getValue("java", Info.class)); if (provider != null) { return provider; } @@ -122,7 +137,7 @@ public Label getToolchainLabel() throws RuleErrorException { /** Returns the target Java bootclasspath. */ public BootClassPathInfo getBootclasspath() throws RuleErrorException { - return BootClassPathInfo.PROVIDER.wrap(getUnderlyingValue("_bootclasspath_info", Info.class)); + return BootClassPathInfo.wrap(getUnderlyingValue("_bootclasspath_info", Info.class)); } /** Returns the {@link Artifact}s of compilation tools. */ @@ -249,7 +264,7 @@ public FilesToRunProvider getJacocoRunner() throws RuleErrorException { } public JavaRuntimeInfo getJavaRuntime() throws RuleErrorException { - return JavaRuntimeInfo.PROVIDER.wrap(getUnderlyingValue("java_runtime", Info.class)); + return JavaRuntimeInfo.wrap(getUnderlyingValue("java_runtime", Info.class)); } @AutoValue @@ -298,13 +313,24 @@ static JspecifyInfo fromStarlark(@Nullable StarlarkValue value) throws RuleError } } - private static class Provider extends StarlarkProviderWrapper { - - private Provider() { + private static class BuiltinsProvider extends Provider { + private BuiltinsProvider() { super( keyForBuiltins( - Label.parseCanonicalUnchecked("@_builtins//:common/java/java_toolchain.bzl")), - "JavaToolchainInfo"); + Label.parseCanonicalUnchecked("@_builtins//:common/java/java_toolchain.bzl"))); + } + } + + private static class Provider extends StarlarkProviderWrapper { + private Provider() { + this( + keyForBuild( + Label.parseCanonicalUnchecked( + "@rules_java//java/common/rules:java_toolchain.bzl"))); + } + + private Provider(BzlLoadValue.Key key) { + super(key, "JavaToolchainInfo"); } @Override diff --git a/src/test/java/com/google/devtools/build/lib/analysis/AutoExecGroupsTest.java b/src/test/java/com/google/devtools/build/lib/analysis/AutoExecGroupsTest.java index d0e05c2496fd2e..9c19232ec688fd 100644 --- a/src/test/java/com/google/devtools/build/lib/analysis/AutoExecGroupsTest.java +++ b/src/test/java/com/google/devtools/build/lib/analysis/AutoExecGroupsTest.java @@ -1412,7 +1412,7 @@ public void javaCommonCompile_automaticExecGroupsEnabled_javaInfoActionsExecuteO useConfiguration("--incompatible_auto_exec_groups"); ConfiguredTarget target = getConfiguredTarget("//test:custom_rule_name"); - JavaInfo javaInfo = target.get(JavaInfo.PROVIDER); + JavaInfo javaInfo = JavaInfo.getJavaInfo(target); Action genSrcOutputAction = getGeneratingAction(javaInfo.getOutputJars().getAllSrcOutputJars().get(0)); JavaGenJarsProvider javaGenJarsProvider = javaInfo.getGenJarsProvider(); @@ -1469,7 +1469,7 @@ public void javaCommonCompile_automaticExecGroupsDisabled_javaInfoActionsExecute useConfiguration("--incompatible_auto_exec_groups=False"); ConfiguredTarget target = getConfiguredTarget("//test:custom_rule_name"); - JavaInfo javaInfo = target.get(JavaInfo.PROVIDER); + JavaInfo javaInfo = JavaInfo.getJavaInfo(target); Action genSrcOutputAction = getGeneratingAction(javaInfo.getOutputJars().getAllSrcOutputJars().get(0)); JavaGenJarsProvider javaGenJarsProvider = javaInfo.getGenJarsProvider(); 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 fc02fc6dc45db8..3bc78375906d12 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,7 +1319,9 @@ public void testSubruleToolchains_requestedToolchainIsResolved_inRule() throws E assertThat(toolchainInfo).isNotNull(); assertThat(toolchainInfo.getValue("java", StarlarkInfo.class).getProvider().getKey()) - .isEqualTo(JavaToolchainProvider.PROVIDER.getKey()); + .isAnyOf( + JavaToolchainProvider.PROVIDER.getKey(), + JavaToolchainProvider.LEGACY_BUILTINS_PROVIDER.getKey()); } @Test @@ -1361,7 +1363,9 @@ public void testSubruleToolchains_requstedToolchainIsResolved_inAspect() throws assertThat(toolchainInfo).isNotNull(); assertThat(toolchainInfo.getValue("java", StarlarkInfo.class).getProvider().getKey()) - .isEqualTo(JavaToolchainProvider.PROVIDER.getKey()); + .isAnyOf( + JavaToolchainProvider.PROVIDER.getKey(), + JavaToolchainProvider.LEGACY_BUILTINS_PROVIDER.getKey()); } @Test diff --git a/src/test/java/com/google/devtools/build/lib/rules/android/AndroidStarlarkCommonTest.java b/src/test/java/com/google/devtools/build/lib/rules/android/AndroidStarlarkCommonTest.java index ad5c7092c807c1..ec02462f8ac8ae 100644 --- a/src/test/java/com/google/devtools/build/lib/rules/android/AndroidStarlarkCommonTest.java +++ b/src/test/java/com/google/devtools/build/lib/rules/android/AndroidStarlarkCommonTest.java @@ -77,8 +77,8 @@ def _impl(ctx): dep = ":foo", ) """); - JavaInfo fooJavaInfo = getConfiguredTarget("//java/android:foo").get(JavaInfo.PROVIDER); - JavaInfo barJavaInfo = getConfiguredTarget("//java/android:bar").get(JavaInfo.PROVIDER); + JavaInfo fooJavaInfo = JavaInfo.getJavaInfo(getConfiguredTarget("//java/android:foo")); + JavaInfo barJavaInfo = JavaInfo.getJavaInfo(getConfiguredTarget("//java/android:bar")); assertThat(barJavaInfo.getProvider(JavaCompilationArgsProvider.class)) .isEqualTo(fooJavaInfo.getProvider(JavaCompilationArgsProvider.class)); assertThat(fooJavaInfo.getJavaPluginInfo()).isNotNull(); 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 b098b1acddbf37..2c77ff9ef5f119 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 @@ -66,7 +66,7 @@ public void javaInfo_canBeSerializedAndDeserialized() throws Exception { ) """); - new SerializationTester(getConfiguredTarget("//java/com/google/test:a").get(JavaInfo.PROVIDER)) + new SerializationTester(JavaInfo.getJavaInfo(getConfiguredTarget("//java/com/google/test:a"))) .makeMemoizingAndAllowFutureBlocking(/* allowFutureBlocking= */ true) .addDependency(FileSystem.class, scratch.getFileSystem()) .addDependency(OptionsChecksumCache.class, new MapBackedChecksumCache()) 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 f20c873cdebfc5..f4b0b8205dfcca 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 @@ -1224,7 +1224,7 @@ public void starlarkJavaOutputsCanBeAddedToJavaPluginInfo() throws Exception { "plugins", JavaPluginData.empty(), "api_generating_plugins", JavaPluginData.empty())); - JavaPluginInfo pluginInfo = JavaPluginInfo.PROVIDER.wrap(starlarkPluginInfo); + JavaPluginInfo pluginInfo = JavaPluginInfo.wrap(starlarkPluginInfo); assertThat(pluginInfo).isNotNull(); assertThat(pluginInfo.getJavaOutputs()).hasSize(1); @@ -1293,8 +1293,7 @@ def _impl(ctx): JavaOutput nativeOutput = JavaOutput.builder().setClassJar(createArtifact("native.jar")).build(); StarlarkList starlarkOutputs = - ((StarlarkInfo) - getConfiguredTarget("//foo:my_starlark_rule").get(JavaInfo.PROVIDER.getKey())) + JavaInfo.getJavaInfo(getConfiguredTarget("//foo:my_starlark_rule")) .getValue("java_outputs", StarlarkList.class); Depset depset = @@ -1328,7 +1327,7 @@ def _impl(ctx): my_rule(name = "my_starlark_rule") """); - JavaInfo javaInfo = getConfiguredTarget("//foo:my_starlark_rule").get(JavaInfo.PROVIDER); + JavaInfo javaInfo = JavaInfo.getJavaInfo(getConfiguredTarget("//foo:my_starlark_rule")); assertThat(javaInfo).isNotNull(); assertThat(javaInfo.isNeverlink()).isTrue(); @@ -1339,13 +1338,13 @@ public void translateStarlarkJavaInfo_minimal() throws Exception { ImmutableMap fields = getBuilderWithMandataryFields().buildOrThrow(); StarlarkInfo starlarkInfo = makeStruct(fields); - JavaInfo javaInfo = JavaInfo.PROVIDER.wrap(starlarkInfo); + JavaInfo javaInfo = JavaInfo.wrap(starlarkInfo); assertThat(javaInfo).isNotNull(); assertThat(javaInfo.getProvider(JavaCompilationArgsProvider.class)).isNotNull(); assertThat(javaInfo.getCompilationInfoProvider()).isNull(); assertThat(javaInfo.getJavaModuleFlagsInfo()).isEqualTo(JavaModuleFlagsProvider.EMPTY); - assertThat(javaInfo.getJavaPluginInfo()).isEqualTo(JavaPluginInfo.empty()); + assertThat(javaInfo.getJavaPluginInfo()).isEqualTo(JavaPluginInfo.empty(false)); } @Test @@ -1354,7 +1353,7 @@ public void translateStarlarkJavaInfo_binariesDoNotContainCompilationArgs() thro getBuilderWithMandataryFields().put("_is_binary", true).buildOrThrow(); StarlarkInfo starlarkInfo = makeStruct(fields); - JavaInfo javaInfo = JavaInfo.PROVIDER.wrap(starlarkInfo); + JavaInfo javaInfo = JavaInfo.wrap(starlarkInfo); assertThat(javaInfo).isNotNull(); assertThat(javaInfo.getProvider(JavaCompilationArgsProvider.class)).isNull(); @@ -1376,7 +1375,7 @@ public void translateStarlarkJavaInfo_compilationInfo() throws Exception { .buildOrThrow(); StarlarkInfo starlarkInfo = makeStruct(fields); - JavaInfo javaInfo = JavaInfo.PROVIDER.wrap(starlarkInfo); + JavaInfo javaInfo = JavaInfo.wrap(starlarkInfo); assertThat(javaInfo).isNotNull(); assertThat(javaInfo.getCompilationInfoProvider()).isNotNull(); @@ -1433,7 +1432,7 @@ public void translateStarlarkJavaInfo_moduleFlagsInfo() throws Exception { .buildOrThrow(); StarlarkInfo starlarkInfo = makeStruct(fields); - JavaInfo javaInfo = JavaInfo.PROVIDER.wrap(starlarkInfo); + JavaInfo javaInfo = JavaInfo.wrap(starlarkInfo); assertThat(javaInfo).isNotNull(); assertThat(javaInfo.getJavaModuleFlagsInfo()).isNotNull(); @@ -1456,7 +1455,7 @@ public void translateStarlarkJavaInfo_pluginInfo() throws Exception { .buildKeepingLast(); StarlarkInfo starlarkInfo = makeStruct(fields); - JavaInfo javaInfo = JavaInfo.PROVIDER.wrap(starlarkInfo); + JavaInfo javaInfo = JavaInfo.wrap(starlarkInfo); assertThat(javaInfo).isNotNull(); assertThat(javaInfo.plugins()).isNotNull(); @@ -1653,6 +1652,6 @@ private JavaInfo fetchJavaInfo() throws Exception { new StarlarkProvider.Key( keyForBuild(Label.parseCanonical("//foo:extension.bzl")), "result")); - return JavaInfo.PROVIDER.wrap(info.getValue("property", Info.class)); + return JavaInfo.wrap(info.getValue("property", Info.class)); } } 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 d136c5a265dd65..ae058b65ee4a03 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,7 +45,8 @@ public void javaPluginFlagAlias_noFlagSet() throws Exception { ConfiguredTarget target = getConfiguredTarget(TestConstants.TOOLS_REPOSITORY + "//tools/jdk:java_plugins_flag_alias"); - assertThat(target.get(JavaPluginInfo.PROVIDER)).isEqualTo(JavaPluginInfo.empty()); + assertThat(JavaPluginInfo.get(target)) + .isAnyOf(JavaPluginInfo.empty(true), JavaPluginInfo.empty(false)); } /** Tests that a single plugin passed by a flag is returned by java_plugins_flag_alias. */ @@ -60,8 +61,7 @@ public void javaPluginFlagAlias_flagWithSinglePlugin() throws Exception { ConfiguredTarget target = getConfiguredTarget(TestConstants.TOOLS_REPOSITORY + "//tools/jdk:java_plugins_flag_alias"); - assertThat(target.get(JavaPluginInfo.PROVIDER).plugins().processorClasspath().toList()) - .hasSize(1); + assertThat(JavaPluginInfo.get(target).plugins().processorClasspath().toList()).hasSize(1); } /** Tests that two plugins passed by flag are returned by java_plugins_flag_alias. */ @@ -86,8 +86,7 @@ public void javaPluginFlagAlias_flagWithTwoPlugins() throws Exception { ConfiguredTarget target = getConfiguredTarget(TestConstants.TOOLS_REPOSITORY + "//tools/jdk:java_plugins_flag_alias"); - assertThat(target.get(JavaPluginInfo.PROVIDER).plugins().processorClasspath().toList()) - .hasSize(2); + assertThat(JavaPluginInfo.get(target).plugins().processorClasspath().toList()).hasSize(2); } /** Tests that passing a java_library to --plugin flag fails. */ diff --git a/src/test/java/com/google/devtools/build/lib/rules/java/JavaRuntimeTest.java b/src/test/java/com/google/devtools/build/lib/rules/java/JavaRuntimeTest.java index e4680c5d970b7f..df62f345f09d27 100644 --- a/src/test/java/com/google/devtools/build/lib/rules/java/JavaRuntimeTest.java +++ b/src/test/java/com/google/devtools/build/lib/rules/java/JavaRuntimeTest.java @@ -57,7 +57,7 @@ public final void initializeJvmPackage() throws Exception { private JavaRuntimeInfo getJavaRuntimeInfo(ProviderCollection collection) throws EvalException, RuleErrorException { ToolchainInfo toolchainInfo = collection.get(ToolchainInfo.PROVIDER); - return JavaRuntimeInfo.PROVIDER.wrap(toolchainInfo.getValue("java_runtime", Info.class)); + return JavaRuntimeInfo.wrap(toolchainInfo.getValue("java_runtime", Info.class)); } @Test diff --git a/src/test/java/com/google/devtools/build/lib/rules/java/JavaStarlarkApiTest.java b/src/test/java/com/google/devtools/build/lib/rules/java/JavaStarlarkApiTest.java index c18590afb76cca..0b0a984ecd99c5 100644 --- a/src/test/java/com/google/devtools/build/lib/rules/java/JavaStarlarkApiTest.java +++ b/src/test/java/com/google/devtools/build/lib/rules/java/JavaStarlarkApiTest.java @@ -589,7 +589,7 @@ public void javaCommonCompile_setsRuntimeDeps() throws Exception { ")"); ConfiguredTarget configuredTarget = getConfiguredTarget("//java/test:custom"); - JavaInfo info = configuredTarget.get(JavaInfo.PROVIDER); + JavaInfo info = JavaInfo.getJavaInfo(configuredTarget); JavaCompilationArgsProvider compilationArgs = info.getProvider(JavaCompilationArgsProvider.class); JavaCompilationInfoProvider compilationInfo = info.getCompilationInfoProvider(); @@ -773,7 +773,7 @@ public void testJavaCommonCompileCompilationInfo() throws Exception { ")"); ConfiguredTarget configuredTarget = getConfiguredTarget("//java/test:custom"); - JavaInfo info = configuredTarget.get(JavaInfo.PROVIDER); + JavaInfo info = JavaInfo.getJavaInfo(configuredTarget); JavaCompilationInfoProvider compilationInfo = info.getCompilationInfoProvider(); assertThat( prettyArtifactNames(compilationInfo.getCompilationClasspath().toList(Artifact.class))) @@ -840,7 +840,7 @@ public void testJavaCommonCompileTransitiveSourceJars() throws Exception { ")"); ConfiguredTarget configuredTarget = getConfiguredTarget("//java/test:custom"); - JavaInfo info = configuredTarget.get(JavaInfo.PROVIDER); + JavaInfo info = JavaInfo.getJavaInfo(configuredTarget); Sequence sourceJars = info.getSourceJars(); NestedSet transitiveSourceJars = info.getTransitiveSourceJars().getSet(Artifact.class); @@ -915,7 +915,7 @@ public void testJavaCommonCompileSourceJarName() throws Exception { ")"); ConfiguredTarget configuredTarget = getConfiguredTarget("//java/test:custom"); - JavaInfo info = configuredTarget.get(JavaInfo.PROVIDER); + JavaInfo info = JavaInfo.getJavaInfo(configuredTarget); Sequence sourceJars = info.getSourceJars(); NestedSet transitiveSourceJars = info.getTransitiveSourceJars().getSet(Artifact.class); @@ -969,7 +969,7 @@ public void testJavaCommonCompileWithOnlyOneSourceJar() throws Exception { ")"); ConfiguredTarget configuredTarget = getConfiguredTarget("//java/test:custom"); - JavaInfo info = configuredTarget.get(JavaInfo.PROVIDER); + JavaInfo info = JavaInfo.getJavaInfo(configuredTarget); Sequence sourceJars = info.getSourceJars(); assertThat(artifactFilesNames(sourceJars)).containsExactly("libcustom-src.jar"); ImmutableList javaOutputs = info.getJavaOutputs(); @@ -1023,7 +1023,7 @@ public void testJavaCommonCompile_noSources() throws Exception { ")"); ConfiguredTarget configuredTarget = getConfiguredTarget("//java/test:custom"); - JavaInfo info = configuredTarget.get(JavaInfo.PROVIDER); + JavaInfo info = JavaInfo.getJavaInfo(configuredTarget); Sequence sourceJars = info.getSourceJars(); assertThat(artifactFilesNames(sourceJars)).containsExactly("libcustom-src.jar"); ImmutableList javaOutputs = info.getJavaOutputs(); @@ -1079,7 +1079,7 @@ public void testJavaCommonCompileCustomSourceJar() throws Exception { ")"); ConfiguredTarget configuredTarget = getConfiguredTarget("//java/test:custom"); - JavaInfo info = configuredTarget.get(JavaInfo.PROVIDER); + JavaInfo info = JavaInfo.getJavaInfo(configuredTarget); Sequence sourceJars = info.getSourceJars(); assertThat(artifactFilesNames(sourceJars)).containsExactly("libcustom-mysrc.jar"); ImmutableList javaOutputs = info.getJavaOutputs(); @@ -1479,8 +1479,7 @@ def _impl(ctx): ) """); - JavaPluginInfo pluginInfo = - getConfiguredTarget("//java/test:plugin").get(JavaPluginInfo.PROVIDER); + JavaPluginInfo pluginInfo = JavaPluginInfo.get(getConfiguredTarget("//java/test:plugin")); JavaPluginData pluginData = pluginInfo.plugins(); JavaPluginData apiPluginData = pluginInfo.apiGeneratingPlugins(); @@ -1544,8 +1543,7 @@ def _impl(ctx): ) """); - JavaPluginInfo pluginInfo = - getConfiguredTarget("//java/test:plugin").get(JavaPluginInfo.PROVIDER); + JavaPluginInfo pluginInfo = JavaPluginInfo.get(getConfiguredTarget("//java/test:plugin")); JavaPluginData pluginData = pluginInfo.plugins(); JavaPluginData apiPluginData = pluginInfo.apiGeneratingPlugins(); @@ -1605,8 +1603,7 @@ def _impl(ctx): ) """); - JavaPluginInfo pluginInfo = - getConfiguredTarget("//java/test:plugin").get(JavaPluginInfo.PROVIDER); + JavaPluginInfo pluginInfo = JavaPluginInfo.get(getConfiguredTarget("//java/test:plugin")); JavaPluginData pluginData = pluginInfo.plugins(); JavaPluginData apiPluginData = pluginInfo.apiGeneratingPlugins(); @@ -1669,8 +1666,7 @@ def _impl(ctx): ) """); - JavaPluginInfo pluginInfo = - getConfiguredTarget("//java/test:plugin").get(JavaPluginInfo.PROVIDER); + JavaPluginInfo pluginInfo = JavaPluginInfo.get(getConfiguredTarget("//java/test:plugin")); JavaPluginData pluginData = pluginInfo.plugins(); JavaPluginData apiPluginData = pluginInfo.apiGeneratingPlugins(); @@ -1804,10 +1800,10 @@ def _impl(ctx): keyForBuild(Label.parseCanonical("//foo:extension.bzl")), "my_provider"); StructImpl declaredProvider = (StructImpl) myRuleTarget.get(myProviderKey); // attempting to wrap will error out if not a JavaInfo - Object javaProvider = JavaInfo.PROVIDER.wrap(declaredProvider.getValue("p", Info.class)); + Object javaProvider = JavaInfo.wrap(declaredProvider.getValue("p", Info.class)); // Compares providers structurally rather than by reference equality. References will not match // after serialization. - assertThat(dumpStructure(javaLibraryTarget.get(JavaInfo.PROVIDER))) + assertThat(dumpStructure(JavaInfo.getJavaInfo(javaLibraryTarget))) .isEqualTo(dumpStructure(javaProvider)); } @@ -1849,16 +1845,16 @@ def _impl(ctx): ConfiguredTarget javaLibraryTarget = getConfiguredTarget("//foo:jl"); ConfiguredTarget topJavaLibraryTarget = getConfiguredTarget("//foo:jl_top"); - Object javaProvider = myRuleTarget.get(JavaInfo.PROVIDER); + Object javaProvider = JavaInfo.getJavaInfo(myRuleTarget); assertThat(javaProvider).isInstanceOf(JavaInfo.class); - JavaInfo jlJavaInfo = javaLibraryTarget.get(JavaInfo.PROVIDER); + JavaInfo jlJavaInfo = JavaInfo.getJavaInfo(javaLibraryTarget); // Compares providers structurally rather than by reference equality. References will not match // after serialization. assertThat(dumpStructure(jlJavaInfo)).isEqualTo(dumpStructure(javaProvider)); - JavaInfo jlTopJavaInfo = topJavaLibraryTarget.get(JavaInfo.PROVIDER); + JavaInfo jlTopJavaInfo = JavaInfo.getJavaInfo(topJavaLibraryTarget); javaCompilationArgsHaveTheSameParent( jlJavaInfo.getProvider(JavaCompilationArgsProvider.class), @@ -2004,8 +2000,7 @@ def _impl(ctx): ConfiguredTarget binary = getConfiguredTarget("//foo:binary"); assertThat( prettyArtifactNames( - binary - .get(JavaInfo.PROVIDER) + JavaInfo.getJavaInfo(binary) .getCompilationInfoProvider() .getRuntimeClasspath() .getSet(Artifact.class))) @@ -2562,7 +2557,7 @@ def _impl(ctx): ConfiguredTarget topJavaLibrary = getConfiguredTarget("//foo:jl_top"); NestedSet librariesForTopTarget = - topJavaLibrary.get(JavaInfo.PROVIDER).getTransitiveNativeLibraries(); + JavaInfo.getJavaInfo(topJavaLibrary).getTransitiveNativeLibraries(); assertThat(librariesForTopTarget.toList().stream().map(LibraryToLink::getLibraryIdentifier)) .containsExactly("foo/libnative", "foo/libccl") .inOrder(); @@ -2745,7 +2740,7 @@ def _impl(ctx): ConfiguredTarget myRuleTarget = getConfiguredTarget("//foo:r"); ConfiguredTarget javaLibraryTarget = getConfiguredTarget("//foo:jl"); - JavaInfo javaInfo = javaLibraryTarget.get(JavaInfo.PROVIDER); + JavaInfo javaInfo = JavaInfo.getJavaInfo(javaLibraryTarget); StarlarkProvider.Key myProviderKey = new StarlarkProvider.Key( keyForBuild(Label.parseCanonical("//foo:extension.bzl")), "my_provider"); @@ -2848,7 +2843,7 @@ def _impl(ctx): ConfiguredTarget configuredTarget = getConfiguredTarget("//java/test:custom"); - JavaInfo info = configuredTarget.get(JavaInfo.PROVIDER); + JavaInfo info = JavaInfo.getJavaInfo(configuredTarget); NestedSet nativeLibraries = info.getTransitiveNativeLibraries(); assertThat(nativeLibraries.toList().stream().map(LibraryToLink::getLibraryIdentifier)) .containsExactly( @@ -3099,7 +3094,7 @@ def _impl(ctx): ConfiguredTarget target = getConfiguredTarget("//java/test:somedep"); - JavaInfo javaInfo = target.get(JavaInfo.PROVIDER); + JavaInfo javaInfo = JavaInfo.getJavaInfo(target); assertThat(javaInfo.isNeverlink()).isTrue(); } @@ -3143,7 +3138,7 @@ def _impl(ctx): ConfiguredTarget target = getConfiguredTarget("//java/test:somedep"); - JavaInfo javaInfo = target.get(JavaInfo.PROVIDER); + JavaInfo javaInfo = JavaInfo.getJavaInfo(target); assertThat(javaInfo.isNeverlink()).isTrue(); } @@ -3188,7 +3183,7 @@ public void javaCommonCompileWithNeverlink() throws Exception { ConfiguredTarget target = getConfiguredTarget("//java/test:somedep"); - JavaInfo javaInfo = target.get(JavaInfo.PROVIDER); + JavaInfo javaInfo = JavaInfo.getJavaInfo(target); assertThat(javaInfo.isNeverlink()).isTrue(); } @@ -3281,7 +3276,7 @@ public void javaCommonCompile_nativeLibrariesPropagate() throws Exception { ConfiguredTarget configuredTarget = getConfiguredTarget("//java/test:custom"); - JavaInfo info = configuredTarget.get(JavaInfo.PROVIDER); + JavaInfo info = JavaInfo.getJavaInfo(configuredTarget); NestedSet nativeLibraries = info.getTransitiveNativeLibraries(); assertThat(nativeLibraries.toList().stream().map(LibraryToLink::getLibraryIdentifier)) .containsExactly( @@ -3344,7 +3339,7 @@ public void javaCommonCompile_directNativeLibraries() throws Exception { ConfiguredTarget configuredTarget = getConfiguredTarget("//java/test:custom"); - JavaInfo info = configuredTarget.get(JavaInfo.PROVIDER); + JavaInfo info = JavaInfo.getJavaInfo(configuredTarget); NestedSet nativeLibraries = info.getTransitiveNativeLibraries(); assertThat(nativeLibraries.toList().stream().map(LibraryToLink::getLibraryIdentifier)) .containsExactly("java/test/libnative.so") @@ -3561,7 +3556,7 @@ def _impl(ctx): """); ConfiguredTarget myRuleTarget = getConfiguredTarget("//foo:custom"); - JavaInfo javaInfo = myRuleTarget.get(JavaInfo.PROVIDER); + JavaInfo javaInfo = JavaInfo.getJavaInfo(myRuleTarget); List directJars = prettyArtifactNames(javaInfo.getRuntimeOutputJars()); assertThat(directJars).containsExactly("foo/liba.jar", "foo/libb.jar"); } @@ -3731,7 +3726,7 @@ public void testCompileExports() throws Exception { " fragments = ['java']", ")"); - JavaInfo info = getConfiguredTarget("//java/test:custom").get(JavaInfo.PROVIDER); + JavaInfo info = JavaInfo.getJavaInfo(getConfiguredTarget("//java/test:custom")); assertThat(prettyArtifactNames(info.getTransitiveSourceJars().getSet(Artifact.class))) .containsExactly("java/test/amazing-src.jar", "java/test/libdep-src.jar"); JavaCompilationArgsProvider provider = info.getProvider(JavaCompilationArgsProvider.class); @@ -3777,7 +3772,7 @@ public void testCompileOutputJarHasManifestProto() throws Exception { """); ConfiguredTarget configuredTarget = getConfiguredTarget("//foo:b"); - JavaInfo info = configuredTarget.get(JavaInfo.PROVIDER); + JavaInfo info = JavaInfo.getJavaInfo(configuredTarget); ImmutableList javaOutputs = info.getJavaOutputs(); assertThat(javaOutputs).hasSize(1); JavaOutput output = javaOutputs.get(0); @@ -3831,7 +3826,7 @@ public void testCompileWithNeverlinkDeps() throws Exception { """); ConfiguredTarget configuredTarget = getConfiguredTarget("//foo:a"); - JavaInfo info = configuredTarget.get(JavaInfo.PROVIDER); + JavaInfo info = JavaInfo.getJavaInfo(configuredTarget); assertThat(artifactFilesNames(info.getTransitiveRuntimeJars().toList(Artifact.class))) .containsExactly("liba.jar"); assertThat(artifactFilesNames(info.getTransitiveSourceJars().getSet(Artifact.class))) @@ -3886,7 +3881,7 @@ public void testCompileOutputJarNotInRuntimePathWithoutAnySourcesDefined() throw """); ConfiguredTarget configuredTarget = getConfiguredTarget("//foo:c"); - JavaInfo info = configuredTarget.get(JavaInfo.PROVIDER); + JavaInfo info = JavaInfo.getJavaInfo(configuredTarget); assertThat(artifactFilesNames(info.getTransitiveRuntimeJars().toList(Artifact.class))) .containsExactly("libb.jar"); assertThat(artifactFilesNames(info.getTransitiveCompileTimeJars().toList(Artifact.class))) diff --git a/src/test/java/com/google/devtools/build/lib/view/java/JavaImportConfiguredTargetTest.java b/src/test/java/com/google/devtools/build/lib/view/java/JavaImportConfiguredTargetTest.java index 9c14bef537f15a..aeb4131837f9b6 100644 --- a/src/test/java/com/google/devtools/build/lib/view/java/JavaImportConfiguredTargetTest.java +++ b/src/test/java/com/google/devtools/build/lib/view/java/JavaImportConfiguredTargetTest.java @@ -577,7 +577,7 @@ public void testNeverlinkIsPopulated() throws Exception { ) """); ConfiguredTarget processorTarget = getConfiguredTarget("//java/com/google/test:jar"); - JavaInfo javaInfo = processorTarget.get(JavaInfo.PROVIDER); + JavaInfo javaInfo = JavaInfo.getJavaInfo(processorTarget); assertThat(javaInfo.isNeverlink()).isTrue(); } diff --git a/src/test/java/com/google/devtools/build/lib/view/java/JavaPluginConfiguredTargetTest.java b/src/test/java/com/google/devtools/build/lib/view/java/JavaPluginConfiguredTargetTest.java index 4b8fa5190aa378..2f317e3c74e5f5 100644 --- a/src/test/java/com/google/devtools/build/lib/view/java/JavaPluginConfiguredTargetTest.java +++ b/src/test/java/com/google/devtools/build/lib/view/java/JavaPluginConfiguredTargetTest.java @@ -86,11 +86,10 @@ public void testNotEmptyProcessorClass() throws Exception { setupEmptyProcessorClass(); ConfiguredTarget processorTarget = getConfiguredTarget("//java/com/google/test:processor"); - assertThat(processorTarget.get(JavaPluginInfo.PROVIDER).plugins().processorClasses().toList()) + assertThat(JavaPluginInfo.get(processorTarget).plugins().processorClasses().toList()) .containsExactly("com.google.test.Processor"); assertThat( - prettyArtifactNames( - processorTarget.get(JavaPluginInfo.PROVIDER).plugins().processorClasspath())) + prettyArtifactNames(JavaPluginInfo.get(processorTarget).plugins().processorClasspath())) .containsExactly( "java/com/google/test/libprocessor.jar", "java/com/google/test/libdeps.jar"); } @@ -100,12 +99,12 @@ public void testEmptyProcessorClass() throws Exception { setupEmptyProcessorClass(); ConfiguredTarget bugcheckerTarget = getConfiguredTarget("//java/com/google/test:bugchecker"); - assertThat(bugcheckerTarget.get(JavaPluginInfo.PROVIDER).plugins().processorClasses().toList()) + assertThat(JavaPluginInfo.get(bugcheckerTarget).plugins().processorClasses().toList()) .isEmpty(); assertThat( prettyArtifactNames( - bugcheckerTarget.get(JavaPluginInfo.PROVIDER).plugins().processorClasspath())) + JavaPluginInfo.get(bugcheckerTarget).plugins().processorClasspath())) .containsExactly( "java/com/google/test/libbugchecker.jar", "java/com/google/test/libdeps.jar"); } @@ -120,11 +119,7 @@ public void testEmptyProcessorClassTarget() throws Exception { (JavaCompileAction) getGeneratingAction(emptyOutput.getArtifact()); assertThat( Artifact.toRootRelativePaths( - bugcheckerTarget - .get(JavaPluginInfo.PROVIDER) - .plugins() - .processorClasspath() - .toList())) + JavaPluginInfo.get(bugcheckerTarget).plugins().processorClasspath().toList())) .containsExactlyElementsIn( Artifact.toRootRelativePaths(getInputs(javacAction, getProcessorpath(javacAction)))); } @@ -240,7 +235,7 @@ public void generatesApi() throws Exception { """); JavaPluginInfo plugin = - getConfiguredTarget("//java/com/google/test:api_generating").get(JavaPluginInfo.PROVIDER); + JavaPluginInfo.get(getConfiguredTarget("//java/com/google/test:api_generating")); assertThat(plugin.plugins().processorClasses().toList()).containsExactly("ApiGeneratingPlugin"); assertThat(plugin.apiGeneratingPlugins().processorClasses().toList()) .containsExactly("ApiGeneratingPlugin"); @@ -266,7 +261,7 @@ public void generatesImplementation() throws Exception { """); JavaPluginInfo plugin = - getConfiguredTarget("//java/com/google/test:impl_generating").get(JavaPluginInfo.PROVIDER); + JavaPluginInfo.get(getConfiguredTarget("//java/com/google/test:impl_generating")); assertThat(plugin.plugins().processorClasses().toList()) .containsExactly("ImplGeneratingPlugin"); assertThat(plugin.apiGeneratingPlugins().processorClasses().toList()).isEmpty(); @@ -298,7 +293,7 @@ public void pluginData() throws Exception { """); JavaPluginInfo plugin = - getConfiguredTarget("//java/com/google/test:impl_generating").get(JavaPluginInfo.PROVIDER); + JavaPluginInfo.get(getConfiguredTarget("//java/com/google/test:impl_generating")); assertThat(prettyArtifactNames(plugin.plugins().data())) .containsExactly("java/com/google/test/data.txt"); FileConfiguredTarget libJar = getFileConfiguredTarget("//java/com/google/test:liblib.jar"); From 892df1dcb4a4123d06c0da1e7079a85c93f2ab7c Mon Sep 17 00:00:00 2001 From: Googler Date: Mon, 11 Nov 2024 06:25:08 -0800 Subject: [PATCH 03/15] Use canonical repo name in `rules_java` provider key labels PiperOrigin-RevId: 695310715 Change-Id: I55fc8f5e61f9a7f508d1fb77d30c64790c18fb82 (cherry picked from commit 84e669898e50f1ac8f8257f5998c9946c5754450) --- .../devtools/build/lib/rules/java/BootClassPathInfo.java | 3 ++- .../com/google/devtools/build/lib/rules/java/JavaInfo.java | 2 +- .../google/devtools/build/lib/rules/java/JavaPluginInfo.java | 2 +- .../google/devtools/build/lib/rules/java/JavaRuntimeInfo.java | 3 ++- .../google/devtools/build/lib/rules/java/JavaSemantics.java | 3 +++ .../devtools/build/lib/rules/java/JavaToolchainProvider.java | 3 ++- 6 files changed, 11 insertions(+), 5 deletions(-) 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 c9da2546e56995..0a47b42016b430 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 @@ -134,7 +134,8 @@ private Provider() { this( keyForBuild( Label.parseCanonicalUnchecked( - "@rules_java//java/private:boot_class_path_info.bzl"))); + JavaSemantics.RULES_JAVA_PROVIDER_LABELS_PREFIX + + "java/private:boot_class_path_info.bzl"))); } private Provider(BzlLoadValue.Key key) { 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 1116741684e20d..80a7230fe13abc 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 @@ -560,7 +560,7 @@ private JavaInfoProvider() { this( keyForBuild( Label.parseCanonicalUnchecked( - "@rules_java//java/private:java_info.bzl"))); + JavaSemantics.RULES_JAVA_PROVIDER_LABELS_PREFIX + "java/private:java_info.bzl"))); } public JavaInfoProvider(BzlLoadValue.Key key) { 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 b167a007917abc..7b32df553a17c8 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 @@ -107,7 +107,7 @@ private Provider() { this( keyForBuild( Label.parseCanonicalUnchecked( - "@rules_java//java/private:java_info.bzl"))); + JavaSemantics.RULES_JAVA_PROVIDER_LABELS_PREFIX + "java/private:java_info.bzl"))); } private Provider(BzlLoadValue.Key key) { 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 890b4fc978878f..6aa7d24af25116 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 @@ -157,7 +157,8 @@ private Provider() { this( keyForBuild( Label.parseCanonicalUnchecked( - "@rules_java//java/common/rules:java_runtime.bzl"))); + JavaSemantics.RULES_JAVA_PROVIDER_LABELS_PREFIX + + "java/common/rules:java_runtime.bzl"))); } private Provider(BzlLoadValue.Key key) { diff --git a/src/main/java/com/google/devtools/build/lib/rules/java/JavaSemantics.java b/src/main/java/com/google/devtools/build/lib/rules/java/JavaSemantics.java index 9601bf1e6ce0b2..012074877dc2e8 100644 --- a/src/main/java/com/google/devtools/build/lib/rules/java/JavaSemantics.java +++ b/src/main/java/com/google/devtools/build/lib/rules/java/JavaSemantics.java @@ -27,6 +27,9 @@ /** Pluggable Java compilation semantics. */ public interface JavaSemantics { + // transformed by Copybara on export + String RULES_JAVA_PROVIDER_LABELS_PREFIX = "@@rules_java+//"; + FileType JAVA_SOURCE = FileType.of(".java"); FileType JAR = FileType.of(".jar"); FileType PROPERTIES = FileType.of(".properties"); 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 d176f62802cd36..cdc77080fb9ace 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 @@ -326,7 +326,8 @@ private Provider() { this( keyForBuild( Label.parseCanonicalUnchecked( - "@rules_java//java/common/rules:java_toolchain.bzl"))); + JavaSemantics.RULES_JAVA_PROVIDER_LABELS_PREFIX + + "java/common/rules:java_toolchain.bzl"))); } private Provider(BzlLoadValue.Key key) { From 12e7f96ef2282934765a851d5b2d85183dc0b318 Mon Sep 17 00:00:00 2001 From: Googler Date: Tue, 12 Nov 2024 00:12:06 -0800 Subject: [PATCH 04/15] Add a third variant of native provider wrappers for `@rules_java` itself Needed for when the main repository is `rules_java` PiperOrigin-RevId: 695621150 Change-Id: I66ff003dcf063ecf7905accfc83a4babedd2d34c (cherry picked from commit 66ea9a037f2d727f5e1c8d70d187dfe680a48c06) --- .../lib/rules/java/BootClassPathInfo.java | 10 ++++ .../build/lib/rules/java/JavaInfo.java | 32 ++++++++++ .../build/lib/rules/java/JavaPluginInfo.java | 60 +++++++++++-------- .../rules/java/JavaPluginsFlagAliasRule.java | 25 +++++--- .../build/lib/rules/java/JavaRuntimeInfo.java | 11 +++- .../lib/rules/java/JavaTargetAttributes.java | 2 +- .../lib/rules/java/JavaToolchainProvider.java | 10 ++++ .../rules/java/JavaInfoStarlarkApiTest.java | 5 +- .../rules/java/JavaPluginsFlagAliasTest.java | 4 +- 9 files changed, 122 insertions(+), 37 deletions(-) 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 0a47b42016b430..47fcd79fa989d2 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 @@ -42,6 +42,8 @@ public class BootClassPathInfo extends StarlarkInfoWrapper { new BuiltinsProvider(); public static final StarlarkProviderWrapper PROVIDER = new Provider(); + public static final StarlarkProviderWrapper RULES_JAVA_PROVIDER = + new RulesJavaProvider(); private static final BootClassPathInfo EMPTY = new BootClassPathInfo(null) { @@ -85,6 +87,8 @@ public static BootClassPathInfo wrap(Info info) throws RuleErrorException { 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 { throw new RuleErrorException("expected BootClassPathInfo, got: " + key); } @@ -129,6 +133,12 @@ private BuiltinsProvider() { } } + private static class RulesJavaProvider extends Provider { + private RulesJavaProvider() { + super(keyForBuild(Label.parseCanonicalUnchecked("//java/private:boot_class_path_info.bzl"))); + } + } + private static class Provider extends StarlarkProviderWrapper { private Provider() { this( 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 80a7230fe13abc..493a47781cae2a 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 @@ -72,6 +72,7 @@ public class JavaInfo extends NativeInfo public static final String STARLARK_NAME = "JavaInfo"; public static final JavaInfoProvider LEGACY_BUILTINS_PROVIDER = new BuiltinsJavaInfoProvider(); + public static final JavaInfoProvider RULES_JAVA_PROVIDER = new RulesJavaJavaInfoProvider(); public static final JavaInfoProvider PROVIDER = new JavaInfoProvider(); // Ideally we would check if the target has a JavaInfo, but this check predates the Starlark @@ -210,6 +211,9 @@ public static JavaInfo getJavaInfo(TransitiveInfoCollection target) throws RuleE if (info == null) { info = target.get(LEGACY_BUILTINS_PROVIDER); } + if (info == null) { + info = target.get(RULES_JAVA_PROVIDER); + } return info; } @@ -217,6 +221,8 @@ 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())) { + return RULES_JAVA_PROVIDER.wrap(info); } else { return JavaInfo.PROVIDER.wrap(info); } @@ -539,6 +545,19 @@ public JavaInfoProvider getProvider() { } } + private static class RulesJavaJavaInfo extends JavaInfo { + + private RulesJavaJavaInfo(StructImpl javaInfo) + throws EvalException, TypeException, RuleErrorException { + super(javaInfo); + } + + @Override + public JavaInfoProvider getProvider() { + return RULES_JAVA_PROVIDER; + } + } + /** Legacy Provider class for {@link JavaInfo} objects. */ public static class BuiltinsJavaInfoProvider extends JavaInfoProvider { private BuiltinsJavaInfoProvider() { @@ -553,6 +572,19 @@ protected JavaInfo makeNewInstance(StructImpl info) } } + /** Legacy Provider class for {@link JavaInfo} objects. */ + public static class RulesJavaJavaInfoProvider extends JavaInfoProvider { + private RulesJavaJavaInfoProvider() { + super(keyForBuild(Label.parseCanonicalUnchecked("//java/private:java_info.bzl"))); + } + + @Override + protected JavaInfo makeNewInstance(StructImpl info) + throws RuleErrorException, TypeException, EvalException { + return new RulesJavaJavaInfo(info); + } + } + /** Provider class for {@link JavaInfo} objects. */ public static class JavaInfoProvider extends StarlarkProviderWrapper implements com.google.devtools.build.lib.packages.Provider { 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 7b32df553a17c8..d160613c27e5b1 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 @@ -52,14 +52,22 @@ public abstract class JavaPluginInfo extends NativeInfo 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(); private static final JavaPluginInfo EMPTY_BUILTIN = new AutoValue_JavaPluginInfo( - ImmutableList.of(), JavaPluginData.empty(), JavaPluginData.empty(), true); + ImmutableList.of(), + JavaPluginData.empty(), + JavaPluginData.empty(), + LEGACY_BUILTINS_PROVIDER); private static final JavaPluginInfo EMPTY = new AutoValue_JavaPluginInfo( - ImmutableList.of(), JavaPluginData.empty(), JavaPluginData.empty(), false); + ImmutableList.of(), JavaPluginData.empty(), JavaPluginData.empty(), PROVIDER); + + private static final JavaPluginInfo EMPTY_RULES_JAVA = + new AutoValue_JavaPluginInfo( + ImmutableList.of(), JavaPluginData.empty(), JavaPluginData.empty(), RULES_JAVA_PROVIDER); public static JavaPluginInfo wrap(Info info) throws RuleErrorException { com.google.devtools.build.lib.packages.Provider.Key key = info.getProvider().getKey(); @@ -83,8 +91,8 @@ public static JavaPluginInfo get(ConfiguredTarget target) throws RuleErrorExcept } @Override - public Provider getProvider() { - return builtin() ? LEGACY_BUILTINS_PROVIDER : PROVIDER; + public com.google.devtools.build.lib.packages.Provider getProvider() { + return providerType(); } /** Legacy Provider class for {@link JavaPluginInfo} objects. */ @@ -93,10 +101,12 @@ private BuiltinsProvider() { super( keyForBuiltins(Label.parseCanonicalUnchecked("@_builtins//:common/java/java_info.bzl"))); } + } - @Override - protected boolean isBuiltin() { - return true; + /** Provider class for {@link JavaPluginInfo} objects in rules_java itself. */ + public static class RulesJavaProvider extends Provider { + private RulesJavaProvider() { + super(keyForBuild(Label.parseCanonicalUnchecked("//java/private:java_info.bzl"))); } } @@ -144,7 +154,7 @@ public JavaPluginInfo wrap(Info value) throws RuleErrorException { Sequence.cast(info.getValue("java_outputs"), Object.class, "java_outputs")), JavaPluginData.wrap(info.getValue("plugins")), JavaPluginData.wrap(info.getValue("api_generating_plugins")), - isBuiltin()); + value.getProvider()); } catch (EvalException e) { throw new RuleErrorException(e); } @@ -153,10 +163,6 @@ public JavaPluginInfo wrap(Info value) throws RuleErrorException { "got element of type " + Starlark.type(value) + ", want JavaPluginInfo"); } } - - protected boolean isBuiltin() { - return false; - } } /** Information about a Java plugin, except for whether it generates API. */ @@ -242,13 +248,12 @@ public boolean isEmpty() { public static JavaPluginInfo mergeWithoutJavaOutputs(JavaPluginInfo a, JavaPluginInfo b) { return a.isEmpty() ? b - : b.isEmpty() - ? a - : mergeWithoutJavaOutputs(ImmutableList.of(a, b), a.builtin() && b.builtin()); + : b.isEmpty() ? a : mergeWithoutJavaOutputs(ImmutableList.of(a, b), a.providerType()); } public static JavaPluginInfo mergeWithoutJavaOutputs( - Iterable providers, boolean builtin) { + Iterable providers, + com.google.devtools.build.lib.packages.Provider providerType) { List plugins = new ArrayList<>(); List apiGeneratingPlugins = new ArrayList<>(); for (JavaPluginInfo provider : providers) { @@ -258,20 +263,24 @@ public static JavaPluginInfo mergeWithoutJavaOutputs( if (!provider.apiGeneratingPlugins().isEmpty()) { apiGeneratingPlugins.add(provider.apiGeneratingPlugins()); } - builtin = builtin && provider.builtin(); } if (plugins.isEmpty() && apiGeneratingPlugins.isEmpty()) { - return JavaPluginInfo.empty(builtin); + return JavaPluginInfo.empty(providerType); } return new AutoValue_JavaPluginInfo( ImmutableList.of(), JavaPluginData.merge(plugins), JavaPluginData.merge(apiGeneratingPlugins), - builtin); + providerType); } - public static JavaPluginInfo empty(boolean builtin) { - return builtin ? EMPTY_BUILTIN : EMPTY; + 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)) { + return EMPTY_RULES_JAVA; + } + return EMPTY; } @Override @@ -280,7 +289,7 @@ public static JavaPluginInfo empty(boolean builtin) { @Override public abstract JavaPluginData apiGeneratingPlugins(); - protected abstract boolean builtin(); + protected abstract com.google.devtools.build.lib.packages.Provider providerType(); /** Returns true if the provider has no associated data. */ public boolean isEmpty() { @@ -308,15 +317,14 @@ public boolean hasProcessors() { */ static JavaPluginInfo fromStarlarkJavaInfo(StructImpl javaInfo) throws EvalException, RuleErrorException { - boolean builtin = - javaInfo.getProvider().getKey().equals(JavaInfo.LEGACY_BUILTINS_PROVIDER.getKey()); + com.google.devtools.build.lib.packages.Provider providerType = javaInfo.getProvider(); JavaPluginData plugins = JavaPluginData.wrap(javaInfo.getValue("plugins")); JavaPluginData apiGeneratingPlugins = JavaPluginData.wrap(javaInfo.getValue("api_generating_plugins")); if (plugins.isEmpty() && apiGeneratingPlugins.isEmpty()) { - return JavaPluginInfo.empty(builtin); + return JavaPluginInfo.empty(providerType); } return new AutoValue_JavaPluginInfo( - ImmutableList.of(), plugins, apiGeneratingPlugins, /* builtin= */ builtin); + ImmutableList.of(), plugins, apiGeneratingPlugins, providerType); } } 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 b4a31cb0a4fa08..571f66e683ad3f 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 @@ -86,18 +86,29 @@ public ConfiguredTarget create(RuleContext ruleContext) ruleContext .getRulePrerequisitesCollection() .getPrerequisites(":java_plugins", JavaPluginInfo.PROVIDER); - // try builtin provider as well - ImmutableList builtinsProviderPlugins = - ruleContext - .getRulePrerequisitesCollection() - .getPrerequisites(":java_plugins", JavaPluginInfo.LEGACY_BUILTINS_PROVIDER); - JavaPluginInfo javaPluginInfo = JavaPluginInfo.mergeWithoutJavaOutputs(plugins, false); + if (plugins.isEmpty()) { + plugins = + ruleContext + .getRulePrerequisitesCollection() + .getPrerequisites(":java_plugins", JavaPluginInfo.LEGACY_BUILTINS_PROVIDER); + } + if (plugins.isEmpty()) { + plugins = + ruleContext + .getRulePrerequisitesCollection() + .getPrerequisites(":java_plugins", JavaPluginInfo.RULES_JAVA_PROVIDER); + } + JavaPluginInfo javaPluginInfo = + JavaPluginInfo.mergeWithoutJavaOutputs(plugins, JavaPluginInfo.PROVIDER); JavaPluginInfo builtinsProviderInfo = - JavaPluginInfo.mergeWithoutJavaOutputs(builtinsProviderPlugins, true); + JavaPluginInfo.mergeWithoutJavaOutputs(plugins, JavaPluginInfo.LEGACY_BUILTINS_PROVIDER); + JavaPluginInfo rulesJavaProviderInfo = + JavaPluginInfo.mergeWithoutJavaOutputs(plugins, JavaPluginInfo.RULES_JAVA_PROVIDER); return new RuleConfiguredTargetBuilder(ruleContext) .addStarlarkDeclaredProvider(javaPluginInfo) .addStarlarkDeclaredProvider(builtinsProviderInfo) + .addStarlarkDeclaredProvider(rulesJavaProviderInfo) .addProvider(RunfilesProvider.class, RunfilesProvider.EMPTY) .build(); } 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 6aa7d24af25116..7fb91641f781ce 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 @@ -48,6 +48,8 @@ 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 PROVIDER = new Provider(); // Helper methods to access an instance of JavaRuntimeInfo. @@ -102,6 +104,8 @@ public static JavaRuntimeInfo wrap(Info info) throws RuleErrorException { 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 { throw new RuleErrorException("expected JavaRuntimeInfo, got: " + key); } @@ -143,7 +147,6 @@ public int version() throws RuleErrorException { } private static class BuiltinsProvider extends Provider { - private BuiltinsProvider() { super( keyForBuiltins( @@ -151,6 +154,12 @@ private BuiltinsProvider() { } } + private static class RulesJavaProvider extends Provider { + private RulesJavaProvider() { + super(keyForBuild(Label.parseCanonicalUnchecked("//java/common/rules:java_runtime.bzl"))); + } + } + private static class Provider extends StarlarkProviderWrapper { private Provider() { diff --git a/src/main/java/com/google/devtools/build/lib/rules/java/JavaTargetAttributes.java b/src/main/java/com/google/devtools/build/lib/rules/java/JavaTargetAttributes.java index 38270c6cafbb97..a6f7e6e618e6a8 100644 --- a/src/main/java/com/google/devtools/build/lib/rules/java/JavaTargetAttributes.java +++ b/src/main/java/com/google/devtools/build/lib/rules/java/JavaTargetAttributes.java @@ -63,7 +63,7 @@ public static class Builder { private ImmutableList sourcePath = ImmutableList.of(); private final ImmutableList.Builder nativeLibraries = ImmutableList.builder(); - private JavaPluginInfo plugins = JavaPluginInfo.empty(false); + private JavaPluginInfo plugins = JavaPluginInfo.empty(JavaPluginInfo.PROVIDER); private final Map resources = new LinkedHashMap<>(); private final NestedSetBuilder resourceJars = NestedSetBuilder.stableOrder(); 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 cdc77080fb9ace..bf4c85557aa8ca 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 @@ -53,6 +53,8 @@ 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 PROVIDER = new Provider(); private JavaToolchainProvider(StarlarkInfo underlying) { @@ -65,6 +67,8 @@ public static JavaToolchainProvider wrap(Info info) throws RuleErrorException { 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 { throw new RuleErrorException("expected JavaToolchainInfo, got: " + key); } @@ -321,6 +325,12 @@ private BuiltinsProvider() { } } + private static class RulesJavaProvider extends Provider { + private RulesJavaProvider() { + super(keyForBuild(Label.parseCanonicalUnchecked("//java/common/rules:java_toolchain.bzl"))); + } + } + private static class Provider extends StarlarkProviderWrapper { private Provider() { this( 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 f4b0b8205dfcca..59fbae4d287559 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 @@ -1344,7 +1344,10 @@ public void translateStarlarkJavaInfo_minimal() throws Exception { assertThat(javaInfo.getProvider(JavaCompilationArgsProvider.class)).isNotNull(); assertThat(javaInfo.getCompilationInfoProvider()).isNull(); assertThat(javaInfo.getJavaModuleFlagsInfo()).isEqualTo(JavaModuleFlagsProvider.EMPTY); - assertThat(javaInfo.getJavaPluginInfo()).isEqualTo(JavaPluginInfo.empty(false)); + assertThat(javaInfo.getJavaPluginInfo()) + .isAnyOf( + JavaPluginInfo.empty(JavaPluginInfo.LEGACY_BUILTINS_PROVIDER), + 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 ae058b65ee4a03..375327a12488d2 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 @@ -46,7 +46,9 @@ public void javaPluginFlagAlias_noFlagSet() throws Exception { getConfiguredTarget(TestConstants.TOOLS_REPOSITORY + "//tools/jdk:java_plugins_flag_alias"); assertThat(JavaPluginInfo.get(target)) - .isAnyOf(JavaPluginInfo.empty(true), JavaPluginInfo.empty(false)); + .isAnyOf( + JavaPluginInfo.empty(JavaPluginInfo.PROVIDER), + JavaPluginInfo.empty(JavaPluginInfo.LEGACY_BUILTINS_PROVIDER)); } /** Tests that a single plugin passed by a flag is returned by java_plugins_flag_alias. */ From 44dd2cac2b02dfb682c5f34a32b98973a4a72e9f Mon Sep 17 00:00:00 2001 From: Googler Date: Tue, 12 Nov 2024 05:38:59 -0800 Subject: [PATCH 05/15] Fix Autoloads skyframe injection Before this, changing the value of `--enable_bzlmod` did not invalidate the existing skyframe precomputed value as the instances were considered the same/equal (see `src/main/java/com/google/devtools/build/skyframe/AbstractInMemoryMemoizingEvaluator.java#pruneInjectedValues`) Fixes https://github.com/bazelbuild/rules_python/issues/2387 PiperOrigin-RevId: 695696010 Change-Id: I136f2bec4e2c668d020f6cb1a7d3200f7523e5a0 (cherry picked from commit a5b6c303333475bf581fe670155baa9b41d983b5) From 2d04f5256c077fbf24f9aac905acfa50fed9d30c Mon Sep 17 00:00:00 2001 From: Googler Date: Tue, 12 Nov 2024 22:44:28 -0800 Subject: [PATCH 06/15] Encode `JavaInfo` provider type. https://github.com/bazelbuild/bazel/commit/da1aba957d71153ec6904ef872b4b8ffd33488fe introduces `BuiltinsJavaInfo`, which uses a different provider type (`LEGACY_BUILTINS_PROVIDER`). This information needs to be encoded along with the serialized provider fields for the deserializer to re-instantiate it back to `BuiltinsJavaInfo` instead of `JavaInfo`. PiperOrigin-RevId: 695991580 Change-Id: I3b7a5b87a2619d83ca6e7d3a3eee0349769b0640 (cherry picked from commit dc4fb9ca276560325c823d384bf39e10d6333129) --- .../devtools/build/lib/rules/java/BUILD | 2 +- .../build/lib/rules/java/JavaInfo.java | 41 ++++++++++++++----- .../lib/rules/java/JavaInfoCodecTest.java | 15 ++++++- .../build/lib/rules/java/JavaInfoTest.java | 11 ++--- .../lib/rules/java/JavaStarlarkApiTest.java | 2 +- 5 files changed, 52 insertions(+), 19 deletions(-) diff --git a/src/main/java/com/google/devtools/build/lib/rules/java/BUILD b/src/main/java/com/google/devtools/build/lib/rules/java/BUILD index 43e7b7b07ed4e8..7420ddc717947d 100644 --- a/src/main/java/com/google/devtools/build/lib/rules/java/BUILD +++ b/src/main/java/com/google/devtools/build/lib/rules/java/BUILD @@ -38,6 +38,7 @@ java_library( "//src/main/java/com/google/devtools/build/lib/rules/cpp", "//src/main/java/com/google/devtools/build/lib/skyframe:bzl_load_value", "//src/main/java/com/google/devtools/build/lib/skyframe/serialization", + "//src/main/java/com/google/devtools/build/lib/skyframe/serialization/autocodec:serialization-constant", "//src/main/java/com/google/devtools/build/lib/starlarkbuildapi/core", "//src/main/java/com/google/devtools/build/lib/starlarkbuildapi/cpp", "//src/main/java/com/google/devtools/build/lib/starlarkbuildapi/java", @@ -107,7 +108,6 @@ java_library( "//src/main/java/com/google/devtools/build/lib/analysis:config/invalid_configuration_exception", "//src/main/java/com/google/devtools/build/lib/analysis:config/toolchain_type_requirement", "//src/main/java/com/google/devtools/build/lib/analysis:configured_target", - "//src/main/java/com/google/devtools/build/lib/analysis:file_provider", "//src/main/java/com/google/devtools/build/lib/analysis:platform_options", "//src/main/java/com/google/devtools/build/lib/analysis:provider_collection", "//src/main/java/com/google/devtools/build/lib/analysis:rule_definition_environment", 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 493a47781cae2a..f93a3bac935099 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 @@ -45,6 +45,7 @@ import com.google.devtools.build.lib.skyframe.serialization.DynamicCodec.FieldHandler; import com.google.devtools.build.lib.skyframe.serialization.SerializationContext; import com.google.devtools.build.lib.skyframe.serialization.SerializationException; +import com.google.devtools.build.lib.skyframe.serialization.autocodec.SerializationConstant; import com.google.devtools.build.lib.starlarkbuildapi.cpp.CcInfoApi; import com.google.devtools.build.lib.starlarkbuildapi.java.JavaInfoApi; import com.google.devtools.build.lib.starlarkbuildapi.java.JavaModuleFlagsProviderApi; @@ -66,14 +67,19 @@ /** A Starlark declared provider that encapsulates all providers that are needed by Java rules. */ @Immutable -public class JavaInfo extends NativeInfo - implements JavaInfoApi { +public sealed class JavaInfo extends NativeInfo + implements JavaInfoApi + permits JavaInfo.BuiltinsJavaInfo, JavaInfo.RulesJavaJavaInfo { 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(); - public static final JavaInfoProvider PROVIDER = new JavaInfoProvider(); + + @SerializationConstant public static final JavaInfoProvider PROVIDER = new JavaInfoProvider(); // Ideally we would check if the target has a JavaInfo, but this check predates the Starlark // sandwich and consumers depend on this returning `false` for java_binary/java_test targets. When @@ -137,7 +143,9 @@ static T nullIfNone(Object object, Class type) { return object != Starlark.NONE ? type.cast(object) : null; } - public static final JavaInfo EMPTY = JavaInfo.Builder.create().build(); + 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; @@ -504,7 +512,8 @@ public int hashCode() { providerJavaPlugin); } - private static class BuiltinsJavaInfo extends JavaInfo { + @VisibleForTesting // package-private for testing. + static final class BuiltinsJavaInfo extends JavaInfo { private BuiltinsJavaInfo(StructImpl javaInfo) throws EvalException, TypeException, RuleErrorException { @@ -545,7 +554,7 @@ public JavaInfoProvider getProvider() { } } - private static class RulesJavaJavaInfo extends JavaInfo { + static final class RulesJavaJavaInfo extends JavaInfo { private RulesJavaJavaInfo(StructImpl javaInfo) throws EvalException, TypeException, RuleErrorException { @@ -559,7 +568,7 @@ public JavaInfoProvider getProvider() { } /** Legacy Provider class for {@link JavaInfo} objects. */ - public static class BuiltinsJavaInfoProvider extends JavaInfoProvider { + public static final class BuiltinsJavaInfoProvider extends JavaInfoProvider { private BuiltinsJavaInfoProvider() { super( keyForBuiltins(Label.parseCanonicalUnchecked("@_builtins//:common/java/java_info.bzl"))); @@ -573,7 +582,7 @@ protected JavaInfo makeNewInstance(StructImpl info) } /** Legacy Provider class for {@link JavaInfo} objects. */ - public static class RulesJavaJavaInfoProvider extends JavaInfoProvider { + public static final class RulesJavaJavaInfoProvider extends JavaInfoProvider { private RulesJavaJavaInfoProvider() { super(keyForBuild(Label.parseCanonicalUnchecked("//java/private:java_info.bzl"))); } @@ -586,8 +595,8 @@ protected JavaInfo makeNewInstance(StructImpl info) } /** Provider class for {@link JavaInfo} objects. */ - public static class JavaInfoProvider extends StarlarkProviderWrapper - implements com.google.devtools.build.lib.packages.Provider { + public static sealed class JavaInfoProvider extends StarlarkProviderWrapper + implements Provider permits BuiltinsJavaInfoProvider, RulesJavaJavaInfoProvider { private JavaInfoProvider() { this( keyForBuild( @@ -795,6 +804,12 @@ 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 JavaInfoProvider unused -> codedOut.writeBoolNoTag(false); + } for (FieldHandler handler : handlers) { handler.serialize(context, codedOut, obj); } @@ -808,10 +823,14 @@ public DeferredValue deserializeDeferred( JavaInfo obj; try { - obj = (JavaInfo) unsafe().allocateInstance(JavaInfo.class); + obj = + codedIn.readBool() + ? (BuiltinsJavaInfo) unsafe().allocateInstance(BuiltinsJavaInfo.class) + : (JavaInfo) unsafe().allocateInstance(JavaInfo.class); } catch (InstantiationException e) { throw new SerializationException("Could not instantiate JavaInfo with Unsafe", e); } + for (FieldHandler handler : handlers) { handler.deserialize(context, codedIn, obj); } 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 2c77ff9ef5f119..99d1d67eb3cc56 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,6 +19,7 @@ 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; @@ -33,12 +34,24 @@ public class JavaInfoCodecTest extends BuildViewTestCase { @Test public void emptyJavaInfo_canBeSerializedAndDeserialized() throws Exception { - new SerializationTester(JavaInfo.EMPTY) + new SerializationTester(JavaInfo.EMPTY_JAVA_INFO_FOR_TESTING) .makeMemoizingAndAllowFutureBlocking(/* allowFutureBlocking= */ true) .setVerificationFunction((in, out) -> assertThat(in).isEqualTo(out)) .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/JavaInfoTest.java b/src/test/java/com/google/devtools/build/lib/rules/java/JavaInfoTest.java index 75db9cd3c643a6..753780cac7a52c 100644 --- a/src/test/java/com/google/devtools/build/lib/rules/java/JavaInfoTest.java +++ b/src/test/java/com/google/devtools/build/lib/rules/java/JavaInfoTest.java @@ -26,26 +26,27 @@ public class JavaInfoTest { @Test public void getTransitiveRuntimeJars_noJavaCompilationArgsProvider() { - assertThat(JavaInfo.EMPTY.getTransitiveRuntimeJars().isEmpty()).isTrue(); + assertThat(JavaInfo.EMPTY_JAVA_INFO_FOR_TESTING.getTransitiveRuntimeJars().isEmpty()).isTrue(); } @Test public void getTransitiveCompileTimeJarsJars_noJavaCompilationArgsProvider() { - assertThat(JavaInfo.EMPTY.getTransitiveCompileTimeJars().isEmpty()).isTrue(); + assertThat(JavaInfo.EMPTY_JAVA_INFO_FOR_TESTING.getTransitiveCompileTimeJars().isEmpty()) + .isTrue(); } @Test public void getCompileTimeJarsJars_noJavaCompilationArgsProvider() { - assertThat(JavaInfo.EMPTY.getCompileTimeJars().isEmpty()).isTrue(); + assertThat(JavaInfo.EMPTY_JAVA_INFO_FOR_TESTING.getCompileTimeJars().isEmpty()).isTrue(); } @Test public void getFullCompileTimeJarsJars_noJavaCompilationArgsProvider() { - assertThat(JavaInfo.EMPTY.getFullCompileTimeJars().isEmpty()).isTrue(); + assertThat(JavaInfo.EMPTY_JAVA_INFO_FOR_TESTING.getFullCompileTimeJars().isEmpty()).isTrue(); } @Test public void getSourceJars_noJavaSourceJarsProvider() { - assertThat(JavaInfo.EMPTY.getSourceJars()).isEmpty(); + assertThat(JavaInfo.EMPTY_JAVA_INFO_FOR_TESTING.getSourceJars()).isEmpty(); } } diff --git a/src/test/java/com/google/devtools/build/lib/rules/java/JavaStarlarkApiTest.java b/src/test/java/com/google/devtools/build/lib/rules/java/JavaStarlarkApiTest.java index 0b0a984ecd99c5..7d37df488b7ddf 100644 --- a/src/test/java/com/google/devtools/build/lib/rules/java/JavaStarlarkApiTest.java +++ b/src/test/java/com/google/devtools/build/lib/rules/java/JavaStarlarkApiTest.java @@ -4951,7 +4951,7 @@ def _impl(ctx): @Test public void testNativeJavaInfoPrintableType_isJavaInfo() { - String type = JavaStarlarkCommon.printableType(JavaInfo.EMPTY); + String type = JavaStarlarkCommon.printableType(JavaInfo.EMPTY_JAVA_INFO_FOR_TESTING); assertThat(type).isEqualTo("JavaInfo"); } From 41e676b67599b2e7dca5eb82a3950aadaeff0f64 Mon Sep 17 00:00:00 2001 From: Googler Date: Wed, 13 Nov 2024 01:38:46 -0800 Subject: [PATCH 07/15] Add the fourth (and last) variant of native Java provider wrappers for use in `WORKSPACE` mode PiperOrigin-RevId: 696033794 Change-Id: I0d49b21567a82f673694c558bbcb8a08950559f3 (cherry picked from commit 5b09ab62704e175649b6b3688473f10e56395d07) --- .../lib/rules/java/BootClassPathInfo.java | 13 ++++++ .../build/lib/rules/java/JavaInfo.java | 40 ++++++++++++++++++- .../build/lib/rules/java/JavaPluginInfo.java | 17 ++++++++ .../rules/java/JavaPluginsFlagAliasRule.java | 11 +++++ .../build/lib/rules/java/JavaRuntimeInfo.java | 12 ++++++ .../lib/rules/java/JavaToolchainProvider.java | 12 ++++++ 6 files changed, 103 insertions(+), 2 deletions(-) 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 47fcd79fa989d2..a95cde4c74b923 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 @@ -44,6 +44,8 @@ public class BootClassPathInfo extends StarlarkInfoWrapper { public static final StarlarkProviderWrapper PROVIDER = new Provider(); public static final StarlarkProviderWrapper RULES_JAVA_PROVIDER = new RulesJavaProvider(); + public static final StarlarkProviderWrapper WORKSPACE_PROVIDER = + new WorkspaceProvider(); private static final BootClassPathInfo EMPTY = new BootClassPathInfo(null) { @@ -89,6 +91,8 @@ public static BootClassPathInfo wrap(Info info) throws RuleErrorException { 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())) { + return WORKSPACE_PROVIDER.wrap(info); } else { throw new RuleErrorException("expected BootClassPathInfo, got: " + key); } @@ -139,6 +143,15 @@ private RulesJavaProvider() { } } + private static class WorkspaceProvider extends Provider { + private WorkspaceProvider() { + super( + keyForBuild( + Label.parseCanonicalUnchecked( + "@@rules_java//java/private:boot_class_path_info.bzl"))); + } + } + private static class Provider extends StarlarkProviderWrapper { private Provider() { this( 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 f93a3bac935099..7418bf4a6d7e53 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 @@ -69,7 +69,7 @@ @Immutable public sealed class JavaInfo extends NativeInfo implements JavaInfoApi - permits JavaInfo.BuiltinsJavaInfo, JavaInfo.RulesJavaJavaInfo { + permits JavaInfo.BuiltinsJavaInfo, JavaInfo.RulesJavaJavaInfo, JavaInfo.WorkspaceJavaInfo { public static final String STARLARK_NAME = "JavaInfo"; @@ -78,6 +78,8 @@ public sealed class JavaInfo extends NativeInfo // Not serialized public static final JavaInfoProvider RULES_JAVA_PROVIDER = new RulesJavaJavaInfoProvider(); + // Not serialized + public static final JavaInfoProvider WORKSPACE_PROVIDER = new WorkspaceJavaInfoProvider(); @SerializationConstant public static final JavaInfoProvider PROVIDER = new JavaInfoProvider(); @@ -222,6 +224,9 @@ public static JavaInfo getJavaInfo(TransitiveInfoCollection target) throws RuleE if (info == null) { info = target.get(RULES_JAVA_PROVIDER); } + if (info == null) { + info = target.get(WORKSPACE_PROVIDER); + } return info; } @@ -231,6 +236,8 @@ public static JavaInfo wrap(Info info) throws RuleErrorException { 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())) { + return WORKSPACE_PROVIDER.wrap(info); } else { return JavaInfo.PROVIDER.wrap(info); } @@ -567,6 +574,19 @@ public JavaInfoProvider getProvider() { } } + static final class WorkspaceJavaInfo extends JavaInfo { + + private WorkspaceJavaInfo(StructImpl javaInfo) + throws EvalException, TypeException, RuleErrorException { + super(javaInfo); + } + + @Override + public JavaInfoProvider getProvider() { + return WORKSPACE_PROVIDER; + } + } + /** Legacy Provider class for {@link JavaInfo} objects. */ public static final class BuiltinsJavaInfoProvider extends JavaInfoProvider { private BuiltinsJavaInfoProvider() { @@ -594,9 +614,23 @@ protected JavaInfo makeNewInstance(StructImpl info) } } + /** Legacy Provider class for {@link JavaInfo} objects in WORKSPACE mode. */ + public static final class WorkspaceJavaInfoProvider extends JavaInfoProvider { + private WorkspaceJavaInfoProvider() { + super(keyForBuild(Label.parseCanonicalUnchecked("@@rules_java//java/private:java_info.bzl"))); + } + + @Override + protected JavaInfo makeNewInstance(StructImpl info) + throws RuleErrorException, TypeException, EvalException { + return new WorkspaceJavaInfo(info); + } + } + /** Provider class for {@link JavaInfo} objects. */ public static sealed class JavaInfoProvider extends StarlarkProviderWrapper - implements Provider permits BuiltinsJavaInfoProvider, RulesJavaJavaInfoProvider { + implements Provider + permits BuiltinsJavaInfoProvider, RulesJavaJavaInfoProvider, WorkspaceJavaInfoProvider { private JavaInfoProvider() { this( keyForBuild( @@ -808,6 +842,8 @@ public void serialize(SerializationContext context, JavaInfo obj, CodedOutputStr 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) { 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 d160613c27e5b1..4652ea8d512e93 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 @@ -53,6 +53,7 @@ public abstract class JavaPluginInfo extends NativeInfo 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( @@ -69,8 +70,14 @@ public abstract class JavaPluginInfo extends NativeInfo new AutoValue_JavaPluginInfo( ImmutableList.of(), JavaPluginData.empty(), JavaPluginData.empty(), RULES_JAVA_PROVIDER); + private static final JavaPluginInfo EMPTY_WORKSPACE = + new AutoValue_JavaPluginInfo( + 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 { @@ -80,6 +87,7 @@ public static JavaPluginInfo wrap(Info info) throws RuleErrorException { @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) { @@ -110,6 +118,13 @@ private RulesJavaProvider() { } } + /** Provider class for {@link JavaPluginInfo} objects in WORKSPACE mode. */ + public static class WorkspaceProvider extends Provider { + private WorkspaceProvider() { + super(keyForBuild(Label.parseCanonicalUnchecked("@@rules_java//java/private:java_info.bzl"))); + } + } + /** Provider class for {@link JavaPluginInfo} objects. */ public static class Provider extends StarlarkProviderWrapper implements com.google.devtools.build.lib.packages.Provider { @@ -279,6 +294,8 @@ public static JavaPluginInfo empty(com.google.devtools.build.lib.packages.Provid return EMPTY_BUILTIN; } else if (providerType.equals(RULES_JAVA_PROVIDER)) { return EMPTY_RULES_JAVA; + } else if (providerType.equals(WORKSPACE_PROVIDER)) { + return EMPTY_WORKSPACE; } return EMPTY; } 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 571f66e683ad3f..6690d848d64cee 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 @@ -53,6 +53,8 @@ public RuleClass build(RuleClass.Builder builder, RuleDefinitionEnvironment envi .mandatoryProvidersList( 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()))) .silentRuleClassFilter() .value(JavaSemantics.JAVA_PLUGINS)) @@ -98,17 +100,26 @@ public ConfiguredTarget create(RuleContext ruleContext) .getRulePrerequisitesCollection() .getPrerequisites(":java_plugins", JavaPluginInfo.RULES_JAVA_PROVIDER); } + if (plugins.isEmpty()) { + plugins = + ruleContext + .getRulePrerequisitesCollection() + .getPrerequisites(":java_plugins", JavaPluginInfo.WORKSPACE_PROVIDER); + } 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 = + JavaPluginInfo.mergeWithoutJavaOutputs(plugins, JavaPluginInfo.WORKSPACE_PROVIDER); return new RuleConfiguredTargetBuilder(ruleContext) .addStarlarkDeclaredProvider(javaPluginInfo) .addStarlarkDeclaredProvider(builtinsProviderInfo) .addStarlarkDeclaredProvider(rulesJavaProviderInfo) + .addStarlarkDeclaredProvider(workspaceProviderInfo) .addProvider(RunfilesProvider.class, RunfilesProvider.EMPTY) .build(); } 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 7fb91641f781ce..cd4208d186eaed 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 @@ -50,6 +50,8 @@ public final class JavaRuntimeInfo extends StarlarkInfoWrapper { new BuiltinsProvider(); public static final StarlarkProviderWrapper RULES_JAVA_PROVIDER = new RulesJavaProvider(); + public static final StarlarkProviderWrapper WORKSPACE_PROVIDER = + new WorkspaceProvider(); public static final StarlarkProviderWrapper PROVIDER = new Provider(); // Helper methods to access an instance of JavaRuntimeInfo. @@ -106,6 +108,8 @@ public static JavaRuntimeInfo wrap(Info info) throws RuleErrorException { 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())) { + return WORKSPACE_PROVIDER.wrap(info); } else { throw new RuleErrorException("expected JavaRuntimeInfo, got: " + key); } @@ -160,6 +164,14 @@ private RulesJavaProvider() { } } + private static class WorkspaceProvider extends Provider { + private WorkspaceProvider() { + super( + keyForBuild( + Label.parseCanonicalUnchecked("@@rules_java//java/common/rules:java_runtime.bzl"))); + } + } + private static class Provider extends StarlarkProviderWrapper { private Provider() { 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 bf4c85557aa8ca..c768203b845979 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 @@ -55,6 +55,8 @@ public final class JavaToolchainProvider extends StarlarkInfoWrapper { new BuiltinsProvider(); public static final StarlarkProviderWrapper RULES_JAVA_PROVIDER = new RulesJavaProvider(); + public static final StarlarkProviderWrapper WORKSPACE_PROVIDER = + new WorkspaceProvider(); public static final StarlarkProviderWrapper PROVIDER = new Provider(); private JavaToolchainProvider(StarlarkInfo underlying) { @@ -69,6 +71,8 @@ public static JavaToolchainProvider wrap(Info info) throws RuleErrorException { 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())) { + return WORKSPACE_PROVIDER.wrap(info); } else { throw new RuleErrorException("expected JavaToolchainInfo, got: " + key); } @@ -331,6 +335,14 @@ private RulesJavaProvider() { } } + private static class WorkspaceProvider extends Provider { + private WorkspaceProvider() { + super( + keyForBuild( + Label.parseCanonicalUnchecked("@@rules_java//java/common/rules:java_toolchain.bzl"))); + } + } + private static class Provider extends StarlarkProviderWrapper { private Provider() { this( From e16eeeb0eefccf78af78d2151778e5e193d43c05 Mon Sep 17 00:00:00 2001 From: Googler Date: Thu, 14 Nov 2024 06:12:40 -0800 Subject: [PATCH 08/15] Prepare tests for moving the Java providers & toolchain rules out of `@_builtins` Mostly just adds `load` statements everywhere. PiperOrigin-RevId: 696496082 Change-Id: I5dfc4a58c2c9dffd144b2488fd33a8e665b88db1 (cherry picked from commit 00c1b7bdce21bdb1db76d63729b28adda610c16e) --- .../JavaPackageConfigurationProvider.java | 41 +++++++++-- .../lib/analysis/AutoExecGroupsTest.java | 16 +++-- .../android/AndroidStarlarkCommonTest.java | 2 + .../lib/rules/java/JavaInfoRoundtripTest.java | 1 + .../rules/java/JavaInfoStarlarkApiTest.java | 4 +- .../lib/rules/java/JavaStarlarkApiTest.java | 71 ++++++++++++++++--- .../StarlarkJavaLiteProtoLibraryTest.java | 1 + .../integration/java_integration_test.sh | 3 + 8 files changed, 118 insertions(+), 21 deletions(-) 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 8bfde1f35618cc..c34fab31afcc60 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 @@ -14,10 +14,13 @@ 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; import com.google.devtools.build.lib.actions.Artifact; +import com.google.devtools.build.lib.analysis.ConfiguredTarget; import com.google.devtools.build.lib.analysis.PackageSpecificationProvider; import com.google.devtools.build.lib.cmdline.Label; import com.google.devtools.build.lib.collect.nestedset.Depset; @@ -28,6 +31,7 @@ import com.google.devtools.build.lib.packages.RuleClass.ConfiguredTargetFactory.RuleErrorException; import com.google.devtools.build.lib.packages.StarlarkProviderWrapper; import com.google.devtools.build.lib.packages.StructImpl; +import com.google.devtools.build.lib.skyframe.BzlLoadValue; import net.starlark.java.eval.EvalException; import net.starlark.java.eval.Sequence; import net.starlark.java.eval.Starlark; @@ -37,8 +41,10 @@ @Immutable public final class JavaPackageConfigurationProvider implements StarlarkValue { - public static final StarlarkProviderWrapper PROVIDER = + private static final StarlarkProviderWrapper PROVIDER = new Provider(); + private static final StarlarkProviderWrapper BUILTINS_PROVIDER = + new BuiltinsProvider(); private final StructImpl underlying; @@ -46,6 +52,16 @@ private JavaPackageConfigurationProvider(StructImpl underlying) { this.underlying = 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; + } + /** Package specifications for which the configuration should be applied. */ private ImmutableList packageSpecifications() throws RuleErrorException { @@ -96,11 +112,15 @@ public boolean matches(Label label) throws RuleErrorException { private static class Provider extends StarlarkProviderWrapper { private Provider() { - super( - keyForBuiltins( + this( + keyForBuild( Label.parseCanonicalUnchecked( - "@_builtins//:common/java/java_package_configuration.bzl")), - "JavaPackageConfigurationInfo"); + JavaSemantics.RULES_JAVA_PROVIDER_LABELS_PREFIX + + "java/common/rules:java_package_configuration.bzl"))); + } + + private Provider(BzlLoadValue.Key key) { + super(key, "JavaPackageConfigurationInfo"); } @Override @@ -115,10 +135,21 @@ 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(); for (StructImpl struct : sequence) { + // this result isn't propagated back to Starlark so we just need any type builder.add(PROVIDER.wrap(struct)); } return builder.build(); diff --git a/src/test/java/com/google/devtools/build/lib/analysis/AutoExecGroupsTest.java b/src/test/java/com/google/devtools/build/lib/analysis/AutoExecGroupsTest.java index 9c19232ec688fd..5ee06d3fa81b80 100644 --- a/src/test/java/com/google/devtools/build/lib/analysis/AutoExecGroupsTest.java +++ b/src/test/java/com/google/devtools/build/lib/analysis/AutoExecGroupsTest.java @@ -1262,7 +1262,7 @@ public void customExecGroupsAndToolchain_notCompatibleError(String action) throw """); scratch.file( "test/defs.bzl", - "load('@rules_java//java:defs.bzl', 'java_common')", + "load('@rules_java//java:defs.bzl', 'java_common', 'JavaInfo')", "def _impl(ctx):", " output_jar = ctx.actions.declare_file('lib_' + ctx.label.name + '.jar')", " java_info = java_common.compile(", @@ -1375,7 +1375,8 @@ public void javaCommonCompile_automaticExecGroupsEnabled_javaInfoActionsExecuteO throws Exception { scratch.file( "test/defs.bzl", - "load('@rules_java//java:defs.bzl', 'java_common')", + "load('@rules_java//java:defs.bzl'," + + " 'java_common', 'JavaInfo', 'JavaPluginInfo')", "def _impl(ctx):", " output_jar = ctx.actions.declare_file('lib_' + ctx.label.name + '.jar')", " java_info = java_common.compile(", @@ -1432,7 +1433,8 @@ public void javaCommonCompile_automaticExecGroupsDisabled_javaInfoActionsExecute throws Exception { scratch.file( "test/defs.bzl", - "load('@rules_java//java:defs.bzl', 'java_common')", + "load('@rules_java//java:defs.bzl'," + + " 'java_common', 'JavaInfo', 'JavaPluginInfo')", "def _impl(ctx):", " output_jar = ctx.actions.declare_file('lib_' + ctx.label.name + '.jar')", " java_info = java_common.compile(", @@ -1489,7 +1491,7 @@ public void javaCommonCompile_automaticExecGroupsEnabled_lazyActionExecutesOnFir throws Exception { scratch.file( "test/defs.bzl", - "load('@rules_java//java:defs.bzl', 'java_common')", + "load('@rules_java//java:defs.bzl', 'java_common', 'JavaInfo')", "def _impl(ctx):", " output_jar = ctx.actions.declare_file('lib_' + ctx.label.name + '.jar')", " java_info = java_common.compile(", @@ -1533,7 +1535,7 @@ public void javaCommonCompile_automaticExecGroupsDisabled_lazyActionExecutesOnSe throws Exception { scratch.file( "test/defs.bzl", - "load('@rules_java//java:defs.bzl', 'java_common')", + "load('@rules_java//java:defs.bzl', 'java_common', 'JavaInfo')", "def _impl(ctx):", " output_jar = ctx.actions.declare_file('lib_' + ctx.label.name + '.jar')", " java_info = java_common.compile(", @@ -1578,7 +1580,7 @@ public void javaCommonCompile_automaticExecGroupsDisabled_lazyActionExecutesOnSe throws Exception { scratch.file( "bazel_internal/test_rules/defs.bzl", - "load('@rules_java//java:defs.bzl', 'java_common')", + "load('@rules_java//java:defs.bzl', 'java_common', 'JavaInfo')", "def _impl(ctx):", " output_jar = ctx.actions.declare_file('lib_' + ctx.label.name + '.jar')", " java_info = java_common.compile(", @@ -1627,7 +1629,7 @@ public void javaCommonCompile_automaticExecGroupsDisabled_lazyActionExecutesOnSe throws Exception { scratch.file( "bazel_internal/test_rules/defs.bzl", - "load('@rules_java//java:defs.bzl', 'java_common')", + "load('@rules_java//java:defs.bzl', 'java_common', 'JavaInfo')", "def _impl(ctx):", " output_jar = ctx.actions.declare_file('lib_' + ctx.label.name + '.jar')", " java_info = java_common.compile(", diff --git a/src/test/java/com/google/devtools/build/lib/rules/android/AndroidStarlarkCommonTest.java b/src/test/java/com/google/devtools/build/lib/rules/android/AndroidStarlarkCommonTest.java index ec02462f8ac8ae..d3391250f1a71f 100644 --- a/src/test/java/com/google/devtools/build/lib/rules/android/AndroidStarlarkCommonTest.java +++ b/src/test/java/com/google/devtools/build/lib/rules/android/AndroidStarlarkCommonTest.java @@ -39,6 +39,8 @@ public void enableImplicitSourcelessDepsExportsCompatibilityTest() throws Except scratch.file( "java/android/compatible.bzl", """ + load("@rules_java//java/common:java_info.bzl", "JavaInfo") + def _impl(ctx): return [ android_common.enable_implicit_sourceless_deps_exports_compatibility( diff --git a/src/test/java/com/google/devtools/build/lib/rules/java/JavaInfoRoundtripTest.java b/src/test/java/com/google/devtools/build/lib/rules/java/JavaInfoRoundtripTest.java index ac2e4ac0889d0f..402656b11794ed 100644 --- a/src/test/java/com/google/devtools/build/lib/rules/java/JavaInfoRoundtripTest.java +++ b/src/test/java/com/google/devtools/build/lib/rules/java/JavaInfoRoundtripTest.java @@ -53,6 +53,7 @@ public void javaInfoToDict() throws Exception { scratch.file( "javainfo/javainfo_to_dict.bzl", """ + load("@rules_java//java/common:java_info.bzl", "JavaInfo") load("//tools/build_defs/inspect:struct_to_dict.bzl", "struct_to_dict") Info = provider() def _impl(ctx): 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 59fbae4d287559..6f3f05d33039e5 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 @@ -1236,6 +1236,7 @@ public void javaOutputSourceJarsReturnsDepsetWithIncompatibleFlagEnabled() throw scratch.file( "foo/extension.bzl", """ + load("@rules_java//java/common:java_info.bzl", "JavaInfo") MyInfo = provider() def _impl(ctx): @@ -1536,7 +1537,8 @@ private String[] newJavaInfo() { assertThat(useIJar && stampJar).isFalse(); ImmutableList.Builder lines = ImmutableList.builder(); lines.add( - "load('@rules_java//java:defs.bzl', 'java_common')", + "load('@rules_java//java:defs.bzl', 'java_common', 'JavaInfo'," + + " 'JavaPluginInfo')", "result = provider()", "def _impl(ctx):", " ctx.actions.write(ctx.outputs.output_jar, 'JavaInfo API Test', is_executable=False) ", diff --git a/src/test/java/com/google/devtools/build/lib/rules/java/JavaStarlarkApiTest.java b/src/test/java/com/google/devtools/build/lib/rules/java/JavaStarlarkApiTest.java index 7d37df488b7ddf..174ae0dbcf394c 100644 --- a/src/test/java/com/google/devtools/build/lib/rules/java/JavaStarlarkApiTest.java +++ b/src/test/java/com/google/devtools/build/lib/rules/java/JavaStarlarkApiTest.java @@ -135,6 +135,7 @@ public void testJavaRuntimeProviderJavaAbsolute() throws Exception { "a/rule.bzl", """ load("//myinfo:myinfo.bzl", "MyInfo") + load("@rules_java//java/common:java_common.bzl", "java_common") def _impl(ctx): provider = ctx.attr._java_runtime[java_common.JavaRuntimeInfo] @@ -185,6 +186,7 @@ public void testJavaRuntimeProviderJavaHermetic() throws Exception { "a/rule.bzl", """ load("//myinfo:myinfo.bzl", "MyInfo") + load("@rules_java//java/common:java_common.bzl", "java_common") def _impl(ctx): provider = ctx.attr._java_runtime[java_common.JavaRuntimeInfo] @@ -236,6 +238,7 @@ public void testJavaRuntimeProviderJavaGenerated() throws Exception { "a/rule.bzl", """ load("//myinfo:myinfo.bzl", "MyInfo") + load("@rules_java//java/common:java_common.bzl", "java_common") def _impl(ctx): provider = ctx.attr._java_runtime[java_common.JavaRuntimeInfo] @@ -286,6 +289,7 @@ public void testExposesJavaCommonProvider() throws Exception { scratch.file( "java/test/extension.bzl", """ + load("@rules_java//java/common:java_common.bzl", "java_common") result = provider() def impl(ctx): @@ -364,6 +368,8 @@ public void javaPlugin_exposesJavaOutputs() throws Exception { scratch.file( "java/test/extension.bzl", """ + load("@rules_java//java/common:java_plugin_info.bzl", + "JavaPluginInfo") result = provider() def impl(ctx): @@ -409,6 +415,7 @@ public void javaToolchainInfo_jacocoRunnerAttribute() throws Exception { scratch.file( "java/test/custom_rule.bzl", """ + load("@rules_java//java/common:java_common.bzl", "java_common") def _impl(ctx): jacoco = ctx.attr._java_toolchain[java_common.JavaToolchainInfo].jacocorunner return [ @@ -456,6 +463,7 @@ public void testJavaCommonCompileExposesOutputJarProvider() throws Exception { scratch.file( "java/test/extension.bzl", """ + load("@rules_java//java/common:java_common.bzl", "java_common") result = provider() def impl(ctx): @@ -473,6 +481,7 @@ def impl(ctx): """); scratch.file( "java/test/custom_rule.bzl", + "load('@rules_java//java/common:java_common.bzl', 'java_common')", "def _impl(ctx):", " output_jar = ctx.actions.declare_file('lib' + ctx.label.name + '.jar')", " compilation_provider = java_common.compile(", @@ -554,6 +563,8 @@ public void javaCommonCompile_setsRuntimeDeps() throws Exception { """); scratch.file( "java/test/custom_rule.bzl", + "load('@rules_java//java/common:java_common.bzl', 'java_common')", + "load('@rules_java//java/common:java_info.bzl', 'JavaInfo')", "def _impl(ctx):", " output_jar = ctx.actions.declare_file('lib' + ctx.label.name + '.jar')", " deps = [dep[JavaInfo] for dep in ctx.attr.deps]", @@ -628,7 +639,8 @@ public void testJavaCommonCompileExposesAnnotationProcessingInfo() throws Except JavaTestUtil.writeBuildFileForJavaToolchain(scratch); scratch.file( "java/test/custom_rule.bzl", - "load('@rules_java//java:defs.bzl', 'java_common')", + "load('@rules_java//java:defs.bzl', 'java_common', 'JavaInfo'," + + " 'JavaPluginInfo')", "def _impl(ctx):", " output_jar = ctx.actions.declare_file('lib' + ctx.label.name + '.jar')", " return java_common.compile(", @@ -670,7 +682,7 @@ public void javaCommonCompile_requiresJavaPluginInfo() throws Exception { JavaTestUtil.writeBuildFileForJavaToolchain(scratch); scratch.file( "java/test/custom_rule.bzl", - "load('@rules_java//java:defs.bzl', 'java_common')", + "load('@rules_java//java:defs.bzl', 'java_common', 'JavaInfo')", "def _impl(ctx):", " output_jar = ctx.actions.declare_file('lib' + ctx.label.name + '.jar')", " return java_common.compile(", @@ -1172,6 +1184,7 @@ private void testAnnotationProcessingInfoIsStarlarkAccessible( scratch.file( "java/test/extension.bzl", """ + load("@rules_java//java/common:java_info.bzl", "JavaInfo") result = provider() def impl(ctx): @@ -1259,6 +1272,7 @@ private JavaPluginData retrieveStarlarkPluginData( String pkg = apiGenerating ? "java/getplugininfo" : "java/getapiplugininfo"; scratch.file( pkg + "/extension.bzl", + "load('@rules_java//java:defs.bzl', 'JavaInfo', 'JavaPluginInfo')", "result = provider()", "def impl(ctx):", " depj = ctx.attr.dep[" + provider + "]", @@ -1436,6 +1450,9 @@ public void javaPluginInfo_create() throws Exception { scratch.file( "java/test/myplugin.bzl", """ + load("@rules_java//java/common:java_info.bzl", "JavaInfo") + load("@rules_java//java/common:java_plugin_info.bzl", + "JavaPluginInfo") def _impl(ctx): output_jar = ctx.actions.declare_file("lib.jar") ctx.actions.write(output_jar, "") @@ -1499,6 +1516,9 @@ public void javaPluginInfo_createApiPlugin() throws Exception { scratch.file( "java/test/myplugin.bzl", """ + load("@rules_java//java/common:java_info.bzl", "JavaInfo") + load("@rules_java//java/common:java_plugin_info.bzl", + "JavaPluginInfo") def _impl(ctx): output_jar = ctx.actions.declare_file("lib.jar") ctx.actions.write(output_jar, "") @@ -1562,6 +1582,9 @@ public void javaPluginInfo_createWithoutProcessorClass() throws Exception { scratch.file( "java/test/myplugin.bzl", """ + load("@rules_java//java/common:java_info.bzl", "JavaInfo") + load("@rules_java//java/common:java_plugin_info.bzl", + "JavaPluginInfo") def _impl(ctx): output_jar = ctx.actions.declare_file("lib.jar") ctx.actions.write(output_jar, "") @@ -1623,6 +1646,9 @@ public void javaPluginInfo_createWithDataDepset() throws Exception { scratch.file( "java/test/myplugin.bzl", """ + load("@rules_java//java/common:java_info.bzl", "JavaInfo") + load("@rules_java//java/common:java_plugin_info.bzl", + "JavaPluginInfo") def _impl(ctx): output_jar = ctx.actions.declare_file("lib.jar") ctx.actions.write(output_jar, "") @@ -1688,6 +1714,7 @@ public void testJavaProviderFieldsAreStarlarkAccessible() throws Exception { scratch.file( "java/test/extension.bzl", """ + load("@rules_java//java/common:java_info.bzl", "JavaInfo") result = provider() def impl(ctx): @@ -1768,6 +1795,7 @@ public void javaProviderExposedOnJavaLibrary() throws Exception { scratch.file( "foo/extension.bzl", """ + load("@rules_java//java/common:java_info.bzl", "JavaInfo") my_provider = provider() def _impl(ctx): @@ -1812,6 +1840,7 @@ public void javaProviderPropagation() throws Exception { scratch.file( "foo/extension.bzl", """ + load("@rules_java//java/common:java_info.bzl", "JavaInfo") def _impl(ctx): dep_params = ctx.attr.dep[JavaInfo] return [dep_params] @@ -1866,6 +1895,7 @@ public void starlarkJavaToJavaLibraryAttributes() throws Exception { scratch.file( "foo/extension.bzl", """ + load("@rules_java//java/common:java_info.bzl", "JavaInfo") def _impl(ctx): dep_params = ctx.attr.dep[JavaInfo] return [dep_params] @@ -1953,6 +1983,7 @@ public void starlarkJavaToJavaBinaryAttributes() throws Exception { scratch.file( "foo/extension.bzl", """ + load("@rules_java//java/common:java_info.bzl", "JavaInfo") def _impl(ctx): dep_params = ctx.attr.dep[JavaInfo] return [dep_params] @@ -2012,6 +2043,7 @@ public void starlarkJavaToJavaImportAttributes() throws Exception { scratch.file( "foo/extension.bzl", """ + load("@rules_java//java/common:java_info.bzl", "JavaInfo") def _impl(ctx): dep_params = ctx.attr.dep[JavaInfo] return [dep_params] @@ -2066,6 +2098,7 @@ public void testJavaInfoSequenceParametersTypeChecked() throws Exception { scratch.file( "foo/bad_rules.bzl", """ + load("@rules_java//java/common:java_info.bzl", "JavaInfo") def make_file(ctx): f = ctx.actions.declare_file("out") ctx.actions.write(f, "out") @@ -2121,6 +2154,7 @@ public void javaInfo_compileJarSet() throws Exception { scratch.file( "foo/javainfo_rules.bzl", """ + load("@rules_java//java/common:java_info.bzl", "JavaInfo") def make_file(ctx): f = ctx.actions.declare_file("out") ctx.actions.write(f, "out") @@ -2149,6 +2183,7 @@ public void javaInfo_compileJarNotSet() throws Exception { scratch.file( "foo/javainfo_rules.bzl", """ + load("@rules_java//java/common:java_info.bzl", "JavaInfo") def make_file(ctx): f = ctx.actions.declare_file("out") ctx.actions.write(f, "out") @@ -2176,6 +2211,7 @@ public void javaInfo_compileJarSetToNone() throws Exception { scratch.file( "foo/javainfo_rules.bzl", """ + load("@rules_java//java/common:java_info.bzl", "JavaInfo") def make_file(ctx): f = ctx.actions.declare_file("out") ctx.actions.write(f, "out") @@ -2205,6 +2241,7 @@ public void javaInfoSourceJarsExposed() throws Exception { scratch.file( "foo/extension.bzl", """ + load("@rules_java//java/common:java_info.bzl", "JavaInfo") result = provider() def _impl(ctx): @@ -2253,6 +2290,7 @@ public void testJavaInfoGetTransitiveSourceJars() throws Exception { scratch.file( "foo/extension.bzl", """ + load("@rules_java//java/common:java_info.bzl", "JavaInfo") result = provider() def _impl(ctx): @@ -2311,6 +2349,7 @@ public void testJavaInfoGetTransitiveDeps() throws Exception { scratch.file( "foo/extension.bzl", """ + load("@rules_java//java/common:java_info.bzl", "JavaInfo") result = provider() def _impl(ctx): @@ -2369,6 +2408,7 @@ public void testJavaInfoGetTransitiveRuntimeDeps() throws Exception { scratch.file( "foo/extension.bzl", """ + load("@rules_java//java/common:java_info.bzl", "JavaInfo") result = provider() def _impl(ctx): @@ -2426,6 +2466,7 @@ public void javaInfo_getTransitiveNativeLibraries() throws Exception { scratch.file( "foo/extension.bzl", """ + load("@rules_java//java/common:java_info.bzl", "JavaInfo") result = provider() def _impl(ctx): @@ -2705,6 +2746,7 @@ public void javaLibrary_exposesNativeLibraryInfoToStarlark() throws Exception { scratch.file( "foo/extension.bzl", """ + load("@rules_java//java/common:java_info.bzl", "JavaInfo") my_provider = provider() def _impl(ctx): @@ -2811,6 +2853,7 @@ public void javaInfo_nativeLibrariesPropagate() throws Exception { scratch.file( "java/test/custom_rule.bzl", """ + load("@rules_java//java/common:java_info.bzl", "JavaInfo") def _impl(ctx): output_jar = ctx.actions.declare_file("lib" + ctx.label.name + ".jar") ctx.actions.write(output_jar, "") @@ -2858,6 +2901,7 @@ public void testJavaInfoGetGenJarsProvider() throws Exception { scratch.file( "foo/extension.bzl", """ + load("@rules_java//java/common:java_info.bzl", "JavaInfo") result = provider() def _impl(ctx): @@ -2904,6 +2948,7 @@ public void javaInfoGetCompilationInfoProvider() throws Exception { scratch.file( "foo/extension.bzl", """ + load("@rules_java//java/common:java_info.bzl", "JavaInfo") result = provider() def _impl(ctx): @@ -2953,6 +2998,7 @@ public void javaInfoStarlarkCompilationInfoJavacOpts() throws Exception { scratch.file( "foo/extension.bzl", """ + load("@rules_java//java/common:java_info.bzl", "JavaInfo") result = provider() def _impl(ctx): @@ -3157,7 +3203,7 @@ public void javaCommonCompileWithNeverlink() throws Exception { """); scratch.file( "java/test/custom_rule.bzl", - "load('@rules_java//java:defs.bzl', 'java_common')", + "load('@rules_java//java:defs.bzl', 'java_common', 'JavaInfo')", "def _impl(ctx):", " output_jar = ctx.actions.declare_file('lib' + ctx.label.name + '.jar')", " java_info = java_common.compile(", @@ -3243,7 +3289,7 @@ public void javaCommonCompile_nativeLibrariesPropagate() throws Exception { """); scratch.file( "java/test/custom_rule.bzl", - "load('@rules_java//java:defs.bzl', 'java_common')", + "load('@rules_java//java:defs.bzl', 'java_common', 'JavaInfo')", "def _impl(ctx):", " output_jar = ctx.actions.declare_file('lib' + ctx.label.name + '.jar')", " compilation_provider = java_common.compile(", @@ -3352,6 +3398,7 @@ public void strictDepsEnabled() throws Exception { "foo/custom_library.bzl", """ load("@rules_java//java:defs.bzl", "java_common") + load("@rules_java//java/common:java_info.bzl", "JavaInfo") def _impl(ctx): java_provider = java_common.merge([dep[JavaInfo] for dep in ctx.attr.deps]) if not ctx.attr.strict_deps: @@ -3404,6 +3451,7 @@ public void strictDepsDisabled() throws Exception { "foo/custom_library.bzl", """ load("@rules_java//java:defs.bzl", "java_common") + load("@rules_java//java/common:java_info.bzl", "JavaInfo") def _impl(ctx): java_provider = java_common.merge([dep[JavaInfo] for dep in ctx.attr.deps]) if not ctx.attr.strict_deps: @@ -3518,6 +3566,7 @@ public void mergeRuntimeOutputJarsTest() throws Exception { "foo/custom_library.bzl", """ load("@rules_java//java:defs.bzl", "java_common") + load("@rules_java//java/common:java_info.bzl", "JavaInfo") def _impl(ctx): java_provider = java_common.merge([dep[JavaInfo] for dep in ctx.attr.deps]) return [java_provider] @@ -3784,7 +3833,7 @@ public void testCompileWithNeverlinkDeps() throws Exception { JavaTestUtil.writeBuildFileForJavaToolchain(scratch); scratch.file( "foo/java_custom_library.bzl", - "load('@rules_java//java:defs.bzl', 'java_common')", + "load('@rules_java//java:defs.bzl', 'java_common', 'JavaInfo')", "def _impl(ctx):", " output_jar = ctx.actions.declare_file('lib%s.jar' % ctx.label.name)", " deps = [deps[JavaInfo] for deps in ctx.attr.deps]", @@ -3840,7 +3889,7 @@ public void testCompileOutputJarNotInRuntimePathWithoutAnySourcesDefined() throw JavaTestUtil.writeBuildFileForJavaToolchain(scratch); scratch.file( "foo/java_custom_library.bzl", - "load('@rules_java//java:defs.bzl', 'java_common')", + "load('@rules_java//java:defs.bzl', 'java_common', 'JavaInfo')", "def _impl(ctx):", " output_jar = ctx.actions.declare_file('lib%s.jar' % ctx.label.name)", " exports = [export[JavaInfo] for export in ctx.attr.exports]", @@ -4083,6 +4132,7 @@ public void testJavaRuntimeProviderFiles() throws Exception { scratch.file( "a/rule.bzl", """ + load("@rules_java//java/common:java_common.bzl", "java_common") def _impl(ctx): provider = ctx.attr._java_runtime[java_common.JavaRuntimeInfo] return DefaultInfo( @@ -4130,7 +4180,8 @@ public void testSkipAnnotationProcessing() throws Exception { JavaTestUtil.writeBuildFileForJavaToolchain(scratch); scratch.file( "foo/custom_rule.bzl", - "load('@rules_java//java:defs.bzl', 'java_common')", + "load('@rules_java//java:defs.bzl', 'java_common', 'JavaInfo'," + + " 'JavaPluginInfo')", "def _impl(ctx):", " output_jar = ctx.actions.declare_file('lib' + ctx.label.name + '.jar')", " compilation_provider = java_common.compile(", @@ -4642,7 +4693,7 @@ public void mergeAddExports() throws Exception { scratch.file( "foo/custom_library.bzl", """ - load("@rules_java//java:defs.bzl", "java_common") + load("@rules_java//java:defs.bzl", "java_common", "JavaInfo") def _impl(ctx): java_provider = java_common.merge([dep[JavaInfo] for dep in ctx.attr.deps]) return [java_provider] @@ -4710,6 +4761,7 @@ public void hermeticStaticLibs() throws Exception { "a/rule.bzl", """ load("//myinfo:myinfo.bzl", "MyInfo") + load("@rules_java//java/common:java_common.bzl", "java_common") def _impl(ctx): provider = ctx.attr._java_runtime[java_common.JavaRuntimeInfo] @@ -4764,6 +4816,7 @@ public void implicitLibCtSym() throws Exception { "a/rule.bzl", """ load("//myinfo:myinfo.bzl", "MyInfo") + load("@rules_java//java/common:java_common.bzl", "java_common") def _impl(ctx): provider = ctx.attr._java_runtime[java_common.JavaRuntimeInfo] @@ -4814,6 +4867,7 @@ public void explicitLibCtSym() throws Exception { "a/rule.bzl", """ load("//myinfo:myinfo.bzl", "MyInfo") + load("@rules_java//java/common:java_common.bzl", "java_common") def _impl(ctx): provider = ctx.attr._java_runtime[java_common.JavaRuntimeInfo] @@ -4919,6 +4973,7 @@ public void testProviderValidationPrintsProviderName() throws Exception { scratch.file( "foo/rule.bzl", """ + load("@rules_java//java/common:java_info.bzl", "JavaInfo") def _impl(ctx): cc_info = ctx.attr.dep[CcInfo] JavaInfo(output_jar = None, compile_jar = None, deps = [cc_info]) diff --git a/src/test/java/com/google/devtools/build/lib/rules/java/proto/StarlarkJavaLiteProtoLibraryTest.java b/src/test/java/com/google/devtools/build/lib/rules/java/proto/StarlarkJavaLiteProtoLibraryTest.java index c0016454f5b1ce..00153cadc674d9 100644 --- a/src/test/java/com/google/devtools/build/lib/rules/java/proto/StarlarkJavaLiteProtoLibraryTest.java +++ b/src/test/java/com/google/devtools/build/lib/rules/java/proto/StarlarkJavaLiteProtoLibraryTest.java @@ -391,6 +391,7 @@ public void testJavaProtosExposeStarlarkProviders() throws Exception { scratch.file( "proto/extensions.bzl", """ + load("@rules_java//java/common:java_info.bzl", "JavaInfo") def _impl(ctx): print(ctx.attr.dep[JavaInfo]) diff --git a/src/test/shell/integration/java_integration_test.sh b/src/test/shell/integration/java_integration_test.sh index f51325a1d96d1f..8a99009387d4da 100755 --- a/src/test/shell/integration/java_integration_test.sh +++ b/src/test/shell/integration/java_integration_test.sh @@ -254,8 +254,11 @@ function assert_singlejar_works() { local -r javabase="${BAZEL_RUNFILES}/${runfiles_relative_javabase}" fi + add_rules_java "MODULE.bazel" + mkdir -p "$pkg/jvm" cat > "$pkg/jvm/BUILD" < Date: Fri, 15 Nov 2024 20:52:16 -0800 Subject: [PATCH 09/15] Automatic code cleanup. PiperOrigin-RevId: 697081436 Change-Id: I135693ec26f937f0439939578437f5ce1eec3ffa (cherry picked from commit 09c848f32ab76e31cd1c109cbce25a49b8c37da9) --- src/test/java/com/google/devtools/build/lib/testutil/BUILD | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/test/java/com/google/devtools/build/lib/testutil/BUILD b/src/test/java/com/google/devtools/build/lib/testutil/BUILD index c2016b873ffb50..9de2b047dd9d5d 100644 --- a/src/test/java/com/google/devtools/build/lib/testutil/BUILD +++ b/src/test/java/com/google/devtools/build/lib/testutil/BUILD @@ -2,7 +2,7 @@ # A grab-bag of testing utilities. load("@bazel_skylib//rules:write_file.bzl", "write_file") -load("@rules_java//java:defs.bzl", "java_library", "java_test") +load("@rules_java//java:defs.bzl", "java_binary", "java_library", "java_test") load("//src/tools/bzlmod:blazel_utils.bzl", "get_canonical_repo_name") package( From 4069f64495571d79902c96b316f68b91e7512af6 Mon Sep 17 00:00:00 2001 From: Googler Date: Mon, 18 Nov 2024 09:08:25 -0800 Subject: [PATCH 10/15] Add `load()`s for the java rules to all tests PiperOrigin-RevId: 697649173 Change-Id: If48cefaae8bb5c6c845ed05de70b2e682c070c15 (cherry picked from commit 89c634ff601a367b9f55a90868f13c35fbe57d61) --- src/test/shell/integration/aquery_test.sh | 9 +++++++ .../bazel_worker_multiplexer_test.sh | 4 +++ .../shell/integration/bazel_worker_test.sh | 6 +++++ .../config_stripped_outputs_test.sh | 10 ++++++++ .../discard_analysis_cache_test.sh | 5 ++++ .../integration/java_integration_test.sh | 25 +++++++++++++++++-- .../shell/integration/java_sandboxing_test.sh | 5 ++++ .../integration/jvm_flags_escaping_test.sh | 6 +++++ .../integration/modify_execution_info_test.sh | 2 ++ .../integration/nestedset_as_skykey_test.sh | 3 +++ .../shell/integration/output_filter_test.sh | 6 +++++ .../integration/stub_finds_runfiles_test.sh | 3 +++ src/test/shell/integration/test_test.sh | 5 ++++ 13 files changed, 87 insertions(+), 2 deletions(-) diff --git a/src/test/shell/integration/aquery_test.sh b/src/test/shell/integration/aquery_test.sh index 65a1eab78a933b..12d470fb61e3ff 100755 --- a/src/test/shell/integration/aquery_test.sh +++ b/src/test/shell/integration/aquery_test.sh @@ -45,6 +45,10 @@ esac add_to_bazelrc "build --package_path=%workspace%" +function set_up() { + add_rules_java MODULE.bazel +} + function has_iso_8859_1_locale() { charmap="$(LC_ALL=en_US.ISO-8859-1 locale charmap 2>/dev/null)" [[ "${charmap}" == "ISO-8859-1" ]] @@ -643,6 +647,7 @@ function test_aquery_all_filters_only_match_foo() { local pkg="${FUNCNAME[0]}" mkdir -p "$pkg" || fail "mkdir -p $pkg" cat > "$pkg/BUILD" <<'EOF' +load("@rules_java//java:java_library.bzl", "java_library") genrule( name = "foo", srcs = ["foo_matching_in.java"], @@ -749,6 +754,7 @@ function test_aquery_mnemonic_filter_only_mach_foo() { local pkg="${FUNCNAME[0]}" mkdir -p "$pkg" || fail "mkdir -p $pkg" cat > "$pkg/BUILD" <<'EOF' +load("@rules_java//java:java_library.bzl", "java_library") genrule( name = "foo", srcs = ["foo_matching_in.java"], @@ -840,6 +846,7 @@ function test_aquery_mnemonic_filter_exact_mnemonic_only_mach_foo() { local pkg="${FUNCNAME[0]}" mkdir -p "$pkg" || fail "mkdir -p $pkg" cat > "$pkg/BUILD" <<'EOF' +load("@rules_java//java:java_library.bzl", "java_library") genrule( name = "foo", srcs = ["foo_matching_in.java"], @@ -890,6 +897,7 @@ function test_aquery_filters_chain_inputs_only_match_one() { local pkg="${FUNCNAME[0]}" mkdir -p "$pkg" || fail "mkdir -p $pkg" cat > "$pkg/BUILD" <<'EOF' +load("@rules_java//java:java_library.bzl", "java_library") genrule( name='foo', srcs=['foo_matching_in.java'], @@ -964,6 +972,7 @@ function test_aquery_filters_chain_mnemonic_only_match_one() { local pkg="${FUNCNAME[0]}" mkdir -p "$pkg" || fail "mkdir -p $pkg" cat > "$pkg/BUILD" <<'EOF' +load("@rules_java//java:java_library.bzl", "java_library") java_library( name='foo', srcs=['Foo.java'] diff --git a/src/test/shell/integration/bazel_worker_multiplexer_test.sh b/src/test/shell/integration/bazel_worker_multiplexer_test.sh index 215bbeff37a413..f784d9a7aba477 100755 --- a/src/test/shell/integration/bazel_worker_multiplexer_test.sh +++ b/src/test/shell/integration/bazel_worker_multiplexer_test.sh @@ -44,6 +44,8 @@ function set_up() { cd ${WORKSPACE_SUBDIR} BINS=$(bazel info $PRODUCT_NAME-bin)/${WORKSPACE_SUBDIR} + add_rules_java ${WORKSPACE_DIR}/MODULE.bazel + # This causes Bazel to shut down all running workers. bazel build --worker_quit_after_build &> $TEST_log \ || fail "'bazel build --worker_quit_after_build' during test set_up failed" @@ -110,6 +112,8 @@ work = rule( ) EOF cat >BUILD < $TEST_log \ || fail "'bazel build --worker_quit_after_build' during test set_up failed" @@ -59,6 +61,8 @@ function tear_down() { function write_hello_library_files() { mkdir -p java/main cat >java/main/BUILD <BUILD < "$pkg/BUILD" < "$pkg/java/hello/BUILD" <<'EOF' +load("@rules_java//java:java_library.bzl", "java_library") java_library(name='a', srcs=['A.java'], deps = [':b']) java_library(name='b', srcs=['B.java'], deps = [':c']) java_library(name='c', srcs=['C.java'], deps = [':d']) @@ -258,6 +265,8 @@ EOF mkdir -p $pkg/java cat > $pkg/java/BUILD < "$pkg/java/hello/BUILD" <<'EOF' +load("@rules_java//java:java_library.bzl", "java_library") java_library(name='a', srcs=['A.java'], deps = [':b']) java_library(name='b', srcs=['B.java'], deps = [':c']) java_library(name='c', srcs=['C.java'], deps = [':d']) diff --git a/src/test/shell/integration/discard_analysis_cache_test.sh b/src/test/shell/integration/discard_analysis_cache_test.sh index 5375f3bdc06413..fd5f9d00305702 100755 --- a/src/test/shell/integration/discard_analysis_cache_test.sh +++ b/src/test/shell/integration/discard_analysis_cache_test.sh @@ -62,6 +62,7 @@ jmaptool="$(rlocation "${javabase}/bin/jmap${EXE_EXT}")" function write_hello_world_files() { mkdir -p hello || fail "mkdir hello failed" cat >hello/BUILD <$pkg/java/hello/BUILD <$pkg/java/hello/BUILD <$pkg/java/main/BUILD <$pkg/java/hello_library/BUILD <$pkg/java/hellosailor/BUILD < "$pkg/jvm/BUILD" < $pkg/java/deploy/BUILD < $pkg/java/hello/BUILD < $pkg/java/hello/BUILD < $pkg/java/hello/BUILD <$pkg/java/test/processor/BUILD <$pkg/java/test/client/BUILD <$pkg/java/com/google/jvmflags/BUILD <$pkg/java/classpath/BUILD < $pkg/java/foo/BUILD < $pkg/java/test/BUILD < $pkg/java/hello/BUILD < "${package}/BUILD" <&2; exit 1; } +function set_up() { + add_rules_java MODULE.bazel +} + function tear_down() { bazel clean --expunge bazel shutdown @@ -70,6 +74,7 @@ function build_with_params() { # sandboxing and support workers. mkdir pkg cat >pkg/BUILD <<'EOF' +load("@rules_java//java:java_binary.bzl", "java_binary") java_binary( name = "java", srcs = ["Main.java"], diff --git a/src/test/shell/integration/jvm_flags_escaping_test.sh b/src/test/shell/integration/jvm_flags_escaping_test.sh index dc37a379e27066..2a2e165a17c704 100755 --- a/src/test/shell/integration/jvm_flags_escaping_test.sh +++ b/src/test/shell/integration/jvm_flags_escaping_test.sh @@ -61,6 +61,10 @@ else declare -r EXE_EXT="" fi +function set_up() { + add_rules_java MODULE.bazel +} + # ---------------------------------------------------------------------- # HELPER FUNCTIONS # ---------------------------------------------------------------------- @@ -100,6 +104,7 @@ function create_build_file_for_untokenizable_flag() { local -r pkg="$1"; shift mkdir -p "$pkg" || fail "mkdir -p $pkg" cat >"$pkg/BUILD" <<'eof' +load("@rules_java//java:java_binary.bzl", "java_binary") java_binary( name = "cannot_tokenize", srcs = ["A.java"], @@ -119,6 +124,7 @@ function create_build_file_with_many_jvm_flags() { local -r pkg="$1"; shift mkdir -p "$pkg" || fail "mkdir -p $pkg" cat >"$pkg/BUILD" <<'eof' +load("@rules_java//java:java_binary.bzl", "java_binary") java_binary( name = "x", srcs = ["A.java"], diff --git a/src/test/shell/integration/modify_execution_info_test.sh b/src/test/shell/integration/modify_execution_info_test.sh index d1a9d529202c5b..7e600c85db3a4b 100755 --- a/src/test/shell/integration/modify_execution_info_test.sh +++ b/src/test/shell/integration/modify_execution_info_test.sh @@ -61,6 +61,7 @@ fi function set_up() { cd ${WORKSPACE_DIR} + add_rules_java MODULE.bazel } function tear_down() { @@ -153,6 +154,7 @@ function test_modify_execution_info_various_types() { mkdir -p "$pkg" || fail "mkdir -p $pkg" echo "load('//$pkg:shell.bzl', 'starlark_shell')" > "$pkg/BUILD" cat >> "$pkg/BUILD" <<'EOF' +load("@rules_java//java:java_library.bzl", "java_library") load("@rules_python//python:py_binary.bzl", "py_binary") starlark_shell( diff --git a/src/test/shell/integration/nestedset_as_skykey_test.sh b/src/test/shell/integration/nestedset_as_skykey_test.sh index b6510697142ce1..dd9e367e7de9b2 100755 --- a/src/test/shell/integration/nestedset_as_skykey_test.sh +++ b/src/test/shell/integration/nestedset_as_skykey_test.sh @@ -62,6 +62,8 @@ fi function set_up() { cd ${WORKSPACE_DIR} + add_rules_java MODULE.bazel + mkdir -p "foo" cat > foo/foocc.py <<'EOF' import sys @@ -189,6 +191,7 @@ EOF function test_incremental_err_reporting() { export DONT_SANITY_CHECK_SERIALIZATION=1 cat > foo/BUILD <$pkg/java/main/BUILD <$pkg/java/hello_library/BUILD < pkg/BUILD << 'EOF' +load("@rules_java//java:java_binary.bzl", "java_binary") +load("@rules_java//java:java_test.bzl", "java_test") load("@rules_python//python:py_binary.bzl", "py_binary") load("@rules_python//python:py_test.bzl", "py_test") diff --git a/src/test/shell/integration/test_test.sh b/src/test/shell/integration/test_test.sh index 046a0f333c704b..4acd2d72f74f5b 100755 --- a/src/test/shell/integration/test_test.sh +++ b/src/test/shell/integration/test_test.sh @@ -55,6 +55,10 @@ msys*) ;; esac +function set_up() { + add_rules_java MODULE.bazel +} + #### TESTS ############################################################# function test_passing_test_is_reported_correctly() { @@ -150,6 +154,7 @@ function test_process_spawned_by_test_doesnt_block_test_from_completing() { mkdir -p $pkg || fail "mkdir -p $pkg failed" cat > $pkg/BUILD <<'EOF' +load("@rules_java//java:java_test.bzl", "java_test") java_test( name = "my_test", main_class = "test.MyTest", From 4afa002519af6e4df08c6f73bbd32366759a95fd Mon Sep 17 00:00:00 2001 From: Googler Date: Wed, 20 Nov 2024 10:29:26 +0100 Subject: [PATCH 11/15] Update `rules_java v8.5.0` Closes #24391. PiperOrigin-RevId: 698301966 Change-Id: I004ae10070354f7f565778a58a1d97be234f55c0 (cherry picked from commit eb2859a73abd39bdfdbd7eeb90858a5c0fc344e3) --- MODULE.bazel | 2 +- MODULE.bazel.lock | 31 +++------------ src/MODULE.tools | 2 +- .../lib/analysis/mock/BazelAnalysisMock.java | 2 +- .../util/AbstractMockJavaSupport.java | 39 +++++++++++++++++++ src/test/shell/bazel/bazel_java_test.sh | 11 ++++++ .../shell/bazel/bazel_proto_library_test.sh | 3 ++ src/test/tools/bzlmod/MODULE.bazel.lock | 31 +++------------ 8 files changed, 68 insertions(+), 53 deletions(-) diff --git a/MODULE.bazel b/MODULE.bazel index 039dbf258e7efc..b9eb373568a26e 100644 --- a/MODULE.bazel +++ b/MODULE.bazel @@ -25,7 +25,7 @@ bazel_dep(name = "zstd-jni", version = "1.5.2-3.bcr.1") bazel_dep(name = "blake3", version = "1.5.1.bcr.1") bazel_dep(name = "zlib", version = "1.3.1.bcr.3") bazel_dep(name = "rules_cc", version = "0.0.16") -bazel_dep(name = "rules_java", version = "8.3.0") +bazel_dep(name = "rules_java", version = "8.5.0") bazel_dep(name = "rules_graalvm", version = "0.11.1") bazel_dep(name = "rules_proto", version = "7.0.2") bazel_dep(name = "rules_jvm_external", version = "6.0") diff --git a/MODULE.bazel.lock b/MODULE.bazel.lock index 13ff08fd4d95e3..0b80c12c97e8e8 100644 --- a/MODULE.bazel.lock +++ b/MODULE.bazel.lock @@ -164,7 +164,8 @@ "https://bcr.bazel.build/modules/rules_java/7.6.1/MODULE.bazel": "2f14b7e8a1aa2f67ae92bc69d1ec0fa8d9f827c4e17ff5e5f02e91caa3b2d0fe", "https://bcr.bazel.build/modules/rules_java/7.6.5/MODULE.bazel": "481164be5e02e4cab6e77a36927683263be56b7e36fef918b458d7a8a1ebadb1", "https://bcr.bazel.build/modules/rules_java/8.3.2/MODULE.bazel": "7336d5511ad5af0b8615fdc7477535a2e4e723a357b6713af439fe8cf0195017", - "https://bcr.bazel.build/modules/rules_java/8.3.2/source.json": "76aeec36622f7ff942e691352a548d3cc808c9dc6c195120d06ef7e4f0632992", + "https://bcr.bazel.build/modules/rules_java/8.5.0/MODULE.bazel": "c081eda83625b6d97144f2da9dd5f074ecd56ba10f238257e7a90f56ee8a9c3c", + "https://bcr.bazel.build/modules/rules_java/8.5.0/source.json": "8aa0f3979d4c41e8575581e877eb2073a922c8f056fe74a67ca12eabf9e58715", "https://bcr.bazel.build/modules/rules_jvm_external/6.0/MODULE.bazel": "37c93a5a78d32e895d52f86a8d0416176e915daabd029ccb5594db422e87c495", "https://bcr.bazel.build/modules/rules_jvm_external/6.0/source.json": "73cc8818203a182e7374adf137f428d276190b2e2bef3022c231990cf0e594aa", "https://bcr.bazel.build/modules/rules_kotlin/1.9.0/MODULE.bazel": "ef85697305025e5a61f395d4eaede272a5393cee479ace6686dba707de804d59", @@ -1318,45 +1319,25 @@ ] } }, - "@@rules_java+//java:extensions.bzl%compatibility_proxy": { + "@@rules_java+//java:rules_java_deps.bzl%compatibility_proxy": { "general": { - "bzlTransitiveDigest": "2vq8vV3s5K7xJklvOlDqsEdH8xUkaddQJ+6Ove5ZoZY=", - "usagesDigest": "oTMuZ87Uif8roeNCdLa40yt9GNy30+6DDYIXqCEjm7I=", + "bzlTransitiveDigest": "lUVy7PIyFpaJ2wPiT8duNgICcHp6qxghhds+CZ5ViXI=", + "usagesDigest": "gTu8Srf8G7tL645OdQBCe0C/Rg1drH4YKoQ4L8eL3K4=", "recordedFileInputs": {}, "recordedDirentsInputs": {}, "envVariables": {}, "generatedRepoSpecs": { "compatibility_proxy": { - "bzlFile": "@@rules_java+//java:repositories.bzl", + "bzlFile": "@@rules_java+//java:rules_java_deps.bzl", "ruleClassName": "_compatibility_proxy_repo_rule", "attributes": {} } }, "recordedRepoMappingEntries": [ - [ - "bazel_features+", - "bazel_features_globals", - "bazel_features++version_extension+bazel_features_globals" - ], - [ - "bazel_features+", - "bazel_features_version", - "bazel_features++version_extension+bazel_features_version" - ], - [ - "rules_java+", - "bazel_features", - "bazel_features+" - ], [ "rules_java+", "bazel_tools", "bazel_tools" - ], - [ - "rules_java+", - "remote_java_tools", - "rules_java++toolchains+remote_java_tools" ] ] } diff --git a/src/MODULE.tools b/src/MODULE.tools index 7fa7b912544341..d5e30a28dd9927 100644 --- a/src/MODULE.tools +++ b/src/MODULE.tools @@ -39,7 +39,7 @@ use_repo(buildozer_binary, "buildozer_binary") # Dependencies used to auto-load removed symbols and rules from Bazel (due to Starlarkification) # See also: --incompatible_autoload_externally, AutoloadSymbols bazel_dep(name = "protobuf", version = "29.0-rc3", repo_name = "com_google_protobuf") -bazel_dep(name = "rules_java", version = "8.3.0") +bazel_dep(name = "rules_java", version = "8.5.0") bazel_dep(name = "rules_cc", version = "0.0.16") bazel_dep(name = "rules_python", version = "0.40.0") bazel_dep(name = "rules_shell", version = "0.2.0") diff --git a/src/test/java/com/google/devtools/build/lib/analysis/mock/BazelAnalysisMock.java b/src/test/java/com/google/devtools/build/lib/analysis/mock/BazelAnalysisMock.java index 3208acef986bb1..71ce932cfe27f6 100644 --- a/src/test/java/com/google/devtools/build/lib/analysis/mock/BazelAnalysisMock.java +++ b/src/test/java/com/google/devtools/build/lib/analysis/mock/BazelAnalysisMock.java @@ -223,7 +223,7 @@ def _impl(ctx): "embedded_tools/tools/jdk/BUILD", """ load("@rules_java//java:defs.bzl", - "java_binary", "java_import", "java_toolchain") + "java_binary", "java_import", "java_toolchain", "java_runtime") load( ":java_toolchain_alias.bzl", "java_host_runtime_alias", diff --git a/src/test/java/com/google/devtools/build/lib/analysis/util/AbstractMockJavaSupport.java b/src/test/java/com/google/devtools/build/lib/analysis/util/AbstractMockJavaSupport.java index 765dc429de7d9c..2c20beff6164cb 100644 --- a/src/test/java/com/google/devtools/build/lib/analysis/util/AbstractMockJavaSupport.java +++ b/src/test/java/com/google/devtools/build/lib/analysis/util/AbstractMockJavaSupport.java @@ -71,6 +71,45 @@ public void setupRulesJava( load("@rules_java//java/bazel/rules:bazel_java_test.bzl", _java_test = "java_test") java_test = _java_test """); + config.overwrite( + "rules_java_workspace/java/toolchains/java_package_configuration.bzl", + """ + load("@rules_java//java/common/rules:java_package_configuration.bzl", + _java_package_configuration = "java_package_configuration") + java_package_configuration = _java_package_configuration + """); + config.overwrite( + "rules_java_workspace/java/toolchains/java_runtime.bzl", + """ + load("@rules_java//java/common/rules:java_runtime.bzl", + _java_runtime = "java_runtime") + java_runtime = _java_runtime + """); + config.overwrite( + "rules_java_workspace/java/toolchains/java_toolchain.bzl", + """ + load("@rules_java//java/common/rules:java_toolchain.bzl", + _java_toolchain = "java_toolchain") + java_toolchain = _java_toolchain + """); + config.overwrite( + "rules_java_workspace/java/common/java_common.bzl", + """ + load("@rules_java//java/private:java_common.bzl", _java_common = "java_common") + java_common = _java_common + """); + config.overwrite( + "rules_java_workspace/java/common/java_info.bzl", + """ + load("@rules_java//java/private:java_info.bzl", _JavaInfo = "JavaInfo") + JavaInfo = _JavaInfo + """); + config.overwrite( + "rules_java_workspace/java/common/java_plugin_info.bzl", + """ + load("@rules_java//java/private:java_info.bzl", _JavaPluginInfo = "JavaPluginInfo") + JavaPluginInfo = _JavaPluginInfo + """); // mocks config.create("rules_java_workspace/toolchains/BUILD"); config.create( diff --git a/src/test/shell/bazel/bazel_java_test.sh b/src/test/shell/bazel/bazel_java_test.sh index 05cd4de2ae647e..15a90ccaa3154e 100755 --- a/src/test/shell/bazel/bazel_java_test.sh +++ b/src/test/shell/bazel/bazel_java_test.sh @@ -87,6 +87,10 @@ function tear_down() { rm -rf "$(bazel info bazel-bin)/java" } +function set_up() { + add_rules_java MODULE.bazel +} + function write_hello_library_files() { mkdir -p java/main cat >java/main/BUILD < java/com/google/sandwich/java_custom_library.bzl << EOF +load("@rules_java//java/common:java_common.bzl", "java_common") def _impl(ctx): deps = [dep[java_common.provider] for dep in ctx.attr.deps] exports = [export[java_common.provider] for export in ctx.attr.exports] @@ -414,6 +419,7 @@ java_custom_library( EOF cat >g/java_custom_library.bzl << EOF +load("@rules_java//java/common:java_common.bzl", "java_common") def _impl(ctx): output_jar = ctx.actions.declare_file("lib" + ctx.label.name + ".jar") @@ -484,6 +490,7 @@ java_custom_library( EOF cat >g/java_custom_library.bzl << EOF +load("@rules_java//java/common:java_common.bzl", "java_common") def _impl(ctx): output_jar = ctx.actions.declare_file("lib" + ctx.label.name + ".jar") @@ -1387,6 +1394,8 @@ class A { EOF cat > java/com/google/sandwich/java_custom_library.bzl << EOF +load("@rules_java//java/common:java_common.bzl", "java_common") +load("@rules_java//java/common:java_info.bzl", "JavaInfo") def _impl(ctx): compiled_jar = ctx.actions.declare_file("lib" + ctx.label.name + ".jar") imported_jar = ctx.files.jar[0]; @@ -1441,6 +1450,8 @@ my_rule( EOF cat > java/com/google/foo/my_rule.bzl << EOF +load("@rules_java//java/common:java_common.bzl", "java_common") +load("@rules_java//java/common:java_info.bzl", "JavaInfo") result = provider() def _impl(ctx): compile_jar = java_common.run_ijar( diff --git a/src/test/shell/bazel/bazel_proto_library_test.sh b/src/test/shell/bazel/bazel_proto_library_test.sh index 0122b4056d17a6..380b87333e9393 100755 --- a/src/test/shell/bazel/bazel_proto_library_test.sh +++ b/src/test/shell/bazel/bazel_proto_library_test.sh @@ -24,6 +24,7 @@ source "${CURRENT_DIR}/../integration_test_setup.sh" \ function set_up() { add_protobuf "MODULE.bazel" + add_rules_java "MODULE.bazel" } # Creates directories and files with the structure: @@ -400,6 +401,8 @@ proto_library( EOF cat > java/proto/my_rule_with_aspect.bzl < Date: Wed, 23 Oct 2024 09:06:48 -0700 Subject: [PATCH 12/15] Remove obsolete logic for handling `.jar` files in deps This logic has been ported to starlark, this method is unused. PiperOrigin-RevId: 688987600 Change-Id: I932fb9a5f40ded4f5b253d2b447045e52a610656 (cherry picked from commit b3badd3dd867f8e16a3a542382b7b354e7124a3f) --- .../java/JavaCompilationArgsProvider.java | 39 ------------------- 1 file changed, 39 deletions(-) diff --git a/src/main/java/com/google/devtools/build/lib/rules/java/JavaCompilationArgsProvider.java b/src/main/java/com/google/devtools/build/lib/rules/java/JavaCompilationArgsProvider.java index a87525b56ac6f2..a707be4bd02e33 100644 --- a/src/main/java/com/google/devtools/build/lib/rules/java/JavaCompilationArgsProvider.java +++ b/src/main/java/com/google/devtools/build/lib/rules/java/JavaCompilationArgsProvider.java @@ -16,22 +16,17 @@ import com.google.auto.value.AutoValue; import com.google.devtools.build.lib.actions.Artifact; -import com.google.devtools.build.lib.analysis.FileProvider; -import com.google.devtools.build.lib.analysis.TransitiveInfoCollection; import com.google.devtools.build.lib.collect.nestedset.Depset; import com.google.devtools.build.lib.collect.nestedset.Depset.TypeException; import com.google.devtools.build.lib.collect.nestedset.NestedSet; import com.google.devtools.build.lib.collect.nestedset.NestedSetBuilder; import com.google.devtools.build.lib.collect.nestedset.Order; import com.google.devtools.build.lib.concurrent.ThreadSafety.Immutable; -import com.google.devtools.build.lib.packages.RuleClass.ConfiguredTargetFactory.RuleErrorException; import com.google.devtools.build.lib.packages.StructImpl; import com.google.devtools.build.lib.rules.java.JavaInfo.JavaInfoInternalProvider; import com.google.devtools.build.lib.skyframe.serialization.autocodec.SerializationConstant; -import com.google.devtools.build.lib.util.FileType; import com.google.errorprone.annotations.CanIgnoreReturnValue; import java.util.Iterator; -import java.util.Optional; import javax.annotation.Nullable; import net.starlark.java.eval.EvalException; @@ -107,40 +102,6 @@ private static JavaCompilationArgsProvider create( */ public abstract NestedSet getCompileTimeJavaDependencyArtifacts(); - /** - * Returns a {@link JavaCompilationArgsProvider} for the given {@link TransitiveInfoCollection}s. - * - *

If the given targets have a {@link JavaCompilationArgsProvider}, the information from that - * provider will be returned. Otherwise, any jar files provided by the targets will be wrapped in - * the returned provider. - * - * @deprecated The handling of raw jar files is present for legacy compatibility. All new - * Java-based rules should require their dependencies to provide {@link - * JavaCompilationArgsProvider}, and that precompiled jar files be wrapped in {@code - * java_import}. New rules should not use this method, and existing rules should be cleaned up - * to disallow jar files in their deps. - */ - // TODO(b/11285003): disallow jar files in deps, require java_import instead - @Deprecated - public static JavaCompilationArgsProvider legacyFromTargets( - Iterable infos) throws RuleErrorException { - Builder argsBuilder = builder(); - for (TransitiveInfoCollection info : infos) { - Optional provider = JavaInfo.getCompilationArgsProvider(info); - if (provider.isPresent()) { - argsBuilder.addExports(provider.get()); - } else { - NestedSet filesToBuild = info.getProvider(FileProvider.class).getFilesToBuild(); - for (Artifact jar : FileType.filter(filesToBuild.toList(), JavaSemantics.JAR)) { - argsBuilder - .addRuntimeJar(jar) - .addDirectCompileTimeJar(/* interfaceJar= */ jar, /* fullJar= */ jar); - } - } - } - return argsBuilder.build(); - } - /** Enum to specify transitive compilation args traversal */ public enum ClasspathType { /* treat the same for compile time and runtime */ From e84a2977034027ae088ec2657f5f284fe9d6020e Mon Sep 17 00:00:00 2001 From: Googler Date: Sun, 6 Oct 2024 08:16:32 +0200 Subject: [PATCH 13/15] Delete unused java rule code from `@_builtins` PiperOrigin-RevId: 685617340 Change-Id: I78937da0298740aa1cf8f09a21c847818a94bea0 (cherry picked from commit 24c3f249380c0c1073214e6237fd98eb1df130c0) --- .../starlark/builtins_bzl/bazel/exports.bzl | 8 - .../bazel/java/bazel_java_binary.bzl | 570 ------------ .../bazel/java/bazel_java_binary_nonexec.bzl | 26 - .../bazel/java/bazel_java_binary_wrapper.bzl | 36 - .../builtins_bzl/common/java/android_lint.bzl | 143 --- .../common/java/basic_java_library.bzl | 280 ------ .../common/java/compile_action.bzl | 172 ---- .../common/java/import_deps_check.bzl | 79 -- .../builtins_bzl/common/java/java_binary.bzl | 817 ------------------ .../common/java/java_binary_deploy_jar.bzl | 254 ------ .../common/java/java_binary_wrapper.bzl | 71 -- .../builtins_bzl/common/java/java_import.bzl | 354 -------- .../builtins_bzl/common/java/java_library.bzl | 387 --------- .../builtins_bzl/common/java/java_plugin.bzl | 182 ---- .../common/java/proguard_validation.bzl | 70 -- .../builtins_bzl/common/rule_util.bzl | 49 -- src/test/shell/bazel/bazel_rules_java_test.sh | 14 +- 17 files changed, 9 insertions(+), 3503 deletions(-) delete mode 100644 src/main/starlark/builtins_bzl/bazel/java/bazel_java_binary.bzl delete mode 100644 src/main/starlark/builtins_bzl/bazel/java/bazel_java_binary_nonexec.bzl delete mode 100644 src/main/starlark/builtins_bzl/bazel/java/bazel_java_binary_wrapper.bzl delete mode 100644 src/main/starlark/builtins_bzl/common/java/android_lint.bzl delete mode 100644 src/main/starlark/builtins_bzl/common/java/basic_java_library.bzl delete mode 100644 src/main/starlark/builtins_bzl/common/java/compile_action.bzl delete mode 100644 src/main/starlark/builtins_bzl/common/java/import_deps_check.bzl delete mode 100644 src/main/starlark/builtins_bzl/common/java/java_binary.bzl delete mode 100644 src/main/starlark/builtins_bzl/common/java/java_binary_deploy_jar.bzl delete mode 100644 src/main/starlark/builtins_bzl/common/java/java_binary_wrapper.bzl delete mode 100644 src/main/starlark/builtins_bzl/common/java/java_import.bzl delete mode 100644 src/main/starlark/builtins_bzl/common/java/java_library.bzl delete mode 100644 src/main/starlark/builtins_bzl/common/java/java_plugin.bzl delete mode 100644 src/main/starlark/builtins_bzl/common/java/proguard_validation.bzl delete mode 100644 src/main/starlark/builtins_bzl/common/rule_util.bzl diff --git a/src/main/starlark/builtins_bzl/bazel/exports.bzl b/src/main/starlark/builtins_bzl/bazel/exports.bzl index 204cfe092cb2cf..8c8696c86d60f7 100644 --- a/src/main/starlark/builtins_bzl/bazel/exports.bzl +++ b/src/main/starlark/builtins_bzl/bazel/exports.bzl @@ -14,20 +14,12 @@ """Exported builtins symbols that are specific to OSS Bazel.""" -load("@_builtins//:common/java/java_library.bzl", "JAVA_LIBRARY_ATTRS", "bazel_java_library_rule") load("@_builtins//:common/python/py_internal.bzl", "py_internal") load(":common/java/java_package_configuration.bzl", "java_package_configuration") load(":common/java/java_runtime.bzl", "java_runtime") load(":common/java/java_toolchain.bzl", "java_toolchain") exported_toplevels = { - # This is an experimental export in Bazel. The interface will change in a way - # that breaks users. In the future, Build API team will provide an interface - # that is conceptually similar to this one and stable. - "experimental_java_library_export_do_not_use": struct( - bazel_java_library_rule = bazel_java_library_rule, - JAVA_LIBRARY_ATTRS = JAVA_LIBRARY_ATTRS, - ), "py_internal": py_internal, "proto_common_do_not_use": struct(INCOMPATIBLE_ENABLE_PROTO_TOOLCHAIN_RESOLUTION = _builtins.toplevel.proto_common_do_not_use.incompatible_enable_proto_toolchain_resolution()), } diff --git a/src/main/starlark/builtins_bzl/bazel/java/bazel_java_binary.bzl b/src/main/starlark/builtins_bzl/bazel/java/bazel_java_binary.bzl deleted file mode 100644 index 999135daa6aa1c..00000000000000 --- a/src/main/starlark/builtins_bzl/bazel/java/bazel_java_binary.bzl +++ /dev/null @@ -1,570 +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. - -load(":common/cc/cc_helper.bzl", "cc_helper") -load(":common/java/android_lint.bzl", "android_lint_subrule") -load(":common/java/java_binary.bzl", "BASE_TEST_ATTRIBUTES", "BASIC_JAVA_BINARY_ATTRIBUTES", "basic_java_binary") -load(":common/java/java_binary_deploy_jar.bzl", "create_deploy_archives") -load(":common/java/java_helper.bzl", "helper") -load(":common/java/java_info.bzl", "JavaInfo") -load(":common/java/java_semantics.bzl", "semantics") -load(":common/paths.bzl", "paths") -load(":common/rule_util.bzl", "merge_attrs") - -def _bazel_java_binary_impl(ctx): - return _bazel_base_binary_impl(ctx, is_test_rule_class = False) + helper.executable_providers(ctx) - -def _bazel_java_test_impl(ctx): - return _bazel_base_binary_impl(ctx, is_test_rule_class = True) + helper.test_providers(ctx) - -def _bazel_base_binary_impl(ctx, is_test_rule_class): - deps = _collect_all_targets_as_deps(ctx, classpath_type = "compile_only") - runtime_deps = _collect_all_targets_as_deps(ctx) - - main_class = _check_and_get_main_class(ctx) - coverage_main_class = main_class - coverage_config = helper.get_coverage_config(ctx, _get_coverage_runner(ctx)) - if coverage_config: - main_class = coverage_config.main_class - - launcher_info = _get_launcher_info(ctx) - - executable = _get_executable(ctx) - - feature_config = helper.get_feature_config(ctx) - if feature_config: - strip_as_default = helper.should_strip_as_default(ctx, feature_config) - else: - # No C++ toolchain available. - strip_as_default = False - - providers, default_info, jvm_flags = basic_java_binary( - ctx, - deps, - runtime_deps, - ctx.files.resources, - main_class, - coverage_main_class, - coverage_config, - launcher_info, - executable, - strip_as_default, - is_test_rule_class = is_test_rule_class, - ) - - if ctx.attr.use_testrunner: - if semantics.find_java_runtime_toolchain(ctx).version >= 17: - jvm_flags.append("-Djava.security.manager=allow") - test_class = ctx.attr.test_class if hasattr(ctx.attr, "test_class") else "" - if test_class == "": - test_class = helper.primary_class(ctx) - if test_class == None: - fail("cannot determine test class. You might want to rename the " + - " rule or add a 'test_class' attribute.") - jvm_flags.extend([ - "-ea", - "-Dbazel.test_suite=" + helper.shell_escape(test_class), - ]) - - java_attrs = providers["InternalDeployJarInfo"].java_attrs - - if executable: - _create_stub(ctx, java_attrs, launcher_info.launcher, executable, jvm_flags, main_class, coverage_main_class) - - runfiles = default_info.runfiles - - if executable: - runtime_toolchain = semantics.find_java_runtime_toolchain(ctx) - runfiles = runfiles.merge(ctx.runfiles(transitive_files = runtime_toolchain.files)) - - test_support = helper.get_test_support(ctx) - if test_support: - runfiles = runfiles.merge(test_support[DefaultInfo].default_runfiles) - - providers["DefaultInfo"] = DefaultInfo( - files = default_info.files, - runfiles = runfiles, - executable = default_info.executable, - ) - - info = providers.pop("InternalDeployJarInfo") - create_deploy_archives( - ctx, - info.java_attrs, - launcher_info, - main_class, - coverage_main_class, - info.strip_as_default, - add_exports = info.add_exports, - add_opens = info.add_opens, - ) - - return providers.values() - -def _get_coverage_runner(ctx): - if ctx.configuration.coverage_enabled and ctx.attr.create_executable: - toolchain = semantics.find_java_toolchain(ctx) - runner = toolchain.jacocorunner - if not runner: - fail("jacocorunner not set in java_toolchain: %s" % toolchain.label) - runner_jar = runner.executable - - # wrap the jar in JavaInfo so we can add it to deps for java_common.compile() - return JavaInfo(output_jar = runner_jar, compile_jar = runner_jar) - - return None - -def _collect_all_targets_as_deps(ctx, classpath_type = "all"): - deps = helper.collect_all_targets_as_deps(ctx, classpath_type = classpath_type) - - if classpath_type == "compile_only" and ctx.fragments.java.enforce_explicit_java_test_deps(): - return deps - - test_support = helper.get_test_support(ctx) - if test_support: - deps.append(test_support) - return deps - -def _check_and_get_main_class(ctx): - create_executable = ctx.attr.create_executable - main_class = _get_main_class(ctx) - - if not create_executable and main_class: - fail("main class must not be specified when executable is not created") - if create_executable and not main_class: - if not ctx.attr.srcs: - fail("need at least one of 'main_class' or Java source files") - main_class = helper.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)") - - return _get_main_class(ctx) - -def _get_main_class(ctx): - if not ctx.attr.create_executable: - return None - - main_class = _get_main_class_from_rule(ctx) - - if main_class == "": - main_class = helper.primary_class(ctx) - return main_class - -def _get_main_class_from_rule(ctx): - main_class = ctx.attr.main_class - if main_class: - return main_class - if ctx.attr.use_testrunner: - return "com.google.testing.junit.runner.BazelTestRunner" - return main_class - -def _get_launcher_info(ctx): - launcher = helper.launcher_artifact_for_target(ctx) - return struct( - launcher = launcher, - unstripped_launcher = launcher, - runfiles = [], - runtime_jars = [], - jvm_flags = [], - classpath_resources = [], - ) - -def _get_executable(ctx): - if not ctx.attr.create_executable: - return None - executable_name = ctx.label.name - if helper.is_target_platform_windows(ctx): - executable_name = executable_name + ".exe" - - return ctx.actions.declare_file(executable_name) - -def _create_stub(ctx, java_attrs, launcher, executable, jvm_flags, main_class, coverage_main_class): - java_runtime_toolchain = semantics.find_java_runtime_toolchain(ctx) - java_executable = helper.get_java_executable(ctx, java_runtime_toolchain, launcher) - workspace_name = ctx.workspace_name - workspace_prefix = workspace_name + ("/" if workspace_name else "") - runfiles_enabled = helper.runfiles_enabled(ctx) - coverage_enabled = ctx.configuration.coverage_enabled - - test_support = helper.get_test_support(ctx) - test_support_jars = test_support[JavaInfo].transitive_runtime_jars if test_support else depset() - classpath = depset( - transitive = [ - java_attrs.runtime_classpath, - test_support_jars if ctx.fragments.java.enforce_explicit_java_test_deps() else depset(), - ], - ) - - if helper.is_target_platform_windows(ctx): - jvm_flags_for_launcher = [] - for flag in jvm_flags: - jvm_flags_for_launcher.extend(ctx.tokenize(flag)) - return _create_windows_exe_launcher(ctx, java_executable, classpath, main_class, jvm_flags_for_launcher, runfiles_enabled, executable) - - if runfiles_enabled: - prefix = "" if helper.is_absolute_target_platform_path(ctx, java_executable) else "${JAVA_RUNFILES}/" - java_bin = "JAVABIN=${JAVABIN:-" + prefix + java_executable + "}" - else: - java_bin = "JAVABIN=${JAVABIN:-$(rlocation " + java_executable + ")}" - - td = ctx.actions.template_dict() - td.add_joined( - "%classpath%", - classpath, - map_each = lambda file: _format_classpath_entry(runfiles_enabled, workspace_prefix, file), - join_with = ctx.configuration.host_path_separator, - format_joined = "\"%s\"", - allow_closure = True, - ) - - ctx.actions.expand_template( - template = ctx.file._stub_template, - output = executable, - substitutions = { - "%runfiles_manifest_only%": "" if runfiles_enabled else "1", - "%workspace_prefix%": workspace_prefix, - "%javabin%": java_bin, - "%needs_runfiles%": "0" if helper.is_absolute_target_platform_path(ctx, java_runtime_toolchain.java_executable_exec_path) else "1", - "%set_jacoco_metadata%": "", - "%set_jacoco_main_class%": "export JACOCO_MAIN_CLASS=" + coverage_main_class if coverage_enabled else "", - "%set_jacoco_java_runfiles_root%": "export JACOCO_JAVA_RUNFILES_ROOT=${JAVA_RUNFILES}/" + workspace_prefix if coverage_enabled else "", - "%java_start_class%": helper.shell_escape(main_class), - "%jvm_flags%": " ".join(jvm_flags), - }, - computed_substitutions = td, - is_executable = True, - ) - return executable - -def _format_classpath_entry(runfiles_enabled, workspace_prefix, file): - if runfiles_enabled: - return "${RUNPATH}" + file.short_path - - return "$(rlocation " + paths.normalize(workspace_prefix + file.short_path) + ")" - -def _create_windows_exe_launcher(ctx, java_executable, classpath, main_class, jvm_flags_for_launcher, runfiles_enabled, executable): - launch_info = ctx.actions.args().use_param_file("%s", use_always = True).set_param_file_format("multiline") - launch_info.add("binary_type=Java") - launch_info.add(ctx.workspace_name, format = "workspace_name=%s") - launch_info.add("1" if runfiles_enabled else "0", format = "symlink_runfiles_enabled=%s") - launch_info.add(java_executable, format = "java_bin_path=%s") - launch_info.add(main_class, format = "java_start_class=%s") - launch_info.add_joined(classpath, map_each = _short_path, join_with = ";", format_joined = "classpath=%s", omit_if_empty = False) - launch_info.add_joined(jvm_flags_for_launcher, join_with = "\t", format_joined = "jvm_flags=%s", omit_if_empty = False) - launch_info.add(semantics.find_java_runtime_toolchain(ctx).java_home_runfiles_path, format = "jar_bin_path=%s/bin/jar.exe") - - # TODO(b/295221112): Change to use the "launcher" attribute (only windows use a fixed _launcher attribute) - launcher_artifact = ctx.executable._launcher - ctx.actions.run( - executable = ctx.executable._windows_launcher_maker, - inputs = [launcher_artifact], - outputs = [executable], - arguments = [launcher_artifact.path, launch_info, executable.path], - use_default_shell_env = True, - ) - return executable - -def _short_path(file): - return file.short_path - -def _compute_test_support(use_testrunner): - return Label(semantics.JAVA_TEST_RUNNER_LABEL) if use_testrunner else None - -def _make_binary_rule(implementation, *, doc, attrs, executable = False, test = False, initializer = None): - return rule( - implementation = implementation, - initializer = initializer, - doc = doc, - attrs = attrs, - executable = executable, - test = test, - fragments = ["cpp", "java"], - provides = [JavaInfo], - toolchains = [semantics.JAVA_TOOLCHAIN] + cc_helper.use_cpp_toolchain() + ( - [semantics.JAVA_RUNTIME_TOOLCHAIN] if executable or test else [] - ), - # TODO(hvd): replace with filegroups? - outputs = { - "classjar": "%{name}.jar", - "sourcejar": "%{name}-src.jar", - "deploysrcjar": "%{name}_deploy-src.jar", - "deployjar": "%{name}_deploy.jar", - "unstrippeddeployjar": "%{name}_deploy.jar.unstripped", - }, - exec_groups = { - "cpp_link": exec_group(toolchains = cc_helper.use_cpp_toolchain()), - }, - subrules = [android_lint_subrule], - ) - -_BASE_BINARY_ATTRS = merge_attrs( - BASIC_JAVA_BINARY_ATTRIBUTES, - { - "resource_strip_prefix": attr.string( - doc = """ -The path prefix to strip from Java resources. -

-If specified, this path prefix is stripped from every file in the resources -attribute. It is an error for a resource file not to be under this directory. If not -specified (the default), the path of resource file is determined according to the same -logic as the Java package of source files. For example, a source file at -stuff/java/foo/bar/a.txt will be located at foo/bar/a.txt. -

- """, - ), - "_test_support": attr.label(default = _compute_test_support), - "_launcher": attr.label( - cfg = "exec", - executable = True, - default = "@bazel_tools//tools/launcher:launcher", - ), - "_windows_launcher_maker": attr.label( - default = "@bazel_tools//tools/launcher:launcher_maker", - cfg = "exec", - executable = True, - ), - }, -) - -def make_java_binary(executable): - return _make_binary_rule( - _bazel_java_binary_impl, - doc = """ -

- Builds a Java archive ("jar file"), plus a wrapper shell script with the same name as the rule. - The wrapper shell script uses a classpath that includes, among other things, a jar file for each - library on which the binary depends. When running the wrapper shell script, any nonempty - JAVABIN environment variable will take precedence over the version specified via - Bazel's --java_runtime_version flag. -

-

- The wrapper script accepts several unique flags. Refer to - //src/main/java/com/google/devtools/build/lib/bazel/rules/java/java_stub_template.txt - for a list of configurable flags and environment variables accepted by the wrapper. -

- -

Implicit output targets

-
    -
  • name.jar: A Java archive, containing the class files and other - resources corresponding to the binary's direct dependencies.
  • -
  • name-src.jar: An archive containing the sources ("source - jar").
  • -
  • name_deploy.jar: A Java archive suitable for deployment (only - built if explicitly requested). -

    - Building the <name>_deploy.jar target for your rule - creates a self-contained jar file with a manifest that allows it to be run with the - java -jar command or with the wrapper script's --singlejar - option. Using the wrapper script is preferred to java -jar because it - also passes the JVM flags and the options - to load native libraries. -

    -

    - The deploy jar contains all the classes that would be found by a classloader that - searched the classpath from the binary's wrapper script from beginning to end. It also - contains the native libraries needed for dependencies. These are automatically loaded - into the JVM at runtime. -

    -

    If your target specifies a launcher - attribute, then instead of being a normal JAR file, the _deploy.jar will be a - native binary. This will contain the launcher plus any native (C++) dependencies of - your rule, all linked into a static binary. The actual jar file's bytes will be - appended to that native binary, creating a single binary blob containing both the - executable and the Java code. You can execute the resulting jar file directly - like you would execute any native binary.

    -
  • -
  • name_deploy-src.jar: An archive containing the sources - collected from the transitive closure of the target. These will match the classes in the - deploy.jar except where jars have no matching source jar.
  • -
- -

-It is good practice to use the name of the source file that is the main entry point of the -application (minus the extension). For example, if your entry point is called -Main.java, then your name could be Main. -

- -

- A deps attribute is not allowed in a java_binary rule without - srcs; such a rule requires a - main_class provided by - runtime_deps. -

- -

The following code snippet illustrates a common mistake:

- -
-
-java_binary(
-    name = "DontDoThis",
-    srcs = [
-        ...,
-        "GeneratedJavaFile.java",  # a generated .java file
-    ],
-    deps = [":generating_rule",],  # rule that generates that file
-)
-
-
- -

Do this instead:

- -
-
-java_binary(
-    name = "DoThisInstead",
-    srcs = [
-        ...,
-        ":generating_rule",
-    ],
-)
-
-
- """, - attrs = merge_attrs( - _BASE_BINARY_ATTRS, - ({} if executable else { - "args": attr.string_list(), - "output_licenses": attr.license() if hasattr(attr, "license") else attr.string_list(), - }), - ), - executable = executable, - ) - -java_binary = make_java_binary(executable = True) - -def _java_test_initializer(**kwargs): - if "stamp" in kwargs and type(kwargs["stamp"]) == type(True): - kwargs["stamp"] = 1 if kwargs["stamp"] else 0 - if "use_launcher" in kwargs and not kwargs["use_launcher"]: - kwargs["launcher"] = None - else: - # If launcher is not set or None, set it to config flag - if "launcher" not in kwargs or not kwargs["launcher"]: - kwargs["launcher"] = semantics.LAUNCHER_FLAG_LABEL - return kwargs - -java_test = _make_binary_rule( - _bazel_java_test_impl, - doc = """ -

-A java_test() rule compiles a Java test. A test is a binary wrapper around your -test code. The test runner's main method is invoked instead of the main class being compiled. -

- -

Implicit output targets

-
    -
  • name.jar: A Java archive.
  • -
  • name_deploy.jar: A Java archive suitable - for deployment. (Only built if explicitly requested.) See the description of the - name_deploy.jar output from - java_binary for more details.
  • -
- -

-See the section on java_binary() arguments. This rule also -supports all attributes common -to all test rules (*_test). -

- -

Examples

- -
-
-
-java_library(
-    name = "tests",
-    srcs = glob(["*.java"]),
-    deps = [
-        "//java/com/foo/base:testResources",
-        "//java/com/foo/testing/util",
-    ],
-)
-
-java_test(
-    name = "AllTests",
-    size = "small",
-    runtime_deps = [
-        ":tests",
-        "//util/mysql",
-    ],
-)
-
-
- """, - attrs = merge_attrs( - BASE_TEST_ATTRIBUTES, - _BASE_BINARY_ATTRS, - { - "_lcov_merger": attr.label( - cfg = "exec", - default = configuration_field( - fragment = "coverage", - name = "output_generator", - ), - ), - "_collect_cc_coverage": attr.label( - cfg = "exec", - allow_single_file = True, - default = "@bazel_tools//tools/test:collect_cc_coverage", - ), - }, - override_attrs = { - "use_testrunner": attr.bool( - default = True, - doc = semantics.DOCS.for_attribute("use_testrunner") + """ -
-You can use this to override the default -behavior, which is to use test runner for -java_test rules, -and not use it for java_binary rules. It is unlikely -you will want to do this. One use is for AllTest -rules that are invoked by another rule (to set up a database -before running the tests, for example). The AllTest -rule must be declared as a java_binary, but should -still use the test runner as its main entry point. - -The name of a test runner class can be overridden with main_class attribute. - """, - ), - "stamp": attr.int( - default = 0, - values = [-1, 0, 1], - doc = """ -Whether to encode build information into the binary. Possible values: -
    -
  • - stamp = 1: Always stamp the build information into the binary, even in - --nostamp builds. This - setting should be avoided, since it potentially kills remote caching for the - binary and any downstream actions that depend on it. -
  • -
  • - stamp = 0: Always replace build information by constant values. This - gives good build result caching. -
  • -
  • - stamp = -1: Embedding of build information is controlled by the - --[no]stamp flag. -
  • -
-

Stamped binaries are not rebuilt unless their dependencies change.

- """, - ), - }, - remove_attrs = ["deploy_env"], - ), - test = True, - initializer = _java_test_initializer, -) diff --git a/src/main/starlark/builtins_bzl/bazel/java/bazel_java_binary_nonexec.bzl b/src/main/starlark/builtins_bzl/bazel/java/bazel_java_binary_nonexec.bzl deleted file mode 100644 index e0b8e373a7df51..00000000000000 --- a/src/main/starlark/builtins_bzl/bazel/java/bazel_java_binary_nonexec.bzl +++ /dev/null @@ -1,26 +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. - -"""Defines a java_binary rule class that is non-executable. - -There are three physical rule classes for java_binary and we want all of them -to have a name string of "java_binary" because various tooling expects that. -But we also need the rule classes to be defined in separate files. That way the -hash of their bzl environments will be different. See http://b/226379109, -specifically #20, for details. -""" - -load(":bazel/java/bazel_java_binary.bzl", "make_java_binary") - -java_binary = make_java_binary(executable = False) diff --git a/src/main/starlark/builtins_bzl/bazel/java/bazel_java_binary_wrapper.bzl b/src/main/starlark/builtins_bzl/bazel/java/bazel_java_binary_wrapper.bzl deleted file mode 100644 index 7f1a2ca81757c1..00000000000000 --- a/src/main/starlark/builtins_bzl/bazel/java/bazel_java_binary_wrapper.bzl +++ /dev/null @@ -1,36 +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. - -"""Macro encapsulating the java_binary implementation - -This is needed since the `executable` nature of the target must be computed from -the supplied value of the `create_executable` attribute. -""" - -load(":bazel/java/bazel_java_binary.bzl", java_bin_exec = "java_binary") -load(":bazel/java/bazel_java_binary_nonexec.bzl", java_bin_nonexec = "java_binary") -load(":common/java/java_binary_wrapper.bzl", "register_java_binary_rules", "register_legacy_java_binary_rules") - -def java_binary(**kwargs): - if _builtins.internal.java_common_internal_do_not_use.incompatible_disable_non_executable_java_binary(): - register_java_binary_rules( - java_bin_exec, - **kwargs - ) - else: - register_legacy_java_binary_rules( - java_bin_exec, - java_bin_nonexec, - **kwargs - ) diff --git a/src/main/starlark/builtins_bzl/common/java/android_lint.bzl b/src/main/starlark/builtins_bzl/common/java/android_lint.bzl deleted file mode 100644 index 2d14b2ac95e4cb..00000000000000 --- a/src/main/starlark/builtins_bzl/common/java/android_lint.bzl +++ /dev/null @@ -1,143 +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. - -"""Creates the android lint action for java rules""" - -load(":common/java/java_helper.bzl", "helper") -load(":common/java/java_semantics.bzl", "semantics") - -def _tokenize_opts(opts_depset): - return helper.tokenize_javacopts(ctx = None, opts = opts_depset) - -def _android_lint_action(ctx, source_files, source_jars, compilation_info): - """ - Creates an action that runs Android lint against Java source files. - - You need to add `ANDROID_LINT_IMPLICIT_ATTRS` to any rule or aspect using this call. - - To lint generated source jars (java_info.java_outputs.gen_source_jar) - add them to the `source_jar` parameter. - - `compilation_info` parameter should supply the classpath and Javac options - that were used during Java compilation. - - The Android lint tool is obtained from Java toolchain. - - Args: - ctx: (RuleContext) Used to register the action. - source_files: (list[File]) A list of .java source files - source_jars: (list[File]) A list of .jar or .srcjar files containing - source files. It should also include generated source jars. - compilation_info: (struct) Information about compilation. - - Returns: - (None|File) The Android lint output file or None if no source files were - present. - """ - - # assuming that linting is enabled for all java rules i.e. - # --experimental_limit_android_lint_to_android_constrained_java=false - - # --experimental_run_android_lint_on_java_rules= is checked in basic_java_library.bzl - - if not (source_files or source_jars): - return None - - toolchain = semantics.find_java_toolchain(ctx) - java_runtime = toolchain.java_runtime - linter = toolchain._android_linter - if not linter: - # TODO(hvd): enable after enabling in tests - # fail("android linter not set in java_toolchain") - return None - - args = ctx.actions.args() - - executable = linter.tool.executable - transitive_inputs = [] - if executable.extension != "jar": - tools = [linter.tool] - transitive_inputs.append(linter.data) - args_list = [args] - else: - jvm_args = ctx.actions.args() - jvm_args.add_all(toolchain.jvm_opt) - jvm_args.add_all(linter.jvm_opts) - jvm_args.add("-jar", executable) - executable = java_runtime.java_executable_exec_path - tools = [java_runtime.files, linter.tool.executable] - transitive_inputs.append(linter.data) - args_list = [jvm_args, args] - - classpath = compilation_info.compilation_classpath - - # TODO(hvd): get from toolchain if we need this - probably android only - bootclasspath_aux = [] - if bootclasspath_aux: - classpath = depset(transitive = [classpath, bootclasspath_aux]) - transitive_inputs.append(classpath) - - bootclasspath = toolchain.bootclasspath - transitive_inputs.append(bootclasspath) - - transitive_inputs.append(compilation_info.plugins.processor_jars) - transitive_inputs.append(compilation_info.plugins.processor_data) - args.add_all("--sources", source_files) - args.add_all("--source_jars", source_jars) - args.add_all("--bootclasspath", bootclasspath) - args.add_all("--classpath", classpath) - args.add_all("--lint_rules", compilation_info.plugins.processor_jars) - args.add("--target_label", ctx.label) - - javac_opts = compilation_info.javac_options - if javac_opts: - # wrap in a list so that map_each passes the depset to _tokenize_opts - args.add_all("--javacopts", [javac_opts], map_each = _tokenize_opts) - args.add("--") - - args.add("--lintopts") - args.add_all(linter.lint_opts) - - for package_config in linter.package_config: - if package_config.matches(ctx.label): - # wrap in a list so that map_each passes the depset to _tokenize_opts - package_opts = [package_config.javac_opts] - args.add_all(package_opts, map_each = _tokenize_opts) - transitive_inputs.append(package_config.data) - - android_lint_out = ctx.actions.declare_file("%s_android_lint_output.xml" % ctx.label.name) - args.add("--xml", android_lint_out) - - args.set_param_file_format(format = "multiline") - args.use_param_file(param_file_arg = "@%s", use_always = True) - ctx.actions.run( - mnemonic = "AndroidLint", - progress_message = semantics.LINT_PROGRESS_MESSAGE, - executable = executable, - inputs = depset( - # TODO(b/213551463) benchmark using a transitive depset instead - source_files + source_jars, - transitive = transitive_inputs, - ), - outputs = [android_lint_out], - tools = tools, - arguments = args_list, - execution_requirements = {"supports-workers": "1"}, - ) - return android_lint_out - -android_lint_subrule = subrule( - implementation = _android_lint_action, - toolchains = [semantics.JAVA_TOOLCHAIN_TYPE], -) diff --git a/src/main/starlark/builtins_bzl/common/java/basic_java_library.bzl b/src/main/starlark/builtins_bzl/common/java/basic_java_library.bzl deleted file mode 100644 index febc1d1876841e..00000000000000 --- a/src/main/starlark/builtins_bzl/common/java/basic_java_library.bzl +++ /dev/null @@ -1,280 +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. - -""" -Common code for reuse across java_* rules -""" - -load(":common/cc/cc_info.bzl", "CcInfo") -load(":common/java/android_lint.bzl", "android_lint_subrule") -load(":common/java/boot_class_path_info.bzl", "BootClassPathInfo") -load(":common/java/compile_action.bzl", "compile_action") -load(":common/java/java_common.bzl", "java_common") -load(":common/java/java_common_internal_for_builtins.bzl", "target_kind") -load(":common/java/java_info.bzl", "JavaInfo", "JavaPluginInfo") -load(":common/java/java_semantics.bzl", "semantics") -load(":common/java/proguard_validation.bzl", "validate_proguard_specs") -load(":common/rule_util.bzl", "merge_attrs") - -coverage_common = _builtins.toplevel.coverage_common - -def _filter_srcs(srcs, ext): - return [f for f in srcs if f.extension == ext] - -def _filter_provider(provider, *attrs): - return [dep[provider] for attr in attrs for dep in attr if provider in dep] - -def _get_attr_safe(ctx, attr, default): - return getattr(ctx.attr, attr) if hasattr(ctx.attr, attr) else default - -# TODO(b/11285003): disallow jar files in deps, require java_import instead -def _filter_javainfo_and_legacy_jars(attr): - dep_list = [] - - # Native code collected data into a NestedSet, using add for legacy jars and - # addTransitive for JavaInfo. This resulted in legacy jars being first in the list. - for dep in attr: - kind = target_kind(dep) - if not JavaInfo in dep or kind == "java_binary" or kind == "java_test": - for file in dep[DefaultInfo].files.to_list(): - if file.extension == "jar": - # Native doesn't construct JavaInfo - java_info = JavaInfo(output_jar = file, compile_jar = file) - dep_list.append(java_info) - - for dep in attr: - if JavaInfo in dep: - dep_list.append(dep[JavaInfo]) - return dep_list - -def basic_java_library( - ctx, - srcs, - deps = [], - runtime_deps = [], - plugins = [], - exports = [], - exported_plugins = [], - resources = [], - resource_jars = [], - classpath_resources = [], - javacopts = [], - neverlink = False, - enable_compile_jar_action = True, - coverage_config = None, - proguard_specs = None, - add_exports = [], - add_opens = [], - bootclasspath = None, - javabuilder_jvm_flags = None): - """ - Creates actions that compile and lint Java sources, sets up coverage and returns JavaInfo, InstrumentedFilesInfo and output groups. - - The call creates actions and providers needed and shared by `java_library`, - `java_plugin`,`java_binary`, and `java_test` rules and it is primarily - intended to be used in those rules. - - Before compilation coverage.runner is added to the dependencies and if - present plugins are extended with the value of `--plugin` flag. - - Args: - ctx: (RuleContext) Used to register the actions. - srcs: (list[File]) The list of source files that are processed to create the target. - deps: (list[Target]) The list of other libraries to be linked in to the target. - runtime_deps: (list[Target]) Libraries to make available to the final binary or test at runtime only. - plugins: (list[Target]) Java compiler plugins to run at compile-time. - exports: (list[Target]) Exported libraries. - exported_plugins: (list[Target]) The list of `java_plugin`s (e.g. annotation - processors) to export to libraries that directly depend on this library. - resources: (list[File]) A list of data files to include in a Java jar. - resource_jars: (list[File]) A list of jar files to unpack and include in a - Java jar. - classpath_resources: (list[File]) - javacopts: (list[str]) - neverlink: (bool) Whether this library should only be used for compilation and not at runtime. - enable_compile_jar_action: (bool) Enables header compilation or ijar creation. - coverage_config: (struct{runner:JavaInfo, support_files:list[File]|depset[File], env:dict[str,str]}) - Coverage configuration. `runner` is added to dependencies during - compilation, `support_files` and `env` is returned in InstrumentedFilesInfo. - proguard_specs: (list[File]) Files to be used as Proguard specification. - Proguard validation is done only when the parameter is set. - add_exports: (list[str]) Allow this library to access the given /. - add_opens: (list[str]) Allow this library to reflectively access the given /. - bootclasspath: (Target) The JDK APIs to compile this library against. - javabuilder_jvm_flags: (list[str]) Additional JVM flags to pass to JavaBuilder. - Returns: - (dict[str, Provider], - {files_to_build: list[File], - runfiles: list[File], - output_groups: dict[str,list[File]]}) - """ - source_files = _filter_srcs(srcs, "java") - source_jars = _filter_srcs(srcs, "srcjar") - - plugins_javaplugininfo = _collect_plugins(plugins) - plugins_javaplugininfo.append(ctx.attr._java_plugins[JavaPluginInfo]) - - properties = _filter_srcs(srcs, "properties") - if properties: - resources = list(resources) - resources.extend(properties) - - java_info, compilation_info = compile_action( - ctx, - ctx.outputs.classjar, - ctx.outputs.sourcejar, - source_files, - source_jars, - collect_deps(deps) + ([coverage_config.runner] if coverage_config and coverage_config.runner else []), - collect_deps(runtime_deps), - plugins_javaplugininfo, - collect_deps(exports), - _collect_plugins(exported_plugins), - resources, - resource_jars, - classpath_resources, - _collect_native_libraries(deps, runtime_deps, exports), - javacopts, - neverlink, - ctx.fragments.java.strict_java_deps, - enable_compile_jar_action, - add_exports = add_exports, - add_opens = add_opens, - bootclasspath = bootclasspath[BootClassPathInfo] if bootclasspath else None, - javabuilder_jvm_flags = javabuilder_jvm_flags, - ) - target = {"JavaInfo": java_info} - - output_groups = dict( - compilation_outputs = compilation_info.files_to_build, - _source_jars = java_info.transitive_source_jars, - _direct_source_jars = java_info.source_jars, - ) - - if ctx.fragments.java.run_android_lint: - generated_source_jars = [ - output.generated_source_jar - for output in java_info.java_outputs - if output.generated_source_jar != None - ] - lint_output = android_lint_subrule( - source_files, - source_jars + generated_source_jars, - compilation_info, - ) - if lint_output: - output_groups["_validation"] = [lint_output] - - target["InstrumentedFilesInfo"] = coverage_common.instrumented_files_info( - ctx, - source_attributes = ["srcs"], - dependency_attributes = ["deps", "data", "resources", "resource_jars", "exports", "runtime_deps", "jars"], - coverage_support_files = coverage_config.support_files if coverage_config else depset(), - coverage_environment = coverage_config.env if coverage_config else {}, - ) - - if proguard_specs != None: - target["ProguardSpecProvider"] = validate_proguard_specs( - ctx, - proguard_specs, - [deps, runtime_deps, exports], - ) - output_groups["_hidden_top_level_INTERNAL_"] = target["ProguardSpecProvider"].specs - - return target, struct( - files_to_build = compilation_info.files_to_build, - runfiles = compilation_info.runfiles, - output_groups = output_groups, - ) - -def _collect_plugins(plugins): - """Collects plugins from an attribute. - - Use this call to collect plugins from `plugins` or `exported_plugins` attribute. - - The call simply extracts JavaPluginInfo provider. - - Args: - plugins: (list[Target]) Attribute to collect plugins from. - Returns: - (list[JavaPluginInfo]) The plugins. - """ - return _filter_provider(JavaPluginInfo, plugins) - -def collect_deps(deps): - """Collects dependencies from an attribute. - - Use this call to collect plugins from `deps`, `runtime_deps`, or `exports` attribute. - - The call extracts JavaInfo and additionaly also "legacy jars". "legacy jars" - are wrapped into a JavaInfo. - - Args: - deps: (list[Target]) Attribute to collect dependencies from. - Returns: - (list[JavaInfo]) The dependencies. - """ - return _filter_javainfo_and_legacy_jars(deps) - -def _collect_native_libraries(*attrs): - """Collects native libraries from a list of attributes. - - Use this call to collect native libraries from `deps`, `runtime_deps`, or `exports` attributes. - - The call simply extracts CcInfo provider. - Args: - *attrs: (*list[Target]) Attribute to collect native libraries from. - Returns: - (list[CcInfo]) The native library dependencies. - """ - return _filter_provider(CcInfo, *attrs) - -def construct_defaultinfo(ctx, files_to_build, files, neverlink, *extra_attrs): - """Constructs DefaultInfo for Java library like rule. - - Args: - ctx: (RuleContext) Used to construct the runfiles. - files_to_build: (list[File]) List of the files built by the rule. - files: (list[File]) List of the files include in runfiles. - neverlink: (bool) When true empty runfiles are constructed. - *extra_attrs: (list[Target]) Extra attributes to merge runfiles from. - - Returns: - (DefaultInfo) DefaultInfo provider. - """ - if neverlink: - runfiles = None - else: - runfiles = ctx.runfiles(files = files, collect_default = True) - runfiles = runfiles.merge_all([dep[DefaultInfo].default_runfiles for attr in extra_attrs for dep in attr]) - default_info = DefaultInfo( - files = depset(files_to_build), - runfiles = runfiles, - ) - return default_info - -BASIC_JAVA_LIBRARY_IMPLICIT_ATTRS = merge_attrs( - { - "_java_plugins": attr.label( - default = semantics.JAVA_PLUGINS_FLAG_ALIAS_LABEL, - providers = [JavaPluginInfo], - ), - # TODO(b/245144242): Used by IDE integration, remove when toolchains are used - "_java_toolchain": attr.label( - default = semantics.JAVA_TOOLCHAIN_LABEL, - providers = [java_common.JavaToolchainInfo], - ), - "_use_auto_exec_groups": attr.bool(default = True), - }, -) diff --git a/src/main/starlark/builtins_bzl/common/java/compile_action.bzl b/src/main/starlark/builtins_bzl/common/java/compile_action.bzl deleted file mode 100644 index 7b9c20ae1a5768..00000000000000 --- a/src/main/starlark/builtins_bzl/common/java/compile_action.bzl +++ /dev/null @@ -1,172 +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 compile action -""" - -load(":common/java/java_common_internal_for_builtins.bzl", _compile_private_for_builtins = "compile") -load(":common/java/java_semantics.bzl", "semantics") - -def _filter_strict_deps(mode): - return "error" if mode in ["strict", "default"] else mode - -def _collect_plugins(deps, plugins): - transitive_processor_jars = [] - transitive_processor_data = [] - for plugin in plugins: - transitive_processor_jars.append(plugin.plugins.processor_jars) - transitive_processor_data.append(plugin.plugins.processor_data) - for dep in deps: - transitive_processor_jars.append(dep.plugins.processor_jars) - transitive_processor_data.append(dep.plugins.processor_data) - return struct( - processor_jars = depset(transitive = transitive_processor_jars), - processor_data = depset(transitive = transitive_processor_data), - ) - -def compile_action( - ctx, - output_class_jar, - output_source_jar, - source_files = [], - source_jars = [], - deps = [], - runtime_deps = [], - plugins = [], - exports = [], - exported_plugins = [], - resources = [], - resource_jars = [], - classpath_resources = [], - native_libraries = [], - javacopts = [], - neverlink = False, - strict_deps = "ERROR", - enable_compile_jar_action = True, - add_exports = [], - add_opens = [], - bootclasspath = None, - javabuilder_jvm_flags = None): - """ - Creates actions that compile Java sources, produce source jar, and produce header jar and returns JavaInfo. - - Use this call when you need the most basic and consistent Java compilation. - - Most parameters correspond to attributes on a java_library (srcs, deps, - plugins, resources ...) except they are more strict, for example: - - - Where java_library's srcs attribute allows mixing of .java, .srcjar, and - .properties files the arguments accepted by this call should be strictly - separated into source_files, source_jars, and resources parameter. - - deps parameter accepts only JavaInfo providers and plugins parameter only - JavaPluginInfo - - The call creates following actions and files: - - compiling Java sources to a class jar (output_class_jar parameter) - - a source jar (output_source_jar parameter) - - optionally a jar containing plugin generated classes when plugins are present - - optionally a jar containing plugin generated sources - - jdeps file containing dependencies used during compilation - - other files used to speed up incremental builds: - - a header jar - a jar containing only method signatures without implementation - - compile jdeps - dependencies used during header compilation - - The returned JavaInfo provider may be used as a "fully-qualified" dependency - to a java_library. - - Args: - ctx: (RuleContext) Used to register the actions. - output_class_jar: (File) Output class .jar file. The file needs to be declared. - output_source_jar: (File) Output source .jar file. The file needs to be declared. - source_files: (list[File]) A list of .java source files to compile. - At least one of source_files or source_jars parameter must be specified. - source_jars: (list[File]) A list of .jar or .srcjar files containing - source files to compile. - At least one of source_files or source_jars parameter must be specified. - deps: (list[JavaInfo]) A list of dependencies. - runtime_deps: (list[JavaInfo]) A list of runtime dependencies. - plugins: (list[JavaPluginInfo]) A list of plugins. - exports: (list[JavaInfo]) A list of exports. - exported_plugins: (list[JavaInfo]) A list of exported plugins. - resources: (list[File]) A list of resources. - resource_jars: (list[File]) A list of jars to unpack. - classpath_resources: (list[File]) A list of classpath resources. - native_libraries: (list[CcInfo]) C++ native library dependencies that are - needed for this library. - javacopts: (list[str]) A list of the desired javac options. The options - may contain `$(location ..)` templates that will be expanded. - neverlink: (bool) Whether or not this library should be used only for - compilation and not at runtime. - strict_deps: (str) A string that specifies how to handle strict deps. - Possible values: 'OFF', 'ERROR', 'WARN' and 'DEFAULT'. For more details - see https://bazel.build/docs/user-manual#strict-java-deps. - By default 'ERROR'. - 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. - add_exports: (list[str]) Allow this library to access the given /. - add_opens: (list[str]) Allow this library to reflectively access the given /. - bootclasspath: (BootClassPathInfo) The set of JDK APIs to compile this library against. - javabuilder_jvm_flags: (list[str]) Additional JVM flags to pass to JavaBuilder. - - Returns: - ((JavaInfo, {files_to_build: list[File], - runfiles: list[File], - compilation_classpath: list[File], - plugins: {processor_jars, - processor_data: depset[File]}})) - A tuple with JavaInfo provider and additional compilation info. - - Files_to_build may include an empty .jar file when there are no sources - or resources present, whereas runfiles in this case are empty. - """ - - java_info = _compile_private_for_builtins( - ctx, - output = output_class_jar, - java_toolchain = semantics.find_java_toolchain(ctx), - source_files = source_files, - source_jars = source_jars, - resources = resources, - resource_jars = resource_jars, - classpath_resources = classpath_resources, - plugins = plugins, - deps = deps, - native_libraries = native_libraries, - runtime_deps = runtime_deps, - exports = exports, - exported_plugins = exported_plugins, - javac_opts = [ctx.expand_location(opt) for opt in javacopts], - neverlink = neverlink, - output_source_jar = output_source_jar, - strict_deps = _filter_strict_deps(strict_deps), - enable_compile_jar_action = enable_compile_jar_action, - add_exports = add_exports, - add_opens = add_opens, - bootclasspath = bootclasspath, - javabuilder_jvm_flags = javabuilder_jvm_flags, - ) - - compilation_info = struct( - files_to_build = [output_class_jar], - runfiles = [output_class_jar] if source_files or source_jars or resources else [], - # TODO(ilist): collect compile_jars from JavaInfo in deps & exports - compilation_classpath = java_info.compilation_info.compilation_classpath, - javac_options = java_info.compilation_info.javac_options, - plugins = _collect_plugins(deps, plugins), - ) - - return java_info, compilation_info diff --git a/src/main/starlark/builtins_bzl/common/java/import_deps_check.bzl b/src/main/starlark/builtins_bzl/common/java/import_deps_check.bzl deleted file mode 100644 index cfdce3b0c54cc2..00000000000000 --- a/src/main/starlark/builtins_bzl/common/java/import_deps_check.bzl +++ /dev/null @@ -1,79 +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. - -"""Creates the import deps checker for java rules""" - -load(":common/java/java_semantics.bzl", "semantics") - -def import_deps_check( - ctx, - jars_to_check, - declared_deps, - transitive_deps, - rule_class): - """ - Creates actions that checks import deps for java rules. - - Args: - ctx: (RuleContext) Used to register the actions. - jars_to_check: (list[File]) A list of jars files to check. - declared_deps: (list[File]) A list of direct dependencies. - transitive_deps: (list[File]) A list of transitive dependencies. - rule_class: (String) Rule class. - - Returns: - (File) Output file of the created action. - """ - java_toolchain = semantics.find_java_toolchain(ctx) - deps_checker = java_toolchain._deps_checker - if deps_checker == None: - return None - - jdeps_output = ctx.actions.declare_file("_%s/%s/jdeps.proto" % (rule_class, ctx.label.name)) - - args = ctx.actions.args() - args.add("-jar", deps_checker) - args.add_all(jars_to_check, before_each = "--input") - args.add_all(declared_deps, before_each = "--directdep") - args.add_all( - depset(order = "preorder", transitive = [declared_deps, transitive_deps]), - before_each = "--classpath_entry", - ) - args.add_all(java_toolchain.bootclasspath, before_each = "--bootclasspath_entry") - args.add("--checking_mode=error") - args.add("--jdeps_output", jdeps_output) - args.add("--rule_label", ctx.label) - - inputs = depset( - jars_to_check, - transitive = [ - declared_deps, - transitive_deps, - java_toolchain.bootclasspath, - ], - ) - tools = [deps_checker, java_toolchain.java_runtime.files] - - ctx.actions.run( - mnemonic = "ImportDepsChecker", - progress_message = "Checking the completeness of the deps for %s" % jars_to_check, - executable = java_toolchain.java_runtime.java_executable_exec_path, - arguments = [args], - inputs = inputs, - outputs = [jdeps_output], - tools = tools, - toolchain = semantics.JAVA_TOOLCHAIN_TYPE, - ) - - return jdeps_output diff --git a/src/main/starlark/builtins_bzl/common/java/java_binary.bzl b/src/main/starlark/builtins_bzl/common/java/java_binary.bzl deleted file mode 100644 index 888044c4b17526..00000000000000 --- a/src/main/starlark/builtins_bzl/common/java/java_binary.bzl +++ /dev/null @@ -1,817 +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. - -""" Implementation of java_binary for bazel """ - -load(":common/cc/cc_common.bzl", "cc_common") -load(":common/cc/cc_info.bzl", "CcInfo") -load(":common/cc/semantics.bzl", cc_semantics = "semantics") -load(":common/java/basic_java_library.bzl", "BASIC_JAVA_LIBRARY_IMPLICIT_ATTRS", "basic_java_library", "collect_deps") -load(":common/java/boot_class_path_info.bzl", "BootClassPathInfo") -load(":common/java/java_binary_deploy_jar.bzl", "create_deploy_archive") -load(":common/java/java_common.bzl", "java_common") -load( - ":common/java/java_common_internal_for_builtins.bzl", - "collect_native_deps_dirs", - "get_runtime_classpath_for_archive", -) -load(":common/java/java_helper.bzl", "helper") -load(":common/java/java_info.bzl", "JavaCompilationInfo", "JavaInfo", "JavaPluginInfo", "to_java_binary_info") -load(":common/java/java_semantics.bzl", "semantics") -load(":common/paths.bzl", "paths") -load(":common/proto/proto_info.bzl", "ProtoInfo") -load(":common/rule_util.bzl", "merge_attrs") - -CcLauncherInfo = _builtins.internal.cc_internal.launcher_provider - -InternalDeployJarInfo = provider( - "Provider for passing info to deploy jar rule", - fields = [ - "java_attrs", - "strip_as_default", - "add_exports", - "add_opens", - ], -) - -def basic_java_binary( - ctx, - deps, - runtime_deps, - resources, - main_class, - coverage_main_class, - coverage_config, - launcher_info, - executable, - strip_as_default, - extension_registry_provider = None, - is_test_rule_class = False): - """Creates actions for compiling and linting java sources, coverage support, and sources jar (_deploy-src.jar). - - Args: - ctx: (RuleContext) The rule context - deps: (list[Target]) The list of other targets to be compiled with - runtime_deps: (list[Target]) The list of other targets to be linked in - resources: (list[File]) The list of data files to be included in the class jar - main_class: (String) FQN of the java main class - coverage_main_class: (String) FQN of the actual main class if coverage is enabled - coverage_config: (Struct|None) If coverage is enabled, a struct with fields (runner, manifest, env, support_files), None otherwise - launcher_info: (Struct) Structure with fields (launcher, unstripped_launcher, runfiles, runtime_jars, jvm_flags, classpath_resources) - executable: (File) The executable output of the rule - strip_as_default: (bool) Whether this target outputs a stripped launcher and deploy jar - extension_registry_provider: (GeneratedExtensionRegistryProvider) internal param, do not use - is_test_rule_class: (bool) Whether this rule is a test rule - - Returns: - Tuple( - dict[str, Provider], // providers - Struct( // default info - files_to_build: depset(File), - runfiles: Runfiles, - executable: File - ), - list[String] // jvm flags - ) - - """ - if not ctx.attr.create_executable and (ctx.attr.launcher and cc_common.launcher_provider in ctx.attr.launcher): - fail("launcher specified but create_executable is false") - if not ctx.attr.use_launcher and (ctx.attr.launcher and ctx.attr.launcher.label != semantics.LAUNCHER_FLAG_LABEL): - fail("launcher specified but use_launcher is false") - - if not ctx.attr.srcs and ctx.attr.deps: - fail("deps not allowed without srcs; move to runtime_deps?") - - module_flags = [dep[JavaInfo].module_flags_info for dep in runtime_deps if JavaInfo in dep] - add_exports = depset(ctx.attr.add_exports, transitive = [m.add_exports for m in module_flags]) - add_opens = depset(ctx.attr.add_opens, transitive = [m.add_opens for m in module_flags]) - - classpath_resources = [] - classpath_resources.extend(launcher_info.classpath_resources) - if hasattr(ctx.files, "classpath_resources"): - classpath_resources.extend(ctx.files.classpath_resources) - - toolchain = semantics.find_java_toolchain(ctx) - timezone_data = [toolchain._timezone_data] if toolchain._timezone_data else [] - target, common_info = basic_java_library( - ctx, - srcs = ctx.files.srcs, - deps = deps, - runtime_deps = runtime_deps, - plugins = ctx.attr.plugins, - resources = resources, - resource_jars = timezone_data, - classpath_resources = classpath_resources, - javacopts = ctx.attr.javacopts, - neverlink = ctx.attr.neverlink, - enable_compile_jar_action = False, - coverage_config = coverage_config, - add_exports = ctx.attr.add_exports, - add_opens = ctx.attr.add_opens, - bootclasspath = ctx.attr.bootclasspath, - ) - java_info = target["JavaInfo"] - compilation_info = java_info.compilation_info - runtime_classpath = depset( - order = "preorder", - transitive = [ - java_info.transitive_runtime_jars - for java_info in ( - collect_deps(ctx.attr.runtime_deps + deps) + - ([coverage_config.runner] if coverage_config and coverage_config.runner else []) - ) - ], - ) - if extension_registry_provider: - runtime_classpath = depset(order = "preorder", direct = [extension_registry_provider.class_jar], transitive = [runtime_classpath]) - java_info = java_common.merge( - [ - java_info, - JavaInfo( - output_jar = extension_registry_provider.class_jar, - compile_jar = None, - source_jar = extension_registry_provider.src_jar, - ), - ], - ) - compilation_info = JavaCompilationInfo( - compilation_classpath = compilation_info.compilation_classpath, - runtime_classpath = runtime_classpath, - boot_classpath = compilation_info.boot_classpath, - javac_options = compilation_info.javac_options, - ) - - java_attrs = _collect_attrs(ctx, runtime_classpath, classpath_resources) - - jvm_flags = [] - - jvm_flags.extend(launcher_info.jvm_flags) - - native_libs_depsets = [] - for dep in runtime_deps: - if JavaInfo in dep: - native_libs_depsets.append(dep[JavaInfo].transitive_native_libraries) - if CcInfo in dep: - native_libs_depsets.append(dep[CcInfo].transitive_native_libraries()) - native_libs_dirs = collect_native_deps_dirs(depset(transitive = native_libs_depsets)) - if native_libs_dirs: - prefix = "${JAVA_RUNFILES}/" + ctx.workspace_name + "/" - jvm_flags.append("-Djava.library.path=%s" % ( - ":".join([prefix + d for d in native_libs_dirs]) - )) - - jvm_flags.extend(ctx.fragments.java.default_jvm_opts) - jvm_flags.extend([ctx.expand_make_variables( - "jvm_flags", - ctx.expand_location(flag, ctx.attr.data, short_paths = True), - {}, - ) for flag in ctx.attr.jvm_flags]) - - # TODO(cushon): make string formatting lazier once extend_template support is added - # https://github.com/bazelbuild/proposals#:~:text=2022%2D04%2D25,Starlark - jvm_flags.extend(["--add-exports=%s=ALL-UNNAMED" % x for x in add_exports.to_list()]) - jvm_flags.extend(["--add-opens=%s=ALL-UNNAMED" % x for x in add_opens.to_list()]) - - files_to_build = [] - - if executable: - files_to_build.append(executable) - - output_groups = common_info.output_groups - - if coverage_config: - _generate_coverage_manifest(ctx, coverage_config.manifest, java_attrs.runtime_classpath) - files_to_build.append(coverage_config.manifest) - - if extension_registry_provider: - files_to_build.append(extension_registry_provider.class_jar) - output_groups["_direct_source_jars"] = ( - output_groups["_direct_source_jars"] + [extension_registry_provider.src_jar] - ) - output_groups["_source_jars"] = depset( - direct = [extension_registry_provider.src_jar], - transitive = [output_groups["_source_jars"]], - ) - - if (ctx.fragments.java.one_version_enforcement_on_java_tests or not is_test_rule_class): - one_version_output = _create_one_version_check(ctx, java_attrs.runtime_classpath, is_test_rule_class) - else: - one_version_output = None - - validation_outputs = [one_version_output] if one_version_output else [] - - _create_deploy_sources_jar(ctx, output_groups["_source_jars"]) - - files = depset(files_to_build + common_info.files_to_build) - - transitive_runfiles_artifacts = depset(transitive = [ - files, - java_attrs.runtime_classpath, - depset(transitive = launcher_info.runfiles), - ]) - - runfiles = ctx.runfiles( - transitive_files = transitive_runfiles_artifacts, - collect_default = True, - ) - - if launcher_info.launcher: - default_launcher = helper.filter_launcher_for_target(ctx) - default_launcher_artifact = helper.launcher_artifact_for_target(ctx) - default_launcher_runfiles = default_launcher[DefaultInfo].default_runfiles - if default_launcher_artifact == launcher_info.launcher: - runfiles = runfiles.merge(default_launcher_runfiles) - else: - # N.B. The "default launcher" referred to here is the launcher target specified through - # an attribute or flag. We wish to retain the runfiles of the default launcher, *except* - # for the original cc_binary artifact, because we've swapped it out with our custom - # launcher. Hence, instead of calling builder.addTarget(), or adding an odd method - # to Runfiles.Builder, we "unravel" the call and manually add things to the builder. - # Because the NestedSet representing each target's launcher runfiles is re-built here, - # we may see increased memory consumption for representing the target's runfiles. - runfiles = runfiles.merge( - ctx.runfiles( - files = [launcher_info.launcher], - transitive_files = depset([ - file - for file in default_launcher_runfiles.files.to_list() - if file != default_launcher_artifact - ]), - symlinks = default_launcher_runfiles.symlinks, - root_symlinks = default_launcher_runfiles.root_symlinks, - ), - ) - - runfiles = runfiles.merge_all([ - dep[DefaultInfo].default_runfiles - for dep in ctx.attr.runtime_deps - if DefaultInfo in dep - ]) - - if validation_outputs: - output_groups["_validation"] = output_groups.get("_validation", []) + validation_outputs - - _filter_validation_output_group(ctx, output_groups) - - java_binary_info = to_java_binary_info(java_info, compilation_info) - - internal_deploy_jar_info = InternalDeployJarInfo( - java_attrs = java_attrs, - strip_as_default = strip_as_default, - add_exports = add_exports, - add_opens = add_opens, - ) - - # "temporary" workaround for https://github.com/bazelbuild/intellij/issues/5845 - extra_files = [] - if is_test_rule_class and ctx.fragments.java.auto_create_java_test_deploy_jars(): - extra_files.append(_auto_create_deploy_jar(ctx, internal_deploy_jar_info, launcher_info, main_class, coverage_main_class)) - - default_info = struct( - files = depset(extra_files, transitive = [files]), - runfiles = runfiles, - executable = executable, - ) - - return { - "OutputGroupInfo": OutputGroupInfo(**output_groups), - "JavaInfo": java_binary_info, - "InstrumentedFilesInfo": target["InstrumentedFilesInfo"], - "JavaRuntimeClasspathInfo": java_common.JavaRuntimeClasspathInfo(runtime_classpath = java_info.transitive_runtime_jars), - "InternalDeployJarInfo": internal_deploy_jar_info, - }, default_info, jvm_flags - -def _collect_attrs(ctx, runtime_classpath, classpath_resources): - deploy_env_jars = depset(transitive = [ - dep[java_common.JavaRuntimeClasspathInfo].runtime_classpath - for dep in ctx.attr.deploy_env - ]) if hasattr(ctx.attr, "deploy_env") else depset() - - runtime_classpath_for_archive = get_runtime_classpath_for_archive(runtime_classpath, deploy_env_jars) - runtime_jars = [ctx.outputs.classjar] - - resources = [p for p in ctx.files.srcs if p.extension == "properties"] - transitive_resources = [] - for r in ctx.attr.resources: - transitive_resources.append( - r[ProtoInfo].transitive_sources if ProtoInfo in r else r.files, - ) - - resource_names = dict() - for r in classpath_resources: - if r.basename in resource_names: - fail("entries must have different file names (duplicate: %s)" % r.basename) - resource_names[r.basename] = None - - return struct( - runtime_jars = depset(runtime_jars), - runtime_classpath_for_archive = runtime_classpath_for_archive, - classpath_resources = depset(classpath_resources), - runtime_classpath = depset(order = "preorder", direct = runtime_jars, transitive = [runtime_classpath]), - resources = depset(resources, transitive = transitive_resources), - ) - -def _generate_coverage_manifest(ctx, output, runtime_classpath): - ctx.actions.write( - output = output, - content = "\n".join([file.short_path for file in runtime_classpath.to_list()]), - ) - -def _create_one_version_check(ctx, inputs, is_test_rule_class): - one_version_level = ctx.fragments.java.one_version_enforcement_level - if one_version_level == "OFF": - return None - tool = helper.check_and_get_one_version_attribute(ctx, "_one_version_tool") - - if is_test_rule_class: - toolchain = semantics.find_java_toolchain(ctx) - allowlist = toolchain._one_version_allowlist_for_tests - else: - allowlist = helper.check_and_get_one_version_attribute(ctx, "_one_version_allowlist") - - if not tool: # On Mac oneversion tool is not available - return None - - output = ctx.actions.declare_file("%s-one-version.txt" % ctx.label.name) - - args = ctx.actions.args() - args.set_param_file_format("shell").use_param_file("@%s", use_always = True) - - one_version_inputs = [] - args.add("--output", output) - if allowlist: - args.add("--allowlist", allowlist) - one_version_inputs.append(allowlist) - if one_version_level == "WARNING": - args.add("--succeed_on_found_violations") - args.add_all( - "--inputs", - inputs, - map_each = helper.jar_and_target_arg_mapper, - ) - - ctx.actions.run( - mnemonic = "JavaOneVersion", - progress_message = "Checking for one-version violations in %{label}", - executable = tool, - toolchain = semantics.JAVA_TOOLCHAIN_TYPE, - inputs = depset(one_version_inputs, transitive = [inputs]), - tools = [tool], - outputs = [output], - arguments = [args], - ) - - return output - -def _create_deploy_sources_jar(ctx, sources): - helper.create_single_jar( - ctx.actions, - toolchain = semantics.find_java_toolchain(ctx), - output = ctx.outputs.deploysrcjar, - sources = sources, - ) - -def _filter_validation_output_group(ctx, output_group): - to_exclude = depset(transitive = [ - dep[OutputGroupInfo]._validation - for dep in ctx.attr.deploy_env - if OutputGroupInfo in dep and hasattr(dep[OutputGroupInfo], "_validation") - ]) if hasattr(ctx.attr, "deploy_env") else depset() - if to_exclude: - transitive_validations = depset(transitive = [ - _get_validations_from_attr(ctx, attr_name) - for attr_name in dir(ctx.attr) - # we also exclude implicit, cfg=host/exec and tool attributes - if not attr_name.startswith("_") and - attr_name not in [ - "deploy_env", - "applicable_licenses", - "package_metadata", - "plugins", - "translations", - # special ignored attributes - "compatible_with", - "restricted_to", - "exec_compatible_with", - "target_compatible_with", - ] - ]) - if not ctx.attr.create_executable: - excluded_set = {x: None for x in to_exclude.to_list()} - transitive_validations = [ - x - for x in transitive_validations.to_list() - if x not in excluded_set - ] - output_group["_validation_transitive"] = transitive_validations - -def _get_validations_from_attr(ctx, attr_name): - attr = getattr(ctx.attr, attr_name) - if type(attr) == "list": - return depset(transitive = [_get_validations_from_target(t) for t in attr]) - else: - return _get_validations_from_target(attr) - -def _get_validations_from_target(target): - if ( - type(target) == "Target" and - OutputGroupInfo in target and - hasattr(target[OutputGroupInfo], "_validation") - ): - return target[OutputGroupInfo]._validation - else: - return depset() - -# TODO: bazelbuild/intellij/issues/5845 - remove this once no longer required -# this need not be completely identical to the regular deploy jar since we only -# care about packaging the classpath -def _auto_create_deploy_jar(ctx, info, launcher_info, main_class, coverage_main_class): - output = ctx.actions.declare_file(ctx.label.name + "_auto_deploy.jar") - java_attrs = info.java_attrs - runtime_classpath = depset( - direct = launcher_info.runtime_jars, - transitive = [ - java_attrs.runtime_jars, - java_attrs.runtime_classpath_for_archive, - ], - order = "preorder", - ) - create_deploy_archive( - ctx, - launcher = launcher_info.launcher, - main_class = main_class, - coverage_main_class = coverage_main_class, - resources = java_attrs.resources, - classpath_resources = java_attrs.classpath_resources, - runtime_classpath = runtime_classpath, - manifest_lines = info.manifest_lines, - build_info_files = [], - build_target = str(ctx.label), - output = output, - one_version_level = ctx.fragments.java.one_version_enforcement_level, - one_version_allowlist = helper.check_and_get_one_version_attribute(ctx, "_one_version_allowlist"), - multi_release = ctx.fragments.java.multi_release_deploy_jars, - hermetic = hasattr(ctx.attr, "hermetic") and ctx.attr.hermetic, - add_exports = info.add_exports, - add_opens = info.add_opens, - ) - return output - -BASIC_JAVA_BINARY_ATTRIBUTES = merge_attrs( - BASIC_JAVA_LIBRARY_IMPLICIT_ATTRS, - { - "srcs": attr.label_list( - allow_files = [".java", ".srcjar", ".properties"] + semantics.EXTRA_SRCS_TYPES, - flags = ["DIRECT_COMPILE_TIME_INPUT", "ORDER_INDEPENDENT"], - doc = """ -The list of source files that are processed to create the target. -This attribute is almost always required; see exceptions below. -

-Source files of type .java are compiled. In case of generated -.java files it is generally advisable to put the generating rule's name -here instead of the name of the file itself. This not only improves readability but -makes the rule more resilient to future changes: if the generating rule generates -different files in the future, you only need to fix one place: the outs of -the generating rule. You should not list the generating rule in deps -because it is a no-op. -

-

-Source files of type .srcjar are unpacked and compiled. (This is useful if -you need to generate a set of .java files with a genrule.) -

-

-Rules: if the rule (typically genrule or filegroup) generates -any of the files listed above, they will be used the same way as described for source -files. -

- -

-This argument is almost always required, except if a -main_class attribute specifies a -class on the runtime classpath or you specify the runtime_deps argument. -

- """, - ), - "deps": attr.label_list( - allow_files = [".jar"], - allow_rules = semantics.ALLOWED_RULES_IN_DEPS + semantics.ALLOWED_RULES_IN_DEPS_WITH_WARNING, - providers = [ - [CcInfo], - [JavaInfo], - ], - flags = ["SKIP_ANALYSIS_TIME_FILETYPE_CHECK"], - doc = """ -The list of other libraries to be linked in to the target. -See general comments about deps at -Typical attributes defined by -most build rules. - """, - ), - "resources": attr.label_list( - allow_files = True, - flags = ["SKIP_CONSTRAINTS_OVERRIDE", "ORDER_INDEPENDENT"], - doc = """ -A list of data files to include in a Java jar. - -

-Resources may be source files or generated files. -

- """ + semantics.DOCS.for_attribute("resources"), - ), - "runtime_deps": attr.label_list( - allow_files = [".jar"], - allow_rules = semantics.ALLOWED_RULES_IN_DEPS, - providers = [[CcInfo], [JavaInfo]], - flags = ["SKIP_ANALYSIS_TIME_FILETYPE_CHECK"], - doc = """ -Libraries to make available to the final binary or test at runtime only. -Like ordinary deps, these will appear on the runtime classpath, but unlike -them, not on the compile-time classpath. Dependencies needed only at runtime should be -listed here. Dependency-analysis tools should ignore targets that appear in both -runtime_deps and deps. - """, - ), - "data": attr.label_list( - allow_files = True, - flags = ["SKIP_CONSTRAINTS_OVERRIDE"], - doc = """ -The list of files needed by this library at runtime. -See general comments about data -at Typical attributes defined by -most build rules. - """ + semantics.DOCS.for_attribute("data"), - ), - "plugins": attr.label_list( - providers = [JavaPluginInfo], - allow_files = True, - cfg = "exec", - doc = """ -Java compiler plugins to run at compile-time. -Every java_plugin specified in this attribute will be run whenever this rule -is built. A library may also inherit plugins from dependencies that use -exported_plugins. Resources -generated by the plugin will be included in the resulting jar of this rule. - """, - ), - "deploy_env": attr.label_list( - providers = [java_common.JavaRuntimeClasspathInfo], - allow_files = False, - doc = """ -A list of other java_binary targets which represent the deployment -environment for this binary. -Set this attribute when building a plugin which will be loaded by another -java_binary.
Setting this attribute excludes all dependencies from -the runtime classpath (and the deploy jar) of this binary that are shared between this -binary and the targets specified in deploy_env. - """, - ), - "launcher": attr.label( - # TODO(b/295221112): add back CcLauncherInfo - allow_files = False, - doc = """ -Specify a binary that will be used to run your Java program instead of the -normal bin/java program included with the JDK. -The target must be a cc_binary. Any cc_binary that -implements the - -Java Invocation API can be specified as a value for this attribute. - -

By default, Bazel will use the normal JDK launcher (bin/java or java.exe).

- -

The related ---java_launcher Bazel flag affects only those -java_binary and java_test targets that have -not specified a launcher attribute.

- -

Note that your native (C++, SWIG, JNI) dependencies will be built differently -depending on whether you are using the JDK launcher or another launcher:

- -
    -
  • If you are using the normal JDK launcher (the default), native dependencies are -built as a shared library named {name}_nativedeps.so, where -{name} is the name attribute of this java_binary rule. -Unused code is not removed by the linker in this configuration.
  • - -
  • If you are using any other launcher, native (C++) dependencies are statically -linked into a binary named {name}_nativedeps, where {name} -is the name attribute of this java_binary rule. In this case, -the linker will remove any code it thinks is unused from the resulting binary, -which means any C++ code accessed only via JNI may not be linked in unless -that cc_library target specifies alwayslink = 1.
  • -
- -

When using any launcher other than the default JDK launcher, the format -of the *_deploy.jar output changes. See the main -java_binary docs for details.

- """, - ), - "bootclasspath": attr.label( - providers = [BootClassPathInfo], - flags = ["SKIP_CONSTRAINTS_OVERRIDE"], - doc = "Restricted API, do not use!", - ), - "neverlink": attr.bool(), - "javacopts": attr.string_list( - doc = """ -Extra compiler options for this binary. -Subject to "Make variable" substitution and -Bourne shell tokenization. -

These compiler options are passed to javac after the global compiler options.

- """, - ), - "add_exports": attr.string_list( - doc = """ -Allow this library to access the given module or package. -

-This corresponds to the javac and JVM --add-exports= flags. - """, - ), - "add_opens": attr.string_list( - doc = """ -Allow this library to reflectively access the given module or -package. -

-This corresponds to the javac and JVM --add-opens= flags. - """, - ), - "main_class": attr.string( - doc = """ -Name of class with main() method to use as entry point. -If a rule uses this option, it does not need a srcs=[...] list. -Thus, with this attribute one can make an executable from a Java library that already -contains one or more main() methods. -

-The value of this attribute is a class name, not a source file. The class must be -available at runtime: it may be compiled by this rule (from srcs) or -provided by direct or transitive dependencies (through runtime_deps or -deps). If the class is unavailable, the binary will fail at runtime; there -is no build-time check. -

- """, - ), - "jvm_flags": attr.string_list( - doc = """ -A list of flags to embed in the wrapper script generated for running this binary. -Subject to $(location) and -"Make variable" substitution, and -Bourne shell tokenization. - -

The wrapper script for a Java binary includes a CLASSPATH definition -(to find all the dependent jars) and invokes the right Java interpreter. -The command line generated by the wrapper script includes the name of -the main class followed by a "$@" so you can pass along other -arguments after the classname. However, arguments intended for parsing -by the JVM must be specified before the classname on the command -line. The contents of jvm_flags are added to the wrapper -script before the classname is listed.

- -

Note that this attribute has no effect on *_deploy.jar -outputs.

- """, - ), - "deploy_manifest_lines": attr.string_list( - doc = """ -A list of lines to add to the META-INF/manifest.mf file generated for the -*_deploy.jar target. The contents of this attribute are not subject -to "Make variable" substitution. - """, - ), - "stamp": attr.int( - default = -1, - values = [-1, 0, 1], - doc = """ -Whether to encode build information into the binary. Possible values: -
    -
  • - stamp = 1: Always stamp the build information into the binary, even in - --nostamp builds. This - setting should be avoided, since it potentially kills remote caching for the - binary and any downstream actions that depend on it. -
  • -
  • - stamp = 0: Always replace build information by constant values. This - gives good build result caching. -
  • -
  • - stamp = -1: Embedding of build information is controlled by the - --[no]stamp flag. -
  • -
-

Stamped binaries are not rebuilt unless their dependencies change.

- """, - ), - "use_testrunner": attr.bool( - default = False, - doc = semantics.DOCS.for_attribute("use_testrunner") + """ -
-You can use this to override the default -behavior, which is to use test runner for -java_test rules, -and not use it for java_binary rules. It is unlikely -you will want to do this. One use is for AllTest -rules that are invoked by another rule (to set up a database -before running the tests, for example). The AllTest -rule must be declared as a java_binary, but should -still use the test runner as its main entry point. - -The name of a test runner class can be overridden with main_class attribute. - """, - ), - "use_launcher": attr.bool( - default = True, - doc = """ -Whether the binary should use a custom launcher. - -

If this attribute is set to false, the -launcher attribute and the related ---java_launcher flag -will be ignored for this target. - """, - ), - "env": attr.string_dict(), - "classpath_resources": attr.label_list( - allow_files = True, - doc = """ -DO NOT USE THIS OPTION UNLESS THERE IS NO OTHER WAY) -

-A list of resources that must be located at the root of the java tree. This attribute's -only purpose is to support third-party libraries that require that their resources be -found on the classpath as exactly "myconfig.xml". It is only allowed on -binaries and not libraries, due to the danger of namespace conflicts. -

- """, - ), - "licenses": attr.license() if hasattr(attr, "license") else attr.string_list(), - "_stub_template": attr.label( - default = semantics.JAVA_STUB_TEMPLATE_LABEL, - allow_single_file = True, - ), - "_java_toolchain_type": attr.label(default = semantics.JAVA_TOOLCHAIN_TYPE), - "_windows_constraints": attr.label_list( - default = ["@" + paths.join(cc_semantics.get_platforms_root(), "os:windows")], - ), - "_build_info_translator": attr.label(default = semantics.BUILD_INFO_TRANSLATOR_LABEL), - } | ({} if _builtins.internal.java_common_internal_do_not_use.incompatible_disable_non_executable_java_binary() else {"create_executable": attr.bool(default = True, doc = "Deprecated, use java_single_jar instead.")}), -) - -BASE_TEST_ATTRIBUTES = { - "test_class": attr.string( - doc = """ -The Java class to be loaded by the test runner.
-

- By default, if this argument is not defined then the legacy mode is used and the - test arguments are used instead. Set the --nolegacy_bazel_java_test flag - to not fallback on the first argument. -

-

- This attribute specifies the name of a Java class to be run by - this test. It is rare to need to set this. If this argument is omitted, - it will be inferred using the target's name and its - source-root-relative path. If the test is located outside a known - source root, Bazel will report an error if test_class - is unset. -

-

- For JUnit3, the test class needs to either be a subclass of - junit.framework.TestCase or it needs to have a public - static suite() method that returns a - junit.framework.Test (or a subclass of Test). - For JUnit4, the class needs to be annotated with - org.junit.runner.RunWith. -

-

- This attribute allows several java_test rules to - share the same Test - (TestCase, TestSuite, ...). Typically - additional information is passed to it - (e.g. via jvm_flags=['-Dkey=value']) so that its - behavior differs in each case, such as running a different - subset of the tests. This attribute also enables the use of - Java tests outside the javatests tree. -

- """, - ), - "env_inherit": attr.string_list(), - "_apple_constraints": attr.label_list( - default = [ - "@" + paths.join(cc_semantics.get_platforms_root(), "os:ios"), - "@" + paths.join(cc_semantics.get_platforms_root(), "os:macos"), - "@" + paths.join(cc_semantics.get_platforms_root(), "os:tvos"), - "@" + paths.join(cc_semantics.get_platforms_root(), "os:visionos"), - "@" + paths.join(cc_semantics.get_platforms_root(), "os:watchos"), - ], - ), - "_legacy_any_type_attrs": attr.string_list(default = ["stamp"]), -} diff --git a/src/main/starlark/builtins_bzl/common/java/java_binary_deploy_jar.bzl b/src/main/starlark/builtins_bzl/common/java/java_binary_deploy_jar.bzl deleted file mode 100644 index 92242a982f3d05..00000000000000 --- a/src/main/starlark/builtins_bzl/common/java/java_binary_deploy_jar.bzl +++ /dev/null @@ -1,254 +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. - -"""Auxiliary rule to create the deploy archives for java_binary""" - -load(":common/java/java_helper.bzl", "helper") -load(":common/java/java_semantics.bzl", "semantics") - -InstrumentedFilesInfo = _builtins.toplevel.InstrumentedFilesInfo - -def _stamping_enabled(ctx, stamp): - if ctx.configuration.is_tool_configuration(): - stamp = 0 - return (stamp == 1) or (stamp == -1 and ctx.configuration.stamp_binaries()) - -def get_build_info(ctx, stamp): - if _stamping_enabled(ctx, stamp): - # Makes the target depend on BUILD_INFO_KEY, which helps to discover stamped targets - # See b/326620485 for more details. - ctx.version_file # buildifier: disable=no-effect - return ctx.attr._build_info_translator[OutputGroupInfo].non_redacted_build_info_files.to_list() - else: - return ctx.attr._build_info_translator[OutputGroupInfo].redacted_build_info_files.to_list() - -def create_deploy_archives( - ctx, - java_attrs, - launcher_info, - main_class, - coverage_main_class, - strip_as_default, - hermetic = False, - add_exports = depset(), - add_opens = depset(), - shared_archive = None, - one_version_level = "OFF", - one_version_allowlist = None, - extra_args = [], - extra_manifest_lines = []): - """ Registers actions for _deploy.jar and _deploy.jar.unstripped - - Args: - ctx: (RuleContext) The rule context - java_attrs: (Struct) Struct of (classpath_resources, runtime_jars, runtime_classpath_for_archive, resources) - launcher_info: (Struct) Struct of (runtime_jars, launcher, unstripped_launcher) - main_class: (String) FQN of the entry point for execution - coverage_main_class: (String) FQN of the entry point for coverage collection - build_target: (String) Name of the build target for stamping - strip_as_default: (bool) Whether to create unstripped deploy jar - hermetic: (bool) - add_exports: (depset) - add_opens: (depset) - shared_archive: (File) Optional .jsa artifact - one_version_level: (String) Optional one version check level, default OFF - one_version_allowlist: (File) Optional allowlist for one version check - extra_args: (list[Args]) Optional arguments for the deploy jar action - extra_manifest_lines: (list[String]) Optional lines added to the jar manifest - """ - classpath_resources = java_attrs.classpath_resources - - runtime_classpath = depset( - direct = launcher_info.runtime_jars, - transitive = [ - java_attrs.runtime_jars, - java_attrs.runtime_classpath_for_archive, - ], - order = "preorder", - ) - multi_release = ctx.fragments.java.multi_release_deploy_jars - build_info_files = get_build_info(ctx, ctx.attr.stamp) - build_target = str(ctx.label) - manifest_lines = ctx.attr.deploy_manifest_lines + extra_manifest_lines - create_deploy_archive( - ctx, - launcher_info.launcher, - main_class, - coverage_main_class, - java_attrs.resources, - classpath_resources, - runtime_classpath, - manifest_lines, - build_info_files, - build_target, - output = ctx.outputs.deployjar, - shared_archive = shared_archive, - one_version_level = one_version_level, - one_version_allowlist = one_version_allowlist, - multi_release = multi_release, - hermetic = hermetic, - add_exports = add_exports, - add_opens = add_opens, - extra_args = extra_args, - ) - - if strip_as_default: - create_deploy_archive( - ctx, - launcher_info.unstripped_launcher, - main_class, - coverage_main_class, - java_attrs.resources, - classpath_resources, - runtime_classpath, - manifest_lines, - build_info_files, - build_target, - output = ctx.outputs.unstrippeddeployjar, - multi_release = multi_release, - hermetic = hermetic, - add_exports = add_exports, - add_opens = add_opens, - extra_args = extra_args, - ) - else: - ctx.actions.write(ctx.outputs.unstrippeddeployjar, "") - -def create_deploy_archive( - ctx, - launcher, - main_class, - coverage_main_class, - resources, - classpath_resources, - runtime_classpath, - manifest_lines, - build_info_files, - build_target, - output, - shared_archive = None, - one_version_level = "OFF", - one_version_allowlist = None, - multi_release = False, - hermetic = False, - add_exports = [], - add_opens = [], - extra_args = []): - """ Creates a deploy jar - - Requires a Java runtime toolchain if and only if hermetic is True. - - Args: - ctx: (RuleContext) The rule context - launcher: (File) the launcher artifact - main_class: (String) FQN of the entry point for execution - coverage_main_class: (String) FQN of the entry point for coverage collection - resources: (Depset) resource inputs - classpath_resources: (Depset) classpath resource inputs - runtime_classpath: (Depset) source files to add to the jar - build_target: (String) Name of the build target for stamping - manifest_lines: (list[String]) Optional lines added to the jar manifest - build_info_files: (list[File]) build info files for stamping - build_target: (String) the owner build target label name string - output: (File) the output jar artifact - shared_archive: (File) Optional .jsa artifact - one_version_level: (String) Optional one version check level, default OFF - one_version_allowlist: (File) Optional allowlist for one version check - multi_release: (bool) - hermetic: (bool) - add_exports: (depset) - add_opens: (depset) - extra_args: (list[Args]) Optional arguments for the deploy jar action - """ - input_files = [] - input_files.extend(build_info_files) - - transitive_input_files = [ - resources, - classpath_resources, - runtime_classpath, - ] - - single_jar = semantics.find_java_toolchain(ctx).single_jar - - manifest_lines = list(manifest_lines) - if ctx.configuration.coverage_enabled: - manifest_lines.append("Coverage-Main-Class: %s" % coverage_main_class) - - args = ctx.actions.args() - args.set_param_file_format("shell").use_param_file("@%s", use_always = True) - - args.add("--output", output) - args.add("--build_target", build_target) - args.add("--normalize") - args.add("--compression") - if main_class: - args.add("--main_class", main_class) - args.add_all("--deploy_manifest_lines", manifest_lines) - args.add_all(build_info_files, before_each = "--build_info_file") - if launcher: - input_files.append(launcher) - args.add("--java_launcher", launcher) - args.add_all("--classpath_resources", classpath_resources) - args.add_all( - "--sources", - runtime_classpath, - map_each = helper.jar_and_target_arg_mapper, - ) - - if one_version_level != "OFF" and one_version_allowlist: - input_files.append(one_version_allowlist) - args.add("--enforce_one_version") - args.add("--one_version_allowlist", one_version_allowlist) - if one_version_level == "WARNING": - args.add("--succeed_on_found_violations") - - if multi_release: - args.add("--multi_release") - - if hermetic: - runtime = ctx.toolchains["@//tools/jdk/hermetic:hermetic_runtime_toolchain_type"].java_runtime - if runtime.lib_modules != None: - java_home = runtime.java_home - lib_modules = runtime.lib_modules - hermetic_files = runtime.hermetic_files - args.add("--hermetic_java_home", java_home) - args.add("--jdk_lib_modules", lib_modules) - args.add_all("--resources", hermetic_files) - input_files.append(lib_modules) - transitive_input_files.append(hermetic_files) - - if shared_archive == None: - shared_archive = runtime.default_cds - - if shared_archive: - input_files.append(shared_archive) - args.add("--cds_archive", shared_archive) - - args.add_all("--add_exports", add_exports) - args.add_all("--add_opens", add_opens) - - inputs = depset(input_files, transitive = transitive_input_files) - - ctx.actions.run( - mnemonic = "JavaDeployJar", - progress_message = "Building deploy jar %s" % output.short_path, - executable = single_jar, - inputs = inputs, - tools = [single_jar], - outputs = [output], - arguments = [args] + extra_args, - use_default_shell_env = True, - toolchain = semantics.JAVA_TOOLCHAIN_TYPE, - ) diff --git a/src/main/starlark/builtins_bzl/common/java/java_binary_wrapper.bzl b/src/main/starlark/builtins_bzl/common/java/java_binary_wrapper.bzl deleted file mode 100644 index d00d962365d2f0..00000000000000 --- a/src/main/starlark/builtins_bzl/common/java/java_binary_wrapper.bzl +++ /dev/null @@ -1,71 +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. - -"""Macro encapsulating the java_binary implementation - -This is needed since the `executable` nature of the target must be computed from -the supplied value of the `create_executable` attribute. -""" - -load(":common/java/java_semantics.bzl", "semantics") - -def register_legacy_java_binary_rules( - rule_exec, - rule_nonexec, - **kwargs): - """Registers the correct java_binary rule and deploy jar rule - - Args: - rule_exec: (Rule) The executable java_binary rule - rule_nonexec: (Rule) The non-executable java_binary rule - **kwargs: Actual args to instantiate the rule - """ - - create_executable = "create_executable" not in kwargs or kwargs["create_executable"] - - # TODO(hvd): migrate depot to integers / maybe use decompose_select_list() - if "stamp" in kwargs and type(kwargs["stamp"]) == type(True): - kwargs["stamp"] = 1 if kwargs["stamp"] else 0 - if not create_executable: - rule_nonexec(**kwargs) - else: - if "use_launcher" in kwargs and not kwargs["use_launcher"]: - kwargs["launcher"] = None - else: - # If launcher is not set or None, set it to config flag - if "launcher" not in kwargs or not kwargs["launcher"]: - kwargs["launcher"] = semantics.LAUNCHER_FLAG_LABEL - rule_exec(**kwargs) - -def register_java_binary_rules( - java_binary, - **kwargs): - """Creates a java_binary rule and a deploy jar rule - - Args: - java_binary: (Rule) The executable java_binary rule - **kwargs: Actual args to instantiate the rule - """ - - # TODO(hvd): migrate depot to integers / maybe use decompose_select_list() - if "stamp" in kwargs and type(kwargs["stamp"]) == type(True): - kwargs["stamp"] = 1 if kwargs["stamp"] else 0 - - if "use_launcher" in kwargs and not kwargs["use_launcher"]: - kwargs["launcher"] = None - else: - # If launcher is not set or None, set it to config flag - if "launcher" not in kwargs or not kwargs["launcher"]: - kwargs["launcher"] = semantics.LAUNCHER_FLAG_LABEL - java_binary(**kwargs) diff --git a/src/main/starlark/builtins_bzl/common/java/java_import.bzl b/src/main/starlark/builtins_bzl/common/java/java_import.bzl deleted file mode 100644 index 925f7682d5b492..00000000000000 --- a/src/main/starlark/builtins_bzl/common/java/java_import.bzl +++ /dev/null @@ -1,354 +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. - -""" -Definition of java_import rule. -""" - -load(":common/cc/cc_info.bzl", "CcInfo") -load(":common/java/basic_java_library.bzl", "construct_defaultinfo") -load(":common/java/import_deps_check.bzl", "import_deps_check") -load(":common/java/java_common.bzl", "java_common") -load(":common/java/java_common_internal_for_builtins.bzl", _run_ijar_private_for_builtins = "run_ijar") -load(":common/java/java_info.bzl", "JavaInfo") -load(":common/java/java_semantics.bzl", "semantics") -load(":common/java/proguard_validation.bzl", "validate_proguard_specs") - -PackageSpecificationInfo = _builtins.toplevel.PackageSpecificationInfo - -def _filter_provider(provider, *attrs): - return [dep[provider] for attr in attrs for dep in attr if provider in dep] - -def _collect_jars(ctx, jars): - jars_dict = {} - for info in jars: - if JavaInfo in info: - fail("'jars' attribute cannot contain labels of Java targets") - for jar in info.files.to_list(): - jar_path = jar.dirname + jar.basename - if jars_dict.get(jar_path) != None: - fail("in jars attribute of java_import rule //" + ctx.label.package + ":" + ctx.attr.name + ": " + jar.basename + " is a duplicate") - jars_dict[jar_path] = jar - return [jar_tuple[1] for jar_tuple in jars_dict.items()] if len(jars_dict.items()) > 0 else [] - -def _process_with_ijars_if_needed(jars, ctx): - file_dict = {} - use_ijars = ctx.fragments.java.use_ijars() - for jar in jars: - interface_jar = jar - if use_ijars: - ijar_basename = jar.short_path.removeprefix("../").removesuffix("." + jar.extension) + "-ijar.jar" - interface_jar_directory = "_ijar/" + ctx.label.name + "/" + ijar_basename - - interface_jar = ctx.actions.declare_file(interface_jar_directory) - _run_ijar_private_for_builtins( - ctx.actions, - target_label = ctx.label, - jar = jar, - output = interface_jar, - java_toolchain = semantics.find_java_toolchain(ctx), - ) - file_dict[jar] = interface_jar - - return file_dict - -def _check_export_error(ctx, exports): - not_in_allowlist = hasattr(ctx.attr, "_allowlist_java_import_exports") and not getattr(ctx.attr, "_allowlist_java_import_exports")[PackageSpecificationInfo].contains(ctx.label) - disallow_java_import_exports = ctx.fragments.java.disallow_java_import_exports() - - if len(exports) != 0 and (disallow_java_import_exports or not_in_allowlist): - fail("java_import.exports is no longer supported; use java_import.deps instead") - -def _check_empty_jars_error(ctx, jars): - # TODO(kotlaja): Remove temporary incompatible flag [disallow_java_import_empty_jars] once migration is done. - not_in_allowlist = hasattr(ctx.attr, "_allowlist_java_import_empty_jars") and not getattr(ctx.attr, "_allowlist_java_import_empty_jars")[PackageSpecificationInfo].contains(ctx.label) - disallow_java_import_empty_jars = ctx.fragments.java.disallow_java_import_empty_jars() - - if len(jars) == 0 and disallow_java_import_empty_jars and not_in_allowlist: - fail("empty java_import.jars is no longer supported " + ctx.label.package) - -def _create_java_info_with_dummy_output_file(ctx, srcjar, all_deps, exports, runtime_deps_list, neverlink, cc_info_list, add_exports, add_opens): - dummy_jar = ctx.actions.declare_file(ctx.label.name + "_dummy.jar") - dummy_src_jar = srcjar - if dummy_src_jar == None: - dummy_src_jar = ctx.actions.declare_file(ctx.label.name + "_src_dummy.java") - ctx.actions.write(dummy_src_jar, "") - return java_common.compile( - ctx, - output = dummy_jar, - java_toolchain = semantics.find_java_toolchain(ctx), - source_files = [dummy_src_jar], - deps = all_deps, - runtime_deps = runtime_deps_list, - neverlink = neverlink, - exports = [export[JavaInfo] for export in exports if JavaInfo in export], # Watchout, maybe you need to add them there manually. - native_libraries = cc_info_list, - add_exports = add_exports, - add_opens = add_opens, - ) - -def bazel_java_import_rule( - ctx, - jars = [], - srcjar = None, - deps = [], - runtime_deps = [], - exports = [], - neverlink = False, - proguard_specs = [], - add_exports = [], - add_opens = []): - """Implements java_import. - - This rule allows the use of precompiled .jar files as libraries in other Java rules. - - Args: - ctx: (RuleContext) Used to register the actions. - jars: (list[Artifact]) List of output jars. - srcjar: (Artifact) The jar containing the sources. - deps: (list[Target]) The list of dependent libraries. - runtime_deps: (list[Target]) Runtime dependencies to attach to the rule. - exports: (list[Target]) The list of exported libraries. - neverlink: (bool) Whether this rule should only be used for compilation and not at runtime. - constraints: (list[String]) Rule constraints. - proguard_specs: (list[File]) Files to be used as Proguard specification. - add_exports: (list[str]) Allow this library to access the given /. - add_opens: (list[str]) Allow this library to reflectively access the given /. - - Returns: - (list[provider]) A list containing DefaultInfo, JavaInfo, - OutputGroupsInfo, ProguardSpecProvider providers. - """ - - _check_empty_jars_error(ctx, jars) - _check_export_error(ctx, exports) - - collected_jars = _collect_jars(ctx, jars) - all_deps = _filter_provider(JavaInfo, deps, exports) - - jdeps_artifact = None - merged_java_info = java_common.merge(all_deps) - not_in_allowlist = hasattr(ctx.attr, "_allowlist_java_import_deps_checking") and not ctx.attr._allowlist_java_import_deps_checking[PackageSpecificationInfo].contains(ctx.label) - if len(collected_jars) > 0 and not_in_allowlist and "incomplete-deps" not in ctx.attr.tags: - jdeps_artifact = import_deps_check( - ctx, - collected_jars, - merged_java_info.compile_jars, - merged_java_info.transitive_compile_time_jars, - "java_import", - ) - - compilation_to_runtime_jar_map = _process_with_ijars_if_needed(collected_jars, ctx) - runtime_deps_list = [runtime_dep[JavaInfo] for runtime_dep in runtime_deps if JavaInfo in runtime_dep] - cc_info_list = [dep[CcInfo] for dep in deps if CcInfo in dep] - java_info = None - if len(collected_jars) > 0: - java_infos = [] - for jar in collected_jars: - java_infos.append(JavaInfo( - output_jar = jar, - compile_jar = compilation_to_runtime_jar_map[jar], - deps = all_deps, - runtime_deps = runtime_deps_list, - neverlink = neverlink, - source_jar = srcjar, - exports = [export[JavaInfo] for export in exports if JavaInfo in export], # Watchout, maybe you need to add them there manually. - native_libraries = cc_info_list, - add_exports = add_exports, - add_opens = add_opens, - )) - java_info = java_common.merge(java_infos) - else: - # TODO(kotlaja): Remove next line once all java_import targets with empty jars attribute are cleaned from depot (b/246559727). - java_info = _create_java_info_with_dummy_output_file(ctx, srcjar, all_deps, exports, runtime_deps_list, neverlink, cc_info_list, add_exports, add_opens) - - target = {"JavaInfo": java_info} - - target["ProguardSpecProvider"] = validate_proguard_specs( - ctx, - proguard_specs, - [deps, runtime_deps, exports], - ) - - # TODO(kotlaja): Revise if collected_runtimes can be added into construct_defaultinfo directly. - collected_runtimes = [] - for runtime_dep in ctx.attr.runtime_deps: - collected_runtimes.extend(runtime_dep.files.to_list()) - - target["DefaultInfo"] = construct_defaultinfo( - ctx, - collected_jars, - collected_jars + collected_runtimes, - neverlink, - exports, - ) - - output_group_src_jars = depset() if srcjar == None else depset([srcjar]) - target["OutputGroupInfo"] = OutputGroupInfo( - **{ - "_source_jars": output_group_src_jars, - "_direct_source_jars": output_group_src_jars, - "_validation": depset() if jdeps_artifact == None else depset([jdeps_artifact]), - "_hidden_top_level_INTERNAL_": target["ProguardSpecProvider"].specs, - } - ) - return target - -def _proxy(ctx): - return bazel_java_import_rule( - ctx, - ctx.attr.jars, - ctx.file.srcjar, - ctx.attr.deps, - ctx.attr.runtime_deps, - ctx.attr.exports, - ctx.attr.neverlink, - ctx.files.proguard_specs, - ctx.attr.add_exports, - ctx.attr.add_opens, - ).values() - -_ALLOWED_RULES_IN_DEPS_FOR_JAVA_IMPORT = [ - "java_library", - "java_import", - "cc_library", - "cc_binary", -] - -JAVA_IMPORT_ATTRS = { - "data": attr.label_list( - allow_files = True, - flags = ["SKIP_CONSTRAINTS_OVERRIDE"], - doc = """ -The list of files needed by this rule at runtime. - """, - ), - "deps": attr.label_list( - providers = [JavaInfo], - allow_rules = _ALLOWED_RULES_IN_DEPS_FOR_JAVA_IMPORT, - doc = """ -The list of other libraries to be linked in to the target. -See java_library.deps. - """, - ), - "exports": attr.label_list( - providers = [JavaInfo], - allow_rules = _ALLOWED_RULES_IN_DEPS_FOR_JAVA_IMPORT, - doc = """ -Targets to make available to users of this rule. -See java_library.exports. - """, - ), - "runtime_deps": attr.label_list( - allow_files = [".jar"], - allow_rules = _ALLOWED_RULES_IN_DEPS_FOR_JAVA_IMPORT, - providers = [[CcInfo], [JavaInfo]], - flags = ["SKIP_ANALYSIS_TIME_FILETYPE_CHECK"], - doc = """ -Libraries to make available to the final binary or test at runtime only. -See java_library.runtime_deps. - """, - ), - # JavaImportBazeRule attr - "jars": attr.label_list( - allow_files = [".jar"], - mandatory = True, - doc = """ -The list of JAR files provided to Java targets that depend on this target. - """, - ), - "srcjar": attr.label( - allow_single_file = [".srcjar", ".jar"], - flags = ["DIRECT_COMPILE_TIME_INPUT"], - doc = """ -A JAR file that contains source code for the compiled JAR files. - """, - ), - "neverlink": attr.bool( - default = False, - doc = """ -Only use this library for compilation and not at runtime. -Useful if the library will be provided by the runtime environment -during execution. Examples of libraries like this are IDE APIs -for IDE plug-ins or tools.jar for anything running on -a standard JDK. - """, - ), - "constraints": attr.string_list( - doc = """ -Extra constraints imposed on this rule as a Java library. - """, - ), - # ProguardLibraryRule attr - "proguard_specs": attr.label_list( - allow_files = True, - doc = """ -Files to be used as Proguard specification. -These will describe the set of specifications to be used by Proguard. If specified, -they will be added to any android_binary target depending on this library. - -The files included here must only have idempotent rules, namely -dontnote, -dontwarn, -assumenosideeffects, and rules that start with -keep. Other options can only appear in -android_binary's proguard_specs, to ensure non-tautological merges. - """, - ), - # Additional attrs - "add_exports": attr.string_list( - doc = """ -Allow this library to access the given module or package. -

-This corresponds to the javac and JVM --add-exports= flags. - """, - ), - "add_opens": attr.string_list( - doc = """ -Allow this library to reflectively access the given module or -package. -

-This corresponds to the javac and JVM --add-opens= flags. - """, - ), - "licenses": attr.license() if hasattr(attr, "license") else attr.string_list(), - "_java_toolchain_type": attr.label(default = semantics.JAVA_TOOLCHAIN_TYPE), -} - -java_import = rule( - _proxy, - doc = """ -

- This rule allows the use of precompiled .jar files as - libraries for java_library and - java_binary rules. -

- -

Examples

- -
-
-    java_import(
-        name = "maven_model",
-        jars = [
-            "maven_model/maven-aether-provider-3.2.3.jar",
-            "maven_model/maven-model-3.2.3.jar",
-            "maven_model/maven-model-builder-3.2.3.jar",
-        ],
-    )
-
-
- """, - attrs = JAVA_IMPORT_ATTRS, - provides = [JavaInfo], - fragments = ["java", "cpp"], - toolchains = [semantics.JAVA_TOOLCHAIN], -) diff --git a/src/main/starlark/builtins_bzl/common/java/java_library.bzl b/src/main/starlark/builtins_bzl/common/java/java_library.bzl deleted file mode 100644 index a93cd2c24105af..00000000000000 --- a/src/main/starlark/builtins_bzl/common/java/java_library.bzl +++ /dev/null @@ -1,387 +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. - -""" -Definition of java_library rule. -""" - -load(":common/cc/cc_info.bzl", "CcInfo") -load(":common/java/android_lint.bzl", "android_lint_subrule") -load(":common/java/basic_java_library.bzl", "BASIC_JAVA_LIBRARY_IMPLICIT_ATTRS", "basic_java_library", "construct_defaultinfo") -load(":common/java/boot_class_path_info.bzl", "BootClassPathInfo") -load(":common/java/java_info.bzl", "JavaInfo", "JavaPluginInfo") -load(":common/java/java_semantics.bzl", "semantics") -load(":common/rule_util.bzl", "merge_attrs") - -def bazel_java_library_rule( - ctx, - srcs = [], - deps = [], - runtime_deps = [], - plugins = [], - exports = [], - exported_plugins = [], - resources = [], - javacopts = [], - neverlink = False, - proguard_specs = [], - add_exports = [], - add_opens = [], - bootclasspath = None, - javabuilder_jvm_flags = None): - """Implements java_library. - - Use this call when you need to produce a fully fledged java_library from - another rule's implementation. - - Args: - ctx: (RuleContext) Used to register the actions. - srcs: (list[File]) The list of source files that are processed to create the target. - deps: (list[Target]) The list of other libraries to be linked in to the target. - runtime_deps: (list[Target]) Libraries to make available to the final binary or test at runtime only. - plugins: (list[Target]) Java compiler plugins to run at compile-time. - exports: (list[Target]) Exported libraries. - exported_plugins: (list[Target]) The list of `java_plugin`s (e.g. annotation - processors) to export to libraries that directly depend on this library. - resources: (list[File]) A list of data files to include in a Java jar. - javacopts: (list[str]) Extra compiler options for this library. - neverlink: (bool) Whether this library should only be used for compilation and not at runtime. - proguard_specs: (list[File]) Files to be used as Proguard specification. - add_exports: (list[str]) Allow this library to access the given /. - add_opens: (list[str]) Allow this library to reflectively access the given /. - bootclasspath: (Target) The JDK APIs to compile this library against. - javabuilder_jvm_flags: (list[str]) Additional JVM flags to pass to JavaBuilder. - Returns: - (dict[str, provider]) A list containing DefaultInfo, JavaInfo, - InstrumentedFilesInfo, OutputGroupsInfo, ProguardSpecProvider providers. - """ - if not srcs and deps: - fail("deps not allowed without srcs; move to runtime_deps?") - - target, base_info = basic_java_library( - ctx, - srcs, - deps, - runtime_deps, - plugins, - exports, - exported_plugins, - resources, - [], # resource_jars - [], # class_pathresources - javacopts, - neverlink, - proguard_specs = proguard_specs, - add_exports = add_exports, - add_opens = add_opens, - bootclasspath = bootclasspath, - javabuilder_jvm_flags = javabuilder_jvm_flags, - ) - - target["DefaultInfo"] = construct_defaultinfo( - ctx, - base_info.files_to_build, - base_info.runfiles, - neverlink, - exports, - runtime_deps, - ) - target["OutputGroupInfo"] = OutputGroupInfo(**base_info.output_groups) - - return target - -def _proxy(ctx): - return bazel_java_library_rule( - ctx, - ctx.files.srcs, - ctx.attr.deps, - ctx.attr.runtime_deps, - ctx.attr.plugins, - ctx.attr.exports, - ctx.attr.exported_plugins, - ctx.files.resources, - ctx.attr.javacopts, - ctx.attr.neverlink, - ctx.files.proguard_specs, - ctx.attr.add_exports, - ctx.attr.add_opens, - ctx.attr.bootclasspath, - ctx.attr.javabuilder_jvm_flags, - ).values() - -JAVA_LIBRARY_IMPLICIT_ATTRS = BASIC_JAVA_LIBRARY_IMPLICIT_ATTRS - -JAVA_LIBRARY_ATTRS = merge_attrs( - JAVA_LIBRARY_IMPLICIT_ATTRS, - { - "srcs": attr.label_list( - allow_files = [".java", ".srcjar", ".properties"] + semantics.EXTRA_SRCS_TYPES, - flags = ["DIRECT_COMPILE_TIME_INPUT", "ORDER_INDEPENDENT"], - doc = """ -The list of source files that are processed to create the target. -This attribute is almost always required; see exceptions below. -

-Source files of type .java are compiled. In case of generated -.java files it is generally advisable to put the generating rule's name -here instead of the name of the file itself. This not only improves readability but -makes the rule more resilient to future changes: if the generating rule generates -different files in the future, you only need to fix one place: the outs of -the generating rule. You should not list the generating rule in deps -because it is a no-op. -

-

-Source files of type .srcjar are unpacked and compiled. (This is useful if -you need to generate a set of .java files with a genrule.) -

-

-Rules: if the rule (typically genrule or filegroup) generates -any of the files listed above, they will be used the same way as described for source -files. -

-

-Source files of type .properties are treated as resources. -

- -

All other files are ignored, as long as there is at least one file of a -file type described above. Otherwise an error is raised.

- -

-This argument is almost always required, except if you specify the runtime_deps argument. -

- """, - ), - "data": attr.label_list( - allow_files = True, - flags = ["SKIP_CONSTRAINTS_OVERRIDE"], - doc = """ -The list of files needed by this library at runtime. -See general comments about data at -Typical attributes defined by -most build rules. -

- When building a java_library, Bazel doesn't put these files anywhere; if the - data files are generated files then Bazel generates them. When building a - test that depends on this java_library Bazel copies or links the - data files into the runfiles area. -

- """ + semantics.DOCS.for_attribute("data"), - ), - "resources": attr.label_list( - allow_files = True, - flags = ["SKIP_CONSTRAINTS_OVERRIDE", "ORDER_INDEPENDENT"], - doc = """ -A list of data files to include in a Java jar. -

-Resources may be source files or generated files. -

- """ + semantics.DOCS.for_attribute("resources"), - ), - "plugins": attr.label_list( - providers = [JavaPluginInfo], - allow_files = True, - cfg = "exec", - doc = """ -Java compiler plugins to run at compile-time. -Every java_plugin specified in this attribute will be run whenever this rule -is built. A library may also inherit plugins from dependencies that use -exported_plugins. Resources -generated by the plugin will be included in the resulting jar of this rule. - """, - ), - "deps": attr.label_list( - allow_files = [".jar"], - allow_rules = semantics.ALLOWED_RULES_IN_DEPS + semantics.ALLOWED_RULES_IN_DEPS_WITH_WARNING, - providers = [ - [CcInfo], - [JavaInfo], - ], - flags = ["SKIP_ANALYSIS_TIME_FILETYPE_CHECK"], - doc = """ -The list of libraries to link into this library. -See general comments about deps at -Typical attributes defined by -most build rules. -

- The jars built by java_library rules listed in deps will be on - the compile-time classpath of this rule. Furthermore the transitive closure of their - deps, runtime_deps and exports will be on the - runtime classpath. -

-

- By contrast, targets in the data attribute are included in the runfiles but - on neither the compile-time nor runtime classpath. -

- """, - ), - "runtime_deps": attr.label_list( - allow_files = [".jar"], - allow_rules = semantics.ALLOWED_RULES_IN_DEPS, - providers = [[CcInfo], [JavaInfo]], - flags = ["SKIP_ANALYSIS_TIME_FILETYPE_CHECK"], - doc = """ -Libraries to make available to the final binary or test at runtime only. -Like ordinary deps, these will appear on the runtime classpath, but unlike -them, not on the compile-time classpath. Dependencies needed only at runtime should be -listed here. Dependency-analysis tools should ignore targets that appear in both -runtime_deps and deps. - """, - ), - "exports": attr.label_list( - allow_rules = semantics.ALLOWED_RULES_IN_DEPS, - providers = [[JavaInfo], [CcInfo]], - doc = """ -Exported libraries. -

- Listing rules here will make them available to parent rules, as if the parents explicitly - depended on these rules. This is not true for regular (non-exported) deps. -

-

- Summary: a rule X can access the code in Y if there exists a dependency - path between them that begins with a deps edge followed by zero or more - exports edges. Let's see some examples to illustrate this. -

-

- Assume A depends on B and B depends on C. In this case - C is a transitive dependency of A, so changing C's sources and rebuilding A will - correctly rebuild everything. However A will not be able to use classes in C. To allow - that, either A has to declare C in its deps, or B can make it easier for A - (and anything that may depend on A) by declaring C in its (B's) exports - attribute. -

-

- The closure of exported libraries is available to all direct parent rules. Take a slightly - different example: A depends on B, B depends on C and D, and also exports C but not D. - Now A has access to C but not to D. Now, if C and D exported some libraries, C' and D' - respectively, A could only access C' but not D'. -

-

- Important: an exported rule is not a regular dependency. Sticking to the previous example, - if B exports C and wants to also use C, it has to also list it in its own - deps. -

- """, - ), - "exported_plugins": attr.label_list( - providers = [JavaPluginInfo], - cfg = "exec", - doc = """ -The list of java_plugins (e.g. annotation -processors) to export to libraries that directly depend on this library. -

- The specified list of java_plugins will be applied to any library which - directly depends on this library, just as if that library had explicitly declared these - labels in plugins. -

- """, - ), - "bootclasspath": attr.label( - providers = [BootClassPathInfo], - flags = ["SKIP_CONSTRAINTS_OVERRIDE"], - doc = """Restricted API, do not use!""", - ), - "javabuilder_jvm_flags": attr.string_list(doc = """Restricted API, do not use!"""), - "javacopts": attr.string_list( - doc = """ -Extra compiler options for this library. -Subject to "Make variable" substitution and -Bourne shell tokenization. -

These compiler options are passed to javac after the global compiler options.

- """, - ), - "neverlink": attr.bool( - doc = """ -Whether this library should only be used for compilation and not at runtime. -Useful if the library will be provided by the runtime environment during execution. Examples -of such libraries are the IDE APIs for IDE plug-ins or tools.jar for anything -running on a standard JDK. -

- Note that neverlink = 1 does not prevent the compiler from inlining material - from this library into compilation targets that depend on it, as permitted by the Java - Language Specification (e.g., static final constants of String - or of primitive types). The preferred use case is therefore when the runtime library is - identical to the compilation library. -

-

- If the runtime library differs from the compilation library then you must ensure that it - differs only in places that the JLS forbids compilers to inline (and that must hold for - all future versions of the JLS). -

- """, - ), - "resource_strip_prefix": attr.string( - doc = """ -The path prefix to strip from Java resources. -

-If specified, this path prefix is stripped from every file in the resources -attribute. It is an error for a resource file not to be under this directory. If not -specified (the default), the path of resource file is determined according to the same -logic as the Java package of source files. For example, a source file at -stuff/java/foo/bar/a.txt will be located at foo/bar/a.txt. -

- """, - ), - "proguard_specs": attr.label_list( - allow_files = True, - doc = """ -Files to be used as Proguard specification. -These will describe the set of specifications to be used by Proguard. If specified, -they will be added to any android_binary target depending on this library. - -The files included here must only have idempotent rules, namely -dontnote, -dontwarn, -assumenosideeffects, and rules that start with -keep. Other options can only appear in -android_binary's proguard_specs, to ensure non-tautological merges. - """, - ), - "add_exports": attr.string_list( - doc = """ -Allow this library to access the given module or package. -

-This corresponds to the javac and JVM --add-exports= flags. - """, - ), - "add_opens": attr.string_list( - doc = """ -Allow this library to reflectively access the given module or -package. -

-This corresponds to the javac and JVM --add-opens= flags. - """, - ), - "licenses": attr.license() if hasattr(attr, "license") else attr.string_list(), - "_java_toolchain_type": attr.label(default = semantics.JAVA_TOOLCHAIN_TYPE), - }, -) - -java_library = rule( - _proxy, - doc = """ -

This rule compiles and links sources into a .jar file.

- -

Implicit outputs

-
    -
  • libname.jar: A Java archive containing the class files.
  • -
  • libname-src.jar: An archive containing the sources ("source - jar").
  • -
- """, - attrs = JAVA_LIBRARY_ATTRS, - provides = [JavaInfo], - outputs = { - "classjar": "lib%{name}.jar", - "sourcejar": "lib%{name}-src.jar", - }, - fragments = ["java", "cpp"], - toolchains = [semantics.JAVA_TOOLCHAIN], - subrules = [android_lint_subrule], -) diff --git a/src/main/starlark/builtins_bzl/common/java/java_plugin.bzl b/src/main/starlark/builtins_bzl/common/java/java_plugin.bzl deleted file mode 100644 index 60d4f26378a279..00000000000000 --- a/src/main/starlark/builtins_bzl/common/java/java_plugin.bzl +++ /dev/null @@ -1,182 +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. - -""" -Definition of java_plugin rule. -""" - -load(":common/java/android_lint.bzl", "android_lint_subrule") -load(":common/java/basic_java_library.bzl", "basic_java_library", "construct_defaultinfo") -load(":common/java/java_info.bzl", "JavaPluginInfo") -load(":common/java/java_library.bzl", "JAVA_LIBRARY_ATTRS", "JAVA_LIBRARY_IMPLICIT_ATTRS") -load(":common/java/java_semantics.bzl", "semantics") -load(":common/rule_util.bzl", "merge_attrs") - -def bazel_java_plugin_rule( - ctx, - srcs = [], - data = [], - generates_api = False, - processor_class = "", - deps = [], - plugins = [], - resources = [], - javacopts = [], - neverlink = False, - proguard_specs = [], - add_exports = [], - add_opens = []): - """Implements java_plugin rule. - - Use this call when you need to produce a fully fledged java_plugin from - another rule's implementation. - - Args: - ctx: (RuleContext) Used to register the actions. - srcs: (list[File]) The list of source files that are processed to create the target. - data: (list[File]) The list of files needed by this plugin at runtime. - generates_api: (bool) This attribute marks annotation processors that generate API code. - processor_class: (str) The processor class is the fully qualified type of - the class that the Java compiler should use as entry point to the annotation processor. - deps: (list[Target]) The list of other libraries to be linked in to the target. - plugins: (list[Target]) Java compiler plugins to run at compile-time. - resources: (list[File]) A list of data files to include in a Java jar. - javacopts: (list[str]) Extra compiler options for this library. - neverlink: (bool) Whether this library should only be used for compilation and not at runtime. - proguard_specs: (list[File]) Files to be used as Proguard specification. - add_exports: (list[str]) Allow this library to access the given /. - add_opens: (list[str]) Allow this library to reflectively access the given /. - Returns: - (list[provider]) A list containing DefaultInfo, JavaInfo, - InstrumentedFilesInfo, OutputGroupsInfo, ProguardSpecProvider providers. - """ - target, base_info = basic_java_library( - ctx, - srcs, - deps, - [], # runtime_deps - plugins, - [], # exports - [], # exported_plugins - resources, - [], # resource_jars - [], # classpath_resources - javacopts, - neverlink, - proguard_specs = proguard_specs, - add_exports = add_exports, - add_opens = add_opens, - ) - java_info = target.pop("JavaInfo") - - # Replace JavaInfo with JavaPluginInfo - target["JavaPluginInfo"] = JavaPluginInfo( - runtime_deps = [java_info], - processor_class = processor_class if processor_class else None, # ignore empty string (default) - data = data, - generates_api = generates_api, - ) - target["DefaultInfo"] = construct_defaultinfo( - ctx, - base_info.files_to_build, - base_info.runfiles, - neverlink, - ) - target["OutputGroupInfo"] = OutputGroupInfo(**base_info.output_groups) - - return target - -def _proxy(ctx): - return bazel_java_plugin_rule( - ctx, - ctx.files.srcs, - ctx.files.data, - ctx.attr.generates_api, - ctx.attr.processor_class, - ctx.attr.deps, - ctx.attr.plugins, - ctx.files.resources, - ctx.attr.javacopts, - ctx.attr.neverlink, - ctx.files.proguard_specs, - ctx.attr.add_exports, - ctx.attr.add_opens, - ).values() - -JAVA_PLUGIN_ATTRS = merge_attrs( - JAVA_LIBRARY_ATTRS, - { - "generates_api": attr.bool(doc = """ -This attribute marks annotation processors that generate API code. -

If a rule uses an API-generating annotation processor, other rules -depending on it can refer to the generated code only if their -compilation actions are scheduled after the generating rule. This -attribute instructs Bazel to introduce scheduling constraints when ---java_header_compilation is enabled. -

WARNING: This attribute affects build -performance, use it only if necessary.

- """), - "processor_class": attr.string(doc = """ -The processor class is the fully qualified type of the class that the Java compiler should -use as entry point to the annotation processor. If not specified, this rule will not -contribute an annotation processor to the Java compiler's annotation processing, but its -runtime classpath will still be included on the compiler's annotation processor path. (This -is primarily intended for use by -Error Prone plugins, which are loaded -from the annotation processor path using - -java.util.ServiceLoader.) - """), - "output_licenses": attr.license() if hasattr(attr, "license") else attr.string_list(), - }, - remove_attrs = ["runtime_deps", "exports", "exported_plugins"], -) - -JAVA_PLUGIN_IMPLICIT_ATTRS = JAVA_LIBRARY_IMPLICIT_ATTRS - -java_plugin = rule( - _proxy, - doc = """ -

- java_plugin defines plugins for the Java compiler run by Bazel. The - only supported kind of plugins are annotation processors. A java_library or - java_binary rule can run plugins by depending on them via the plugins - attribute. A java_library can also automatically export plugins to libraries that - directly depend on it using - exported_plugins. -

- -

Implicit output targets

-
    -
  • libname.jar: A Java archive.
  • -
- -

- Arguments are identical to java_library, except - for the addition of the processor_class argument. -

- """, - attrs = merge_attrs( - JAVA_PLUGIN_ATTRS, - JAVA_PLUGIN_IMPLICIT_ATTRS, - ), - provides = [JavaPluginInfo], - outputs = { - "classjar": "lib%{name}.jar", - "sourcejar": "lib%{name}-src.jar", - }, - fragments = ["java", "cpp"], - toolchains = [semantics.JAVA_TOOLCHAIN], - subrules = [android_lint_subrule], -) diff --git a/src/main/starlark/builtins_bzl/common/java/proguard_validation.bzl b/src/main/starlark/builtins_bzl/common/java/proguard_validation.bzl deleted file mode 100644 index d054990541db63..00000000000000 --- a/src/main/starlark/builtins_bzl/common/java/proguard_validation.bzl +++ /dev/null @@ -1,70 +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. - -""" -Proguard -""" - -load(":common/java/java_semantics.bzl", "semantics") - -ProguardSpecProvider = _builtins.toplevel.ProguardSpecProvider - -def _filter_provider(provider, *attrs): - return [dep[provider] for attr in attrs for dep in attr if provider in dep] - -def _validate_spec(ctx, spec_file): - validated_proguard_spec = ctx.actions.declare_file( - "validated_proguard/%s/%s_valid" % (ctx.label.name, spec_file.path), - ) - - toolchain = semantics.find_java_toolchain(ctx) - - args = ctx.actions.args() - args.add("--path", spec_file) - args.add("--output", validated_proguard_spec) - - ctx.actions.run( - mnemonic = "ValidateProguard", - progress_message = "Validating proguard configuration %{input}", - executable = toolchain.proguard_allowlister, - arguments = [args], - inputs = [spec_file], - outputs = [validated_proguard_spec], - toolchain = Label(semantics.JAVA_TOOLCHAIN_TYPE), - ) - - return validated_proguard_spec - -def validate_proguard_specs(ctx, proguard_specs = [], transitive_attrs = []): - """ - Creates actions that validate Proguard specification and returns ProguardSpecProvider. - - Use transtive_attrs parameter to collect Proguard validations from `deps`, - `runtime_deps`, `exports`, `plugins`, and `exported_plugins` attributes. - - Args: - ctx: (RuleContext) Used to register the actions. - proguard_specs: (list[File]) List of Proguard specs files. - transitive_attrs: (list[list[Target]]) Attributes to collect transitive - proguard validations from. - Returns: - (ProguardSpecProvider) A ProguardSpecProvider. - """ - proguard_validations = _filter_provider(ProguardSpecProvider, *transitive_attrs) - return ProguardSpecProvider( - depset( - [_validate_spec(ctx, spec_file) for spec_file in proguard_specs], - transitive = [validation.specs for validation in proguard_validations], - ), - ) diff --git a/src/main/starlark/builtins_bzl/common/rule_util.bzl b/src/main/starlark/builtins_bzl/common/rule_util.bzl deleted file mode 100644 index 200bf3415c6744..00000000000000 --- a/src/main/starlark/builtins_bzl/common/rule_util.bzl +++ /dev/null @@ -1,49 +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. - -"""Defines rule utilities""" - -def merge_attrs(*attribute_dicts, override_attrs = {}, remove_attrs = []): - """Merges attributes together. - - Attributes are first merged, then overridden and removed. - - If there are duplicate definitions of an attribute, the last one is used. - (Current API doesn't let us compare) - - Overridden and removed attributes need to be present. - - Args: - *attribute_dicts: (*dict[str,Attribute]) A list of attribute dictionaries - to merge together. - override_attrs: (dict[str,Attribute]) A dictionary of attributes to override - remove_attrs: (list[str]) A list of attributes to remove. - Returns: - (dict[str,Attribute]) The merged attributes dictionary. - """ - all_attributes = {} - for attribute_dict in attribute_dicts: - for key, attr in attribute_dict.items(): - all_attributes.setdefault(key, attr) - for key, attr in override_attrs.items(): - if all_attributes.get(key) == None: - fail("Trying to override attribute %s where there is none." % key) - all_attributes[key] = attr - for key in remove_attrs: - if key in override_attrs: - fail("Trying to remove overridden attribute %s." % key) - if key not in all_attributes: - fail("Trying to remove non-existent attribute %s." % key) - all_attributes.pop(key) - return all_attributes diff --git a/src/test/shell/bazel/bazel_rules_java_test.sh b/src/test/shell/bazel/bazel_rules_java_test.sh index 381cfe41900891..54b549c817b708 100755 --- a/src/test/shell/bazel/bazel_rules_java_test.sh +++ b/src/test/shell/bazel/bazel_rules_java_test.sh @@ -93,12 +93,17 @@ function test_rules_java_repository_builds_itself() { || fail "Build failed unexpectedly" } +# Formerly --experimental_java_library_export +function test_java_library_extension_support() { + add_rules_java "MODULE.bazel" + write_default_bazelrc -function test_experimental_java_library_export_do_not_use() { mkdir -p java cat >java/java_library.bzl < $TEST_log && fail "build succeeded" - bazel build --experimental_java_library_export //java:hello_library &> $TEST_log || fail "build failed" + bazel build //java:hello_library &> $TEST_log || fail "build failed" } run_suite "rules_java tests" From a16d6df7187d3d4ea4e1372e8d82b896f52a2671 Mon Sep 17 00:00:00 2001 From: Googler Date: Wed, 20 Nov 2024 09:10:17 -0800 Subject: [PATCH 14/15] Stop exporting java rules / providers from `@_builtins` `java_common` needs to remain (minimally exported) for private APIs PiperOrigin-RevId: 698412708 Change-Id: I58708761e7abbc63013f75276b1cd1f98c11430f (cherry picked from commit ae3262f1450d44fcbb1d8646b2ffac685541a0de) --- .../java/com/google/devtools/build/lib/bazel/rules/BUILD | 5 +++-- .../devtools/build/lib/rules/java/MessageBundleInfo.java | 8 +++++--- src/main/starlark/builtins_bzl/bazel/exports.bzl | 9 +-------- src/main/starlark/builtins_bzl/common/exports.bzl | 5 +---- .../build/lib/rules/java/JavaInfoStarlarkApiTest.java | 2 ++ .../StarlarkRuleImplementationFunctionsTest.java | 1 + src/test/shell/bazel/bazel_rules_java_test.sh | 4 +++- .../integration/incompatible_autoload_externally_test.sh | 4 +++- src/test/shell/testenv.sh | 4 +++- workspace_deps.bzl | 6 +++--- 10 files changed, 25 insertions(+), 23 deletions(-) diff --git a/src/main/java/com/google/devtools/build/lib/bazel/rules/BUILD b/src/main/java/com/google/devtools/build/lib/bazel/rules/BUILD index 2c4ab5e8f0258c..4837d099b8e0e7 100644 --- a/src/main/java/com/google/devtools/build/lib/bazel/rules/BUILD +++ b/src/main/java/com/google/devtools/build/lib/bazel/rules/BUILD @@ -130,13 +130,14 @@ gen_workspace_stanza( name = "rules_suffix", out = "rules_suffix.WORKSPACE", postamble = """ - load("@rules_java//java:repositories.bzl", "rules_java_dependencies", "rules_java_toolchains") + load("@rules_java//java:rules_java_deps.bzl", "rules_java_dependencies") rules_java_dependencies() - rules_java_toolchains() load("@rules_python//python:repositories.bzl", "py_repositories") py_repositories() load("@com_google_protobuf//:protobuf_deps.bzl", "protobuf_deps") protobuf_deps() + load("@rules_java//java:repositories.bzl", "rules_java_toolchains") + rules_java_toolchains() """, preamble = """ load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive") diff --git a/src/main/java/com/google/devtools/build/lib/rules/java/MessageBundleInfo.java b/src/main/java/com/google/devtools/build/lib/rules/java/MessageBundleInfo.java index 2cefa4b1ed9112..c06966475e41aa 100644 --- a/src/main/java/com/google/devtools/build/lib/rules/java/MessageBundleInfo.java +++ b/src/main/java/com/google/devtools/build/lib/rules/java/MessageBundleInfo.java @@ -14,7 +14,7 @@ package com.google.devtools.build.lib.rules.java; -import static com.google.devtools.build.lib.skyframe.BzlLoadValue.keyForBuiltins; +import static com.google.devtools.build.lib.skyframe.BzlLoadValue.keyForBuild; import com.google.common.collect.ImmutableList; import com.google.devtools.build.lib.actions.Artifact; @@ -42,8 +42,10 @@ public final class MessageBundleInfo { private static class Provider extends StarlarkProviderWrapper { private Provider() { super( - keyForBuiltins( - Label.parseCanonicalUnchecked("@_builtins//:common/java/message_bundle_info.bzl")), + keyForBuild( + Label.parseCanonicalUnchecked( + JavaSemantics.RULES_JAVA_PROVIDER_LABELS_PREFIX + + "java/private:message_bundle_info.bzl")), STARLARK_NAME); } diff --git a/src/main/starlark/builtins_bzl/bazel/exports.bzl b/src/main/starlark/builtins_bzl/bazel/exports.bzl index 8c8696c86d60f7..be2ebba962140e 100644 --- a/src/main/starlark/builtins_bzl/bazel/exports.bzl +++ b/src/main/starlark/builtins_bzl/bazel/exports.bzl @@ -15,17 +15,10 @@ """Exported builtins symbols that are specific to OSS Bazel.""" load("@_builtins//:common/python/py_internal.bzl", "py_internal") -load(":common/java/java_package_configuration.bzl", "java_package_configuration") -load(":common/java/java_runtime.bzl", "java_runtime") -load(":common/java/java_toolchain.bzl", "java_toolchain") exported_toplevels = { "py_internal": py_internal, "proto_common_do_not_use": struct(INCOMPATIBLE_ENABLE_PROTO_TOOLCHAIN_RESOLUTION = _builtins.toplevel.proto_common_do_not_use.incompatible_enable_proto_toolchain_resolution()), } -exported_rules = { - "java_package_configuration": java_package_configuration, - "java_runtime": java_runtime, - "java_toolchain": java_toolchain, -} +exported_rules = {} exported_to_java = {} diff --git a/src/main/starlark/builtins_bzl/common/exports.bzl b/src/main/starlark/builtins_bzl/common/exports.bzl index 1e96b1b8b1a29f..e7d0902ba6152e 100755 --- a/src/main/starlark/builtins_bzl/common/exports.bzl +++ b/src/main/starlark/builtins_bzl/common/exports.bzl @@ -37,7 +37,6 @@ load(":common/cc/fdo/fdo_profile.bzl", "fdo_profile") load(":common/cc/fdo/memprof_profile.bzl", "memprof_profile") load(":common/cc/fdo/propeller_optimize.bzl", "propeller_optimize") load(":common/java/java_common.bzl", "java_common") -load(":common/java/java_info.bzl", "JavaInfo", "JavaPluginInfo") load(":common/objc/apple_common.bzl", "apple_common") load(":common/objc/objc_common.bzl", "objc_common") @@ -49,9 +48,7 @@ exported_toplevels = { "CcSharedLibraryInfo": CcSharedLibraryInfo, "CcSharedLibraryHintInfo": CcSharedLibraryHintInfo, "cc_common": cc_common, - "+JavaPluginInfo": JavaPluginInfo, - "+JavaInfo": JavaInfo, - "java_common": java_common, + "java_common": struct(internal_DO_NOT_USE = java_common.internal_DO_NOT_USE), "apple_common": apple_common, } 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 6f3f05d33039e5..8c23af4bcb40bc 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 @@ -1277,6 +1277,7 @@ public void nativeAndStarlarkJavaOutputsCanBeAddedToADepset() throws Exception { scratch.file( "foo/extension.bzl", """ + load("@rules_java//java/common:java_info.bzl", "JavaInfo") def _impl(ctx): f = ctx.actions.declare_file(ctx.label.name + ".jar") ctx.actions.write(f, "") @@ -1313,6 +1314,7 @@ public void testNeverlinkIsStoredAsABoolean() throws Exception { scratch.file( "foo/extension.bzl", """ + load("@rules_java//java/common:java_info.bzl", "JavaInfo") def _impl(ctx): f = ctx.actions.declare_file(ctx.label.name + ".jar") ctx.actions.write(f, "") diff --git a/src/test/java/com/google/devtools/build/lib/starlark/StarlarkRuleImplementationFunctionsTest.java b/src/test/java/com/google/devtools/build/lib/starlark/StarlarkRuleImplementationFunctionsTest.java index 9cef7af493cba4..57f37f0ea20d31 100644 --- a/src/test/java/com/google/devtools/build/lib/starlark/StarlarkRuleImplementationFunctionsTest.java +++ b/src/test/java/com/google/devtools/build/lib/starlark/StarlarkRuleImplementationFunctionsTest.java @@ -1572,6 +1572,7 @@ public void testLacksAdvertisedBuiltinProvider() throws Exception { scratch.file( "test/foo.bzl", """ + load("@rules_java//java/common:java_info.bzl", "JavaInfo") FooInfo = provider() def _impl(ctx): MyFooInfo = FooInfo() diff --git a/src/test/shell/bazel/bazel_rules_java_test.sh b/src/test/shell/bazel/bazel_rules_java_test.sh index 54b549c817b708..eaa871d67f9054 100755 --- a/src/test/shell/bazel/bazel_rules_java_test.sh +++ b/src/test/shell/bazel/bazel_rules_java_test.sh @@ -72,9 +72,11 @@ EOF filegroup(name = 'yolo') EOF touch override/java/BUILD || fail "couldn't touch override/java/BUILD" - cat > override/java/repositories.bzl < override/java/rules_java_deps.bzl < override/java/repositories.bzl < "${rules_java_workspace}/java/repositories.bzl" < "${rules_java_workspace}/java/rules_java_deps.bzl" < "${rules_java_workspace}/java/repositories.bzl" < "${rules_java_workspace}/java/repositories.bzl" < "${rules_java_workspace}/java/rules_java_deps.bzl" < "${rules_java_workspace}/java/repositories.bzl" < Date: Wed, 20 Nov 2024 10:41:58 -0800 Subject: [PATCH 15/15] Use the toolchain rules from `@rules_java` in the Bazel Build Encyclopedia. PiperOrigin-RevId: 698443050 Change-Id: Ibd7baccd8ef8e865d5006ecc8f19cb135a174ad5 (cherry picked from commit 117d71177cd951d0cce85126fe184215f311fe79) --- src/main/starlark/docgen/java.bzl | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/src/main/starlark/docgen/java.bzl b/src/main/starlark/docgen/java.bzl index 9dd0f314ddfba6..2965ccd3b8ae50 100644 --- a/src/main/starlark/docgen/java.bzl +++ b/src/main/starlark/docgen/java.bzl @@ -18,6 +18,9 @@ load("@rules_java//java/bazel/rules:bazel_java_import.bzl", _java_import = "java load("@rules_java//java/bazel/rules:bazel_java_library.bzl", _java_library = "java_library") load("@rules_java//java/bazel/rules:bazel_java_plugin.bzl", _java_plugin = "java_plugin") load("@rules_java//java/bazel/rules:bazel_java_test.bzl", _java_test = "java_test") +load("@rules_java//java/common/rules:java_package_configuration.bzl", _java_package_configuration = "java_package_configuration") +load("@rules_java//java/common/rules:java_runtime.bzl", _java_runtime = "java_runtime") +load("@rules_java//java/common/rules:java_toolchain.bzl", _java_toolchain = "java_toolchain") # Build Encyclopedia entry point for Java rules implemented in Starlark @@ -35,8 +38,8 @@ test_rules = struct( ) other_rules = struct( - java_package_configuration = native.java_package_configuration, + java_package_configuration = _java_package_configuration, java_plugin = _java_plugin, - java_runtime = native.java_runtime, - java_toolchain = native.java_toolchain, + java_runtime = _java_runtime, + java_toolchain = _java_toolchain, )