nixpkgs mirror (for testing)
github.com/NixOS/nixpkgs
nix
1# Haskell {#haskell}
2
3The Haskell infrastructure in Nixpkgs has two main purposes: The primary purpose
4is to provide a Haskell compiler and build tools as well as infrastructure for
5packaging Haskell-based packages.
6
7The secondary purpose is to provide support for Haskell development environments
8including prebuilt Haskell libraries. However, in this area sacrifices have been
9made due to self-imposed restrictions in Nixpkgs, to lessen the maintenance
10effort and to improve performance. (More details in the subsection
11[Limitations.](#haskell-limitations))
12
13## Available packages {#haskell-available-packages}
14
15The compiler and most build tools are exposed at the top level:
16
17* `ghc` is the default version of GHC
18* Language specific tools: `cabal-install`, `stack`, `hpack`, …
19
20Many “normal” user facing packages written in Haskell, like `niv` or `cachix`,
21are also exposed at the top level, and there is nothing Haskell specific to
22installing and using them.
23
24All of these packages are originally defined in the `haskellPackages` package set.
25The same packages are re-exposed with a reduced dependency closure for convenience (see `justStaticExecutables` or `separateBinOutput` below).
26
27:::{.note}
28See [](#chap-language-support) for techniques to explore package sets.
29:::
30
31The `haskellPackages` set includes at least one version of every package from [Hackage](https://hackage.haskell.org/) as well as some manually injected packages.
32
33The attribute names in `haskellPackages` always correspond with their name on
34Hackage. Since Hackage allows names that are not valid Nix without escaping,
35you need to take care when handling attribute names like `3dmodels`.
36
37For packages that are part of [Stackage] (a curated set of known to be
38compatible packages), we use the version prescribed by a Stackage snapshot
39(usually the current LTS one) as the default version. For all other packages we
40use the latest version from [Hackage](https://hackage.org) (the repository of
41basically all open source Haskell packages). See [below](#haskell-available-versions) for a few more details on this.
42
43Roughly half of the 16K packages contained in `haskellPackages` don’t actually
44build and are [marked as broken semi-automatically](https://github.com/NixOS/nixpkgs/blob/haskell-updates/pkgs/development/haskell-modules/configuration-hackage2nix/broken.yaml).
45Most of those packages are deprecated or unmaintained, but sometimes packages
46that should build, do not build. Very often fixing them is not a lot of work.
47
48<!--
49TODO(@sternenseemann):
50How you can help with that is
51described in [Fixing a broken package](#haskell-fixing-a-broken-package).
52-->
53
54`haskellPackages` is built with our default compiler, but we also provide other releases of GHC and package sets built with them.
55Available compilers are collected under `haskell.compiler`.
56
57Each of those compiler versions has a corresponding attribute set `packages` built with
58it. However, the non-standard package sets are not tested regularly and, as a
59result, contain fewer working packages. The corresponding package set for GHC
609.4.5 is `haskell.packages.ghc945`. In fact `haskellPackages` is just an alias
61for `haskell.packages.ghc964`:
62
63Every package set also re-exposes the GHC used to build its packages as `haskell.packages.*.ghc`.
64
65### Available package versions {#haskell-available-versions}
66
67We aim for a “blessed” package set which only contains one version of each
68package, like [Stackage], which is a curated set of known to be compatible
69packages. We use the version information from Stackage snapshots and extend it
70with more packages. Normally in Nixpkgs the number of building Haskell packages
71is roughly two to three times the size of Stackage. For choosing the version to
72use for a certain package we use the following rules:
73
741. By default, for `haskellPackages.foo` is the newest version of the package
75`foo` found on [Hackage](https://hackage.org), which is the central registry
76of all open source Haskell packages. Nixpkgs contains a reference to a pinned
77Hackage snapshot, thus we use the state of Hackage as of the last time we
78updated this pin.
792. If the [Stackage] snapshot that we use (usually the newest LTS snapshot)
80contains a package, [we use instead the version in the Stackage snapshot as
81default version for that package.](https://github.com/NixOS/nixpkgs/blob/haskell-updates/pkgs/development/haskell-modules/configuration-hackage2nix/stackage.yaml)
823. For some packages, which are not on Stackage, we have if necessary [manual
83overrides to set the default version to a version older than the newest on
84Hackage.](https://github.com/NixOS/nixpkgs/blob/haskell-updates/pkgs/development/haskell-modules/configuration-hackage2nix/main.yaml)
854. For all packages, for which the newest Hackage version is not the default
86version, there will also be a `haskellPackages.foo_x_y_z` package with the
87newest version. The `x_y_z` part encodes the version with dots replaced by
88underscores. When the newest version changes by a new release to Hackage the
89old package will disappear under that name and be replaced by a newer one under
90the name with the new version. The package name including the version will
91also disappear when the default version e.g. from Stackage catches up with the
92newest version from Hackage. E.g. if `haskellPackages.foo` gets updated from
931.0.0 to 1.1.0 the package `haskellPackages.foo_1_1_0` becomes obsolete and
94gets dropped.
955. For some packages, we also [manually add other `haskellPackages.foo_x_y_z`
96versions](https://github.com/NixOS/nixpkgs/blob/haskell-updates/pkgs/development/haskell-modules/configuration-hackage2nix/main.yaml),
97if they are required for a certain build.
98
99Relying on `haskellPackages.foo_x_y_z` attributes in derivations outside
100nixpkgs is discouraged because they may change or disappear with every package
101set update.
102<!-- TODO(@maralorn) We should add a link to callHackage, etc. once we added
103them to the docs. -->
104
105All `haskell.packages.*` package sets use the same package descriptions and the same sets
106of versions by default. There are however GHC version specific override `.nix`
107files to loosen this a bit.
108
109### Dependency resolution {#haskell-dependency-resolution}
110
111Normally when you build Haskell packages with `cabal-install`, `cabal-install`
112does dependency resolution. It will look at all Haskell package versions known
113on Hackage and tries to pick for every (transitive) dependency of your build
114exactly one version. Those versions need to satisfy all the version constraints
115given in the `.cabal` file of your package and all its dependencies.
116
117The [Haskell builder in nixpkgs](#haskell-mkderivation) does no such thing.
118It will take as input packages with names off the desired dependencies
119and just check whether they fulfill the version bounds and fail if they don’t
120(by default, see `jailbreak` to circumvent this).
121
122The `haskellPackages.callPackage` function does the package resolution.
123It will, e.g., use `haskellPackages.aeson`which has the default version as
124described above for a package input of name `aeson`. (More general:
125`<packages>.callPackage f` will call `f` with named inputs provided from the
126package set `<packages>`.)
127While this is the default behavior, it is possible to override the dependencies
128for a specific package, see
129[`override` and `overrideScope`](#haskell-overriding-haskell-packages).
130
131### Limitations {#haskell-limitations}
132
133Our main objective with `haskellPackages` is to package Haskell software in
134nixpkgs. This entails some limitations, partially due to self-imposed
135restrictions of nixpkgs, partially in the name of maintainability:
136
137* Only the packages built with the default compiler see extensive testing of the
138 whole package set. For other GHC versions only a few essential packages are
139 tested and cached.
140* As described above we only build one version of most packages.
141
142The experience using an older or newer packaged compiler or using different
143versions may be worse, because builds will not be cached on `cache.nixos.org`
144or may fail.
145
146Thus, to get the best experience, make sure that your project can be compiled
147using the default compiler of nixpkgs and recent versions of its dependencies.
148
149A result of this setup is, that getting a valid build plan for a given
150package can sometimes be quite painful, and in fact this is where most of the
151maintenance work for `haskellPackages` is required. Besides that, it is not
152possible to get the dependencies of a legacy project from nixpkgs or to use a
153specific stack solver for compiling a project.
154
155Even though we couldn’t use them directly in nixpkgs, it would be desirable
156to have tooling to generate working Nix package sets from build plans generated
157by `cabal-install` or a specific Stackage snapshot via import-from-derivation.
158Sadly we currently don’t have tooling for this. For this you might be
159interested in the alternative [haskell.nix] framework, which, be warned, is
160completely incompatible with packages from `haskellPackages`.
161
162<!-- TODO(@maralorn) Link to package set generation docs in the contributors guide below. -->
163
164## `haskellPackages.mkDerivation` {#haskell-mkderivation}
165
166Every haskell package set has its own haskell-aware `mkDerivation` which is used
167to build its packages. Generally you won't have to interact with this builder
168since [cabal2nix](#haskell-cabal2nix) can generate packages
169using it for an arbitrary cabal package definition. Still it is useful to know
170the parameters it takes when you need to
171[override](#haskell-overriding-haskell-packages) a generated Nix expression.
172
173`haskellPackages.mkDerivation` is a wrapper around `stdenv.mkDerivation` which
174re-defines the default phases to be haskell aware and handles dependency
175specification, test suites, benchmarks etc. by compiling and invoking the
176package's `Setup.hs`. It does *not* use or invoke the `cabal-install` binary,
177but uses the underlying `Cabal` library instead.
178
179### General arguments {#haskell-derivation-args}
180
181`pname`
182: Package name, assumed to be the same as on Hackage (if applicable)
183
184`version`
185: Packaged version, assumed to be the same as on Hackage (if applicable)
186
187`src`
188: Source of the package. If omitted, fetch package corresponding to `pname`
189and `version` from Hackage.
190
191`sha256`
192: Hash to use for the default case of `src`.
193
194`revision`
195: Revision number of the updated cabal file to fetch from Hackage.
196If `null` (which is the default value), the one included in `src` is used.
197
198`editedCabalFile`
199: `sha256` hash of the cabal file identified by `revision` or `null`.
200
201`configureFlags`
202: Extra flags passed when executing the `configure` command of `Setup.hs`.
203
204`buildFlags`
205: Extra flags passed when executing the `build` command of `Setup.hs`.
206
207`haddockFlags`
208: Extra flags passed to `Setup.hs haddock` when building the documentation.
209
210`doCheck`
211: Whether to execute the package's test suite if it has one. Defaults to `true` unless cross-compiling.
212
213`doBenchmark`
214: Whether to execute the package's benchmark if it has one. Defaults to `false`.
215
216`doHoogle`
217: Whether to generate an index file for [hoogle][hoogle] as part of
218`haddockPhase` by passing the [`--hoogle` option][haddock-hoogle-option].
219Defaults to `true`.
220
221`doHaddockQuickjump`
222: Whether to generate an index for interactive navigation of the HTML documentation.
223Defaults to `true` if supported.
224
225`doInstallIntermediates`
226: Whether to install intermediate build products (files written to `dist/build`
227by GHC during the build process). With `enableSeparateIntermediatesOutput`,
228these files are instead installed to [a separate `intermediates`
229output.][multiple-outputs] The output can then be passed into a future build of
230the same package with the `previousIntermediates` argument to support
231incremental builds. See [“Incremental builds”](#haskell-incremental-builds) for
232more information. Defaults to `false`.
233
234`enableLibraryProfiling`
235: Whether to enable [profiling][profiling] for libraries contained in the
236package. Enabled by default if supported.
237
238`enableExecutableProfiling`
239: Whether to enable [profiling][profiling] for executables contained in the
240package. Disabled by default.
241
242`profilingDetail`
243: [Profiling detail level][profiling-detail] to set. Defaults to `exported-functions`.
244
245`enableSharedExecutables`
246: Whether to link executables dynamically. By default, executables are linked statically.
247
248`enableSharedLibraries`
249: Whether to build shared Haskell libraries. This is enabled by default unless we are using
250`pkgsStatic` or shared libraries have been disabled in GHC.
251
252`enableStaticLibraries`
253: Whether to build static libraries. Enabled by default if supported.
254
255`enableDeadCodeElimination`
256: Whether to enable linker based dead code elimination in GHC.
257Enabled by default if supported.
258
259`enableHsc2hsViaAsm`
260: Whether to pass `--via-asm` to `hsc2hs`. Enabled by default only on Windows.
261
262`hyperlinkSource`
263: Whether to render the source as well as part of the haddock documentation
264by passing the [`--hyperlinked-source` flag][haddock-hyperlinked-source-option].
265Defaults to `true`.
266
267`isExecutable`
268: Whether the package contains an executable.
269
270`isLibrary`
271: Whether the package contains a library.
272
273`jailbreak`
274: Whether to execute [jailbreak-cabal][jailbreak-cabal] before `configurePhase`
275to lift any version constraints in the cabal file. Note that this can't
276lift version bounds if they are conditional, i.e. if a dependency is hidden
277behind a flag.
278
279`enableParallelBuilding`
280: Whether to use the `-j` flag to make GHC/Cabal start multiple jobs in parallel.
281
282`maxBuildCores`
283: Upper limit of jobs to use in parallel for compilation regardless of
284`$NIX_BUILD_CORES`. Defaults to 16 as Haskell compilation with GHC currently
285sees a [performance regression](https://gitlab.haskell.org/ghc/ghc/-/issues/9221)
286if too many parallel jobs are used.
287
288`doCoverage`
289: Whether to generate and install files needed for [HPC][haskell-program-coverage].
290Defaults to `false`.
291
292`doHaddock`
293: Whether to build (HTML) documentation using [haddock][haddock].
294Defaults to `true` if supported.
295
296`testTarget`
297: Name of the test suite to build and run. If unset, all test suites will be executed.
298
299`preCompileBuildDriver`
300: Shell code to run before compiling `Setup.hs`.
301
302`postCompileBuildDriver`
303: Shell code to run after compiling `Setup.hs`.
304
305`preHaddock`
306: Shell code to run before building documentation using haddock.
307
308`postHaddock`
309: Shell code to run after building documentation using haddock.
310
311`coreSetup`
312: Whether to only allow core libraries to be used while building `Setup.hs`.
313Defaults to `false`.
314
315`useCpphs`
316: Whether to enable the [cpphs][cpphs] preprocessor. Defaults to `false`.
317
318`enableSeparateBinOutput`
319: Whether to install executables to a separate `bin` output. Defaults to `false`.
320
321`enableSeparateDataOutput`
322: Whether to install data files shipped with the package to a separate `data` output.
323Defaults to `false`.
324
325`enableSeparateDocOutput`
326: Whether to install documentation to a separate `doc` output.
327Is automatically enabled if `doHaddock` is `true`.
328
329`enableSeparateIntermediatesOutput`
330: When `doInstallIntermediates` is true, whether to install intermediate build
331products to a separate `intermediates` output. See [“Incremental
332builds”](#haskell-incremental-builds) for more information. Defaults to
333`false`.
334
335`allowInconsistentDependencies`
336: If enabled, allow multiple versions of the same Haskell package in the
337dependency tree at configure time. Often in such a situation compilation would
338later fail because of type mismatches. Defaults to `false`.
339
340`enableLibraryForGhci`
341: Build and install a special object file for GHCi. This improves performance
342when loading the library in the REPL, but requires extra build time and
343disk space. Defaults to `false`.
344
345`previousIntermediates`
346: If non-null, intermediate build artifacts are copied from this input to
347`dist/build` before performing compiling. See [“Incremental
348builds”](#haskell-incremental-builds) for more information. Defaults to `null`.
349
350`buildTarget`
351: Name of the executable or library to build and install.
352If unset, all available targets are built and installed.
353
354### Specifying dependencies {#haskell-derivation-deps}
355
356Since `haskellPackages.mkDerivation` is intended to be generated from cabal
357files, it reflects cabal's way of specifying dependencies. For one, dependencies
358are grouped by what part of the package they belong to. This helps to reduce the
359dependency closure of a derivation, for example benchmark dependencies are not
360included if `doBenchmark == false`.
361
362`setup*Depends`
363: dependencies necessary to compile `Setup.hs`
364
365`library*Depends`
366: dependencies of a library contained in the package
367
368`executable*Depends`
369: dependencies of an executable contained in the package
370
371`test*Depends`
372: dependencies of a test suite contained in the package
373
374`benchmark*Depends`
375: dependencies of a benchmark contained in the package
376
377The other categorization relates to the way the package depends on the dependency:
378
379`*ToolDepends`
380: Tools we need to run as part of the build process.
381They are added to the derivation's `nativeBuildInputs`.
382
383`*HaskellDepends`
384: Haskell libraries the package depends on.
385They are added to `propagatedBuildInputs`.
386
387`*SystemDepends`
388: Non-Haskell libraries the package depends on.
389They are added to `buildInputs`
390
391`*PkgconfigDepends`
392: `*SystemDepends` which are discovered using `pkg-config`.
393They are added to `buildInputs` and it is additionally
394ensured that `pkg-config` is available at build time.
395
396`*FrameworkDepends`
397: Apple SDK Framework which the package depends on when compiling it on Darwin.
398
399Using these two distinctions, you should be able to categorize most of the dependency
400specifications that are available:
401`benchmarkFrameworkDepends`,
402`benchmarkHaskellDepends`,
403`benchmarkPkgconfigDepends`,
404`benchmarkSystemDepends`,
405`benchmarkToolDepends`,
406`executableFrameworkDepends`,
407`executableHaskellDepends`,
408`executablePkgconfigDepends`,
409`executableSystemDepends`,
410`executableToolDepends`,
411`libraryFrameworkDepends`,
412`libraryHaskellDepends`,
413`libraryPkgconfigDepends`,
414`librarySystemDepends`,
415`libraryToolDepends`,
416`setupHaskellDepends`,
417`testFrameworkDepends`,
418`testHaskellDepends`,
419`testPkgconfigDepends`,
420`testSystemDepends` and
421`testToolDepends`.
422
423That only leaves the following extra ways for specifying dependencies:
424
425`buildDepends`
426: Allows specifying Haskell dependencies which are added to `propagatedBuildInputs` unconditionally.
427
428`buildTools`
429: Like `*ToolDepends`, but are added to `nativeBuildInputs` unconditionally.
430
431`extraLibraries`
432: Like `*SystemDepends`, but are added to `buildInputs` unconditionally.
433
434`pkg-configDepends`
435: Like `*PkgconfigDepends`, but are added to `buildInputs` unconditionally.
436
437`testDepends`
438: Deprecated, use either `testHaskellDepends` or `testSystemDepends`.
439
440`benchmarkDepends`
441: Deprecated, use either `benchmarkHaskellDepends` or `benchmarkSystemDepends`.
442
443The dependency specification methods in this list which are unconditional
444are especially useful when writing [overrides](#haskell-overriding-haskell-packages)
445when you want to make sure that they are definitely included. However, it is
446recommended to use the more accurate ones listed above when possible.
447
448### Meta attributes {#haskell-derivation-meta}
449
450`haskellPackages.mkDerivation` accepts the following attributes as direct
451arguments which are transparently set in `meta` of the resulting derivation. See
452the [Meta-attributes section](#chap-meta) for their documentation.
453
454* These attributes are populated with a default value if omitted:
455 * `homepage`: defaults to the Hackage page for `pname`.
456 * `platforms`: defaults to `lib.platforms.all` (since GHC can cross-compile)
457* These attributes are only set if given:
458 * `description`
459 * `license`
460 * `changelog`
461 * `maintainers`
462 * `broken`
463 * `hydraPlatforms`
464
465### Incremental builds {#haskell-incremental-builds}
466
467`haskellPackages.mkDerivation` supports incremental builds for GHC 9.4 and
468newer with the `doInstallIntermediates`, `enableSeparateIntermediatesOutput`,
469and `previousIntermediates` arguments.
470
471The basic idea is to first perform a full build of the package in question,
472save its intermediate build products for later, and then copy those build
473products into the build directory of an incremental build performed later.
474Then, GHC will use those build artifacts to avoid recompiling unchanged
475modules.
476
477For more detail on how to store and use incremental build products, see
478[Gabriella Gonzalez’ blog post “Nixpkgs support for incremental Haskell
479builds”.][incremental-builds] motivation behind this feature.
480
481An incremental build for [the `turtle` package][turtle] can be performed like
482so:
483
484```nix
485let
486 pkgs = import <nixpkgs> {};
487 inherit (pkgs) haskell;
488 inherit (haskell.lib.compose) overrideCabal;
489
490 # Incremental builds work with GHC >=9.4.
491 turtle = haskell.packages.ghc944.turtle;
492
493 # This will do a full build of `turtle`, while writing the intermediate build products
494 # (compiled modules, etc.) to the `intermediates` output.
495 turtle-full-build-with-incremental-output = overrideCabal (drv: {
496 doInstallIntermediates = true;
497 enableSeparateIntermediatesOutput = true;
498 }) turtle;
499
500 # This will do an incremental build of `turtle` by copying the previously
501 # compiled modules and intermediate build products into the source tree
502 # before running the build.
503 #
504 # GHC will then naturally pick up and reuse these products, making this build
505 # complete much more quickly than the previous one.
506 turtle-incremental-build = overrideCabal (drv: {
507 previousIntermediates = turtle-full-build-with-incremental-output.intermediates;
508 }) turtle;
509in
510 turtle-incremental-build
511```
512
513## Development environments {#haskell-development-environments}
514
515In addition to building and installing Haskell software, nixpkgs can also
516provide development environments for Haskell projects. This has the obvious
517advantage that you benefit from `cache.nixos.org` and no longer need to compile
518all project dependencies yourself. While it is often very useful, this is not
519the primary use case of our package set. Have a look at the section
520[available package versions](#haskell-available-versions) to learn which
521versions of packages we provide and the section
522[limitations](#haskell-limitations), to judge whether a `haskellPackages`
523based development environment for your project is feasible.
524
525By default, every derivation built using
526[`haskellPackages.mkDerivation`](#haskell-mkderivation) exposes an environment
527suitable for building it interactively as the `env` attribute. For example, if
528you have a local checkout of `random`, you can enter a development environment
529for it like this (if the dependencies in the development and packaged version
530match):
531
532```console
533$ cd ~/src/random
534$ nix-shell -A haskellPackages.random.env '<nixpkgs>'
535[nix-shell:~/src/random]$ ghc-pkg list
536/nix/store/a8hhl54xlzfizrhcf03c1l3f6l9l8qwv-ghc-9.2.4-with-packages/lib/ghc-9.2.4/package.conf.d
537 Cabal-3.6.3.0
538 array-0.5.4.0
539 base-4.16.3.0
540 binary-0.8.9.0
541 …
542 ghc-9.2.4
543 …
544```
545
546As you can see, the environment contains a GHC which is set up so it finds all
547dependencies of `random`. Note that this environment does not mirror
548the environment used to build the package, but is intended as a convenient
549tool for development and simple debugging. `env` relies on the `ghcWithPackages`
550wrapper which automatically injects a pre-populated package-db into every
551GHC invocation. In contrast, using `nix-shell -A haskellPackages.random` will
552not result in an environment in which the dependencies are in GHCs package
553database. Instead, the Haskell builder will pass in all dependencies explicitly
554via configure flags.
555
556`env` mirrors the normal derivation environment in one aspect: It does not include
557familiar development tools like `cabal-install`, since we rely on plain `Setup.hs`
558to build all packages. However, `cabal-install` will work as expected if in
559`PATH` (e.g. when installed globally and using a `nix-shell` without `--pure`).
560A declarative and pure way of adding arbitrary development tools is provided
561via [`shellFor`](#haskell-shellFor).
562
563When using `cabal-install` for dependency resolution you need to be a bit
564careful to achieve build purity. `cabal-install` will find and use all
565dependencies installed from the packages `env` via Nix, but it will also
566consult Hackage to potentially download and compile dependencies if it can’t
567find a valid build plan locally. To prevent this you can either never run
568`cabal update`, remove the cabal database from your `~/.cabal` folder or run
569`cabal` with `--offline`. Note though, that for some usecases `cabal2nix` needs
570the local Hackage db.
571
572Often you won't work on a package that is already part of `haskellPackages` or
573Hackage, so we first need to write a Nix expression to obtain the development
574environment from. Luckily, we can generate one very easily from an already
575existing cabal file using `cabal2nix`:
576
577```console
578$ ls
579my-project.cabal src …
580$ cabal2nix ./. > my-project.nix
581```
582
583The generated Nix expression evaluates to a function ready to be
584`callPackage`-ed. For now, we can add a minimal `default.nix` which does just
585that:
586
587```nix
588# Retrieve nixpkgs impurely from NIX_PATH for now, you can pin it instead, of course.
589{ pkgs ? import <nixpkgs> {} }:
590
591# use the nixpkgs default haskell package set
592pkgs.haskellPackages.callPackage ./my-project.nix { }
593```
594
595Using `nix-build default.nix` we can now build our project, but we can also
596enter a shell with all the package's dependencies available using `nix-shell
597-A env default.nix`. If you have `cabal-install` installed globally, it'll work
598inside the shell as expected.
599
600### shellFor {#haskell-shellFor}
601
602Having to install tools globally is obviously not great, especially if you want
603to provide a batteries-included `shell.nix` with your project. Luckily there's a
604proper tool for making development environments out of packages' build
605environments: `shellFor`, a function exposed by every haskell package set. It
606takes the following arguments and returns a derivation which is suitable as a
607development environment inside `nix-shell`:
608
609`packages`
610: This argument is used to select the packages for which to build the
611development environment. This should be a function which takes a haskell package
612set and returns a list of packages. `shellFor` will pass the used package set to
613this function and include all dependencies of the returned package in the build
614environment. This means you can reuse Nix expressions of packages included in
615nixpkgs, but also use local Nix expressions like this: `hpkgs: [
616(hpkgs.callPackage ./my-project.nix { }) ]`.
617
618`nativeBuildInputs`
619: Expects a list of derivations to add as build tools to the build environment.
620This is the place to add packages like `cabal-install`, `doctest` or `hlint`.
621Defaults to `[]`.
622
623`buildInputs`
624: Expects a list of derivations to add as library dependencies, like `openssl`.
625This is rarely necessary as the haskell package expressions usually track system
626dependencies as well. Defaults to `[]`. (see also
627[derivation dependencies](#haskell-derivation-deps))
628
629`withHoogle`
630: If this is true, `hoogle` will be added to `nativeBuildInputs`.
631Additionally, its database will be populated with all included dependencies,
632so you'll be able search through the documentation of your dependencies.
633Defaults to `false`.
634
635`genericBuilderArgsModifier`
636: This argument accepts a function allowing you to modify the arguments passed
637to `mkDerivation` in order to create the development environment. For example,
638`args: { doCheck = false; }` would cause the environment to not include any test
639dependencies. Defaults to `lib.id`.
640
641`doBenchmark`
642: This is a shortcut for enabling `doBenchmark` via `genericBuilderArgsModifier`.
643Setting it to `true` will cause the development environment to include all
644benchmark dependencies which would be excluded by default. Defaults to `false`.
645
646One neat property of `shellFor` is that it allows you to work on multiple
647packages using the same environment in conjunction with
648[cabal.project files][cabal-project-files].
649Say our example above depends on `distribution-nixpkgs` and we have a project
650file set up for both, we can add the following `shell.nix` expression:
651
652```nix
653{ pkgs ? import <nixpkgs> {} }:
654
655pkgs.haskellPackages.shellFor {
656 packages = hpkgs: [
657 # reuse the nixpkgs for this package
658 hpkgs.distribution-nixpkgs
659 # call our generated Nix expression manually
660 (hpkgs.callPackage ./my-project/my-project.nix { })
661 ];
662
663 # development tools we use
664 nativeBuildInputs = [
665 pkgs.cabal-install
666 pkgs.haskellPackages.doctest
667 pkgs.cabal2nix
668 ];
669
670 # Extra arguments are added to mkDerivation's arguments as-is.
671 # Since it adds all passed arguments to the shell environment,
672 # we can use this to set the environment variable the `Paths_`
673 # module of distribution-nixpkgs uses to search for bundled
674 # files.
675 # See also: https://cabal.readthedocs.io/en/latest/cabal-package.html#accessing-data-files-from-package-code
676 distribution_nixpkgs_datadir = toString ./distribution-nixpkgs;
677}
678```
679
680<!-- TODO(@sternenseemann): deps are not included if not selected -->
681
682### haskell-language-server {#haskell-language-server}
683
684To use HLS in short: Install `pkgs.haskell-language-server` e.g. in
685`nativeBuildInputs` in `shellFor` and use the `haskell-language-server-wrapper`
686command to run it. See the [HLS user guide] on how to configure your text
687editor to use HLS and how to test your setup.
688
689HLS needs to be compiled with the GHC version of the project you use it
690on.
691
692``pkgs.haskell-language-server`` provides
693``haskell-language-server-wrapper``, ``haskell-language-server``
694and ``haskell-language-server-x.x.x``
695binaries, where ``x.x.x`` is the GHC version for which it is compiled. By
696default, it only includes binaries for the current GHC version, to reduce
697closure size. The closure size is large, because HLS needs to be dynamically
698linked to work reliably. You can override the list of supported GHC versions
699with e.g.
700
701```nix
702pkgs.haskell-language-server.override { supportedGhcVersions = [ "90" "94" ]; }
703```
704Where all strings `version` are allowed such that
705`haskell.packages.ghc${version}` is an existing package set.
706
707When you run `haskell-language-server-wrapper` it will detect the GHC
708version used by the project you are working on (by asking e.g. cabal or
709stack) and pick the appropriate versioned binary from your path.
710
711Be careful when installing HLS globally and using a pinned nixpkgs for a
712Haskell project in a `nix-shell`. If the nixpkgs versions deviate to much
713(e.g., use different `glibc` versions) the `haskell-language-server-?.?.?`
714executable will try to detect these situations and refuse to start. It is
715recommended to obtain HLS via `nix-shell` from the nixpkgs version pinned in
716there instead.
717
718The top level `pkgs.haskell-language-server` attribute is just a convenience
719wrapper to make it possible to install HLS for multiple GHC versions at the
720same time. If you know, that you only use one GHC version, e.g., in a project
721specific `nix-shell` you can use
722`pkgs.haskellPackages.haskell-language-server` or
723`pkgs.haskell.packages.*.haskell-language-server` from the package set you use.
724
725If you use `nix-shell` for your development environments remember to start your
726editor in that environment. You may want to use something like `direnv` and/or an
727editor plugin to achieve this.
728
729## Overriding Haskell packages {#haskell-overriding-haskell-packages}
730
731### Overriding a single package {#haskell-overriding-a-single-package}
732
733<!-- TODO(@sternenseemann): we should document /somewhere/ that base == null etc. -->
734
735Like many language specific subsystems in nixpkgs, the Haskell infrastructure
736also has its own quirks when it comes to overriding. Overriding of the *inputs*
737to a package at least follows the standard procedure. For example, imagine you
738need to build `nix-tree` with a more recent version of `brick` than the default
739one provided by `haskellPackages`:
740
741```nix
742haskellPackages.nix-tree.override {
743 brick = haskellPackages.brick_0_67;
744}
745```
746
747<!-- TODO(@sternenseemann): This belongs in the next section
748One common problem you may run into with such an override is the build failing
749with “abort because of serious configure-time warning from Cabal”. When scrolling
750up, you'll usually notice that Cabal noticed that more than one versions of the same
751package was present in the dependency graph. This typically causes a later compilation
752failure (the error message `haskellPackages.mkDerivation` produces tries to save
753you the time of finding this out yourself, but if you wish to do so, you can
754disable it using `allowInconsistentDependencies`). Luckily, `haskellPackages` provides
755you with a tool to deal with this. `overrideScope` creates a new `haskellPackages`
756instance with the override applied *globally* for this package, so the dependency
757closure automatically uses a consistent version of the overridden package. E. g.
758if `haskell-ci` needs a recent version of `Cabal`, but also uses other packages
759that depend on that library, you may want to use:
760
761```nix
762haskellPackages.haskell-ci.overrideScope (self: super: {
763 Cabal = self.Cabal_3_6_2_0;
764})
765```
766
767-->
768
769The custom interface comes into play when you want to override the arguments
770passed to `haskellPackages.mkDerivation`. For this, the function `overrideCabal`
771from `haskell.lib.compose` is used. E.g., if you want to install a man page
772that is distributed with the package, you can do something like this:
773
774```nix
775haskell.lib.compose.overrideCabal (drv: {
776 postInstall = ''
777 ${drv.postInstall or ""}
778 install -Dm644 man/pnbackup.1 -t $out/share/man/man1
779 '';
780}) haskellPackages.pnbackup
781```
782
783`overrideCabal` takes two arguments:
784
7851. A function which receives all arguments passed to `haskellPackages.mkDerivation`
786 before and returns a set of arguments to replace (or add) with a new value.
7872. The Haskell derivation to override.
788
789The arguments are ordered so that you can easily create helper functions by making
790use of currying:
791
792```nix
793let
794 installManPage = haskell.lib.compose.overrideCabal (drv: {
795 postInstall = ''
796 ${drv.postInstall or ""}
797 install -Dm644 man/${drv.pname}.1 -t "$out/share/man/man1"
798 '';
799 });
800in
801
802installManPage haskellPackages.pnbackup
803```
804
805In fact, `haskell.lib.compose` already provides lots of useful helpers for common
806tasks, detailed in the next section. They are also structured in such a way that
807they can be combined using `lib.pipe`:
808
809```nix
810lib.pipe my-haskell-package [
811 # lift version bounds on dependencies
812 haskell.lib.compose.doJailbreak
813 # disable building the haddock documentation
814 haskell.lib.compose.dontHaddock
815 # pass extra package flag to Cabal's configure step
816 (haskell.lib.compose.enableCabalFlag "myflag")
817]
818```
819
820#### `haskell.lib.compose` {#haskell-haskell.lib.compose}
821
822The base interface for all overriding is the following function:
823
824`overrideCabal f drv`
825: Takes the arguments passed to obtain `drv` to `f` and uses the resulting
826attribute set to update the argument set. Then a recomputed version of `drv`
827using the new argument set is returned.
828
829<!--
830TODO(@sternenseemann): ideally we want to be more detailed here as well, but
831I want to avoid the documentation having to be kept in sync in too many places.
832We already document this stuff in the mkDerivation section and lib/compose.nix.
833Ideally this section would be generated from the latter in the future.
834-->
835
836All other helper functions are implemented in terms of `overrideCabal` and make
837common overrides shorter and more complicate ones trivial. The simple overrides
838which only change a single argument are only described very briefly in the
839following overview. Refer to the
840[documentation of `haskellPackages.mkDerivation`](#haskell-mkderivation)
841for a more detailed description of the effects of the respective arguments.
842
843##### Packaging Helpers {#haskell-packaging-helpers}
844
845`overrideSrc { src, version } drv`
846: Replace the source used for building `drv` with the path or derivation given
847as `src`. The `version` attribute is optional. Prefer this function over
848overriding `src` via `overrideCabal`, since it also automatically takes care of
849removing any Hackage revisions.
850
851<!-- TODO(@sternenseemann): deprecated
852
853`generateOptparseApplicativeCompletions list drv`
854: Generate and install shell completion files for the installed executables whose
855names are given via `list`. The executables need to be using `optparse-applicative`
856for this to work.
857-->
858
859`justStaticExecutables drv`
860: Only build and install the executables produced by `drv`, removing everything
861 that may refer to other Haskell packages' store paths (like libraries and
862 documentation). This dramatically reduces the closure size of the resulting
863 derivation. Note that the executables are only statically linked against their
864 Haskell dependencies, but will still link dynamically against libc, GMP and
865 other system library dependencies.
866
867 If a library or its dependencies use their Cabal-generated
868 `Paths_*` module, this may not work as well if GHC's dead code elimination is
869 unable to remove the references to the dependency's store path that module
870 contains.
871 As a consequence, an unused reference may be created from the static binary to such a _library_ store path.
872 (See [nixpkgs#164630][164630] for more information.)
873
874 Importing the `Paths_*` module may cause builds to fail with this message:
875
876 ```
877 error: output '/nix/store/64k8iw0ryz76qpijsnl9v87fb26v28z8-my-haskell-package-1.0.0.0' is not allowed to refer to the following paths:
878 /nix/store/5q5s4a07gaz50h04zpfbda8xjs8wrnhg-ghc-9.6.3
879 ```
880
881 If that happens, first disable the check for GHC references and rebuild the
882 derivation:
883
884 ```nix
885 pkgs.haskell.lib.overrideCabal
886 (pkgs.haskell.lib.justStaticExecutables my-haskell-package)
887 (drv: {
888 disallowGhcReference = false;
889 })
890 ```
891
892 Then use `strings` to determine which libraries are responsible:
893
894 ```
895 $ nix-build ...
896 $ strings result/bin/my-haskell-binary | grep /nix/store/
897 ...
898 /nix/store/n7ciwdlg8yyxdhbrgd6yc2d8ypnwpmgq-hs-opentelemetry-sdk-0.0.3.6/bin
899 ...
900 ```
901
902 Finally, use `remove-references-to` to delete those store paths from the produced output:
903
904 ```nix
905 pkgs.haskell.lib.overrideCabal
906 (pkgs.haskell.lib.justStaticExecutables my-haskell-package)
907 (drv: {
908 postInstall = ''
909 ${drv.postInstall or ""}
910 remove-references-to -t ${pkgs.haskellPackages.hs-opentelemetry-sdk}
911 '';
912 })
913 ```
914
915[164630]: https://github.com/NixOS/nixpkgs/issues/164630
916
917`enableSeparateBinOutput drv`
918: Install executables produced by `drv` to a separate `bin` output. This
919has a similar effect as `justStaticExecutables`, but preserves the libraries
920and documentation in the `out` output alongside the `bin` output with a
921much smaller closure size.
922
923`markBroken drv`
924: Sets the `broken` flag to `true` for `drv`.
925
926`markUnbroken drv`, `unmarkBroken drv`
927: Set the `broken` flag to `false` for `drv`.
928
929`doDistribute drv`
930: Updates `hydraPlatforms` so that Hydra will build `drv`. This is
931sometimes necessary when working with versioned packages in
932`haskellPackages` which are not built by default.
933
934`dontDistribute drv`
935: Sets `hydraPlatforms` to `[]`, causing Hydra to skip this package
936altogether. Useful if it fails to evaluate cleanly and is causing
937noise in the evaluation errors tab on Hydra.
938
939##### Development Helpers {#haskell-development-helpers}
940
941`sdistTarball drv`
942: Create a source distribution tarball like those found on Hackage
943instead of building the package `drv`.
944
945`documentationTarball drv`
946: Create a documentation tarball suitable for uploading to Hackage
947instead of building the package `drv`.
948
949`buildFromSdist drv`
950: Uses `sdistTarball drv` as the source to compile `drv`. This helps to catch
951packaging bugs when building from a local directory, e.g. when required files
952are missing from `extra-source-files`.
953
954`failOnAllWarnings drv`
955: Enables all warnings GHC supports and makes it fail the build if any of them
956are emitted.
957
958<!-- TODO(@sternenseemann):
959`checkUnusedPackages opts drv`
960: Adds an extra check to `postBuild` which fails the build if any dependency
961taken as an input is not used. The `opts` attribute set allows relaxing this
962check.
963-->
964
965`enableDWARFDebugging drv`
966: Compiles the package with additional debug symbols enabled, useful
967for debugging with e.g. `gdb`.
968
969`doStrip drv`
970: Sets `doStrip` to `true` for `drv`.
971
972`dontStrip drv`
973: Sets `doStrip` to `false` for `drv`.
974
975<!-- TODO(@sternenseemann): shellAware -->
976
977##### Trivial Helpers {#haskell-trivial-helpers}
978
979`doJailbreak drv`
980: Sets the `jailbreak` argument to `true` for `drv`.
981
982`dontJailbreak drv`
983: Sets the `jailbreak` argument to `false` for `drv`.
984
985`doHaddock drv`
986: Sets `doHaddock` to `true` for `drv`.
987
988`dontHaddock drv`
989: Sets `doHaddock` to `false` for `drv`. Useful if the build of a package is
990failing because of e.g. a syntax error in the Haddock documentation.
991
992`doHyperlinkSource drv`
993: Sets `hyperlinkSource` to `true` for `drv`.
994
995`dontHyperlinkSource drv`
996: Sets `hyperlinkSource` to `false` for `drv`.
997
998`doCheck drv`
999: Sets `doCheck` to `true` for `drv`.
1000
1001`dontCheck drv`
1002: Sets `doCheck` to `false` for `drv`. Useful if a package has a broken,
1003flaky or otherwise problematic test suite breaking the build.
1004
1005`dontCheckIf condition drv`
1006: Sets `doCheck` to `false` for `drv`, but only if `condition` applies.
1007Otherwise it's a no-op. Useful to conditionally disable tests for a package
1008without interfering with previous overrides or default values.
1009
1010<!-- Purposefully omitting the non-list variants here. They are a bit
1011ugly, and we may want to deprecate them at some point. -->
1012
1013`appendConfigureFlags list drv`
1014: Adds the strings in `list` to the `configureFlags` argument for `drv`.
1015
1016`enableCabalFlag flag drv`
1017: Makes sure that the Cabal flag `flag` is enabled in Cabal's configure step.
1018
1019`disableCabalFlag flag drv`
1020: Makes sure that the Cabal flag `flag` is disabled in Cabal's configure step.
1021
1022`appendBuildFlags list drv`
1023: Adds the strings in `list` to the `buildFlags` argument for `drv`.
1024
1025<!-- TODO(@sternenseemann): removeConfigureFlag -->
1026
1027`appendPatches list drv`
1028: Adds the `list` of derivations or paths to the `patches` argument for `drv`.
1029
1030<!-- TODO(@sternenseemann): link dep section -->
1031
1032`addBuildTools list drv`
1033: Adds the `list` of derivations to the `buildTools` argument for `drv`.
1034
1035`addExtraLibraries list drv`
1036: Adds the `list` of derivations to the `extraLibraries` argument for `drv`.
1037
1038`addBuildDepends list drv`
1039: Adds the `list` of derivations to the `buildDepends` argument for `drv`.
1040
1041`addTestToolDepends list drv`
1042: Adds the `list` of derivations to the `testToolDepends` argument for `drv`.
1043
1044`addPkgconfigDepends list drv`
1045: Adds the `list` of derivations to the `pkg-configDepends` argument for `drv`.
1046
1047`addSetupDepends list drv`
1048: Adds the `list` of derivations to the `setupHaskellDepends` argument for `drv`.
1049
1050`doBenchmark drv`
1051: Set `doBenchmark` to `true` for `drv`. Useful if your development
1052environment is missing the dependencies necessary for compiling the
1053benchmark component.
1054
1055`dontBenchmark drv`
1056: Set `doBenchmark` to `false` for `drv`.
1057
1058`setBuildTargets drv list`
1059: Sets the `buildTarget` argument for `drv` so that the targets specified in `list` are built.
1060
1061`doCoverage drv`
1062: Sets the `doCoverage` argument to `true` for `drv`.
1063
1064`dontCoverage drv`
1065: Sets the `doCoverage` argument to `false` for `drv`.
1066
1067`enableExecutableProfiling drv`
1068: Sets the `enableExecutableProfiling` argument to `true` for `drv`.
1069
1070`disableExecutableProfiling drv`
1071: Sets the `enableExecutableProfiling` argument to `false` for `drv`.
1072
1073`enableLibraryProfiling drv`
1074: Sets the `enableLibraryProfiling` argument to `true` for `drv`.
1075
1076`disableLibraryProfiling drv`
1077: Sets the `enableLibraryProfiling` argument to `false` for `drv`.
1078
1079#### Library functions in the Haskell package sets {#haskell-package-set-lib-functions}
1080
1081Some library functions depend on packages from the Haskell package sets. Thus they are
1082exposed from those instead of from `haskell.lib.compose` which can only access what is
1083passed directly to it. When using the functions below, make sure that you are obtaining them
1084from the same package set (`haskellPackages`, `haskell.packages.ghc944` etc.) as the packages
1085you are working with or – even better – from the `self`/`final` fix point of your overlay to
1086`haskellPackages`.
1087
1088Note: Some functions like `shellFor` that are not intended for overriding per se, are omitted
1089in this section. <!-- TODO(@sternenseemann): note about ifd section -->
1090
1091`cabalSdist { src, name ? ... }`
1092: Generates the Cabal sdist tarball for `src`, suitable for uploading to Hackage.
1093Contrary to `haskell.lib.compose.sdistTarball`, it uses `cabal-install` over `Setup.hs`,
1094so it is usually faster: No build dependencies need to be downloaded, and we can
1095skip compiling `Setup.hs`.
1096
1097`buildFromCabalSdist drv`
1098: Build `drv`, but run its `src` attribute through `cabalSdist` first. Useful for catching
1099files necessary for compilation that are missing from the sdist.
1100
1101`generateOptparseApplicativeCompletions list drv`
1102: Generate and install shell completion files for the installed executables whose
1103names are given via `list`. The executables need to be using `optparse-applicative`
1104for [this to work][optparse-applicative-completions].
1105Note that this feature is automatically disabled when cross-compiling, since it
1106requires executing the binaries in question.
1107
1108## Import-from-Derivation helpers {#haskell-import-from-derivation}
1109
1110### cabal2nix {#haskell-cabal2nix}
1111
1112[`cabal2nix`][cabal2nix] can generate Nix package definitions for arbitrary
1113Haskell packages using [import from derivation][import-from-derivation].
1114`cabal2nix` will generate Nix expressions that look like this:
1115
1116```nix
1117# cabal get mtl-2.2.1 && cd mtl-2.2.1 && cabal2nix .
1118{ mkDerivation, base, lib, transformers }:
1119mkDerivation {
1120 pname = "mtl";
1121 version = "2.2.1";
1122 src = ./.;
1123 libraryHaskellDepends = [ base transformers ];
1124 homepage = "http://github.com/ekmett/mtl";
1125 description = "Monad classes, using functional dependencies";
1126 license = lib.licenses.bsd3;
1127}
1128```
1129
1130This expression should be called with `haskellPackages.callPackage`, which will
1131supply [`haskellPackages.mkDerivation`](#haskell-mkderivation) and the Haskell
1132dependencies as arguments.
1133
1134`callCabal2nix name src args`
1135: Create a package named `name` from the source derivation `src` using
1136 `cabal2nix`.
1137
1138 `args` are extra arguments provided to `haskellPackages.callPackage`.
1139
1140`callCabal2nixWithOptions name src opts args`
1141: Create a package named `name` from the source derivation `src` using
1142 `cabal2nix`.
1143
1144 `opts` are extra options for calling `cabal2nix`. If `opts` is a string, it
1145 will be used as extra command line arguments for `cabal2nix`, e.g. `--subpath
1146 path/to/dir/containing/cabal-file`. Otherwise, `opts` should be an AttrSet
1147 which can contain the following attributes:
1148
1149 `extraCabal2nixOptions`
1150 : Extra command line arguments for `cabal2nix`.
1151
1152 `srcModifier`
1153 : A function which is used to modify the given `src` instead of the default
1154 filter.
1155
1156 The default source filter will remove all files from `src` except for
1157 `.cabal` files and `package.yaml` files.
1158
1159<!--
1160
1161`callHackage`
1162: TODO
1163
1164`callHackageDirect`
1165: TODO
1166
1167`developPackage`
1168: TODO
1169
1170-->
1171
1172<!--
1173
1174TODO(@NixOS/haskell): finish these planned sections
1175### Overriding the entire package set
1176
1177## Contributing {#haskell-contributing}
1178
1179### Fixing a broken package {#haskell-fixing-a-broken-package}
1180
1181### Package set generation {#haskell-package-set-generation}
1182
1183### Packaging a Haskell project
1184
1185### Backporting {#haskell-backporting}
1186
1187Backporting changes to a stable NixOS version in general is covered
1188in nixpkgs' `CONTRIBUTING.md` in general. In particular refer to the
1189[backporting policy](https://github.com/NixOS/nixpkgs/blob/master/CONTRIBUTING.md#criteria-for-backporting-changes)
1190to check if the change you have in mind may be backported.
1191
1192This section focuses on how to backport a package update (e.g. a
1193bug fix or security release). Fixing a broken package works like
1194it does for the unstable branches.
1195
1196-->
1197
1198## F.A.Q. {#haskell-faq}
1199
1200### Why is topic X not covered in this section? Why is section Y missing? {#haskell-why-not-covered}
1201
1202We have been working on [moving the nixpkgs Haskell documentation back into the
1203nixpkgs manual](https://github.com/NixOS/nixpkgs/issues/121403). Since this
1204process has not been completed yet, you may find some topics missing here
1205covered in the old [haskell4nix docs](https://haskell4nix.readthedocs.io/).
1206
1207If you feel any important topic is not documented at all, feel free to comment
1208on the issue linked above.
1209
1210### How to enable or disable profiling builds globally? {#haskell-faq-override-profiling}
1211
1212By default, Nixpkgs builds a profiling version of each Haskell library. The
1213exception to this rule are some platforms where it is disabled due to concerns
1214over output size. You may want to…
1215
1216* …enable profiling globally so that you can build a project you are working on
1217 with profiling ability giving you insight in the time spent across your code
1218 and code you depend on using [GHC's profiling feature][profiling].
1219
1220* …disable profiling (globally) to reduce the time spent building the profiling
1221 versions of libraries which a significant amount of build time is spent on
1222 (although they are not as expensive as the “normal” build of a Haskell library).
1223
1224::: {.note}
1225The method described below affects the build of all libraries in the
1226respective Haskell package set as well as GHC. If your choices differ from
1227Nixpkgs' default for your (host) platform, you will lose the ability to
1228substitute from the official binary cache.
1229
1230If you are concerned about build times and thus want to disable profiling, it
1231probably makes sense to use `haskell.lib.compose.disableLibraryProfiling` (see
1232[](#haskell-trivial-helpers)) on the packages you are building locally while
1233continuing to substitute their dependencies and GHC.
1234:::
1235
1236Since we need to change the profiling settings for the desired Haskell package
1237set _and_ GHC (as the core libraries like `base`, `filepath` etc. are bundled
1238with GHC), it is recommended to use overlays for Nixpkgs to change them.
1239Since the interrelated parts, i.e. the package set and GHC, are connected
1240via the Nixpkgs fixpoint, we need to modify them both in a way that preserves
1241their connection (or else we'd have to wire it up again manually). This is
1242achieved by changing GHC and the package set in separate overlays to prevent
1243the package set from pulling in GHC from `prev`.
1244
1245The result is two overlays like the ones shown below. Adjustable parts are
1246annotated with comments, as are any optional or alternative ways to achieve
1247the desired profiling settings without causing too many rebuilds.
1248
1249<!-- TODO(@sternenseemann): buildHaskellPackages != haskellPackages with this overlay,
1250affected by https://github.com/NixOS/nixpkgs/issues/235960 which needs to be fixed
1251properly still.
1252-->
1253
1254```nix
1255let
1256 # Name of the compiler and package set you want to change. If you are using
1257 # the default package set `haskellPackages`, you need to look up what version
1258 # of GHC it currently uses (note that this is subject to change).
1259 ghcName = "ghc92";
1260 # Desired new setting
1261 enableProfiling = true;
1262in
1263
1264[
1265 # The first overlay modifies the GHC derivation so that it does or does not
1266 # build profiling versions of the core libraries bundled with it. It is
1267 # recommended to only use such an overlay if you are enabling profiling on a
1268 # platform that doesn't by default, because compiling GHC from scratch is
1269 # quite expensive.
1270 (final: prev:
1271 let
1272 inherit (final) lib;
1273 in
1274
1275 {
1276 haskell = prev.haskell // {
1277 compiler = prev.haskell.compiler // {
1278 ${ghcName} = prev.haskell.compiler.${ghcName}.override {
1279 # Unfortunately, the GHC setting is named differently for historical reasons
1280 enableProfiledLibs = enableProfiling;
1281 };
1282 };
1283 };
1284 })
1285
1286 (final: prev:
1287 let
1288 inherit (final) lib;
1289 haskellLib = final.haskell.lib.compose;
1290 in
1291
1292 {
1293 haskell = prev.haskell // {
1294 packages = prev.haskell.packages // {
1295 ${ghcName} = prev.haskell.packages.${ghcName}.override {
1296 overrides = hfinal: hprev: {
1297 mkDerivation = args: hprev.mkDerivation (args // {
1298 # Since we are forcing our ideas upon mkDerivation, this change will
1299 # affect every package in the package set.
1300 enableLibraryProfiling = enableProfiling;
1301
1302 # To actually use profiling on an executable, executable profiling
1303 # needs to be enabled for the executable you want to profile. You
1304 # can either do this globally or…
1305 enableExecutableProfiling = enableProfiling;
1306 });
1307
1308 # …only for the package that contains an executable you want to profile.
1309 # That saves on unnecessary rebuilds for packages that you only depend
1310 # on for their library, but also contain executables (e.g. pandoc).
1311 my-executable = haskellLib.enableExecutableProfiling hprev.my-executable;
1312
1313 # If you are disabling profiling to save on build time, but want to
1314 # retain the ability to substitute from the binary cache. Drop the
1315 # override for mkDerivation above and instead have an override like
1316 # this for the specific packages you are building locally and want
1317 # to make cheaper to build.
1318 my-library = haskellLib.disableLibraryProfiling hprev.my-library;
1319 };
1320 };
1321 };
1322 };
1323 })
1324]
1325```
1326
1327<!-- TODO(@sternenseemann): write overriding mkDerivation, overriding GHC, and
1328overriding the entire package set sections and link to them from here where
1329relevant.
1330-->
1331
1332[Stackage]: https://www.stackage.org
1333[cabal-project-files]: https://cabal.readthedocs.io/en/latest/cabal-project.html
1334[cabal2nix]: https://github.com/nixos/cabal2nix
1335[cpphs]: https://Hackage.haskell.org/package/cpphs
1336[haddock-hoogle-option]: https://haskell-haddock.readthedocs.io/en/latest/invoking.html#cmdoption-hoogle
1337[haddock-hyperlinked-source-option]: https://haskell-haddock.readthedocs.io/en/latest/invoking.html#cmdoption-hyperlinked-source
1338[haddock]: https://www.haskell.org/haddock/
1339[haskell-program-coverage]: https://downloads.haskell.org/~ghc/latest/docs/html/users_guide/profiling.html#observing-code-coverage
1340[haskell.nix]: https://input-output-hk.github.io/haskell.nix/index.html
1341[HLS user guide]: https://haskell-language-server.readthedocs.io/en/latest/configuration.html#configuring-your-editor
1342[hoogle]: https://wiki.haskell.org/Hoogle
1343[incremental-builds]: https://www.haskellforall.com/2022/12/nixpkgs-support-for-incremental-haskell.html
1344[jailbreak-cabal]: https://github.com/NixOS/jailbreak-cabal/
1345[multiple-outputs]: https://nixos.org/manual/nixpkgs/stable/#chap-multiple-output
1346[optparse-applicative-completions]: https://github.com/pcapriotti/optparse-applicative/blob/7726b63796aa5d0df82e926d467f039b78ca09e2/README.md#bash-zsh-and-fish-completions
1347[profiling-detail]: https://cabal.readthedocs.io/en/latest/cabal-project.html#cfg-field-profiling-detail
1348[profiling]: https://downloads.haskell.org/~ghc/latest/docs/html/users_guide/profiling.html
1349[search.nixos.org]: https://search.nixos.org
1350[turtle]: https://hackage.haskell.org/package/turtle
1351[import-from-derivation]: https://nixos.org/manual/nix/stable/language/import-from-derivation