load("//:platforms.bzl", "platforms")
load(":toolchain.bzl", "current_perl_toolchain", "perl_toolchain")

exports_files(["binary_wrapper.tpl"])

# toolchain_type defines a name for a kind of toolchain. Our toolchains
# declare that they have this type. Our rules request a toolchain of this type.
# Bazel selects a toolchain of the correct type that satisfies platform
# constraints from among registered toolchains.
toolchain_type(
    name = "toolchain_type",
    visibility = ["//visibility:public"],
)

[
    (
        # toolchain_impl gathers information about the Perl toolchain.
        # See the PerlToolchain provider.
        perl_toolchain(
            name = "perl_{os}_{cpu}_toolchain_impl".format(
                cpu = platform.cpu,
                os = platform.os,
            ),
            runtime = ["@perl_{os}_{cpu}//:runtime".format(
                cpu = platform.cpu,
                os = platform.os,
            )],
            visibility = ["//visibility:public"],
        ),

        # toolchain is a Bazel toolchain that expresses execution and target
        # constraints for toolchain_impl. This target should be registered by
        # calling register_toolchains in a WORKSPACE file.
        toolchain(
            name = "perl_{os}_{cpu}_toolchain".format(
                cpu = platform.cpu,
                os = platform.os,
            ),
            exec_compatible_with = platform.exec_compatible_with,
            toolchain = ":perl_{os}_{cpu}_toolchain_impl".format(
                cpu = platform.cpu,
                os = platform.os,
            ),
            toolchain_type = ":toolchain_type",
            visibility = ["//visibility:public"],
        ),
    )
    for platform in platforms
]

# This rule exists so that the current perl toolchain can be used in the `toolchains` attribute of
# other rules, such as genrule. It allows exposing a perl_toolchain after toolchain resolution has
# happened, to a rule which expects a concrete implementation of a toolchain, rather than a
# toolchain_type which could be resolved to that toolchain.
#
# See https://github.com/bazelbuild/bazel/issues/14009#issuecomment-921960766
current_perl_toolchain(
    name = "current_toolchain",
    visibility = ["//visibility:public"],
)
