packages feed

cabal-buck2-0.6.0.0: buck2/prelude/haskell/ghc_api_tool.bzl

load("@prelude//decls:toolchains_common.bzl", "toolchains_common")
load("@prelude//haskell:toolchain.bzl", "HaskellToolchainInfo", "compile_env_script", "in_compile_env")

# Rule to build a local tool that uses the GHC API. It has to be able
# to read .hi files generated by the toolchain's GHC, so it must be
# built by the same GHC. It can only depend on GHC and GHC's built-in
# packages. We can't use haskell rules to build it because that would
# be a cyclic dependency, hence this rather horrible hand-crafted
# rule.
#
# The rules pass the program GHC's libdir when they run it (see Libdir in
# tools/ghc-api).

def _haskell_ghc_api_tool_impl(ctx: AnalysisContext) -> list[Provider]:
    haskell_toolchain = ctx.attrs._haskell_toolchain[HaskellToolchainInfo]
    srcs = ctx.actions.symlinked_dir("srcs", {src.basename: src for src in ctx.attrs.srcs}, has_content_based_path = False)
    exe = build_ghc_api_tool(
        ctx.actions,
        ctx.attrs.name,
        haskell_toolchain.compiler,
        haskell_toolchain.compile_env,
        [cmd_args(srcs, format = "-i{}")],
        cmd_args(srcs, ctx.attrs.main, delimiter = "/"),
        GHC_API_TOOL_PACKAGES,
        [],
    )
    return [DefaultInfo(default_output = exe), RunInfo(args = cmd_args(exe))]

# Build a program that uses the GHC API, with `compiler`, from the Main
# module `main` and the modules that the -i flags `includes` find, using only
# GHC's own `packages`.
#
# This is a function rather than just a rule, so that a toolchain can build
# such a program with its own compiler. It can't do that through a
# rule without depending on itself.
def build_ghc_api_tool(actions: AnalysisActions, name: str, compiler, compile_env: dict[str, str], includes: list, main, packages: list[str], flags: list[str]) -> Artifact:
    # Run GHC with the toolchain's compile_env set, as every GHC command is.
    env_script = compile_env_script(compile_env)
    exe = actions.declare_output(name)
    actions.run(
        in_compile_env(env_script, [], cmd_args(
            "sh",
            "-c",
            'exec "$@" -outputdir "$BUCK_SCRATCH_PATH"',
            "sh",
            compiler,
            "-v0",
            "-O",
            # Use only GHC's own packages, ignoring any package environment
            # file (one in the project, for example).
            "-package-env=-",
            "-hide-all-packages",
            [["-package", p] for p in packages],
            # Leave out the debug information that the GHC library may have:
            # with it, each tool can be a gigabyte.
            "-optl-Wl,-S",
            flags,
            includes,
            main,
            "-o",
            exe.as_output(),
        )),
        category = "haskell_ghc_api_tool",
        identifier = name,
    )
    return exe

# The packages the tools use, all of which come with GHC.
GHC_API_TOOL_PACKAGES = ["base", "bytestring", "containers", "directory", "filepath", "ghc", "ghc-boot", "process"]

# The tools of the per-module compiles, by the name of their Main module. The
# tools' sources are in prelude//haskell/tools/ghc-api, and each source is
# also a target of prelude//haskell/tools, named after its path there.
GHC_API_TOOLS = {
    "per_module_compile": "PerModuleCompile",
    "per_module_deps": "PerModuleDeps",
}

# The modules that the tools share.
_SHARED_MODULES = ["Contract", "DepFile", "Imports", "Interface", "Libdir", "Pragmas", "Request"]

def ghc_api_tool_srcs(tool: str) -> dict[str, str]:
    """The `srcs` of a haskell_binary() that builds one of GHC_API_TOOLS,
    keyed by module name.

    A toolchain whose GHC is built from source can't use the tools that
    haskell_ghc_api_tool() builds, because they are linked with the GHC
    library of the GHC that builds them. It can build its own instead, as
    haskell_binary() targets that depend on the GHC library of the GHC that
    the toolchain runs, and pass them in the toolchain's `per_module_deps`
    and `per_module_compile`.
    """
    def src(module):
        return "prelude//haskell/tools:ghc-api/{}.hs".format(module)
    srcs = {module: src(module) for module in _SHARED_MODULES}
    srcs["Main"] = src(GHC_API_TOOLS[tool])
    return srcs

def ghc_api_tool_sources() -> list[str]:
    """The tools' source files, relative to prelude//haskell/tools."""
    return ["ghc-api/{}.hs".format(module) for module in _SHARED_MODULES + GHC_API_TOOLS.values()]

def check_ghc_api_tool_sources(found: list[str]):
    """Fails if a source in `found` isn't one of ghc_api_tool_sources().

    The modules are listed here, rather than found with a glob, because a
    toolchain in another cell can't glob the tools' directory. So the
    directory's BUCK file passes its own glob here, to make sure that a new
    module doesn't go unlisted.
    """
    missing = [src for src in found if src not in ghc_api_tool_sources()]
    if missing:
        fail("add these modules to GHC_API_TOOLS or _SHARED_MODULES in ghc_api_tool.bzl: " + ", ".join(missing))

haskell_ghc_api_tool = rule(
    impl = _haskell_ghc_api_tool_impl,
    attrs = {
        # The program's modules. They must all be in the same directory,
        # which is the program's only source directory.
        "srcs": attrs.list(attrs.source()),
        # The file name of the Main module, which must be one of `srcs`.
        "main": attrs.string(),
        "_haskell_toolchain": toolchains_common.haskell(),
    },
)