Validate extra link-time callbacks with Starlark Args (#827)

Validate extra link-time library callbacks with `ctx.actions.args().add_all([], map_each = callback)` immediately before invocation. `Args.add_all` performs the same top-level-function check as `_cc_internal.check_toplevel`, so the C++ Java helper is no longer needed.

Validation: 88 C++ common and binary analysis tests passed, including new tests for top-level and nested callbacks.

Closes #827

COPYBARA_INTEGRATE_REVIEW=https://github.com/bazelbuild/rules_cc/pull/827 from dzbarsky:codex/starlarkify-check-toplevel 73c8487ad9c4432e6558d78e4c97db5ef95140e9
PiperOrigin-RevId: 1011439742
Change-Id: Id543c4e4dd18385b288e1129be95641b70d2560c
diff --git a/cc/private/link/create_extra_link_time_library.bzl b/cc/private/link/create_extra_link_time_library.bzl
index 27a3d05..344a83f 100644
--- a/cc/private/link/create_extra_link_time_library.bzl
+++ b/cc/private/link/create_extra_link_time_library.bzl
@@ -57,16 +57,21 @@
     Any implementations must be immutable (and therefore thread-safe), because this is passed
     between rules and accessed in a multi-threaded context.
 
+    The callback is part of the key used to merge inputs from dependencies. Pass rule-specific
+    values through kwargs so dependencies can reuse the same callback.
+
     Args:
-      build_library_func: A function that takes a rule context, static_mode, for_dynamic_library,
-        and kwargs, and returns a tuple of (linker_input, runtime_library): `tuple[LinkerInputInfo,
-        File]`.
+      build_library_func: A top-level Starlark function that takes a rule context, static_mode,
+        for_dynamic_library, and kwargs. It returns a struct with linker_input (a depset of linker
+        inputs), runtime_library (a depset of files), and optional additional_stamp_info. The
+        top-level requirement is checked when the library is built.
       **kwargs: Additional fields to pass to the build function.
 
     Returns:
       ExtraLinkTimeLibraryInfo.
     """
-    _cc_internal.check_toplevel(build_library_func)
+    if type(build_library_func) != "function":
+        fail("build_library_func must be a Starlark function, got %s" % type(build_library_func))
     return ExtraLinkTimeLibraryInfo(
         build_library_func = build_library_func,
         # Key to identify the "class" of a StarlarkDefinedLinkTimeLibrary. Uses the build function and
@@ -173,6 +178,12 @@
     transitive_runtime_libraries = []
     additional_stamp_infos = []
     for library in extra_libraries:
+        # Merging uses build_library_func as part of the key, so require a
+        # top-level def with the same identity across dependency analysis.
+        # Args.add_all normally uses this check to keep closures out of execution;
+        # here an empty, discarded Args validates the function without invoking it
+        # or registering an action. We call build_library_func below during analysis.
+        ctx.actions.args().add_all([], map_each = library.build_library_func)
         kwargs = {}
         for key in dir(library):
             if key not in ["build_library_func", "_key"]:
diff --git a/tests/cc/common/cc_common_test.bzl b/tests/cc/common/cc_common_test.bzl
index 15af500..39be3c3 100644
--- a/tests/cc/common/cc_common_test.bzl
+++ b/tests/cc/common/cc_common_test.bzl
@@ -7,6 +7,7 @@
 load("//cc:cc_binary.bzl", "cc_binary")
 load("//cc:cc_library.bzl", "cc_library")
 load("//cc/common:cc_info.bzl", "CcInfo")
+load("//cc/private/link:create_extra_link_time_library.bzl", "build_libraries", "create_extra_link_time_libraries", "create_extra_link_time_library", "merge_extra_link_time_libraries")  # buildifier: disable=bzl-visibility
 load("//tests/cc/testutil:cc_analysis_test.bzl", "cc_analysis_test")
 load("//tests/cc/testutil:cc_info_subject.bzl", "cc_info_subject")
 
@@ -707,6 +708,133 @@
     files = [f.basename for f in target[DefaultInfo].files.to_list()]
     env.expect.that_collection(files).contains("libalways_link.lo")
 
+# buildifier: disable=provider-params
+_ExtraLinkTimeLibraryTestInfo = provider(fields = ["stamp_infos"])
+
+def _build_extra_link_time_library(_ctx, _static_mode, _for_dynamic_library, inputs):
+    return struct(
+        linker_input = depset(),
+        runtime_library = depset(),
+        additional_stamp_info = inputs.to_list(),
+    )
+
+def _top_level_extra_link_time_library_impl(ctx):
+    first = create_extra_link_time_library(
+        build_library_func = _build_extra_link_time_library,
+        inputs = depset(["first"]),
+    )
+    second = create_extra_link_time_library(
+        build_library_func = _build_extra_link_time_library,
+        inputs = depset(["second"]),
+    )
+    libraries = merge_extra_link_time_libraries([
+        create_extra_link_time_libraries(first),
+        create_extra_link_time_libraries(second),
+    ])
+    result = build_libraries(libraries.libraries, ctx, False, False)
+    return [_ExtraLinkTimeLibraryTestInfo(stamp_infos = result.additional_stamp_infos)]
+
+_top_level_extra_link_time_library = rule(
+    implementation = _top_level_extra_link_time_library_impl,
+)
+
+def _nested_extra_link_time_library_impl(ctx):
+    def nested_build_library(_ctx, _static_mode, _for_dynamic_library):
+        # buildifier: disable=rule-impl-returns
+        return struct(
+            linker_input = depset(),
+            runtime_library = depset(),
+        )
+
+    library = create_extra_link_time_library(
+        build_library_func = nested_build_library,
+    )
+    build_libraries([library], ctx, False, False)
+    return []
+
+_nested_extra_link_time_library = rule(
+    implementation = _nested_extra_link_time_library_impl,
+)
+
+def _invalid_extra_link_time_library_impl(ctx):
+    create_extra_link_time_library(build_library_func = struct if ctx.attr.builtin else None)
+    return []
+
+_invalid_extra_link_time_library = rule(
+    implementation = _invalid_extra_link_time_library_impl,
+    attrs = {"builtin": attr.bool()},
+)
+
+def _test_top_level_extra_link_time_library(name):
+    util.helper_target(
+        _top_level_extra_link_time_library,
+        name = name + "/library",
+    )
+    cc_analysis_test(
+        name = name,
+        impl = _test_top_level_extra_link_time_library_impl,
+        target = name + "/library",
+    )
+
+def _test_top_level_extra_link_time_library_impl(env, target):
+    env.expect.that_target(target).failures().contains_exactly([])
+    stamp_infos = target[_ExtraLinkTimeLibraryTestInfo].stamp_infos
+    env.expect.that_collection(stamp_infos).has_size(1)
+    env.expect.that_collection(stamp_infos[0]).contains_exactly(["first", "second"])
+
+def _test_nested_extra_link_time_library(name):
+    util.helper_target(
+        _nested_extra_link_time_library,
+        name = name + "/library",
+    )
+    cc_analysis_test(
+        name = name,
+        impl = _test_nested_extra_link_time_library_impl,
+        target = name + "/library",
+        expect_failure = True,
+    )
+
+def _test_nested_extra_link_time_library_impl(env, target):
+    env.expect.that_target(target).failures().contains_predicate(
+        matching.custom(
+            "contains 'must be declared by a top-level def statement'",
+            lambda message: "must be declared by a top-level def statement" in message,
+        ),
+    )
+
+def _test_builtin_extra_link_time_library(name):
+    util.helper_target(
+        _invalid_extra_link_time_library,
+        name = name + "/library",
+        builtin = True,
+    )
+    cc_analysis_test(
+        name = name,
+        impl = _test_invalid_extra_link_time_library_impl,
+        target = name + "/library",
+        expect_failure = True,
+    )
+
+def _test_none_extra_link_time_library(name):
+    util.helper_target(
+        _invalid_extra_link_time_library,
+        name = name + "/library",
+    )
+    cc_analysis_test(
+        name = name,
+        impl = _test_invalid_extra_link_time_library_impl,
+        target = name + "/library",
+        expect_failure = True,
+    )
+
+def _test_invalid_extra_link_time_library_impl(env, target):
+    env.expect.that_target(target).failures().contains_predicate(
+        matching.custom(
+            "contains 'build_library_func must be a Starlark function'",
+            lambda message: "build_library_func must be a Starlark function" in message,
+        ),
+    )
+
 def cc_common_tests(name):
     tests = [
         _test_same_cc_file_twice,
@@ -732,6 +860,10 @@
     ]
     if bazel_features.cc.cc_common_is_in_rules_cc:
         tests.extend([
+            _test_top_level_extra_link_time_library,
+            _test_nested_extra_link_time_library,
+            _test_builtin_extra_link_time_library,
+            _test_none_extra_link_time_library,
             _test_strip_include_prefix_uses_virtual_includes_by_default,
             _test_strip_include_prefix_no_virtual_includes_when_enabled,
             _test_strip_include_prefix_with_include_prefix_uses_virtual_includes,