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