# -----------------------------------------------------------------------------
#
# (c) 2009-2013 The University of Glasgow
#
# This file is part of the GHC build system.
#
# To understand how the build system works and how to modify it, see
#      https://gitlab.haskell.org/ghc/ghc/wikis/building/architecture
#      https://gitlab.haskell.org/ghc/ghc/wikis/building/modifying
#
# -----------------------------------------------------------------------------

# ToDo List.
#
#   * remove old Makefiles, add new stubs for building in subdirs
#     * docs/Makefile
#     * docs/storage-mgmt/Makefile
#     * docs/vh/Makefile
#     * rts/dotnet/Makefile
#     * utils/Makefile
#   * add Makefiles for the rest of the utils/ programs that aren't built
#     by default (need to exclude them from 'make all' too)

# Possible cleanups:
#
#   * per-source-file dependencies instead of one .depend file?
#   * eliminate undefined variables, and use --warn-undefined-variables?
#   * put outputs from different ways in different subdirs of distdir/build,
#     then we don't have to use -osuf/-hisuf.  We would have to install
#     them in different places too, so we'd need ghc-pkg support for packages
#     of different ways.
#   * make PACKAGES_STAGE1 generated by './configure' or './boot'?
#   * we should use a directory of package.conf files rather than a single
#     file for the inplace package database, so that we can express
#     dependencies more accurately.  Otherwise it's possible to get into
#     a state where the package database is out of date, and the build
#     system doesn't know.

# Approximate build order.
#
# The actual build order is defined by dependencies, and the phase
# ordering used to ensure correct ordering of makefile-generation; see
#    https://gitlab.haskell.org/ghc/ghc/wikis/building/architecture/idiom/phase-ordering
#
#     * With bootstrapping compiler:
#           o Build utils/ghc-cabal
#           o Build utils/ghc-pkg
#           o Build utils/hsc2hs
#           o Build utils/genprimopcode
#           o Build utils/deriveConstants
#     * For each package:
#	    o configure, generate package-data.mk and inplace-pkg-config
#           o register each package into inplace/lib/package.conf
#     * build libffi (if not disabled by --with-system-libffi)
#     * With bootstrapping compiler:
#	    o Build libraries/{filepath,hpc,Cabal}
#           o Build compiler (stage 1)
#     * With stage 1 compiler:
#           o Build libraries/*
#	    o Build rts
#           o Build utils/* (except haddock)
#           o Build compiler (stage 2)
#     * With stage 2 compiler:
#           o Build utils/haddock
#           o Build compiler (stage 3) (optional)
#     * With haddock:
#           o libraries/*
#           o compiler

.PHONY: default all haddock

# We need second expansion for the way we handle directories, so that
#     | $$$$(dir $$$$@)/.
# expands to the directory of a rule that uses a % pattern.
.SECONDEXPANSION:

default : all


##################################################
# Check that we have a new enough 'make'

HAVE_EVAL := NO
$(eval HAVE_EVAL := YES)

ifeq "$(HAVE_EVAL)" "NO"
$(error Your make does not support eval. You need GNU make >= 3.81)
endif

ifeq "$(abspath /)" ""
$(error Your make does not support abspath. You need GNU make >= 3.81)
endif
##################################################

# -----------------------------------------------------------------------------
# Catch make if it runs away into an infinite loop
ifeq      "$(MAKE_RESTARTS)" ""
else ifeq "$(MAKE_RESTARTS)" "1"
else
$(error Make has restarted itself $(MAKE_RESTARTS) times; is there a makefile bug? See https://gitlab.haskell.org/ghc/ghc/wikis/building/troubleshooting#make-has-restarted-itself-3-times-is-there-a-makefile-bug for details)
endif

# -----------------------------------------------------------------------------
# Misc GNU make utils

nothing=
space=$(nothing) $(nothing)
comma=,

# -----------------------------------------------------------------------------
# Makefile debugging
#
# to see the effective value used for a Makefile variable, do
#  make show VALUE=MY_VALUE
#

show:
	@echo '$(VALUE)="$($(VALUE))"'

# echo is used by the nightly builders to query the build system for
# information.
# Using printf means that we don't get a trailing newline. We escape
# backslashes and double quotes in the string to protect them from the
# shell, and percent signs to protect them from printf.
echo:
	@printf "$(subst %,%%,$(subst ",\",$(subst \,\\\\,$($(VALUE)))))"

# -----------------------------------------------------------------------------
# Include subsidiary build-system bits

include mk/tree.mk

ifneq "$(CLEANING)" "YES"
include mk/config.mk
ifeq "$(ProjectVersion)" ""
$(error Please run ./configure first)
endif
endif

include mk/ways.mk

# (Optional) build-specific configuration
include mk/custom-settings.mk

# The user can reset SRC_HC_OPTS from mk/build.mk. Since we try to append
# '-Wall' to it in mk/warnings.mk, we have to include mk/warnings.mk after
# mk/custom-settings.mk.
include mk/warnings.mk

# -----------------------------------------------------------------------------
# Check for inconsistent settings, after reading mk/build.mk.
# Although mk/config.mk should always contain consistent settings (set by
# configure), mk/build.mk can contain pretty much anything.

ifneq "$(CLEANING)" "YES"

ifeq "$(DYNAMIC_GHC_PROGRAMS)" "YES"
ifeq "$(findstring dyn,$(GhcLibWays))" ""
$(error dyn is not in $$(GhcLibWays), but $$(DYNAMIC_GHC_PROGRAMS) is YES)
endif
else
ifeq "$(findstring v,$(GhcLibWays))" ""
$(error v is not in $$(GhcLibWays), and $$(DYNAMIC_GHC_PROGRAMS) is not YES)
endif
endif

ifeq "$(GhcProfiled)" "YES"
ifeq "$(findstring p,$(GhcLibWays))" ""
$(error p is not in $$(GhcLibWays), and $$(GhcProfiled) is YES)
endif
endif

ifeq "$(BUILD_SPHINX_HTML)" "YES"
ifeq "$(SPHINXBUILD)" ""
$(error BUILD_SPHINX_HTML=YES, but `sphinx-build` was not found. \
  Create a file `mk/validate.mk` containing `BUILD_SPHINX_HTML=NO` \
  (when validating), or install `sphinx-build` and rerun `./configure`. \
  See https://gitlab.haskell.org/ghc/ghc/wikis/building/preparation)
endif
endif

ifeq "$(BUILD_SPHINX_PDF)" "YES"
ifeq "$(XELATEX)" ""
$(error BUILD_SPHINX_PDF=YES, but `xelatex` was not found. \
  Install `xelatex`, then rerun `./configure`. \
  See https://gitlab.haskell.org/ghc/ghc/wikis/building/preparation)
endif
endif

ifeq "$(HSCOLOUR_SRCS)" "YES"
ifeq "$(HSCOLOUR_CMD)" ""
$(error HSCOLOUR_SRCS=YES, but HSCOLOUR_CMD is empty. \
  Run `cabal install hscolour`, then rerun `./configure`. \
  See https://gitlab.haskell.org/ghc/ghc/wikis/building/preparation)
endif
endif

ifeq "$(HADDOCK_DOCS)" "YES"
ifneq "$(CrossCompiling) $(Stage1Only)" "NO NO"
$(error Can not build haddock docs when CrossCompiling or Stage1Only. \
  Set HADDOCK_DOCS=NO in your mk/build.mk file. \
  See Note [No stage2 packages when CrossCompiling or Stage1Only])
endif
endif

endif # CLEANING

# -----------------------------------------------------------------------------

ifeq "$(phase)" ""
phase = final
endif

# -----------------------------------------------------------------------------
# Utility definitions

include rules/prof.mk
include rules/trace.mk
include rules/library-path.mk
include rules/add-dependency.mk
include rules/make-command.mk
include rules/pretty_commands.mk

# -----------------------------------------------------------------------------
# Macros for standard targets

include rules/all-target.mk
include rules/clean-target.mk

# -----------------------------------------------------------------------------
# The inplace tree

$(eval $(call clean-target,root,inplace,inplace/bin inplace/lib))

# -----------------------------------------------------------------------------
# Whether to build dependencies or not

# When we're just doing 'make clean' or 'make show', then we don't need
# to build dependencies.

ifeq "$(CLEANING)" "YES"
NO_INCLUDE_DEPS = YES
NO_INCLUDE_PKGDATA = YES
endif
ifneq "$(findstring bootstrapping-files,$(MAKECMDGOALS))" ""
NO_INCLUDE_DEPS = YES
NO_INCLUDE_PKGDATA = YES
endif
ifeq "$(findstring show,$(MAKECMDGOALS))" "show"
NO_INCLUDE_DEPS = YES
# We want package-data.mk for show
endif

# -----------------------------------------------------------------------------
# Ways

include rules/way-prelims.mk

$(foreach way,$(ALL_WAYS),\
  $(eval $(call way-prelims,$(way))))

ifeq "$(DYNAMIC_GHC_PROGRAMS)" "YES"
GHCI_WAY = dyn
HADDOCK_WAY = dyn
else
GHCI_WAY = v
HADDOCK_WAY = v
endif

WINDOWS_DYN_PROG_RTS := rts
ifeq "$(GhcThreaded)" "YES"
WINDOWS_DYN_PROG_RTS := $(WINDOWS_DYN_PROG_RTS)_thr
endif
ifeq "$(GhcDebugged)" "YES"
WINDOWS_DYN_PROG_RTS := $(WINDOWS_DYN_PROG_RTS)_debug
endif
WINDOWS_DYN_PROG_RTS := $(WINDOWS_DYN_PROG_RTS)_dyn_LIB_FILE

# -----------------------------------------------------------------------------
# Compilation Flags

include rules/distdir-opts.mk
include rules/distdir-way-opts.mk

# -----------------------------------------------------------------------------
# Finding source files and object files

include rules/hs-sources.mk
include rules/c-sources.mk
include rules/includes-sources.mk
include rules/hs-objs.mk
include rules/c-objs.mk
include rules/cmm-objs.mk

# -----------------------------------------------------------------------------
# Suffix rules

# Suffix rules cause "make clean" to fail on Windows (trac #3233)
# so we don't make any when cleaning.
ifneq "$(CLEANING)" "YES"
include rules/hs-suffix-rules-srcdir.mk
include rules/hs-suffix-way-rules-srcdir.mk
include rules/hs-suffix-way-rules.mk
include rules/hi-rule.mk
include rules/c-suffix-rules.mk
include rules/cmm-suffix-rules.mk
endif

# -----------------------------------------------------------------------------
# Building package-data.mk files from .cabal files

include rules/package-config.mk

# -----------------------------------------------------------------------------
# Building dependencies

include rules/dependencies.mk
include rules/build-dependencies.mk
include rules/include-dependencies.mk

# -----------------------------------------------------------------------------
# Build package-data.mk files

include rules/build-package-data.mk

# -----------------------------------------------------------------------------
# Build and install a program

include rules/build-prog.mk
include rules/shell-wrapper.mk

# -----------------------------------------------------------------------------
# Build a package

include rules/build-package.mk
include rules/build-package-way.mk
include rules/haddock.mk
include rules/foreachLibrary.mk

# -----------------------------------------------------------------------------
# Registering hand-written package descriptions (used in rts)

include rules/manual-package-config.mk

# -----------------------------------------------------------------------------
# Docs

include rules/sphinx.mk

# -----------------------------------------------------------------------------
# Making bindists and sdists

include rules/bindist.mk
include rules/sdist-ghc-file.mk

# -----------------------------------------------------------------------------
# Directories

# Don't try to delete directories:
.PRECIOUS: %/.

# Create build directories on demand.  NB. the | below: this indicates
# that $(MKDIRHIER) is an order-only dependency, which means that this
# rule fires after building mkdirhier, but we won't try to recreate
# directories if mkdirhier changes.
%/. : | $(MKDIRHIER)
	"$(MKDIRHIER)" $@

# -----------------------------------------------------------------------------
# Lax dependencies

ifeq "$(LAX_DEPENDENCIES)" "YES"
LAX_DEPS_FOLLOW = |
else
LAX_DEPS_FOLLOW =
endif

# This is a bit of a hack. When LAX_DEPS_FOLLOW is | some rules end up
# looking like
#     target: a | b | c
# The first | signals the start of the order-only dependencies, but make
# treats the second | as a dependency. So we need to tell make how to
# build that dependency.

.PHONY: |
| :
	@:

# -----------------------------------------------------------------------------
# Packages to build
# The lists of packages that we *actually* going to build in each stage:
#
#  $(PACKAGES_STAGE0)
#  $(PACKAGES_STAGE1)
#  $(PACKAGES_STAGE2)
#
# Note that we need to add them to these variables in dependency
# order, as this is the order that they get configured in.

ifeq "$(CLEANING)" "YES"

define addLibraryForCleaning
# We just add all packages to both the stage 0 and stage 1 lists.
# Stage 2 gets cleaned in the same way as stage 1, so no need to
# add it there.
PACKAGES_STAGE0 += $1
PACKAGES_STAGE1 += $1
endef
$(eval $(call foreachLibrary,addLibraryForCleaning))

else # CLEANING

# Packages that are built by stage0. These packages are dependencies of
# programs such as GHC and ghc-pkg, that we do not assume the stage0
# compiler already has installed (or up-to-date enough).

PACKAGES_STAGE0 = binary text transformers mtl parsec Cabal/Cabal hpc ghc-boot-th ghc-boot template-haskell ghc-heap ghci
ifeq "$(Windows_Host)" "NO"
PACKAGES_STAGE0 += terminfo
endif

PACKAGES_STAGE1 += ghc-prim
PACKAGES_STAGE1 += $(INTEGER_LIBRARY)
PACKAGES_STAGE1 += base
PACKAGES_STAGE1 += filepath
PACKAGES_STAGE1 += array
PACKAGES_STAGE1 += deepseq
PACKAGES_STAGE1 += bytestring
PACKAGES_STAGE1 += containers/containers

ifeq "$(Windows_Target)" "YES"
PACKAGES_STAGE1 += Win32
endif
PACKAGES_STAGE1 += time
ifeq "$(Windows_Target)" "NO"
PACKAGES_STAGE1 += unix
endif

PACKAGES_STAGE1 += directory
PACKAGES_STAGE1 += process
PACKAGES_STAGE1 += hpc
PACKAGES_STAGE1 += pretty
PACKAGES_STAGE1 += binary
PACKAGES_STAGE1 += text
PACKAGES_STAGE1 += transformers
PACKAGES_STAGE1 += mtl
PACKAGES_STAGE1 += parsec
PACKAGES_STAGE1 += Cabal/Cabal
PACKAGES_STAGE1 += ghc-boot-th
PACKAGES_STAGE1 += ghc-boot
PACKAGES_STAGE1 += template-haskell
PACKAGES_STAGE1 += ghc-compact
PACKAGES_STAGE1 += ghc-heap

ifeq "$(HADDOCK_DOCS)" "YES"
PACKAGES_STAGE1 += xhtml
endif

ifeq "$(WITH_TERMINFO)" "YES"
PACKAGES_STAGE1 += terminfo
else
libraries/haskeline_CONFIGURE_OPTS += --flags=-terminfo
endif

PACKAGES_STAGE1 += stm
PACKAGES_STAGE1 += haskeline
PACKAGES_STAGE1 += ghci
PACKAGES_STAGE1 += libiserv

# See Note [No stage2 packages when CrossCompiling or Stage1Only].
# See Note [Stage1Only vs stage=1] in mk/config.mk.in.
ifeq "$(CrossCompiling) $(Stage1Only)" "NO NO"
define addExtraPackage
ifeq "$2" "-"
# Do nothing; this package is already handled above
else ifeq "$2" "extra"
ifeq "$$(BUILD_EXTRA_PKGS)" "YES"
PACKAGES_STAGE2 += $1
endif
else
$$(error Unknown package tag: $2)
endif
endef
$(eval $(call foreachLibrary,addExtraPackage))
endif

# We install all packages that we build.
INSTALL_PACKAGES := $(addprefix libraries/,$(PACKAGES_STAGE1))
# See Note [Stage1Only vs stage=1] in mk/config.mk.in.
ifneq "$(Stage1Only)" "YES"
INSTALL_PACKAGES += compiler
endif
INSTALL_PACKAGES += $(addprefix libraries/,$(PACKAGES_STAGE2))

endif # CLEANING

# -------------------------------------------
# Note [Dependencies between package-data.mk files].

# We cannot run ghc-cabal to configure a package until we have
# configured and registered all of its dependencies.  So the following
# hack forces all the configure steps to happen in exactly the following order:
#
#  $(PACKAGES_STAGE1) ghc(stage2) $(PACKAGES_STAGE2)
#
# Ideally we should use the correct dependencies here to allow more
# parallelism, but we don't know the dependencies until we've
# generated the package-data.mk files.
define fixed_pkg_dep
libraries/$1/$2/package-data.mk : $$(fixed_pkg_prev)
fixed_pkg_prev:=libraries/$1/$2/package-data.mk
endef

ifneq "$(BINDIST)" "YES"
fixed_pkg_prev=
$(foreach pkg,$(PACKAGES_STAGE1),$(eval $(call fixed_pkg_dep,$(pkg),dist-install)))

# Intermezzo: utils that we build with the stage1 compiler. They depend on
# the stage1 packages, so we have to make sure those packages get configured
# and registered before we can start with these. Note that they don't depend on
# eachother, so we can configure them in parallel.
utils/ghc-cabal/dist-install/package-data.mk: $(fixed_pkg_prev)
utils/hpc/dist-install/package-data.mk: $(fixed_pkg_prev)
utils/ghc-pkg/dist-install/package-data.mk: $(fixed_pkg_prev)
utils/hsc2hs/dist-install/package-data.mk: $(fixed_pkg_prev)
utils/compare_sizes/dist-install/package-data.mk: $(fixed_pkg_prev)
utils/runghc/dist-install/package-data.mk: $(fixed_pkg_prev)
utils/iserv/stage2/package-data.mk: $(fixed_pkg_prev)
utils/iserv/stage2_p/package-data.mk: $(fixed_pkg_prev)
utils/iserv/stage2_dyn/package-data.mk: $(fixed_pkg_prev)
ifeq "$(Windows_Host)" "YES"
utils/gen-dll/dist-install/package-data.mk: $(fixed_pkg_prev)
endif

# the GHC package doesn't live in libraries/, so we add its dependency manually:
compiler/stage2/package-data.mk: $(fixed_pkg_prev)

# and continue with PACKAGES_STAGE2, which depend on GHC:
fixed_pkg_prev:=compiler/stage2/package-data.mk
$(foreach pkg,$(PACKAGES_STAGE2),$(eval $(call fixed_pkg_dep,$(pkg),dist-install)))

ghc/stage1/package-data.mk: compiler/stage1/package-data.mk
ghc/stage2/package-data.mk: compiler/stage2/package-data.mk

# Utils that we build with the stage2 compiler.
# They depend on the ghc library and some other libraries, but depending on
# the ghc library's package-data.mk is sufficient, as that in turn depends on
# all the other libraries' package-data.mk files.
utils/haddock/dist/package-data.mk: compiler/stage2/package-data.mk
utils/check-api-annotations/dist-install/package-data.mk: compiler/stage2/package-data.mk
utils/check-ppr/dist-install/package-data.mk: compiler/stage2/package-data.mk

# add the final package.conf dependency: ghc-prim depends on RTS
libraries/ghc-prim/dist-install/package-data.mk : rts/dist/package.conf.inplace
endif

# --------------------------------
# Misc package-related settings

# Run Haddock for the packages that will be installed. We need to handle
# compiler specially due to the different dist directory name.
$(foreach p,$(INSTALL_PACKAGES),$(eval $p_dist-install_DO_HADDOCK = YES))
compiler_stage2_DO_HADDOCK = YES

BOOT_PKG_CONSTRAINTS := \
    $(foreach d,$(PACKAGES_STAGE0),\
        $(foreach p,$(basename $(notdir $(wildcard libraries/$d/*.cabal))),\
            --constraint "$p == $(shell grep -i "^Version:" libraries/$d/$p.cabal | sed "s/[^0-9.]//g")"))

# The actual .a and .so/.dll files: needed for dependencies.
$(foreach way,$(GhcLibWays),$(eval ALL_STAGE1_$(way)_LIBS = $$(foreach lib,$$(PACKAGES_STAGE1),$$(libraries/$$(lib)_dist-install_$(way)_LIB))))

ALL_STAGE1_LIBS = $(ALL_STAGE1_v_LIBS)

ifeq "$(BuildSharedLibs)" "YES"
ALL_STAGE1_LIBS += $(foreach lib,$(PACKAGES_STAGE1),$(libraries/$(lib)_dist-install_dyn_LIB))
endif
BOOT_LIBS = $(foreach lib,$(PACKAGES_STAGE0),$(libraries/$(lib)_dist-boot_v_LIB))

# Only build internal interpreter support for the stage2 ghci lib
libraries/ghci_dist-install_CONFIGURE_OPTS += --flags=ghci

# ----------------------------------------
# Special magic for the ghc-prim package

# We want the ghc-prim package to include the GHC.Prim module when it
# is registered, but not when it is built, because GHC.Prim is not a
# real source module, it is built-in to GHC.

# Strip it out again before building the package:
define libraries/ghc-prim_PACKAGE_MAGIC
libraries/ghc-prim_dist-install_MODULES := $$(filter-out GHC.Prim,$$(libraries/ghc-prim_dist-install_MODULES))
endef

PRIMOPS_TXT_STAGE1 = compiler/stage1/build/primops.txt

libraries/ghc-prim/dist-install/build/GHC/PrimopWrappers.hs : $$(genprimopcode_INPLACE) $(PRIMOPS_TXT_STAGE1) | $$(dir $$@)/.
	"$(genprimopcode_INPLACE)" --make-haskell-wrappers < $(PRIMOPS_TXT_STAGE1) >$@

# Required so that Haddock documents the primops.
libraries/ghc-prim_dist-install_EXTRA_HADDOCK_SRCS = libraries/ghc-prim/dist-install/build/autogen/GHC/Prim.hs

# ----------------------------------------
# Special magic for the integer package

ifneq "$(CLEANING)" "YES"
ifeq "$(INTEGER_LIBRARY)" "integer-gmp"
libraries/base_dist-install_CONFIGURE_OPTS += --flags=integer-gmp
compiler_stage2_CONFIGURE_OPTS += --flags=integer-gmp
else ifeq "$(INTEGER_LIBRARY)" "integer-simple"
libraries/base_dist-install_CONFIGURE_OPTS += --flags=integer-simple
compiler_stage2_CONFIGURE_OPTS += --flags=integer-simple
else
$(error Unknown integer library: $(INTEGER_LIBRARY))
endif
endif

# -----------------------------------------------------------------------------
# Include build instructions from all subdirs
BUILD_DIRS += utils/mkdirhier
BUILD_DIRS += utils/touchy
BUILD_DIRS += utils/unlit
BUILD_DIRS += utils/hp2ps
BUILD_DIRS += utils/genprimopcode
BUILD_DIRS += driver
BUILD_DIRS += driver/ghci
BUILD_DIRS += driver/ghc
BUILD_DIRS += driver/haddock
BUILD_DIRS += libffi
BUILD_DIRS += utils/deriveConstants
BUILD_DIRS += includes
BUILD_DIRS += rts
BUILD_DIRS += bindisttest
BUILD_DIRS += utils/genapply
ifeq "$(Windows_Host)" "YES"
BUILD_DIRS += utils/gen-dll
endif

# When cleaning, don't add any library packages to BUILD_DIRS. We include
# ghc.mk files for all BUILD_DIRS, but they don't exist until after running
# `./boot`. Running `make clean` before anything else, as well as running
# `make maintainer-clean` twice, should work.
ifneq "$(CLEANING)" "YES"
# These are deliberately in reverse order, so as to ensure that
# there is no need to have them in dependency order. That's important
# because it's tricky to ensure that they are in dependency order when
# cross-compiling, as some packages may only be in PACKAGES_STAGE0
# or PACKAGES_STAGE1.
BUILD_DIRS += $(patsubst %, libraries/%, $(PACKAGES_STAGE2))
BUILD_DIRS += $(patsubst %, libraries/%, $(PACKAGES_STAGE1))
BUILD_DIRS += $(patsubst %, libraries/%, $(filter-out $(PACKAGES_STAGE1),$(PACKAGES_STAGE0)))
endif

BUILD_DIRS += libraries/integer-gmp/gmp
BUILD_DIRS += utils/haddock
BUILD_DIRS += utils/haddock/doc
BUILD_DIRS += compiler
BUILD_DIRS += utils/hsc2hs
BUILD_DIRS += utils/ghc-pkg
BUILD_DIRS += utils/testremove
BUILD_DIRS += utils/check-api-annotations
BUILD_DIRS += utils/check-ppr
BUILD_DIRS += utils/ghc-cabal
BUILD_DIRS += utils/hpc
BUILD_DIRS += utils/runghc
BUILD_DIRS += ghc
BUILD_DIRS += docs/users_guide
BUILD_DIRS += utils/compare_sizes
BUILD_DIRS += utils/iserv

# ----------------------------------------------
# Actually include the sub-ghc.mk's

ifeq "$(CLEANING)" "YES"
# Don't exclude any BUILD_DIRS when cleaning. When you for example build
# haddock once, but later set HADDOCK_DOCS back to NO, then 'make clean'
# should still clean the haddock directory.
else # CLEANING
ifeq "$(BINDIST)" "YES"
BUILD_DIRS := $(filter-out utils/mkdirhier,$(BUILD_DIRS))
BUILD_DIRS := $(filter-out utils/genprimopcode,$(BUILD_DIRS))
BUILD_DIRS := $(filter-out bindisttest,$(BUILD_DIRS))
BUILD_DIRS := $(filter-out utils/genapply,$(BUILD_DIRS))
endif
ifeq "$(HADDOCK_DOCS)" "NO"
BUILD_DIRS := $(filter-out utils/haddock,$(BUILD_DIRS))
BUILD_DIRS := $(filter-out utils/haddock/doc,$(BUILD_DIRS))
endif
ifeq "$(BUILD_SPHINX_HTML) $(BUILD_SPHINX_PDF)" "NO NO"
BUILD_DIRS := $(filter-out docs/users_guide,$(BUILD_DIRS))
# Don't to build this little utility if we're not building the User's Guide.
endif
ifeq "$(Windows_Host)" "NO"
BUILD_DIRS := $(filter-out utils/touchy,$(BUILD_DIRS))
endif
ifeq "$(GhcWithInterpreter)" "NO"
# runghc is just GHCi in disguise
BUILD_DIRS := $(filter-out utils/runghc,$(BUILD_DIRS))
endif
ifneq "$(INTEGER_LIBRARY)" "integer-gmp"
BUILD_DIRS := $(filter-out libraries/integer-gmp/gmp,$(BUILD_DIRS))
endif
ifneq "$(CrossCompiling) $(Stage1Only)" "NO NO"
# See Note [No stage2 packages when CrossCompiling or Stage1Only].
# See Note [Stage1Only vs stage=1] in mk/config.mk.in.
BUILD_DIRS := $(filter-out utils/check-api-annotations,$(BUILD_DIRS))
BUILD_DIRS := $(filter-out utils/check-ppr,$(BUILD_DIRS))
endif
endif # CLEANING

include $(patsubst %, %/ghc.mk, $(BUILD_DIRS))

# A useful pseudo-target (must be after the include above, because it needs
# the value of things like $(libraries/base_dist-install_v_LIB).
.PHONY: stage1_libs
stage1_libs : $(ALL_STAGE1_LIBS)

# We need this extra dependency when building our own libffi, because
# GHCi.FFI.hs #includes ffi.h
ifneq "$(UseSystemLibFFI)" "YES"
libraries/ghci/dist-install/build/GHCi/FFI.hs : $(libffi_HEADERS)
endif

# ----------------------------------------------
# Per-package compiler flags
#
# If you want to add per-package compiler flags, see `mk/warnings.mk`.

# Add $(GhcLib(Extra)HcOpts) to all package builds
$(foreach pkg,$(PACKAGES_STAGE1) $(PACKAGES_STAGE2),$(eval libraries/$(pkg)_dist-install_HC_OPTS += $$(GhcLibHcOpts)))
$(foreach pkg,$(PACKAGES_STAGE1) $(PACKAGES_STAGE2),$(eval libraries/$(pkg)_dist-install_EXTRA_HC_OPTS += $$(GhcLibExtraHcOpts)))

# Add $(GhcBootLib(Extra)HcOpts) to all stage0 package builds
$(foreach pkg,$(PACKAGES_STAGE0),$(eval libraries/$(pkg)_dist-boot_HC_OPTS += $$(GhcBootLibHcOpts)))
$(foreach pkg,$(PACKAGES_STAGE0),$(eval libraries/$(pkg)_dist-boot_EXTRA_HC_OPTS += $$(GhcBootLibExtraHcOpts)))

# -----------------------------------------------------------------------------
# Bootstrapping libraries

# We need to build a few libraries with the installed GHC, since GHC itself
# and some of the tools depend on them:

ifneq "$(BINDIST)" "YES"

ifneq "$(BOOTSTRAPPING_CONF)" ""
ifeq "$(wildcard $(BOOTSTRAPPING_CONF))" ""
$(shell "$(GHC_PKG)" init $(BOOTSTRAPPING_CONF))
endif
endif

$(eval $(call clean-target,root,bootstrapping_conf,$(BOOTSTRAPPING_CONF)))

# register the boot packages in strict sequence, because running
# multiple ghc-pkgs in parallel doesn't work (registrations may get
# lost).
fixed_pkg_prev=
$(foreach pkg,$(PACKAGES_STAGE0),$(eval $(call fixed_pkg_dep,$(pkg),dist-boot)))
# ghc-pkg, unlike other utils that we build with the stage0 compiler (TODO: is
# this really true?), depends on several boot packages (e.g. Cabal and
# ghc-boot). They need to be configured before ghc-pkg, so we add a
# dependency between their package-data.mk files. See also Note
# [Dependencies between package-data.mk files].
utils/ghc-pkg/dist/package-data.mk: $(fixed_pkg_prev)
compiler/stage1/package-data.mk:    $(fixed_pkg_prev)
endif

ifneq "$(BINDIST)" "YES"
# Make sure we have all the GHCi libs by the time we've built
# ghc-stage2.
#
GHCI_LIBS = \
    $(foreach way,$(GhcLibWays),\
        $(foreach lib,$(PACKAGES_STAGE1),\
            $(libraries/$(lib)_dist-install_$(way)_GHCI_LIB)) \
        $(compiler_stage2_$(way)_GHCI_LIB))

ifeq "$(UseArchivesForGhci)" "NO"
ghc/stage2/build/tmp/$(ghc_stage2_PROG) : $(GHCI_LIBS)
endif

ifeq "$(UseArchivesForGhci)" "YES"
GHCI_lib_way = v
else
GHCI_lib_way = GHCI
endif

# Deps for TH uses in libraries
$(foreach way, $(GhcLibWays),$(eval \
libraries/vector/dist-install/build/Data/Vector/Fusion/Stream/Monadic.$($(way)_osuf): \
    $(libraries/primitive_dist-install_$(GHCI_lib_way)_LIB) \
  ))
endif

# -----------------------------------------------
# Haddock-related bits

# Build the Haddock contents and index
ifeq "$(HADDOCK_DOCS)" "YES"
libraries/dist-haddock/index.html: $(haddock_INPLACE) $(ALL_HADDOCK_FILES)
	cd libraries && sh gen_contents_index --intree
ifeq "$(phase)" "final"
$(eval $(call all-target,library_doc_index,libraries/dist-haddock/index.html))
endif
INSTALL_LIBRARY_DOCS += libraries/dist-haddock/*
endif

# -----------------------------------------------------------------------------
# Creating a local mingw copy on Windows

ifeq "$(Windows_Host)" "YES"

install : install_mingw
.PHONY: install_mingw
install_mingw : $(INPLACE_MINGW)
	"$(CP)" -Rp $(INPLACE_MINGW) $(prefix)

endif # Windows_Host

ifneq "$(BINDIST)" "YES"
$(ghc-prim-$(libraries/ghc-prim_dist-install_VERSION)_HADDOCK_FILE): \
    libraries/ghc-prim/dist-install/build/autogen/GHC/Prim.hs
endif # BINDIST

libraries/ghc-prim/dist-install/build/autogen/GHC/Prim.hs: \
                            $(PRIMOPS_TXT_STAGE1) $$(genprimopcode_INPLACE) \
                          | $$(dir $$@)/.
	"$(genprimopcode_INPLACE)" --make-haskell-source < $< > $@

# -----------------------------------------------------------------------------
# Installation

install: install_libs install_packages install_libexecs \
         install_bins install_libexec_scripts
ifeq "$(HADDOCK_DOCS)" "YES"
install: install_docs
endif

define installLibsTo
# $1 = libraries to install
# $2 = directory to install to
#
# The .dll case calls STRIP_CMD explicitly, instead of `install -s`, because
# on Win64, "install -s" calls a strip that doesn't understand 64bit binaries.
# For some reason, this means the DLLs end up non-executable, which means
# executables that use them just segfault.
	$(INSTALL_DIR) $2
	for i in $1; do \
		case $$i in \
		  *.a) \
		    $(INSTALL_DATA) $(INSTALL_OPTS) $$i $2; \
		    $(RANLIB_CMD) $2/`basename $$i` ;; \
		  *.dll) \
		    $(INSTALL_PROGRAM) $(INSTALL_OPTS) $$i $2 ; \
		    $(STRIP_CMD) $2/`basename $$i` ;; \
		  *.so) \
		    $(INSTALL_SHLIB) $(INSTALL_OPTS) $$i $2 ;; \
		  *.dylib) \
		    $(INSTALL_SHLIB) $(INSTALL_OPTS) $$i $2;; \
		  *) \
		    $(INSTALL_DATA) $(INSTALL_OPTS) $$i $2; \
		esac; \
	done
endef

install_bins: $(INSTALL_BINS) $(INSTALL_SCRIPTS)
	$(INSTALL_DIR) "$(DESTDIR)$(bindir)"
ifneq "$(INSTALL_BINS)" ""
	for i in $(INSTALL_BINS); do \
		$(INSTALL_PROGRAM) $(INSTALL_BIN_OPTS) $$i "$(DESTDIR)$(bindir)" ;  \
	done
endif
ifneq "$(INSTALL_SCRIPTS)" ""
	for i in $(INSTALL_SCRIPTS); do \
		$(INSTALL_SCRIPT) $(INSTALL_OPTS) $$i "$(DESTDIR)$(bindir)" ;  \
	done
endif

install_libs: $(INSTALL_LIBS)
	$(call installLibsTo, $(INSTALL_LIBS), "$(DESTDIR)$(ghclibdir)")

# We rename ghc-stage2, so that the right program name is used in error
# messages etc. But not on windows.
RENAME_LIBEXEC_GHC_STAGE_TO_GHC = YES
ifeq "$(Stage1Only) $(Windows_Host)" "YES YES"
# resulting ghc-stage1 is built to run on windows
RENAME_LIBEXEC_GHC_STAGE_TO_GHC = NO
endif
ifeq "$(Stage1Only) $(Windows_Target)" "NO YES"
# resulting ghc-stage1 is built to run on windows
RENAME_LIBEXEC_GHC_STAGE_TO_GHC = NO
endif

install_libexecs:  $(INSTALL_LIBEXECS)
ifneq "$(INSTALL_LIBEXECS)" ""
	$(INSTALL_DIR) "$(DESTDIR)$(ghclibexecdir)/bin"
	for i in $(INSTALL_LIBEXECS); do \
		$(INSTALL_PROGRAM) $(INSTALL_BIN_OPTS) $$i "$(DESTDIR)$(ghclibexecdir)/bin"; \
	done
ifeq "$(RENAME_LIBEXEC_GHC_STAGE_TO_GHC)" "YES"
	"$(MV)" "$(DESTDIR)$(ghclibexecdir)/bin/ghc-stage$(INSTALL_GHC_STAGE)" "$(DESTDIR)$(ghclibexecdir)/bin/ghc"
endif
endif

install_libexec_scripts: $(INSTALL_LIBEXEC_SCRIPTS)
ifneq "$(INSTALL_LIBEXEC_SCRIPTS)" ""
	$(INSTALL_DIR) "$(DESTDIR)$(ghclibexecdir)/bin"
	for i in $(INSTALL_LIBEXEC_SCRIPTS); do \
		$(INSTALL_SCRIPT) $(INSTALL_OPTS) $$i "$(DESTDIR)$(ghclibexecdir)/bin"; \
	done
endif

install_docs: $(INSTALL_DOCS)
	$(INSTALL_DIR) "$(DESTDIR)$(docdir)"
ifneq "$(INSTALL_DOCS)" ""
	for i in $(INSTALL_DOCS); do \
		$(INSTALL_DOC) $(INSTALL_OPTS) $$i "$(DESTDIR)$(docdir)"; \
	done
endif
	$(INSTALL_DIR) "$(DESTDIR)$(docdir)/html"
	$(INSTALL_DOC) $(INSTALL_OPTS) docs/index.html "$(DESTDIR)$(docdir)/html"
ifneq "$(INSTALL_LIBRARY_DOCS)" ""
	$(INSTALL_DIR) "$(DESTDIR)$(docdir)/html/libraries"
	for i in $(INSTALL_LIBRARY_DOCS); do \
		$(INSTALL_DOC) $(INSTALL_OPTS) $$i "$(DESTDIR)$(docdir)/html/libraries/"; \
	done
	$(INSTALL_DATA) $(INSTALL_OPTS) libraries/prologue.txt "$(DESTDIR)$(docdir)/html/libraries/"
	$(INSTALL_SCRIPT) $(INSTALL_OPTS) libraries/gen_contents_index "$(DESTDIR)$(docdir)/html/libraries/"
endif
ifneq "$(INSTALL_HTML_DOC_DIRS)" ""
	for i in $(INSTALL_HTML_DOC_DIRS); do \
		$(CP) -Rp $$i "$(DESTDIR)$(docdir)/html"; \
	done
endif

INSTALLED_PACKAGE_CONF=$(DESTDIR)$(topdir)/package.conf.d

ifeq "$(BINDIST) $(CrossCompiling)" "NO YES"
# when installing ghc-stage2 we can't run target's
# 'ghc-pkg' and 'ghc-stage2' but those are needed for registration.
INSTALLED_GHC_REAL=$(TOP)/inplace/bin/ghc-stage1
INSTALLED_GHC_PKG_REAL=$(TOP)/$(ghc-pkg_DIST_BINARY)
else # CrossCompiling
# Install packages in the right order, so that ghc-pkg doesn't complain.
# Also, install ghc-pkg first.
ifeq "$(Windows_Host)" "NO"
INSTALLED_GHC_REAL=$(DESTDIR)$(ghclibexecdir)/bin/ghc
INSTALLED_GHC_PKG_REAL=$(DESTDIR)$(ghclibexecdir)/bin/ghc-pkg
else
INSTALLED_GHC_REAL=$(DESTDIR)$(bindir)/ghc.exe
INSTALLED_GHC_PKG_REAL=$(DESTDIR)$(bindir)/ghc-pkg.exe
endif
endif # CrossCompiling

# Set the INSTALL_DISTDIR_p for each package; compiler is special
$(foreach p,$(filter-out compiler,$(INSTALL_PACKAGES)),\
   $(eval INSTALL_DISTDIR_$p = dist-install))
INSTALL_DISTDIR_compiler = stage2

# Now we can do the installation
install_packages: install_libexecs
install_packages: rts/dist/package.conf.install
	$(INSTALL_DIR) "$(DESTDIR)$(topdir)"
	$(call removeTrees,"$(INSTALLED_PACKAGE_CONF)")
	$(INSTALL_DIR) "$(INSTALLED_PACKAGE_CONF)"
	$(INSTALL_DIR) "$(DESTDIR)$(topdir)/rts"
	$(call installLibsTo, $(RTS_INSTALL_LIBS), "$(DESTDIR)$(topdir)/rts")
	$(foreach p, $(INSTALL_PACKAGES),                             \
	    $(call make-command,                                      \
	           "$(ghc-cabal_INPLACE)" copy                        \
	                                  $p $(INSTALL_DISTDIR_$p)    \
	                                  "$(STRIP_CMD)"              \
	                                  '$(DESTDIR)'                \
	                                  '$(prefix)'                 \
	                                  '$(ghclibdir)'              \
	                                  '$(docdir)/html/libraries'  \
	                                  '$(GhcLibWays)'))
	"$(INSTALLED_GHC_PKG_REAL)" --force --global-package-db "$(INSTALLED_PACKAGE_CONF)" update rts/dist/package.conf.install
	$(foreach p, $(INSTALL_PACKAGES),                             \
	    $(call make-command,                                      \
	           "$(ghc-cabal_INPLACE)" register                    \
	                                  $p $(INSTALL_DISTDIR_$p)    \
	                                  "$(INSTALLED_GHC_REAL)"     \
	                                  "$(INSTALLED_GHC_PKG_REAL)" \
	                                  "$(DESTDIR)$(topdir)"       \
	                                  '$(DESTDIR)'                \
	                                  '$(prefix)'                 \
	                                  '$(ghclibdir)'              \
	                                  '$(docdir)/html/libraries'  \
	                                  $(RelocatableBuild)))
# when we install the packages above, ghc-pkg obeys umask when creating
# the package.conf files, but for everything else we specify the
# permissions. We therefore now fix the permissions of package.cache.
# This means "sudo make install" does the right thing even if it runs
# with an 077 umask.
	for f in '$(INSTALLED_PACKAGE_CONF)'/*; do $(CREATE_DATA) "$$f"; done

# Finally, update package.cache to ensure it's newer than the registration
# files. This avoids #13375.
	"$(INSTALLED_GHC_PKG_REAL)" --global-package-db "$(INSTALLED_PACKAGE_CONF)" recache

# -----------------------------------------------------------------------------
# Binary distributions

ifneq "$(CLEANING)" "YES"
# This rule seems to hold some files open on Windows which prevents
# cleaning, perhaps due to the $(wildcard).

$(eval $(call bindist-list,.,\
    LICENSE \
    README \
    INSTALL \
    configure config.sub config.guess install-sh \
    llvm-targets \
    llvm-passes \
    packages \
    Makefile \
    mk/config.mk.in \
    $(INPLACE_BIN)/mkdirhier \
    utils/ghc-cabal/dist-install/build/tmp/ghc-cabal \
    $(BINDIST_WRAPPERS) \
    $(BINDIST_LIBS) \
    $(BINDIST_HI) \
    $(BINDIST_EXTRAS) \
    includes/Makefile \
    $(includes_H_FILES) \
    $(includes_DERIVEDCONSTANTS) \
    $(includes_GHCCONSTANTS) \
    $(libffi_HEADERS) \
    $(INSTALL_LIBEXECS) \
    $(INSTALL_LIBEXEC_SCRIPTS) \
    $(INSTALL_BINS) \
    $(INSTALL_SCRIPTS) \
    $(INSTALL_MANPAGES) \
    $(INSTALL_DOCS) \
    $(INSTALL_LIBRARY_DOCS) \
    $(addsuffix /*,$(INSTALL_HTML_DOC_DIRS)) \
    docs/index.html \
    $(wildcard compiler/stage2/doc) \
    $(wildcard libraries/*/dist-install/doc/) \
    $(wildcard libraries/*/*/dist-install/doc/) \
    $(filter-out llvm-targets llvm-passes,$(INSTALL_LIBS)) \
    $(RTS_INSTALL_LIBS) \
    $(filter-out %/project.mk mk/config.mk %/mk/install.mk,$(MAKEFILE_LIST)) \
    mk/project.mk \
    mk/install.mk.in \
    bindist.mk \
    libraries/gen_contents_index \
    libraries/prologue.txt \
 ))
endif
# mk/project.mk gets an absolute path, so we manually include it in
# the bindist with a relative path

BIN_DIST_MK = $(BIN_DIST_PREP_DIR)/bindist.mk

# Note [Persist CrossCompiling in binary distributions]
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#
# The build system uses the CrossCompiling variable to decide whether or not we
# should build various packages that must be built using the compiler.
# Consequently, it is important that we persist its value in the binary
# distribution so we know during `make install` not to go looking for files that
# would have been built for these packages. Failing to do this causes #13325.
#
# See Note [No stage2 packages when CrossCompiling or Stage1Only].

unix-binary-dist-prep:
	$(call removeTrees,bindistprep/)
	"$(MKDIRHIER)" $(BIN_DIST_PREP_DIR)
	set -e; for i in packages LICENSE compiler ghc rts libraries utils docs libffi includes driver mk rules Makefile aclocal.m4 config.sub config.guess install-sh llvm-targets llvm-passes ghc.mk inplace distrib/configure.ac distrib/README distrib/INSTALL; do ln -s ../../$$i $(BIN_DIST_PREP_DIR)/; done
	echo "HADDOCK_DOCS       = $(HADDOCK_DOCS)"       >> $(BIN_DIST_MK)
	echo "BUILD_SPHINX_HTML  = $(BUILD_SPHINX_HTML)"  >> $(BIN_DIST_MK)
	echo "BUILD_SPHINX_PDF   = $(BUILD_SPHINX_PDF)"   >> $(BIN_DIST_MK)
	echo "BUILD_MAN          = $(BUILD_MAN)"          >> $(BIN_DIST_MK)
	echo "override ghc-cabal_INPLACE = utils/ghc-cabal/dist-install/build/tmp/ghc-cabal-bindist" >> $(BIN_DIST_MK)
	echo "UseSystemLibFFI    = $(UseSystemLibFFI)"    >> $(BIN_DIST_MK)
# See Note [Persist CrossCompiling in binary distributions]
	echo "CrossCompiling     = $(CrossCompiling)"     >> $(BIN_DIST_MK)
	cd $(BIN_DIST_PREP_DIR) && autoreconf
	$(call removeFiles,$(BIN_DIST_PREP_TAR))
# h means "follow symlinks", e.g. if aclocal.m4 is a symlink to a source
# tree then we want to include the real file, not a symlink to it
	sort bindist-list | uniq > bindist-list.uniq
	cd bindistprep && "$(TAR_CMD)" hcf - -T ../bindist-list.uniq | $(TAR_COMP_CMD) -c > ../$(BIN_DIST_PREP_TAR_COMP)

windows-binary-dist-prep:
	$(call removeTrees,bindistprep/)
	$(MAKE) prefix=$(TOP)/$(BIN_DIST_PREP_DIR) install
	cd bindistprep && "$(TAR_CMD)" cf - $(BIN_DIST_NAME) | $(TAR_COMP_CMD) -c > ../$(BIN_DIST_PREP_TAR_COMP)

# tryTimes tries to run its third argument multiple times, until it
# succeeds. Don't call it directly; call try10Times instead.
# The first and second argument to tryTimes are lists of values.
# The length of the first argument is the number of times we have
# already tried. The length of the second argument is the number more
# times we will try.
tryTimes = $(if $2, \
                { echo 'Try $(words x $1): $3' ; $3 ; } || \
                $(call tryTimes,x $1,$(wordlist 2,$(words $2),$2),$3), \
                )

# Try to run the argument 10 times. If all 10 fail, fail.
try10Times = $(call tryTimes,,x x x x x x x x x x,$1) { echo Failed; false; }

.PHONY: publish-binary-dist
publish-binary-dist:
	$(call try10Times,$(PublishCp) $(BIN_DIST_TAR_COMP) $(PublishLocation)/dist)

ifeq "$(mingw32_TARGET_OS)" "1"
DOCDIR_TO_PUBLISH = $(BIN_DIST_INST_DIR)/doc
else
DOCDIR_TO_PUBLISH = $(BIN_DIST_INST_DIR)/share/doc/ghc
endif

.PHONY: publish-docs
publish-docs:
	$(call try10Times,$(PublishCp) -r $(DOCDIR_TO_PUBLISH)/* $(PublishLocation)/docs)

# -----------------------------------------------------------------------------
# Source distributions

# Do it like this:
#
#	$ ./boot
#	$ ./configure
#	$ make sdist
#

# A source dist is built from a (partial) build tree, because we
# require some extra files not contained in a git checkout: the
# output from Happy and Alex, for example.
#
# The steps performed by 'make sdist' are as follows:
#   - build those extra files
#   - create a complete link-tree of the current build tree in /tmp
#   - run 'make distclean' on that tree
#   - remove a bunch of other files that we know shouldn't be in the dist

#
# Directory in which we're going to build the src dist
#
SRC_DIST_ROOT      = sdistprep
SRC_DIST_BASE_NAME = ghc-$(ProjectVersion)

SRC_DIST_GHC_NAME                 = ghc-$(ProjectVersion)-src
SRC_DIST_GHC_ROOT                 = $(SRC_DIST_ROOT)/ghc
SRC_DIST_GHC_DIR                  = $(SRC_DIST_GHC_ROOT)/$(SRC_DIST_BASE_NAME)
SRC_DIST_GHC_TARBALL              = $(SRC_DIST_ROOT)/$(SRC_DIST_GHC_NAME).tar.$(TAR_COMP_EXT)

SRC_DIST_WINDOWS_TARBALLS_NAME    = ghc-$(ProjectVersion)-windows-extra-src
SRC_DIST_WINDOWS_TARBALLS_ROOT    = $(SRC_DIST_ROOT)/windows-tarballs
SRC_DIST_WINDOWS_TARBALLS_DIR     = $(SRC_DIST_WINDOWS_TARBALLS_ROOT)/$(SRC_DIST_BASE_NAME)
SRC_DIST_WINDOWS_TARBALLS_TARBALL = $(SRC_DIST_ROOT)/$(SRC_DIST_WINDOWS_TARBALLS_NAME).tar.$(TAR_COMP_EXT)

SRC_DIST_TESTSUITE_NAME           = ghc-$(ProjectVersion)-testsuite
SRC_DIST_TESTSUITE_ROOT           = $(SRC_DIST_ROOT)/testsuite-ghc
SRC_DIST_TESTSUITE_DIR            = $(SRC_DIST_TESTSUITE_ROOT)/$(SRC_DIST_BASE_NAME)
SRC_DIST_TESTSUITE_TARBALL        = $(SRC_DIST_ROOT)/$(SRC_DIST_TESTSUITE_NAME).tar.$(TAR_COMP_EXT)

#
# Files to include in source distributions
#
SRC_DIST_GHC_DIRS = mk rules docs distrib bindisttest libffi includes \
    utils docs rts compiler ghc driver libraries libffi-tarballs
SRC_DIST_GHC_FILES += \
    configure.ac config.guess config.sub configure \
    aclocal.m4 README.md ANNOUNCE HACKING.md INSTALL.md LICENSE Makefile \
    install-sh llvm-targets llvm-passes VERSION GIT_COMMIT_ID \
    boot packages ghc.mk MAKEHELP.md

.PHONY: VERSION
VERSION:
	@if test -f $@ && test "`cat $@`" = "$(ProjectVersion)"; \
	then echo "$@ needs no update"; \
	else echo "update $@ ($(ProjectVersion))"; echo "$(ProjectVersion)" > $@; fi

.PHONY: GIT_COMMIT_ID
GIT_COMMIT_ID:
	@if test -d .git && test "`git rev-parse HEAD`" != "$(ProjectGitCommitId)"; then \
	   echo "******************************************************************************"; \
	   echo "Stale ProjectGitCommitId (=$(ProjectGitCommitId)) detected!"; \
           echo "'git rev-parse HEAD' says: `git rev-parse HEAD`"; \
	   echo "Please re-run './configure' before creating source-distribution"; \
	   echo "******************************************************************************"; \
	   exit 1; \
	fi
	@if test -f $@ && test "`cat $@`" = "$(ProjectGitCommitId)"; \
	then echo "$@ needs no update"; \
	else echo "update $@ ($(ProjectGitCommitId))"; echo -n "$(ProjectGitCommitId)" > $@; fi

sdist-ghc-prep-tree : VERSION GIT_COMMIT_ID

.PHONY: sdist-ghc-prep-tree
sdist-ghc-prep-tree :
	$(call removeTrees,$(SRC_DIST_GHC_ROOT))
	$(call removeFiles,$(SRC_DIST_GHC_TARBALL))
	mkdir -p $(SRC_DIST_ROOT)
	mkdir -p $(SRC_DIST_GHC_ROOT)
	mkdir -p $(SRC_DIST_GHC_DIR)
	cd $(SRC_DIST_GHC_DIR) && for i in $(SRC_DIST_GHC_DIRS); do mkdir -p $$i; ( cd $$i && lndir $(TOP)/$$i ); done
	cd $(SRC_DIST_GHC_DIR) && for i in $(SRC_DIST_GHC_FILES); do $(LN_S) $(TOP)/$$i .; done
	cd $(SRC_DIST_GHC_DIR) && $(MAKE) distclean
	$(call removeTrees,$(SRC_DIST_GHC_DIR)/libraries/tarballs/)
	$(call removeTrees,$(SRC_DIST_GHC_DIR)/libraries/stamp/)
	$(call removeTrees,$(SRC_DIST_GHC_DIR)/compiler/stage[123])
	$(call removeFiles,$(SRC_DIST_GHC_DIR)/mk/build.mk)
	cd $(SRC_DIST_GHC_DIR) && "$(FIND)" $(SRC_DIST_GHC_DIRS) \( -name .git -o -name "autom4te*" -o -name "*~" -o -name "\#*" -o -name ".\#*" -o -name "log" -o -name "*-SAVE" -o -name "*.orig" -o -name "*.rej" \) -print | "$(XARGS)" $(XARGS_OPTS) "$(RM)" $(RM_OPTS_REC)

# Add files generated by alex and happy.
# These rules depend on sdist-ghc-prep-tree.
$(eval $(call sdist-ghc-file,compiler,stage2,cmm,CmmLex,x))
$(eval $(call sdist-ghc-file,compiler,stage2,cmm,CmmParse,y))
$(eval $(call sdist-ghc-file,compiler,stage2,parser,Lexer,x))
$(eval $(call sdist-ghc-file,compiler,stage2,parser,Parser,y))
$(eval $(call sdist-ghc-file,utils/hpc,dist-install,,HpcParser,y))
$(eval $(call sdist-ghc-file,utils/genprimopcode,dist,,Lexer,x))
$(eval $(call sdist-ghc-file,utils/genprimopcode,dist,,Parser,y))

# Recent Cabal library versions have a pre-generated Lexer.hs in the source
# repo, and have moved Lexer.x out of the way, so trying to generate it from
# here no longer works, and is no longer necessary.
# According to https://github.com/haskell/cabal/issues/4633 however, this is
# only a temporary solution, so we will probably have to adjust to whatever
# the proper solution is going to be once there is one.
#
# $(eval $(call sdist-ghc-file2,libraries/Cabal/Cabal,dist-install,Distribution/Parsec,Lexer,x))

.PHONY: sdist-ghc-prep
sdist-ghc-prep : sdist-ghc-prep-tree

.PHONY: sdist-windows-tarballs-prep
sdist-windows-tarballs-prep :
	$(call removeTrees,$(SRC_DIST_WINDOWS_TARBALLS_ROOT))
	$(call removeFiles,$(SRC_DIST_WINDOWS_TARBALLS_TARBALL))
	mkdir -p $(SRC_DIST_ROOT)
	mkdir -p $(SRC_DIST_WINDOWS_TARBALLS_ROOT)
	mkdir -p $(SRC_DIST_WINDOWS_TARBALLS_DIR)
	mkdir -p $(SRC_DIST_WINDOWS_TARBALLS_DIR)/ghc-tarballs
	cd $(SRC_DIST_WINDOWS_TARBALLS_DIR)/ghc-tarballs && lndir $(TOP)/ghc-tarballs
	$(call removeTrees,$(SRC_DIST_WINDOWS_TARBALLS_DIR)/ghc-tarballs/.git)

.PHONY: sdist-testsuite-prep
sdist-testsuite-prep :
	$(call removeTrees,$(SRC_DIST_TESTSUITE_ROOT))
	$(call removeFiles,$(SRC_DIST_TESTSUITE_TARBALL))
	mkdir -p $(SRC_DIST_ROOT)
	mkdir -p $(SRC_DIST_TESTSUITE_ROOT)
	mkdir -p $(SRC_DIST_TESTSUITE_DIR)
	mkdir -p $(SRC_DIST_TESTSUITE_DIR)/testsuite
	cd $(SRC_DIST_TESTSUITE_DIR)/testsuite && lndir $(TOP)/testsuite
	cd $(SRC_DIST_TESTSUITE_DIR)/testsuite && $(MAKE) distclean

.PHONY: sdist-ghc
sdist-ghc: sdist-ghc-prep
	cd $(SRC_DIST_GHC_ROOT)              && "$(TAR_CMD)" chf - $(SRC_DIST_BASE_NAME) 2> src_ghc_log               | $(TAR_COMP_CMD) -c > $(TOP)/$(SRC_DIST_GHC_TARBALL)

.PHONY: sdist-windows-tarballs
sdist-windows-tarballs: sdist-windows-tarballs-prep
	cd $(SRC_DIST_WINDOWS_TARBALLS_ROOT) && "$(TAR_CMD)" chf - $(SRC_DIST_BASE_NAME) 2> windows_extra_src_ghc_log | $(TAR_COMP_CMD) -c > $(TOP)/$(SRC_DIST_WINDOWS_TARBALLS_TARBALL)

.PHONY: sdist-testsuite
sdist-testsuite: sdist-testsuite-prep
	cd $(SRC_DIST_TESTSUITE_ROOT)        && "$(TAR_CMD)" chf - $(SRC_DIST_BASE_NAME) 2> testsuite_log             | $(TAR_COMP_CMD) -c > $(TOP)/$(SRC_DIST_TESTSUITE_TARBALL)


.PHONY: sdist
sdist : sdist-ghc sdist-windows-tarballs sdist-testsuite

sdist-manifest : $(SRC_DIST_GHC_TARBALL)
	tar tjf $(SRC_DIST_GHC_TARBALL) | sed "s|^ghc-$(ProjectVersion)/||" | sort >sdist-manifest

# Upload the distribution(s)
# Retrying is to work around buggy firewalls that corrupt large file transfers
# over SSH.
ifneq "$(PublishLocation)" ""
publish-sdist :
	$(call try10Times,$(PublishCp) $(SRC_DIST_GHC_TARBALL) $(PublishLocation)/dist)
	$(call try10Times,$(PublishCp) $(SRC_DIST_TESTSUITE_TARBALL) $(PublishLocation)/dist)
endif

# -----------------------------------------------------------------------------
# sdisting libraries

# Use manually, with e.g.:
#     make sdist_directory

sdist_%:
	inplace/bin/ghc-cabal sdist libraries/$* dist-install

# -----------------------------------------------------------------------------
# Cleaning

.PHONY: clean

CLEAN_FILES += libraries/integer-gmp/include/HsIntegerGmp.h
CLEAN_FILES += libraries/base/include/EventConfig.h
CLEAN_FILES += mk/config.mk.old
CLEAN_FILES += mk/project.mk.old
CLEAN_FILES += compiler/ghc.cabal.old

# These are no longer generated, but we still clean them for a while
# as they may still be in old GHC trees:
CLEAN_FILES += includes/GHCConstants.h
CLEAN_FILES += includes/DerivedConstants.h
CLEAN_FILES += includes/ghcautoconf.h
CLEAN_FILES += includes/ghcplatform.h
CLEAN_FILES += includes/ghcversion.h
CLEAN_FILES += $(includes_SETTINGS)
CLEAN_FILES += utils/ghc-pkg/Version.hs
CLEAN_FILES += compiler/prelude/primops.txt
CLEAN_FILES += $(wildcard compiler/primop*incl)

clean : clean_files clean_libraries

.PHONY: clean_files
clean_files :
	$(call removeFiles,$(CLEAN_FILES))
# this is here since CLEAN_FILES can't handle folders
	$(call removeTrees,includes/dist-derivedconstants)
	$(call removeTrees,inplace/bin)
	$(call removeTrees,inplace/lib)
	$(call removeTrees,libraries/bootstrapping.conf)
# Clean the files that ./validate creates.
	$(call removeFiles,mk/are-validating.mk)

.PHONY: clean_libraries
clean_libraries: $(patsubst %,clean_libraries/%_dist-install,$(PACKAGES_STAGE1) $(PACKAGES_STAGE2))
clean_libraries: $(patsubst %,clean_libraries/%_dist-boot,$(PACKAGES_STAGE0))

clean_libraries:
	$(call removeTrees,$(patsubst %, libraries/%/dist, $(PACKAGES_STAGE1) $(PACKAGES_STAGE2)))
	$(call removeFiles,$(wildcard $(patsubst %.in, %, $(wildcard $(patsubst %, libraries/%/*.buildinfo.in, $(PACKAGES_STAGE1) $(PACKAGES_STAGE2))))))
	$(call removeFiles,$(patsubst %, libraries/%/config.log, $(PACKAGES_STAGE1) $(PACKAGES_STAGE2)))
	$(call removeFiles,$(patsubst %, libraries/%/config.status, $(PACKAGES_STAGE1) $(PACKAGES_STAGE2)))
	$(call removeFiles,$(wildcard $(patsubst %, libraries/%/include/Hs*Config.h, $(PACKAGES_STAGE1) $(PACKAGES_STAGE2))))

# We have to define a clean target for each library manually, because the
# libraries/*/ghc.mk files are not included when we're cleaning.
ifeq "$(CLEANING)" "YES"
$(foreach lib,$(PACKAGES_STAGE0),\
  $(eval $(call clean-target,libraries/$(lib),dist-boot,libraries/$(lib)/dist-boot)))
$(foreach lib,$(PACKAGES_STAGE1) $(PACKAGES_STAGE2),\
  $(eval $(call clean-target,libraries/$(lib),dist-install,libraries/$(lib)/dist-install)))
endif

clean : clean_haddock_index
.PHONY: clean_haddock_index
clean_haddock_index:
	$(call removeTrees,libraries/dist-haddock)

clean : clean_bindistprep
.PHONY: clean_bindistprep
clean_bindistprep:
	$(call removeTrees,bindistprep/)

distclean : clean
# Clean the files that we ask ./configure to create.
	$(call removeFiles,mk/config.mk)
	$(call removeFiles,mk/install.mk)
	$(call removeFiles,mk/project.mk)
	$(call removeFiles,compiler/ghc.cabal)
	$(call removeFiles,ghc/ghc-bin.cabal)
	$(call removeFiles,libraries/ghci/ghci.cabal)
	$(call removeFiles,utils/runghc/runghc.cabal)
	$(call removeFiles,utils/gen-dll/gen-dll.cabal)
	$(call removeFiles,settings)
	$(call removeFiles,docs/users_guide/ug-book.xml)
	$(call removeFiles,docs/users_guide/ug-ent.xml)
	$(call removeFiles,docs/users_guide/ghc_config.py)
	$(call removeFiles,docs/index.html)
	$(call removeFiles,libraries/prologue.txt)
	$(call removeFiles,distrib/configure.ac)
	$(call removeFiles,ch01.html ch02.html index.html)

# ./configure also makes these.
	$(call removeFiles,mk/config.h)

# Internal files generated by ./configure for itself.
	$(call removeFiles,config.cache config.status config.log)

# The root Makefile makes .old versions of some files that configure
# generates, so we clean those too.
	$(call removeFiles,mk/config.mk.old)
	$(call removeFiles,mk/project.mk.old)
	$(call removeFiles,compiler/ghc.cabal.old)

# Clean the *Config.h files generated by library configure scripts
	$(call removeFiles,libraries/base/include/HsBaseConfig.h)
	$(call removeFiles,libraries/base/include/EventConfig.h)
	$(call removeFiles,libraries/directory/include/HsDirectoryConfig.h)
	$(call removeFiles,libraries/process/include/HsProcessConfig.h)
	$(call removeFiles,libraries/unix/include/HsUnixConfig.h)
	$(call removeFiles,libraries/time/lib/include/HsTimeConfig.h)

# The library configure scripts also like creating autom4te.cache
# directories, so clean them all up.
	$(call removeTrees,$(patsubst %, libraries/%/autom4te.cache, $(PACKAGES_STAGE1) $(PACKAGES_STAGE2)))

# We make these when making or testing bindists
	$(call removeFiles,bindist-list)
	$(call removeFiles,bindist-list.uniq)
	$(call removeTrees,bindisttest/a)

# Not sure why this is being cleaned here.
	$(call removeTrees,includes/dist-derivedconstants)

# Also clean Windows-only inplace directories.
# Don't delete 'inplace' itself, it contains source files.
	$(call removeTrees,inplace/mingw)

# Remove the fs utilities.
	$(call removeFiles,utils/lndir/fs.h)
	$(call removeFiles,utils/lndir/fs.c)
	$(call removeFiles,utils/unlit/fs.h)
	$(call removeFiles,utils/unlit/fs.c)
	$(call removeFiles,rts/fs.h)
	$(call removeFiles,rts/fs.c)
	$(call removeFiles,libraries/base/include/fs.h)
	$(call removeFiles,libraries/base/cbits/fs.c)

CLEAN_LIBRARY_GHC_MK_FILES += $(patsubst %, libraries/%/ghc.mk, $(PACKAGES_STAGE1) $(PACKAGES_STAGE2))
# Don't clean `libraries/ghc-boot/ghc.mk`, since it's intended to be version-controlled (#16953)
CLEAN_LIBRARY_GHC_MK_FILES := $(filter-out libraries/ghc-boot/ghc.mk,$(CLEAN_LIBRARY_GHC_MK_FILES))

maintainer-clean : distclean
	$(call removeFiles,configure mk/config.h.in)
	$(call removeTrees,autom4te.cache $(wildcard libraries/*/autom4te.cache))
	$(call removeFiles,$(patsubst %, libraries/%/GNUmakefile, \
	        $(PACKAGES_STAGE1) $(PACKAGES_STAGE2)))
	$(call removeFiles,$(CLEAN_LIBRARY_GHC_MK_FILES))
	$(call removeFiles,$(patsubst %, libraries/%/configure, \
	        $(PACKAGES_STAGE1) $(PACKAGES_STAGE2)))
	$(call removeFiles,libraries/base/include/HsBaseConfig.h.in)
	$(call removeFiles,libraries/directory/include/HsDirectoryConfig.h.in)
	$(call removeFiles,libraries/process/include/HsProcessConfig.h.in)
	$(call removeFiles,libraries/unix/include/HsUnixConfig.h.in)
	$(call removeFiles,libraries/time/lib/include/HsTimeConfig.h.in)

.PHONY: all_libraries

.PHONY: bootstrapping-files
# See https://gitlab.haskell.org/ghc/ghc/wikis/building/porting
bootstrapping-files: $(includes_H_CONFIG)
bootstrapping-files: $(includes_DERIVEDCONSTANTS)
bootstrapping-files: $(includes_GHCCONSTANTS)
bootstrapping-files: $(libffi_HEADERS)

.DELETE_ON_ERROR:

# -----------------------------------------------------------------------------

ifeq "$(HADDOCK_DOCS)" "YES"
BINDIST_HADDOCK_FLAG = --with-haddock="$(BINDIST_PREFIX)/bin/haddock"
endif
ifeq "$(DYNAMIC_GHC_PROGRAMS)" "YES"
BINDIST_LIBRARY_FLAGS = --enable-shared --disable-library-vanilla
else
BINDIST_LIBRARY_FLAGS = --enable-library-vanilla --disable-shared
endif
BINDIST_LIBRARY_FLAGS += --disable-library-prof

.PHONY: validate_build_xhtml
validate_build_xhtml:
	cd libraries/xhtml && "$(BINDIST_PREFIX)/bin/ghc" --make Setup
	cd libraries/xhtml && ./Setup configure --with-ghc="$(BINDIST_PREFIX)/bin/ghc" $(BINDIST_HADDOCK_FLAG) $(BINDIST_LIBRARY_FLAGS) --global --builddir=dist-bindist --prefix="$(BINDIST_PREFIX)"
	cd libraries/xhtml && ./Setup build   --builddir=dist-bindist
ifeq "$(HADDOCK_DOCS)" "YES"
	cd libraries/xhtml && ./Setup haddock -v0 --ghc-options=-optP-P --builddir=dist-bindist
endif
	cd libraries/xhtml && ./Setup install --builddir=dist-bindist
	cd libraries/xhtml && ./Setup clean   --builddir=dist-bindist
	cd libraries/xhtml && rm -f Setup Setup.exe Setup.hi Setup.o

# Note [No stage2 packages when CrossCompiling or Stage1Only]
#
# (first read Note [CrossCompiling vs Stage1Only] and
#  Note [Stage1Only vs stage=1] in mk/config.mk.in)
#
# When either CrossCompiling=YES or Stage1Only=YES, we have to exclude the
# following packages from the build:
#   * packages that we build with ghc-stage2 [1]
#   * packages that depend on the ghc library [2]
#
# Here's why:
#  - first of all, ghc-stage1 can't use stage0's ghc library (it's too old)
#  - neither do we register the ghc library (compiler/stage1) that we build
#    with stage0. TODO Why not? We do build it...
#  - as a result, we need to a) use ghc-stage2 to build packages that depend on
#    the ghc library and b) exclude those packages when ghc-stage2 is not
#    available.
#  - when Stage1Only=YES, it's clear that ghc-stage2 is not available (we just
#    said we didn't want it), so we have to exclude the stage2 packages from
#    the build. This includes the case where Stage1Only=YES is combined with
#    CrossCompiling=YES (Building GHC as a cross-compiler [3]).
#  - when CrossCompiling=YES, but Stage1Only=NO (Cross-compiling GHC itself
#    [3]), we can not use ghc-stage2 either. The reason is that stage2 doesn't
#    run on the host platform at all; it is built to run on $(TARGETPLATFORM)"
#    [4]. Therefore in this case we also have to exclude the stage2 packages
#    from the build.
#
# Because we omit certain packages from the build when CrossCompiling=YES,
# it is important that we remember the value of CrossCompiling in binary
# distributions that we produce. See Note [Persist CrossCompiling in binary
# distributions].
#
#  [1] find utils -name ghc.mk | xargs grep -l 'build-prog.*,2'
#
#  [2]
#  find utils -name package-data.mk | xargs grep -l 'DEP_NAMES =.* ghc\($\| \)'
#
#  [3] https://gitlab.haskell.org/ghc/ghc/wikis/building/cross-compiling
#
#  [4] * bc31dbe8ee22819054df60f5ef219fed393a1c54
#      "Disable any packages built with stage 2 when cross-compiling
#       Since we can't run stage 2 on the host."
#
#      * 72995160b0b190577b5c0cb8d7bd0426cc455b05
#      "We cannot use the stage 2 compiler, it runs on $(TARGETPLATFORM)"

# -----------------------------------------------------------------------------
# Numbered phase targets

# In phase 1, we'll be building dependency files for most things
# built by the bootstrapping compiler while make is 'include'ing
# makefiles. But in order to build dependency files, we'll need to
# build any automatically generated .hs files, which means that
# we'll need to be able to build any tools that generate .hs files
# etc. But in order to do that, we need to already know the
# dependencies for those tools, so we build their dependency files
# here.
.PHONY: phase_0_builds
# hsc2hs is needed, e.g. to make the .hs files for hpc.
phase_0_builds: $(utils/hsc2hs_dist_depfile_haskell)
phase_0_builds: $(utils/hsc2hs_dist_depfile_c_asm)
# genprimopcode is needed to make the .hs-incl files that are in the
# ghc package.
phase_0_builds: $(utils/genprimopcode_dist_depfile_haskell)
phase_0_builds: $(utils/genprimopcode_dist_depfile_c_asm)
# deriveConstants is used to create header files included in the
# ghc package.
phase_0_builds: $(utils/deriveConstants_dist_depfile_haskell)
phase_0_builds: $(utils/deriveConstants_dist_depfile_c_asm)

.PHONY: phase_1_builds
phase_1_builds: $(PACKAGE_DATA_MKS)