diff --git a/.bazelrc b/.bazelrc index 760a273d..d244032c 100644 --- a/.bazelrc +++ b/.bazelrc @@ -18,8 +18,8 @@ build --workspace_status_command=$(pwd)/workspace_status.sh # To update these lines, execute # `bazel run @rules_bazel_integration_test//tools:update_deleted_packages` # docs: https://bazel.build/reference/command-line-reference#flag--deleted_packages -build --deleted_packages=e2e/workspace,e2e/workspace/bazel_builtin,e2e/workspace/c-sources,e2e/workspace/canonical-name-module,e2e/workspace/canonical-name-module/other,e2e/workspace/cc-dependencies,e2e/workspace/cc-dependencies/shared-library,e2e/workspace/cc-dependencies/static-library,e2e/workspace/cc-dependencies/static-library-cdeps,e2e/workspace/configure-mode,e2e/workspace/configure-target,e2e/workspace/configure-threaded,e2e/workspace/configure-use_cc_common_link,e2e/workspace/configure-use_cc_common_link/shared-library,e2e/workspace/configure-use_cc_common_link/static-library,e2e/workspace/configure-version,e2e/workspace/data-dependencies,e2e/workspace/embed-file,e2e/workspace/env-attr,e2e/workspace/import-name-attr,e2e/workspace/include-dependencies,e2e/workspace/include-dependencies/zig-include,e2e/workspace/include-dependencies/zig-include-define,e2e/workspace/include-dependencies/zig-include-isystem,e2e/workspace/include-dependencies/zig-std-include,e2e/workspace/link-dependencies,e2e/workspace/link-dependencies/shared-library,e2e/workspace/link-dependencies/static-library,e2e/workspace/linker-script,e2e/workspace/linkopts-attr,e2e/workspace/location-expansion,e2e/workspace/multiple-sources-and-packages-test,e2e/workspace/multiple-sources-binary,e2e/workspace/root-module-from-single-dependency,e2e/workspace/runfiles-library,e2e/workspace/runfiles-library/dependency,e2e/workspace/runfiles-library/dependency/transitive-dependency,e2e/workspace/simple-binary,e2e/workspace/simple-cmake-library,e2e/workspace/simple-library,e2e/workspace/simple-shared-library,e2e/workspace/simple-test,e2e/workspace/test-runner-attr,e2e/workspace/toolchain-glibc-version,e2e/workspace/transitive-zig-modules-binary,e2e/workspace/transitive-zig-modules-binary/hello-world,e2e/workspace/transitive-zig-modules-binary/hello-world/data,e2e/workspace/transitive-zig-modules-binary/hello-world/data/hello,e2e/workspace/transitive-zig-modules-binary/hello-world/data/world,e2e/workspace/transitive-zig-modules-binary/hello-world/io,e2e/workspace/translate-c/transitive-cc-library-zig-binary,e2e/workspace/zig-docs,e2e/workspace/zig-header,e2e/workspace/zig-module-binary,e2e/workspace/zig-module-binary/data,e2e/workspace/zig-module-binary/io,zig/tests/integration_tests/minimal,zig/tests/integration_tests/mirrors,zig/tests/integration_tests/workspace,zig/tests/integration_tests/workspace/custom_interpreter,zig/tests/integration_tests/workspace/env-attr,zig/tests/integration_tests/workspace/runfiles -query --deleted_packages=e2e/workspace,e2e/workspace/bazel_builtin,e2e/workspace/c-sources,e2e/workspace/canonical-name-module,e2e/workspace/canonical-name-module/other,e2e/workspace/cc-dependencies,e2e/workspace/cc-dependencies/shared-library,e2e/workspace/cc-dependencies/static-library,e2e/workspace/cc-dependencies/static-library-cdeps,e2e/workspace/configure-mode,e2e/workspace/configure-target,e2e/workspace/configure-threaded,e2e/workspace/configure-use_cc_common_link,e2e/workspace/configure-use_cc_common_link/shared-library,e2e/workspace/configure-use_cc_common_link/static-library,e2e/workspace/configure-version,e2e/workspace/data-dependencies,e2e/workspace/embed-file,e2e/workspace/env-attr,e2e/workspace/import-name-attr,e2e/workspace/include-dependencies,e2e/workspace/include-dependencies/zig-include,e2e/workspace/include-dependencies/zig-include-define,e2e/workspace/include-dependencies/zig-include-isystem,e2e/workspace/include-dependencies/zig-std-include,e2e/workspace/link-dependencies,e2e/workspace/link-dependencies/shared-library,e2e/workspace/link-dependencies/static-library,e2e/workspace/linker-script,e2e/workspace/linkopts-attr,e2e/workspace/location-expansion,e2e/workspace/multiple-sources-and-packages-test,e2e/workspace/multiple-sources-binary,e2e/workspace/root-module-from-single-dependency,e2e/workspace/runfiles-library,e2e/workspace/runfiles-library/dependency,e2e/workspace/runfiles-library/dependency/transitive-dependency,e2e/workspace/simple-binary,e2e/workspace/simple-cmake-library,e2e/workspace/simple-library,e2e/workspace/simple-shared-library,e2e/workspace/simple-test,e2e/workspace/test-runner-attr,e2e/workspace/toolchain-glibc-version,e2e/workspace/transitive-zig-modules-binary,e2e/workspace/transitive-zig-modules-binary/hello-world,e2e/workspace/transitive-zig-modules-binary/hello-world/data,e2e/workspace/transitive-zig-modules-binary/hello-world/data/hello,e2e/workspace/transitive-zig-modules-binary/hello-world/data/world,e2e/workspace/transitive-zig-modules-binary/hello-world/io,e2e/workspace/translate-c/transitive-cc-library-zig-binary,e2e/workspace/zig-docs,e2e/workspace/zig-header,e2e/workspace/zig-module-binary,e2e/workspace/zig-module-binary/data,e2e/workspace/zig-module-binary/io,zig/tests/integration_tests/minimal,zig/tests/integration_tests/mirrors,zig/tests/integration_tests/workspace,zig/tests/integration_tests/workspace/custom_interpreter,zig/tests/integration_tests/workspace/env-attr,zig/tests/integration_tests/workspace/runfiles +build --deleted_packages=e2e/workspace,e2e/workspace/bazel_builtin,e2e/workspace/c-sources,e2e/workspace/canonical-name-module,e2e/workspace/canonical-name-module/other,e2e/workspace/cc-dependencies,e2e/workspace/cc-dependencies/shared-library,e2e/workspace/cc-dependencies/static-library,e2e/workspace/cc-dependencies/static-library-cdeps,e2e/workspace/configure-mode,e2e/workspace/configure-target,e2e/workspace/configure-threaded,e2e/workspace/configure-use_cc_common_link,e2e/workspace/configure-use_cc_common_link/shared-library,e2e/workspace/configure-use_cc_common_link/static-library,e2e/workspace/configure-version,e2e/workspace/data-dependencies,e2e/workspace/embed-file,e2e/workspace/env-attr,e2e/workspace/import-name-attr,e2e/workspace/include-dependencies,e2e/workspace/include-dependencies/zig-include,e2e/workspace/include-dependencies/zig-include-define,e2e/workspace/include-dependencies/zig-include-isystem,e2e/workspace/include-dependencies/zig-std-include,e2e/workspace/link-dependencies,e2e/workspace/link-dependencies/shared-library,e2e/workspace/link-dependencies/static-library,e2e/workspace/linker-script,e2e/workspace/linkopts-attr,e2e/workspace/location-expansion,e2e/workspace/multiple-sources-and-packages-test,e2e/workspace/multiple-sources-binary,e2e/workspace/root-module-from-single-dependency,e2e/workspace/runfiles-library,e2e/workspace/runfiles-library/dependency,e2e/workspace/runfiles-library/dependency/transitive-dependency,e2e/workspace/simple-binary,e2e/workspace/simple-cmake-library,e2e/workspace/simple-library,e2e/workspace/simple-shared-library,e2e/workspace/simple-test,e2e/workspace/test-runner-attr,e2e/workspace/third_party/arocc,e2e/workspace/third_party/translate-c,e2e/workspace/toolchain-glibc-version,e2e/workspace/transitive-zig-modules-binary,e2e/workspace/transitive-zig-modules-binary/hello-world,e2e/workspace/transitive-zig-modules-binary/hello-world/data,e2e/workspace/transitive-zig-modules-binary/hello-world/data/hello,e2e/workspace/transitive-zig-modules-binary/hello-world/data/world,e2e/workspace/transitive-zig-modules-binary/hello-world/io,e2e/workspace/translate-c/transitive-cc-library-zig-binary,e2e/workspace/zig-docs,e2e/workspace/zig-header,e2e/workspace/zig-module-binary,e2e/workspace/zig-module-binary/data,e2e/workspace/zig-module-binary/io,zig/tests/integration_tests/minimal,zig/tests/integration_tests/mirrors,zig/tests/integration_tests/workspace,zig/tests/integration_tests/workspace/custom_interpreter,zig/tests/integration_tests/workspace/env-attr,zig/tests/integration_tests/workspace/runfiles +query --deleted_packages=e2e/workspace,e2e/workspace/bazel_builtin,e2e/workspace/c-sources,e2e/workspace/canonical-name-module,e2e/workspace/canonical-name-module/other,e2e/workspace/cc-dependencies,e2e/workspace/cc-dependencies/shared-library,e2e/workspace/cc-dependencies/static-library,e2e/workspace/cc-dependencies/static-library-cdeps,e2e/workspace/configure-mode,e2e/workspace/configure-target,e2e/workspace/configure-threaded,e2e/workspace/configure-use_cc_common_link,e2e/workspace/configure-use_cc_common_link/shared-library,e2e/workspace/configure-use_cc_common_link/static-library,e2e/workspace/configure-version,e2e/workspace/data-dependencies,e2e/workspace/embed-file,e2e/workspace/env-attr,e2e/workspace/import-name-attr,e2e/workspace/include-dependencies,e2e/workspace/include-dependencies/zig-include,e2e/workspace/include-dependencies/zig-include-define,e2e/workspace/include-dependencies/zig-include-isystem,e2e/workspace/include-dependencies/zig-std-include,e2e/workspace/link-dependencies,e2e/workspace/link-dependencies/shared-library,e2e/workspace/link-dependencies/static-library,e2e/workspace/linker-script,e2e/workspace/linkopts-attr,e2e/workspace/location-expansion,e2e/workspace/multiple-sources-and-packages-test,e2e/workspace/multiple-sources-binary,e2e/workspace/root-module-from-single-dependency,e2e/workspace/runfiles-library,e2e/workspace/runfiles-library/dependency,e2e/workspace/runfiles-library/dependency/transitive-dependency,e2e/workspace/simple-binary,e2e/workspace/simple-cmake-library,e2e/workspace/simple-library,e2e/workspace/simple-shared-library,e2e/workspace/simple-test,e2e/workspace/test-runner-attr,e2e/workspace/third_party/arocc,e2e/workspace/third_party/translate-c,e2e/workspace/toolchain-glibc-version,e2e/workspace/transitive-zig-modules-binary,e2e/workspace/transitive-zig-modules-binary/hello-world,e2e/workspace/transitive-zig-modules-binary/hello-world/data,e2e/workspace/transitive-zig-modules-binary/hello-world/data/hello,e2e/workspace/transitive-zig-modules-binary/hello-world/data/world,e2e/workspace/transitive-zig-modules-binary/hello-world/io,e2e/workspace/translate-c/transitive-cc-library-zig-binary,e2e/workspace/zig-docs,e2e/workspace/zig-header,e2e/workspace/zig-module-binary,e2e/workspace/zig-module-binary/data,e2e/workspace/zig-module-binary/io,zig/tests/integration_tests/minimal,zig/tests/integration_tests/mirrors,zig/tests/integration_tests/workspace,zig/tests/integration_tests/workspace/custom_interpreter,zig/tests/integration_tests/workspace/env-attr,zig/tests/integration_tests/workspace/runfiles # Load any settings specific to the current user. # Place settings that should affect the integration tests into `.bazelrc.ic.user`. diff --git a/MODULE.bazel b/MODULE.bazel index 84fafb87..4e9eb9f3 100644 --- a/MODULE.bazel +++ b/MODULE.bazel @@ -4,6 +4,7 @@ module( compatibility_level = 1, ) +bazel_dep(name = "apple_support", version = "2.2.0") bazel_dep(name = "aspect_bazel_lib", version = "2.22.5") bazel_dep(name = "bazel_skylib", version = "1.9.0") bazel_dep(name = "rules_cc", version = "0.2.18") diff --git a/docs/rules.md b/docs/rules.md index 6fda82a6..2137a651 100644 --- a/docs/rules.md +++ b/docs/rules.md @@ -121,7 +121,8 @@ zig_c_library( load("@rules_zig//zig:defs.bzl", "zig_configure") zig_configure(name, actual, extra_toolchains, host_mode, host_threaded, host_use_cc_common_link, - host_zigopt, mode, target, threaded, use_cc_common_link, zig_version, zigopt) + host_zigopt, mode, target, threaded, use_cc_common_link, use_standalone_translate_c, + zig_version, zigopt) Transitions a target and its dependencies to a different configuration. @@ -180,6 +181,7 @@ zig_configure( | target | The target platform, expects a label to a Bazel target platform used to select a `zig_target_toolchain` instance. | Label | optional | `None` | | threaded | The threaded setting, corresponds to the `-fsingle-threaded` Zig compiler flag. | String | optional | `""` | | use_cc_common_link | Whether to use cc_common.link to link zig binaries, tests and shared libraries. Possible values: [-1, 0, 1]. -1 means use current configuration value for //zig/settings:experimental_use_cc_common_link. 0 means do not use cc_common.link (use zig build-exe instead). 1 means use cc_common.link. | Integer | optional | `-1` | +| use_standalone_translate_c | Whether to use a registered standalone translate-c toolchain for C translation instead of the built-in zig translate-c tool. Possible values: [-1, 0, 1]. -1 means use current configuration value for //zig/settings:use_standalone_translate_c. 0 means do not use the standalone translate-c toolchain. 1 means use the standalone translate-c toolchain. | Integer | optional | `-1` | | zig_version | The Zig SDK version, must be registered using the `zig` module extension. | String | optional | `""` | | zigopt | Additional list of flags passed to the zig compiler for all Zig compile actions.

The flags specified by this setting do not override those specified via the `zigopts` attribute of `zig_*` rules. Instead, they are prepended to the command line before module specific flags.

This is an advanced feature that can conflict with attributes, build settings, and other flags defined by the toolchain itself. Use this at your own risk of hitting undefined behaviors. | List of strings | optional | `[]` | @@ -193,7 +195,7 @@ load("@rules_zig//zig:defs.bzl", "zig_configure_binary") zig_configure_binary(name, actual, extra_toolchains, host_mode, host_threaded, host_use_cc_common_link, host_zigopt, mode, target, threaded, use_cc_common_link, - zig_version, zigopt) + use_standalone_translate_c, zig_version, zigopt) Transitions a target and its dependencies to a different configuration. @@ -252,6 +254,7 @@ zig_configure_binary( | target | The target platform, expects a label to a Bazel target platform used to select a `zig_target_toolchain` instance. | Label | optional | `None` | | threaded | The threaded setting, corresponds to the `-fsingle-threaded` Zig compiler flag. | String | optional | `""` | | use_cc_common_link | Whether to use cc_common.link to link zig binaries, tests and shared libraries. Possible values: [-1, 0, 1]. -1 means use current configuration value for //zig/settings:experimental_use_cc_common_link. 0 means do not use cc_common.link (use zig build-exe instead). 1 means use cc_common.link. | Integer | optional | `-1` | +| use_standalone_translate_c | Whether to use a registered standalone translate-c toolchain for C translation instead of the built-in zig translate-c tool. Possible values: [-1, 0, 1]. -1 means use current configuration value for //zig/settings:use_standalone_translate_c. 0 means do not use the standalone translate-c toolchain. 1 means use the standalone translate-c toolchain. | Integer | optional | `-1` | | zig_version | The Zig SDK version, must be registered using the `zig` module extension. | String | optional | `""` | | zigopt | Additional list of flags passed to the zig compiler for all Zig compile actions.

The flags specified by this setting do not override those specified via the `zigopts` attribute of `zig_*` rules. Instead, they are prepended to the command line before module specific flags.

This is an advanced feature that can conflict with attributes, build settings, and other flags defined by the toolchain itself. Use this at your own risk of hitting undefined behaviors. | List of strings | optional | `[]` | @@ -265,7 +268,7 @@ load("@rules_zig//zig:defs.bzl", "zig_configure_test") zig_configure_test(name, actual, extra_toolchains, host_mode, host_threaded, host_use_cc_common_link, host_zigopt, mode, target, threaded, use_cc_common_link, - zig_version, zigopt) + use_standalone_translate_c, zig_version, zigopt) Transitions a target and its dependencies to a different configuration. @@ -324,6 +327,7 @@ zig_configure_test( | target | The target platform, expects a label to a Bazel target platform used to select a `zig_target_toolchain` instance. | Label | optional | `None` | | threaded | The threaded setting, corresponds to the `-fsingle-threaded` Zig compiler flag. | String | optional | `""` | | use_cc_common_link | Whether to use cc_common.link to link zig binaries, tests and shared libraries. Possible values: [-1, 0, 1]. -1 means use current configuration value for //zig/settings:experimental_use_cc_common_link. 0 means do not use cc_common.link (use zig build-exe instead). 1 means use cc_common.link. | Integer | optional | `-1` | +| use_standalone_translate_c | Whether to use a registered standalone translate-c toolchain for C translation instead of the built-in zig translate-c tool. Possible values: [-1, 0, 1]. -1 means use current configuration value for //zig/settings:use_standalone_translate_c. 0 means do not use the standalone translate-c toolchain. 1 means use the standalone translate-c toolchain. | Integer | optional | `-1` | | zig_version | The Zig SDK version, must be registered using the `zig` module extension. | String | optional | `""` | | zigopt | Additional list of flags passed to the zig compiler for all Zig compile actions.

The flags specified by this setting do not override those specified via the `zigopts` attribute of `zig_*` rules. Instead, they are prepended to the command line before module specific flags.

This is an advanced feature that can conflict with attributes, build settings, and other flags defined by the toolchain itself. Use this at your own risk of hitting undefined behaviors. | List of strings | optional | `[]` | diff --git a/e2e/workspace/MODULE.bazel b/e2e/workspace/MODULE.bazel index 97b041d0..950fd733 100644 --- a/e2e/workspace/MODULE.bazel +++ b/e2e/workspace/MODULE.bazel @@ -19,6 +19,26 @@ zig.toolchain(zig_version = "0.16.0") zig.toolchain(zig_version = "0.15.2") use_repo(zig, "zig_toolchains") +http_archive = use_repo_rule("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive") + +http_archive( + name = "arocc", + build_file = "//third_party/arocc:arocc.bazel", + sha256 = "e20b49a13049e8ef5aa1d798a70d8fc02b691fe44c7c78928aae3d363a1deb7e", + strip_prefix = "arocc-5f5a050569a95ecc40a426f0c3666ae7ef987ede", + url = "https://github.com/Vexu/arocc/archive/5f5a050569a95ecc40a426f0c3666ae7ef987ede.tar.gz", +) + +http_archive( + name = "translate-c", + build_file = "//third_party/translate-c:translate-c.bazel", + sha256 = "2f062a9e8baadf9e9e1a9460639175af727aa132237ca5ec7ea2435ea906f5a4", + strip_prefix = "translate-c", + url = "https://codeberg.org/ziglang/translate-c/archive/42f630117deffd5318b4a6ceffbd366dd0af8cee.tar.gz", +) + +register_toolchains("//third_party/translate-c:toolchain") + bazel_dep(name = "toolchains_buildbuddy", version = "0.0.4", dev_dependency = True) buildbuddy = use_extension( diff --git a/e2e/workspace/third_party/arocc/BUILD.bazel b/e2e/workspace/third_party/arocc/BUILD.bazel new file mode 100644 index 00000000..4485ef7e --- /dev/null +++ b/e2e/workspace/third_party/arocc/BUILD.bazel @@ -0,0 +1 @@ +# Intentionally empty. The repository build file is exported from this package. diff --git a/e2e/workspace/third_party/arocc/arocc.bazel b/e2e/workspace/third_party/arocc/arocc.bazel new file mode 100644 index 00000000..97832920 --- /dev/null +++ b/e2e/workspace/third_party/arocc/arocc.bazel @@ -0,0 +1,117 @@ +"""Build file for the e2e arocc repository.""" + +load("@bazel_skylib//rules:run_binary.bzl", "run_binary") +load("@bazel_skylib//rules:write_file.bzl", "write_file") +load("@rules_zig//zig:defs.bzl", "zig_binary", "zig_library") + +write_file( + name = "system_defaults_zig", + out = "system_defaults.zig", + content = ["""\ +pub const enable_linker_build_id: bool = false; +pub const linker: []const u8 = ""; +pub const sysroot: []const u8 = ""; +pub const gcc_install_prefix: []const u8 = ""; +pub const rtlib: []const u8 = ""; +pub const unwindlib: []const u8 = ""; +"""], +) + +zig_library( + name = "system_defaults", + main = ":system_defaults_zig", +) + +write_file( + name = "aro_options_zig", + out = "aro_options.zig", + content = ["""\ +pub const enable_tracy: bool = false; +pub const enable_tracy_callstack: bool = false; +pub const enable_tracy_allocation: bool = false; +pub const debug_allocations: bool = false; +pub const version_str: []const u8 = ""; +"""], +) + +zig_library( + name = "build_options", + main = ":aro_options_zig", +) + +zig_library( + name = "zig", + srcs = glob(["deps/zig/**/*.zig"]), + main = "deps/zig/lib.zig", +) + +zig_library( + name = "backend", + main = "src/backend.zig", + deps = [ + ":build_options", + ":zig", + ], +) + +zig_library( + name = "aro", + srcs = glob(["src/**/*.zig"]), + main = "src/aro.zig", + visibility = ["//visibility:public"], + deps = [ + ":backend", + ":build_options", + ":system_defaults", + ] + [ + ":{}".format(name.replace("src/aro/", "")) + for name in glob(["src/aro/**/*.def"]) + ], +) + +zig_library( + name = "assembly_backend", + main = "src/assembly_backend.zig", + deps = [ + ":aro", + ], +) + +zig_binary( + name = "arocc", + srcs = glob(["src/**/*.zig"]), + main = "src/main.zig", + deps = [ + ":aro", + ":assembly_backend", + ":build_options", + ], + zigopts = ["-fm"], +) + +zig_binary( + name = "generate-def", + main = "build/generate_def.zig", +) + +[ + run_binary( + name = "def_{}".format(name), + srcs = [name], + outs = ["{}.zig".format(name)], + args = [ + "$(location {})".format(name), + "$(location {}.zig)".format(name), + ], + tool = ":generate-def", + ) + for name in glob(["src/aro/**/*.def"]) +] + +[ + zig_library( + name = "{}".format(name.replace("src/aro/", "")), + main = ":def_{}".format(name), + ) + for name in glob(["src/aro/**/*.def"]) +] diff --git a/e2e/workspace/third_party/translate-c/BUILD.bazel b/e2e/workspace/third_party/translate-c/BUILD.bazel new file mode 100644 index 00000000..8cb9cc74 --- /dev/null +++ b/e2e/workspace/third_party/translate-c/BUILD.bazel @@ -0,0 +1,18 @@ +load("@rules_zig//zig/translate-c:toolchain.bzl", "translate_c_toolchain") + +translate_c_toolchain( + name = "toolchain_impl", + runtime_modules = [ + "@translate-c//:c_builtins", + "@translate-c//:helpers", + ], + translate_c = "@translate-c//:translate-c", +) + +toolchain( + name = "toolchain", + target_settings = ["@rules_zig//zig/config/use_standalone_translate_c:enabled"], + toolchain = ":toolchain_impl", + toolchain_type = "@rules_zig//zig/translate-c:toolchain_type", + visibility = ["//visibility:public"], +) diff --git a/e2e/workspace/third_party/translate-c/translate-c.bazel b/e2e/workspace/third_party/translate-c/translate-c.bazel new file mode 100644 index 00000000..2460e705 --- /dev/null +++ b/e2e/workspace/third_party/translate-c/translate-c.bazel @@ -0,0 +1,28 @@ +"""Build file for the e2e translate-c repository.""" + +load("@rules_zig//zig:defs.bzl", "zig_binary", "zig_library") + +zig_library( + name = "c_builtins", + main = "lib/c_builtins.zig", + visibility = ["//visibility:public"], +) + +zig_library( + name = "helpers", + main = "lib/helpers.zig", + visibility = ["//visibility:public"], +) + +zig_binary( + name = "translate-c", + data = glob(["lib/**/*.zig"]), + srcs = glob(["src/**/*.zig"]), + main = "src/main.zig", + visibility = ["//visibility:public"], + deps = [ + ":c_builtins", + ":helpers", + "@arocc//:aro", + ], +) diff --git a/e2e/workspace/translate-c/transitive-cc-library-zig-binary/BUILD.bazel b/e2e/workspace/translate-c/transitive-cc-library-zig-binary/BUILD.bazel index c0341421..ae5de011 100644 --- a/e2e/workspace/translate-c/transitive-cc-library-zig-binary/BUILD.bazel +++ b/e2e/workspace/translate-c/transitive-cc-library-zig-binary/BUILD.bazel @@ -1,6 +1,6 @@ load("@bazel_skylib//rules:diff_test.bzl", "diff_test") load("@rules_cc//cc:defs.bzl", "cc_library") -load("@rules_zig//zig:defs.bzl", "zig_binary", "zig_c_library", "zig_library") +load("@rules_zig//zig:defs.bzl", "zig_binary", "zig_c_library", "zig_configure_test", "zig_library") cc_library( name = "local_c", @@ -40,6 +40,12 @@ zig_binary( ], ) +zig_binary( + name = "global_binary", + main = "main_global.zig", + deps = [":global_c"], +) + genrule( name = "output", outs = ["output.actual"], @@ -47,9 +53,34 @@ genrule( tools = [":binary"], ) +genrule( + name = "global_output", + outs = ["output_global.actual"], + cmd = "$(execpath :global_binary) > $(OUTS)", + tools = [":global_binary"], +) + diff_test( name = "output_test", size = "small", file1 = ":output.expected", file2 = ":output.actual", ) + +diff_test( + name = "global_output_test", + size = "small", + file1 = ":output_global.expected", + file2 = ":output_global.actual", +) + +zig_configure_test( + name = "output_test_external_translate_c", + size = "small", + actual = ":global_output_test", + target_compatible_with = select({ + "@zig_toolchains//:0.15.2": ["@platforms//:incompatible"], + "//conditions:default": [], + }), + use_standalone_translate_c = 1, +) diff --git a/e2e/workspace/translate-c/transitive-cc-library-zig-binary/main_global.zig b/e2e/workspace/translate-c/transitive-cc-library-zig-binary/main_global.zig new file mode 100644 index 00000000..3026788a --- /dev/null +++ b/e2e/workspace/translate-c/transitive-cc-library-zig-binary/main_global.zig @@ -0,0 +1,23 @@ +const std = @import("std"); +const c = @import("c"); +const builtin = @import("builtin"); + +const is_zig_0_16_or_later = builtin.zig_version.major == 0 and builtin.zig_version.minor >= 16; + +pub const main = if (is_zig_0_16_or_later) main_016 else main_pre_016; + +fn main_pre_016() !void { + var buffer: [512]u8 = undefined; + var writer = std.fs.File.stdout().writer(&buffer); + const stdout = &writer.interface; + try stdout.print("global={}\n", .{c.global()}); + try stdout.flush(); +} + +fn main_016(init: std.process.Init) !void { + var buffer: [512]u8 = undefined; + var writer = std.Io.File.stdout().writer(init.io, &buffer); + const stdout = &writer.interface; + try stdout.print("global={}\n", .{c.global()}); + try stdout.flush(); +} diff --git a/e2e/workspace/translate-c/transitive-cc-library-zig-binary/output_global.expected b/e2e/workspace/translate-c/transitive-cc-library-zig-binary/output_global.expected new file mode 100644 index 00000000..72f39d4a --- /dev/null +++ b/e2e/workspace/translate-c/transitive-cc-library-zig-binary/output_global.expected @@ -0,0 +1 @@ +global=42 diff --git a/zig/BUILD.bazel b/zig/BUILD.bazel index 89ebcb8f..6dae3b9f 100644 --- a/zig/BUILD.bazel +++ b/zig/BUILD.bazel @@ -90,6 +90,7 @@ filegroup( "//zig/runfiles:all_files", "//zig/settings:all_files", "//zig/target:all_files", + "//zig/translate-c:all_files", ], visibility = ["//:__pkg__"], ) diff --git a/zig/config/BUILD.bazel b/zig/config/BUILD.bazel index a694dccb..0c635c2a 100644 --- a/zig/config/BUILD.bazel +++ b/zig/config/BUILD.bazel @@ -5,6 +5,7 @@ filegroup( ":BUILD.bazel", "//zig/config/mode:all_files", "//zig/config/threaded:all_files", + "//zig/config/use_standalone_translate_c:all_files", ], visibility = ["//zig:__pkg__"], ) diff --git a/zig/config/use_standalone_translate_c/BUILD.bazel b/zig/config/use_standalone_translate_c/BUILD.bazel new file mode 100644 index 00000000..c19b3236 --- /dev/null +++ b/zig/config/use_standalone_translate_c/BUILD.bazel @@ -0,0 +1,22 @@ +config_setting( + name = "enabled", + flag_values = { + "//zig/settings:use_standalone_translate_c": "1", + }, + visibility = ["//visibility:public"], +) + +config_setting( + name = "disabled", + flag_values = { + "//zig/settings:use_standalone_translate_c": "0", + }, + visibility = ["//visibility:public"], +) + +# Execute `bazel run //util:update_filegroups` to update this target. +filegroup( + name = "all_files", + srcs = [":BUILD.bazel"], + visibility = ["//zig/config:__pkg__"], +) diff --git a/zig/private/BUILD.bazel b/zig/private/BUILD.bazel index 7310642c..6fbfc971 100644 --- a/zig/private/BUILD.bazel +++ b/zig/private/BUILD.bazel @@ -30,7 +30,9 @@ bzl_library( "//zig/private/common:bazel_builtin", "//zig/private/common:data", "//zig/private/common:filetypes", + "//zig/private/common:translate_c", "//zig/private/providers:zig_module_info", + "@apple_support//lib:apple_support", ], ) @@ -42,6 +44,7 @@ bzl_library( deps = [ "//zig/private/common:zig_build", "//zig/private/common:zig_docs", + "@apple_support//lib:apple_support", ], ) @@ -69,6 +72,7 @@ bzl_library( deps = [ "//zig/private/common:zig_build", "//zig/private/common:zig_docs", + "@apple_support//lib:apple_support", ], ) diff --git a/zig/private/bzlmod/zig.bzl b/zig/private/bzlmod/zig.bzl index a3b7f511..a9d635d2 100644 --- a/zig/private/bzlmod/zig.bzl +++ b/zig/private/bzlmod/zig.bzl @@ -183,7 +183,6 @@ def _toolchain_extension(module_ctx): known_versions = merge_version_specs(version_specs) (err, versions) = handle_toolchain_tags(module_ctx.modules, known_versions = known_versions.keys()) - if err != None: fail(*err) diff --git a/zig/private/cc_helper.bzl b/zig/private/cc_helper.bzl index e65a3a2d..199b4852 100644 --- a/zig/private/cc_helper.bzl +++ b/zig/private/cc_helper.bzl @@ -6,12 +6,14 @@ load("@rules_cc//cc/common:cc_common.bzl", "cc_common") def need_translate_c(cc_info): return cc_info.compilation_context and (cc_info.compilation_context.headers or cc_info.compilation_context.defines) -def find_cc_toolchain(ctx, *, mandatory): +def find_cc_toolchain(ctx, *, mandatory, features = [], disabled_features = []): """Extracts a CcToolchain from the current target's context Args: ctx (ctx): The current target's rule context object mandatory (bool): Whether the toolchain is mandatory + features (list): A list of features to enable in the toolchain + disabled_features (list): A list of features to disable in the toolchain Returns: tuple: A tuple of (CcToolchain, FeatureConfiguration) @@ -23,7 +25,7 @@ def find_cc_toolchain(ctx, *, mandatory): feature_configuration = cc_common.configure_features( ctx = ctx, cc_toolchain = cc_toolchain, - requested_features = ctx.features, - unsupported_features = ctx.disabled_features, + requested_features = ctx.features + features, + unsupported_features = ctx.disabled_features + disabled_features, ) return cc_toolchain, feature_configuration diff --git a/zig/private/common/BUILD.bazel b/zig/private/common/BUILD.bazel index 5de68601..57d2d063 100644 --- a/zig/private/common/BUILD.bazel +++ b/zig/private/common/BUILD.bazel @@ -53,8 +53,10 @@ bzl_library( ":csrcs", ":escape_label", ":location_expansion", + ":translate_c", ":zig_cache", ":zig_lib_dir", + "//zig/private:cc_helper", "//zig/private/providers:zig_module_info", "//zig/private/providers:zig_settings_info", "//zig/private/providers:zig_target_info", @@ -94,7 +96,9 @@ bzl_library( ":escape_label", "//zig/private:cc_helper", "//zig/private/providers:zig_module_info", + "@apple_support//lib:apple_support", "@rules_cc//cc:action_names.bzl", + "@rules_cc//cc/common", ], ) diff --git a/zig/private/common/translate_c.bzl b/zig/private/common/translate_c.bzl index 08feceb9..1fb98a46 100644 --- a/zig/private/common/translate_c.bzl +++ b/zig/private/common/translate_c.bzl @@ -1,33 +1,83 @@ """Handle translate-c pass.""" -load("@rules_cc//cc:find_cc_toolchain.bzl", "find_cc_toolchain") +load("@apple_support//lib:apple_support.bzl", "apple_support") +load("@bazel_skylib//lib:paths.bzl", "paths") +load("@rules_cc//cc:action_names.bzl", "ACTION_NAMES") load("@rules_cc//cc/common:cc_common.bzl", "cc_common") load("@rules_cc//cc/common:cc_info.bzl", "CcInfo") +load("//zig/private:cc_helper.bzl", "find_cc_toolchain") load("//zig/private/common:escape_label.bzl", "escape_label", "escape_label_str") load("//zig/private/providers:zig_module_info.bzl", "zig_module_info") -def zig_translate_c(*, ctx, name, canonical_name = None, zigtoolchaininfo, global_args, cc_infos, output_prefix = ""): - """Handle translate-c build action. +_DEFAULT_SYSROOT_INCLUDE_DIRS = [ + paths.join("usr", "include"), +] - Sets the appropriate command-line flags for the Zig compiler to expose - provided headers and link against the provided libraries. +_APPLE_DEFAULT_TOOLCHAIN_INCLUDE_DIRS = _DEFAULT_SYSROOT_INCLUDE_DIRS + [ + paths.join("usr", "lib", "clang", str(version), "include") + for version in range(15, 22) +] - Args: - ctx: Context object. - name: String, the name of the resulting Zig module. - canonical_name: String or None, optional canonical name override for the resulting Zig module. - zigtoolchaininfo: ZigToolchainInfo. - global_args: Args; mutable, Append the global Zig command-line flags to this object. - cc_infos: List of CcInfo, The CcInfo providers for the C dependencies. - output_prefix: String, a prefix to be used for generated files. Used for zig_docs. +_TRANSLATED_ARGS = { + "-internal-isystem": "-isystem", +} - Returns: - `ZigModuleInfo` surrounding the generated zig file. - """ - cc_info = cc_common.merge_cc_infos(direct_cc_infos = cc_infos) - compilation_context = cc_info.compilation_context - linking_context = cc_info.linking_context +_FILTERED_ARGS = [ + "-Xclang", +] + +def _sanitize_commandline(args): + ret = [] + for arg in args: + if arg in _TRANSLATED_ARGS: + ret.append(_TRANSLATED_ARGS[arg]) + continue + elif arg in _FILTERED_ARGS: + continue + for prefix, replacement in _TRANSLATED_ARGS.items(): + if arg.startswith(prefix): + ret.append(replacement + arg[len(prefix):]) + continue + for prefix in _FILTERED_ARGS: + if arg.startswith(prefix): + continue + ret.append(arg) + return ret + +def _extract_sysroot(command_line): + sysroot = None + waiting_for_sysroot = False + + for arg in command_line: + if waiting_for_sysroot: + return arg + elif arg == "-isysroot": + waiting_for_sysroot = True + elif arg.startswith("-isysroot"): + # rare compact form: -isysroot/path + return arg[len("-isysroot"):] + elif arg.startswith("--sysroot="): + return arg[len("--sysroot="):] + + if waiting_for_sysroot: + fail("-isysroot without following path in command_line") + return sysroot + +def _include_path_for_file(file): + if (file.is_source == False): + virtual_include_prefix = "/_virtual_includes/{}/".format(file.owner.name) + virtual_include_idx = file.path.find(virtual_include_prefix) + if (virtual_include_idx > 0): + return file.path[virtual_include_idx + len(virtual_include_prefix):] + if (file.owner.repo_name): + return file.path.removeprefix(file.owner.workspace_root + "/") + return file.path + +def _is_local_config_apple_cc(cc_toolchain): + return cc_toolchain and "local_config_apple_cc" in cc_toolchain.compiler_executable + +def _builtin_translate_c(*, ctx, zigtoolchaininfo, global_args, compilation_context, output_prefix): inputs = [] transitive_inputs = [compilation_context.headers] @@ -57,7 +107,7 @@ def zig_translate_c(*, ctx, name, canonical_name = None, zigtoolchaininfo, globa # If there is a CC toolchain, add builtin directories. # This allows including to extra headers provided directly by the toolchain. # E.g. on macOS. - cc_toolchain = find_cc_toolchain(ctx, mandatory = False) + cc_toolchain, _ = find_cc_toolchain(ctx, mandatory = False) if cc_toolchain: transitive_inputs.append(cc_toolchain.all_files) args.add_all(cc_toolchain.built_in_include_directories, before_each = "-isystem") @@ -83,12 +133,188 @@ def zig_translate_c(*, ctx, name, canonical_name = None, zigtoolchaininfo, globa toolchain = "//zig:toolchain_type", ) - # Only forward the linking context since compilation_context is now handled - # by Zig through the generated _c.zig. - cc_info = CcInfo( - linking_context = linking_context, + return zig_out, [] + +def _external_translate_c(*, ctx, zigtoolchaininfo, translatectoolchaininfo, compilation_context, output_prefix): + inputs = [] + transitive_inputs = [compilation_context.headers] + + hdrs = compilation_context.direct_public_headers + + # If there is a CC toolchain, add builtin directories. + # This allows including to extra headers provided directly by the toolchain. + # E.g. on macOS. + cc_toolchain, cc_feature_configuration = find_cc_toolchain( + ctx, + mandatory = False, + disabled_features = ["thin_lto"], ) + # Detect if the toolchain is the local apple cc toolchain since it requires + # special handling to get the builtin headers included. + is_local_apple_cc = _is_local_config_apple_cc(cc_toolchain) + if cc_toolchain: + toolchain_defines_hdr = ctx.actions.declare_file("{}{}.toolchain_defines_hdr.c".format(output_prefix, ctx.label.name)) + ctx.actions.write(toolchain_defines_hdr, "") + + _, cc_results = cc_common.compile( + actions = ctx.actions, + feature_configuration = cc_feature_configuration, + cc_toolchain = cc_toolchain, + srcs = [toolchain_defines_hdr], + name = ctx.label.name, + # -fblocks is by default on darwin. but gcc doesn't handle it so best undef the macro manually. + user_compile_flags = ["-x", "c", "-E", "-dM", "-D__building_module(x)=0", "-U__BLOCKS__"], + disallow_pic_outputs = True, + ) + + hdrs = cc_results.objects + hdrs + transitive_inputs.append(depset(direct = cc_results.objects)) + + hdr = ctx.actions.declare_file("{}{}_c.h".format(output_prefix, ctx.label.name)) + ctx.actions.write(hdr, "\n".join([ + '#include "{}"'.format(_include_path_for_file(hdr)) + for hdr in hdrs + ])) + inputs.append(hdr) + + args = ctx.actions.args() + args.add(hdr) + + args.add_all([ + "-undef", + "-nobuiltininc", + "-fmodule-libs", + "-D__building_module(x)=0", + ]) + + if cc_toolchain: + c_compile_variables = cc_common.create_compile_variables( + feature_configuration = cc_feature_configuration, + cc_toolchain = cc_toolchain, + user_compile_flags = ctx.fragments.cpp.copts + ctx.fragments.cpp.conlyopts, + ) + command_line = cc_common.get_memory_inefficient_command_line( + feature_configuration = cc_feature_configuration, + action_name = ACTION_NAMES.c_compile, + variables = c_compile_variables, + ) + + transitive_inputs.append(cc_toolchain.all_files) + args.add_all(_sanitize_commandline(command_line)) + args.add_all(cc_toolchain.built_in_include_directories, before_each = "-isystem") + + # If the toolchain specifies a sysroot, add the sysroot's /usr/include as an + # include path since that's where the toolchain's builtin headers are expected to be. + sysroot = _extract_sysroot(command_line) + if sysroot != None and sysroot != "/dev/null": + args.add("-isystem", paths.join(sysroot, "usr", "include")) + + # If using the local apple cc toolchain, also include the default toolchain's + # builtin headers since the local apple cc toolchain doesn't include them by default. + if is_local_apple_cc: + args.add_all( + _APPLE_DEFAULT_TOOLCHAIN_INCLUDE_DIRS, + before_each = "-isystem", + format_each = paths.join( + apple_support.path_placeholders.xcode(), + "Toolchains", + "XcodeDefault.xctoolchain", + "", + ) + "%s", + ) + + args.add_all(compilation_context.defines, format_each = "-D%s") + args.add("-I.") + args.add_all(compilation_context.includes, format_each = "-I%s") + + # Note, Zig does not support `-iquote` as of Zig 0.12.0 + # args.add_all(compilation_context.quote_includes, format_each = "-iquote%s") + args.add_all(compilation_context.quote_includes, format_each = "-I%s") + args.add_all(compilation_context.system_includes, before_each = "-isystem") + + # Added in Bazel 7, see https://github.com/bazelbuild/bazel/commit/a6ef0b341a8ffe8ab27e5ace79d8eaae158c422b + args.add_all(getattr(compilation_context, "external_includes", []), before_each = "-isystem") + args.add_all(compilation_context.framework_includes, format_each = "-F%s") + + zig_out = ctx.actions.declare_file("{}{}_c.zig".format(output_prefix, ctx.label.name)) + args.add("-o", zig_out) + args.add("--emulate=clang") + + actions_run = ctx.actions.run + actions_run_extra_kwargs = {} + if is_local_apple_cc: + actions_run = apple_support.run + actions_run_extra_kwargs = dict( + actions = ctx.actions, + apple_fragment = ctx.fragments.apple, + xcode_config = ctx.attr._xcode_config[apple_common.XcodeVersionConfig], + xcode_path_resolve_level = apple_support.xcode_path_resolve_level.args, + ) + + actions_run( + inputs = depset( + direct = inputs, + transitive = transitive_inputs, + ), + executable = translatectoolchaininfo.executable, + outputs = [zig_out], + arguments = [args], + mnemonic = "ZigTranslateC", + progress_message = "zig translate-c %{label}", + execution_requirements = {tag: "" for tag in ctx.attr.tags}, + env = { + "ZIG_GLOBAL_CACHE_DIR": zigtoolchaininfo.zig_cache, + "ZIG_LIB_DIR": zigtoolchaininfo.zig_lib_path, + "ZIG_LOCAL_CACHE_DIR": zigtoolchaininfo.zig_cache, + }, + tools = [translatectoolchaininfo.files_to_run] + zigtoolchaininfo.zig_files, + toolchain = "//zig:toolchain_type", + **actions_run_extra_kwargs + ) + + return zig_out, translatectoolchaininfo.runtime_modules + +def zig_translate_c(*, ctx, name, zigtoolchaininfo, global_args, cc_infos, output_prefix = "", canonical_name = None, translatectoolchaininfo = None): + """Handle translate-c build action. + + Sets the appropriate command-line flags for the Zig compiler to expose + provided headers and link against the provided libraries. + + Args: + ctx: Context object. + name: String, the name of the resulting Zig module. + canonical_name: String or None, optional canonical name override for the resulting Zig module. + zigtoolchaininfo: ZigToolchainInfo. + global_args: Args; mutable, Append the global Zig command-line flags to this object. + cc_infos: List of CcInfo, The CcInfo providers for the C dependencies. + output_prefix: String, a prefix to be used for generated files. Used for zig_docs. + translatectoolchaininfo: TranslateCToolchainInfo or None. If present, use the external translate-c executable. + + Returns: + `ZigModuleInfo` surrounding the generated zig file. + """ + cc_info = cc_common.merge_cc_infos(direct_cc_infos = cc_infos) + compilation_context = cc_info.compilation_context + linking_context = cc_info.linking_context + + if translatectoolchaininfo: + zig_out, translate_c_deps = _external_translate_c( + ctx = ctx, + zigtoolchaininfo = zigtoolchaininfo, + translatectoolchaininfo = translatectoolchaininfo, + compilation_context = compilation_context, + output_prefix = output_prefix, + ) + else: + zig_out, translate_c_deps = _builtin_translate_c( + ctx = ctx, + zigtoolchaininfo = zigtoolchaininfo, + global_args = global_args, + compilation_context = compilation_context, + output_prefix = output_prefix, + ) + return zig_module_info( name = name, # To avoid collisions, we need to escape both label and name, @@ -96,5 +322,6 @@ def zig_translate_c(*, ctx, name, canonical_name = None, zigtoolchaininfo, globa # (here "__" is used as separator, since "_" is escaped as "_U"). canonical_name = canonical_name if canonical_name else "{}__{}".format(escape_label(label = ctx.label), escape_label_str(name)), main = zig_out, - cdeps = [cc_info], + cdeps = [CcInfo(linking_context = linking_context)], + deps = translate_c_deps, ) diff --git a/zig/private/common/zig_build.bzl b/zig/private/common/zig_build.bzl index dc76803f..8d290890 100644 --- a/zig/private/common/zig_build.bzl +++ b/zig/private/common/zig_build.bzl @@ -198,6 +198,7 @@ Environment variables to inherit from external environment when executed by `baz TOOLCHAINS = [ "//zig:toolchain_type", "//zig/target:toolchain_type", + config_common.toolchain_type("//zig/translate-c:toolchain_type", mandatory = False), ] + use_cc_toolchain(mandatory = False) FRAGMENTS = ["cpp"] @@ -242,6 +243,8 @@ def zig_build_impl(ctx, *, kind): zigtoolchaininfo = ctx.toolchains["//zig:toolchain_type"].zigtoolchaininfo zigtargetinfo = ctx.toolchains["//zig/target:toolchain_type"].zigtargetinfo + translate_c_toolchain = ctx.toolchains["//zig/translate-c:toolchain_type"] + translatectoolchaininfo = translate_c_toolchain.translatectoolchaininfo if translate_c_toolchain else None use_cc_common_link = ctx.attr._settings[ZigSettingsInfo].use_cc_common_link @@ -409,6 +412,7 @@ def zig_build_impl(ctx, *, kind): zigtoolchaininfo = zigtoolchaininfo, global_args = global_args, cc_infos = [root_module.cc_info], + translatectoolchaininfo = translatectoolchaininfo, ) transitive_inputs.append(c_module.transitive_inputs) diff --git a/zig/private/common/zig_docs.bzl b/zig/private/common/zig_docs.bzl index 81b7a4fd..0437c6e9 100644 --- a/zig/private/common/zig_docs.bzl +++ b/zig/private/common/zig_docs.bzl @@ -57,6 +57,8 @@ def zig_docs_impl(ctx, *, kind): zigtoolchaininfo = ctx.toolchains["//zig:toolchain_type"].zigtoolchaininfo zigtargetinfo = ctx.toolchains["//zig/target:toolchain_type"].zigtargetinfo + translate_c_toolchain = ctx.toolchains["//zig/translate-c:toolchain_type"] + translatectoolchaininfo = translate_c_toolchain.translatectoolchaininfo if translate_c_toolchain else None files = None @@ -149,6 +151,7 @@ def zig_docs_impl(ctx, *, kind): global_args = global_args, cc_infos = [root_module.cc_info], output_prefix = "docs", + translatectoolchaininfo = translatectoolchaininfo, ) transitive_inputs.append(c_module.transitive_inputs) diff --git a/zig/private/zig_binary.bzl b/zig/private/zig_binary.bzl index 5fa4d0e7..e040e151 100644 --- a/zig/private/zig_binary.bzl +++ b/zig/private/zig_binary.bzl @@ -1,5 +1,6 @@ """Implementation of the zig_binary rule.""" +load("@apple_support//lib:apple_support.bzl", "apple_support") load( "//zig/private/common:zig_build.bzl", "BINARY_ATTRS", @@ -41,14 +42,15 @@ zig_binary( ``` """ -ATTRS = COMMON_ATTRS | BINARY_ATTRS | DOCS_ATTRS +ATTRS = COMMON_ATTRS | BINARY_ATTRS | DOCS_ATTRS | apple_support.action_required_attrs() TOOLCHAINS = COMMON_TOOLCHAINS -FRAGMENTS = COMMON_FRAGMENTS +FRAGMENTS = COMMON_FRAGMENTS + ["apple"] def _zig_binary_impl(ctx): build, build_groups = zig_build_impl(ctx, kind = "zig_binary") + docs, docs_groups = zig_docs_impl(ctx, kind = "zig_binary") return build + docs + [OutputGroupInfo(**(build_groups | docs_groups))] diff --git a/zig/private/zig_c_library.bzl b/zig/private/zig_c_library.bzl index 84ba6461..3ce893d3 100644 --- a/zig/private/zig_c_library.bzl +++ b/zig/private/zig_c_library.bzl @@ -1,5 +1,6 @@ """Implementation of the zig_library rule.""" +load("@apple_support//lib:apple_support.bzl", "apple_support") load("@rules_cc//cc:find_cc_toolchain.bzl", "use_cc_toolchain") load("@rules_cc//cc/common:cc_info.bzl", "CcInfo") load( @@ -52,16 +53,19 @@ ATTRS = { doc = "Files required by the module during runtime.", mandatory = False, ), -} | BAZEL_BUILTIN_ATTRS +} | BAZEL_BUILTIN_ATTRS | apple_support.action_required_attrs() TOOLCHAINS = [ "//zig:toolchain_type", + config_common.toolchain_type("//zig/translate-c:toolchain_type", mandatory = False), ] + use_cc_toolchain(mandatory = False) -FRAGMENTS = ["cpp"] +FRAGMENTS = ["apple", "cpp"] def _zig_c_library_impl(ctx): zigtoolchaininfo = ctx.toolchains["//zig:toolchain_type"].zigtoolchaininfo + translate_c_toolchain = ctx.toolchains["//zig/translate-c:toolchain_type"] + translatectoolchaininfo = translate_c_toolchain.translatectoolchaininfo if translate_c_toolchain else None transitive_data = [] transitive_runfiles = [] @@ -102,6 +106,7 @@ def _zig_c_library_impl(ctx): zigtoolchaininfo = zigtoolchaininfo, global_args = global_args, cc_infos = cc_infos, + translatectoolchaininfo = translatectoolchaininfo, ) return [default, module] diff --git a/zig/private/zig_configure.bzl b/zig/private/zig_configure.bzl index 9541ef14..e86f2b47 100644 --- a/zig/private/zig_configure.bzl +++ b/zig/private/zig_configure.bzl @@ -123,6 +123,8 @@ def _zig_transition_impl(settings, attr): result["//zig/settings:zigopt"] = attr.zigopt if attr.host_zigopt: result["//zig/settings:host_zigopt"] = attr.host_zigopt + if attr.use_standalone_translate_c != -1: + result["//zig/settings:use_standalone_translate_c"] = attr.use_standalone_translate_c == 1 return result _zig_transition = transition( @@ -139,6 +141,7 @@ _zig_transition = transition( "//zig/settings:host_threaded", "//zig/settings:zigopt", "//zig/settings:host_zigopt", + "//zig/settings:use_standalone_translate_c", ], outputs = [ "//command_line_option:extra_toolchains", @@ -152,6 +155,7 @@ _zig_transition = transition( "//zig/settings:host_threaded", "//zig/settings:zigopt", "//zig/settings:host_zigopt", + "//zig/settings:use_standalone_translate_c", ], ) @@ -219,6 +223,18 @@ def _make_attrs(*, executable): mandatory = False, values = THREADED_VALUES, ), + "use_standalone_translate_c": attr.int( + doc = ( + "Whether to use a registered standalone translate-c toolchain for C translation instead of the built-in zig translate-c tool. " + + "Possible values: [-1, 0, 1]. " + + "-1 means use current configuration value for //zig/settings:use_standalone_translate_c. " + + "0 means do not use the standalone translate-c toolchain. " + + "1 means use the standalone translate-c toolchain." + ), + mandatory = False, + values = [-1, 0, 1], + default = -1, + ), "zigopt": attr.string_list( doc = """ Additional list of flags passed to the zig compiler for all Zig compile actions. diff --git a/zig/private/zig_test.bzl b/zig/private/zig_test.bzl index 630e4068..72ab902d 100644 --- a/zig/private/zig_test.bzl +++ b/zig/private/zig_test.bzl @@ -1,5 +1,6 @@ """Implementation of the zig_test rule.""" +load("@apple_support//lib:apple_support.bzl", "apple_support") load( "//zig/private/common:zig_build.bzl", "TEST_ATTRS", @@ -40,11 +41,11 @@ zig_test( ``` """ -ATTRS = COMMON_ATTRS | TEST_ATTRS | DOCS_ATTRS +ATTRS = COMMON_ATTRS | TEST_ATTRS | DOCS_ATTRS | apple_support.action_required_attrs() TOOLCHAINS = COMMON_TOOLCHAINS -FRAGMENTS = COMMON_FRAGMENTS +FRAGMENTS = COMMON_FRAGMENTS + ["apple"] def _zig_test_impl(ctx): build, build_groups = zig_build_impl(ctx, kind = "zig_test") diff --git a/zig/settings/BUILD.bazel b/zig/settings/BUILD.bazel index e0f8b400..14962998 100644 --- a/zig/settings/BUILD.bazel +++ b/zig/settings/BUILD.bazel @@ -71,6 +71,12 @@ repeatable_string_flag( visibility = ["//visibility:private"], ) +bool_flag( + name = "use_standalone_translate_c", + build_setting_default = False, + visibility = ["//zig/config/use_standalone_translate_c:__pkg__"], +) + # Execute `bazel run //util:update_filegroups` to update this target. filegroup( name = "all_files", diff --git a/zig/tests/BUILD.bazel b/zig/tests/BUILD.bazel index d80572b3..e56d013b 100644 --- a/zig/tests/BUILD.bazel +++ b/zig/tests/BUILD.bazel @@ -11,6 +11,7 @@ load(":target_platform_test.bzl", "target_platform_test_suite") load(":target_triple_test.bzl", "target_triple_test_suite") load(":threaded_test.bzl", "threaded_test_suite") load(":toolchain_header_test.bzl", "toolchain_header_test_suite") +load(":translate_c_action_test.bzl", "translate_c_action_test_suite") load(":use_cc_common_link_test.bzl", "use_cc_common_link_test_suite") load(":util.bzl", "forward_exec_settings") load(":versions_test.bzl", "versions_test_suite") @@ -44,6 +45,8 @@ threaded_test_suite(name = "threaded_test") toolchain_header_test_suite(name = "toolchain_header_test") +translate_c_action_test_suite(name = "translate_c_action_test") + versions_test_suite(name = "versions_test") zigopt_test_suite(name = "zigopt_test") diff --git a/zig/tests/translate-c-action/BUILD.bazel b/zig/tests/translate-c-action/BUILD.bazel new file mode 100644 index 00000000..3d63d455 --- /dev/null +++ b/zig/tests/translate-c-action/BUILD.bazel @@ -0,0 +1,31 @@ +load("@rules_cc//cc:defs.bzl", "cc_library") +load("//zig:defs.bzl", "zig_c_library") +load("//zig/translate-c:toolchain.bzl", "translate_c_toolchain") +load(":fake_translate_c.bzl", "fake_translate_c") + +cc_library( + name = "c", + hdrs = ["data.h"], +) + +zig_c_library( + name = "c_module", + cdeps = [":c"], + visibility = ["//zig/tests:__pkg__"], +) + +fake_translate_c( + name = "fake_translate_c", +) + +translate_c_toolchain( + name = "fake_translate_c_toolchain_impl", + translate_c = ":fake_translate_c", +) + +toolchain( + name = "fake_translate_c_toolchain", + target_settings = ["//zig/config/use_standalone_translate_c:enabled"], + toolchain = ":fake_translate_c_toolchain_impl", + toolchain_type = "//zig/translate-c:toolchain_type", +) diff --git a/zig/tests/translate-c-action/data.h b/zig/tests/translate-c-action/data.h new file mode 100644 index 00000000..74bc79a4 --- /dev/null +++ b/zig/tests/translate-c-action/data.h @@ -0,0 +1 @@ +int answer(void); diff --git a/zig/tests/translate-c-action/fake_translate_c.bzl b/zig/tests/translate-c-action/fake_translate_c.bzl new file mode 100644 index 00000000..f8763fb3 --- /dev/null +++ b/zig/tests/translate-c-action/fake_translate_c.bzl @@ -0,0 +1,20 @@ +"""Test-only fake translate-c executable.""" + +def _fake_translate_c_impl(ctx): + executable = ctx.actions.declare_file(ctx.label.name) + ctx.actions.write( + output = executable, + content = "#!/bin/sh\nexit 1\n", + is_executable = True, + ) + return [ + DefaultInfo( + executable = executable, + files = depset([executable]), + ), + ] + +fake_translate_c = rule( + implementation = _fake_translate_c_impl, + executable = True, +) diff --git a/zig/tests/translate_c_action_test.bzl b/zig/tests/translate_c_action_test.bzl new file mode 100644 index 00000000..8b2274d7 --- /dev/null +++ b/zig/tests/translate_c_action_test.bzl @@ -0,0 +1,79 @@ +"""Analysis tests for translate-c action selection.""" + +load("@bazel_skylib//lib:partial.bzl", "partial") +load("@bazel_skylib//lib:unittest.bzl", "analysistest", "asserts", "unittest") +load(":util.bzl", "assert_find_action", "canonical_label") + +_SETTINGS_TRANSLATE_C = canonical_label("@//zig/settings:use_standalone_translate_c") +_EXTRA_TOOLCHAINS = "//command_line_option:extra_toolchains" + +def _contains_exact(args, value): + for arg in args: + if arg == value: + return True + return False + +def _contains_substring(args, value): + for arg in args: + if value in arg: + return True + return False + +def _builtin_translate_c_action_test_impl(ctx): + env = analysistest.begin(ctx) + + action = assert_find_action(env, "ZigTranslateC") + asserts.true( + env, + _contains_exact(action.argv, "translate-c"), + "builtin translate-c action should invoke the Zig translate-c subcommand", + ) + asserts.false( + env, + _contains_substring(action.argv, "fake_translate_c"), + "builtin translate-c action should not invoke the external translate-c executable", + ) + + return analysistest.end(env) + +_builtin_translate_c_action_test = analysistest.make(_builtin_translate_c_action_test_impl) + +def _external_translate_c_action_test_impl(ctx): + env = analysistest.begin(ctx) + + action = assert_find_action(env, "ZigTranslateC") + asserts.false( + env, + _contains_exact(action.argv, "translate-c"), + "external translate-c action should not invoke the Zig translate-c subcommand", + ) + asserts.true( + env, + _contains_substring(action.argv, "fake_translate_c"), + "external translate-c action should invoke the external translate-c executable", + ) + + return analysistest.end(env) + +_external_translate_c_action_test = analysistest.make( + _external_translate_c_action_test_impl, + config_settings = { + _EXTRA_TOOLCHAINS: "//zig/tests/translate-c-action:fake_translate_c_toolchain", + _SETTINGS_TRANSLATE_C: True, + }, +) + +def translate_c_action_test_suite(name): + unittest.suite( + name, + partial.make( + _builtin_translate_c_action_test, + target_under_test = "//zig/tests/translate-c-action:c_module", + size = "small", + ), + partial.make( + _external_translate_c_action_test, + target_under_test = "//zig/tests/translate-c-action:c_module", + size = "small", + ), + ) diff --git a/zig/translate-c/BUILD.bazel b/zig/translate-c/BUILD.bazel new file mode 100644 index 00000000..01965a98 --- /dev/null +++ b/zig/translate-c/BUILD.bazel @@ -0,0 +1,23 @@ +load("@bazel_skylib//:bzl_library.bzl", "bzl_library") + +toolchain_type( + name = "toolchain_type", + visibility = ["//visibility:public"], +) + +bzl_library( + name = "toolchain", + srcs = ["toolchain.bzl"], + visibility = ["//visibility:public"], + deps = ["//zig/private/providers:zig_module_info"], +) + +# Execute `bazel run //util:update_filegroups` to update this target. +filegroup( + name = "all_files", + srcs = [ + ":BUILD.bazel", + ":toolchain.bzl", + ], + visibility = ["//zig:__pkg__"], +) diff --git a/zig/translate-c/toolchain.bzl b/zig/translate-c/toolchain.bzl new file mode 100644 index 00000000..78e8c0bd --- /dev/null +++ b/zig/translate-c/toolchain.bzl @@ -0,0 +1,59 @@ +"""Rules to declare translate-c toolchains.""" + +load( + "//zig/private/providers:zig_module_info.bzl", + "ZigModuleInfo", +) + +TranslateCToolchainInfo = provider( + doc = "Information about how to invoke an external translate-c executable.", + fields = { + "executable": "File, The translate-c executable.", + "files_to_run": "FilesToRunProvider, The translate-c executable and its runfiles.", + "runtime_modules": "List of ZigModuleInfo modules imported by generated translate-c output.", + }, +) + +def _disable_translate_c_transition_impl(_, __): + return { + "//zig/settings:use_standalone_translate_c": False, + } + +_disable_translate_c_transition = transition( + implementation = _disable_translate_c_transition_impl, + inputs = [], + outputs = [ + "//zig/settings:use_standalone_translate_c", + ], +) + +def _translate_c_toolchain_impl(ctx): + translatectoolchaininfo = TranslateCToolchainInfo( + executable = ctx.executable.translate_c, + files_to_run = ctx.attr.translate_c[DefaultInfo].files_to_run, + runtime_modules = [dep[ZigModuleInfo] for dep in ctx.attr.runtime_modules], + ) + return [ + platform_common.ToolchainInfo( + translatectoolchaininfo = translatectoolchaininfo, + ), + ] + +translate_c_toolchain = rule( + implementation = _translate_c_toolchain_impl, + attrs = { + "translate_c": attr.label( + doc = "The translate-c executable target or prebuilt executable file.", + allow_single_file = True, + cfg = "exec", + executable = True, + mandatory = True, + ), + "runtime_modules": attr.label_list( + doc = "Zig modules imported by Zig code generated by the translate-c executable.", + providers = [ZigModuleInfo], + ), + }, + cfg = _disable_translate_c_transition, + doc = "Defines a translate-c toolchain.", +)