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