| # Copyright 2018 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. | |
| """Rules for performing `rustdoc --test` on Bazel built crates""" | |
| load("@rules_cc//cc:find_cc_toolchain.bzl", "use_cc_toolchain") | |
| load("@rules_cc//cc/common:cc_info.bzl", "CcInfo") | |
| load("//rust/private:common.bzl", "rust_common") | |
| load("//rust/private:providers.bzl", "CrateInfo") | |
| load("//rust/private:rustdoc.bzl", "rustdoc_compile_action") | |
| load("//rust/private:rustdoc_toolchain.bzl", "find_rustdoc") | |
| load("//rust/private:utils.bzl", "dedent", "find_toolchain", "transform_deps") | |
| def _construct_writer_arguments(ctx, test_runner, opt_test_params, action): | |
| """Construct arguments and environment variables specific to `rustdoc_test_writer`. | |
| This is largely solving for the fact that tests run from a runfiles directory | |
| where actions run in an execroot. But it also tracks what environment variables | |
| were explicitly added to the action. | |
| Args: | |
| ctx (ctx): The rule's context object. | |
| test_runner (File): The test_runner output file declared by `rustdoc_test`. | |
| opt_test_params (File): An output file we can optionally use to store params for `rustdoc`. | |
| action (struct): Action arguments generated by `rustdoc_compile_action`. | |
| Returns: | |
| tuple: A tuple of `rustdoc_test_writer` specific inputs | |
| - Args: Arguments for the test writer | |
| - dict: Required environment variables | |
| """ | |
| writer_args = ctx.actions.args() | |
| # Track the output path where the test writer should write the test | |
| writer_args.add("--output={}".format(test_runner.path)) | |
| # Track where the test writer should move "spilled" Args to | |
| writer_args.add("--optional_test_params={}".format(opt_test_params.path)) | |
| # Track what environment variables should be written to the test runner | |
| writer_args.add("--action_env=DEVELOPER_DIR") | |
| writer_args.add("--action_env=PATHEXT") | |
| writer_args.add("--action_env=SDKROOT") | |
| writer_args.add("--action_env=SYSROOT") | |
| for var in action.env.keys(): | |
| writer_args.add("--action_env={}".format(var)) | |
| # Every declared input is staged in runfiles. Strip each generated root, | |
| # including compiler tools built in an execution configuration. Empty roots | |
| # are source files: stripping "/" would corrupt every path in the command. | |
| roots = {file.root.path: True for file in action.inputs.to_list() if file.root.path} | |
| writer_args.add_all(roots.keys(), format_each = "--strip_substring=%s/") | |
| # Indicate that the rustdoc_test args are over. | |
| writer_args.add("--") | |
| # Prepare for the process runner to ingest the rest of the arguments | |
| # to match the expectations of `rustc_compile_action`. | |
| writer_args.add(ctx.executable._process_wrapper.short_path) | |
| return (writer_args, action.env) | |
| def _create_crate_info(ctx): | |
| """Create a CrateInfo for doc test compilation. | |
| Args: | |
| ctx (ctx): The rule's context object | |
| Returns: | |
| CrateInfo: A provider configured for doc test compilation | |
| """ | |
| crate = ctx.attr.crate[rust_common.crate_info] | |
| deps = transform_deps(ctx.attr.deps) | |
| proc_macro_deps = transform_deps(ctx.attr.proc_macro_deps) | |
| return rust_common.create_crate_info( | |
| name = crate.name, | |
| type = crate.type, | |
| root = crate.root, | |
| root_path = crate.root_path, | |
| srcs = crate.srcs, | |
| deps = depset(deps, transitive = [crate.deps]), | |
| proc_macro_deps = depset(proc_macro_deps, transitive = [crate.proc_macro_deps]), | |
| aliases = crate.aliases, | |
| output = crate.output, | |
| edition = crate.edition, | |
| rustc_env = crate.rustc_env, | |
| rustc_env_files = crate.rustc_env_files, | |
| is_test = True, | |
| compile_data = crate.compile_data, | |
| compile_data_targets = crate.compile_data_targets, | |
| wrapped_crate_type = crate.type, | |
| owner = ctx.label, | |
| ) | |
| def _rlocationpath(file, workspace_name): | |
| if file.short_path.startswith("../"): | |
| return file.short_path.removeprefix("../") | |
| return "{}/{}".format(workspace_name, file.short_path) | |
| def _compiled_rust_doc_test_impl(ctx, toolchain, rustdoc_toolchain, crate_info): | |
| """Implementation for rust_doc_test using pre-compiled doc test binaries. | |
| Compiles doc tests during the build phase using `rustdoc --test --no-run` | |
| and runs them via `rustdoc_test_runner` at test time. | |
| Args: | |
| ctx (ctx): The rule's context object | |
| toolchain: The rust toolchain | |
| rustdoc_toolchain: The rustdoc toolchain to run, as returned by `find_rustdoc` | |
| crate_info (CrateInfo): The crate info for doc test compilation | |
| Returns: | |
| list: A list of providers | |
| """ | |
| doctest_dir = ctx.actions.declare_directory(ctx.label.name + ".doctests") | |
| test_metadata = ctx.actions.declare_file(ctx.label.name + ".doctest_metadata") | |
| rustdoc_flags = ctx.actions.args() | |
| rustdoc_flags.add_all( | |
| [crate_info.output], | |
| format_each = "--extern={}=%s".format(crate_info.name), | |
| ) | |
| rustdoc_flags.add("--test") | |
| rustdoc_flags.add("--no-run") | |
| rustdoc_flags.add("-Zunstable-options") | |
| rustdoc_flags.add("--persist-doctests") | |
| rustdoc_flags.add_all([doctest_dir], expand_directories = False) | |
| rustdoc_flags.add_all(ctx.attr.rustdoc_flags) | |
| action = rustdoc_compile_action( | |
| ctx = ctx, | |
| rust_toolchain = toolchain, | |
| rustdoc_toolchain = rustdoc_toolchain, | |
| crate_info = crate_info, | |
| rustdoc_flags = rustdoc_flags, | |
| is_test = False, | |
| force_depend_on_objects = True, | |
| ) | |
| wrapper_args = ctx.actions.args() | |
| wrapper_args.add("--test-metadata", test_metadata) | |
| wrapper_args.add("--") | |
| wrapper_args.add(action.executable) | |
| ctx.actions.run( | |
| mnemonic = "RustdocTestCompile", | |
| progress_message = "Compiling Rustdoc tests for %{label} (RustdocTestCompile)", | |
| outputs = [doctest_dir, test_metadata], | |
| executable = ctx.executable._rustdoc_compile_wrapper, | |
| inputs = action.inputs, | |
| env = action.env, | |
| arguments = [wrapper_args] + action.arguments, | |
| tools = action.tools + [action.executable], | |
| toolchain = Label("//rust:toolchain_type"), | |
| execution_requirements = {"supports-path-mapping": ""} if action.supports_path_mapping else None, | |
| ) | |
| test_runner = ctx.actions.declare_file(ctx.label.name + (".exe" if ctx.executable._test_runner_bin.extension == "exe" else "")) | |
| ctx.actions.symlink( | |
| output = test_runner, | |
| target_file = ctx.executable._test_runner_bin, | |
| is_executable = True, | |
| ) | |
| # An rlib's runfiles need not include its native shared libraries. The | |
| # persisted doctest executables still need those libraries at test time. | |
| runtime_libraries = [] | |
| for target in [ctx.attr.crate] + ctx.attr.deps: | |
| if CcInfo not in target: | |
| continue | |
| for linker_input in target[CcInfo].linking_context.linker_inputs.to_list(): | |
| for lib in linker_input.libraries: | |
| if lib.static_library or lib.pic_static_library: | |
| continue | |
| if lib.dynamic_library: | |
| runtime_libraries.append(lib.dynamic_library) | |
| if lib.resolved_symlink_dynamic_library: | |
| runtime_libraries.append(lib.resolved_symlink_dynamic_library) | |
| return [ | |
| DefaultInfo( | |
| files = depset([test_runner]), | |
| runfiles = ctx.runfiles( | |
| files = [doctest_dir, test_metadata, ctx.executable._test_runner_bin] + runtime_libraries, | |
| transitive_files = crate_info.compile_data, | |
| ).merge_all([ | |
| target[DefaultInfo].default_runfiles | |
| for target in [ctx.attr.crate] + ctx.attr.deps + [ctx.attr._test_runner_bin] | |
| if target[DefaultInfo].default_runfiles != None | |
| ]), | |
| executable = test_runner, | |
| ), | |
| RunEnvironmentInfo( | |
| environment = { | |
| "RUSTDOC_TEST_METADATA": _rlocationpath(test_metadata, ctx.workspace_name), | |
| "RUSTDOC_TEST_RUNNER_ARGS": _rlocationpath(doctest_dir, ctx.workspace_name), | |
| }, | |
| ), | |
| ] | |
| def _legacy_rust_doc_test_impl(ctx, toolchain, rustdoc_toolchain, crate_info): | |
| """Existing implementation for rust_doc_test using a generated test runner script. | |
| Args: | |
| ctx (ctx): The rule's context object | |
| toolchain: The rust toolchain | |
| rustdoc_toolchain: The rustdoc toolchain to run, as returned by `find_rustdoc` | |
| crate_info (CrateInfo): The crate info for doc test compilation | |
| Returns: | |
| list: A list containing a DefaultInfo provider | |
| """ | |
| if toolchain.target_os == "windows": | |
| test_runner = ctx.actions.declare_file(ctx.label.name + ".rustdoc_test.bat") | |
| else: | |
| test_runner = ctx.actions.declare_file(ctx.label.name + ".rustdoc_test.sh") | |
| # Bazel will auto-magically spill params to a file, if they are too many for a given OSes shell | |
| # (e.g. Windows ~32k, Linux ~2M). The executable script (aka test_runner) that gets generated, | |
| # is run from the runfiles, which is separate from the params_file Bazel generates. To handle | |
| # this case, we declare our own params file, that the test_writer will populate, if necessary | |
| opt_test_params = ctx.actions.declare_file(ctx.label.name + ".rustdoc_opt_params", sibling = test_runner) | |
| # Add the current crate as an extern for the compile action. | |
| # | |
| # NOTE: This legacy impl deliberately passes a plain list rather than an | |
| # `Args` object. Args would trigger Bazel's auto-spill into a | |
| # `*-0.params` file at relatively small sizes, but that spilled file is | |
| # not present in the test runfiles. The `rustdoc_test_writer` step below | |
| # has its own `opt_test_params` handoff for relocating params to a | |
| # runfiles-visible location, so we keep the list form here to avoid | |
| # stepping on that mechanism. | |
| rustdoc_flags = [ | |
| "--extern", | |
| "{}={}".format(crate_info.name, crate_info.output.short_path), | |
| "--test", | |
| ] | |
| rustdoc_flags.extend(ctx.attr.rustdoc_flags) | |
| action = rustdoc_compile_action( | |
| ctx = ctx, | |
| rust_toolchain = toolchain, | |
| rustdoc_toolchain = rustdoc_toolchain, | |
| crate_info = crate_info, | |
| rustdoc_flags = rustdoc_flags, | |
| is_test = True, | |
| ) | |
| tools = action.tools + [ctx.executable._process_wrapper] | |
| writer_args, env = _construct_writer_arguments( | |
| ctx = ctx, | |
| test_runner = test_runner, | |
| opt_test_params = opt_test_params, | |
| action = action, | |
| ) | |
| # Allow writer environment variables to override those from the action. | |
| action.env.update(env) | |
| ctx.actions.run( | |
| mnemonic = "RustdocTestWriter", | |
| progress_message = "Generating Rustdoc test runner for %{label} (RustdocTestWriter)", | |
| executable = ctx.executable._test_writer, | |
| inputs = action.inputs, | |
| tools = tools, | |
| arguments = [writer_args] + action.arguments, | |
| env = action.env, | |
| outputs = [test_runner, opt_test_params], | |
| ) | |
| return [DefaultInfo( | |
| files = depset([test_runner]), | |
| runfiles = ctx.runfiles(files = tools + [opt_test_params], transitive_files = action.inputs), | |
| executable = test_runner, | |
| )] | |
| def _rust_doc_test_impl(ctx): | |
| """The implementation for the `rust_doc_test` rule | |
| Args: | |
| ctx (ctx): The rule's context object | |
| Returns: | |
| list: A list containing a DefaultInfo provider | |
| """ | |
| toolchain = find_toolchain(ctx) | |
| rustdoc_toolchain = find_rustdoc(ctx, toolchain) | |
| if not rustdoc_toolchain: | |
| fail("{}: no `rustdoc_toolchain` is registered for the current platform and the `rust_toolchain` has no `rust_doc`".format(ctx.label)) | |
| crate_info = _create_crate_info(ctx) | |
| use_compiled_doctest = ( | |
| toolchain._experimental_compile_rustdoc_tests and | |
| toolchain.channel == "nightly" | |
| ) | |
| if use_compiled_doctest: | |
| return _compiled_rust_doc_test_impl(ctx, toolchain, rustdoc_toolchain, crate_info) | |
| else: | |
| if toolchain.exec_triple.str != toolchain.target_triple.str: | |
| fail("Cross-built doctests require experimental_compile_rustdoc_tests and a nightly compiler; legacy doctests execute their compiler during the test.") | |
| return _legacy_rust_doc_test_impl(ctx, toolchain, rustdoc_toolchain, crate_info) | |
| rust_doc_test = rule( | |
| implementation = _rust_doc_test_impl, | |
| attrs = { | |
| "crate": attr.label( | |
| doc = ( | |
| "The label of the target to generate code documentation for. " + | |
| "`rust_doc_test` can generate HTML code documentation for the " + | |
| "source files of `rust_library` or `rust_binary` targets." | |
| ), | |
| providers = [rust_common.crate_info], | |
| mandatory = True, | |
| ), | |
| "crate_features": attr.string_list( | |
| doc = dedent("""\ | |
| List of features to enable for the crate being documented. | |
| """), | |
| ), | |
| "deps": attr.label_list( | |
| doc = dedent("""\ | |
| List of other libraries to be linked to this library target. | |
| These can be either other `rust_library` targets or `cc_library` targets if | |
| linking a native library. | |
| """), | |
| providers = [[CrateInfo], [CcInfo]], | |
| ), | |
| "proc_macro_deps": attr.label_list( | |
| doc = dedent("""\ | |
| List of `rust_proc_macro` targets used to help build this library target. | |
| """), | |
| cfg = "exec", | |
| providers = [rust_common.crate_info], | |
| ), | |
| "rustdoc_flags": attr.string_list( | |
| doc = dedent("""\ | |
| List of flags passed to `rustdoc`. | |
| These strings are subject to Make variable expansion for predefined | |
| source/output path variables like `$location`, `$execpath`, and | |
| `$rootpath`. This expansion is useful if you wish to pass a generated | |
| file of arguments to rustc: `@$(location //package:target)`. | |
| """), | |
| ), | |
| "_process_wrapper": attr.label( | |
| doc = "A process wrapper for running rustdoc on all platforms", | |
| cfg = "exec", | |
| default = Label("//util/process_wrapper"), | |
| executable = True, | |
| ), | |
| "_rustdoc_compile_wrapper": attr.label( | |
| doc = "A wrapper that suppresses stdout on success for compiled doc test actions.", | |
| cfg = "exec", | |
| default = Label("//rust/private/rustdoc:rustdoc_compile_wrapper"), | |
| executable = True, | |
| ), | |
| "_test_runner_bin": attr.label( | |
| doc = "A binary used for running compiled doc test binaries.", | |
| cfg = config.exec("test"), | |
| default = Label("//rust/private/rustdoc:rustdoc_test_runner"), | |
| executable = True, | |
| ), | |
| "_test_writer": attr.label( | |
| doc = "A binary used for writing script for use as the test executable.", | |
| cfg = "exec", | |
| default = Label("//rust/private/rustdoc:rustdoc_test_writer"), | |
| executable = True, | |
| ), | |
| }, | |
| test = True, | |
| fragments = ["cpp"], | |
| toolchains = [ | |
| str(Label("//rust:toolchain_type")), | |
| config_common.toolchain_type(rust_common.rustdoc_toolchain_type, mandatory = False), | |
| ] + use_cc_toolchain(mandatory = False), | |
| doc = dedent("""\ | |
| Runs Rust documentation tests. | |
| Example: | |
| Suppose you have the following directory structure for a Rust library crate: | |
| ```output | |
| [workspace]/ | |
| WORKSPACE | |
| hello_lib/ | |
| BUILD | |
| src/ | |
| lib.rs | |
| ``` | |
| To run [documentation tests][doc-test] for the `hello_lib` crate, define a `rust_doc_test` \ | |
| target that depends on the `hello_lib` `rust_library` target: | |
| [doc-test]: https://doc.rust-lang.org/book/documentation.html#documentation-as-tests | |
| ```python | |
| package(default_visibility = ["//visibility:public"]) | |
| load("@rules_rust//rust:defs.bzl", "rust_library", "rust_doc_test") | |
| rust_library( | |
| name = "hello_lib", | |
| srcs = ["src/lib.rs"], | |
| ) | |
| rust_doc_test( | |
| name = "hello_lib_doc_test", | |
| crate = ":hello_lib", | |
| ) | |
| ``` | |
| Running `bazel test //hello_lib:hello_lib_doc_test` will run all documentation tests for the `hello_lib` library crate. | |
| """), | |
| ) |