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