Users Guide
Users Guide
Release 9.0.2
GHC Team
1 Introduction 3
1.1 Obtaining GHC . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.2 Meta-information: Web sites, mailing lists, etc. . . . . . . . . . . . . . . . . . . . . 3
1.3 Reporting bugs in GHC . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.4 GHC version numbering policy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.5 The Glasgow Haskell Compiler License . . . . . . . . . . . . . . . . . . . . . . . . . 5
2 Release notes 7
2.1 Version 9.0.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
2.1.1 Highlights . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
2.1.2 Full details . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
Language . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
Compiler . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
GHCi . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
Runtime system . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
Template Haskell . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
Arrow notation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
Haddock . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
base library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
ghc-prim library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
ghc library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
base library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
Build system . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
2.1.3 Bootstrapping requirements . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
2.1.4 Included libraries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
2.2 Version 9.0.2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
2.2.1 Highlights . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
2.2.2 General bug fixes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
2.2.3 Packaging fixes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
2.2.4 Portability fixes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
2.2.5 Included libraries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
3 Using GHCi 23
3.1 Introduction to GHCi . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
3.2 Loading source files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
3.2.1 Modules vs. filenames . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
3.2.2 Making changes and recompilation . . . . . . . . . . . . . . . . . . . . . . . 25
3.3 Loading compiled code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
3.4 Interactive evaluation at the prompt . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
3.4.1 I/O actions at the prompt . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
3.4.2 Using do notation at the prompt . . . . . . . . . . . . . . . . . . . . . . . . . 28
i
3.4.3 Multiline input . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30
3.4.4 Type, class and other declarations . . . . . . . . . . . . . . . . . . . . . . . . 31
3.4.5 What’s really in scope at the prompt? . . . . . . . . . . . . . . . . . . . . . . 32
The effect of :load on what is in scope . . . . . . . . . . . . . . . . . . . . . . 33
Controlling what is in scope with import . . . . . . . . . . . . . . . . . . . . . 33
Controlling what is in scope with the :module command . . . . . . . . . . . 34
Qualified names . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
:module and :load . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
3.4.6 The :main and :run commands . . . . . . . . . . . . . . . . . . . . . . . . . . 35
3.4.7 The it variable . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
3.4.8 Type defaulting in GHCi . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36
Interactive classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
Extended rules around default declarations . . . . . . . . . . . . . . . . . . 38
3.4.9 Using a custom interactive printing function . . . . . . . . . . . . . . . . . . 38
3.4.10 Stack Traces in GHCi . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
3.5 The GHCi Debugger . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
3.5.1 Breakpoints and inspecting variables . . . . . . . . . . . . . . . . . . . . . . 40
Setting breakpoints . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
Managing breakpoints . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44
3.5.2 Single-stepping . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44
3.5.3 Nested breakpoints . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
3.5.4 The _result variable . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
3.5.5 Tracing and history . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46
3.5.6 Debugging exceptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47
3.5.7 Example: inspecting functions . . . . . . . . . . . . . . . . . . . . . . . . . . 48
3.5.8 Limitations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49
3.6 Invoking GHCi . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50
3.6.1 Packages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50
3.6.2 Extra libraries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51
3.7 GHCi commands . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51
3.8 The :set and :seti commands . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63
3.8.1 GHCi options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63
3.8.2 Setting GHC command-line options in GHCi . . . . . . . . . . . . . . . . . . 64
3.8.3 Setting options for interactive evaluation only . . . . . . . . . . . . . . . . . 64
3.9 The .ghci and .haskeline files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65
3.9.1 The .ghci files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65
3.9.2 The .haskeline file . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67
3.10 Compiling to object code inside GHCi . . . . . . . . . . . . . . . . . . . . . . . . . . 67
3.11 Running the interpreter in a separate process . . . . . . . . . . . . . . . . . . . . . 67
3.12 Running the interpreter on a different host . . . . . . . . . . . . . . . . . . . . . . . 68
3.13 FAQ and Things To Watch Out For . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68
4 Using runghc 71
4.1 Usage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71
4.2 runghc flags . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71
4.3 GHC Flags . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71
5 Using GHC 73
5.1 Using GHC . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73
5.1.1 Getting started: compiling programs . . . . . . . . . . . . . . . . . . . . . . 73
5.1.2 Options overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 74
Command-line arguments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 74
Command line options in source files . . . . . . . . . . . . . . . . . . . . . . . 74
Setting options in GHCi . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75
ii
5.1.3 Dynamic and Mode options . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75
5.1.4 Meaningful file suffixes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75
5.1.5 Modes of operation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 76
Using ghc --make . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77
Expression evaluation mode . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78
Batch compiler mode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78
5.1.6 Verbosity options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79
5.1.7 Platform-specific Flags . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84
5.1.8 Haddock . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85
5.1.9 Miscellaneous flags . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85
Other environment variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85
5.2 Warnings and sanity-checking . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85
5.3 Optimisation (code improvement) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 104
5.3.1 -O*: convenient “packages” of optimisation flags. . . . . . . . . . . . . . . 105
5.3.2 -f*: platform-independent flags . . . . . . . . . . . . . . . . . . . . . . . . . 105
5.4 Using Concurrent Haskell . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 117
5.5 Using SMP parallelism . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 118
5.5.1 Compile-time options for SMP parallelism . . . . . . . . . . . . . . . . . . . 118
5.5.2 RTS options for SMP parallelism . . . . . . . . . . . . . . . . . . . . . . . . . 118
5.5.3 Hints for using SMP parallelism . . . . . . . . . . . . . . . . . . . . . . . . . 119
5.6 Flag reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 120
5.6.1 Verbosity options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 120
5.6.2 Alternative modes of operation . . . . . . . . . . . . . . . . . . . . . . . . . . 123
5.6.3 Which phases to run . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 124
5.6.4 Redirecting output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 124
5.6.5 Keeping intermediate files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 125
5.6.6 Temporary files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 126
5.6.7 Finding imports . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 126
5.6.8 Interface file options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 126
5.6.9 Recompilation checking . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 126
5.6.10 Interactive-mode options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 127
5.6.11 Packages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 128
5.6.12 Language options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 129
5.6.13 Warnings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 129
5.6.14 Optimisation levels . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 137
5.6.15 Individual optimisations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 138
5.6.16 Profiling options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 143
5.6.17 Program coverage options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 144
5.6.18 C pre-processor options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 144
5.6.19 Code generation options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 145
5.6.20 Linking options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 145
5.6.21 Plugin options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 148
5.6.22 Replacing phases . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 148
5.6.23 Forcing options to particular phases . . . . . . . . . . . . . . . . . . . . . . . 149
5.6.24 Platform-specific options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 150
5.6.25 Compiler debugging options . . . . . . . . . . . . . . . . . . . . . . . . . . . . 150
5.6.26 Miscellaneous compiler options . . . . . . . . . . . . . . . . . . . . . . . . . . 155
5.7 Running a compiled program . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 155
5.7.1 Setting RTS options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 155
Setting RTS options on the command line . . . . . . . . . . . . . . . . . . . . 156
Setting RTS options at compile time . . . . . . . . . . . . . . . . . . . . . . . . 156
Setting RTS options with the GHCRTS environment variable . . . . . . . . . . 157
“Hooks” to change RTS behaviour . . . . . . . . . . . . . . . . . . . . . . . . . 157
5.7.2 Miscellaneous RTS options . . . . . . . . . . . . . . . . . . . . . . . . . . . . 158
iii
5.7.3 RTS options to control the garbage collector . . . . . . . . . . . . . . . . . . 160
5.7.4 RTS options to produce runtime statistics . . . . . . . . . . . . . . . . . . . 167
5.7.5 RTS options for concurrency and parallelism . . . . . . . . . . . . . . . . . 169
5.7.6 RTS options for profiling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 170
5.7.7 Tracing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 170
5.7.8 RTS options for hackers, debuggers, and over-interested souls . . . . . . 171
5.7.9 Getting information about the RTS . . . . . . . . . . . . . . . . . . . . . . . . 173
5.8 Filenames and separate compilation . . . . . . . . . . . . . . . . . . . . . . . . . . . 175
5.8.1 Haskell source files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 175
5.8.2 Output files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 175
5.8.3 The search path . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 176
5.8.4 Redirecting the compilation output(s) . . . . . . . . . . . . . . . . . . . . . . 176
5.8.5 Keeping Intermediate Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . 179
5.8.6 Redirecting temporary files . . . . . . . . . . . . . . . . . . . . . . . . . . . . 179
5.8.7 Other options related to interface files . . . . . . . . . . . . . . . . . . . . . 179
5.8.8 Options related to extended interface files . . . . . . . . . . . . . . . . . . . 180
5.8.9 The recompilation checker . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 180
5.8.10 How to compile mutually recursive modules . . . . . . . . . . . . . . . . . . 181
5.8.11 Module signatures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 183
5.8.12 Using make . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 189
5.8.13 Dependency generation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 190
5.8.14 Orphan modules and instance declarations . . . . . . . . . . . . . . . . . . . 191
5.9 Packages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 193
5.9.1 Using Packages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 193
5.9.2 The main package . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 196
5.9.3 Consequences of packages for the Haskell language . . . . . . . . . . . . . 196
5.9.4 Thinning and renaming modules . . . . . . . . . . . . . . . . . . . . . . . . . 197
5.9.5 Package Databases . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 197
The GHC_PACKAGE_PATH environment variable . . . . . . . . . . . . . . . . . . 198
Package environments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 199
5.9.6 Installed package IDs, dependencies, and broken packages . . . . . . . . 200
5.9.7 Package management (the ghc-pkg command) . . . . . . . . . . . . . . . . 202
5.9.8 Building a package from Haskell source . . . . . . . . . . . . . . . . . . . . 204
5.9.9 InstalledPackageInfo: a package specification . . . . . . . . . . . . . . . 206
5.10 GHC Backends . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 209
5.10.1 Native Code Generator (-fasm) . . . . . . . . . . . . . . . . . . . . . . . . . . 209
5.10.2 LLVM Code Generator (-fllvm) . . . . . . . . . . . . . . . . . . . . . . . . . . 209
5.10.3 C Code Generator (-fvia-C) . . . . . . . . . . . . . . . . . . . . . . . . . . . 210
5.10.4 Unregisterised compilation . . . . . . . . . . . . . . . . . . . . . . . . . . . . 210
5.11 Options related to a particular phase . . . . . . . . . . . . . . . . . . . . . . . . . . . 211
5.11.1 Replacing the program for one or more phases . . . . . . . . . . . . . . . . 211
5.11.2 Forcing options to a particular phase . . . . . . . . . . . . . . . . . . . . . . 212
5.11.3 Options affecting the C pre-processor . . . . . . . . . . . . . . . . . . . . . . 213
Standard CPP macros . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 213
CPP and string gaps . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 215
5.11.4 Options affecting a Haskell pre-processor . . . . . . . . . . . . . . . . . . . 215
5.11.5 Options affecting code generation . . . . . . . . . . . . . . . . . . . . . . . . 216
5.11.6 Options affecting linking . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 217
5.12 Using shared libraries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 223
5.12.1 Building programs that use shared libraries . . . . . . . . . . . . . . . . . . 223
5.12.2 Shared libraries for Haskell packages . . . . . . . . . . . . . . . . . . . . . . 224
5.12.3 Shared libraries that export a C API . . . . . . . . . . . . . . . . . . . . . . . 224
5.12.4 Finding shared libraries at runtime . . . . . . . . . . . . . . . . . . . . . . . 225
Unix . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 225
iv
Mac OS X . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 226
5.13 Debugging the compiler . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 226
5.13.1 Dumping out compiler intermediate structures . . . . . . . . . . . . . . . . 227
Front-end . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 227
Type-checking and renaming . . . . . . . . . . . . . . . . . . . . . . . . . . . . 228
Core representation and simplification . . . . . . . . . . . . . . . . . . . . . . 229
STG representation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 230
C-\- representation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 230
LLVM code generator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 231
Native code generator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 232
Miscellaneous backend dumps . . . . . . . . . . . . . . . . . . . . . . . . . . . 232
5.13.2 Formatting dumps . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 233
5.13.3 Suppressing unwanted information . . . . . . . . . . . . . . . . . . . . . . . 233
5.13.4 Checking for consistency . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 234
5.13.5 Checking for determinism . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 235
5.13.6 Other . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 235
v
6.2.20 Arrow notation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 273
do-notation for commands . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 275
Conditional commands . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 276
Defining your own control structures . . . . . . . . . . . . . . . . . . . . . . . 277
Primitive constructs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 278
Differences with the paper . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 279
Portability . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 279
6.2.21 Lexical negation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 279
6.3 Import and export . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 280
6.3.1 Hiding things the imported module doesn’t export . . . . . . . . . . . . . . 280
6.3.2 Package-qualified imports . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 281
6.3.3 Safe imports . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 281
6.3.4 Explicit namespaces in import/export . . . . . . . . . . . . . . . . . . . . . . 282
6.3.5 Writing qualified in postpositive position . . . . . . . . . . . . . . . . . . . . 282
6.4 Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 283
6.4.1 Data types with no constructors . . . . . . . . . . . . . . . . . . . . . . . . . 283
6.4.2 Data type contexts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 283
6.4.3 Infix type constructors, classes, and type variables . . . . . . . . . . . . . . 284
6.4.4 Type operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 284
6.4.5 Liberalised type synonyms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 285
6.4.6 Existentially quantified data constructors . . . . . . . . . . . . . . . . . . . . 286
Why existential? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 287
Existentials and type classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . 287
Record Constructors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 288
Restrictions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 289
6.4.7 Declaring data types with explicit constructor signatures . . . . . . . . . . 290
Formal syntax for GADTs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 292
GADT syntax odds and ends . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 294
6.4.8 Generalised Algebraic Data Types (GADTs) . . . . . . . . . . . . . . . . . . . 296
6.4.9 Type families . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 298
Data families . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 299
Synonym families . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 301
Wildcards on the LHS of data and type family instances . . . . . . . . . . . 306
Associated data and type families . . . . . . . . . . . . . . . . . . . . . . . . . 307
Import and export . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 311
Type families and instance declarations . . . . . . . . . . . . . . . . . . . . . 313
Injective type families . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 314
6.4.10 Datatype promotion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 315
Motivation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 316
Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 316
Distinguishing between types and constructors . . . . . . . . . . . . . . . . . 317
Promoted list and tuple types . . . . . . . . . . . . . . . . . . . . . . . . . . . . 318
Promoting existential data constructors . . . . . . . . . . . . . . . . . . . . . 318
6.4.11 Kind polymorphism . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 319
Overview of kind polymorphism . . . . . . . . . . . . . . . . . . . . . . . . . . 319
Overview of Type-in-Type . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 320
Principles of kind inference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 320
Inferring the order of variables in a type/class declaration . . . . . . . . . . 321
Complete user-supplied kind signatures and polymorphic recursion . . . . 322
Standalone kind signatures and polymorphic recursion . . . . . . . . . . . . 324
Standalone kind signatures and declaration headers . . . . . . . . . . . . . 325
Kind inference in closed type families . . . . . . . . . . . . . . . . . . . . . . . 326
Kind inference in class instance declarations . . . . . . . . . . . . . . . . . . 327
Kind inference in type signatures . . . . . . . . . . . . . . . . . . . . . . . . . 327
vi
Explicit kind quantification . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 328
Implicit quantification in type synonyms and type family instances . . . . . 328
Kind-indexed GADTs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 330
Higher-rank kinds . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 330
Constraints in kinds . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 331
The kind Type . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 331
Inferring dependency in datatype declarations . . . . . . . . . . . . . . . . . 332
Inferring dependency in user-written foralls . . . . . . . . . . . . . . . . . 332
Kind defaulting without PolyKinds . . . . . . . . . . . . . . . . . . . . . . . . 332
Pretty-printing in the presence of kind polymorphism . . . . . . . . . . . . . 333
Datatype return kinds . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 333
6.4.12 Levity polymorphism . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 334
No levity-polymorphic variables or arguments . . . . . . . . . . . . . . . . . 335
Levity-polymorphic bottoms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 335
Printing levity-polymorphic types . . . . . . . . . . . . . . . . . . . . . . . . . 336
6.4.13 Type-Level Literals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 336
Runtime Values for Type-Level Literals . . . . . . . . . . . . . . . . . . . . . . 337
Computing With Type-Level Naturals . . . . . . . . . . . . . . . . . . . . . . . 337
6.4.14 Visible type application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 338
Inferred vs. specified type variables . . . . . . . . . . . . . . . . . . . . . . . . 338
Ordering of specified variables . . . . . . . . . . . . . . . . . . . . . . . . . . . 340
Manually defining inferred variables . . . . . . . . . . . . . . . . . . . . . . . 340
6.4.15 Arbitrary-rank polymorphism . . . . . . . . . . . . . . . . . . . . . . . . . . . 342
Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 343
Subsumption . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 344
Type inference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 345
Implicit quantification . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 345
6.4.16 Impredicative polymorphism . . . . . . . . . . . . . . . . . . . . . . . . . . . 346
6.4.17 Linear types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 347
Data types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 348
Printing multiplicity-polymorphic types . . . . . . . . . . . . . . . . . . . . . . 348
Limitations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 349
Design and further reading . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 349
6.4.18 Custom compile-time errors . . . . . . . . . . . . . . . . . . . . . . . . . . . . 350
6.4.19 Deferring type errors to runtime . . . . . . . . . . . . . . . . . . . . . . . . . 351
Enabling deferring of type errors . . . . . . . . . . . . . . . . . . . . . . . . . 351
Deferred type errors in GHCi . . . . . . . . . . . . . . . . . . . . . . . . . . . . 351
Limitations of deferred type errors . . . . . . . . . . . . . . . . . . . . . . . . 352
6.4.20 Roles . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 352
Nominal, Representational, and Phantom . . . . . . . . . . . . . . . . . . . . 353
Role inference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 354
Role annotations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 354
6.5 Records . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 356
6.5.1 Traditional record syntax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 356
6.5.2 Field selectors and TypeApplications . . . . . . . . . . . . . . . . . . . . . 356
Field selectors for Haskell98-style data constructors . . . . . . . . . . . . . 356
Field selectors for GADT constructors . . . . . . . . . . . . . . . . . . . . . . 356
Field selectors for pattern synonyms . . . . . . . . . . . . . . . . . . . . . . . 357
6.5.3 Record field disambiguation . . . . . . . . . . . . . . . . . . . . . . . . . . . . 358
6.5.4 Duplicate record fields . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 359
Selector functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 359
Record updates . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 360
Import and export of record fields . . . . . . . . . . . . . . . . . . . . . . . . . 361
6.5.5 Record puns . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 361
vii
6.5.6 Record wildcards . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 362
6.5.7 Record field selector polymorphism . . . . . . . . . . . . . . . . . . . . . . . 363
Solving HasField constraints . . . . . . . . . . . . . . . . . . . . . . . . . . . . 364
Virtual record fields . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 365
6.6 Deriving mechanism . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 366
6.6.1 Deriving instances for empty data types . . . . . . . . . . . . . . . . . . . . 367
6.6.2 Inferred context for deriving clauses . . . . . . . . . . . . . . . . . . . . . . 367
6.6.3 Stand-alone deriving declarations . . . . . . . . . . . . . . . . . . . . . . . . 368
6.6.4 Deriving instances of extra classes (Data, etc.) . . . . . . . . . . . . . . . . 369
Deriving Functor instances . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 370
Deriving Foldable instances . . . . . . . . . . . . . . . . . . . . . . . . . . . . 373
Deriving Traversable instances . . . . . . . . . . . . . . . . . . . . . . . . . . 375
Deriving Data instances . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 376
Deriving Typeable instances . . . . . . . . . . . . . . . . . . . . . . . . . . . . 377
Deriving Lift instances . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 377
6.6.5 Generalised derived instances for newtypes . . . . . . . . . . . . . . . . . . 378
Generalising the deriving clause . . . . . . . . . . . . . . . . . . . . . . . . . . 379
A more precise specification . . . . . . . . . . . . . . . . . . . . . . . . . . . . 381
Associated type families . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 382
6.6.6 Deriving any other class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 384
6.6.7 Deriving strategies . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 386
Default deriving strategy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 387
6.6.8 Deriving via . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 388
6.7 Patterns . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 389
6.7.1 Pattern guards . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 389
6.7.2 View patterns . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 390
6.7.3 n+k patterns . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 392
6.7.4 Pattern synonyms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 392
Record Pattern Synonyms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 394
Syntax and scoping of pattern synonyms . . . . . . . . . . . . . . . . . . . . . 395
Import and export of pattern synonyms . . . . . . . . . . . . . . . . . . . . . . 396
Typing of pattern synonyms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 397
Matching of pattern synonyms . . . . . . . . . . . . . . . . . . . . . . . . . . . 399
6.8 Class and instances declarations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 399
6.8.1 Multi-parameter type classes . . . . . . . . . . . . . . . . . . . . . . . . . . . 400
6.8.2 Flexible contexts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 400
6.8.3 Undecidable (or recursive) superclasses . . . . . . . . . . . . . . . . . . . . 401
6.8.4 Constrained class method types . . . . . . . . . . . . . . . . . . . . . . . . . 402
6.8.5 Default method signatures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 402
6.8.6 Nullary type classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 404
6.8.7 Functional dependencies . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 404
Rules for functional dependencies . . . . . . . . . . . . . . . . . . . . . . . . . 405
Background on functional dependencies . . . . . . . . . . . . . . . . . . . . . 405
6.8.8 Instance declarations and resolution . . . . . . . . . . . . . . . . . . . . . . . 409
Relaxed rules for the instance head . . . . . . . . . . . . . . . . . . . . . . . . 409
Formal syntax for instance declaration types . . . . . . . . . . . . . . . . . . 410
Relaxed rules for instance contexts . . . . . . . . . . . . . . . . . . . . . . . . 411
Instance termination rules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 412
Undecidable instances . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 413
Overlapping instances . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 414
Instance signatures: type signatures in instance declarations . . . . . . . . 418
6.9 Literals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 419
6.9.1 Negative literals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 419
6.9.2 Binary integer literals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 419
viii
6.9.3 Hexadecimal floating point literals . . . . . . . . . . . . . . . . . . . . . . . . 419
6.9.4 Fractional looking integer literals . . . . . . . . . . . . . . . . . . . . . . . . 420
6.9.5 Numeric underscores . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 420
6.9.6 Overloaded string literals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 422
6.9.7 Overloaded labels . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 423
6.10 Constraints . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 424
6.10.1 Equality constraints and Coercible constraint . . . . . . . . . . . . . . . . . 424
Equality constraints . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 424
Heterogeneous equality . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 425
Unlifted heterogeneous equality . . . . . . . . . . . . . . . . . . . . . . . . . . 425
The Coercible constraint . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 425
6.10.2 The Constraint kind . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 425
6.10.3 Quantified constraints . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 426
Motivation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 427
Syntax changes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 428
Typing changes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 429
Superclasses . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 429
Overlap . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 429
Instance lookup . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 430
Termination . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 430
Coherence . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 431
6.11 Type signatures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 431
6.11.1 Explicit universal quantification (forall) . . . . . . . . . . . . . . . . . . . . . 431
The forall-or-nothing rule . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 432
6.11.2 The context of a type signature . . . . . . . . . . . . . . . . . . . . . . . . . . 433
6.11.3 Ambiguous types and the ambiguity check . . . . . . . . . . . . . . . . . . . 433
6.11.4 Explicitly-kinded quantification . . . . . . . . . . . . . . . . . . . . . . . . . . 435
6.11.5 Lexically scoped type variables . . . . . . . . . . . . . . . . . . . . . . . . . . 436
Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 437
Declaration type signatures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 438
Expression type signatures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 439
Pattern type signatures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 439
Class and instance declarations . . . . . . . . . . . . . . . . . . . . . . . . . . 440
6.11.6 Implicit parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 441
Implicit-parameter type constraints . . . . . . . . . . . . . . . . . . . . . . . . 442
Implicit-parameter bindings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 442
Implicit parameters and polymorphic recursion . . . . . . . . . . . . . . . . . 443
Implicit parameters and monomorphism . . . . . . . . . . . . . . . . . . . . . 444
6.11.7 Partial Type Signatures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 444
Syntax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 444
Where can they occur? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 448
6.12 Bindings and generalisation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 449
6.12.1 Switching off the Monomorphism Restriction . . . . . . . . . . . . . . . . . 449
6.12.2 Let-generalisation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 449
6.13 Template Haskell . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 450
6.13.1 Syntax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 450
6.13.2 Using Template Haskell . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 456
6.13.3 Viewing Template Haskell generated code . . . . . . . . . . . . . . . . . . . 456
6.13.4 A Template Haskell Worked Example . . . . . . . . . . . . . . . . . . . . . . 457
6.13.5 Template Haskell quotes and Rebindable Syntax . . . . . . . . . . . . . . . 458
6.13.6 Using Template Haskell with Profiling . . . . . . . . . . . . . . . . . . . . . . 458
6.13.7 Template Haskell Quasi-quotation . . . . . . . . . . . . . . . . . . . . . . . . 459
6.14 Bang patterns and Strict Haskell . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 461
6.14.1 Bang patterns . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 462
ix
6.14.2 Strict-by-default data types . . . . . . . . . . . . . . . . . . . . . . . . . . . . 463
6.14.3 Strict-by-default pattern bindings . . . . . . . . . . . . . . . . . . . . . . . . 464
6.14.4 Modularity . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 466
6.14.5 Dynamic semantics of bang patterns . . . . . . . . . . . . . . . . . . . . . . . 466
6.15 Parallel and Concurrent . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 468
6.15.1 Concurrent and Parallel Haskell . . . . . . . . . . . . . . . . . . . . . . . . . 469
Concurrent Haskell . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 469
Parallel Haskell . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 469
Annotating pure code for parallelism . . . . . . . . . . . . . . . . . . . . . . . 469
6.15.2 Software Transactional Memory . . . . . . . . . . . . . . . . . . . . . . . . . 470
6.15.3 Static pointers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 470
Using static pointers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 471
Static semantics of static pointers . . . . . . . . . . . . . . . . . . . . . . . . . 472
6.16 Unboxed types and primitive operations . . . . . . . . . . . . . . . . . . . . . . . . . 473
6.16.1 Unboxed types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 473
6.16.2 Unboxed type kinds . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 473
6.16.3 Unboxed tuples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 474
6.16.4 Unboxed sums . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 475
6.16.5 Unlifted Newtypes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 477
6.17 Foreign function interface (FFI) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 478
6.17.1 GHC differences to the FFI Chapter . . . . . . . . . . . . . . . . . . . . . . . 478
Guaranteed call safety . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 478
Interactions between safe calls and bound threads . . . . . . . . . . . . . . 479
Varargs not supported by ccall calling convention . . . . . . . . . . . . . . 479
6.17.2 GHC extensions to the FFI Chapter . . . . . . . . . . . . . . . . . . . . . . . 479
Unlifted FFI Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 479
Newtype wrapping of the IO monad . . . . . . . . . . . . . . . . . . . . . . . . 481
Explicit “forall”s in foreign types . . . . . . . . . . . . . . . . . . . . . . . . . . 481
Primitive imports . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 482
Interruptible foreign calls . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 482
The CAPI calling convention . . . . . . . . . . . . . . . . . . . . . . . . . . . . 483
hs_thread_done() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 484
Freeing many stable pointers efficiently . . . . . . . . . . . . . . . . . . . . . 484
6.17.3 Using the FFI with GHC . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 484
Using foreign export and foreign import ccall "wrapper" with GHC 485
Using header files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 488
Memory Allocation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 488
Multi-threading and the FFI . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 489
Floating point and the FFI . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 492
Pinned Byte Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 492
6.18 Safe Haskell . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 493
6.18.1 Uses of Safe Haskell . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 493
Strict type-safety (good style) . . . . . . . . . . . . . . . . . . . . . . . . . . . . 494
Building secure systems (restricted IO Monads) . . . . . . . . . . . . . . . . 494
6.18.2 Safe Language . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 496
Safe Overlapping Instances . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 497
6.18.3 Safe Imports . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 498
6.18.4 Trust and Safe Haskell Modes . . . . . . . . . . . . . . . . . . . . . . . . . . . 498
Trust check (-fpackage-trust disabled) . . . . . . . . . . . . . . . . . . . . . 499
Trust check (-fpackage-trust enabled) . . . . . . . . . . . . . . . . . . . . . 499
Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 500
Trustworthy Requirements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 501
Package Trust . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 501
6.18.5 Safe Haskell Inference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 501
x
6.18.6 Safe Haskell Flag Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . 502
6.18.7 Safe Compilation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 503
6.19 Miscellaneous . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 504
6.19.1 Rewrite rules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 504
Syntax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 504
Semantics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 506
How rules interact with INLINE/NOINLINE pragmas . . . . . . . . . . . . . . 507
How rules interact with CONLIKE pragmas . . . . . . . . . . . . . . . . . . . . 507
How rules interact with class methods . . . . . . . . . . . . . . . . . . . . . . 508
List fusion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 509
Specialisation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 510
Controlling what’s going on in rewrite rules . . . . . . . . . . . . . . . . . . . 510
6.19.2 Special built-in functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 511
6.19.3 Generic programming . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 511
Deriving representations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 511
Writing generic functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 513
Unlifted representation types . . . . . . . . . . . . . . . . . . . . . . . . . . . . 514
Generic defaults . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 514
More information . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 515
6.19.4 Assertions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 515
6.19.5 HasCallStack . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 515
Compared with other sources of stack traces . . . . . . . . . . . . . . . . . . 517
6.20 Pragmas . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 518
6.20.1 LANGUAGE pragma . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 518
6.20.2 OPTIONS_GHC pragma . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 518
6.20.3 INCLUDE pragma . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 519
6.20.4 WARNING and DEPRECATED pragmas . . . . . . . . . . . . . . . . . . . . . . . . 519
6.20.5 MINIMAL pragma . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 520
6.20.6 INLINE and NOINLINE pragmas . . . . . . . . . . . . . . . . . . . . . . . . . . 520
INLINE pragma . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 521
INLINABLE pragma . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 522
NOINLINE pragma . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 523
CONLIKE modifier . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 523
Phase control . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 523
6.20.7 LINE pragma . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 524
6.20.8 COLUMN pragma . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 524
6.20.9 RULES pragma . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 525
6.20.10SPECIALIZE pragma . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 525
SPECIALIZE INLINE . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 526
SPECIALIZE for imported functions . . . . . . . . . . . . . . . . . . . . . . . . 527
6.20.11SPECIALIZE instance pragma . . . . . . . . . . . . . . . . . . . . . . . . . . . 527
6.20.12UNPACK pragma . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 528
6.20.13NOUNPACK pragma . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 528
6.20.14SOURCE pragma . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 529
6.20.15COMPLETE pragmas . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 529
6.20.16OVERLAPPING, OVERLAPPABLE, OVERLAPS, and INCOHERENT pragmas . . . . 530
xi
7.3.1 Using compiler plugins . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 533
7.3.2 Writing compiler plugins . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 535
7.3.3 Core plugins in more detail . . . . . . . . . . . . . . . . . . . . . . . . . . . . 535
Manipulating bindings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 536
Using Annotations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 537
7.3.4 Typechecker plugins . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 537
Constraint solving with plugins . . . . . . . . . . . . . . . . . . . . . . . . . . . 538
7.3.5 Source plugins . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 539
Parsed representation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 539
Type checked representation . . . . . . . . . . . . . . . . . . . . . . . . . . . . 540
Evaluated code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 540
Interface files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 540
Source plugin example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 541
7.3.6 Hole fit plugins . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 543
Stateful hole fit plugins . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 543
Hole fit plugin example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 544
7.3.7 Controlling Recompilation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 548
7.3.8 Frontend plugins . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 549
7.3.9 DynFlags plugins . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 549
8 Profiling 553
8.1 Cost centres and cost-centre stacks . . . . . . . . . . . . . . . . . . . . . . . . . . . 553
8.1.1 Inserting cost centres by hand . . . . . . . . . . . . . . . . . . . . . . . . . . 555
8.1.2 Rules for attributing costs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 557
8.2 Compiler options for profiling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 557
8.3 Time and allocation profiling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 558
8.3.1 JSON profile format . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 559
8.4 Profiling memory usage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 561
8.4.1 RTS options for heap profiling . . . . . . . . . . . . . . . . . . . . . . . . . . 562
8.4.2 Retainer Profiling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 564
Hints for using retainer profiling . . . . . . . . . . . . . . . . . . . . . . . . . . 565
8.4.3 Biographical Profiling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 565
8.4.4 Actual memory residency . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 566
8.5 hp2ps – Rendering heap profiles to PostScript . . . . . . . . . . . . . . . . . . . . . 566
8.5.1 Manipulating the hp file . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 568
8.5.2 Zooming in on regions of your profile . . . . . . . . . . . . . . . . . . . . . . 568
8.5.3 Viewing the heap profile of a running program . . . . . . . . . . . . . . . . 568
8.5.4 Viewing a heap profile in real time . . . . . . . . . . . . . . . . . . . . . . . . 569
8.6 Profiling Parallel and Concurrent Programs . . . . . . . . . . . . . . . . . . . . . . 569
8.7 Observing Code Coverage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 570
8.7.1 A small example: Reciprocation . . . . . . . . . . . . . . . . . . . . . . . . . 570
8.7.2 Options for instrumenting code for coverage . . . . . . . . . . . . . . . . . . 572
8.7.3 The hpc toolkit . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 572
hpc report . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 572
hpc markup . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 573
hpc sum . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 573
hpc combine . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 574
hpc map . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 574
hpc overlay and hpc draft . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 574
8.7.4 Caveats and Shortcomings of Haskell Program Coverage . . . . . . . . . . 575
8.8 Using “ticky-ticky” profiling (for implementors) . . . . . . . . . . . . . . . . . . . . 575
xii
9.2 Requesting a stack trace from Haskell code . . . . . . . . . . . . . . . . . . . . . . 580
9.3 Requesting a stack trace with SIGQUIT . . . . . . . . . . . . . . . . . . . . . . . . . 580
9.4 Implementor’s notes: DWARF annotations . . . . . . . . . . . . . . . . . . . . . . . 581
9.4.1 Debugging information entities . . . . . . . . . . . . . . . . . . . . . . . . . . 581
DW_TAG_ghc_src_note . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 582
9.5 Further Reading . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 582
11 Hints 585
11.1 Sooner: producing a program more quickly . . . . . . . . . . . . . . . . . . . . . . . 585
11.2 Faster: producing a program that runs quicker . . . . . . . . . . . . . . . . . . . . 586
11.3 Smaller: producing a program that is smaller . . . . . . . . . . . . . . . . . . . . . 589
11.4 Thriftier: producing a program that gobbles less heap space . . . . . . . . . . . . 589
xiii
14.1.2 GHC’s interpretation of undefined behaviour in Haskell 98 and
Haskell 2010 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 609
14.2 Known bugs or infelicities . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 610
14.2.1 Bugs in GHC . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 610
14.2.2 Bugs in GHCi (the interactive GHC) . . . . . . . . . . . . . . . . . . . . . . . 612
xiv
Bibliography 637
Index 639
xv
xvi
GHC User’s Guide Documentation, Release 9.0.2
Contents:
CONTENTS 1
GHC User’s Guide Documentation, Release 9.0.2
2 CONTENTS
CHAPTER
ONE
INTRODUCTION
This is a guide to using the Glasgow Haskell Compiler (GHC): an interactive and batch com-
pilation system for the Haskell 2010 language.
GHC has two main components: an interactive Haskell interpreter (also known as GHCi),
described in Using GHCi (page 23), and a batch compiler, described throughout Using GHC
(page 73). In fact, GHC consists of a single program which is just run with different options
to provide either the interactive or the batch system.
The batch compiler can be used alongside GHCi: compiled modules can be loaded into an
interactive session and used in the same way as interpreted code, and in fact when using
GHCi most of the library code will be pre-compiled. This means you get the best of both
worlds: fast pre-compiled library code, and fast compile turnaround for the parts of your
program being actively developed.
GHC supports numerous language extensions, including concurrency, a foreign function inter-
face, exceptions, type system extensions such as multi-parameter type classes, local universal
and existential quantification, functional dependencies, scoped type variables and explicit un-
boxed types. These are all described in Language extensions (page 237).
GHC has a comprehensive optimiser, so when you want to Really Go For It (and you’ve got time
to spare) GHC can produce pretty fast code. Alternatively, the default option is to compile as
fast as possible while not making too much effort to optimise the generated code (although
GHC probably isn’t what you’d describe as a fast compiler :-).
GHC’s profiling system supports “cost centre stacks”: a way of seeing the profile of a Haskell
program in a call-graph like structure. See Profiling (page 553) for more details.
GHC comes with a number of libraries. These are described in separate documentation.
Go to the GHC home page and follow the “download” link to download GHC for your platform.
Alternatively, if you want to build GHC yourself, head on over to the GHC Building Guide to
find out how to get the sources, and build it on your system. Note that GHC itself is written
in Haskell, so you will still need to install GHC in order to build it.
3
GHC User’s Guide Documentation, Release 9.0.2
Glasgow Haskell is a changing system so there are sure to be bugs in it. If you find one, please
see this wiki page for information on how to report it.
As of GHC version 6.8, we have adopted the following policy for numbering GHC versions:
Stable branches are numbered x.y, where ⟨y⟩ is even. Releases on the stable branch
x.y are numbered x.y.z, where ⟨z⟩ (>= 1) is the patchlevel number. Patchlevels
are bug-fix releases only, and never change the programmer interface to any system-
supplied code. However, if you install a new patchlevel over an old one you will need
to recompile any code that was compiled against the old libraries.
The value of __GLASGOW_HASKELL__ (see Options affecting the C pre-processor
(page 213)) for a major release x.y.z is the integer ⟨xyy⟩ (if ⟨y⟩ is a single digit,
then a leading zero is added, so for example in version 6.8.2 of GHC we would have
__GLASGOW_HASKELL__==608).
We may make snapshot releases of the current stable branch available for download,
and the latest sources are available from the git repositories.
Stable snapshot releases are named [Link]. where YYYYMMDD is the date
of the sources from which the snapshot was built, and x.y.z+1 is the next release
to be made on that branch. For example, 6.8.1.20040225 would be a snapshot of
the 6.8 branch during the development of 6.8.2.
We may make snapshot releases of the HEAD available for download, and the latest
sources are available from the git repositories.
Unstable snapshot releases are named [Link]. where YYYYMMDD is the date of
the sources from which the snapshot was built. For example, 6.7.20040225 would
be a snapshot of the HEAD before the creation of the 6.8 branch.
The value of __GLASGOW_HASKELL__ for a snapshot release is the integer ⟨xyy⟩. You
should never write any conditional code which tests for this value, however: since
4 Chapter 1. Introduction
GHC User’s Guide Documentation, Release 9.0.2
interfaces change on a day-to-day basis, and we don’t have finer granularity in the
values of __GLASGOW_HASKELL__, you should only conditionally compile using pred-
icates which test whether __GLASGOW_HASKELL__ is equal to, later than, or earlier
than a given major release.
The version number of your copy of GHC can be found by invoking ghc with the --version
flag (see Verbosity options (page 79)).
The compiler version can be tested within compiled code with the
MIN_VERSION_GLASGOW_HASKELL CPP macro (defined only when CPP (page 213) is used).
See Standard CPP macros (page 213) for details.
Copyright 2002 - 2007, The University Court of the University of Glasgow. All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted
provided that the following conditions are met:
• Redistributions of source code must retain the above copyright notice, this list of condi-
tions and the following disclaimer.
• Redistributions in binary form must reproduce the above copyright notice, this list of
conditions and the following disclaimer in the documentation and/or other materials
provided with the distribution.
• Neither name of the University nor the names of its contributors may be used to endorse
or promote products derived from this software without specific prior written permis-
sion.
THIS SOFTWARE IS PROVIDED BY THE UNIVERSITY COURT OF THE UNIVERSITY OF
GLASGOW AND THE CONTRIBUTORS “AS IS” AND ANY EXPRESS OR IMPLIED WAR-
RANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MER-
CHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
EVENT SHALL THE UNIVERSITY COURT OF THE UNIVERSITY OF GLASGOW OR THE
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EX-
EMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PRO-
CUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABIL-
ITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
6 Chapter 1. Introduction
CHAPTER
TWO
RELEASE NOTES
The significant changes to the various parts of the compiler are listed in the following sections.
The LLVM backend (page 216) of this release is to be used with LLVM 9.
2.1.1 Highlights
• The LinearTypes (page 347) extension enables linear function syntax a %1 -> b, as
described in the Linear Types GHC proposal.
The GADT syntax can be used to define data types with linear and nonlinear fields.
This extension is considered experimental: it doesn’t implement the full proposal yet and
the details are subject to change.
• NCG
– The linear register allocator saw improvements reducing the number of redundant
move instructions. Rare edge cases can see double digit improvements in runtime
for inner loops.
In the mean this improved runtime by about 0.8%. For details see ticket #17823.
• Pattern-Match Coverage Checking
– The revamp of the pattern-match coverage checker that started in 8.10 concludes
with this release and implements the novel *Lower Your Guards* algorithm.
– Compared to 8.10, end users might notice improvements to “long-distance informa-
tion”:
f True = 1
f x = ... case x of { False -> 2; True -> 3 } ...
7
GHC User’s Guide Documentation, Release 9.0.2
• Support for 32-bit Windows has officially been dropped as Microsoft has formally discon-
tinued new 32-bit Windows 10 releases in 2020. See #18487 for details.
Language
• Record field selectors are now given type signatures that preserve the user-written order
of quantified type variables. Moreover, field selector type signatures no longer make
inferred type variables available for explicit type application. See Field selectors and
TypeApplications (page 356) for more details.
In certain situations, this will constitute a breaking change as this can affect TypeAppli-
cations (page 338). For instance, given the following definitions:
Previous versions of GHC would give the following types to unP and unN:
• In obscure scenarios, GHC now rejects programs it previously accepted, but with un-
helpful types. For example, if (with -XPartialTypeSignatures) you were to write x ::
forall (f :: forall a (b :: a -> Type). b _). f _, GHC previously would have
accepted x, but its type would have involved the mysterious Any internal type family.
Now, GHC rejects, explaining the situation.
• GHC now more faithfully implements the instance-lookup scheme described with Quan-
tifiedConstraints (page 426). Previous bugs meant that programs like this were ac-
cepted:
Note that in the instance declaration for Applicative (T c), we cannot prove Functor
(T c), because the quantified constraint shadows the global instance. There is an easy
workaround, though: just include Functor (T c) as an assumption.
There is a chance we will tweak the lookup scheme in the future, to make this workaround
unnecessary.
• GHC now consistently does eager instantiation during type inference. As a consequence,
visible type application (VTA) now only works when the head of the application is:
– A variable
– An expression with a type signature
For example (let x = blah in id) @Bool True no longer typechecks. You should
write let x = blah in id @Bool True instead.
This change prepares the way for Quick Look impredicativity.
• GHC now implements simplified subsumption, as described in GHC Proposal #287. This
change simplifies the type system, and prevents the possibility of GHC silently changing
the semantics of user programs, but it does mean that some libraries may need eta-
expansion to typecheck. More info here: Subsumption (page 344).
This change also prepares the way for Quick Look impredicativity.
• GHC now allows users to manually define the specificity of type variable binders. By
marking a variable with braces {tyvar} or {tyvar :: kind}, it becomes inferred de-
spite appearing in a type signature. This feature effectively allows users to choose which
variables can or can’t be instantiated through visible type application. More information
can be found here: Manually defining inferred variables (page 340).
• GADT constructor types now properly adhere to The forall-or-nothing rule (page 432).
As a result, GHC will now reject some GADT constructors that previous versions of GHC
would accept, such as the following:
data T where
MkT1 :: (forall a. a -> b -> T)
MkT2 :: (forall a. a -> T)
MkT1 and MkT2 are rejected because the lack of an outermost forall triggers implicit
quantification, making the explicit foralls nested. Furthermore, GADT constructors
do not permit the use of nested foralls, as explained in Formal syntax for GADTs
(page 292).
In addition to rejecting nested foralls, GHC is now more stringent about rejecting uses
of nested contexts in GADT constructors. For example, the following example, which
previous versions of GHC would accept, is now rejected:
data U a where
MkU :: (Show a => U a)
• GHC more strictly enforces the rule that the type in the top of an instance declaration
is not permitted to contain nested foralls or contexts, as documented in Formal syntax
for instance declaration types (page 410). For example, the following examples, which
previous versions of GHC would accept, are now rejected:
instance (forall a. C a) where ... instance (Show a => C a) where ...
In addition, GHC now enforces the rule that the types in deriving clauses and via types
(for instances derived with DerivingVia (page 388)) cannot contain nested foralls or
contexts. For example, the following examples, which previous versions of GHC would
accept, are now rejected:
data T = MkT deriving (C1, (forall x. C2 x))
deriving via (forall x. V x) instance C (S x)
f = (- x) -- operator section
c = (-x) -- negation
• The behavior of NegativeLiterals (page 419) changed, and now we require that a neg-
ative literal must not be preceded by a closing token (see GHC Proposal #229) for the
definition of a closing token). In other words, we parse f -123 as f (-123), but x-123
as (-) x 123. Before this amendment, NegativeLiterals (page 419) caused x-123 to
be parsed as x(-123).
• GHC is now more sensitive to whitespace between infix operators and their arguments,
requiring it in some cases where it was not previously necessary as the result of the
whitespace-sensitive operator parsing proposal. It also affects the usage of !,‘‘~‘‘ and
@ as BangPatterns, irrefutable patterns and type applications respectively. This means
that expressions that were parsed as visible type applications in previous versions when
the @ was surrounded by whitespace will now be parsed as an operator application. For
more details see the migration guide on the wiki.
Compiler
• A new flag -flink-rts (page 219) to enable linking the RTS when linking shared li-
braries.
• The -funfolding-keeness-factor flag has been deprecated as its scaling strategy re-
sulted in unreasonably large discounts in some cases (see #15304). Users who pre-
viously used this flag to suggest more aggressive inlining are advised to look at -
funfolding-use-threshold=⟨n⟩ (page 116) or use INLINE (page 521) pragmas to more
precisely force inlining.
• The -funfolding-keeness-factor flag has been deprecated as its scaling strategy re-
sulted in unreasonably large discounts in some cases (see #15304). Users who pre-
viously used this flag to suggest more aggressive inlining are advised to look at -
funfolding-use-threshold=⟨n⟩ (page 116) or use INLINE (page 521) pragmas to more
precisely force inlining.
GHCi
• GHCi prompt no longer lists loaded modules. The previous behavior can be restored
with :set prompt "%s> " and :set prompt-cont "%s| ".
• The :script command now allows for file names that contain spaces to passed as argu-
ments: either by enclosing the file names in double quotes or by escaping spaces in file
names with a backslash. (#18027)
• The GHCi debugger syntax :break <[Link]> now allows to set breakpoints on
all functions. The restrictions top-Level and exported have been removed. Hence it’s
now possible to use this syntax to set breakpoints on functions defined in nested where
or let clauses.
Runtime system
• -N (page 118) without a count now tries to respect the number of processors in the pro-
cess’s affinity mask, making GHC’s behavior more predictable in containerized settings
(#14781).
• Support for Windows Vista has been dropped. GHC-compiled programs now require
Windows 7 or later.
• Windows now uses the large address space allocator by default. In extreme cases we
saw improvements by up to 3% decreased runtime.
The downside is that haskell apps run on older (Pre Win-8.1/Server 2012) systems will
have higher memory footprints.
Template Haskell
• Implement the Overloaded Quotations proposal (#246). The type of all quotation forms
have now been generalised in terms of a minimal interface necessary (the Quote type
class) for the implementation rather than the overapproximation of the Q monad.
• Template Haskell quotes now handle fixity declarations in let and where bindings prop-
erly. Previously, such fixity declarations would be dropped when quoted due to a Tem-
plate Haskell bug.
• The -XTemplateHaskellQuotes extension now allows nested splices as nested splices
do not lead directly to compile-time evaluation. (Merge request !2288)
Arrow notation
• When combined with Arrows (page 273), the LambdaCase (page 262) extension now ad-
ditionally allows \case syntax to be used as a command in proc notation.
• When combined with Arrows (page 273), the effects of the BlockArguments (page 265)
extension now also apply to applications of arrow control operators in (| banana brackets
|):
Haddock
class C a where
f :: a -> a
-- ^ This comment used to trigger a parse error
g :: a -> a
• -Winvalid-haddock (page 103) is a new warning that reports discarded Haddock com-
ments that cannot be associated with AST elements:
myValue =
-- | Invalid (discarded) comment in an expression
2 + 2
• When faced with several comments for a data constructor or a data constructor field,
Haddock now picks the first one instead of the last one. The extraneous comment is
reported as invalid when -Winvalid-haddock (page 103) is enabled:
data T
-- | First comment
= MkT
-- ^ Second comment (rejected)
• Haddock is now more relaxed about the placement of comments in types relative to the
function arrow ->, allowing more formatting styles:
• Haddock can now parse the documentation comment for the first declaration in a module
without a module header (#17561):
base library
ghc-prim library
ghc library
• The type of the getAnnotations function has changed to better reflect the fact that it
returns two different kinds of annotations, those on names and those on modules:
getAnnotations :: Typeable a
=> ([Word8] -> a) -> ModGuts
-> CoreM (ModuleEnv [a], NameEnv [a])
• The meaning of the hs_fixds field of HsGroup has changed slightly. It now only contains
fixity signatures defined for top-level declarations and class methods defined outside of
the class itself. Previously, hs_fixds would also contain fixity signatures for class meth-
ods defined inside the class, such as the fixity signature for m in the following example:
class C a where
infixl 4 `m`
m :: a -> a -> a
If you wish to attain the previous behavior of hs_fixds, use the new hsGroupTo-
pLevelFixitySigs function, which collects all top-level fixity signatures, including those
for class methods defined inside classes.
• The Exception module was boiled down acknowledging the existence of the exceptions
dependency. In particular, the ExceptionMonad class is not a proper class anymore,
but a mere synonym for MonadThrow, MonadCatch, MonadMask (all from exceptions) and
MonadIO. All of g*-functions from the module (gtry, gcatch, etc.) are erased, and their
exceptions-alternatives are meant to be used in the GHC code instead.
• parseModule is now the only parser entry point that deals with Haddock comments. The
other entry points (parseDeclaration, parseExpression, etc) do not insert the Haddock
comments into the AST.
base library
Build system
• GHC now requires a C compiler which supports __atomic_op_n builtins. This raises the
requirement for GCC to 4.7.
The package database provided with this distribution also contains a number of packages
other than GHC itself. See the changelogs provided with these packages for further change
information.
The significant changes to the various parts of the compiler are listed in the following sections.
The LLVM backend (page 216) of this release is to be used with LLVM versions 9 through 12.
2.2.1 Highlights
• First-class support for Apple M1 hardware using GHC’s LLVM ARM backend.
• Fixes for a number of critical compiler and runtime system correctness bugs.
• Improved compiler performance and memory usage.
• Fix incorrect rewrite rules for fromInteger resulting in incorrect code when compiling
with optimisations (#19345, #20066).
• Unify primary and secondary GHCi prompts (#20042).
• Warn if Unicode Bidirectional Formatting characters are found in the source, possibly
misleading code reviewers (#20263).
• Fix a memory leak in the simplifier, leading to the consumption of more memory on each
iteration (#20134).
• Reduce memory usage in --make mode (#13586).
• Fix a long standing bug in constraint solving which lead to incorrect build failures
(#19315).
• Fix a a bug affecting the demand analyser which lead to runtime crashes when compiling
with optimisation (#18638).
• Fix a bug where code may be unloaded prematurely when using the parallel garbage
collector (see #19417).
• Fix a long standing GHC API bug affecting clients like Haskell Language Server where
async exceptions used to cancel threads during typechecking would be caught by the
Template Haskell evaluator and reported as compile errors (#19410).
• Fix an inconsistency in the way GHC calls typechecker plugins where slightly different
typechecker environment would be made available as an argument as compared to the
monadic environment (see #19191).
• Greatly improve performance and memory usage while compiling modules with many
partial type signatures and -Wno-partial-type-signatures
• Fix a bug where the linker may during shutdown unload code before libraries’ atexit
handlers have a chance to run (#19297).
• Improvements to code generation (#19581).
• Fix a bug where levity monomorphic programs would be incorrectly rejected (#19522).
• Fix a typechecker bug which lead to an assertion failure while compiling certain pro-
grams with -XLinearTypes (#19400).
• Fix some RTS statistic calculations when using more than one thread with the parallel
GC (#19147).
• Fix a bug where an imported main function would not be recognised (#19397).
• Fix a bug where unboxed objects would be entered, leading to runtime crashes (#19645).
• Fix a regression causing compiler panics during the STG conversion (#19700).
• Disallow -XDerivingVia when -XSafe is on (#19786).
• Fix a bug where using magicDict in GHCi would lead to a crash (#19667).
• Fix a bug with the constructed product result (CPR) analysis involving usages of runRW#
(#19822).
• Fix a compiler performance issue causing exponential blowup during zonk-
ing/typechecking (#19668).
• Improve sharing of join points (#19996).
• Fix a compiler panic involving used existential type variables (#19849).
• Avoid including the path source file in the interface fingerprint, allowing interface files
to be more portable (#16956).
• Fix some timer races in the RTS possibly manifesting in #18033 and #20132.
• Fix a crash on the non-moving GC due to incorrect logic for calculating the header size
for array write barries (#19715).
• Fix a bug with the decoding of strings involving the null byte in the optimiser (#19976).
• Fix a bug with the parser leading to the incorrect rejection of programs mixing infix
operators and -XLexicalNegation (#19838).
• Export more functions from [Link] for use by plugin authors (#19864).
• Fix a bug in base leading to a high likelihood of space leaks when using lazy bytestrings.
(#20107).
• Fix some memory ordering issues manifesting on aarch64-darwin due to an RTS bug
(#20093).
• Fix a bug leading to typechecker errors being discarded inside splices (#20179,
#19470).
• Fix some spurious warnings arising from the interaction between -Wunused-packages
and reexported modules (#19518, #19777, #20242).
• Fix an RTS bug causing allocateExec to fail with certain versions of libffi (#20051).
• Fix an RTS bug resulting a crash m32_allocator_init: Failed to map (#19421).
• Stop leaking defunct llc processes (#20305).
• Fix an bug with the non moving GC leading to crashes due to missing write barriers
(#20399, #20414).
• Improve code generator performance by elminating a few thunks (#19471).
• Fix a memory leak when using GHCi with -fno-code (#20509).
• Fix a bug in the RTS linker where mmapForLinkerMarkExecutable could be called with
a zero-length argument, leading to undefined behaviouar (#20648).
• Fix a bug with the GC resulting in object code being prematurely collected leading to
runtime crashes (#20649).
• [Link]: Don’t use one-shot kqueue on macOS. This reverts a commit that
removed the workaround for a bug (#7651) in the OSX implementation of kqueue. It
turns out the bug still affects modern macOS versions, so we keep the workaround for
now. (#20662).
• Check the buffer size before calling the continuation in withEncodedCString (#20107).
• Pass -DLIBICONV_PLUG when building base library on FreeBSD (#19958).
• Make unsafeDupablePerformIO have a lazy demand (#19181).
• Fix accidental unsoundness in [Link]
(#19288).
• Fix an issue making GHC unable to build on FreeBSD due to an undefined reference to
libiconv. (#19958).
• Match the C calling convention on platforms like s390x by sign/zero extending parame-
ters for foreign calls. (#19023).
• Fix an issue resulting in build failures on certains platforms due to conflicting types for
environ (#20512).
• Fix xxHash duplicate symbol errors on FreeBSD. (#19948).
• Properly honour -fno-use-rpaths (page 218) on darwin. (#20004).
• Fix an issue causing libraries like network to fail building due to incorrect linker paths.
(#19968).
• Fix a linking portability issue on macOS that resulted in undefined symbol errors for
___darwin_check_fd_set_overflow (#19950).
• PowerPC: fix unsigned compare with 16-bit constants (#19852, #19609)
• Fix “undefined reference to libiconv” errors when compiling on FreeBSD (#19958)
• Allow the RTS to be compiled with a C++ compiler (#20394)
• Don’t rely on realpath in the binary distribution makefile (#19963)
• Fix “conflicting types for ‘environ’” error with certian glibc versions (#20512, #20577)
The package database provided with this distribution also contains a number of packages
other than GHC itself. See the changelogs provided with these packages for further change
information.
THREE
USING GHCI
GHCi 1 is GHC’s interactive environment that includes an interactive debugger (see The GHCi
Debugger (page 39)).
GHCi can
• interactively evaluate Haskell expressions
• interpret Haskell programs
• load GHC-compiled modules.
At the moment GHCi supports most of GHC’s language extensions.
Let’s start with an example GHCi session. You can fire up GHCi with the command ghci:
$ ghci
GHCi, version 8.y.z: [Link] :? for help
ghci>
There may be a short pause while GHCi loads the prelude and standard libraries, after which
the prompt is shown. As the banner says, you can type :? (page 55) to see the list of com-
mands available, and a half line description of each of them. We’ll explain most of these
commands as we go along, and there is complete documentation for all the commands in
GHCi commands (page 51).
Haskell expressions can be typed at the prompt:
ghci> 1+2
3
ghci> let x = 42 in x / 9
4.666666666666667
ghci>
GHCi interprets the whole line as an expression to evaluate. The expression may not span
several lines - as soon as you press enter, GHCi will attempt to evaluate it.
In Haskell, a let expression is followed by in. However, in GHCi, since the expression can
also be interpreted in the IO monad, a let binding with no accompanying in statement can
be signalled by an empty line, as in the above example.
Since GHC 8.0.1, you can bind values and functions to names without let statement:
1 The “i” stands for “Interactive”
23
GHC User’s Guide Documentation, Release 9.0.2
ghci> x = 42
ghci> x
42
ghci>
Suppose we have the following Haskell source code, which we place in a file [Link]:
fac 0 = 1
fac n = n * fac (n-1)
You can save [Link] anywhere you like, but if you save it somewhere other than the current
directory 3 then we will need to change to the right directory in GHCi:
where ⟨dir⟩ is the directory (or folder) in which you saved [Link].
To load a Haskell source file into GHCi, use the :load (page 57) command:
GHCi has loaded the Main module, and the prompt has changed to *ghci> to indicate that the
current context for expressions typed at the prompt is the Main module we just loaded (we’ll
explain what the * means later in What’s really in scope at the prompt? (page 32)). So we
can now type expressions involving the functions from [Link]:
*ghci> fac 17
355687428096000
Loading a multi-module program is just as straightforward; just give the name of the “topmost”
module to the :load (page 57) command (hint: :load (page 57) can be abbreviated to :l).
The topmost module will normally be Main, but it doesn’t have to be. GHCi will discover
which modules are required, directly or indirectly, by the topmost module, and load them all
in dependency order.
-fshow-loaded-modules
Default off
Since 8.2.2
Typically GHCi will show only the number of modules that it loaded after a :load
(page 57) command. With this flag, GHC will also list the loaded modules’ names. This
was the default behavior prior to GHC 8.2.1 and can be useful for some tooling users.
3 If you started up GHCi from the command line then GHCi’s current directory is the same as the current directory
of the shell from which it was started. If you started GHCi from the “Start” menu in Windows, then the current
directory is probably something like C:\Documents and Settings\user name.
Question: How does GHC find the filename which contains module ⟨M⟩? Answer: it looks for
the file [Link], or [Link]. This means that for most modules, the module name must match the
filename. If it doesn’t, GHCi won’t be able to find it.
There is one exception to this general rule: when you load a program with :load (page 57),
or specify it when you invoke ghci, you can give a filename rather than a module name. This
filename is loaded if it exists, and it may contain any module you like. This is particularly
convenient if you have several Main modules in the same directory and you can’t call them all
[Link].
The search path for finding source files is specified with the -i (page 176) option on the GHCi
command line, like so:
ghci -idir1:...:dirn
or it can be set using the :set (page 59) command from within GHCi (see Setting GHC
command-line options in GHCi (page 64)) 4
One consequence of the way that GHCi follows dependencies to find modules to load is that
every module must have a source file. The only exception to the rule is modules that come
from a package, including the Prelude and standard libraries such as IO and Complex. If you
attempt to load a module for which GHCi can’t find a source file, even if there are object and
interface files for the module, you’ll get an error message.
If you make some changes to the source code and want GHCi to recompile the program, give
the :reload (page 58) command. The program will be recompiled as necessary, with GHCi
doing its best to avoid actually recompiling modules if their external dependencies haven’t
changed. This is the same mechanism we use to avoid re-compiling modules in the batch
compilation setting (see The recompilation checker (page 180)).
When you load a Haskell source module into GHCi, it is normally converted to byte-code and
run using the interpreter. However, interpreted code can also run alongside compiled code
in GHCi; indeed, normally when GHCi starts, it loads up a compiled copy of the base package,
which contains the Prelude.
Why should we want to run compiled code? Well, compiled code is roughly 10x faster than
interpreted code, but takes about 2x longer to produce (perhaps longer if optimisation is on).
So it pays to compile the parts of a program that aren’t changing very often, and use the
interpreter for the code being actively developed.
When loading up source modules with :load (page 57), GHCi normally looks for any corre-
sponding compiled object files, and will use one in preference to interpreting the source if
possible. For example, suppose we have a 4-module program consisting of modules A, B, C,
and D. Modules B and C both import D only, and A imports both B and C:
4 Note that in GHCi, and --make (page 76) mode, the -i (page 176) option is used to specify the search path for
source files, whereas in standard batch-compilation mode the -i (page 176) option is used to specify the search path
for interface files, see The search path (page 176).
A
/ \
B C
\ /
D
In the messages from the compiler, we see that there is no line for D. This is because it isn’t
necessary to compile D, because the source and everything it depends on is unchanged since
the last compilation.
Note the -dynamic (page 218) flag to GHC: GHCi uses dynamically-linked object code (if you
are on a platform that supports it), and so in order to use compiled code with GHCi it must
be compiled for dynamic linking.
At any time you can use the command :show modules (page 61) to get a list of the modules
currently loaded into GHCi:
If we now modify the source of D (or pretend to: using the Unix command touch on the source
file is handy for this), the compiler will no longer be able to use the object file, because it might
be out of date:
Note that module D was compiled, but in this instance because its source hadn’t really
changed, its interface remained the same, and the recompilation checker determined that
A, B and C didn’t need to be recompiled.
So let’s try compiling one of the other modules:
We didn’t get the compiled version of C! What happened? Well, in GHCi a compiled module
may only depend on other compiled modules, and in this case C depends on D, which doesn’t
have an object file, so GHCi also rejected C‘s object file. Ok, so let’s also compile D:
Nothing happened! Here’s another lesson: newly compiled modules aren’t picked up by
:reload (page 58), only :load (page 57):
*ghci> :load A
Compiling B ( [Link], interpreted )
Compiling A ( [Link], interpreted )
Ok, modules loaded: A, B, C (C.o), D (D.o).
The automatic loading of object files can sometimes lead to confusion, because non-exported
top-level definitions of a module are only available for use in expressions at the prompt when
the module is interpreted (see What’s really in scope at the prompt? (page 32)). For this
reason, you might sometimes want to force GHCi to load a module using the interpreter. This
can be done by prefixing a * to the module name or filename when using :load (page 57), for
example
ghci> :load *A
Compiling A ( [Link], interpreted )
*ghci>
When the * is used, GHCi ignores any pre-compiled object code and interprets the module. If
you have already loaded a number of modules as object code and decide that you wanted to
interpret one of them, instead of re-loading the whole set you can use :add *M to specify that
you want M to be interpreted (note that this might cause other modules to be interpreted too,
because compiled modules cannot depend on interpreted ones).
To always compile everything to object code and never use the interpreter, use the -fobject-
code (page 216) option (see Compiling to object code inside GHCi (page 67)).
Hint: Since GHCi will only use a compiled object file if it can be sure that the compiled
version is up-to-date, a good technique when working on a large program is to occasionally
run ghc --make to compile the whole project (say before you go for lunch :-), then continue
working in the interpreter. As you modify code, the changed modules will be interpreted, but
the rest of the project will remain compiled.
When you type an expression at the prompt, GHCi immediately evaluates and prints the result:
GHCi does more than simple expression evaluation at the prompt. If you enter an expression
of type IO a for some a, then GHCi executes it as an IO-computation.
ghci> "hello"
"hello"
ghci> putStrLn "hello"
hello
This works even if the type of the expression is more general, provided it can be instantiated
to IO a. For example
Furthermore, GHCi will print the result of the I/O action if (and only if):
• The result type is an instance of Show.
• The result type is not ().
For example, remembering that putStrLn :: String -> IO ():
GHCi actually accepts statements rather than just expressions at the prompt. This means you
can bind values and functions to names, and use them in future expressions or statements.
The syntax of a statement accepted at the GHCi prompt is exactly the same as the syntax
of a statement in a Haskell do expression. However, there’s no monad overloading here:
statements typed at the prompt must be in the IO monad.
The statement x <-return 42 means “execute return 42 in the IO monad, and bind the
result to x”. We can then use x in future statements, for example to print it as we did above.
-fprint-bind-result
If -fprint-bind-result (page 28) is set then GHCi will print the result of a statement
if and only if:
•The statement is not a binding, or it is a monadic binding (p <-e) that binds exactly
one variable.
•The variable’s type is not polymorphic, is not (), and is an instance of Show.
Of course, you can also bind normal non-IO expressions using the let-statement:
ghci> let x = 42
ghci> x
42
ghci>
Another important difference between the two types of binding is that the monadic bind (p
<-e) is strict (it evaluates e), whereas with the let form, the expression isn’t evaluated imme-
diately:
Note that let bindings do not automatically print the value bound, unlike monadic bindings.
You can also define functions at the prompt:
ghci> add a b = a + b
ghci> add 1 2
3
ghci>
However, this quickly gets tedious when defining functions with multiple clauses, or groups
of mutually recursive functions, because the complete definition has to be given on a single
line, using explicit semicolons instead of layout:
:{
:}
Begin or end a multi-line GHCi command block.
To alleviate this issue, GHCi commands can be split over multiple lines, by wrapping them in
:{ and :} (each on a single line of its own):
ghci> :{
ghci| g op n [] = n
ghci| g op n (h:t) = h `op` g op n t
ghci| :}
ghci> g (*) 1 [1..3]
6
Such multiline commands can be used with any GHCi command, and note that the layout rule
is in effect. The main purpose of multiline commands is not to replace module loading but
to make definitions in .ghci-files (see The .ghci and .haskeline files (page 65)) more readable
and maintainable.
Any exceptions raised during the evaluation or execution of the statement are caught and
printed by the GHCi command line interface (for more information on exceptions, see the
module [Link] in the libraries documentation.
Every new binding shadows any existing bindings of the same name, including entities that
are in scope in the current module context.
Warning: Temporary bindings introduced at the prompt only last until the next :load
(page 57) or :reload (page 58) command, at which time they will be simply lost. However,
they do survive a change of context with :module (page 58): the temporary bindings just
move to the new location.
Hint: To get a list of the bindings currently in scope, use the :show bindings (page 60)
command:
Hint: If you turn on the +t option, GHCi will show the type of each variable bound by a
statement. For example:
ghci> :set +t
ghci> let (x:xs) = [1..]
x :: Integer
xs :: [Integer]
Apart from the :{ ... :} syntax for multi-line input mentioned above, GHCi also has a mul-
tiline mode, enabled by :set +m, :set +m in which GHCi detects automatically when the
current statement is unfinished and allows further lines to be added. A multi-line input is
terminated with an empty line. For example:
ghci> :set +m
ghci> let x = 42
ghci|
Further bindings can be added to this let statement, so GHCi indicates that the next line
continues the previous one by changing the prompt. Note that layout is in effect, so to add
more bindings to this let we have to line them up:
ghci> :set +m
ghci> let x = 42
ghci| y = 3
ghci|
ghci>
ghci> do {
ghci| putStrLn "hello"
ghci| ;putStrLn "world"
ghci| }
hello
world
ghci>
Note that after the closing brace, GHCi knows that the current statement is finished, so no
empty line is required.
Multiline mode is useful when entering monadic do statements:
During a multiline interaction, the user can interrupt and return to the top-level prompt.
ghci> do
ghci| putStrLn "Hello, World!"
ghci| ^C
ghci>
At the GHCi prompt you can also enter any top-level Haskell declaration, including data, type,
newtype, class, instance, deriving, and foreign declarations. For example:
As with ordinary variable bindings, later definitions shadow earlier ones, so you can re-enter
a declaration to fix a problem with it or extend it. But there’s a gotcha: when a new type
declaration shadows an older one, there might be other declarations that refer to the old
type. The thing to remember is that the old type still exists, and these other declarations still
refer to the old type. However, while the old and the new type have the same name, GHCi
will treat them as distinct. For example:
ghci> data T = A | B
ghci> let f A = True; f B = False
ghci> data T = A | B | C
ghci> f A
<interactive>:2:3:
Couldn't match expected type `main::Interactive.T'
with actual type `T'
In the first argument of `f', namely `A'
In the expression: f A
In an equation for `it': it = f A
ghci>
<interactive>:3:15: error:
Conflicting family instance declarations:
T a b = a -- Defined at <interactive>:3:15
T a b = b -- Defined at <interactive>:5:15
<interactive>:8:1: error:
• Couldn't match type ‘Char’ with ‘Int’
Expected type: Int
Actual type: Ghci1.T Char b0
• In the expression: uc 'a' :: Int
In an equation for ‘it’: it = uc 'a' :: Int
When you type an expression at the prompt, what identifiers and types are in scope? GHCi
provides a flexible way to control exactly how the context for an expression is constructed:
• The :load (page 57), :add (page 51), and :reload (page 58) commands (The effect of
:load on what is in scope (page 33)).
• The import declaration (Controlling what is in scope with import (page 33)).
• The :module (page 58) command (Controlling what is in scope with the :module com-
mand (page 34)).
The command :show imports (page 61) will show a summary of which modules contribute
to the top-level scope.
Hint: GHCi will tab-complete names that are in scope; for example, if you run GHCi and
type J<tab> then GHCi will expand it to Just.
The :load (page 57), :add (page 51), and :reload (page 58) commands (Loading source files
(page 24) and Loading compiled code (page 25)) affect the top-level scope. Let’s start with
the simple cases; when you start GHCi the prompt looks like this:
ghci>
By default, this means that everything from the module Prelude is currently in scope. Should
the prompt be set to %s> in the .ghci configuration file, we would be seeing Prelude> dis-
played. However, it is not the default mechanism due to the large space the prompt can take
if more imports are done.
The syntax in the prompt *module indicates that it is the full top-level scope of ⟨module⟩ that is
contributing to the scope for expressions typed at the prompt. Without the *, just the exports
of the module are visible.
Note: For technical reasons, GHCi can only support the *-form for modules that are in-
terpreted. Compiled modules and package modules can only contribute their exports to the
current scope. To ensure that GHCi loads the interpreted version of a module, add the * when
loading the module, e.g. :load *M.
In general, after a :load (page 57) command, an automatic import is added to the scope for
the most recently loaded “target” module, in a *-form if possible. For example, if you say
:load [Link] [Link] and [Link] contains module Bar, then the scope will be set to *Bar if
Bar is interpreted, or if Bar is compiled it will be set to Prelude and Bar (GHCi automatically
adds Prelude if it isn’t present and there aren’t any *-form modules). These automatically-
added imports can be seen with :show imports (page 61):
and the automatically-added import is replaced the next time you use :load (page 57), :add
(page 51), or :reload (page 58). It can also be removed by :module (page 58) as with normal
imports.
We are not limited to a single module: GHCi can combine scopes from multiple modules, in
any mixture of * and non-* forms. GHCi combines the scopes from all of these modules to
form the scope that is in effect at the prompt.
To add modules to the scope, use ordinary Haskell import syntax:
The full Haskell import syntax is supported, including hiding and as clauses. The prompt
shows the modules that are currently imported, but it omits details about hiding, as, and so
on. To see the full story, use :show imports (page 61):
Note that the Prelude import is marked as implicit. It can be overridden with an explicit
Prelude import, just like in a Haskell module.
With multiple modules in scope, especially multiple *-form modules, it is likely that name
clashes will occur. Haskell specifies that name clashes are only reported when an ambiguous
identifier is used, and GHCi behaves in the same way for expressions typed at the prompt.
Another way to manipulate the scope is to use the :module (page 58) command, whose syntax
is this:
Using the + form of the module commands adds modules to the current scope, and - removes
them. Without either + or -, the current scope is replaced by the set of modules specified.
Note that if you use this form and leave out Prelude, an implicit Prelude import will be added
automatically.
The :module (page 58) command provides a way to do two things that cannot be done with
ordinary import declarations:
• :module (page 58) supports the * modifier on modules, which opens the full top-level
scope of a module, rather than just its exports.
• Imports can be removed from the context, using the syntax :module -M. The import
syntax is cumulative (as in a Haskell module), so this is the only way to subtract from
the scope.
Qualified names
To make life slightly easier, the GHCi prompt also behaves as if there is an implicit import
qualified declaration for every module in every package, and every module currently loaded
into GHCi. This behaviour can be disabled with the -fno-implicit-import-qualified flag.
It might seem that :module (page 58)/import and :load (page 57)/:add (page 51)/:reload
(page 58) do similar things: you can use both to bring a module into scope. However, there
is a very important difference. GHCi is concerned with two sets of modules:
• The set of modules that are currently loaded. This set is modified by :load (page 57),
:add (page 51) and :reload (page 58), and can be shown with :show modules (page 61).
• The set of modules that are currently in scope at the prompt. This set is modified by
import and :module (page 58), and it is also modified automatically after :load (page 57),
:add (page 51), and :reload (page 58), as described above. The set of modules in scope
can be shown with :show imports (page 61).
You can add a module to the scope (via :module (page 58) or import) only if either (a) it is
loaded, or (b) it is a module from a package that GHCi knows about. Using :module (page 58)
or import to try bring into scope a non-loaded module may result in the message module M
is not loaded.
When a program is compiled and executed, it can use the getArgs function to access the
command-line arguments. However, we cannot simply pass the arguments to the main func-
tion while we are testing in ghci, as the main function doesn’t take its directly.
Instead, we can use the :main (page 58) command. This runs whatever main is in scope, with
any arguments being treated the same as command-line arguments, e.g.:
We can also quote arguments which contains characters like spaces, and they are treated like
Haskell strings, or we can just use Haskell list syntax:
Finally, other functions can be called, either with the -main-is flag or the :run (page 59)
command:
ghci> 1+2
3
ghci> it * 2
6
What actually happens is that GHCi typechecks the expression, and if it doesn’t have an IO
type, then it transforms it as follows: an expression e turns into
let it = e;
print it
<interactive>:1:0:
No instance for (Show (a -> a))
arising from use of `print' at <interactive>:1:0-1
Possible fix: add an instance declaration for (Show (a -> a))
In the expression: print it
In a 'do' expression: print it
The error message contains some clues as to the transformation happening internally.
If the expression was instead of type IO a for some a, then it will be bound to the result of
the IO computation, which is of type a. eg.:
ghci> [Link]
2017-04-10 12:34:56.93213581 UTC
ghci> print it
2017-04-10 12:34:56.93213581 UTC
Note that it is shadowed by the new value each time you evaluate a new expression, and the
old value of it is lost.
In order to stop the value it being bound on each command, the flag -fno-it (page 36) can
be set. The it variable can be the source of space leaks due to how shadowed declarations
are handled by GHCi (see Type, class and other declarations (page 31)).
-fno-it
When this flag is set, the variable it will no longer be set to the result of the previously
evaluated expression.
ExtendedDefaultRules
Since 6.8.1
Allow defaulting to take place for more than just numeric classes.
Consider this GHCi session:
ghci> reverse []
What should GHCi do? Strictly speaking, the program is ambiguous. show (reverse [])
(which is what GHCi computes here) has type Show a => String and how that displays de-
pends on the type a. For example:
ghci> reverse ([] :: String)
""
ghci> reverse ([] :: [Int])
[]
However, it is tiresome for the user to have to specify the type, so GHCi extends Haskell’s
type-defaulting rules (Section 4.3.4 of the Haskell 2010 Report) as follows. The standard rules
take each group of constraints (C1 a,C2 a,...,Cn a) for each type variable a, and defaults
the type variable if
1. The type variable a appears in no other constraints
2. All the classes Ci are standard.
3. At least one of the classes Ci is numeric.
At the GHCi prompt, or with GHC if the ExtendedDefaultRules (page 36) flag is given, the
types are instead resolved with the following method:
Find all the unsolved constraints. Then:
• Find those that are of form (C a) where a is a type variable, and partition those con-
straints into groups that share a common type variable a.
• Keep only the groups in which at least one of the classes is an interactive class (defined
below).
• Now, for each remaining group G, try each type ty from the default-type list in turn; if
setting a = ty would allow the constraints in G to be completely solved. If so, default a
to ty.
• The unit type () and the list type [] are added to the start of the standard list of types
which are tried when doing type defaulting.
Note that any multi-parameter constraints (D a b) or (D [a] Int) do not participate in the
process (either to help or to hinder); but they must of course be soluble once the defaulting
process is complete.
The last point means that, for example, this program:
main :: IO ()
main = print def
instance Num ()
Interactive classes
The interactive classes (only relevant when ExtendedDefaultRules (page 36) is in effect) are:
any numeric class, Show, Eq, Ord, Foldable or Traversable.
As long as a type variable is constrained by one of these classes, defaulting will occur, as
outlined above.
Since the rules for defaulting are relaxed under ExtendedDefaultRules (page 36), the rules
for default declarations are also relaxed. According to Section 4.3.4 of the Haskell 2010
Report, a default declaration looks like default (t1,...,tn) where, for each ti, Num ti
must hold. This is relaxed to say that for each ti, there must exist an interactive class C such
that C ti holds. This means that type constructors can be allowed in these lists. For example,
the following works if you wish your Foldable constraints to default to Maybe but your Num
constraints to still default to Integer or Double:
Since GHC 7.6.1, GHCi prints the result of expressions typed at the prompt using the function
[Link]. Its type signature is Show a => a -> IO (), and it works by converting
the value to String using show.
This is not ideal in certain cases, like when the output is long, or contains strings with non-
ascii characters.
The -interactive-print ⟨name⟩ (page 38) flag allows to specify any function of type C a =>
a -> IO (), for some constraint C, as the function for printing evaluated expressions. The
function can reside in any loaded module or any registered package, but only when it resides
in a registered package will it survive a :cd (page 52), :add (page 51), :load (page 57),
:reload (page 58) or, :set (page 59).
-interactive-print ⟨name⟩
Set the function used by GHCi to print evaluation results. Given name must be of type C
a => a -> IO ().
As an example, suppose we have following special printing module:
The sprint function adds an exclamation mark at the end of any printed value. Running GHCi
with the command:
will start an interactive session where values with be printed using sprint:
*SpecPrinter> [1,2,3]
[1,2,3]!
*SpecPrinter> 42
42!
A custom pretty printing function can be used, for example, to format tree-like and nested
structures in a more readable way.
The -interactive-print ⟨name⟩ (page 38) flag can also be used when running GHC in -e
mode:
[ This is an experimental feature enabled by the new -fexternal-interpreter flag that was
introduced in GHC 8.0.1. It is currently not supported on Windows.]
GHCi can use the profiling system to collect stack trace information when running interpreted
code. To gain access to stack traces, start GHCi like this:
This runs the interpreted code in a separate process (see Running the interpreter in a separate
process (page 67)) and runs it in profiling mode to collect call stack information. Note that
because we’re running the interpreted code in profiling mode, all packages that you use must
be compiled for profiling. The -prof flag to GHCi only works in conjunction with -fexternal-
interpreter.
There are three ways to get access to the current call stack.
• error and undefined automatically attach the current stack to the error message. This
often complements the HasCallStack stack (see HasCallStack (page 515)), so both call
stacks are shown.
• [Link] is a version of [Link] that also prints the current
call stack.
• Functions in the module [Link] can be used to get the current stack and render it.
You don’t need to use -fprof-auto for interpreted modules, annotations are automatically
added at a granularity fine enough to distinguish individual call sites. However, you won’t
see any call stack information for compiled code unless it was compiled with -fprof-auto or
has explicit SCC annotations (see Inserting cost centres by hand (page 555)).
GHCi contains a simple imperative-style debugger in which you can stop a running computa-
tion in order to examine the values of variables. The debugger is integrated into GHCi, and
is turned on by default: no flags are required to enable the debugging facilities. There is one
major restriction: breakpoints and single-stepping are only available in interpreted modules;
compiled code is invisible to the debugger 5 .
The debugger provides the following:
• The ability to set a breakpoint on a function definition or expression in the program.
When the function is called, or the expression evaluated, GHCi suspends execution and
returns to the prompt, where you can inspect the values of local variables before contin-
uing with the execution.
5 Note that packages only contain compiled code, so debugging a package requires finding its source and loading
that directly.
qsort [] = []
qsort (a:as) = qsort left ++ [a] ++ qsort right
where (left,right) = (filter (<=a) as, filter (>a) as)
ghci> :l [Link]
[1 of 1] Compiling Main ( [Link], interpreted )
Ok, modules loaded: Main.
*ghci>
Now, let’s set a breakpoint on the right-hand-side of the second equation of qsort:
*ghci> :break 2
Breakpoint 0 activated at [Link]:15-46
*ghci>
The command :break 2 sets a breakpoint on line 2 of the most recently-loaded module, in
this case [Link]. Specifically, it picks the leftmost complete subexpression on that line
on which to set the breakpoint, which in this case is the expression (qsort left ++ [a] ++
qsort right).
Now, we run the program:
*ghci> main
Stopped at [Link]:15-46
_result :: [a]
a :: a
left :: [a]
right :: [a]
[[Link]:15-46] *ghci>
Execution has stopped at the breakpoint. The prompt has changed to indicate that we are
currently stopped at a breakpoint, and the location: [[Link]:15-46]. To further clarify
the location, we can use the :list (page 57) command:
The :list (page 57) command lists the source code around the current breakpoint. If your
output device supports it, then GHCi will highlight the active subexpression in bold.
GHCi has provided bindings for the free variables 6 of the expression on which the break-
point was placed (a, left, right), and additionally a binding for the result of the expression
(_result). These variables are just like other variables that you might define in GHCi; you
can use them in expressions that you type at the prompt, you can ask for their types with
:type (page 61), and so on. There is one important difference though: these variables may
only have partial types. For example, if we try to display the value of left:
<interactive>:1:0:
Ambiguous type variable `a' in the constraint:
`Show a' arising from a use of `print' at <interactive>:1:0-3
Cannot resolve unknown runtime types: a
Use :print or :force to determine these types
This is because qsort is a polymorphic function, and because GHCi does not carry type infor-
mation at runtime, it cannot determine the runtime types of free variables that involve type
variables. Hence, when you ask to display left at the prompt, GHCi can’t figure out which
instance of Show to use, so it emits the type error above.
Fortunately, the debugger includes a generic printing command, :print (page 58), which can
inspect the actual runtime value of a variable and attempt to reconstruct its type. If we try it
on left:
This isn’t particularly enlightening. What happened is that left is bound to an unevaluated
computation (a suspension, or thunk), and :print (page 58) does not force any evaluation.
The idea is that :print (page 58) can be used to inspect values at a breakpoint without
any unfortunate side effects. It won’t force any evaluation, which could cause the program
to give a different answer than it would normally, and hence it won’t cause any exceptions
to be raised, infinite loops, or further breakpoints to be triggered (see Nested breakpoints
(page 45)). Rather than forcing thunks, :print (page 58) binds each thunk to a fresh variable
beginning with an underscore, in this case _t1.
-fprint-evld-with-show
The flag -fprint-evld-with-show (page 41) instructs :print (page 58) to reuse avail-
able Show instances when possible. This happens only when the contents of the variable
being inspected are completely evaluated.
If we aren’t concerned about preserving the evaluatedness of a variable, we can use :force
(page 55) instead of :print (page 58). The :force (page 55) command behaves exactly like
:print (page 58), except that it forces the evaluation of any thunks it encounters:
6 We originally provided bindings for all variables in scope, rather than just the free variables of the expression,
but found that this affected performance considerably, hence the current restriction to just the free variables.
Now, since :force (page 55) has inspected the runtime value of left, it has reconstructed
its type. We can see the results of this type reconstruction:
Not only do we now know the type of left, but all the other partial types have also been
resolved. So we can ask for the value of a, for example:
[[Link]:15-46] *ghci> a
8
You might find it useful to use Haskell’s seq function to evaluate individual thunks rather than
evaluating the whole expression with :force (page 55). For example:
We evaluated only the _t1 thunk, revealing the head of the list, and the tail is another thunk
now bound to _t2. The seq function is a little inconvenient to use here, so you might want to
use :def (page 54) to make a nicer interface (left as an exercise for the reader!).
Finally, we can continue the current execution:
The execution continued at the point it previously stopped, and has now stopped at the break-
point for a second time.
Setting breakpoints
Breakpoints can be set in various ways. Perhaps the easiest way to set a breakpoint is to
name a top-level function:
:break identifier
Where ⟨identifier⟩ names any top-level function in an interpreted module currently loaded into
GHCi (qualified names may be used). The breakpoint will be set on the body of the function,
when it is fully applied. If the function has several patterns, then a breakpoint will be set on
each of them.
By using qualified names, one can set breakpoints on all functions (top-level and nested) in
every loaded and interpreted module:
:break [ModQual.]topLevelIdent[.nestedIdent]...[.nestedIdent]
⟨ModQual⟩ is optional and is either the effective name of a module or the local alias of a
qualified import statement.
⟨topLevelIdent⟩ is the name of a top level function in the module referenced by ⟨ModQual⟩.
⟨nestedIdent⟩ is optional and the name of a function nested in a let or where clause inside the
previously mentioned function ⟨nestedIdent⟩ or ⟨topLevelIdent⟩.
If ⟨ModQual⟩ is a module name, then ⟨topLevelIdent⟩ can be any top level identifier in this
module. If ⟨ModQual⟩ is missing or a local alias of a qualified import, then ⟨topLevelIdent⟩
must be in scope.
Breakpoints can be set on arbitrarily deeply nested functions, but the whole chain of nested
function names must be specified.
Consider the function foo in a module Main:
The breakpoint on the function add can be set with one of the following commands:
:break [Link]
:break [Link]
:break line
:break line column
:break module line
:break module line column
When a breakpoint is set on a particular line, GHCi sets the breakpoint on the leftmost subex-
pression that begins and ends on that line. If two complete subexpressions start at the same
column, the longest one is picked. If there is no complete subexpression on the line, then the
leftmost expression starting on the line is picked, and failing that the rightmost expression
that partially or completely covers the line.
When a breakpoint is set on a particular line and column, GHCi picks the smallest subexpres-
sion that encloses that location on which to set the breakpoint. Note: GHC considers the TAB
character to have a width of 1, wherever it occurs; in other words it counts characters, rather
than columns. This matches what some editors do, and doesn’t match others. The best advice
is to avoid tab characters in your source code altogether (see -Wtabs (page 99) in Warnings
and sanity-checking (page 85)).
If the module is omitted, then the most recently-loaded module is used.
Not all subexpressions are potential breakpoint locations. Single variables are typically not
considered to be breakpoint locations (unless the variable is the right-hand-side of a function
definition, lambda, or case alternative). The rule of thumb is that all redexes are breakpoint
locations, together with the bodies of functions, lambdas, case alternatives and binding state-
ments. There is normally no breakpoint on a let expression, but there will always be a break-
point on its body, because we are usually interested in inspecting the values of the variables
bound by the let.
Managing breakpoints
The list of breakpoints currently defined can be displayed using :show breaks (page 61):
To disable one or several defined breakpoint, use the :disable (page 55) command with one
or several blank separated numbers given in the output from :show breaks (page 61):. To
disable all breakpoints at once, use :disable *.
*ghci> :disable 0
*ghci> :show breaks
[0] Main [Link]:11-12 disabled
[1] Main [Link]:15-46 enabled
Disabled breakpoints can be (re-)enabled with the :enable (page 55) command. The param-
eters of the :disable (page 55) and :enable (page 55) commands are identical.
To delete a breakpoint, use the :delete (page 55) command with the number given in the
output from :show breaks (page 61):
*ghci> :delete 0
*ghci> :show breaks
[1] Main [Link]:15-46 disabled
3.5.2 Single-stepping
Single-stepping is a great way to visualise the execution of your program, and it is also a
useful tool for identifying the source of a bug. GHCi offers two variants of stepping. Use
:step (page 61) to enable all the breakpoints in the program, and execute until the next
breakpoint is reached. Use :steplocal (page 61) to limit the set of enabled breakpoints to
those in the current top level function. Similarly, use :stepmodule (page 61) to single step
only on breakpoints contained in the current module. For example:
The command :step expr (page 61) begins the evaluation of ⟨expr⟩ in single-stepping mode.
If ⟨expr⟩ is omitted, then it single-steps from the current breakpoint. :steplocal (page 61)
and :stepmodule (page 61) commands work similarly.
The :list (page 57) command is particularly useful when single-stepping, to see where you
currently are:
In fact, GHCi provides a way to run a command when a breakpoint is hit, so we can make it
automatically do :list (page 57):
When GHCi is stopped at a breakpoint, and an expression entered at the prompt triggers a
second breakpoint, the new breakpoint becomes the “current” one, and the old one is saved
on a stack. An arbitrary number of breakpoint contexts can be built up in this way. For
example:
While stopped at the breakpoint on line 2 that we set earlier, we started a new evaluation with
:step qsort [1,3]. This new evaluation stopped after one step (at the definition of qsort).
The prompt has changed, now prefixed with ..., to indicate that there are saved breakpoints
beyond the current one. To see the stack of contexts, use :show context (page 61):
When stopped at a breakpoint or single-step, GHCi binds the variable _result to the value of
the currently active expression. The value of _result is presumably not available yet, because
we stopped its evaluation, but it can be forced: if the type is known and showable, then
just entering _result at the prompt will show it. However, there’s one caveat to doing this:
evaluating _result will be likely to trigger further breakpoints, starting with the breakpoint
we are currently stopped at (if we stopped at a real breakpoint, rather than due to :step
(page 61)). So it will probably be necessary to issue a :continue (page 54) immediately when
evaluating _result. Alternatively, you can use :force (page 55) which ignores breakpoints.
A question that we often want to ask when debugging a program is “how did I get here?”.
Traditional imperative debuggers usually provide some kind of stack-tracing feature that lets
you see the stack of active function calls (sometimes called the “lexical call stack”), describ-
ing a path through the code to the current location. Unfortunately this is hard to provide
in Haskell, because execution proceeds on a demand-driven basis, rather than a depth-first
basis as in strict languages. The “stack“ in GHC’s execution engine bears little resemblance
to the lexical call stack. Ideally GHCi would maintain a separate lexical call stack in addition
to the dynamic call stack, and in fact this is exactly what our profiling system does (Profiling
(page 553)), and what some other Haskell debuggers do. For the time being, however, GHCi
doesn’t maintain a lexical call stack (there are some technical challenges to be overcome).
Instead, we provide a way to backtrack from a breakpoint to previous evaluation steps: es-
sentially this is like single-stepping backwards, and should in many cases provide enough
information to answer the “how did I get here?” question.
To use tracing, evaluate an expression with the :trace (page 61) command. For example, if
we set a breakpoint on the base case of qsort:
-14 : [Link]:15-24
-15 : [Link]:15-46
-16 : [Link]:(1,0)-(3,55)
<end of history>
To examine one of the steps in the history, use :back (page 52):
Note that the local variables at each step in the history have been preserved, and can be
examined as usual. Also note that the prompt has changed to indicate that we’re currently
examining the first step in the history: -1. The command :forward (page 55) can be used to
traverse forward in the history.
The :trace (page 61) command can be used with or without an expression. When used with-
out an expression, tracing begins from the current breakpoint, just like :step (page 61).
The history is only available when using :trace (page 61); the reason for this is we found that
logging each breakpoint in the history cuts performance by a factor of 2 or more.
-fghci-hist-size=⟨n⟩
Default 50
Modify the depth of the evaluation history tracked by GHCi.
Another common question that comes up when debugging is “where did this exception come
from?”. Exceptions such as those raised by error or head [] have no context information
attached to them. Finding which particular call to head in your program resulted in the
error can be a painstaking process, usually involving [Link], or compiling with
profiling and using [Link] or +RTS -xc (see -xc (page 172)).
The GHCi debugger offers a way to hopefully shed some light on these errors quickly and
without modifying or recompiling the source code. One way would be to set a breakpoint on
the location in the source code that throws the exception, and then use :trace (page 61) and
:history (page 55) to establish the context. However, head is in a library and we can’t set
a breakpoint on it directly. For this reason, GHCi provides the flags -fbreak-on-exception
(page 48) which causes the evaluator to stop when an exception is thrown, and -fbreak-on-
error (page 48), which works similarly but stops only on uncaught exceptions. When stopping
at an exception, GHCi will act just as it does when a breakpoint is hit, with the deviation that it
will not show you any source code location. Due to this, these commands are only really useful
in conjunction with :trace (page 61), in order to log the steps leading up to the exception.
For example:
-2 : [Link]:23-55
-3 : [Link]:(1,0)-(3,55)
-4 : [Link]:15-24
-5 : [Link]:15-46
-6 : [Link]:(1,0)-(3,55)
<end of history>
[<exception thrown>] *ghci> :back
Logged breakpoint at [Link]:24-38
_result :: [a]
as :: [a]
a :: a
[-1: [Link]:24-38] *ghci> :force as
*** Exception: [Link]
[-1: [Link]:24-38] *ghci> :print as
as = 'b' : 'c' : (_t1::[Char])
It is possible to use the debugger to examine function values. When we are at a breakpoint
and a function is in scope, the debugger cannot show you the source code for it; however, it is
possible to get some information by applying it to some arguments and observing the result.
The process is slightly complicated when the binding is polymorphic. We show the process
by means of an example. To keep things simple, we will use the well known map function:
*ghci> :break 5
Breakpoint 0 activated at [Link]:15-28
*ghci> map Just [1..5]
Stopped at [Link]:(4,0)-(5,12)
_result :: [b]
x :: a
f :: a -> b
xs :: [a]
GHCi tells us that, among other bindings, f is in scope. However, its type is not fully known
yet, and thus it is not possible to apply it to any arguments. Nevertheless, observe that the
type of its first argument is the same as the type of x, and its result type is shared with
_result.
As we demonstrated earlier (Breakpoints and inspecting variables (page 40)), the debugger
has some intelligence built-in to update the type of f whenever the types of x or _result are
discovered. So what we do in this scenario is force x a bit, in order to recover both its type
and the argument part of f.
*ghci> seq x ()
*ghci> :print x
x = 1
We can check now that as expected, the type of x has been reconstructed, and with it the type
of f has been too:
*ghci> :t x
x :: Integer
*ghci> :t f
f :: Integer -> b
From here, we can apply f to any argument of type Integer and observe the results.
*ghci> let b = f 10
*ghci> :t b
b :: b
*ghci> b
<interactive>:1:0:
Ambiguous type variable `b' in the constraint:
`Show b' arising from a use of `print' at <interactive>:1:0
*ghci> :p b
b = (_t2::a)
*ghci> seq b ()
()
*ghci> :t b
b :: a
*ghci> :p b
b = Just 10
*ghci> :t b
b :: Maybe Integer
*ghci> :t f
f :: Integer -> Maybe Integer
*ghci> f 20
Just 20
*ghci> map f [1..5]
[Just 1, Just 2, Just 3, Just 4, Just 5]
In the first application of f, we had to do some more type reconstruction in order to recover
the result type of f. But after that, we are free to use f normally.
3.5.8 Limitations
• When stopped at a breakpoint, if you try to evaluate a variable that is already under
evaluation, the second evaluation will hang. The reason is that GHC knows the variable
is under evaluation, so the new evaluation just waits for the result before continuing, but
of course this isn’t going to happen because the first evaluation is stopped at a breakpoint.
Control-C can interrupt the hung evaluation and return to the prompt.
The most common way this can happen is when you’re evaluating a CAF (e.g. main),
stop at a breakpoint, and ask for the value of the CAF at the prompt again.
• Implicit parameters (see Implicit parameters (page 441)) are only available at the scope
of a breakpoint if there is an explicit type signature.
GHCi is invoked with the command ghci or ghc --interactive. One or more modules or
filenames can also be specified on the command line; this instructs GHCi to load the specified
modules or filenames (and all the modules they depend on), just as if you had said :load
modules at the GHCi prompt (see GHCi commands (page 51)). For example, to start GHCi
and load the program whose topmost module is in the file [Link], we could say:
$ ghci [Link]
Most of the command-line options accepted by GHC (see Using GHC (page 73)) also make
sense in interactive mode. The ones that don’t make sense are mostly obvious.
-flocal-ghci-history
By default, GHCi keeps global history in ~/.ghc/ghci_history or %APP-
DATA%/<app>/ghci_history, but you can use current directory, e.g.:
$ ghci -flocal-ghci-history
3.6.1 Packages
Most packages (see Using Packages (page 193)) are available without needing to specify any
extra flags at all: they will be automatically loaded the first time they are needed.
For hidden packages, however, you need to request the package be loaded by using the -
package ⟨pkg⟩ (page 194) flag:
The following command works to load new packages into a running GHCi:
But note that doing this will cause all currently loaded modules to be unloaded, and you’ll be
dumped back into the Prelude.
Extra libraries may be specified on the command line using the normal -llib option. (The
term library here refers to libraries of foreign object code; for using libraries of Haskell source
code, see Modules vs. filenames (page 25).) For example, to load the “m” library:
$ ghci -lm
On systems with .so-style shared libraries, the actual library loaded will the [Link]. GHCi
searches the following places for libraries, in this order:
• Paths specified using the -L ⟨dir⟩ (page 218) command-line option,
• The standard library search path for your system loader, which on some systems may be
overridden by setting the LD_LIBRARY_PATH environment variable.
• The linker standard library search can also be overridden on some systems using the LI-
BRARY_PATH environment variable. Because of some implementation detail on Windows,
setting LIBRARY_PATH will also extend the system loader path for any library it finds. So
often setting LIBRARY_PATH is enough.
On systems with .dll-style shared libraries, the actual library loaded will be [Link], lib-
[Link]. GHCi also has full support for import libraries, either Microsoft style .lib, or GNU
GCC style .a and .dll.a libraries. If you have an import library it is advisable to always spec-
ify the import library instead of the .dll. e.g. use -lgcc` instead of ``-llibgcc_s_seh-1.
Again, GHCi will signal an error if it can’t find the library.
GHCi can also load plain object files (.o or .obj depending on your platform) or static archives
(.a) from the command-line. Just add the name the object file or library to the command line.
On Windows GHCi also supports the big-obj format.
Ordering of -l options matters: a library should be mentioned before the libraries it depends
on (see Options affecting linking (page 217)).
GHCi commands all begin with “:” and consist of a single command name followed by zero or
more parameters. The command name may be abbreviated, with ambiguities being resolved
in favour of the more commonly used commands.
:abandon
Abandons the current evaluation (only available when stopped at a breakpoint).
:add[*] ⟨module⟩
Add ⟨module⟩(s) to the current target set, and perform a reload. Normally pre-compiled
code for the module will be loaded if available, or otherwise the module will be compiled
to byte-code. Using the * prefix forces the module to be loaded as byte-code.
⟨module⟩ may be a file path. A “~” symbol at the beginning of ⟨module⟩ will be replaced
by the contents of the environment variable HOME.
:all-types
List all types collected for expressions and (local) bindings currently loaded (while :set
+c (page 63) was active) with their respective source-code span, e.g.
GhciTypes> :all-types
[Link]:(38,13)-(38,24): Maybe Id
:back ⟨n⟩
Travel back ⟨n⟩ steps in the history. ⟨n⟩ is one if omitted. See Tracing and history
(page 46) for more about GHCi’s debugging facilities. See also: :trace (page 61), :his-
tory (page 55), :forward (page 55).
:break [⟨identifier⟩ | [⟨module⟩] ⟨line⟩ [⟨column⟩]]
Set a breakpoint on the specified function or line and column. See Setting breakpoints
(page 42).
:browse[!] [[*] ⟨module⟩]
Displays the identifiers exported by the module ⟨module⟩, which must be either loaded
into GHCi or be a member of a package. If ⟨module⟩ is omitted, the most recently-loaded
module is used.
Like all other GHCi commands, the output is always displayed in the current GHCi scope
(What’s really in scope at the prompt? (page 32)).
There are two variants of the browse command:
•If the * symbol is placed before the module name, then all the identifiers in scope in
⟨module⟩ (rather that just its exports) are shown.
The *-form is only available for modules which are interpreted; for compiled mod-
ules (including modules from packages) only the non-* form of :browse (page 52) is
available.
•Data constructors and class methods are usually displayed in the context of their
data type or class declaration. However, if the ! symbol is appended to the command,
thus :browse!, they are listed individually. The !-form also annotates the listing with
comments giving possible imports for each group of entries. Here is an example:
This output shows that, in the context of the current session (ie in the scope of
Prelude), the first group of items from [Link] are not in scope (although they
are available in fully qualified form in the GHCi session - see What’s really in scope
at the prompt? (page 32)), whereas the second group of items are in scope (via
Prelude) and are therefore available either unqualified, or with a Prelude. qualifier.
:cd ⟨dir⟩
Changes the current working directory to ⟨dir⟩. A “~” symbol at the beginning of ⟨dir⟩
will be replaced by the contents of the environment variable HOME. See also the :show
paths (page 61) command for showing the current working directory.
Note: changing directories causes all currently loaded modules to be unloaded. This is
because the search path is usually expressed using relative directories, and changing
the search path in the middle of a session is not supported.
:cmd ⟨expr⟩
Executes ⟨expr⟩ as a computation of type IO String, and then executes the resulting
string as a list of GHCi commands. Multiple commands are separated by newlines. The
:cmd (page 53) command is useful with :def (page 54) and :set stop (page 60).
:complete ⟨type⟩ [⟨n⟩-][⟨m⟩] ⟨string-literal⟩
This command allows to request command completions from GHCi even when interacting
over a pipe instead of a proper terminal and is designed for integrating GHCi’s comple-
tion with text editors and IDEs.
When called, :complete (page 53) prints the ⟨n⟩th to ⟨m⟩th completion candidates for
the partial input ⟨string-literal⟩ for the completion domain denoted by ⟨type⟩. Currently,
only the repl domain is supported which denotes the kind of completion that would be
provided interactively by GHCi at the input prompt.
If omitted, ⟨n⟩ and ⟨m⟩ default to the first or last available completion candidate respec-
tively. If there are less candidates than requested via the range argument, ⟨n⟩ and ⟨m⟩
are implicitly capped to the number of available completion candidates.
The output of :complete (page 53) begins with a header line containing three space-
delimited fields:
•An integer denoting the number l of printed completions,
•an integer denoting the total number of completions available, and finally
•a string literal denoting a common prefix to be added to the returned completion
candidates.
The header line is followed by ⟨l⟩ lines each containing one completion candidate encoded
as (quoted) string literal. Here are some example invocations showing the various cases:
ghci> :complete repl 0 ""
0 470 ""
ghci> :complete repl 5 "import For"
5 21 "import "
"Foreign"
"Foreign.C"
"[Link]"
"[Link]"
"[Link]"
ghci> :complete repl 5-10 "import For"
6 21 "import "
"[Link]"
"[Link]"
"[Link]"
"[Link]"
"[Link]"
"[Link]"
ghci> :complete repl 20- "import For"
2 21 "import "
"[Link]"
"[Link]"
ghci> :complete repl "map"
3 3 ""
"map"
"mapM"
"mapM_"
ghci> :complete repl 5-10 "map"
0 3 ""
:continue
Continue the current evaluation, when stopped at a breakpoint.
:ctags [⟨filename⟩]
Generates a “tags” file for Vi-style editors (:ctags (page 54)) or Emacs-style editors
(:etags (page 55)). If no filename is specified, the default tags or TAGS is used, respec-
tively. Tags for all the functions, constructors and types in the currently loaded modules
are created. All modules must be interpreted for these commands to work.
:def[!] ⟨name⟩ ⟨expr⟩
:def (page 54) is used to define new commands, or macros, in GHCi. The command :def
⟨name⟩ ⟨expr⟩ defines a new GHCi command :name, implemented by the Haskell expres-
sion ⟨expr⟩, which must have type String -> IO String. When :name args is typed at
the prompt, GHCi will run the expression (name args), take the resulting String, and
feed it back into GHCi as a new sequence of commands. Separate commands in the
result must be separated by “\n”.
That’s all a little confusing, so here’s a few examples. To start with, here’s a new GHCi
command which doesn’t take any arguments or produce any results, it just outputs the
current date and time:
ghci> let date _ = [Link] >>= print >> return ""
ghci> :def date date
ghci> :date
2017-04-10 12:34:56.93213581 UTC
Or I could define a simple way to invoke “ghc --make Main” in the current directory:
ghci> :def make (\_ -> return ":! ghc --make Main")
We can define a command that reads GHCi input from a file. This might be useful for
creating a set of bindings that we want to repeatedly load into the GHCi session:
ghci> :def . readFile
ghci> :. [Link]
Notice that we named the command :., by analogy with the “.” Unix shell command
that does the same thing.
Typing :def on its own lists the currently-defined macros. Attempting to redefine an
existing command name results in an error unless the :def! form is used, in which case
the old command with that name is silently overwritten. However for builtin commands
the old command can still be used by preceding the command name with a double colon
(eg ::load). It’s not possible to redefine the commands :{, :} and :!.
For types and classes, GHCi also summarises instances that mention them. To avoid
showing irrelevant information, an instance is shown only if (a) its head mentions ⟨name⟩,
and (b) all the other things mentioned in the instance are in scope (either qualified or
otherwise) as a result of a :load (page 57) or :module (page 58) commands.
The command :info! works in a similar fashion but it removes restriction (b), showing
all instances that are in scope and mention ⟨name⟩ in their head.
:instances ⟨type⟩
Displays all the class instances available to the argument ⟨type⟩. The command will
match ⟨type⟩ with the first parameter of every instance and then check that all constraints
are satisfiable.
When combined with PartialTypeSignatures (page 444), a user can insert wildcards
into a query and learn the constraints required of each wildcard for ⟨type⟩ match with
an instance.
The output is a listing of all matching instances, simplified and instantiated as much as
possible.
For example:
> :instances Maybe (Maybe Int)
instance Eq (Maybe (Maybe Int)) -- Defined in ‘[Link]’
instance Ord (Maybe (Maybe Int)) -- Defined in ‘[Link]’
instance Show (Maybe (Maybe Int)) -- Defined in ‘[Link]’
instance Read (Maybe (Maybe Int)) -- Defined in ‘[Link]’
Only instances which could potentially be used will be displayed in the results. Instances
which require unsatisfiable constraints such as TypeError will not be included. In the
following example, the instance for A is not shown because it cannot be used.
ghci>:set -XDataKinds -XUndecidableInstances
ghci>import [Link]
ghci>class A a
ghci>instance (TypeError (Text "Not possible")) => A Bool
ghci>:instances Bool
instance Eq Bool -- Defined in ‘[Link]’
instance Ord Bool -- Defined in ‘[Link]’
instance Enum Bool -- Defined in ‘[Link]’
instance Show Bool -- Defined in ‘[Link]’
instance Read Bool -- Defined in ‘[Link]’
instance Bounded Bool -- Defined in ‘[Link]’
:issafe [⟨module⟩]
Displays Safe Haskell information about the given module (or the current module if omit-
ted). This includes the trust type of the module and its containing package.
:kind[!] ⟨type⟩
Infers and prints the kind of ⟨type⟩. The latter can be an arbitrary type expression, in-
cluding a partial application of a type constructor, such as Either Int. In fact, :kind
(page 56) even allows you to write a partial application of a type synonym (usually disal-
lowed), so that this works:
If you specify the optional “!”, GHC will in addition normalise the type by expanding out
type synonyms and evaluating type-function applications, and display the normalised
result.
:list ⟨identifier⟩
Lists the source code around the definition of ⟨identifier⟩ or the current breakpoint if
not given. This requires that the identifier be defined in an interpreted module. If your
output device supports it, then GHCi will highlight the active subexpression in bold.
:list [⟨module⟩] ⟨line⟩
Lists the source code around the given line number of ⟨module⟩. This requires that the
module be interpreted. If your output device supports it, then GHCi will highlight the
active subexpression in bold.
:load[!] [*]⟨module⟩
Recursively loads the specified ⟨module⟩s, and all the modules they depend on. Here,
each ⟨module⟩ must be a module name or filename, but may not be the name of a module
in a package.
All previously loaded modules, except package modules, are forgotten. The new set of
modules is known as the target set. Note that :load (page 57) can be used without any
arguments to unload all the currently loaded modules and bindings.
Normally pre-compiled code for a module will be loaded if available, or otherwise the
module will be compiled to byte-code. Using the * prefix forces a module to be loaded
as byte-code.
Adding the optional “!” turns type errors into warnings while loading. This allows to
use the portions of the module that are correct, even if there are type errors in some
definitions. Effectively, the “-fdefer-type-errors” flag is set before loading and unset after
loading if the flag has not already been set before. See Deferring type errors to runtime
(page 351) for further motivation and details.
After a :load (page 57) command, the current context is set to:
•⟨module⟩, if it was loaded successfully, or
•the most recently successfully loaded module, if any other modules were loaded as
a result of the current :load (page 57), or
•Prelude otherwise.
:loc-at ⟨module⟩ ⟨line⟩ ⟨col⟩ ⟨end-line⟩ ⟨end-col⟩ [⟨name⟩]
Tries to find the definition site of the name at the given source-code span, e.g.:
This command is useful when integrating GHCi with text editors and IDEs for providing
a goto-definition facility.
The :loc-at command requires :set +c (page 63) to be set.
:main ⟨arg1⟩ ... ⟨argn⟩
When a program is compiled and executed, it can use the getArgs function to access the
command-line arguments. However, we cannot simply pass the arguments to the main
function while we are testing in ghci, as the main function doesn’t take its arguments
directly.
Instead, we can use the :main (page 58) command. This runs whatever main is in scope,
with any arguments being treated the same as command-line arguments, e.g.:
We can also quote arguments which contains characters like spaces, and they are treated
like Haskell strings, or we can just use Haskell list syntax:
Finally, other functions can be called, either with the -main-is flag or the :run (page 59)
command:
:reload[!]
Attempts to reload the current target set (see :load (page 57)) if any of the modules in
the set, or any dependent module, has changed. Note that this may entail loading new
modules, or dropping modules which are no longer indirectly required by the target.
Adding the optional “!” turns type errors into warnings while loading. This allows to
use the portions of the module that are correct, even if there are type errors in some
definitions. Effectively, the “-fdefer-type-errors” flag is set before loading and unset after
loading if the flag has not already been set before. See Deferring type errors to runtime
(page 351) for further motivation and details.
:run
See :main (page 58).
:script [⟨n⟩] ⟨filename⟩
Executes the lines of a file as a series of GHCi commands. The syntax for file-name ar-
guments respects shell quoting rules, i.e., file names containing spaces can be enclosed
in double quotes or with spaces escaped with a backslash. This command is compatible
with multiline statements as set by :set +m (page 63)
:set [⟨option⟩ ...]
Sets various options. See The :set and :seti commands (page 63) for a list of available
options and Interactive-mode options (page 127) for a list of GHCi-specific flags. The
:set (page 59) command by itself shows which options are currently set. It also lists the
current dynamic flag settings, with GHCi-specific flags listed separately.
:set args ⟨arg⟩
Sets the list of arguments which are returned when the program calls [Link].
:set editor ⟨cmd⟩
Sets the command used by :edit (page 55) to ⟨cmd⟩.
:set local-config ⟨source|ignore⟩
If ignore, ./.ghci files will be ignored (sourcing untrusted local scripts is a security
risk). The default is source. Set this directive in your user .ghci script, i.e. before the
local script would be sourced.
Even when set to ignore, a local script will still be processed if given by -ghci-script
(page 66) on the command line, or sourced via :script (page 59).
:set prog ⟨prog⟩
Sets the string to be returned when the program calls [Link].
:set prompt ⟨prompt⟩
Sets the string to be used as the prompt in GHCi. Inside ⟨prompt⟩, the next sequences
are replaced:
•%s by the names of the modules currently in scope.
•%l by the line number (as referenced in compiler messages) of the current prompt.
•%d by the date in “Weekday Month Date” format (e.g., “Tue May 26”) .
•%t by the current time in 24-hour HH:MM:SS format.
•%T by the current time in 12-hour HH:MM:SS format.
•%@ by the current time in 12-hour am/pm format.
•%A by the current time in 24-hour HH:MM format.
•%u by the username of the current user.
*ghci> :def cond \expr -> return (":cmd if (" ++ expr ++ ") then return \"\"␣
,→else return \":continue\"")
Ignoring breakpoints for a specified number of iterations is also possible using similar
techniques.
:seti [⟨option⟩ ...]
Like :set (page 59), but options set with :seti (page 60) affect only expressions and com-
mands typed at the prompt, and not modules loaded with :load (page 57) (in contrast,
options set with :set (page 59) apply everywhere). See Setting options for interactive
evaluation only (page 64).
Without any arguments, displays the current set of options that are applied to expres-
sions and commands typed at the prompt.
:show bindings
Show the bindings made at the prompt and their types.
:show breaks
List the active breakpoints.
:show context
List the active evaluations that are stopped at breakpoints.
:show imports
Show the imports that are currently in force, as created by import and :module (page 58)
commands.
:show modules
Show the list of modules currently loaded.
:show packages
Show the currently active package flags, as well as the list of packages currently loaded.
:show paths
Show the current working directory (as set via :cd (page 52) command), as well as the
list of directories searched for source files (as set by the -i option).
:show language
Show the currently active language flags for source files.
:showi language
Show the currently active language flags for expressions typed at the prompt (see also
:seti (page 60)).
:show [args|prog|prompt|editor|stop]
Displays the specified setting (see :set (page 59)).
:sprint ⟨expr⟩
Prints a value without forcing its evaluation. :sprint (page 61) is similar to :print
(page 58), with the difference that unevaluated subterms are not bound to new variables,
they are simply denoted by _.
:step [⟨expr⟩]
Enable all breakpoints and begin evaluating an expression in single-stepping mode. In
this mode evaluation will be stopped after every reduction, allowing local variables to
be inspected. If ⟨expr⟩ is not given, evaluation will resume at the last breakpoint. See
Single-stepping (page 44).
:steplocal
Enable only breakpoints in the current top-level binding and resume evaluation at the
last breakpoint. Continuation with :steplocal (page 61) is not possible if this last break-
point was hit by an error (-fbreak-on-error (page 48)) or an exception (-fbreak-on-
exception (page 48)).
:stepmodule
Enable only breakpoints in the current module and resume evaluation at the last break-
point.
:trace ⟨expr⟩
Evaluates the given expression (or from the last breakpoint if no expression is given),
and additionally logs the evaluation steps for later inspection using :history (page 55).
See Tracing and history (page 46).
:type ⟨expression⟩
Infers and prints the type of ⟨expression⟩, including explicit forall quantifiers for polymor-
phic types. The type reported is the type that would be inferred for a variable assigned
to the expression, but without the monomorphism restriction applied.
*X> :type length
length :: Foldable t => t a -> Int
:type +v ⟨expression⟩
Infers and prints the type of ⟨expression⟩, but without fiddling with type variables or class
constraints. This is useful when you are using TypeApplications (page 338) and care
about the distinction between specified type variables (available for type application) and
inferred type variables (not available). This mode sometimes prints constraints (such as
Show Int) that could readily be solved, but solving these constraints may affect the type
variables, so GHC refrains.
*X> :set -fprint-explicit-foralls
*X> :type +v length
length :: forall (t :: * -> *). Foldable t => forall a. t a -> Int
:type +d ⟨expression⟩
Infers and prints the type of ⟨expression⟩, defaulting type variables if possible. In this
mode, if the inferred type is constrained by any interactive class (Num, Show, Eq, Ord,
Foldable, or Traversable), the constrained type variable(s) are defaulted according to
the rules described under ExtendedDefaultRules (page 36). This mode is quite useful
when the inferred type is quite general (such as for foldr) and it may be helpful to see
a more concrete instantiation.
*X> :type +d length
length :: [a] -> Int
This command is useful when integrating GHCi with text editors and IDEs for providing
a show-type-under-point facility.
The first parameter (path) must be a file path and not a module name. The type of this
path is dependent on how the module was loaded into GHCi: If the module was loaded
by name, then the path name calculated by GHCi as described in Modules vs. filenames
(page 25) must be used. If the module was loaded with an absolute or a relative path,
then the same path must be specified.
The last string parameter is useful for when the span is out of date, i.e. the file changed
and the code has moved. In which case :type-at (page 62) falls back to a general :type
(page 61) like lookup.
The :type-at (page 62) command requires :set +c (page 63) to be set.
:undef ⟨name⟩
Undefines the user-defined command ⟨name⟩ (see :def (page 54) above).
:unset ⟨option⟩
Unsets certain options. See The :set and :seti commands (page 63) for a list of available
options.
:uses ⟨module⟩ ⟨line⟩ ⟨col⟩ ⟨end-line⟩ ⟨end-col⟩ [⟨name⟩]
Reports all module-local uses of the thing at the given position in the module, e.g.:
This command is useful for highlighting and navigating all uses of an identifier in editors
and IDEs.
The :uses (page 62) command requires :set +c (page 63) to be set.
:: ⟨builtin-command⟩
Executes the GHCi built-in command (e.g. ::type 3). That is, look up on the list of
builtin commands, excluding defined macros. See also: :def (page 54).
:! ⟨command⟩
Executes the shell command ⟨command⟩.
The :set (page 59) command sets two types of options: GHCi options, which begin with “+”,
and “command-line” options, which begin with “-”.
Note: At the moment, the :set (page 59) command doesn’t support any kind of quoting in
its arguments: quotes will not be removed and cannot be used to group words together. For
example, :set -DFOO='BAR BAZ' will not do what you expect.
GHCi options may be set using :set (page 59) and unset using :unset (page 62).
The available GHCi options are:
:set +c
Collect type and location information after loading modules. The commands :all-types
(page 51), :loc-at (page 57), :type-at (page 62), and :uses (page 62) require +c to be
active.
:set +m
Enable parsing of multiline commands. A multiline command is prompted for when the
current input line contains open layout contexts (see Multiline input (page 30)).
:set +r
Normally, any evaluation of top-level expressions (otherwise known as CAFs or Constant
Applicative Forms) in loaded modules is retained between evaluations. Turning on +r
causes all evaluation of top-level expressions to be discarded after each evaluation (they
are still retained during a single evaluation).
This option may help if the evaluated top-level expressions are consuming large amounts
of space, or if you need repeatable performance measurements.
:set +s
Display some stats after evaluating each expression, including the elapsed time and num-
ber of bytes allocated. NOTE: the allocation figure is only accurate to the size of the stor-
age manager’s allocation area, because it is calculated at every GC. Hence, you might
see values of zero if no GC has occurred.
:set +t
Display the type of each variable bound after a statement is entered at the prompt. If the
statement is a single expression, then the only variable binding will be for the variable
it.
Normal GHC command-line options may also be set using :set (page 59). For example, to
turn on -Wmissing-signatures (page 96), you would say:
Any GHC command-line option that is designated as dynamic (see the table in Flag reference
(page 120)), may be set using :set (page 59). To unset an option, you can set the reverse
option:
Flag reference (page 120) lists the reverse for each option where applicable.
Certain static options (-package ⟨pkg⟩ (page 194), -I⟨dir⟩ (page 213), -i⟨dir⟩[:⟨dir⟩]*
(page 176), and -l ⟨lib⟩ (page 217) in particular) will also work, but some may not take
effect until the next reload.
:seti -XMonoLocalBinds
It would be undesirable if MonoLocalBinds (page 449) were to apply to loaded modules too:
that might cause a compilation error, but more commonly it will cause extra recompilation,
because GHC will think that it needs to recompile the module because the flags have changed.
If you are setting language options in your .ghci file, it is good practice to use :seti (page 60)
rather than :set (page 59), unless you really do want them to apply to all modules you load
in GHCi.
The two sets of options can be inspected using the :set (page 59) and :seti (page 60) com-
mands respectively, with no arguments. For example, in a clean GHCi session we might see
something like this:
ghci> :seti
base language is: Haskell2010
with the following modifiers:
-XNoMonomorphismRestriction
-XNoDatatypeContexts
-XNondecreasingIndentation
-XExtendedDefaultRules
GHCi-specific dynamic flag settings:
other dynamic, non-language, flag settings:
-fimplicit-import-qualified
warning settings:
The two sets of options are initialised as follows. First, both sets of options are initialised
as described in The .ghci and .haskeline files (page 65). Then the interactive options are
modified as follows:
• The option -XExtendedDefaultRules is enabled, in order to apply special defaulting
rules to expressions typed at the prompt (see Type defaulting in GHCi (page 36)).
• The Monomorphism Restriction is disabled (see Switching off the Monomorphism Re-
striction (page 449)).
When it starts, unless the -ignore-dot-ghci (page 66) flag is given, GHCi reads and executes
commands from the following files, in this order, if they exist:
1. ghcappdata/[Link], where ⟨ghcappdata⟩ depends on your system, but is usually
something like $HOME/.ghc on Unix or C:/Documents and Settings/user/Application
Data/ghc on Windows.
2. $HOME/.ghci
3. ./.ghci
The [Link] file is most useful for turning on favourite options (e.g. :set +s), and defining
useful macros.
Note: When setting language options in this file it is usually desirable to use :seti (page 60)
rather than :set (page 59) (see Setting options for interactive evaluation only (page 64)).
Placing a .ghci file in a directory with a Haskell project is a useful way to set certain project-
wide options so you don’t have to type them every time you start GHCi: eg. if your project
uses multi-parameter type classes, scoped type variables, and CPP, and has source files in
three subdirectories A, B and C, you might put the following lines in .ghci:
:set -XMultiParamTypeClasses -XScopedTypeVariables -cpp
:set -iA:B:C
(Note that strictly speaking the -i (page 176) flag is a static one, but in fact it works to set it
using :set (page 59) like this. The changes won’t take effect until the next :load (page 57),
though.)
Warning: Sourcing untrusted ./.ghci files is a security risk. They can contain arbitrary
commands that will be executed as the user. Use :set local-config (page 59) to inhibit
the processing of ./.ghci files.
Once you have a library of GHCi macros, you may want to source them from separate files, or
you may want to source your .ghci file into your running GHCi session while debugging it
With this macro defined in your .ghci file, you can use :source file to read GHCi commands
from file. You can find (and contribute!-) other suggestions for .ghci files on this Haskell
wiki page: GHC/GHCi
Additionally, any files specified with -ghci-script (page 66) flags will be read after the stan-
dard files, allowing the use of custom .ghci files.
Two command-line options control whether the startup files files are read:
-ignore-dot-ghci
Don’t read either ./.ghci or the other startup files when starting up.
-ghci-script
Read a specific file after the usual startup files. May be specified repeatedly for multiple
inputs. -ignore-dot-ghci (page 66) does not apply to these files.
When defining GHCi macros, there is some important behavior you should be aware of when
names may conflict with built-in commands, especially regarding tab completion.
For example, consider if you had a macro named :time and in the shell, typed :t 3 — what
should happen? The current algorithm we use for completing commands is:
1. First, look up an exact match on the name from the defined macros.
2. Look for the exact match on the name in the built-in command list.
3. Do a prefix lookup on the list of built-in commands - if a built-in command matches, but
a macro is defined with the same name as the built-in defined, pick the macro.
4. Do a prefix lookup on the list of built-in commands.
5. Do a prefix lookup on the list of defined macros.
Here are some examples:
1. You have a macro :time and enter :t 3
You get :type 3
2. You have a macro :type and enter :t 3
You get :type 3 with your defined macro, not the builtin.
3. You have a macro :time and a macro :type, and enter :t 3
You get :type 3 with your defined macro.
When giving priority to built-in commands, you can use :: ⟨builtin-command⟩ (page 63),
like ::type 3.
GHCi uses Haskeline under the hood. You can configure it to, among other things, prune
duplicates from GHCi history. See: Haskeline user preferences.
By default, GHCi compiles Haskell source code into byte-code that is interpreted by the run-
time system. GHCi can also compile Haskell code to object code: to turn on this feature, use
the -fobject-code (page 216) flag either on the command line or with :set (page 59) (the
option -fbyte-code (page 216) restores byte-code compilation again). Compiling to object
code takes longer, but typically the code will execute 10-20 times faster than byte-code.
Compiling to object code inside GHCi is particularly useful if you are developing a compiled
application, because the :reload (page 58) command typically runs much faster than restart-
ing GHC with --make (page 76) from the command-line, because all the interface files are
already cached in memory.
There are disadvantages to compiling to object-code: you can’t set breakpoints in object-
code modules, for example. Only the exports of an object-code module will be visible in GHCi,
rather than all top-level bindings as in interpreted modules.
Normally GHCi runs the interpreted code in the same process as GHC itself, on top of the same
RTS and sharing the same heap. However, if the flag -fexternal-interpreter (page 67) is
given, then GHC will spawn a separate process for running interpreted code, and communi-
cate with it using messages over a pipe.
-fexternal-interpreter
Since 8.0.1
Run interpreted code (for GHCi, Template Haskell, Quasi-quoting, or Annotations) in a
separate process. The interpreter will run in profiling mode if -prof (page 557) is in
effect, and in dynamically-linked mode if -dynamic (page 218) is in effect.
There are a couple of caveats that will hopefully be removed in the future: this option is
currently not implemented on Windows (it is a no-op), and the external interpreter does
not support the GHCi debugger, so breakpoints and single-stepping don’t work with -
fexternal-interpreter (page 67).
See also the -pgmi ⟨cmd⟩ (page 211) (Replacing the program for one or more phases
(page 211)) and -opti ⟨option⟩ (page 212) (Forcing options to a particular phase
(page 212)) flags.
Why might we want to do this? The main reason is that the RTS running the interpreted code
can be a different flavour (profiling or dynamically-linked) from GHC itself. So for example:
• We can use the profiler to collect stack traces when using GHCi (see Stack Traces in
GHCi (page 39)).
• When compiling Template Haskell code with -prof (page 557) we don’t need to compile
the modules without -prof (page 557) first (see Using Template Haskell with Profiling
(page 458)) because we can run the profiled object code in the interpreter.
This feature is experimental in GHC 8.0.x, but it may become the default in future releases.
When using the flag -fexternal-interpreter (page 67) GHC will spawn and communicate
with the separate process using pipes. There are scenarios (e.g. when cross compiling) where
it is favourable to have the communication happen over the network. GHC provides two
utilities for this, which can be found in the utils directory.
• remote-iserv needs to be built with the cross compiler to be executed on the remote
host. Or in the case of using it on the same host the stage2 compiler will do as well.
• iserv-proxy needs to be built on the build machine by the build compiler.
After starting remote-iserv ⟨tmp_dir⟩ ⟨port⟩ on the target and providing it with a tempo-
rary folder (where it will copy the necessary libraries to load to) and port it will listen for the
proxy to connect.
Providing -pgmi ⟨/path/to/iserv-proxy⟩ (page 211) and -opti ⟨slave-ip⟩ -opti
⟨slave-port⟩ [-opti -v] (page 212) in addition to -fexternal-interpreter (page 67) will
then make ghc go through the proxy instead.
There are some limitations when using this. File and process IO will be executed on the target.
As such packages like git-embed, file-embed and others might not behave as expected if the
target and host do not share the same filesystem.
The interpreter can’t load modules with foreign export declarations! Unfortunately
not. We haven’t implemented it yet. Please compile any offending modules by hand
before loading them into GHCi.
-O (page 105) doesn’t work with GHCi!
For technical reasons, the bytecode compiler doesn’t interact well with one of the
optimisation passes, so we have disabled optimisation when using the interpreter.
This isn’t a great loss: you’ll get a much bigger win by compiling the bits of your
code that need to go fast, rather than interpreting them with optimisation turned
on.
Modules using unboxed tuples or sums will automatically enable -fobject-code (page 216)
The bytecode interpreter doesn’t support most uses of unboxed tuples or sums, so
GHCi will automatically compile these modules, and all modules they depend on, to
object code instead of bytecode.
GHCi checks for the presence of unboxed tuples and sums in a somewhat con-
servative fashion: it simply checks to see if a module enables the UnboxedTuples
(page 474) or UnboxedSums (page 475) language extensions. It is not always the case
that code which enables UnboxedTuples (page 474) or UnboxedSums (page 475) re-
quires -fobject-code (page 216), so if you really want to compile UnboxedTuples
(page 474)/UnboxedSums (page 475)-using code to bytecode, you can do so explicitly
by enabling the -fbyte-code (page 216) flag. If you do this, do note that bytecode
interpreter will throw an error if it encounters unboxed tuple/sum–related code that
it cannot handle.
Incidentally, the previous point, that -O (page 105) is incompatible with GHCi, is
because the bytecode compiler can’t deal with unboxed tuples or sums.
Concurrent threads don’t carry on running when GHCi is waiting for input. This
should work, as long as your GHCi was built with the -threaded (page 220) switch,
which is the default. Consult whoever supplied your GHCi installation.
After using getContents, I can’t use stdin, until I do :load or :reload This is the de-
fined behaviour of getContents: it puts the stdin Handle in a state known as semi-closed,
wherein any further I/O operations on it are forbidden. Because I/O state is retained be-
tween computations, the semi-closed state persists until the next :load (page 57) or
:reload (page 58) command.
You can make stdin reset itself after every evaluation by giving GHCi the command :set
+r. This works because stdin is just a top-level expression that can be reverted to its
unevaluated state in the same way as any other top-level expression (CAF).
I can’t use Control-C to interrupt computations in GHCi on Windows. See Running
GHCi on Windows (page 595).
The default buffering mode is different in GHCi to GHC. In GHC, the stdout handle is
line-buffered by default. However, in GHCi we turn off the buffering on stdout, because
this is normally what you want in an interpreter: output appears as it is generated.
If you want line-buffered behaviour, as in GHC, you can start your program thus:
FOUR
USING RUNGHC
runghc allows you to run Haskell programs without first having to compile them.
4.1 Usage
Any flags not recognized by runghc are automatically passed to GHC. If a flag is recognized by
both runghc and GHC but you want to pass it to GHC then you can place it after a -- separator.
Flags after the separator are treated as GHC only flags. Alternatively you can use the runghc
option --ghc-arg=<arg> to pass any flag or argument directly to GHC.
module could be a Haskell source filename with or without the extension. If for some reason
the filename starts with a - you can use a second -- to indicate the end of flags. Anything
following a second -- will be considered a program file or module name followed by its argu-
ments. For example:
• runghc -- -- -[Link]
71
GHC User’s Guide Documentation, Release 9.0.2
• runghc --ghc-arg=-fliberate-case
Note that any non-flag arguments are never passed to GHC. An unused non-flag argument
will be considered as the name of the program to run. If a GHC flag takes an argument use
--ghc-arg=<arg> to pass the argument to GHC. For example, if you want to pass -package
foo to GHC use any of the following:
• runghc -package --ghc-arg=foo [Link]
• runghc --ghc-arg=-package --ghc-arg=foo [Link]
FIVE
USING GHC
In this chapter you’ll find a complete reference to the GHC command-line syntax, including
all 400+ flags. It’s a large and complex system, and there are lots of details, so it can be quite
hard to figure out how to get started. With that in mind, this introductory section provides
a quick introduction to the basic usage of GHC for compiling a Haskell program, before the
following sections dive into the full syntax.
Let’s create a Hello World program, and compile and run it. First, create a file [Link]
containing the Haskell code:
$ ghc [Link]
(where $ represents the prompt: don’t type it). GHC will compile the source file [Link],
producing an object file hello.o and an interface file [Link], and then it will link the
object file to the libraries that come with GHC to produce an executable called hello on
Unix/Linux/Mac, or [Link] on Windows.
By default GHC will be very quiet about what it is doing, only printing error messages. If
you want to see in more detail what’s going on behind the scenes, add -v (page 79) to the
command line.
Then we can run the program like this:
$ ./hello
Hello World!
If your program contains multiple modules, then you only need to tell GHC the name of the
source file containing the Main module, and GHC will examine the import declarations to
find the other modules that make up the program and find their source files. This means that,
with the exception of the Main module, every source file should be named after the module
name that it contains (with dots replaced by directory separators). For example, the module
[Link] would be in the file Data/[Link] on Unix/Linux/Mac, or Data\[Link] on
Windows.
73
GHC User’s Guide Documentation, Release 9.0.2
GHC’s behaviour is controlled by options, which for historical reasons are also sometimes
referred to as command-line flags or arguments. Options can be specified in three ways:
Command-line arguments
ghc [argument...]
Note: Note that command-line options are order-dependent, with arguments being evalu-
ated from left-to-right. This can have seemingly strange effects in the presence of flag implica-
tion. For instance, consider -fno-specialise (page 113) and -O1 (page 105) (which implies
-fspecialise (page 113)). These two command lines mean very different things:
-fno-specialise -O1
-fspecialise will be enabled as the -fno-specialise is overridden by the -O1.
-O1 -fno-specialise
-fspecialise will not be enabled, since the -fno-specialise overrides the -
fspecialise implied by -O1.
Sometimes it is useful to make the connection between a source file and the command-line
options it requires quite tight. For instance, if a Haskell source file deliberately uses name
shadowing, it should be compiled with the -Wno-name-shadowing option. Rather than main-
taining the list of per-file options in a Makefile, it is possible to do this directly in the source
file using the OPTIONS_GHC pragma (page 518)
Note: The contents of OPTIONS_GHC are appended to the command-line options, so options
given in the source file override those given on the command-line.
It is not recommended to move all the contents of your Makefiles into your source files, but
in some circumstances, the OPTIONS_GHC pragma is the Right Thing. (If you use -keep-hc-
file (page 179) and have OPTION flags in your module, the OPTIONS_GHC will get put into the
generated .hc file).
Options may also be modified from within GHCi, using the :set (page 59) command.
File names with “meaningful” suffixes (e.g., .lhs or .o) cause the “right thing” to happen to
those files.
.hs A Haskell module.
.lhs A “literate Haskell” module.
.hspp A file created by the preprocessor.
.hi A Haskell interface file, probably compiler-generated.
.hie An extended Haskell interface file, produced by the Haskell compiler.
.hc Intermediate C file produced by the Haskell compiler.
.c A C file not produced by the Haskell compiler.
.ll An llvm-intermediate-language source file, usually produced by the compiler.
.bc An llvm-intermediate-language bitcode file, usually produced by the compiler.
.s An assembly-language source file, usually produced by the compiler.
.o An object file, produced by an assembler.
Files with other suffixes (or without suffixes) are passed straight to the linker.
GHC’s behaviour is firstly controlled by a mode flag. Only one of these flags may be given,
but it does not necessarily need to be the first option on the command-line. For instance,
If no mode flag is present, then GHC will enter --make (page 76) mode (Using ghc –make
(page 77)) if there are any Haskell source files given on the command line, or else it will link
the objects named on the command line to produce an executable.
The available mode flags are:
--interactive
Interactive mode, which is also available as ghci. Interactive mode is described in more
detail in Using GHCi (page 23).
--make
In this mode, GHC will build a multi-module Haskell program automatically, figuring out
dependencies for itself. If you have a straightforward Haskell program, this is likely to
be much easier, and faster, than using make. Make mode is described in Using ghc –make
(page 77).
This mode is the default if there are any Haskell source files mentioned on the command
line, and in this case the --make (page 76) option can be omitted.
-e ⟨expr⟩
Expression-evaluation mode. This is very similar to interactive mode, except that there
is a single expression to evaluate (⟨expr⟩) which is given on the command line. See
Expression evaluation mode (page 78) for more details.
-E
Stop after preprocessing (.hspp file)
-C
Stop after generating C (.hc file)
-S
Stop after generating assembly (.s file)
-c
Stop after generating object (.o) file
This is the traditional batch-compiler mode, in which GHC can compile source files one at
a time, or link objects together into an executable. See Batch compiler mode (page 78).
-M
Dependency-generation mode. In this mode, GHC can be used to generate dependency
information suitable for use in a Makefile. See Dependency generation (page 190).
--frontend ⟨module⟩
Run GHC using the given frontend plugin. See Frontend plugins (page 549) for details.
--mk-dll
DLL-creation mode (Windows only). See Creating a DLL (page 598).
--help
-?
Cause GHC to spew a long usage message to standard output and then exit.
--show-iface ⟨file⟩
Read the interface in ⟨file⟩ and dump it as text to stdout. For example ghc --show-iface
[Link].
--supported-extensions
--supported-languages
Print the supported language extensions.
--show-options
Print the supported command line options. This flag can be used for autocompletion in
a shell.
--info
Print information about the compiler.
--version
-V
Print a one-line string including GHC’s version number.
--numeric-version
Print GHC’s numeric version number only.
--print-libdir
Print the path to GHC’s library directory. This is the top of the directory tree
containing GHC’s libraries, interfaces, and include files (usually something like
/usr/local/lib/ghc-5.04 on Unix). This is the value of $libdir in the package config-
uration file (see Packages (page 193)).
In this mode, GHC will build a multi-module Haskell program by following dependencies from
one or more root modules (usually just Main). For example, if your Main module is in a file
called [Link], you could compile and link the program like this:
In fact, GHC enters make mode automatically if there are any Haskell source files on the
command line and no other mode is specified, so in this case we could just type
ghc [Link]
Any number of source file names or module names may be specified; GHC will figure out all
the modules in the program by following the imports from these initial modules. It will then
attempt to compile each module which is out of date, and finally, if there is a Main module,
the program will also be linked into an executable.
The main advantages to using ghc --make over traditional Makefiles are:
• GHC doesn’t have to be restarted for each compilation, which means it can cache infor-
mation between compilations. Compiling a multi-module program with ghc --make can
be up to twice as fast as running ghc individually on each source file.
• You don’t have to write a Makefile.
• GHC re-calculates the dependencies each time it is invoked, so the dependencies never
get out of sync with the source.
• Using the -j[⟨n⟩] (page 78) flag, you can compile modules in parallel. Specify -j ⟨n⟩ to
compile ⟨n⟩ jobs in parallel. If ⟨n⟩ is omitted, then it defaults to the number of processors.
Any of the command-line options described in the rest of this chapter can be used with --
make, but note that any options you give on the command line will apply to all the source files
compiled, so if you want any options to apply to a single source file only, you’ll need to use an
OPTIONS_GHC pragma (see Command line options in source files (page 74)).
If the program needs to be linked with additional objects (say, some auxiliary C code), then
the object files can be given on the command line and GHC will include them when linking
the executable.
For backward compatibility with existing make scripts, when used in combination with -c
(page 76), the linking phase is omitted (same as --make -no-link).
Note that GHC can only follow dependencies if it has the source file available, so if your
program includes a module for which there is no source file, even if you have an object and
an interface file for the module, then GHC will complain. The exception to this rule is for
package modules, which may or may not have source files.
The source files for the program don’t all need to be in the same directory; the -i (page 176)
option can be used to add directories to the search path (see The search path (page 176)).
-j[⟨n⟩]
Perform compilation in parallel when possible. GHC will use up to ⟨N⟩ threads during
compilation. If N is omitted, then it defaults to the number of processors. Note that
compilation of a module may not begin until its dependencies have been built.
This mode is very similar to interactive mode, except that there is a single expression to
evaluate which is specified on the command line as an argument to the -e option:
ghc -e expr
Haskell source files may be named on the command line, and they will be loaded exactly as
in interactive mode. The expression is evaluated in the context of the loaded modules.
For example, to load and run a Haskell program containing a module Main, we might say:
or we can just use this mode to evaluate expressions in the context of the Prelude:
In batch mode, GHC will compile one or more source files given on the command line.
The first phase to run is determined by each input-file suffix, and the last phase is determined
by a flag. If no relevant flag is present, then go all the way through to linking. This table
summarises:
Phase of the compilation Suffix saying “start Flag saying “stop (suffix of) output
system here” after” file
literate pre-processor .lhs .hs
C pre-processor (opt.) .hs (with -cpp) -E .hspp
Haskell compiler .hs -C, -S .hc, .s
C compiler (opt.) .hc or .c -S .s
assembler .s -c .o
linker ⟨other⟩ [Link]
Thus, a common invocation would be:
ghc -c [Link]
Note: What the Haskell compiler proper produces depends on what backend code generator
is used. See GHC Backends (page 209) for more details.
Note: Pre-processing is optional, the -cpp (page 213) flag turns it on. See Options affecting
the C pre-processor (page 213) for more details.
Note: The option -E (page 76) runs just the pre-processing passes of the compiler, dumping
the result in a file.
Note: The option -C (page 76) is only available when GHC is built in unregisterised mode.
See Unregisterised compilation (page 210) for more details.
As described above, the way in which a file is processed by GHC depends on its suffix. This
behaviour can be overridden using the -x ⟨suffix⟩ (page 79) option:
-x ⟨suffix⟩
Causes all files following this option on the command line to be processed as if they had
the suffix ⟨suffix⟩. For example, to compile a Haskell module in the file [Link]-hs, use ghc
-c -x hs [Link]-hs.
See also the --help, --version, --numeric-version, and --print-libdir modes in Modes
of operation (page 76).
-v
The -v (page 79) option makes GHC verbose: it reports its version number and shows
(on stderr) exactly how it invokes each phase of the compilation system. Moreover, it
passes the -v flag to most phases; each reports its version number (and possibly some
other information).
Please, oh please, use the -v option when reporting bugs! Knowing that you ran the
right bits in the right order is always the first thing we want to verify.
-v⟨n⟩
To provide more control over the compiler’s verbosity, the -v flag takes an optional nu-
meric argument. Specifying -v on its own is equivalent to -v3, and the other levels have
the following meanings:
-v0 Disable all non-essential messages (this is the default).
-v1 Minimal verbosity: print one line per compilation (this is the default when --make
(page 76) or --interactive (page 76) is on).
-v2 Print the name of each compilation phase as it is executed. (equivalent to -dshow-
passes (page 227)).
-v3 The same as -v2, except that in addition the full command line (if appropriate) for
each compilation phase is also printed.
-v4 The same as -v3 except that the intermediate program representation after each
compilation phase is also printed (excluding preprocessed and C/assembly files).
-fprint-potential-instances
When GHC can’t find an instance for a class, it displays a short list of some in the in-
stances it knows about. With this flag it prints all the instances it knows about.
-fhide-source-paths
Starting with minimal verbosity (-v1, see -v (page 79)), GHC displays the name, the
source path and the target path of each compiled module. This flag can be used to
reduce GHC’s output by hiding source paths and target paths.
The following flags control the way in which GHC displays types in error messages and in
GHCi:
-fprint-unicode-syntax
When enabled GHC prints type signatures using the unicode symbols from the Uni-
codeSyntax (page 242) extension. For instance,
-fprint-explicit-foralls
Using -fprint-explicit-foralls (page 80) makes GHC print explicit forall quantifi-
cation at the top level of a type; normally this is suppressed. For example, in GHCi:
ghci> let f x = x
ghci> :t f
f :: a -> a
ghci> :set -fprint-explicit-foralls
ghci> :t f
f :: forall a. a -> a
However, regardless of the flag setting, the quantifiers are printed under these circum-
stances:
•For nested foralls, e.g.
ghci> :t [Link]
[Link] :: (forall s. [Link] s a) -> a
•If any of the quantified type variables has a kind that mentions a kind variable, e.g.
ghci> :i [Link]
[Link] ::
forall k (a :: k) (b :: k).
(a [Link].:~: b) -> b [Link].:~: a
-- Defined in [Link]
-fprint-explicit-kinds
Using -fprint-explicit-kinds (page 81) makes GHC print kind arguments in types,
which are normally suppressed. This can be important when you are using kind poly-
morphism. For example:
ghci> :set -XPolyKinds
ghci> data T a (b :: l) = MkT
ghci> :t MkT
MkT :: forall k l (a :: k) (b :: l). T a b
ghci> :set -fprint-explicit-kinds
ghci> :t MkT
MkT :: forall k l (a :: k) (b :: l). T @{k} @l a b
ghci> :set -XNoPolyKinds
ghci> :t MkT
MkT :: T @{*} @* a b
In the output above, observe that T has two kind variables (k and l) and two type vari-
ables (a and b). Note that k is an inferred variable and l is a specified variable (see
Inferred vs. specified type variables (page 338)), so as a result, they are displayed using
slightly different syntax in the type T @{k} @l a b. The application of l (with @l) is the
standard syntax for visible type application (see Visible type application (page 338)). The
application of k (with @{k}), however, uses a hypothetical syntax for visible type applica-
tion of inferred type variables. This syntax is not currently exposed to the programmer,
but it is nevertheless displayed when -fprint-explicit-kinds (page 81) is enabled.
-fprint-explicit-coercions
Using -fprint-explicit-coercions (page 81) makes GHC print coercions in types.
When trying to prove the equality between types of different kinds, GHC uses type-level
coercions. Users will rarely need to see these, as they are meant to be internal.
-fprint-axiom-incomps
Using -fprint-axiom-incomps (page 81) tells GHC to display incompatibilities between
closed type families’ equations, whenever they are printed by :info (page 55) or --show-
iface ⟨file⟩ (page 76).
ghci> :i [Link].==
type family (==) (a :: k) (b :: k) :: Bool
where
(==) (f a) (g b) = (f == g) && (a == b)
(==) a a = 'True
(==) _1 _2 = 'False
ghci> :set -fprint-axiom-incomps
ghci> :i [Link].==
type family (==) (a :: k) (b :: k) :: Bool
where
{- #0 -} (==) (f a) (g b) = (f == g) && (a == b)
{- #1 -} (==) a a = 'True
-- incompatible with: #0
{- #2 -} (==) _1 _2 = 'False
-- incompatible with: #1, #0
The equations are numbered starting from 0, and the comment after each equation refers
to all preceding equations it is incompatible with.
-fprint-equality-relations
Using -fprint-equality-relations (page 82) tells GHC to distinguish between its
equality relations when printing. For example, ~ is homogeneous lifted equality (the
kinds of its arguments are the same) while ~~ is heterogeneous lifted equality (the
kinds of its arguments might be different) and ~# is heterogeneous unlifted equality,
the internal equality relation used in GHC’s solver. Generally, users should not need
to worry about the subtleties here; ~ is probably what you want. Without -fprint-
equality-relations (page 82), GHC prints all of these as ~. See also Equality con-
straints (page 424).
-fprint-expanded-synonyms
When enabled, GHC also prints type-synonym-expanded types in type errors. For exam-
ple, with this type synonyms:
Becomes this:
-fprint-typechecker-elaboration
When enabled, GHC also prints extra information from the typechecker in warnings. For
example:
main :: IO ()
main = do
return $ let a = "hello" in a
return ()
Becomes this:
let
AbsBinds [] []
{Exports: [a <= a
<>]
Exported types: a :: [Char]
[LclId, Str=DmdType]
Binds: a = "hello"}
in a’
or by using the flag -fno-warn-unused-do-bind
-fdefer-diagnostics
Causes GHC to group diagnostic messages by severity and output them after other mes-
sages when building a multi-module Haskell program. This flag can make diagnostic
messages more visible when used in conjunction with --make (page 76) and -j[⟨n⟩]
(page 78). Otherwise, it can be hard to find the relevant errors or likely to ignore the
warnings when they are mixed with many other messages.
-fdiagnostics-color=⟨always|auto|never⟩
Causes GHC to display error messages with colors. To do this, the terminal must have
support for ANSI color codes, or else garbled text will appear. The default value is auto,
which means GHC will make an attempt to detect whether terminal supports colors and
choose accordingly.
The precise color scheme is controlled by the environment variable GHC_COLORS (or
GHC_COLOURS). This can be set to colon-separated list of key=value pairs. These are
the default settings:
header=:message=1:warning=1;35:error=1;31:fatal=1;31:margin=1;34
Each value is expected to be a Select Graphic Rendition (SGR) substring. The formatting
of each element can inherit from parent elements. For example, if header is left empty,
it will inherit the formatting of message. Alternatively if header is set to 1 (bold), it will
be bolded but still inherits the color of message.
Currently, in the primary message, the following inheritance tree is in place:
•message
–header
∗warning
∗error
∗fatal
In the caret diagnostics, there is currently no inheritance at all between margin, warning,
error, and fatal.
The environment variable can also be set to the magical values never or always, which
is equivalent to setting the corresponding -fdiagnostics-color flag but with lower
precedence.
-fdiagnostics-show-caret
Controls whether GHC displays a line of the original source code where the error was
detected. This also affects the associated caret symbol that points at the region of code
at fault. The flag is on by default.
-ferror-spans
Causes GHC to emit the full source span of the syntactic entity relating to an error
message. Normally, GHC emits the source location of the start of the syntactic entity
only.
For example:
becomes:
[Link]:(5,4)-(6,7):
Conflicting definitions for `a'
Bound at: [Link]:4
[Link]:7
In the binding group for: a, b, a
Note that line numbers start counting at one, but column numbers start at zero. This
choice was made to follow existing convention (i.e. this is how Emacs does it).
-fkeep-going
Since 8.10.1
Causes GHC to continue the compilation if a module has an error. Any reverse depen-
dencies are pruned immediately and the whole compilation is still flagged as an error.
This option has no effect if parallel compilation (-j[⟨n⟩] (page 78)) is in use.
-freverse-errors
Causes GHC to output errors in reverse line-number order, so that the errors and warn-
ings that originate later in the file are displayed first.
-H ⟨size⟩
Set the minimum size of the heap to ⟨size⟩. This option is equivalent to +RTS -Hsize, see
RTS options to control the garbage collector (page 160).
-Rghc-timing
Prints a one-line summary of timing statistics for the GHC run. This option is equivalent
to +RTS -tstderr, see RTS options to control the garbage collector (page 160).
compiled code will only run on processors that support SSE4.2 (Intel Core i7 and later).
The LLVM backend (page 209) will also use SSE4.2 if your processor supports it but
detects this automatically so no flag is required.
-mbmi2
(x86 only, added in GHC 7.4.1) Use the BMI2 instruction set to implement some bit op-
erations when using the native code generator (page 209). The resulting compiled code
will only run on processors that support BMI2 (Intel Haswell and newer, AMD Excavator,
Zen and newer).
5.1.8 Haddock
-haddock
By default, GHC ignores Haddock comments (-- | ... and -- ^ ...) and does not
check that they’re associated with a valid term, such as a top-level type-signature. With
this flag GHC will parse Haddock comments and include them in the interface file it
produces.
Note that this flag makes GHC’s parser more strict so programs which are accepted
without Haddock may be rejected with -haddock (page 85).
GHC can also be configured using environment variables. Currently the only variable it sup-
ports is GHC_NO_UNICODE, which, when set, disables Unicode output regardless of locale set-
tings. GHC_NO_UNICODE can be set to anything +(event an empty string) to trigger this be-
haviour.
GHC has a number of options that select which types of non-fatal error messages, other-
wise known as warnings, can be generated during compilation. Some options control indi-
vidual warnings and others control collections of warnings. To turn off an individual warning
-W<wflag>, use -Wno-<wflag>. To reverse -Werror, which makes all warnings into errors, use
-Wwarn.
-Wdefault
Since 8.0
By default, you get a standard set of warnings which are generally likely to indicate bugs
in your program. These are:
•-Woverlapping-patterns (page 97)
•-Wwarnings-deprecations (page 90)
•-Wdeprecations (page 90)
•-Wdeprecated-flags (page 91)
•-Wunrecognised-pragmas (page 89)
•-Wduplicate-exports (page 93)
•-Wderiving-defaults (page 92)
•-Woverflowed-literals (page 92)
•-Wempty-enumerations (page 92)
•-Wmissing-fields (page 95)
•-Wmissing-methods (page 96)
•-Wwrong-do-bind (page 102)
•-Wsimplifiable-class-constraints (page 99)
•-Wtyped-holes (page 88)
•-Wdeferred-type-errors (page 88)
•-Wpartial-type-signatures (page 89)
•-Wunsupported-calling-conventions (page 91)
•-Wdodgy-foreign-imports (page 92)
•-Winline-rule-shadowing (page 103)
•-Wunsupported-llvm-version (page 99)
•-Wmissed-extra-shared-lib (page 99)
•-Wtabs (page 99)
•-Wunrecognised-warning-flags (page 88)
•-Winaccessible-code (page 97)
•-Wstar-binder (page 98)
•-Wunicode-bidirectional-format-characters (page 104)
The following flags are simple ways to select standard “packages” of warnings:
-W
Provides the standard warnings plus
•-Wunused-binds (page 100)
•-Wunused-matches (page 101)
•-Wunused-foralls (page 102)
•-Wunused-imports (page 101)
•-Wincomplete-patterns (page 94)
•-Wdodgy-exports (page 92)
•-Wdodgy-imports (page 92)
•-Wunbanged-strict-patterns (page 103)
-Wall
Turns on all warning options that indicate potentially suspicious code. The warnings
that are not enabled by -Wall (page 86) are
•-Wincomplete-uni-patterns (page 94)
•-Wincomplete-record-updates (page 95)
•-Wmonomorphism-restriction (page 99)
•-Wimplicit-prelude (page 94)
•-Wmissing-local-signatures (page 96)
•-Wmissing-exported-signatures (page 96)
•-Wmissing-export-lists (page 95)
-Wwarn
Warnings are treated only as warnings, not as errors. This is the default, but can be
useful to negate a -Werror (page 87) flag.
-Wwarn=⟨wflag⟩
Causes a specific warning to be treated as normal warning, not fatal error.
Note that it doesn’t fully negate the effects of -Werror=<wflag> - the warning will still
be enabled.
-Wwarn=compat has the same effect as -Wwarn=... for each warning flag in the -Wcompat
(page 87) option group.
When a warning is emitted, the specific warning flag which controls it is shown.
-fshow-warning-groups
When showing which flag controls a warning, also show the respective warning group
flag(s) that warning is contained in.
This option is off by default.
The full set of warning options is described below. To turn off any warning, simply give the
corresponding -Wno-... option on the command line. For backwards compatibility with GHC
versions prior to 8.0, all these warnings can still be controlled with -f(no-)warn-* instead
of -W(no-)*.
-Wunrecognised-warning-flags
Since 8.0
Default on
Enables warnings when the compiler encounters a -W... flag that is not recognised.
-Wcompat-unqualified-imports
Since 8.10
Warns on qualified imports of core library modules which are subject to change in future
GHC releases. Currently the following modules are covered by this warning:
•[Link] due to the future addition of [Link] and specialisation of
exports to the [] type. See the mailing list for details.
This warning can be addressed by either adding an explicit import list or using a quali-
fied import.
-Wtyped-holes
Since 7.8
Default on
Determines whether the compiler reports typed holes warnings. Has no effect unless
typed holes errors are deferred until runtime. See Typed Holes (page 266) and Deferring
type errors to runtime (page 351)
-Wdeferred-type-errors
Since 8.4
Causes a warning to be reported when a type error is deferred until runtime. See Defer-
ring type errors to runtime (page 351)
This warning is on by default.
-fdefer-type-errors
Implies -fdefer-typed-holes (page 89), -fdefer-out-of-scope-variables
(page 89)
Defer as many type errors as possible until runtime. At compile time you get a warning
(instead of an error). At runtime, if you use a value that depends on a type error, you
get a runtime error; but you can run any type-correct parts of your code just fine. See
Deferring type errors to runtime (page 351)
-fdefer-typed-holes
Defer typed holes errors (errors about names with a leading underscore (e.g., “_”, “_foo”,
“_bar”)) until runtime. This will turn the errors produced by typed holes (page 266) into
warnings. Using a value that depends on a typed hole produces a runtime error, the
same as -fdefer-type-errors (page 88) (which implies this option). See Typed Holes
(page 266) and Deferring type errors to runtime (page 351).
Implied by -fdefer-type-errors (page 88). See also -Wtyped-holes (page 88).
-fdefer-out-of-scope-variables
Since 8.0
Defer variable out-of-scope errors (errors about names without a leading underscore)
until runtime. This will turn variable-out-of-scope errors into warnings. Using a value
that depends on an out-of-scope variable produces a runtime error, the same as -fdefer-
type-errors (page 88) (which implies this option). See Typed Holes (page 266) and
Deferring type errors to runtime (page 351).
Implied by -fdefer-type-errors (page 88). See also -Wdeferred-out-of-scope-
variables (page 89).
-Wdeferred-out-of-scope-variables
Warn when a deferred out-of-scope variable is encountered.
-Wpartial-type-signatures
Since 7.10
Determines whether the compiler reports holes in partial type signatures as warnings.
Has no effect unless PartialTypeSignatures (page 444) is enabled, which controls
whether errors should be generated for holes in types or not. See Partial Type Signatures
(page 444).
This warning is on by default.
-fhelpful-errors
When a name or package is not found in scope, make suggestions for the name or package
you might have meant instead.
This option is on by default.
-Wunrecognised-pragmas
Since 6.10
Causes a warning to be emitted when a pragma that GHC doesn’t recognise is used. As
well as pragmas that GHC itself uses, GHC also recognises pragmas known to be used
by other tools, e.g. OPTIONS_HUGS and DERIVE.
This option is on by default.
-Wmissed-specialisations
Since 8.0
Emits a warning if GHC cannot specialise an overloaded function, usually because the
function needs an INLINABLE pragma. Reports when the situation arises during special-
isation of an imported function.
This form is intended to catch cases where an imported function that is marked as IN-
LINABLE (presumably to enable specialisation) cannot be specialised as it calls other
functions that are themselves not specialised.
Note that this warning will not throw errors if used with -Werror (page 87).
This option is off by default.
-Wall-missed-specialisations
Since 8.0
Emits a warning if GHC cannot specialise an overloaded function, usually because the
function needs an INLINABLE pragma. Reports all such situations.
Note that this warning will not throw errors if used with -Werror (page 87).
This option is off by default.
-Wwarnings-deprecations
Since 6.10
Causes a warning to be emitted when a module, function or type with a WARNING or
DEPRECATED pragma is used. See WARNING and DEPRECATED pragmas (page 519) for
more details on the pragmas.
This option is on by default.
-Wdeprecations
Causes a warning to be emitted when a module, function or type with a WARNING or
DEPRECATED pragma is used. See WARNING and DEPRECATED pragmas (page 519) for
more details on the pragmas. An alias for -Wwarnings-deprecations (page 90).
This option is on by default.
-Wnoncanonical-monad-instances
Since 8.0
Warn if noncanonical Applicative or Monad instances declarations are detected.
When this warning is enabled, the following conditions are verified:
In Monad instances declarations warn if any of the following conditions does not hold:
•If return is defined it must be canonical (i.e. return = pure).
•If (>>) is defined it must be canonical (i.e. (>>) = (*>)).
Moreover, in Applicative instance declarations:
•Warn if pure is defined backwards (i.e. pure = return).
•Warn if (*>) is defined backwards (i.e. (*>) = (>>)).
This option is off by default.
-Wnoncanonical-monadfail-instances
Since 8.0
Since 7.6
Causes a warning to be emitted for foreign declarations that use unsupported calling
conventions. In particular, if the stdcall calling convention is used on an architecture
other than i386 then it will be treated as ccall.
-Wdodgy-foreign-imports
Since 6.10
Causes a warning to be emitted for foreign imports of the following form:
foreign import "f" f :: FunPtr t
The first form declares that f is a (pure) C function that takes no arguments and returns
a pointer to a C function with type t, whereas the second form declares that f itself is a
C function with type t. The first declaration is usually a mistake, and one that is hard to
debug because it results in a crash, hence this warning.
-Wdodgy-exports
Since 6.12
Causes a warning to be emitted when a datatype T is exported with all constructors, i.e.
T(..), but is it just a type synonym.
Also causes a warning to be emitted when a module is re-exported, but that module
exports nothing.
-Wdodgy-imports
Since 6.8
Causes a warning to be emitted in the following cases:
•When a datatype T is imported with all constructors, i.e. T(..), but has been ex-
ported abstractly, i.e. T.
•When an import statement hides an entity that is not exported.
-Woverflowed-literals
Since 7.8
Causes a warning to be emitted if a literal will overflow, e.g. 300 :: Word8.
-Wempty-enumerations
Since 7.8
Causes a warning to be emitted if an enumeration is empty, e.g. [5 .. 3].
-Wderiving-defaults
Since 8.10
Causes a warning when both DeriveAnyClass (page 384) and GeneralizedNewtypeD-
eriving (page 378) are enabled and no explicit deriving strategy is in use. For example,
this would result a warning:
class C a
newtype T a = MkT a deriving C
-Wduplicate-constraints
Since 7.8
Have the compiler warn about duplicate constraints in a type signature. For example
The warning will indicate the redundant Eq a constraint: it is subsumed by the Ord
a constraint.
•A constraint in the type signature is not used in the code it covers:
The warning will indicate the redundant Eq a constraint: : it is not used by the
definition of f.)
Similar warnings are given for a redundant constraint in an instance declaration.
When turning on, you can suppress it on a per-module basis with -Wno-redundant-
constraints (page 93). Occasionally you may specifically want a function to have a
more constrained signature than necessary, perhaps to leave yourself wiggle-room for
changing the implementation without changing the API. In that case, you can suppress
the warning on a per-function basis, using a call in a dead binding. For example:
Here the call to (==) makes GHC think that the (Eq a) constraint is needed, so no
warning is issued.
-Wduplicate-exports
Have the compiler warn about duplicate entries in export lists. This is useful information
if you maintain large export lists, and want to avoid the continued export of a definition
after you’ve deleted (one) mention of it in the export list.
This option is on by default.
-Whi-shadowing
Causes the compiler to emit a warning when a module or interface file in the current
directory is shadowing one with the same module name in a library or other directory.
This flag was not implemented correctly and is now deprecated. It will be removed in a
later version of GHC.
-Widentities
Since 7.2
Causes the compiler to emit a warning when a Prelude numeric conversion converts
a type T to the same type T; such calls are probably no-ops and can be omitted. The
functions checked for are: toInteger, toRational, fromIntegral, and realToFrac.
-Wimplicit-kind-vars
Since 8.6
Have the compiler warn if a kind variable is not explicitly quantified over. For instance,
the following would produce a warning:
f :: forall (a :: k). Proxy a
-Wimplicit-prelude
Since 6.8
Have the compiler warn if the Prelude is implicitly imported. This happens unless either
the Prelude module is explicitly imported with an import ... Prelude ... line, or
this implicit import is disabled (either by NoImplicitPrelude (page 259) or a LANGUAGE
NoImplicitPrelude pragma).
Note that no warning is given for syntax that implicitly refers to the Prelude, even if NoIm-
plicitPrelude (page 259) would change whether it refers to the Prelude. For example,
no warning is given when 368 means [Link] (368::[Link])
(where Prelude refers to the actual Prelude module, regardless of the imports of the
module being compiled).
This warning is off by default.
-Wincomplete-patterns
Since 5.04
The option -Wincomplete-patterns (page 94) warns about places where a pattern-
match might fail at runtime. The function g below will fail when applied to non-empty
lists, so the compiler will emit a warning about this when -Wincomplete-patterns
(page 94) is enabled.
g [] = 2
This option isn’t enabled by default because it can be a bit noisy, and it doesn’t always
indicate a bug in the program. However, it’s generally considered good practice to cover
all the cases in your functions, and it is switched on by -W (page 86).
-Wincomplete-uni-patterns
Since 7.2
The flag -Wincomplete-uni-patterns (page 94) is similar to -Wincomplete-patterns
(page 94), except that it applies only to lambda-expressions and pattern bindings, con-
structs that only allow a single pattern:
h = \[] -> 2
Just k = f y
-fmax-pmcheck-models=⟨n⟩
Default 30
The pattern match checker works by assigning symbolic values to each pattern. We call
each such assignment a ‘model’. Now, each pattern match clause leads to potentially
multiple splits of that model, encoding different ways for the pattern match to fail. For
example, when matching x against Just 4, we split each incoming matching model into
two uncovered sub-models: One where x is Nothing and one where x is Just y but y is
not 4.
This can be exponential in the arity of the pattern and in the number of guards in some
cases. The -fmax-pmcheck-models=⟨n⟩ (page 95) limit makes sure we scale polynomi-
ally in the number of patterns, by forgetting refined information gained from a partially
successful match. For the above example, if we had a limit of 1, we would continue
checking the next clause with the original, unrefined model.
-Wincomplete-record-updates
Since 6.4
The function f below will fail when applied to Bar, so the compiler will emit a warning
about this when -Wincomplete-record-updates (page 95) is enabled.
data Foo = Foo { x :: Int }
| Bar
This option isn’t enabled by default because it can be very noisy, and it often doesn’t
indicate a bug in the program.
-Wmissing-deriving-strategies
Since 8.8
The datatype below derives the Eq typeclass, but doesn’t specify a strategy. When -
Wmissing-deriving-strategies (page 95) is enabled, the compiler will emit a warning
about this.
data Foo a = Foo a
deriving (Eq)
The compiler will warn here that the deriving clause doesn’t specify a strategy. If the
warning is enabled, but DerivingStrategies (page 386) is not enabled, the compiler
will suggest turning on the DerivingStrategies (page 386) extension. This option is
not on by default, having to be turned on manually or with -Weverything (page 87).
-Wmissing-fields
This option is on by default, and warns you whenever the construction of a labelled field
constructor isn’t complete, missing initialisers for one or more fields. While not an error
(the missing fields are initialised with bottoms), it is often an indication of a programmer
error.
-Wmissing-export-lists
Since 8.4
This flag warns if you declare a module without declaring an explicit export list. For
example
module M where
p x = x
The -Wmissing-export-lists (page 95) flag will warn that M does not declare an export
list. Declaring an explicit export list for M enables GHC dead code analysis, prevents
accidental export of names and can ease optimizations like inlining.
-Wmissing-import-lists
Since 7.0
This flag warns if you use an unqualified import declaration that does not explicitly list
the entities brought into scope. For example
module M where
import X( f )
import Y
import qualified Z
p x = f x x
The -Wmissing-import-lists (page 96) flag will warn about the import of Y but not X
If module Y is later changed to export (say) f, then the reference to f in M will become
ambiguous. No warning is produced for the import of Z because extending Z‘s exports
would be unlikely to produce ambiguity in M.
-Wmissing-methods
This option is on by default, and warns you whenever an instance declaration is missing
one or more methods, and the corresponding class declaration has no default declaration
for them.
The MINIMAL pragma can be used to change which combination of methods will be re-
quired for instances of a particular class. See MINIMAL pragma (page 520).
-Wmissing-signatures
If you would like GHC to check that every top-level function/value has a type signature,
use the -Wmissing-signatures (page 96) option. As part of the warning GHC also re-
ports the inferred type. The option is off by default.
-Wmissing-exported-sigs
Since 7.10
This option is now deprecated in favour of -Wmissing-exported-signatures (page 96).
-Wmissing-exported-signatures
Since 8.0
If you would like GHC to check that every exported top-level function/value has a type
signature, but not check unexported values, use the -Wmissing-exported-signatures
(page 96) option. This option takes precedence over -Wmissing-signatures (page 96).
As part of the warning GHC also reports the inferred type. The option is off by default.
-Wmissing-local-sigs
Since 7.0
This option is now deprecated in favour of -Wmissing-local-signatures (page 96).
-Wmissing-local-signatures
Since 8.0
If you use the -Wmissing-local-signatures (page 96) flag GHC will warn you about
any polymorphic local bindings. As part of the warning GHC also reports the inferred
type. The option is off by default.
-Wmissing-pattern-synonym-signatures
Since 8.0
If you would like GHC to check that every pattern synonym has a type signature, use
the -Wmissing-pattern-synonym-signatures (page 97) option. If this option is used
in conjunction with -Wmissing-exported-signatures (page 96) then only exported pat-
tern synonyms must have a type signature. GHC also reports the inferred type. This
option is off by default.
-Wname-shadowing
This option causes a warning to be emitted whenever an inner-scope value has the same
name as an outer-scope value, i.e. the inner value shadows the outer one. This can catch
typographical errors that turn into hard-to-find bugs, e.g., in the inadvertent capture of
what would be a recursive call in f = ... let f = id in ... f ....
The warning is suppressed for names beginning with an underscore. For example
-Worphans
Since 6.4
These flags cause a warning to be emitted whenever the module contains an “orphan”
instance declaration or rewrite rule. An instance declaration is an orphan if it appears
in a module in which neither the class nor the type being instanced are declared in the
same module. A rule is an orphan if it is a rule for a function declared in another module.
A module containing any orphans is called an orphan module.
The trouble with orphans is that GHC must pro-actively read the interface files for all
orphan modules, just in case their instances or rules play a role, whether or not the
module’s interface would otherwise be of any use. See Orphan modules and instance
declarations (page 191) for details.
The flag -Worphans (page 97) warns about user-written orphan rules or instances.
-Woverlapping-patterns
By default, the compiler will warn you if a set of patterns are overlapping, e.g.,
where the last pattern match in f won’t ever be reached, as the second pattern overlaps
it. More often than not, redundant patterns is a programmer mistake/error, so this option
is enabled by default.
-Winaccessible-code
Since 8.6
By default, the compiler will warn you if types make a branch inaccessible. This generally
requires GADTs or similar extensions.
Take, for example, the following program
step2 :: Bool
step2 = case checkTEQ Foo1 Foo2 of
Just Refl -> True -- Inaccessible code
Nothing -> False
The Just Refl case in step2 is inaccessible, because in order for checkTEQ to be able to
produce a Just, t ~ u must hold, but since we’re passing Foo1 and Foo2 here, it follows
that t ~ Char, and u ~ Int, and thus t ~ u cannot hold.
-Wstar-is-type
Since 8.6
The use of * to denote the kind of inhabited types relies on the StarIsType (page 331) ex-
tension, which in a future release will be turned off by default and then possibly removed.
The reasons for this and the deprecation schedule are described in GHC proposal #30.
This warning allows to detect such uses of * before the actual breaking change takes
place. The recommended fix is to replace * with Type imported from [Link].
Being part of the -Wcompat (page 87) option group, this warning is off by default, but
will be switched on in a future GHC release.
-Wstar-binder
Since 8.6
Under StarIsType (page 331), a * in types is not an operator nor even a name, it is special
syntax that stands for [Link]. This means that an expression like Either *
Char is parsed as Either (*) Char and not (*) Either Char.
In binding positions, we have similar parsing rules. Consider the following example
type family a + b
type family a * b
While a + b is parsed as (+) a b and becomes a binding position for the (+) type oper-
ator, a * b is parsed as a (*) b and is rejected.
As a workaround, we allow to bind (*) in prefix form:
Here the Eq [a] in the signature overlaps with the top-level instance for Eq [a]. GHC
goes to some efforts to use the former, but if it should use the latter, it would then have
an insoluble Eq a constraint. Best avoided by instead writing:
f :: Eq a => a -> a
This option is on by default. As usual you can suppress it on a per-module basis with
-Wno-simplifiable-class-constraints (page 99).
-Wtabs
Since 6.8
Have the compiler warn if there are tabs in your source file.
-Wtype-defaults
Have the compiler warn/inform you where in your source the Haskell defaulting mecha-
nism for numeric types kicks in. This is useful information when converting code from
a context that assumed one default into one with another, e.g., the ‘default default’ for
Haskell 1.4 caused the otherwise unconstrained value 1 to be given the type Int, whereas
Haskell 98 and later defaults it to Integer. This may lead to differences in performance
and behaviour, hence the usefulness of being non-silent about this.
This warning is off by default.
-Wmonomorphism-restriction
Since 6.8
Have the compiler warn/inform you where in your source the Haskell Monomorphism
Restriction is applied. If applied silently the MR can give rise to unexpected behaviour,
so it can be helpful to have an explicit warning that it is being applied.
This warning is off by default.
-Wunsupported-llvm-version
Since 7.8
Warn when using -fllvm (page 216) with an unsupported version of LLVM.
-Wmissed-extra-shared-lib
Since 8.8
Warn when GHCi can’t load a shared lib it deduced it should load when loading a package
and analyzing the extra-libraries stanza of the target package description.
-Wunticked-promoted-constructors
Since 7.10
Warn if a promoted data constructor is used without a tick preceding its name.
For example:
Will raise two warnings because Zero and Succ are not written as 'Zero and 'Succ.
This warning is enabled by default in -Wall (page 86) mode.
-Wunused-binds
Report any function definitions (and local bindings) which are unused. An alias for
•-Wunused-top-binds (page 100)
•-Wunused-local-binds (page 100)
•-Wunused-pattern-binds (page 100)
-Wunused-top-binds
Since 8.0
Report any function definitions which are unused.
More precisely, warn if a binding brings into scope a variable that is not used, except if
the variable’s name starts with an underscore. The “starts-with-underscore” condition
provides a way to selectively disable the warning.
A variable is regarded as “used” if
•It is exported, or
•It appears in the right hand side of a binding that binds at least one used variable
that is used
For example:
-Wunused-local-binds
Since 8.0
Report any local definitions which are unused. For example:
-Wunused-pattern-binds
Since 8.0
Warn if a pattern binding binds no variables at all, unless it is a lone wild-card pattern,
or a banged pattern. For example:
In general a lazy pattern binding p = e is a no-op if p does not bind any variables. The
motivation for allowing lone wild-card patterns is they are not very different from _v =
rhs3, which elicits no warning; and they can be useful to add a type constraint, e.g. _
= x::Int. A banged pattern (see Bang patterns and Strict Haskell (page 461)) is not a
no-op, because it forces evaluation, and is useful as an alternative to seq.
-Wunused-imports
Report any modules that are explicitly imported but never used. However, the form
import M() is never reported as an unused import, because it is a useful idiom for im-
porting instance declarations, which are anonymous in Haskell.
-Wunused-matches
Report all unused variables which arise from term-level pattern matches, including pat-
terns consisting of a single variable. For instance f x y = [] would report x and y as
unused. The warning is suppressed if the variable name begins with an underscore, thus:
f _x = True
Note that -Wunused-matches (page 101) does not warn about variables which arise from
type-level patterns, as found in type family and data family instances. This must be
enabled separately through the -Wunused-type-patterns (page 101) flag.
-Wunused-do-bind
Since 6.12
Report expressions occurring in do and mdo blocks that appear to silently throw informa-
tion away. For instance do { mapM popInt xs ; return 10 } would report the first
statement in the do block as suspicious, as it has the type StackM [Int] and not StackM
(), but that [Int] value is not bound to anything. The warning is suppressed by explicitly
mentioning in the source code that your program is throwing something away:
-Wunused-type-patterns
Since 8.0
Report all unused implicitly bound type variables which arise from patterns in type family
and data family instances. For instance:
type instance F x y = []
would report x and y as unused on the right hand side. The warning is suppressed if the
type variable name begins with an underscore, like so:
type instance F _x _y = []
When ExplicitForAll (page 431) is enabled, explicitly quantified type variables may
also be identified as unused. For instance:
type instance forall x y. F x y = []
f1 :: P -> Int
f1 P{..} = 1 + 3
f1 :: P -> Int
f1 P{x,y,..} = x + y
would report that the P{x,y,..} match has a redundant use of ...
-Wwrong-do-bind
Since 6.12
Report expressions occurring in do and mdo blocks that appear to lack a binding. For
instance do { return (popInt 10) ; return 10 } would report the first statement in
the do block as suspicious, as it has the type StackM (StackM Int) (which consists of two
nested applications of the same monad constructor), but which is not then “unpacked”
by binding the result. The warning is suppressed by explicitly mentioning in the source
code that your program is throwing something away:
For almost all sensible programs this will indicate a bug, and you probably intended to
write:
do { popInt 10 ; return 10 }
-Winline-rule-shadowing
Since 7.8
Warn if a rewrite RULE might fail to fire because the function might be inlined before
the rule has a chance to fire. See How rules interact with INLINE/NOINLINE pragmas
(page 507).
-Wcpp-undef
Since 8.2
This flag passes -Wundef to the C pre-processor (if its being used) which causes the
pre-processor to warn on uses of the #if directive on undefined identifiers.
-Wunbanged-strict-patterns
Since 8.2
This flag warns whenever you write a pattern that binds a variable whose type is un-
lifted, and yet the pattern is not a bang pattern nor a bare variable. See Unboxed types
(page 473) for information about unlifted types.
-Wmissing-home-modules
Since 8.2
When a module provided by the package currently being compiled (i.e. the “home” pack-
age) is imported, but not explicitly listed in command line as a target. Useful for Cabal
to ensure GHC won’t pick up modules, not listed neither in exposed-modules, nor in
other-modules.
-Wpartial-fields
Since 8.4
The option -Wpartial-fields (page 103) warns about record fields that could fail when
accessed via a lacking constructor. The function f below will fail when applied to Bar,
so the compiler will emit a warning at its definition when -Wpartial-fields (page 103)
is enabled.
The warning is suppressed if the field name begins with an underscore.
-Wunused-packages
Since 8.10
The option -Wunused-packages (page 103) warns about packages, specified on command
line via -package ⟨pkg⟩ (page 194) or -package-id ⟨unit-id⟩ (page 195), but were not
loaded during compilation. Usually it means that you have an unused dependency.
You may want to enable this warning on a clean build or enable -fforce-recomp
(page 180) in order to get reliable results.
-Winvalid-haddock
Since 9.0
When the -haddock option is enabled, GHC collects documentation comments and asso-
ciates them with declarations, function arguments, data constructors, and other syntac-
tic elements. Documentation comments in invalid positions are discarded:
myValue =
-- | Invalid (discarded) comment in an expression
2 + 2
This warning informs you about discarded documentation comments. It has no effect
when -haddock (page 85) is disabled.
-Wauto-orphans
Since 7.4
Does nothing.
-Wmissing-space-after-bang
Since 8.8
Does nothing.
-Wderiving-typeable
Since 7.10
This flag warns when Typeable is listed in a deriving clause or derived with StandaloneD-
eriving (page 368).
Since GHC 7.10, Typeable is automatically derived for all types. Thus, deriving Typeable
yourself is redundant.
-Wunicode-bidirectional-format-characters
Explicit unicode bidirectional formatting characters can cause source code to be ren-
dered misleadingly in many viewers. We warn if any such character is present in the
source.
Specifically, the characters disallowed by this warning are those which are a part of the
‘Explicit Formatting‘ category of the Unicode Bidirectional Character Type Listing
Since 9.0.2
If you’re feeling really paranoid, the -dcore-lint (page 234) option is a good choice. It turns
on heavyweight intra-pass sanity-checking within GHC. (It checks GHC’s sanity, not yours.)
The -O* options specify convenient “packages” of optimisation flags; the -f* options de-
scribed later on specify individual optimisations to be turned on/off; the -m* options specify
machine-specific optimisations to be turned on/off.
Most of these options are boolean and have options to turn them both “on” and “off” (be-
ginning with the prefix no-). For instance, while -fspecialise enables specialisation, -fno-
specialise disables it. When multiple flags for the same option appear in the command-line
they are evaluated from left to right. For instance, -fno-specialise -fspecialise will en-
able specialisation.
It is important to note that the -O* flags are roughly equivalent to combinations of -f* flags.
For this reason, the effect of the -O* and -f* flags is dependent upon the order in which they
occur on the command line.
For instance, take the example of -fno-specialise -O1. Despite the -fno-specialise ap-
pearing in the command line, specialisation will still be enabled. This is the case as -O1
implies -fspecialise, overriding the previous flag. By contrast, -O1 -fno-specialise will
compile without specialisation, as one would expect.
There are many options that affect the quality of code produced by GHC. Most people only
have a general goal, something like “Compile quickly” or “Make my program run like greased
lightning.” The following “packages” of optimisations (or lack thereof) should suffice.
Note that higher optimisation levels cause more cross-module optimisation to be performed,
which can have an impact on how much of your program needs to be recompiled when you
change something. This is one reason to stick to no-optimisation when developing code.
No ‘‘-O*‘‘-type option specified: This is taken to mean “Please compile quickly; I’m not
over-bothered about compiled-code quality.” So, for example, ghc -c [Link]
-O0
Means “turn off all optimisation”, reverting to the same settings as if no -O options had
been specified. Saying -O0 can be useful if e.g. make has inserted a -O on the command
line already.
-O
-O1
Means: “Generate good-quality code without taking too long about it.” Thus, for exam-
ple: ghc -c -O [Link]
-O2
Means: “Apply every non-dangerous optimisation, even if it means significantly longer
compile times.”
The avoided “dangerous” optimisations are those that can make runtime or space worse
if you’re unlucky. They are normally turned on or off individually.
-O⟨n⟩
Any -On where n > 2 is the same as -O2.
We don’t use a -O* flag for day-to-day work. We use -O to get respectable speed; e.g., when
we want to measure something. When we want to go for broke, we tend to use -O2 (and we
go for lots of coffee breaks).
The easiest way to see what -O (etc.) “really mean” is to run with -v (page 79), then stand
back in amazement.
These flags turn on and off individual optimisations. Flags marked as on by default are enabled
by -O, and as such you shouldn’t need to set any of them explicitly. A flag -fwombat can be
negated by saying -fno-wombat.
-fcase-merge
Default on
Merge immediately-nested case expressions that scrutinise the same variable. For ex-
ample,
case x of
Red -> e1
_ -> case x of
Blue -> e2
Green -> e3
Is transformed to,
case x of
Red -> e1
Blue -> e2
Green -> e2
-fcase-folding
Default on
Allow constant folding in case expressions that scrutinise some primops: For example,
Is transformed to,
case x of
20## -> e1
30## -> e2
_ -> let v = x `minusWord#` 10## in e3
-fcall-arity
Default on
Enable call-arity analysis.
-fexitification
Default on
Enables the floating of exit paths out of recursive functions.
-fcmm-elim-common-blocks
Default on
Enables the common block elimination optimisation in the code generator. This optimi-
sation attempts to find identical Cmm blocks and eliminate the duplicates.
-fcmm-sink
Default on
Enables the sinking pass in the code generator. This optimisation attempts to find iden-
tical Cmm blocks and eliminate the duplicates attempts to move variable bindings closer
to their usage sites. It also inlines simple expressions like literals or registers.
-fcmm-static-pred
Default off but enabled with -O (page 105).
This enables static control flow prediction on the final Cmm code. If enabled GHC will
apply certain heuristics to identify loops and hot code paths. This information is then
used by the register allocation and code layout passes.
-fasm-shortcutting
Default off
This enables shortcutting at the assembly stage of the code generator. In simpler terms
shortcutting means if a block of instructions A only consists of a unconditionally jump,
we replace all jumps to A by jumps to the successor of A.
This is mostly done during Cmm passes. However this can miss corner cases. So at -O2
we run the pass again at the asm stage to catch these.
-fblock-layout-cfg
Default off but enabled with -O (page 105).
The new algorithm considers all outgoing edges of a basic blocks for code layout instead
of only the last jump instruction. It also builds a control flow graph for functions, tries to
find hot code paths and place them sequentially leading to better cache utilization and
performance.
This is expected to improve performance on average, but actual performance difference
can vary.
If you find cases of significant performance regressions, which can be traced back to
obviously bad code layout please open a ticket.
-fblock-layout-weights
This flag is hacker territory. The main purpose of this flag is to make it easy to debug
and tune the new code layout algorithm. There is no guarantee that values giving better
results now won’t be worse with the next release.
If you feel your code warrants modifying these settings please consult the source code
for default values and documentation. But I strongly advise against this.
-fblock-layout-weightless
Default off
When not using the cfg based blocklayout layout is determined either by the last jump
in a basic block or the heaviest outgoing edge of the block in the cfg.
With this flag enabled we use the last jump instruction in blocks. Without this flags the
old algorithm also uses the heaviest outgoing edge.
When this flag is enabled and -fblock-layout-cfg (page 107) is disabled block layout
behaves the same as in 8.6 and earlier.
-fcpr-anal
Default on
Turn on CPR analysis in the demand analyser.
-fcse
Default on
Enables the common-sub-expression elimination optimisation. Switching this off can be
useful if you have some unsafePerformIO expressions that you don’t want commoned-
up.
-fstg-cse
Default on
Enables the common-sub-expression elimination optimisation on the STG intermediate
language, where it is able to common up some subexpressions that differ in their types,
but not their representation.
-fdicts-cheap
Default off
A very experimental flag that makes dictionary-valued expressions seem cheap to the
optimiser.
-fdicts-strict
Default off
Make dictionaries strict.
-fdmd-tx-dict-sel
Default on
Use a special demand transformer for dictionary selectors. Behaviour is unconditionally
enabled starting with 9.2
-fdo-eta-reduction
Default on
Eta-reduce lambda expressions, if doing so gets rid of a whole group of lambdas.
-fdo-lambda-eta-expansion
Default on
Eta-expand let-bindings to increase their arity.
-feager-blackholing
Default off
Usually GHC black-holes a thunk only when it switches threads. This flag makes it do so
as soon as the thunk is entered. See Haskell on a shared-memory multiprocessor.
See Compile-time options for SMP parallelism (page 118) for a discussion on its use.
-fexcess-precision
Default off
When this option is given, intermediate floating point values can have a greater preci-
sion/range than the final type. Generally this is a good thing, but some programs may
rely on the exact precision/range of Float/Double values and should not use this option
for their compilation.
Note that the 32-bit x86 native code generator only supports excess-precision mode,
so neither -fexcess-precision nor -fno-excess-precision has any effect. This is a
known bug, see Bugs in GHC (page 610).
-fexpose-all-unfoldings
Default off
An experimental flag to expose all unfoldings, even for very large or recursive functions.
This allows for all functions to be inlined while usually GHC would avoid inlining larger
functions.
-ffloat-in
Default on
Float let-bindings inwards, nearer their binding site. See Let-floating: moving bindings
to give faster programs (ICFP‘96).
This optimisation moves let bindings closer to their use site. The benefit here is that
this may avoid unnecessary allocation if the branch the let is now on is never executed.
It also enables other optimisation passes to work more effectively as they have more
information locally.
This optimisation isn’t always beneficial though (so GHC applies some heuristics to de-
cide when to apply it). The details get complicated but a simple example is that it is often
beneficial to move let bindings outwards so that multiple let bindings can be grouped into
a larger single let binding, effectively batching their allocation and helping the garbage
collector and allocator.
-ffull-laziness
Default on
Run the full laziness optimisation (also known as let-floating), which floats let-bindings
outside enclosing lambdas, in the hope they will be thereby be computed less often. See
Let-floating: moving bindings to give faster programs (ICFP‘96). Full laziness increases
sharing, which can lead to increased memory residency.
Note: GHC doesn’t implement complete full laziness. Although GHC’s full-laziness op-
timisation does enable some transformations which would be performed by a fully lazy
implementation (such as extracting repeated computations from loops), these transfor-
mations are not applied consistently, so don’t rely on them.
-ffun-to-thunk
Default off
Worker-wrapper removes unused arguments, but usually we do not remove them all,
lest it turn a function closure into a thunk, thereby perhaps creating a space leak and/or
disrupting inlining. This flag allows worker/wrapper to remove all value lambdas.
-fignore-asserts
Default on
Causes GHC to ignore uses of the function [Link] in source code (in other
words, rewriting [Link] p e to e (see Assertions (page 515)).
-fignore-interface-pragmas
Default off
Tells GHC to ignore all inessential information when reading interface files. That is, even
if [Link] contains unfolding or strictness information for a function, GHC will ignore that
information.
-flate-dmd-anal
Default off
Run demand analysis again, at the end of the simplification pipeline. We found some
opportunities for discovering strictness that were not visible earlier; and optimisations
like -fspec-constr (page 112) can create functions with unused arguments which are
eliminated by late demand analysis. Improvements are modest, but so is the cost. See
notes on the wiki page.
-fliberate-case
Default off but enabled with -O2 (page 105).
Turn on the liberate-case transformation. This unrolls recursive function once in its own
RHS, to avoid repeated case analysis of free variables. It’s a bit like the call-pattern
specialiser (-fspec-constr (page 112)) but for free variables rather than arguments.
-fliberate-case-threshold=⟨n⟩
Default 2000
Set the size threshold for the liberate-case transformation.
-floopification
Default on
When this optimisation is enabled the code generator will turn all self-recursive saturated
tail calls into local jumps rather than function calls.
-fllvm-pass-vectors-in-regs
Default on
Instructs GHC to use the platform’s native vector registers to pass vector arguments
during function calls. As with all vector support, this requires -fllvm (page 216).
-fmax-inline-alloc-size=⟨n⟩
Default 128
Set the maximum size of inline array allocations to n bytes. GHC will allocate non-pinned
arrays of statically known size in the current nursery block if they’re no bigger than n
bytes, ignoring GC overheap. This value should be quite a bit smaller than the block size
(typically: 4096).
-fmax-inline-memcpy-insns=⟨n⟩
Default 32
Inline memcpy calls if they would generate no more than ⟨n⟩ pseudo-instructions.
-fmax-inline-memset-insns=⟨n⟩
Default 32
Inline memset calls if they would generate no more than n pseudo instructions.
-fmax-relevant-binds=⟨n⟩
Default 6
The type checker sometimes displays a fragment of the type environment in error mes-
sages, but only up to some maximum number, set by this flag. Turning it off with -
fno-max-relevant-binds gives an unlimited number. Syntactically top-level bindings
are also usually excluded (since they may be numerous), but -fno-max-relevant-binds
includes them too.
-fmax-uncovered-patterns=⟨n⟩
Default 4
Maximum number of unmatched patterns to be shown in warnings generated by -
Wincomplete-patterns (page 94) and -Wincomplete-uni-patterns (page 94).
-fmax-simplifier-iterations=⟨n⟩
Default 4
Sets the maximal number of iterations for the simplifier.
-fmax-worker-args=⟨n⟩
Default 10
A function will not be split into worker and wrapper if the number of value arguments of
the resulting worker exceeds both that of the original function and this setting.
-fno-opt-coercion
Default coercion optimisation enabled.
Turn off the coercion optimiser.
-fno-pre-inlining
Default pre-inlining enabled
Turn off pre-inlining.
-fno-state-hack
Default state hack is enabled
Turn off the “state hack” whereby any lambda with a State# token as argument is con-
sidered to be single-entry, hence it is considered okay to inline things inside it. This can
improve performance of IO and ST monad code, but it runs the risk of reducing sharing.
-fomit-interface-pragmas
Default Implied by -O0 (page 105), otherwise off.
Tells GHC to omit all inessential information from the interface file generated for the
module being compiled (say M). This means that a module importing M will see only
the types of the functions that M exports, but not their unfoldings, strictness info, etc.
Hence, for example, no function exported by M will be inlined into an importing module.
The benefit is that modules that import M will need to be recompiled less often (only
when M’s exports change their type, not when they change their implementation).
-fomit-yields
Default yield points enabled
Tells GHC to omit heap checks when no allocation is being performed. While this im-
proves binary sizes by about 5%, it also means that threads run in tight non-allocating
loops will not get preempted in a timely fashion. If it is important to always be able to
interrupt such threads, you should turn this optimization off. Consider also recompiling
all libraries with this optimization turned off, if you need to guarantee interruptibility.
-fpedantic-bottoms
Default off
Make GHC be more precise about its treatment of bottom (but see also -fno-state-hack
(page 111)). In particular, stop GHC eta-expanding through a case expression, which is
good for performance, but bad if you are using seq on partial applications.
-fregs-graph
Default off due to a performance regression bug (#7679)
Only applies in combination with the native code generator. Use the graph colouring reg-
ister allocator for register allocation in the native code generator. By default, GHC uses
a simpler, faster linear register allocator. The downside being that the linear register
allocator usually generates worse code.
Note that the graph colouring allocator is a bit experimental and may fail when faced
with code with high register pressure #8657.
-fregs-iterative
Default off
Only applies in combination with the native code generator. Use the iterative coalescing
graph colouring register allocator for register allocation in the native code generator.
This is the same register allocator as the -fregs-graph (page 111) one but also enables
iterative coalescing during register allocation.
-fsimplifier-phases=⟨n⟩
Default 2
Set the number of phases for the simplifier. Ignored with -O0.
-fsimpl-tick-factor=⟨n⟩
Default 100
GHC’s optimiser can diverge if you write rewrite rules (Rewrite rules (page 504)) that
don’t terminate, or (less satisfactorily) if you code up recursion through data types (Bugs
in GHC (page 610)). To avoid making the compiler fall into an infinite loop, the optimiser
carries a “tick count” and stops inlining and applying rewrite rules when this count is
exceeded. The limit is set as a multiple of the program size, so bigger programs get more
ticks. The -fsimpl-tick-factor flag lets you change the multiplier. The default is 100;
numbers larger than 100 give more ticks, and numbers smaller than 100 give fewer.
If the tick-count expires, GHC summarises what simplifier steps it has done; you can use
-fddump-simpl-stats to generate a much more detailed list. Usually that identifies the
loop quite accurately, because some numbers are very large.
-fspec-constr
Default off but enabled by -O2 (page 105).
Turn on call-pattern specialisation; see Call-pattern specialisation for Haskell programs.
This optimisation specializes recursive functions according to their argument “shapes”.
This is best explained by example so consider:
In this code, once we pass the initial check for an empty list we know that in the recursive
case this pattern match is redundant. As such -fspec-constr will transform the above
code to:
As well avoid unnecessary pattern matching it also helps avoid unnecessary allocation.
This applies when a argument is strict in the recursive call to itself but not on the initial
entry. As strict recursive branch of the function is created similar to the above example.
It is also possible for library writers to instruct GHC to perform call-pattern specialisation
extremely aggressively. This is necessary for some highly optimized libraries, where we
may want to specialize regardless of the number of specialisations, or the size of the
code. As an example, consider a simplified use-case from the vector library:
Here, after GHC inlines the body of foldl to a call site, it will perform call-pattern
specialisation very aggressively on foldl_loop due to the use of SPEC in the argument
of the loop body. SPEC from [Link] is specifically recognised by the compiler.
(NB: it is extremely important you use seq or a bang pattern on the SPEC argument!)
In particular, after inlining this will expose f to the loop body directly, allowing heavy
specialisation over the recursive cases.
-fspec-constr-keen
Default off
If this flag is on, call-pattern specialisation will specialise a call (f (Just x)) with an
explicit constructor argument, even if the argument is not scrutinised in the body of the
function. This is sometimes beneficial; e.g. the argument might be given to some other
function that can itself be specialised.
-fspec-constr-count=⟨n⟩
Default 3
Set the maximum number of specialisations that will be created for any one function by
the SpecConstr transformation.
-fspec-constr-threshold=⟨n⟩
Default 2000
Set the size threshold for the SpecConstr transformation.
-fspecialise
Default on
Specialise each type-class-overloaded function defined in this module for the types at
which it is called in this module. If -fcross-module-specialise (page 114) is set im-
ported functions that have an INLINABLE pragma (INLINABLE pragma (page 522)) will
be specialised as well.
-fspecialise-aggressively
Default off
By default only type class methods and methods marked INLINABLE or INLINE are spe-
cialised. This flag will specialise any overloaded function regardless of size if its un-
folding is available. This flag is not included in any optimisation level as it can mas-
sively increase code size. It can be used in conjunction with -fexpose-all-unfoldings
(page 108) if you want to ensure all calls are specialised.
-fcross-module-specialise
Default on
Specialise INLINABLE (INLINABLE pragma (page 522)) type-class-overloaded functions
imported from other modules for the types at which they are called in this module. Note
that specialisation must be enabled (by -fspecialise) for this to have any effect.
-flate-specialise
Default off
Runs another specialisation pass towards the end of the optimisation pipeline. This can
catch specialisation opportunities which arose from the previous specialisation pass or
other inlining.
You might want to use this if you are you have a type class method which returns a
constrained type. For example, a type class where one of the methods implements a
traversal.
-fsolve-constant-dicts
Default on
When solving constraints, try to eagerly solve super classes using available dictionaries.
For example:
type C a b = (Num a, M a b)
The body of f requires a Num Int instance. We could solve this constraint from the context
because we have C Int b and that provides us a solution for Num Int. However, we can
often produce much better code by directly solving for an available Num Int dictionary
we might have at hand. This removes potentially many layers of indirection and crucially
allows other optimisations to fire as the dictionary will be statically known and selector
functions can be inlined.
The optimisation also works for GADTs which bind dictionaries. If we statically know
which class dictionary we need then we will solve it directly rather than indirectly using
the one passed in at run time.
-fstatic-argument-transformation
Default off
Turn on the static argument transformation, which turns a recursive function into a non-
recursive one with a local recursive loop. See Chapter 7 of Andre Santos’s PhD thesis.
-fstg-lift-lams
Default on
Enables the late lambda lifting optimisation on the STG intermediate language. This
selectively lifts local functions to top-level by converting free variables into function pa-
rameters.
-fstg-lift-lams-known
Default off
Allow turning known into unknown calls while performing late lambda lifting. This is
deemed non-beneficial, so it’s off by default.
-fstg-lift-lams-non-rec-args
Default 5
Create top-level non-recursive functions with at most <n> parameters while performing
late lambda lifting. The default is 5, the number of available parameter registers on
x86_64.
-fstg-lift-lams-rec-args
Default 5
Create top-level recursive functions with at most <n> parameters while performing late
lambda lifting. The default is 5, the number of available parameter registers on x86_64.
-fstrictness
Default on
Switch on the strictness analyser. The implementation is described in the paper Theory
and Practice of Demand Analysis in Haskell.
The strictness analyser figures out when arguments and variables in a function can be
treated ‘strictly’ (that is they are always evaluated in the function at some point). This
allow GHC to apply certain optimisations such as unboxing that otherwise don’t apply
as they change the semantics of the program when applied to lazy arguments.
-fstrictness-before=⟨n⟩
Run an additional strictness analysis before simplifier phase ⟨n⟩.
-funbox-small-strict-fields
Default on
This option causes all constructor fields which are marked strict (i.e. “!”) and which
representation is smaller or equal to the size of a pointer to be unpacked, if possible. It
is equivalent to adding an UNPACK pragma (see UNPACK pragma (page 528)) to every
strict constructor field that fulfils the size restriction.
For example, the constructor fields in the following data types
data A = A !Int
data B = B !A
newtype C = C B
data D = D !C
would all be represented by a single Int# (see Unboxed types and primitive operations
(page 473)) value with -funbox-small-strict-fields enabled.
This option is less of a sledgehammer than -funbox-strict-fields: it should rarely
make things worse. If you use -funbox-small-strict-fields to turn on unboxing by
default you can disable it for certain constructor fields using the NOUNPACK pragma (see
NOUNPACK pragma (page 528)).
Note that for consistency Double, Word64, and Int64 constructor fields are unpacked
on 32-bit platforms, even though they are technically larger than a pointer on those
platforms.
-funbox-strict-fields
Default off
This option causes all constructor fields which are marked strict (i.e. !) to be unpacked
if possible. It is equivalent to adding an UNPACK pragma to every strict constructor field
(see UNPACK pragma (page 528)).
This option is a bit of a sledgehammer: it might sometimes make things worse. Selec-
tively unboxing fields by using UNPACK pragmas might be better. An alternative is to
use -funbox-strict-fields to turn on unboxing by default but disable it for certain
constructor fields using the NOUNPACK pragma (see NOUNPACK pragma (page 528)).
Alternatively you can use -funbox-small-strict-fields (page 115) to only unbox strict
fields which are “small”.
-funfolding-creation-threshold=⟨n⟩
Default 750
Governs the maximum size that GHC will allow a function unfolding to be. (An unfolding
has a “size” that reflects the cost in terms of “code bloat” of expanding (aka inlining)
that unfolding at a call site. A bigger function would be assigned a bigger cost.)
Consequences:
[Link] larger than this will be inlined (unless it has an INLINE pragma)
[Link] larger than this will be spewed into an interface file.
Increasing this figure is more likely to result in longer compile times than faster code.
The -funfolding-use-threshold=⟨n⟩ (page 116) is more useful.
-funfolding-dict-discount=⟨n⟩
Default 30
How eager should the compiler be to inline dictionaries?
-funfolding-fun-discount=⟨n⟩
Default 60
How eager should the compiler be to inline functions?
-funfolding-keeness-factor=⟨n⟩
This factor was deprecated in GHC 9.0.1. See #15304 for details. Users who need to
control inlining should rather consider -funfolding-use-threshold=⟨n⟩ (page 116).
-funfolding-use-threshold=⟨n⟩
Default 80
This is the magic cut-off figure for unfolding (aka inlining): below this size, a function
definition will be unfolded at the call-site, any bigger and it won’t. The size computed for
a function depends on two things: the actual size of the expression minus any discounts
that apply depending on the context into which the expression is to be inlined.
The difference between this and -funfolding-creation-threshold=⟨n⟩ (page 116) is
that this one determines if a function definition will be inlined at a call site. The other
option determines if a function definition will be kept around at all for potential inlining.
-fworker-wrapper
Enable the worker-wrapper transformation after a strictness analysis pass. Implied by -O
(page 105), and by -fstrictness (page 115). Disabled by -fno-strictness (page 115).
Enabling -fworker-wrapper (page 117) while strictness analysis is disabled (by -fno-
strictness (page 115)) has no effect.
-fbinary-blob-threshold=⟨n⟩
Default 500000
The native code-generator can either dump binary blobs (e.g. string literals) into the
assembly file (by using ”.asciz” or ”.string” assembler directives) or it can dump them
as binary data into a temporary file which is then included by the assembler (using the
”.incbin” assembler directive).
This flag sets the size (in bytes) threshold above which the second approach is used. You
can disable the second approach entirely by setting the threshold to 0.
GHC supports Concurrent Haskell by default, without requiring a special option or libraries
compiled in a certain way. To get access to the support libraries for Concurrent Haskell,
just import [Link]. More information on Concurrent Haskell is provided in the
documentation for that module.
Optionally, the program may be linked with the -threaded (page 220) option (see Options
affecting linking (page 217). This provides two benefits:
• It enables the -N ⟨x⟩ (page 118) to be used, which allows threads to run in parallel on
a multi-processor or multi-core machine. See Using SMP parallelism (page 118).
• If a thread makes a foreign call (and the call is not marked unsafe), then other Haskell
threads in the program will continue to run while the foreign call is in progress. Addi-
tionally, foreign exported Haskell functions may be called from multiple OS threads
simultaneously. See Multi-threading and the FFI (page 489).
The following RTS option(s) affect the behaviour of Concurrent Haskell programs:
-C ⟨s⟩
Default 20 milliseconds
Sets the context switch interval to ⟨s⟩ seconds. A context switch will occur at the next
heap block allocation after the timer expires (a heap block allocation occurs every 4k
of allocation). With -C0 or -C, context switches will occur as often as possible (at every
heap block allocation).
In order to make use of multiple CPUs, your program must be linked with the -threaded
(page 220) option (see Options affecting linking (page 217)). Additionally, the following com-
piler options affect parallelism:
-feager-blackholing
Blackholing is the act of marking a thunk (lazy computation) as being under evaluation.
It is useful for three reasons: firstly it lets us detect certain kinds of infinite loop (the
NonTermination exception), secondly it avoids certain kinds of space leak, and thirdly
it avoids repeating a computation in a parallel program, because we can tell when a
computation is already in progress.
The option -feager-blackholing (page 108) causes each thunk to be blackholed as soon
as evaluation begins. The default is “lazy blackholing”, whereby thunks are only marked
as being under evaluation when a thread is paused for some reason. Lazy blackholing is
typically more efficient (by 1-2% or so), because most thunks don’t need to be blackholed.
However, eager blackholing can avoid more repeated computation in a parallel program,
and this often turns out to be important for parallelism.
We recommend compiling any code that is intended to be run in parallel with the -feager-
blackholing (page 108) flag.
There are two ways to run a program on multiple processors: call Con-
[Link] from your program, or use the RTS -N ⟨x⟩ (page 118)
options.
-N ⟨x⟩
-N
-maxN ⟨x⟩
Use ⟨x⟩ simultaneous threads when running the program.
The runtime manages a set of virtual processors, which we call capabilities, the number
of which is determined by the -N option. Each capability can run one Haskell thread at a
time, so the number of capabilities is equal to the number of Haskell threads that can run
physically in parallel. A capability is animated by one or more OS threads; the runtime
manages a pool of OS threads for each capability, so that if a Haskell thread makes a
foreign call (see Multi-threading and the FFI (page 489)) another OS thread can take
over that capability.
Normally ⟨x⟩ should be chosen to match the number of CPU cores on the machine 1 . For
example, on a dual-core machine we would probably use +RTS -N2 -RTS.
Omitting ⟨x⟩, i.e. +RTS -N -RTS, lets the runtime choose the value of ⟨x⟩ itself based on
how many processors are in your machine.
Omitting -N⟨x⟩ entirely means -N1.
With -maxN⟨x⟩, i.e. +RTS -maxN3 -RTS, the runtime will choose at most (x), also limited
by the number of processors on the system. Omitting (x) is an error, if you need a default
use option -N.
Be careful when using all the processors in your machine: if some of your processors
are in use by other programs, this can actually harm performance rather than improve it.
Asking GHC to create more capabilities than you have physical threads is almost always
a bad idea.
Setting -N also has the effect of enabling the parallel garbage collector (see RTS options
to control the garbage collector (page 160)).
The current value of the -N option is available to the Haskell program via Con-
[Link], and it may be changed while the program is
running by calling [Link].
The following options affect the way the runtime schedules threads on CPUs:
-qa
Use the OS’s affinity facilities to try to pin OS threads to CPU cores.
When this option is enabled, the OS threads for a capability i are bound to the CPU core
i using the API provided by the OS for setting thread affinity. e.g. on Linux GHC uses
sched_setaffinity().
Depending on your workload and the other activity on the machine, this may or may not
result in a performance improvement. We recommend trying it out and measuring the
difference.
-qm
Disable automatic migration for load balancing. Normally the runtime will automatically
try to schedule threads across the available CPUs to make use of idle CPUs; this option
disables that behaviour. Note that migration only applies to threads; sparks created by
par are load-balanced separately by work-stealing.
This option is probably only of use for concurrent programs that explicitly schedule
threads onto CPUs with [Link].
Add the -s [⟨file⟩] (page 167) RTS option when running the program to see timing stats,
which will help to tell you whether your program got faster by using more CPUs or not. If the
user time is greater than the elapsed time, then the program used more than one CPU. You
should also run the program without -N ⟨x⟩ (page 118) for comparison.
1 Whether hyperthreading cores should be counted or not is an open question; please feel free to experiment and
let us know what results you find.
The output of +RTS -s tells you how many “sparks” were created and executed during the
run of the program (see RTS options to control the garbage collector (page 160)), which will
give you an idea how well your par annotations are working.
GHC’s parallelism support has improved in 6.12.1 as a result of much experimentation and
tuning in the runtime system. We’d still be interested to hear how well it works for you, and
we’re also interested in collecting parallel programs to add to our benchmarking suite.
This section is a quick-reference for GHC’s command-line flags. For each flag, we also list its
mode/dynamic status (see Dynamic and Mode options (page 75)), and the flag’s opposite (if
available).
5.6.11 Packages
Language options can be enabled either by a command-line option -Xblah, or by a {-# LAN-
GUAGE blah #-} pragma in the file itself. See Controlling extensions (page 237).
5.6.13 Warnings
-Wall (page 86) enable almost all warnings dynamic -w (page 87)
(details in Warnings and
sanity-checking (page 85))
-Wall-missed- warn when specialisation dynamic -Wno-all-missed-
specialisations of any overloaded function specialisations
(page 90) fails. (page 90)
-Werror (page 87) make warnings fatal dynamic -Wwarn (page 87)
-Wno-compat (page 87) Disables all warnings dynamic -Wcompat (page 87)
enabled by -Wcompat
(page 87).
-Wnoncanonical-monad- warn when Applicative dynamic -Wno-noncanonical-
instances (page 90) or Monad instances have monad-instances
noncanonical definitions (page 90)
of return, pure, (>>), or
(*>). See flag description
in Warnings and sanity-
checking (page 85) for
more details.
-Wnoncanonical- warn when Monad or Mon- dynamic -Wno-noncanonical-
monadfail-instances adFail instances have monadfail-instances
(page 90) noncanonical definitions (page 90)
of fail. See flag de-
scription in Warnings and
sanity-checking (page 85)
for more details.
-Wnoncanonical- warn when Semigroup or dynamic -Wno-noncanonical-
monoid-instances Monoid instances have monoid-instances
(page 91) noncanonical definitions (page 91)
of (<>) or mappend. See
flag description in Warn-
ings and sanity-checking
(page 85) for more details.
-Worphans (page 97) warn when the module dynamic -Wno-orphans (page 97)
contains orphan instance
declarations or rewrite
rules (page 191)
-Woverflowed-literals warn about literals that dynamic -Wno-overflowed-
(page 92) will overflow their type literals (page 92)
-Wtabs (page 99) warn if there are tabs in dynamic -Wno-tabs (page 99)
the source file
-Wtrustworthy-safe warn if the module being dynamic -Wno-safe (page 503)
(page 503) compiled is marked as
Trustworthy (page 502)
but it could instead
be marked as Safe
(page 502), a more in-
formative bound.
-Wtype-defaults warn when defaulting hap- dynamic -Wno-type-defaults
(page 99) pens (page 99)
These options are described in more detail in Optimisation (code improvement) (page 104).
See Individual optimisations (page 138) for a list of optimisations enabled on level 1 and level
2.
These options are described in more detail in -f*: platform-independent flags (page 105). If
a flag is implied by -O then it is also implied by -O2 (unless flag description explicitly says
otherwise). If a flag is implied by -O0 only then the flag is not implied by -O and -O2.
-main-is ⟨thing⟩ (page 219) Set main module and function dynamic
More details in Replacing the program for one or more phases (page 211)
-ddump-cmm-sink (page 231) Dump the results of the C-\- sinking dynamic
pass.
-ddump-cmm-sp (page 231) Dump the results of the C-\- stack lay- dynamic
out pass.
-ddump-cmm-split (page 231) Dump the results of the C-\- proc-point dynamic
splitting pass.
-ddump-cmm-switch Dump the results of switch lowering dynamic
(page 231) passes
-ddump-cmm-verbose Write output from main C-\- pipeline dynamic
(page 231) passes to files
-ddump-cmm-verbose-by- Show output from main C-\- pipeline dynamic
proc (page 230) passes (grouped by proc)
-ddump-core-stats Print a one-line summary of the size of dynamic
(page 229) the Core program at the end of the op-
timisation pipeline
-ddump-cpr-signatures Dump CPR signatures dynamic
(page 230)
-ddump-cpranal (page 230) Dump CPR analysis output dynamic
-ddump-hie (page 228) Dump the hie file syntax tree dynamic
-ddump-mod-map (page 232) Dump the state of the module mapping dynamic
database.
-ddump-occur-anal Dump occurrence analysis output dynamic
(page 230)
-ddump-opt-cmm (page 232) Dump the results of C-\- to C-\- optimis- dynamic
ing passes
-ddump-parsed (page 227) Dump parse tree dynamic
To make an executable program, the GHC system compiles your code and then links it with
a non-trivial runtime system (RTS), which handles storage management, thread scheduling,
profiling, and so on.
The RTS has a lot of options to control its behaviour. For example, you can change the context-
switch interval, the default size of the heap, and enable heap profiling. These options can be
passed to the runtime system in a variety of different ways; the next section (Setting RTS
options (page 155)) describes the various methods, and the following sections describe the
RTS options themselves.
The RTS will snaffle -H32m -S for itself, and the remaining arguments -f -h foo bar will be
available to your program if/when it calls [Link].
No -RTS option is required if the runtime-system options extend to the end of the command
line, as in this example:
If you absolutely positively want all the rest of the options in a command line to go to the
program (and not the RTS), use a --RTS or --. The difference is that --RTS will not be passed
to the program, while -- will.
As always, for RTS options that take ⟨size⟩s: If the last character of ⟨size⟩ is a K or k, multiply
by 1000; if an M or m, by 1,000,000; if a G or G, by 1,000,000,000. (And any wraparound in
the counters is your fault!)
Giving a +RTS -? RTS option will print out the RTS options actually available in your program
(which vary, depending on how you compiled).
Note: Since GHC is itself compiled by GHC, you can change RTS options in the compiler
using the normal +RTS ... -RTS combination. For instance, to set the maximum heap size
for a compilation to 128M, you would add +RTS -M128m -RTS to the command line.
GHC lets you change the default RTS options for a program at compile time, using the -with-
rtsopts flag (Options affecting linking (page 217)). A common use for this is to give your
program a default heap and/or stack size that is greater than the default. For example, to set
-H128m -K64m, link with -with-rtsopts="-H128m -K64m".
GHCRTS
If the -rtsopts flag is set to something other than none or ignoreAll when linking, RTS
options are also taken from the environment variable GHCRTS (page 157). For example,
to set the maximum heap size to 2G for all GHC-compiled programs (using an sh-like
shell):
GHCRTS='-M2G'
export GHCRTS
RTS options taken from the GHCRTS (page 157) environment variable can be overridden
by options given on the command line.
Tip: Setting something like GHCRTS=-M2G in your environment is a handy way to avoid Haskell
programs growing beyond the real memory in your machine, which is easy to do by accident
and can cause the machine to slow to a crawl until the OS decides to kill the process (and you
hope it kills the right one).
GHC lets you exercise rudimentary control over certain RTS settings for any given program,
by compiling in a “hook” that is called by the run-time system. The RTS contains stub defini-
tions for these hooks, but by writing your own version and linking it on the GHC command
line, you can override the defaults.
Owing to the vagaries of DLL linking, these hooks don’t work under Windows when the pro-
gram is built dynamically.
Runtime events
You can change the messages printed when the runtime system “blows up,” e.g., on stack
overflow. The hooks for these are as follows:
void OutOfHeapHook(unsigned long, unsigned long)
The heap-overflow message.
void StackOverflowHook(long int)
The stack-overflow message.
void MallocFailHook(long int)
The message printed if malloc fails.
Furthermore GHC lets you specify the way event log data (see -l ⟨flags⟩ (page 170)) is
written through a custom EventLogWriter (page 157):
size_t
Hidden
EventLogWriter
A sink of event-log data.
void initEventLogWriter(void)
Initializes your EventLogWriter (page 157). This is optional.
bool writeEventLog(void *eventlog, size_t eventlog_size)
Hands buffered event log data to your event log writer. Return true on success.
Required for a custom EventLogWriter (page 157).
Note that this function may be called by multiple threads simultaneously.
void flushEventLog(void)
Flush buffers (if any) of your custom EventLogWriter (page 157). This can be NULL.
Note that this function may be called by multiple threads simultaneously.
void stopEventLogWriter(void)
Called when event logging is about to stop. This can be NULL.
To use an EventLogWriter (page 157) the RTS API provides the following functions:
EventLogStatus (page 158) eventLogStatus(void)
Query whether the current runtime system supports the eventlog (e.g. whether the
current executable was linked with -eventlog (page 220)) and, if it is supported, whether
it is currently logging.
bool startEventLogging(const EventLogWriter (page 157) *writer)
Start logging events to the given EventLogWriter (page 157). Returns true on success
or false is another writer has already been configured.
void endEventLogging()
Tear down the active EventLogWriter (page 157).
where the enum EventLogStatus (page 158) is:
EventLogStatus
•EVENTLOG_NOT_SUPPORTED: The runtime system wasn’t compiled with eventlog sup-
port.
•EVENTLOG_NOT_CONFIGURED: An EventLogWriter (page 157) has not yet been config-
ured.
•EVENTLOG_RUNNING: An EventLogWriter (page 157) has been configured and is run-
ning.
--install-signal-handlers=⟨yes|no⟩
If yes (the default), the RTS installs signal handlers to catch things like Ctrl-C. This
option is primarily useful for when you are using the Haskell code as a DLL, and want to
set your own signal handlers.
Note that even with --install-signal-handlers=no, the RTS interval timer signal is
still enabled. The timer signal is either SIGVTALRM or SIGALRM, depending on the RTS
configuration and OS capabilities. To disable the timer signal, use the -V0 RTS option
(see -V ⟨secs⟩ (page 559)).
--install-seh-handlers=⟨yes|no⟩
If yes (the default), the RTS on Windows installs exception handlers to catch unhandled
exceptions using the Windows exception handling mechanism. This option is primarily
useful for when you are using the Haskell code as a DLL, and don’t want the RTS to
ungracefully terminate your application on errors such as segfaults.
--generate-crash-dumps
If yes (the default), the RTS on Windows will generate a core dump on any crash. These
dumps can be inspected using debuggers such as WinDBG. The dumps record all code,
registers and threading information at the time of the crash. Note that this implies --
install-seh-handlers=yes.
--generate-stack-traces=<yes|no>
If yes (the default), the RTS on Windows will generate a stack trace on crashes if excep-
tion handling are enabled. In order to get more information in compiled executables, C
code or DLLs symbols need to be available.
--disable-delayed-os-memory-return
If given, uses MADV_DONTNEED instead of MADV_FREE on platforms where this results in
more accurate resident memory usage of the program as shown in memory usage re-
porting tools (e.g. the RSS column in top and htop).
Using this is expected to make the program slightly slower.
On Linux, MADV_FREE is newer and faster because it can avoid zeroing pages if they
are re-used by the process later (see man 2 madvise), but for the trade-off that memory
inspection tools like top will not immediately reflect the freeing in their display of res-
ident memory (RSS column): Only under memory pressure will Linux actually remove
the freed pages from the process and update its RSS statistics. Until then, the pages
show up as LazyFree in /proc/PID/smaps (see man 5 proc).
The delayed RSS update can confuse programmers debugging memory issues, produc-
tion memory monitoring tools, and end users who may complain about undue memory
usage shown in reporting tools, so with this flag it can be turned off.
-xp
On 64-bit machines, the runtime linker usually needs to map object code into the low 2Gb
of the address space, due to the x86_64 small memory model where most symbol refer-
ences are 32 bits. The problem is that this 2Gb of address space can fill up, especially if
you’re loading a very large number of object files into GHCi.
This flag offers a workaround, albeit a slightly convoluted one. To be able to load an
object file outside of the low 2Gb, the object code needs to be compiled with -fPIC -
fexternal-dynamic-refs. When the +RTS -xp flag is passed, the linker will assume
that all object files were compiled with -fPIC -fexternal-dynamic-refs and load them
anywhere in the address space. It’s up to you to arrange that the object files you load
(including all packages) were compiled in the right way. If this is not the case for an
object, the linker will probably fail with an error message when the problem is detected.
On some platforms where PIC is always the case, e.g. macOS and OpenBSD on x86_64,
and macOS and Linux on aarch64 this flag is enabled by default. One repercussion of
this is that referenced system libraries also need to be compiled with -fPIC if we need
to load them in the runtime linker.
-xm ⟨address⟩
Warning: This option is for working around memory allocation problems only. Do not
use unless GHCi fails with a message like “failed to mmap() memory below 2Gb”.
Consider recompiling the objects with -fPIC -fexternal-dynamic-refs and using
the -xp flag instead. If you need to use this option to get GHCi working on your
machine, please file a bug.
On 64-bit machines, the RTS needs to allocate memory in the low 2Gb of the address
space. Support for this across different operating systems is patchy, and sometimes
fails. This option is there to give the RTS a hint about where it should be able to allocate
memory in the low 2Gb of the address space. For example, +RTS -xm20000000 -RTS
would hint that the RTS should allocate starting at the 0.5Gb mark. The default is to use
the OS’s built-in support for allocating memory in the low 2Gb if available (e.g. mmap
with MAP_32BIT on Linux), or otherwise -xm40000000.
-xq ⟨size⟩
Default 100k
This option relates to allocation limits; for more about this see
[Link]. When a thread hits its allocation limit, the RTS
throws an exception to the thread, and the thread gets an additional quota of allocation
before the exception is raised again, the idea being so that the thread can execute its
exception handlers. The -xq controls the size of this additional quota.
There are several options to give you precise control over garbage collection. Hopefully, you
won’t need any of these in normal operation, but there are several things that can be tweaked
for maximum performance.
--copying-gc
Default on
Since 8.10.2
Reverse –nonmoving-gc
Uses the generational copying garbage collector for all generations. This is the default.
--nonmoving-gc
Default off
Since 8.10.1
Reverse –copying-gc
Enable the concurrent mark-and-sweep garbage collector for old generation collectors.
Typically GHC uses a stop-the-world copying garbage collector for all generations. This
can cause long pauses in execution during major garbage collections. --nonmoving-
gc (page 160) enables the use of a concurrent mark-and-sweep garbage collector for
oldest generation collections. Under this collection strategy oldest-generation garbage
collection can proceed concurrently with mutation.
Note that --nonmoving-gc (page 160) cannot be used with -G1, profiling (page 563)
nor -c (page 162).
-xn
Default off
Since 8.10.1
An alias for --nonmoving-gc (page 160)
-A ⟨size⟩
Default 1MB
Set the allocation area size used by the garbage collector. The allocation area (actually
generation 0 step 0) is fixed and is never resized (unless you use -H [⟨size⟩] (page 163),
below).
Increasing the allocation area size may or may not give better performance (a bigger
allocation area means worse cache behaviour but fewer garbage collections and less
promotion).
With only 1 generation (e.g. -G1, see -G ⟨generations⟩ (page 162)) the -A option spec-
ifies the minimum allocation area, since the actual size of the allocation area will be
resized according to the amount of data in the heap (see -F ⟨factor⟩ (page 162), be-
low).
-AL ⟨size⟩
Default -A (page 160) value
Since 8.2.1
Sets the limit on the total size of “large objects” (objects larger than about 3KB) that
can be allocated before a GC is triggered. By default this limit is the same as the -A
(page 160) value.
Large objects are not allocated from the normal allocation area set by the -A flag, which
is why there is a separate limit for these. Large objects tend to be much rarer than small
objects, so most programs hit the -A limit before the -AL limit. However, the -A limit
is per-capability, whereas the -AL limit is global, so as -N gets larger it becomes more
likely that we hit the -AL limit first. To counteract this, it might be necessary to use a
larger -AL limit when using a large -N.
To see whether you’re making good use of all the memory reseverd for the allocation area
(-A times -N), look at the output of +RTS -S and check whether the amount of memory
allocated between GCs is equal to -A times -N. If not, there are two possible remedies:
use -n to set a nursery chunk size, or use -AL to increase the limit for large objects.
-O ⟨size⟩
Default 1m
Set the minimum size of the old generation. The old generation is collected whenever it
grows to this size or the value of the -F ⟨factor⟩ (page 162) option multiplied by the
size of the live data at the previous major collection, whichever is larger.
-n ⟨size⟩
Default 4m with -A16m (page 160) or larger, otherwise 0.
[Example: -n4m ] When set to a non-zero value, this option divides the allocation area (-A
value) into chunks of the specified size. During execution, when a processor exhausts
its current chunk, it is given another chunk from the pool until the pool is exhausted, at
which point a collection is triggered.
This option is only useful when running in parallel (-N2 or greater). It allows the pro-
cessor cores to make better use of the available allocation area, even when cores are
allocating at different rates. Without -n, each core gets a fixed-size allocation area spec-
ified by the -A, and the first core to exhaust its allocation area triggers a GC across all
the cores. This can result in a collection happening when the allocation areas of some
cores are only partially full, so the purpose of the -n is to allow cores that are allocating
faster to get more of the allocation area. This means less frequent GC, leading a lower
GC overhead for the same heap size.
This is particularly useful in conjunction with larger -A values, for example -A64m -n4m
is a useful combination on larger core counts (8+).
-c
Use a compacting algorithm for collecting the oldest generation. By default, the oldest
generation is collected using a copying algorithm; this option causes it to be compacted
in-place instead. The compaction algorithm is slower than the copying algorithm, but
the savings in memory use can be considerable.
For a given heap size (using the -H [⟨size⟩] (page 163) option), compaction can in fact
reduce the GC cost by allowing fewer GCs to be performed. This is more likely when the
ratio of live data to heap size is high, say greater than 30%.
Note: Compaction doesn’t currently work when a single generation is requested using
the -G1 option.
-c ⟨n⟩
Default 30
Automatically enable compacting collection when the live data exceeds ⟨n⟩% of the max-
imum heap size (see the -M ⟨size⟩ (page 165) option). Note that the maximum heap
size is unlimited by default, so this option has no effect unless the maximum heap size is
set with -M ⟨size⟩ (page 165).
-F ⟨factor⟩
Default 2
This option controls the amount of memory reserved for the older generations (and in
the case of a two space collector the size of the allocation area) as a factor of the amount
of live data. For example, if there was 2M of live data in the oldest generation when we
last collected it, then by default we’ll wait until it grows to 4M before collecting it again.
The default seems to work well here. If you have plenty of memory, it is usually better to
use -H ⟨size⟩ (see -H [⟨size⟩] (page 163)) than to increase -F ⟨factor⟩ (page 162).
The -F ⟨factor⟩ (page 162) setting will be automatically reduced by the garbage col-
lector when the maximum heap size (the -M ⟨size⟩ (page 165) setting) is approaching.
-G ⟨generations⟩
Default 2
Set the number of generations used by the garbage collector. The default of 2 seems to
be good, but the garbage collector can support any number of generations. Anything
larger than about 4 is probably not a good idea unless your program runs for a long time,
because the oldest generation will hardly ever get collected.
Specifying 1 generation with +RTS -G1 gives you a simple 2-space collector, as you would
expect. In a 2-space collector, the -A ⟨size⟩ (page 160) option specifies the minimum
allocation area size, since the allocation area will grow with the amount of live data in
the heap. In a multi-generational collector the allocation area is a fixed size (unless you
use the -H [⟨size⟩] (page 163) option).
-qg ⟨gen⟩
Default 0
Since 6.12.1
Use parallel GC in generation ⟨gen⟩ and higher. Omitting ⟨gen⟩ turns off the parallel GC
completely, reverting to sequential GC.
The default parallel GC settings are usually suitable for parallel programs (i.e. those
using [Link], Strategies, or with multiple threads). However, it is sometimes
beneficial to enable the parallel GC for a single-threaded sequential program too, espe-
cially if the program has a large amount of heap data and GC is a significant fraction of
runtime. To use the parallel GC in a sequential program, enable the parallel runtime with
a suitable -N ⟨x⟩ (page 118) option, and additionally it might be beneficial to restrict
parallel GC to the old generation with -qg1.
-qb ⟨gen⟩
Default 1 for -A (page 160) < 32M, 0 otherwise
Since 6.12.1
Use load-balancing in the parallel GC in generation ⟨gen⟩ and higher. Omitting ⟨gen⟩
disables load-balancing entirely.
Load-balancing shares out the work of GC between the available cores. This is a good
idea when the heap is large and we need to parallelise the GC work, however it is also
pessimal for the short young-generation collections in a parallel program, because it
can harm locality by moving data from the cache of the CPU where is it being used
to the cache of another CPU. Hence the default is to do load-balancing only in the old-
generation. In fact, for a parallel program it is sometimes beneficial to disable load-
balancing entirely with -qb.
-qn ⟨x⟩
Default the value of -N (page 118) or the number of CPU cores, whichever is
smaller.
Since 8.2.1
By default, all of the capabilities participate in parallel garbage collection. If we want to
use a very large -N value, however, this can reduce the performance of the GC. For this
reason, the -qn flag can be used to specify a lower number for the threads that should
participate in GC. During GC, if there are more than this number of workers active, some
of them will sleep for the duration of the GC.
The -qn flag may be useful when running with a large -A value (so that GC is infrequent),
and a large -N value (so as to make use of hyperthreaded cores, for example). For ex-
ample, on a 24-core machine with 2 hyperthreads per core, we might use -N48 -qn24
-A128m to specify that the mutator should use hyperthreads but the GC should only use
real cores. Note that this configuration would use 6GB for the allocation area.
-H [⟨size⟩]
Default 0
This option provides a “suggested heap size” for the garbage collector. Think of -Hsize
as a variable -A ⟨size⟩ (page 160) option. It says: I want to use at least ⟨size⟩ bytes, so
use whatever is left over to increase the -A value.
This option does not put a limit on the heap size: the heap may grow beyond the given
size as usual.
If ⟨size⟩ is omitted, then the garbage collector will take the size of the heap at the pre-
vious GC as the ⟨size⟩. This has the effect of allowing for a larger -A value but without
increasing the overall memory requirements of the program. It can be useful when the
default small -A value is suboptimal, as it can be in programs that create large amounts
of long-lived data.
-I ⟨seconds⟩
Default 0.3 seconds in the threaded runtime, 0 in the non-threaded runtime
In the threaded and SMP versions of the RTS (see -threaded (page 220), Options af-
fecting linking (page 217)), a major GC is automatically performed if the runtime has
been idle (no Haskell computation has been running) for a period of time. The amount of
idle time which must pass before a GC is performed is set by the -I ⟨seconds⟩ option.
Specifying -I0 disables the idle GC.
For an interactive application, it is probably a good idea to use the idle GC, because this
will allow finalizers to run and deadlocked threads to be detected in the idle time when
no Haskell computation is happening. Also, it will mean that a GC is less likely to happen
when the application is busy, and so responsiveness may be improved. However, if the
amount of live data in the heap is particularly large, then the idle GC can cause a signif-
icant delay, and too small an interval could adversely affect interactive responsiveness.
This is an experimental feature, please let us know if it causes problems and/or could
benefit from further tuning.
-Iw ⟨seconds⟩
Default 0 seconds
By default, if idle GC is enabled in the threaded runtime, a major GC will be performed
every time the process goes idle for a sufficiently long duration (see -I ⟨seconds⟩
(page 164)). For large server processes accepting regular but infrequent requests (e.g.,
once per second), an expensive, major GC may run after every request. As an alternative
to shutting off idle GC entirely (with -I0), a minimum wait time between idle GCs can
be specified with this flag. For example, -Iw60 will ensure that an idle GC runs at most
once per minute.
This is an experimental feature, please let us know if it causes problems and/or could
benefit from further tuning.
-ki ⟨size⟩
Default 1k
Set the initial stack size for new threads.
Thread stacks (including the main thread’s stack) live on the heap. As the stack grows,
new stack chunks are added as required; if the stack shrinks again, these extra stack
chunks are reclaimed by the garbage collector. The default initial stack size is delib-
erately small, in order to keep the time and space overhead for thread creation to a
minimum, and to make it practical to spawn threads for even tiny pieces of work.
Note: This flag used to be simply -k, but was renamed to -ki in GHC 7.2.1. The old
name is still accepted for backwards compatibility, but that may be removed in a future
version.
-kc ⟨size⟩
Default 32k
Set the size of “stack chunks”. When a thread’s current stack overflows, a new stack
chunk is created and added to the thread’s stack, until the limit set by -K ⟨size⟩
(page 165) is reached.
The advantage of smaller stack chunks is that the garbage collector can avoid traversing
stack chunks if they are known to be unmodified since the last collection, so reducing
the chunk size means that the garbage collector can identify more stack as unmodified,
and the GC overhead might be reduced. On the other hand, making stack chunks too
small adds some overhead as there will be more overflow/underflow between chunks.
The default setting of 32k appears to be a reasonable compromise in most cases.
-kb ⟨size⟩
Default 1k
Sets the stack chunk buffer size. When a stack chunk overflows and a new stack chunk
is created, some of the data from the previous stack chunk is moved into the new chunk,
to avoid an immediate underflow and repeated overflow/underflow at the boundary. The
amount of stack moved is set by the -kb option.
Note that to avoid wasting space, this value should typically be less than 10% of the
size of a stack chunk (-kc ⟨size⟩ (page 164)), because in a chain of stack chunks, each
chunk will have a gap of unused space of this size.
-K ⟨size⟩
Default 80% of physical memory
Set the maximum stack size for an individual thread to ⟨size⟩ bytes. If the thread at-
tempts to exceed this limit, it will be sent the StackOverflow exception. The limit can
be disabled entirely by specifying a size of zero.
This option is there mainly to stop the program eating up all the available memory in the
machine if it gets into an infinite loop.
-m ⟨n⟩
Default 3%
Minimum % ⟨n⟩ of heap which must be available for allocation.
-M ⟨size⟩
Default unlimited
Set the maximum heap size to ⟨size⟩ bytes. The heap normally grows and shrinks accord-
ing to the memory requirements of the program. The only reason for having this option
is to stop the heap growing without bound and filling up all the available swap space,
which at the least will result in the program being summarily killed by the operating
system.
The maximum heap size also affects other garbage collection parameters: when the
amount of live data in the heap exceeds a certain fraction of the maximum heap size,
compacting collection will be automatically enabled for the oldest generation, and the
-F parameter will be reduced in order to avoid exceeding the maximum heap size.
-Mgrace=⟨size⟩
Default 1M
If the program’s heap exceeds the value set by -M ⟨size⟩ (page 165), the RTS throws
an exception to the program, and the program gets an additional quota of allocation
before the exception is raised again, the idea being so that the program can execute its
exception handlers. -Mgrace= controls the size of this additional quota.
--numa
--numa=<mask>
Enable NUMA-aware memory allocation in the runtime (only available with -threaded,
and only on Linux and Windows currently).
Background: some systems have a Non-Uniform Memory Architecture, whereby main
memory is split into banks which are “local” to specific CPU cores. Accessing local
memory is faster than accessing remote memory. The OS provides APIs for allocating
local memory and binding threads to particular CPU cores, so that we can ensure certain
memory accesses are using local memory.
The --numa option tells the RTS to tune its memory usage to maximize local memory
accesses. In particular, the RTS will:
•Determine the number of NUMA nodes (N) by querying the OS.
•Manage separate memory pools for each node.
•Map capabilities to NUMA nodes. Capability C is mapped to NUMA node C mod N.
•Bind worker threads on a capability to the appropriate node.
•Allocate the nursery from node-local memory.
•Perform other memory allocation, including in the GC, from node-local memory.
•When load-balancing, we prefer to migrate threads to another Capability on the
same node.
The --numa flag is typically beneficial when a program is using all cores of a large multi-
core NUMA system, with a large allocation area (-A). All memory accesses to the alloca-
tion area will go to local memory, which can save a significant amount of remote memory
access. A runtime speedup on the order of 10% is typical, but can vary a lot depending
on the hardware and the memory behaviour of the program.
Note that the RTS will not set CPU affinity for bound threads and threads entering
Haskell from C/C++, so if your program uses bound threads you should ensure that each
bound thread calls the RTS API rts_setInCallCapability(c,1) from C/C++ before calling
into Haskell. Otherwise there could be a mismatch between the CPU that the thread is
running on and the memory it is using while running Haskell code, which will negate
any benefits of --numa.
If given an explicit <mask>, the <mask> is interpreted as a bitmap that indicates the
NUMA nodes on which to run the program. For example, --numa=3 would run the pro-
gram on NUMA nodes 0 and 1.
--long-gc-sync
--long-gc-sync=<seconds>
When a GC starts, all the running mutator threads have to stop and synchronise. The
period between when the GC is initiated and all the mutator threads are stopped is called
the GC synchronisation phase. If this phase is taking a long time (longer than 1ms is
considered long), then it can have a severe impact on overall throughput.
A long GC sync can be caused by a mutator thread that is inside an unsafe FFI call, or
running in a loop that doesn’t allocate memory and so doesn’t yield. To fix the former,
make the call safe, and to fix the latter, either avoid calling the code in question or
compile it with -fomit-yields (page 111).
By default, the flag will cause a warning to be emitted to stderr when the sync time ex-
ceeds the specified time. This behaviour can be overridden, however: the longGCSync()
hook is called when the sync time is exceeded during the sync period, and the longGC-
SyncEnd() hook at the end. Both of these hooks can be overridden in the RtsConfig
when the runtime is started with hs_init_ghc(). The default implementations of these
hooks (LongGcSync() and LongGCSyncEnd() respectively) print warnings to stderr.
One way to use this flag is to set a breakpoint on LongGCSync() in the debugger, and find
the thread that is delaying the sync. You probably want to use -g (page 577) to provide
more info to the debugger.
The GC sync time, along with other GC stats, are available by calling the getRTSStats()
function from C, or [Link] from Haskell.
-T
-t [⟨file⟩]
-s [⟨file⟩]
-S [⟨file⟩]
--machine-readable
--internal-counters
These options produce runtime-system statistics, such as the amount of time spent exe-
cuting the program and in the garbage collector, the amount of memory allocated, the
maximum size of the heap, and so on. The three variants give different levels of detail:
-T collects the data but produces no output -t produces a single line of output in the
same format as GHC’s -Rghc-timing option, -s produces a more detailed summary at
the end of the program, and -S additionally produces information about each and every
garbage collection. Passing --internal-counters to a threaded runtime will cause a
detailed summary to include various internal counts accumulated during the run; note
that these are unspecified and may change between releases.
The output is placed in ⟨file⟩. If ⟨file⟩ is omitted, then the output is sent to stderr.
If you use the -T flag then, you should access the statistics using [Link].
If you use the -t flag then, when your program finishes, you will see something like this:
<<ghc: 36169392 bytes, 69 GCs, 603392/1065272 avg/max bytes residency (2 samples),
,→ 3M in use, 0.00 INIT (0.00 elapsed), 0.02 MUT (0.02 elapsed), 0.07 GC (0.07␣
,→elapsed) :ghc>>
You can also get this in a more future-proof, machine readable format, with -t --
machine-readable:
If you use the -s flag then, when your program finishes, you will see something like this
(the exact details will vary depending on what sort of RTS you have, e.g. you will only
see profiling data if your RTS is compiled for profiling):
•The “bytes allocated in the heap” is the total bytes allocated by the program over
the whole run.
•GHC uses a copying garbage collector by default. “bytes copied during GC” tells
you how many bytes it had to copy during garbage collection.
•The maximum space actually used by your program is the “bytes maximum resi-
dency” figure. This is only checked during major garbage collections, so it is only
an approximation; the number of samples tells you how many times it is checked.
•The “bytes maximum slop” tells you the most space that is ever wasted due to the
way GHC allocates memory in blocks. Slop is memory at the end of a block that
was wasted. There’s no way to control this; we just like to see how much memory is
being lost this way.
•The “total memory in use” tells you the peak memory the RTS has allocated from
the OS.
•Next there is information about the garbage collections done. For each generation it
says how many garbage collections were done, how many of those collections were
done in parallel, the total CPU time used for garbage collecting that generation, and
the total wall clock time elapsed while garbage collecting that generation.
•The SPARKS statistic refers to the use of [Link] and related func-
tionality in the program. Each spark represents a call to par; a spark is “converted”
when it is executed in parallel; and a spark is “pruned” when it is found to be already
evaluated and is discarded from the pool by the garbage collector. Any remaining
sparks are discarded at the end of execution, so “converted” plus “pruned” does not
necessarily add up to the total.
•Next there is the CPU time and wall clock time elapsed broken down by what the
runtime system was doing at the time. INIT is the runtime system initialisation.
MUT is the mutator time, i.e. the time spent actually running your code. GC is the
time spent doing garbage collection. RP is the time spent doing retainer profiling.
PROF is the time spent doing other profiling. EXIT is the runtime system shutdown
time. And finally, Total is, of course, the total.
%GC time tells you what percentage GC is of Total. “Alloc rate” tells you the “bytes
allocated in the heap” divided by the MUT CPU time. “Productivity” tells you what
percentage of the Total CPU and wall clock elapsed times are spent in the mutator
(MUT).
The -S flag, as well as giving the same output as the -s flag, prints information about
each GC as it happens:
The RTS options related to concurrency are described in Using Concurrent Haskell (page 117),
and those for parallelism in RTS options for SMP parallelism (page 118).
Most profiling runtime options are only available when you compile your program for profiling
(see Compiler options for profiling (page 557), and RTS options for heap profiling (page 562)
for the runtime options). However, there is one profiling option that is available for ordinary
non-profiled executables:
-hT
-h
Generates a basic heap profile, in the file [Link]. To produce the heap profile graph,
use hp2ps (see hp2ps – Rendering heap profiles to PostScript (page 566)). The basic
heap profile is broken down by data constructor, with other types of closures (functions,
thunks, etc.) grouped into broad categories (e.g. FUN, THUNK). To get a more detailed
profile, use the full profiling support (Profiling (page 553)). Can be shortened to -h
(page 170).
Note: The meaning of the shortened -h (page 170) is dependent on whether your
program was compiled for profiling. (See RTS options for heap profiling (page 562) for
details.)
-L ⟨n⟩
Default 25 characters
Sets the maximum length of the cost-centre names listed in the heap profile.
5.7.7 Tracing
When the program is linked with the -eventlog (page 220) option (Options affecting linking
(page 217)), runtime events can be logged in several ways:
• In binary format to a file for later analysis by a variety of tools. One such tool is Thread-
Scope, which interprets the event log to produce a visual parallel execution profile of
the program.
• In binary format to customized event log writer. This enables live analysis of the events
while the program is running.
• As text to standard output, for debugging purposes.
-l ⟨flags⟩
Log events in binary format. Without any ⟨flags⟩ specified, this logs a default set of
events, suitable for use with tools like ThreadScope.
Per default the events are written to [Link] though the mechanism for writ-
ing event log data can be overridden with a custom EventLogWriter.
For some special use cases you may want more control over which events are included.
The ⟨flags⟩ is a sequence of zero or more characters indicating which classes of events
to log. Currently these the classes of events that can be enabled/disabled:
•s — scheduler events, including Haskell thread creation and start/stop events. En-
abled by default.
•g — GC events, including GC start/stop. Enabled by default.
These RTS options might be used (a) to avoid a GHC bug, (b) to see “what’s really happening”,
or (c) because you feel like it. Not recommended for everyday use!
-B
Sound the bell at the start of each (major) garbage collection.
Oddly enough, people really do use this option! Our pal in Durham (England), Paul
Callaghan, writes: “Some people here use it for a variety of purposes—honestly!—e.g.,
confirmation that the code/machine is doing something, infinite loop detection, gauging
cost of recently added code. Certain people can even tell what stage [the program] is in
by the beep pattern. But the major use is for annoying others in the same office…”
-D ⟨x⟩
An RTS debugging flag; only available if the program was linked with the -debug
(page 220) option. Various values of ⟨x⟩ are provided to enable debug messages and
additional runtime sanity checks in different subsystems in the RTS, for example +RTS
-Ds -RTS enables debug messages from the scheduler. Use +RTS -? to find out which
debug flags are supported.
Full list of currently supported flags:
-Ds DEBUG: scheduler
-Di DEBUG: interpreter
-Dw DEBUG: weak
-DG DEBUG: gccafs
-Dg DEBUG: gc
-Db DEBUG: block
-DS DEBUG: sanity
-DZ DEBUG: zero freed memory on GC
-Dt DEBUG: stable
-Dp DEBUG: prof
-Da DEBUG: apply
-Dl DEBUG: linker
-Dm DEBUG: stm
-Dz DEBUG: stack squeezing
-Dc DEBUG: program coverage
-Dr DEBUG: sparks
-DC DEBUG: compact
Debug messages will be sent to the binary event log file instead of stdout if the -l
⟨flags⟩ (page 170) option is added. This might be useful for reducing the overhead
of debug tracing.
To figure out what exactly they do, the least bad way is to grep the rts/ directory in the
ghc code for macros like DEBUG(scheduler or DEBUG_scheduler.
-r ⟨file⟩
Produce “ticky-ticky” statistics at the end of the program run (only available if the pro-
gram was linked with -debug (page 220)). The ⟨file⟩ business works just like on the -S
[⟨file⟩] (page 167) RTS option, above.
For more information on ticky-ticky profiling, see Using “ticky-ticky” profiling (for imple-
mentors) (page 575).
-xc
(Only available when the program is compiled for profiling.) When an exception is raised
in the program, this option causes a stack trace to be dumped to stderr.
This can be particularly useful for debugging: if your program is complaining about a
head [] error and you haven’t got a clue which bit of code is causing it, compiling with
-prof -fprof-auto (see -prof (page 557)) and running with +RTS -xc -RTS will tell you
exactly the call stack at the point the error was raised.
The output contains one report for each exception raised in the program (the program
might raise and catch several exceptions during its execution), where each report looks
something like this:
The stack trace may often begin with something uninformative like [Link]; this
is an artifact of GHC’s optimiser, which lifts out exceptions to the top-level where the
profiling system assigns them to the cost centre “CAF”. However, +RTS -xc doesn’t just
print the current stack, it looks deeper and reports the stack at the time the CAF was
evaluated, and it may report further stacks until a non-CAF stack is found. In the example
above, the next stack (after --> evaluated by) contains plenty of information about
what the program was doing when it evaluated head [].
Implementation details aside, the function names in the stack should hopefully give you
enough clues to track down the bug.
See also the function traceStack in the module [Link] for another way to view
call stacks.
-Z
Turn off update frame squeezing on context switch. (There’s no particularly good reason
to turn it off, except to ensure the accuracy of certain data collected regarding thunk
entry counts.)
--info
It is possible to ask the RTS to give some information about itself. To do this, use the
--info (page 173) flag, e.g.
This section describes what files GHC expects to find, what files it creates, where these files
are stored, and what options affect this behaviour.
Pathname conventions vary from system to system. In particular, the directory separator
is “/” on Unix systems and “\” on Windows systems. In the sections that follow, we shall
consistently use “/” as the directory separator; substitute this for the appropriate character
for your system.
When asked to compile a source file, GHC normally generates two files: an object file, and an
interface file.
The object file, which normally ends in a .o suffix, contains the compiled code for the module.
The interface file, which normally ends in a .hi suffix, contains the information that GHC
needs in order to compile further modules that depend on this module. It contains things like
the types of exported functions, definitions of data types, and so on. It is stored in a binary
format, so don’t try to read one; use the --show-iface ⟨file⟩ (page 76) option instead (see
Other options related to interface files (page 179)).
You should think of the object file and the interface file as a pair, since the interface file is in a
sense a compiler-readable description of the contents of the object file. If the interface file and
object file get out of sync for any reason, then the compiler may end up making assumptions
about the object file that aren’t true; trouble will almost certainly follow. For this reason,
we recommend keeping object files and interface files in the same place (GHC does this by
default, but it is possible to override the defaults as we’ll explain shortly).
Every module has a module name defined in its source code (module A.B.C where ...).
The name of the object file generated by GHC is derived according to the following rules,
where ⟨osuf⟩ is the object-file suffix (this can be changed with the -osuf option).
• If there is no -odir option (the default), then the object filename is derived from the
source filename (ignoring the module name) by replacing the suffix with ⟨osuf⟩.
• If -odir ⟨dir⟩ has been specified, then the object filename is ⟨dir⟩/⟨mod⟩.⟨osuf⟩, where
⟨mod⟩ is the module name with dots replaced by slashes. GHC will silently create the
necessary directory structure underneath ⟨dir⟩, if it does not already exist.
The name of the interface file is derived using the same rules, except that the suffix is ⟨hisuf⟩
(.hi by default) instead of ⟨osuf⟩, and the relevant options are -hidir ⟨dir⟩ (page 178)
and -hisuf ⟨suffix⟩ (page 178) instead of -odir ⟨dir⟩ (page 177) and -osuf ⟨suffix⟩
(page 178) respectively.
For example, if GHC compiles the module A.B.C in the file src/A/B/[Link], with no -odir or
-hidir flags, the interface file will be put in src/A/B/[Link] and the object file in src/A/B/C.o.
For any module that is imported, GHC requires that the name of the module in the import
statement exactly matches the name of the module in the interface file (or source file) found
using the strategy specified in The search path (page 176). This means that for most modules,
the source file name should match the module name.
However, note that it is reasonable to have a module Main in a file named [Link], but this
only works because GHC never needs to search for the interface for module Main (because it
is never imported). It is therefore possible to have several Main modules in separate source
files in the same directory, and GHC will not get confused.
In batch compilation mode, the name of the object file can also be overridden using the -o
⟨file⟩ (page 176) option, and the name of the interface file can be specified directly using
the -ohi ⟨file⟩ (page 177) option.
In your program, you import a module Foo by saying import Foo. In --make (page 76) mode
or GHCi, GHC will look for a source file for Foo and arrange to compile it first. Without --make
(page 76), GHC will look for the interface file for Foo, which should have been created by an
earlier compilation of Foo. GHC uses the same strategy in each of these cases for finding the
appropriate file.
This strategy is as follows: GHC keeps a list of directories called the search path. For each
of these directories, it tries appending ⟨basename⟩.⟨extension⟩ to the directory, and checks
whether the file exists. The value of ⟨basename⟩ is the module name with dots replaced by
the directory separator (“/” or “\\", depending on the system), and ⟨extension⟩ is a source
extension (hs, lhs) if we are in --make (page 76) mode or GHCi, or ⟨hisuf⟩ otherwise.
For example, suppose the search path contains directories d1, d2, and d3, and we are in
--make (page 76) mode looking for the source file for a module A.B.C. GHC will look in
d1/A/B/[Link], d1/A/B/[Link], d2/A/B/[Link], and so on.
The search path by default contains a single directory: “.” (i.e. the current directory). The
following options can be used to add to or change the contents of the search path:
-i⟨dir⟩[:⟨dir⟩]*
This flag appends a colon-separated list of dirs to the search path.
-i
resets the search path back to nothing.
This isn’t the whole story: GHC also looks for modules in pre-compiled libraries, known as
packages. See the section on packages (Packages (page 193)) for details.
-o ⟨file⟩
GHC’s compiled output normally goes into a .hc, .o, etc., file, depending on the last-run
compilation phase. The option -o file re-directs the output of that last-run phase to
⟨file⟩.
Note: This “feature” can be counterintuitive: ghc -C -o foo.o [Link] will put the
intermediate C code in the file foo.o, name notwithstanding!
This option is most often used when creating an executable file, to set the filename of
the executable. For example:
will compile the program starting with module Main and put the executable in the file
prog.
Note: on Windows, if the result is an executable file, the extension “.exe” is added if the
specified filename does not already have an extension. Thus
will compile and link the module [Link], and put the resulting executable in [Link]
(not foo).
If you use ghc --make and you don’t use the -o, the name GHC will choose for the
executable will be based on the name of the file containing the module Main. Note that
with GHC the Main module doesn’t have to be put in file [Link]. Thus both
and
The object files, Foo.o, Bar.o, and Bumble.o would be put into a subdirectory named
after the architecture of the executing machine (x86, mips, etc).
Note that the -odir option does not affect where the interface files are put; use the -
hidir option for that. In the above example, they would still be put in parse/[Link],
parse/[Link], and gurgle/[Link].
Please also note that when doing incremental compilation, this directory is where GHC
looks into to find object files from previous builds.
-ohi ⟨file⟩
The interface output may be directed to another file bar2/[Link] with the option
-ohi bar2/[Link] (not recommended).
Warning: If you redirect the interface file somewhere that GHC can’t find it, then
the recompilation checker may get confused (at the least, you won’t get any recompi-
lation avoidance). We recommend using a combination of -hidir and -hisuf options
instead, if possible.
To avoid generating an interface at all, you could use this option to redirect the interface
into the bit bucket: -ohi /dev/null, for example.
-hidir ⟨dir⟩
Redirects all generated interface files into ⟨dir⟩, instead of the default.
Please also note that when doing incremental compilation (by ghc --make or ghc -c),
this directory is where GHC looks into to find interface files.
-hiedir ⟨dir⟩
Redirects all generated extended interface files into ⟨dir⟩, instead of the default.
Please also note that when doing incremental compilation (by ghc --make or ghc -c),
this directory is where GHC looks into to find extended interface files.
-stubdir ⟨dir⟩
Redirects all generated FFI stub files into ⟨dir⟩. Stub files are generated when the
Haskell source contains a foreign export or foreign import "&wrapper" declaration
(see Using foreign export and foreign import ccall “wrapper” with GHC (page 485)). The
-stubdir option behaves in exactly the same way as -odir and -hidir with respect to
hierarchical modules.
-dumpdir ⟨dir⟩
Redirects all dump files into ⟨dir⟩. Dump files are generated when -ddump-to-file is
used with other -ddump-* flags.
-outputdir ⟨dir⟩
The -outputdir option is shorthand for the combination of -odir ⟨dir⟩ (page 177), -
hidir ⟨dir⟩ (page 178), -hiedir ⟨dir⟩ (page 178), -stubdir ⟨dir⟩ (page 178) and
-dumpdir ⟨dir⟩ (page 178).
-osuf ⟨suffix⟩
The -osuf ⟨suffix⟩ will change the .o file suffix for object files to whatever you specify.
We use this when compiling libraries, so that objects for the profiling versions of the
libraries don’t clobber the normal ones.
-hisuf ⟨suffix⟩
Similarly, the -hisuf ⟨suffix⟩ will change the .hi file suffix for non-system interface files
(see Other options related to interface files (page 179)).
The -hisuf/-osuf game is particularly useful if you want to compile a program both with
and without profiling, in the same directory. You can say:
ghc ...
The following options are useful for keeping (or not keeping) certain intermediate files around,
when normally GHC would throw these away after compilation:
-keep-hc-file
-keep-hc-files
Keep intermediate .hc files when doing .hs-to-.o compilations via C (page 210) (Note:
.hc files are only generated by unregisterised (page 210) compilers).
-keep-hi-files
Keep intermediate .hi files. This is the default. You may use -no-keep-hi-files if you
are not interested in the .hi files.
-keep-hscpp-file
-keep-hscpp-files
Keep the output of the CPP pre-processor phase as .hscpp files. A .hscpp file is only
created, if a module gets compiled and uses the C pre-processor.
-keep-llvm-file
-keep-llvm-files
Implies -fllvm (page 216)
Keep intermediate .ll files when doing .hs-to-.o compilations via LLVM (page 209)
(Note: .ll files aren’t generated when using the native code generator, you may need
to use -fllvm (page 216) to force them to be produced).
-keep-o-files
Keep intermediate .o files. This is the default. You may use -no-keep-o-files if you
are not interested in the .o files.
-keep-s-file
-keep-s-files
Keep intermediate .s files.
-keep-tmp-files
Instructs the GHC driver not to delete any of its temporary files, which it normally keeps
in /tmp (or possibly elsewhere; see Redirecting temporary files (page 179)). Running
GHC with -v will show you what temporary files were generated along the way.
-tmpdir ⟨dir⟩
If you have trouble because of running out of space in /tmp (or wherever your installation
thinks temporary files should go), you may use the -tmpdir ⟨dir⟩ (page 179) option to
specify an alternate directory. For example, -tmpdir . says to put temporary files in
the current working directory.
Alternatively, use your TMPDIR environment variable. Set it to the name of the directory
where temporary files should be put. GCC and other programs will honour the TMPDIR
variable as well.
-ddump-hi
Dumps the new interface to standard output.
-ddump-hi-diffs
The compiler does not overwrite an existing .hi interface file if the new one is the same
as the old one; this is friendly to make. When an interface does change, it is often enlight-
ening to be informed. The -ddump-hi-diffs (page 179) option will make GHC report
the differences between the old and new .hi files.
-ddump-minimal-imports
Dump to the file [Link] (where ⟨M⟩ is the name of the module being compiled) a
“minimal” set of import declarations. The directory where the .imports files are created
can be controlled via the -dumpdir ⟨dir⟩ (page 178) option.
You can safely replace all the import declarations in [Link] with those found in its respec-
tive .imports file. Why would you want to do that? Because the “minimal” imports (a)
import everything explicitly, by name, and (b) import nothing that is not required. It can
be quite painful to maintain this property by hand, so this flag is intended to reduce the
labour.
--show-iface ⟨file⟩
where ⟨file⟩ is the name of an interface file, dumps the contents of that interface in a
human-readable format. See Modes of operation (page 76).
GHC builds up a wealth of information about a Haskell source file as it compiles it. Extended
interface files are a way of persisting some of this information to disk so that external tools,
such as IDE’s, can avoid parsing, typechecking, and renaming all over again. These files
contain
• a simplified AST
– nodes are annotated with source positions and types
– identifiers are annotated with scope information
• the raw bytes of the initial Haskell source
The GHC API exposes functions for reading and writing these files.
-fwrite-ide-info
Writes out extended interface files alongside regular interface files. Just like regular
interface files, GHC has a recompilation check to detect out of date or missing extended
interface files.
-fvalidate-ide-info
Runs a series of sanity checks and lints on the extended interface files that are being
written out. These include testing things properties such as variables not occurring
outside of their expected scopes.
The format in which GHC currently stores its typechecked AST, makes it costly to collect the
types for some expressions nodes. For the sake of performance, GHC currently chooses to
skip over these, so not all expression nodes should be expected to have type information on
them. See #16233 for more.
-fforce-recomp
Turn off recompilation checking (which is on by default). Recompilation checking nor-
mally stops compilation early, leaving an existing .o file in place, if it can be determined
that the module does not need to be recompiled.
-fignore-optim-changes
-fignore-hpc-changes
In the olden days, GHC compared the newly-generated .hi file with the previous version;
if they were identical, it left the old one alone and didn’t change its modification date. In
consequence, importers of a module with an unchanged output .hi file were not recompiled.
This doesn’t work any more. Suppose module C imports module B, and B imports module A. So
changes to module A might require module C to be recompiled, and hence when [Link] changes
we should check whether C should be recompiled. However, the dependencies of C will only
list [Link], not [Link], and some changes to A (changing the definition of a function that appears
in an inlining of a function exported by B, say) may conceivably not change [Link] one jot. So
now…
GHC calculates a fingerprint (in fact an MD5 hash) of each interface file, and of each decla-
ration within the interface file. It also keeps in every interface file a list of the fingerprints
of everything it used when it last compiled the file. If the source file’s modification date is
earlier than the .o file’s date (i.e. the source hasn’t changed since the file was last compiled),
and the recompilation checking is on, GHC will be clever. It compares the fingerprints on the
things it needs this time with the fingerprints on the things it needed last time (gleaned from
the interface file of the module being compiled); if they are all the same it stops compiling
early in the process saying “Compilation IS NOT required”. What a beautiful sight!
You can read about how all this works in the GHC commentary.
GHC supports the compilation of mutually recursive modules. This section explains how.
Every cycle in the module import graph must be broken by a hs-boot file. Suppose that
modules [Link] and [Link] are Haskell source files, thus:
module A where
import B( TB(..) )
f :: TB -> TA
f (MkTB x) = MkTA x
module B where
import {-# SOURCE #-} A( TA(..) )
g :: TA -> TB
g (MkTA x) = MkTB x
Here A imports B, but B imports A with a {-# SOURCE #-} pragma, which breaks the circular
dependency. Every loop in the module import graph must be broken by a {-# SOURCE #-}
import; or, equivalently, the module import graph must be acyclic if {-# SOURCE #-} imports
are ignored.
For every module [Link] that is {-# SOURCE #-}-imported in this way there must exist a source
file [Link]-boot. This file contains an abbreviated version of [Link], thus:
module A where
newtype TA = MkTA Int
ghc -c [Link]-boot
When a hs-boot file [Link]-boot is compiled, it is checked for scope and type errors. When
its parent module [Link] is compiled, the two are compared, and an error is reported if
the two are inconsistent.
• Just as compiling [Link] produces an interface file [Link], and an object file A.o, so compil-
ing [Link]-boot produces an interface file [Link]-boot, and a pseudo-object file A.o-boot:
– The pseudo-object file A.o-boot is empty (don’t link it!), but it is very useful when
using a Makefile, to record when the [Link]-boot was last brought up to date (see
Using make (page 189)).
– The hi-boot generated by compiling a hs-boot file is in the same machine-
generated binary format as any other GHC-generated interface file (e.g. [Link]). You
can display its contents with ghc --show-iface. If you specify a directory for inter-
face files, the -ohidir flag, then that affects hi-boot files too.
• If hs-boot files are considered distinct from their parent source files, and if a {-# SOURCE
#-} import is considered to refer to the hs-boot file, then the module import graph must
have no cycles. The command ghc -M will report an error if a cycle is found.
• A module M that is {-# SOURCE #-}-imported in a program will usually also be ordinarily
imported elsewhere. If not, ghc --make automatically adds M to the set of modules it tries
to compile and link, to ensure that M‘s implementation is included in the final program.
A hs-boot file need only contain the bare minimum of information needed to get the bootstrap-
ping process started. For example, it doesn’t need to contain declarations for everything that
module A exports, only the things required by the module(s) that import A recursively.
A hs-boot file is written in a subset of Haskell:
• The module header (including the export list), and import statements, are exactly as in
Haskell, and so are the scoping rules. Hence, to mention a non-Prelude type or class,
you must import it.
• There must be no value declarations, but there can be type signatures for values. For
example:
The .. is meant literally – you should write two dots in your file. Note that the where
clause is still necessary to distinguish closed families from open ones. If you give any
equations of a closed family, you must give all of them, in the same order as they appear
in the accompanying Haskell file.
• A data type declaration can either be given in full, exactly as in Haskell, or it can be
given abstractly, by omitting the ‘=’ sign and everything that follows. For example:
data T a b
data R (x :: * -> *) y
You cannot use deriving on a data type declaration; write an instance declaration in-
stead.
• Class declarations is exactly as in Haskell, except that you may not put default method
declarations. You can also omit all the superclasses and class methods entirely; but you
must either omit them all or put them all in.
• You can include instance declarations just as in Haskell; but omit the “where” part.
• The default role for abstract datatype parameters is now representational. (An abstract
datatype is one with no constructors listed.) To get another role, use a role annotation.
(See Roles (page 352).)
GHC 8.2 supports module signatures (hsig files), which allow you to write a signature in
place of a module implementation, deferring the choice of implementation until a later point
in time. This feature is not intended to be used without Cabal; this manual entry will focus
on the syntax and semantics of signatures.
To start with an example, suppose you had a module A which made use of some string opera-
tions. Using normal module imports, you would only be able to pick a particular implementa-
tion of strings:
empty :: Str
empty = ""
module A where
import Str
z = toString empty
By replacing [Link] with a signature [Link], A (and any other modules in this package)
are now parametrized by a string implementation:
We can typecheck A against this signature, or we can instantiate Str with a module that
provides the following declarations. Refer to Cabal’s documentation for a more in-depth dis-
cussion on how to instantiate signatures.
Module signatures actually consist of two closely related features:
• The ability to define an hsig file, containing type definitions and type signature for values
which can be used by modules that import the signature, and must be provided by the
eventual implementing module, and
• The ability to inherit required signatures from packages we depend upon, combining the
signatures into a single merged signature which reflects the requirements of any locally
defined signature, as well as the requirements of our dependencies.
A signature file is denoted by an hsig file; every required signature must have an hsig file
(even if it is an empty one), including required signatures inherited from dependencies. Sig-
natures can be imported using an ordinary import Sig declaration.
hsig files are written in a variant of Haskell similar to hs-boot files, but with some slight
changes:
• The header of a signature is signature A where ... (instead of the usual module A
where ...).
• Import statements and scoping rules are exactly as in Haskell. To mention a non-Prelude
type or class, you must import it.
• Unlike regular modules, the defined entities of a signature include not only those written
in the local hsig file, but also those from inherited signatures (as inferred from the -
package-id ⟨unit-id⟩ (page 195) flags). These entities are not considered in scope
when typechecking the local hsig file, but are available for import by any module or
signature which imports the signature. The one exception to this rule is the export list,
described below.
If a declaration occurs in multiple inherited signatures, they will be merged together.
For values, we require that the types from both signatures match exactly; however, other
declarations may merge in more interesting ways. The merging operation in these cases
has the effect of textually replacing all occurrences of the old name with a reference to
the new, merged declaration. For example, if we have the following two signatures:
signature A where
data T
f :: T -> T
signature A where
data T = MkT
g :: T
signature A where
data T = MkT
f :: T -> T
g :: T
• If no export list is provided for a signature, the exports of a signature are all of its defined
entities merged with the exports of all inherited signatures.
If you want to reexport an entity from a signature, you must also include a module Sig-
Name export, so that all of the entities defined in the signature are exported. For example,
the following module exports both f and Int from Prelude:
Reexports merge with local declarations; thus, the signature above would successfully
merge with:
signature A where
data Int
Conversely, any entity requested by a signature can be provided by a reexport from the
implementing module. This is different from hs-boot files, which require every entity to
be defined locally in the implementing module.
• GHC has experimental support for signature thinning, which is used when a signature
has an explicit export list without a module export of the signature itself. In this case,
the export list applies to the final export list after merging, in particular, you may refer
to entities which are not declared in the body of the local hsig file.
The semantics in this case is that the set of required entities is defined exclusively by its
exports; if an entity is not mentioned in the export list, it is not required. The motivation
behind this feature is to allow a library author to provide an omnibus signature contain-
ing the type of every function someone might want to use, while a client thins down the
exports to the ones they actually require. For example, supposing that you have inher-
ited a signature for strings, you might write a local signature of this form, listing only
the entities that you need:
A few caveats apply here. First, it is illegal to export an entity which refers to a locally
defined type which itself is not exported (GHC will report an error in this case). Second,
signatures which come from dependencies which expose modules cannot be thinned in
this way (after all, the dependency itself may need the entity); these requirements are
unconditionally exported. Finally, any module reexports must refer to modules imported
by the local signature (even if an inherited signature exported the module).
We may change the syntax and semantics of this feature in the future.
• The declarations and types from signatures of dependencies that will be merged in are
not in scope when type checking an hsig file. To refer to any such type, you must declare
it yourself:
-- Not OK
signature A (T, f) where
f :: T -> T
-- OK
signature A (T, f) where
data T
f :: T -> T
• There must be no value declarations, but there can be type signatures for values. For
example, we might define the signature:
signature A where
double :: Int -> Int
A module implementing A would have to export the function double with a type defini-
tionally equal to the signature. Note that this means you can’t implement double using
a polymorphic function double :: Num a => a -> a.
Note that signature matching does check if fixity matches, so be sure specify fixity of
ordinary identifiers if you intend to use them with backticks.
• Fixity, type synonym, open type/data family declarations are permitted as in normal
Haskell.
• Closed type family declarations are permitted as in normal Haskell. They can also be
given abstractly, as in the following example:
The .. is meant literally – you should write two dots in your file. The where clause
distinguishes closed families from open ones.
• A data type declaration can either be given in full, exactly as in Haskell, or it can be
given abstractly, by omitting the ‘=’ sign and everything that follows. For example:
signature A where
data T a b
Abstract data types can be implemented not only with data declarations, but also new-
types and type synonyms (with the restriction that a type synonym must be fully eta-
reduced, e.g., type T = ... to be accepted.) For example, the following are all valid
implementations of the T above:
-- Newtype
newtype T a b = MkT (a, b)
-- Type synonym
data T2 a b = MkT2 a a b b
type T = T2
Data type declarations merge only with other data type declarations which match exactly,
except abstract data, which can merge with data, newtype or type declarations. Merges
with type synonyms are especially useful: suppose you are using a package of strings
which has left the type of characters in the string unspecified:
If you locally define a signature which specifies type Elem = Char, you can now use
head from the inherited signature as if it returned a Char.
If you do not write out the constructors, you may need to give a kind to tell GHC what
the kinds of the type variables are, if they are not the default *. Unlike regular data
type declarations, the return kind of an abstract data declaration can be anything (in
which case it probably will be implemented using a type synonym.) This can be used to
allow compile-time representation polymorphism (as opposed to run-time representation
polymorphism (page ??)), as in this example:
Roles of type parameters are subject to the subtyping relation phantom < representa-
tional < nominal: for example, an abstract type with a nominal type parameter can
be implemented using a concrete type with a representational type parameter. Merging
respects this subtyping relation (e.g., nominal merged with representational is repre-
sentational.) Roles in signatures default to nominal, which gives maximum flexibility
on the implementor’s side. You should only need to give an explicit role annotation if
a client of the signature would like to coerce the abstract type in a type parameter (in
which case you should specify representational explicitly.) Unlike regular data types,
we do not assume that abstract data types are representationally injective: if we have
Coercible (T a) (T b), and T has role nominal, this does not imply that a ~ b.
• A class declarations can either be abstract or concrete. An abstract class is one with no
superclasses or class methods:
signature A where
class Key k
It can be implemented in any way, with any set of superclasses and methods; however,
modules depending on an abstract class are not permitted to define instances (as of GHC
8.2, this restriction is not checked, see #13086.) These declarations can be implemented
by type synonyms of kind Constraint; this can be useful if you want to parametrize over
a constraint in functions. For example, with the ConstraintKinds extension, this type
synonym is a valid implementation of the signature above:
module A where
type Key = Eq
A concrete class specifies its superclasses, methods, default method signatures (but not
their implementations) and a MINIMAL pragma. Unlike regular Haskell classes, you don’t
have to explicitly declare a default for a method to make it optional vis-a-vis the MINIMAL
pragma.
When merging class declarations, we require that the superclasses and methods match
exactly; however, MINIMAL pragmas are logically ORed together, and a method with a
default signature will merge successfully against one that does not.
• You can include instance declarations as in Haskell; just omit the “where” part. An
instance declaration need not be implemented directly; if an instance can be derived
based on instances in the environment, it is considered implemented. For example, the
following signature:
signature A where
data Str
instance Eq Str
is considered implemented by the following module, since there are instances of Eq for
[] and Char which can be combined to form an instance Eq [Char]:
module A where
type Str = [Char]
Unlike other declarations, for which only the entities declared in a signature file are
brought into scope, instances from the implementation are always brought into scope,
even if they were not declared in the signature file. This means that a module may
typecheck against a signature, but not against a matching implementation. You can
avoid situations like this by never defining orphan instances inside a package that has
signatures.
Instance declarations are only merged if their heads are exactly the same, so it is possible
to get into a situation where GHC thinks that instances in a signature are overlapping,
even if they are implemented in a non-overlapping way. If this is giving you problems
give us a shout.
• Any orphan instances which are brought into scope by an import from a signature are
unconditionally considered in scope, even if the eventual implementing module doesn’t
actually import the same orphans.
Known limitations:
• Pattern synonyms are not supported.
• Algebraic data types specified in a signature cannot be implemented using pattern syn-
onyms. See #12717
It is reasonably straightforward to set up a Makefile to use with GHC, assuming you name
your source files the same as your modules. Thus:
HC = ghc
HC_OPTS = -cpp $(EXTRA_HC_OPTS)
cool_pgm : $(OBJS)
rm -f $@
$(HC) -o $@ $(HC_OPTS) $(OBJS)
.lhs.o:
$(HC) -c $< $(HC_OPTS)
.hs.o:
$(HC) -c $< $(HC_OPTS)
.[Link]-boot:
@:
.lhs-boot.o-boot:
$(HC) -c $< $(HC_OPTS)
.hs-boot.o-boot:
$(HC) -c $< $(HC_OPTS)
# Inter-module dependencies
Foo.o [Link] Foo.s : [Link] # Foo imports Baz
Main.o [Link] Main.s : [Link] [Link] # Main imports Foo and Baz
Note: Sophisticated make variants may achieve some of the above more elegantly. Notably,
gmake‘s pattern rules let you write the more comprehensible:
%.o : %.lhs
$(HC) -c $< $(HC_OPTS)
Note the cheesy .[Link] rule: It records the dependency of the interface (.hi) file on the source.
The rule says a .hi file can be made from a .o file by doing…nothing. Which is true.
Note that the suffix rules are all repeated twice, once for normal Haskell source files, and
once for hs-boot files (see How to compile mutually recursive modules (page 181)).
Note also the inter-module dependencies at the end of the Makefile, which take the form
They tell make that if any of Foo.o, [Link] or Foo.s have an earlier modification date than
[Link], then the out-of-date file must be brought up to date. To bring it up to date, make looks
for a rule to do so; one of the preceding suffix rules does the job nicely. These dependencies
can be generated automatically by ghc; see Dependency generation (page 190)
Putting inter-dependencies of the form Foo.o : [Link] into your Makefile by hand is rather
error-prone. Don’t worry, GHC has support for automatically generating the required depen-
dencies. Add the following to your Makefile:
depend :
ghc -dep-suffix '' -M $(HC_OPTS) $(SRCS)
Now, before you start compiling, and any time you change the imports in your program, do
make depend before you do make cool_pgm. The command ghc -M will append the needed
dependencies to your Makefile.
In general, ghc -M Foo does the following. For each module M in the set Foo plus all its
imports (transitively), it adds to the Makefile:
• A line recording the dependence of the object file on the source file.
M.o : [Link]
M.o : [Link]
• For each import declaration import {-# SOURCE #-} X in M, a line recording the depen-
dence of M on X:
M.o : [Link]-boot
(See How to compile mutually recursive modules (page 181) for details of hi-boot style
interface files.)
If M imports multiple modules, then there will be multiple lines with M.o as the target.
There is no need to list all of the source files as arguments to the ghc -M command; ghc traces
the dependencies, just like ghc --make (a new feature in GHC 6.4).
Note that ghc -M needs to find a source file for each module in the dependency graph, so that
it can parse the import declarations and follow dependencies. Any pre-compiled modules
without source files must therefore belong to a package 1 .
By default, ghc -M generates all the dependencies, and then concatenates them onto the
end of makefile (or Makefile if makefile doesn’t exist) bracketed by the lines “# DO NOT
DELETE: Beginning of Haskell dependencies” and “# DO NOT DELETE: End of Haskell
dependencies”. If these lines already exist in the makefile, then the old dependencies are
deleted first.
1 This is a change in behaviour relative to 6.2 and earlier.
Don’t forget to use the same -package options on the ghc -M command line as you would
when compiling; this enables the dependency generator to locate any imported modules that
come from packages. The package modules won’t be included in the dependencies generated,
though (but see the -include-pkg-deps option below).
The dependency generation phase of GHC can take some additional options, which you may
find useful. The options which affect dependency generation are:
-ddump-mod-cycles
Display a list of the cycles in the module graph. This is useful when trying to eliminate
such cycles.
-v2
Print a full list of the module dependencies to stdout. (This is the standard verbosity flag,
so the list will also be displayed with -v3 and -v4; see Verbosity options (page 79).)
-dep-makefile ⟨file⟩
Use ⟨file⟩ as the makefile, rather than makefile or Makefile. If ⟨file⟩ doesn’t exist, mkde-
pendHS creates it. We often use -dep-makefile .depend to put the dependencies in
.depend and then include the file .depend into Makefile.
-dep-suffix ⟨suffix⟩
Make dependencies that declare that files with suffix .⟨suf⟩⟨osuf⟩ depend on interface
files with suffix .⟨suf⟩hi, or (for {-# SOURCE #-} imports) on .hi-boot. Multiple -dep-
suffix flags are permitted. For example, -dep-suffix a_ -dep-suffix b_ will make
dependencies for .hs on .hi, .a_hs on .a_hi, and .b_hs on .b_hi. Note that you must
provide at least one suffix; if you do not want a suffix then pass -dep-suffix ''.
--exclude-module=⟨file⟩
Regard ⟨file⟩ as “stable”; i.e., exclude it from having dependencies on it.
-include-pkg-deps
Regard modules imported from packages as unstable, i.e., generate dependencies on any
imported package modules (including Prelude, and all other standard Haskell libraries).
Dependencies are not traced recursively into packages; dependencies are only gener-
ated for home-package modules on external-package modules directly imported by the
home package module. This option is normally only used by the various system libraries.
-include-cpp-deps
Output preprocessor dependencies. This only has an effect when the CPP language
extension is enabled. These dependencies are files included with the #include prepro-
cessor directive (as well as transitive includes) and implicitly included files such as stan-
dard c preprocessor headers and a GHC version header. One exception to this is that
GHC generates a temporary header file (during compilation) containing package version
macros. As this is only a temporary file that GHC will always generate, it is not output
as a dependency.
Haskell specifies that when compiling module M, any instance declaration in any module “be-
low” M is visible. (Module A is “below” M if A is imported directly by M, or if A is below a
module that M imports directly.) In principle, GHC must therefore read the interface files of
every module below M, just in case they contain an instance declaration that matters to M. This
would be a disaster in practice, so GHC tries to be clever.
In particular, if an instance declaration is in the same module as the definition of any type
or class mentioned in the head of the instance declaration (the part after the “=>”; see Re-
laxed rules for instance contexts (page 411)), then GHC has to visit that interface file anyway.
Example:
module A where
instance C a => D (T a) where ...
data T a = ...
The instance declaration is only relevant if the type T is in use, and if so, GHC will have visited
A‘s interface file to find T‘s definition.
The only problem comes when a module contains an instance declaration and GHC has no
other reason for visiting the module. Example:
Here, neither D nor T is declared in module Orphan. We call such modules “orphan modules”.
GHC identifies orphan modules, and visits the interface file of every orphan module below the
module being compiled. This is usually wasted work, but there is no avoiding it. You should
therefore do your best to have as few orphan modules as possible.
Functional dependencies complicate matters. Suppose we have:
module B where
instance E T Int where ...
data T = ...
Is this an orphan module? Apparently not, because T is declared in the same module. But
suppose class E had a functional dependency:
Then in some importing module M, the constraint (E a Int) should be “improved” by setting
a = T, even though there is no explicit mention of T in M.
These considerations lead to the following definition of an orphan module:
• An orphan module orphan module contains at least one orphan instance or at least one
orphan rule.
• An instance declaration in a module M is an orphan instance if
– The class of the instance declaration is not declared in M, and
– Either the class has no functional dependencies, and none of the type constructors
in the instance head is declared in M; or there is a functional dependency for which
none of the type constructors mentioned in the non-determined part of the instance
head is defined in M.
Only the instance head counts. In the example above, it is not good enough for C‘s
declaration to be in module A; it must be the declaration of D or T.
• A rewrite rule in a module M is an orphan rule orphan rule if none of the variables, type
constructors, or classes that are free in the left hand side of the rule are declared in M.
If you use the flag -Worphans (page 97), GHC will warn you if you are creating an orphan
module. Like any warning, you can switch the warning off with -Wno-orphans (page 97), and
-Werror (page 87) will make the compilation fail if the warning is issued.
You can identify an orphan module by looking in its interface file, [Link], using the --show-
iface ⟨file⟩ (page 76) mode (page 76). If there is a [orphan module] on the first line,
GHC considers it an orphan module.
5.9 Packages
A package is a library of Haskell modules known to the compiler. GHC comes with several
packages: see the accompanying library documentation. More packages to install can be
obtained from HackageDB.
Using a package couldn’t be simpler: if you’re using --make or GHCi, then most of the in-
stalled packages will be automatically available to your program without any further options.
The exceptions to this rule are covered below in Using Packages (page 193).
Building your own packages is also quite straightforward: we provide the Cabal infrastructure
which automates the process of configuring, building, installing and distributing a package.
All you need to do is write a simple configuration file, put a few files in the right places, and
you have a package. See the Cabal documentation for details, and also the Cabal libraries
([Link], for example).
GHC only knows about packages that are installed. Installed packages live in package
databases. For details on package databases and how to control which package databases or
specific set of packages are visible to GHC, see Package Databases (page 197).
To see which packages are currently available, use the ghc-pkg list command:
$ ghc-pkg list
/usr/lib/ghc-6.12.1/[Link].d:
Cabal-1.7.4
array-[Link]
base-[Link]
base-[Link]
bin-package-db-[Link]
binary-[Link]
bytestring-[Link]
containers-[Link]
directory-[Link]
(dph-base-0.4.0)
(dph-par-0.4.0)
(dph-prim-interface-0.4.0)
(dph-prim-par-0.4.0)
(dph-prim-seq-0.4.0)
(dph-seq-0.4.0)
extensible-exceptions-[Link]
ffi-1.0
filepath-[Link]
(ghc-6.12.1)
ghc-prim-[Link]
haskeline-0.6.2
haskell98-[Link]
hpc-[Link]
integer-gmp-[Link]
mtl-[Link]
old-locale-[Link]
old-time-[Link]
pretty-[Link]
process-[Link]
random-[Link]
rts-1.0.1
syb-[Link]
template-haskell-[Link]
terminfo-0.3.1
time-1.1.4
unix-[Link]
utf8-string-0.3.4
An installed package is either exposed or hidden by default. Packages hidden by default are
listed in parentheses (e.g. (lang-1.0)), or possibly in blue if your terminal supports colour,
in the output of ghc-pkg list. Command-line flags, described below, allow you to expose
a hidden package or hide an exposed one. Only modules from exposed packages may be
imported by your Haskell code; if you try to import a module from a hidden package, GHC
will emit an error message. It should be noted that a hidden package might still get linked
with your program as a dependency of an exposed package, it is only restricted from direct
imports.
If there are multiple exposed versions of a package, GHC will prefer the latest one. Addi-
tionally, some packages may be broken: that is, they are missing from the package database,
or one of their dependencies are broken; in this case; these packages are excluded from the
default set of packages.
Note: If you’re using Cabal, then the exposed or hidden status of a package is irrelevant:
the available packages are instead determined by the dependencies listed in your .cabal
specification. The exposed/hidden status of packages is only relevant when using ghc or ghci
directly.
Similar to a package’s hidden status is a package’s trusted status. A package can be either
trusted or not trusted (distrusted). By default packages are distrusted. This property of a
package only plays a role when compiling code using GHC’s Safe Haskell feature (see Safe
Haskell (page 493)) with the -fpackage-trust flag enabled.
To see which modules are provided by a package use the ghc-pkg command (see Package
management (the ghc-pkg command) (page 202)):
one version of a package, all other versions become hidden. If -package option is spec-
ified multiple times for the same package the last one overrides the previous ones. On
the other hand, if -hide-all-packages (page 195) is used, GHC allows you to expose
multiple versions of a package by using the -package option multiple times with different
versions of the same package.
-package supports thinning and renaming described in Thinning and renaming modules
(page 197).
The -package ⟨pkg⟩ option also causes package ⟨pkg⟩ to be linked into the resulting exe-
cutable or shared object. Whether a packages’ library is linked statically or dynamically
is controlled by the flag pair -static (page 218)/ -dynamic (page 218).
In --make (page 76) mode and --interactive (page 76) mode (see Modes of operation
(page 76)), the compiler normally determines which packages are required by the cur-
rent Haskell modules, and links only those. In batch mode however, the dependency
information isn’t available, and explicit -package options must be given when linking.
The one other time you might need to use -package to force linking a package is when
the package does not contain any Haskell modules (it might contain a C library only,
for example). In that case, GHC will never discover a dependency on it, so it has to be
mentioned explicitly.
For example, to link a program consisting of objects Foo.o and Main.o, where we made
use of the network package, we need to give GHC the -package flag thus:
The same flag is necessary even if we compiled the modules from source, because GHC
still reckons it’s in batch mode:
-package-id ⟨unit-id⟩
Exposes a package like -package ⟨pkg⟩ (page 194), but the package is named by its
unit ID (i.e. the value of id in its entry in the installed package database, also previously
known as an installed package ID) rather than by name. This is a more robust way to
name packages, and can be used to select packages that would otherwise be shadowed.
Cabal passes -package-id flags to GHC. -package-id supports thinning and renaming
described in Thinning and renaming modules (page 197).
-hide-all-packages
Ignore the exposed flag on installed packages, and hide them all by default. If you use
this flag, then any packages you require (including base) need to be explicitly exposed
using -package ⟨pkg⟩ (page 194) options.
This is a good way to insulate your program from differences in the globally exposed
packages, and being explicit about package dependencies is a Good Thing. Cabal always
passes the -hide-all-packages flag to GHC, for exactly this reason.
-hide-package ⟨pkg⟩
This option does the opposite of -package ⟨pkg⟩ (page 194): it causes the specified
package to be hidden, which means that none of its modules will be available for import
by Haskell import directives.
Note that the package might still end up being linked into the final program, if it is a
dependency (direct or indirect) of another exposed package.
-ignore-package ⟨pkg⟩
Causes the compiler to behave as if package ⟨pkg⟩, and any packages that depend on
Every complete Haskell program must define main in module Main in package main. Omitting
the -this-unit-id ⟨unit-id⟩ (page 196) flag compiles code for package main. Failure to
do so leads to a somewhat obscure link-time error of the form:
It is possible that by using packages you might end up with a program that contains two
modules with the same name: perhaps you used a package P that has a hidden module M,
and there is also a module M in your program. Or perhaps the dependencies of packages that
you used contain some overlapping modules. Perhaps the program even contains multiple
versions of a certain package, due to dependencies from other packages.
None of these scenarios gives rise to an error on its own 1 , but they may have some interesting
1 it used to in GHC 6.4, but not since 6.6
consequences. For instance, if you have a type M.T from version 1 of package P, then this is
not the same as the type M.T from version 2 of package P, and GHC will report an error if you
try to use one where the other is expected.
Formally speaking, in Haskell 98, an entity (function, type or class) in a program is uniquely
identified by the pair of the module name in which it is defined and its name. In GHC, an
entity is uniquely defined by a triple: package, module, and name.
When incorporating packages from multiple sources, you may end up in a situation where mul-
tiple packages publish modules with the same name. Previously, the only way to distinguish
between these modules was to use Package-qualified imports (page 281). However, since
GHC 7.10, the -package ⟨pkg⟩ (page 194) flags (and their variants) have been extended to
allow a user to explicitly control what modules a package brings into scope, by analogy to the
import lists that users can attach to module imports.
The basic syntax is that instead of specifying a package name P to the package flag -package,
instead we specify both a package name and a parenthesized, comma-separated list of mod-
ule names to import. For example, -package "base ([Link],[Link])" makes only
[Link] and [Link] visible from package base. We also support renaming of modules,
in case you need to refer to both modules simultaneously; this is supporting by writing Old-
ModName as NewModName, e.g. -package "base ([Link] as Bool). You can also write
-package "base with ([Link] as Bool) to include all of the original bindings (e.g. the
renaming is strictly additive). It’s important to specify quotes so that your shell passes the
package name and thinning/renaming list as a single argument to GHC.
Package imports with thinning/renaming do not hide other versions of the package: e.g.
if containers-0.9 is already exposed, -package "containers-0.8 ([Link] as ListV8)"
will only add an additional binding to the environment. Similarly, -package "base
([Link] as Bool)" -package "base ([Link] as List)" is equivalent to -package
"base ([Link] as Bool,[Link] as List)". Literal names must refer to modules
defined by the original package, so for example -package "base ([Link] as Bool,Bool
as Baz)" is invalid unless there was a Bool module defined in the original package. Hiding
a package also clears all of its renamings.
You can use renaming to provide an alternate prelude, e.g. -hide-all-packages -package
"basic-prelude (BasicPrelude as Prelude)", in lieu of the Rebindable syntax and the im-
plicit Prelude import (page 259) extension.
A package database is where the details about installed packages are stored. It is a directory,
usually called [Link].d, that contains a file for each package, together with a binary
cache of the package data in the file [Link]. Normally you won’t need to look at or
modify the contents of a package database directly; all management of package databases
can be done through the ghc-pkg tool (see Package management (the ghc-pkg command)
(page 202)).
GHC knows about two package databases in particular:
• The global package database, which comes with your GHC installation, e.g.
/usr/lib/ghc-6.12.1/[Link].d.
• The user package database private to each user. On Unix systems this will be
$HOME/.ghc/arch-os-version/[Link].d, and on Windows it will be something
GHC_PACKAGE_PATH
The GHC_PACKAGE_PATH environment variable may be set to a :-separated (;-
separated on Windows) list of files containing package databases. This list of package
databases, used by GHC and ghc-pkg, specifies a stack of package databases from top to
bottom. This order was chosen to match the behaviour of the PATH environment variable
where entries earlier in the PATH override ones that come later. See Package Databases
(page 197) for details on how the package database stack is used.
Normally GHC_PACKAGE_PATH replaces the default package stack. For example, all of
the following commands are equivalent, creating a stack with db1 at the top followed by
db2 (use ; instead of : on Windows):
$ export GHC_PACKAGE_PATH=$HOME/.[Link]:
To check whether your GHC_PACKAGE_PATH setting is doing the right thing, ghc-pkg
list will list all the databases in use, in the reverse order they are searched.
Package environments
A package environment file is a file that tells ghc precisely which packages should be visible.
It can be used to create environments for ghc or ghci that are local to a shell session or to
some file system location. They are intended to be managed by build/package tools, to enable
ghc and ghci to automatically use an environment created by the tool.
The file contains package IDs and optionally package databases, one directive per line:
clear-package-db
global-package-db
user-package-db
package-db db.d/
package-id id_1
package-id id_2
...
package-id id_n
If such a package environment is found, it is equivalent to passing these command line argu-
ments to ghc:
-hide-all-packages
-clear-package-db
-global-package-db
-user-package-db
-package-db db.d/
-package-id id_1
-package-id id_2
...
-package-id id_n
Note the implicit -hide-all-packages (page 195) and the fact that it is -package-id ⟨unit-
id⟩ (page 195), not -package ⟨pkg⟩ (page 194). This is because the environment specifies
Each installed package has a unique identifier (the “installed package ID”), which distin-
guishes it from all other installed packages on the system. To see the installed package IDs
associated with each installed package, use ghc-pkg list -v:
$ ghc-pkg list -v
using cache: /usr/lib/ghc-6.12.1/[Link].d/[Link]
/usr/lib/ghc-6.12.1/[Link].d
Cabal-1.7.4 (Cabal-1.7.4-48f5247e06853af93593883240e11238)
array-[Link] (array-[Link]-9cbf76a576b6ee9c1f880cf171a0928d)
base-[Link] (base-[Link]-6cbb157b9ae852096266e113b8fac4a2)
base-[Link] (base-[Link]-247bb20cde37c3ef4093ee124e04bc1c)
...
The string in parentheses after the package name is the installed package ID: it normally be-
gins with the package name and version, and ends in a hash string derived from the compiled
package. Dependencies between packages are expressed in terms of installed package IDs,
rather than just packages and versions. For example, take a look at the dependencies of the
haskell98 package:
The purpose of the installed package ID is to detect problems caused by re-installing a pack-
age without also recompiling the packages that depend on it. Recompiling dependencies is
necessary, because the newly compiled package may have a different ABI (Application Binary
Interface) than the previous version, even if both packages were built from the same source
code using the same compiler. With installed package IDs, a recompiled package will have a
different installed package ID from the previous version, so packages that depended on the
previous version are now orphaned - one of their dependencies is not satisfied. Packages that
are broken in this way are shown in the ghc-pkg list output either in red (if possible) or oth-
erwise surrounded by braces. In the following example, we have recompiled and reinstalled
the filepath package, and this has caused various dependencies including Cabal to break:
$ ghc-pkg list
WARNING: there are broken packages. Run 'ghc-pkg check' for more details.
/usr/lib/ghc-6.12.1/[Link].d:
{Cabal-1.7.4}
array-[Link]
base-[Link]
... etc ...
Additionally, ghc-pkg list reminds you that there are broken packages and suggests ghc-
pkg check, which displays more information about the nature of the failure:
$ ghc-pkg check
There are problems in package ghc-6.12.1:
dependency "filepath-[Link]-87511764eb0af2bce4db05e702750e63" doesn't exist
There are problems in package haskeline-0.6.2:
dependency "filepath-[Link]-87511764eb0af2bce4db05e702750e63" doesn't exist
There are problems in package Cabal-1.7.4:
dependency "filepath-[Link]-87511764eb0af2bce4db05e702750e63" doesn't exist
There are problems in package process-[Link]:
dependency "filepath-[Link]-87511764eb0af2bce4db05e702750e63" doesn't exist
There are problems in package directory-[Link]:
dependency "filepath-[Link]-87511764eb0af2bce4db05e702750e63" doesn't exist
The following packages are broken, either because they have a problem
listed above, or because they depend on a broken package.
ghc-6.12.1
haskeline-0.6.2
Cabal-1.7.4
process-[Link]
directory-[Link]
bin-package-db-[Link]
hpc-[Link]
haskell98-[Link]
To fix the problem, you need to recompile the broken packages against the new dependen-
cies. The easiest way to do this is to use cabal-install, or download the packages from
HackageDB and build and install them as normal.
Be careful not to recompile any packages that GHC itself depends on, as this may render the
ghc package itself broken, and ghc cannot be simply recompiled. The only way to recover
from this would be to re-install GHC.
The ghc-pkg tool is for querying and modifying package databases. To see what pack-
age databases are in use, use ghc-pkg list. The stack of databases that ghc-pkg knows
about can be modified using the GHC_PACKAGE_PATH (page 198) environment variable (see
The GHC_PACKAGE_PATH environment variable (page 198), and using -package-db ⟨file⟩
(page 198) options on the ghc-pkg command line.
When asked to modify a database, ghc-pkg modifies the global database by default. Specifying
--user causes it to act on the user database, or --package-db can be used to act on another
database entirely. When multiple of these options are given, the rightmost one is used as the
database to act upon.
Commands that query the package database (list, latest, describe, field, dot) operate on the
list of databases specified by the flags --user, --global, and --package-db. If none of these
flags are given, the default is --global --user.
If the environment variable GHC_PACKAGE_PATH (page 198) is set, and its value does not end
in a separator (: on Unix, ; on Windows), then the last database is considered to be the
global database, and will be modified by default by ghc-pkg. The intention here is that
GHC_PACKAGE_PATH can be used to create a virtual package environment into which Cabal
packages can be installed without setting anything other than GHC_PACKAGE_PATH.
The ghc-pkg program may be run in the ways listed below. Where a package name is required,
the package can be named in full including the version number (e.g. network-1.0), or without
the version number. Naming a package without the version number matches all versions of
the package; the specified action will be applied to all the matching packages. A package
specifier that matches all version of the package can also be written ⟨pkg⟩ -*, to make it
clearer that multiple packages are being matched. To match against the installed package ID
instead of just package name and version, pass the --ipid flag.
ghc-pkg init path Creates a new, empty, package database at ⟨path⟩, which must not al-
ready exist.
ghc-pkg register ⟨file⟩ Reads a package specification from ⟨file⟩ (which may be “-” to
indicate standard input), and adds it to the database of installed packages. The syntax
of ⟨file⟩ is given in InstalledPackageInfo: a package specification (page 206).
The package specification must be a package that isn’t already installed.
ghc-pkg update ⟨file⟩ The same as register, except that if a package of the same name
is already installed, it is replaced by the new one.
ghc-pkg unregister ⟨P⟩ Remove the specified package from the database.
ghc-pkg check Check consistency of dependencies in the package database, and report pack-
ages that have missing dependencies.
ghc-pkg expose ⟨P⟩ Sets the exposed flag for package ⟨P⟩ to True.
ghc-pkg hide ⟨P⟩ Sets the exposed flag for package ⟨P⟩ to False.
ghc-pkg trust ⟨P⟩ Sets the trusted flag for package ⟨P⟩ to True.
ghc-pkg distrust ⟨P⟩ Sets the trusted flag for package ⟨P⟩ to False.
ghc-pkg list [⟨P⟩] [--simple-output] This option displays the currently installed pack-
ages, for each of the databases known to ghc-pkg. That includes the global database, the
user’s local database, and any further files specified using the -f option on the command
line.
Hidden packages (those for which the exposed flag is False) are shown in parentheses
in the list of packages.
If an optional package identifier ⟨P⟩ is given, then only packages matching that identifier
are shown.
If the option --simple-output is given, then the packages are listed on a single line
separated by spaces, and the database names are not included. This is intended to make
it easier to parse the output of ghc-pkg list using a script.
ghc-pkg find-module ⟨M⟩ [--simple-output] This option lists registered packages expos-
ing module ⟨M⟩. Examples:
ghc-pkg dump Emit the full description of every package, in the form of an InstalledPack-
ageInfo. Multiple package descriptions are separated by the string --- on a line by
itself.
This is almost the same as ghc-pkg describe '*', except that ghc-pkg dump is intended
for use by tools that parse the results, so for example where ghc-pkg describe '*' will
emit an error if it can’t find any packages that match the pattern, ghc-pkg dump will
simply emit nothing.
ghc-pkg recache Re-creates the binary cache file [Link] for the selected database.
This may be necessary if the cache has somehow become out-of-sync with the contents
of the database (ghc-pkg will warn you if this might be the case).
The other time when ghc-pkg recache is useful is for registering packages manually: it
is possible to register a package by simply putting the appropriate file in the package
database directory and invoking ghc-pkg recache to update the cache. This method of
registering packages may be more convenient for automated packaging systems.
Substring matching is supported for ⟨M⟩ in find-module and for ⟨P⟩ in list, describe, and
field, where a '*' indicates open substring ends (prefix*, *suffix, *infix*). Examples
(output omitted):
We don’t recommend building packages the hard way. Instead, use the Cabal infrastructure
if possible. If your package is particularly complicated or requires a lot of configuration, then
you might have to fall back to the low-level mechanisms, so a few hints for those brave souls
follow.
You need to build an “installed package info” file for passing to ghc-pkg when installing your
package. The contents of this file are described in InstalledPackageInfo: a package specifica-
tion (page 206).
The Haskell code in a package may be built into one or more archive libraries (e.g. libHS-
foo.a), or a single shared object (e.g. [Link]/.so/.dylib). The restriction to a single
shared object is because the package system is used to tell the compiler when it should make
an inter-shared-object call rather than an intra-shared-object-call call (inter-shared-object
calls require an extra indirection).
• Building a static library is done by using the ar tool, like so:
where A.o, B.o and so on are the compiled Haskell modules, and libHSfoo.a is the
library you wish to create. The syntax may differ slightly on your system, so check the
documentation if you run into difficulties.
• To load a package foo, GHCi can load its libHSfoo.a library directly, but it can also
load a package in the form of a single HSfoo.o file that has been pre-linked. Loading
the .o file is slightly quicker, but at the expense of having another copy of the compiled
package. The rule of thumb is that if the modules of the package were compiled with
-split-sections (page 218) then building the HSfoo.o is worthwhile because it saves
time when loading the package into GHCi. Without -split-sections (page 218), there
is not much difference in load time between the .o and .a libraries, so it is better to save
the disk space and only keep the .a around. In a GHC distribution we provide .o files
for most packages except the GHC package itself.
The HSfoo.o file is built by Cabal automatically; use --disable-library-for-ghci to
disable it. To build one manually, the following GNU ld command can be used:
Using GHC’s version number in the shared object name allows different library versions
compiled by different GHC versions to be installed in standard system locations, e.g. un-
der *nix /usr/lib. To obtain the version number of GHC invoke ghc --numeric-version
and use its output in place of ⟨GHCVersion⟩. See also Options affecting code generation
(page 216) on how object files must be prepared for shared object linking.
• When building a shared library, care must be taken to ensure that the resulting object
is named appropriately. In particular, GHC expects the name of a shared object to have
the form libHS<unit id>-ghc<ghc version>.<ext> where unit id is the unit ID given
during compilation via the -this-unit-id ⟨unit-id⟩ (page 196) flag, ghc version is the
version of GHC that produced/consumes the object and ext is the host system’s usual file
extension for shared objects.
To compile a module which is to be part of a new package, use the -package-name (to identify
the name of the package) and -library-name (to identify the version and the version hashes
of its identities.) options (Using Packages (page 193)). Failure to use these options when
compiling a package will probably result in disaster, but you will only discover later when
you attempt to import modules from the package. At this point GHC will complain that the
package name it was expecting the module to come from is not the same as the package name
stored in the .hi file.
It is worth noting with shared objects, when each package is built as a single shared object
file, since a reference to a shared object costs an extra indirection, intra-package references
are cheaper than inter-package references. Of course, this applies to the main package as
well.
library-dirs: /usr/lib/ghc-6.12.1/unix-[Link]
hs-libraries: HSunix-[Link]
extra-libraries: rt util dl
extra-ghci-libraries:
include-dirs: /usr/lib/ghc-6.12.1/unix-[Link]/include
includes: HsUnix.h execvpe.h
depends: base-[Link]-247bb20cde37c3ef4093ee124e04bc1c
hugs-options:
cc-options:
ld-options:
framework-dirs:
frameworks:
haddock-interfaces: /usr/share/doc/ghc/html/libraries/unix/[Link]
haddock-html: /usr/share/doc/ghc/html/libraries/unix
category (optional freeform) Which category the package belongs to. This field is for use in
conjunction with a future centralised package distribution framework, tentatively titled
Hackage.
author (optional freeform) Author of the package.
exposed (bool) Whether the package is exposed or not.
exposed-modules (string list) modules exposed by this package.
hidden-modules (string list) modules provided by this package, but not exposed to the pro-
grammer. These modules cannot be imported, but they are still subject to the overlap-
ping constraint: no other package in the same program may provide a module of the
same name.
reexported-modules Modules reexported by this package. This list takes the form of
pkg:OldName as NewName (A@orig-pkg-0.1-HASH): the first portion of the string is the
user-written reexport specification (possibly omitting the package qualifier and the re-
naming), while the parenthetical is the original package which exposed the module under
are particular name. Reexported modules have a relaxed overlap constraint: it’s permis-
sible for two packages to reexport the same module as the same name if the reexported
moduleis identical.
trusted (bool) Whether the package is trusted or not.
import-dirs (string list) A list of directories containing interface files (.hi files) for this
package.
If the package contains profiling libraries, then the interface files for those library mod-
ules should have the suffix .p_hi. So the package can contain both normal and profiling
versions of the same library without conflict (see also library_dirs below).
library-dirs (string list) A list of directories containing libraries for this package.
hs-libraries (string list) A list of libraries containing Haskell code for this package, with
the .a or .dll suffix omitted. When packages are built as libraries, the lib prefix is also
omitted.
For use with GHCi, each library should have an object file too. The name of the object
file does not have a lib prefix, and has the normal object suffix for your platform.
For example, if we specify a Haskell library as HSfoo in the package spec, then the various
flavours of library that GHC actually uses will be called:
libHSfoo.a The name of the library on Unix and Windows (mingw) systems.
[Link] The name of the dynamic library on Windows systems (optional).
HSfoo.o; [Link] The object version of the library used by GHCi.
extra-libraries (string list) A list of extra libraries for this package. The difference be-
tween hs-libraries and extra-libraries is that hs-libraries normally have several
versions, to support profiling, parallel and other build options. The various versions
are given different suffixes to distinguish them, for example the profiling version of the
standard prelude library is named libHSbase_p.a, with the _p indicating that this is a
profiling version. The suffix is added automatically by GHC for hs-libraries only, no
suffix is added for libraries in extra-libraries.
The libraries listed in extra-libraries may be any libraries supported by your system’s
linker, including dynamic libraries (.so on Unix, .DLL on Windows).
Also, extra-libraries are placed on the linker command line after the hs-libraries for
the same package. If your package has dependencies in the other direction (i.e. extra-
libraries depends on hs-libraries), and the libraries are static, you might need to
make two separate packages.
include-dirs (string list) A list of directories containing C includes for this package.
includes (string list) A list of files to include for via-C compilations using this package. Typ-
ically the include file(s) will contain function prototypes for any C functions used in the
package, in case they end up being called as a result of Haskell functions from the pack-
age being inlined.
depends (package id list) Packages on which this package depends.
hugs-options (string list) Options to pass to Hugs for this package.
cc-options (string list) Extra arguments to be added to the gcc command line when this
package is being used (only for via-C compilations).
ld-options (string list) Extra arguments to be added to the gcc command line (for linking)
when this package is being used.
framework-dirs (string list) On Darwin/MacOS X, a list of directories containing frameworks
for this package. This corresponds to the -framework-path option. It is ignored on all
other platforms.
frameworks (string list) On Darwin/MacOS X, a list of frameworks to link to. This corresponds
to the -framework option. Take a look at Apple’s developer documentation to find out
what frameworks actually are. This entry is ignored on all other platforms.
haddock-interfaces (string list) A list of filenames containing Haddock interface files (.had-
dock files) for this package.
haddock-html (optional string) The directory containing the Haddock-generated HTML for
this package.
GHC supports multiple backend code generators. This is the part of the compiler responsible
for taking the last intermediate representation that GHC uses (a form called Cmm that is a
simple, C like language) and compiling it to executable code. The backends that GHC support
are described below.
The default backend for GHC. It is a native code generator, compiling Cmm all the way to
assembly code. It is the fastest backend and generally produces good performance code. It
has the best support for compiling shared libraries. Select it with the -fasm flag.
This is an alternative backend that uses the LLVM compiler to produce executable code. It
generally produces code with performance as good as the native code generator but for some
cases can produce much faster code. This is especially true for numeric, array heavy code
using packages like vector. The penalty is a significant increase in compilation times. Select
the LLVM backend with the -fllvm (page 216) flag.
You must install and have LLVM available on your PATH for the LLVM code generator to work.
Specifically GHC needs to be able to call the opt and llc tools. Secondly, if you are run-
ning Mac OS X with LLVM 3.0 or greater then you also need the Clang C compiler compiler
available on your PATH.
Note: Note that this GHC release expects an LLVM version in the @LlvmVersion@ release
series.
-fvia-C
Use the C code generator. Only supposed in unregisterised GHC builds.
This is the oldest code generator in GHC and is generally not included any more having been
deprecated around GHC 7.0. Select it with the -fvia-C (page 210) flag.
The C code generator is only supported when GHC is built in unregisterised mode, a mode
where GHC produces “portable” C code as output to facilitate porting GHC itself to a new
platform. This mode produces much slower code though so it’s unlikely your version of GHC
was built this way. If it has then the native code generator probably won’t be available. You
can check this information by calling ghc --info (see --info (page 77)).
The term “unregisterised” really means “compile via vanilla C”, disabling some of the platform-
specific tricks that GHC normally uses to make programs go faster. When compiling unregis-
terised, GHC simply generates a C file which is compiled via gcc.
When GHC is build in unregisterised mode only the LLVM and C code generators will be
available. The native code generator won’t be. LLVM usually offers a substantial performance
benefit over the C backend in unregisterised mode.
Unregisterised compilation can be useful when porting GHC to a new machine, since it re-
duces the prerequisite tools to gcc, as, and ld and nothing more, and furthermore the amount
of platform-specific code that needs to be written in order to get unregisterised compilation
going is usually fairly small.
Unregisterised compilation cannot be selected at compile-time; you have to build GHC with
the appropriate options set. Consult the GHC Building Guide for details.
You can check if your GHC is unregisterised by calling ghc --info (see --info (page 77)).
You may specify that a different program be used for one of the phases of the compilation
system, in place of whatever the ghc has wired into it. For example, you might want to try
a different assembler. The following options allow you to change the external program used
for a given compilation phase:
-pgmL ⟨cmd⟩
Use ⟨cmd⟩ as the literate pre-processor.
-pgmP ⟨cmd⟩
Use ⟨cmd⟩ as the C pre-processor (with -cpp only).
-pgmc ⟨cmd⟩
Use ⟨cmd⟩ as the C compiler.
-pgmlo ⟨cmd⟩
Use ⟨cmd⟩ as the LLVM optimiser.
-pgmlc ⟨cmd⟩
Use ⟨cmd⟩ as the LLVM compiler.
-pgms ⟨cmd⟩
Use ⟨cmd⟩ as the splitter.
-pgma ⟨cmd⟩
Use ⟨cmd⟩ as the assembler.
-pgml ⟨cmd⟩
Use ⟨cmd⟩ as the linker.
-pgmlm ⟨cmd⟩
Use ⟨cmd⟩ as the linker when merging object files (e.g. when generating joined objects
for loading into GHCi).
-pgmdll ⟨cmd⟩
Use ⟨cmd⟩ as the DLL generator.
-pgmF ⟨cmd⟩
Use ⟨cmd⟩ as the pre-processor (with -F (page 215) only).
-pgmotool ⟨cmd⟩
Use ⟨cmd⟩ as the program to inspect mach-o dynamic libraries and executables to read
the dynamic library dependencies. We will compute the necessary runpath``s to em-
bed for the dependencies based on the result of the ``otool call.
-pgminstall_name_tool ⟨cmd⟩
Use ⟨cmd⟩ as the program to inject runpath``s into mach-o dynamic libraries and
executables. As detected by the ``otool call.
-pgmwindres ⟨cmd⟩
Use ⟨cmd⟩ as the program to use for embedding manifests on Windows. Normally this
is the program windres, which is supplied with a GHC installation. See -fno-embed-
manifest in Options affecting linking (page 217).
-pgmlibtool ⟨cmd⟩
Use ⟨cmd⟩ as the libtool command (when using -staticlib (page 218) only).
-pgmi ⟨cmd⟩
Use ⟨cmd⟩ as the external interpreter command (see Running the interpreter in a sepa-
rate process (page 67)). Default: ghc-iserv-prof if -prof (page 557) is enabled, ghc-
iserv-dyn if -dynamic (page 218) is enabled, or ghc-iserv otherwise.
Options can be forced through to a particular compilation phase, using the following flags:
-optL ⟨option⟩
Pass ⟨option⟩ to the literate pre-processor
-optP ⟨option⟩
Pass ⟨option⟩ to CPP (makes sense only if -cpp is also on).
-optF ⟨option⟩
Pass ⟨option⟩ to the custom pre-processor (see Options affecting a Haskell pre-processor
(page 215)).
-optc ⟨option⟩
Pass ⟨option⟩ to the C compiler.
-pgmc-supports-no-pie
When -pgmc is used, GHC by default will never pass the -no-pie command line flag. The
rationale is that it is not known whether the specified compiler will support it. This flag
can be used to indicate that -no-pie is supported. It has to be passed after -pgmc.
This flag is not neccessary when -pgmc is not used, since GHC remembers whether the
default C compiler supports -no-pie in an internal settings file.
-optcxx ⟨option⟩
Pass ⟨option⟩ to the C++ compiler.
-optlo ⟨option⟩
Pass ⟨option⟩ to the LLVM optimiser.
-optlc ⟨option⟩
Pass ⟨option⟩ to the LLVM compiler.
-opta ⟨option⟩
Pass ⟨option⟩ to the assembler.
-optl ⟨option⟩
Pass ⟨option⟩ to the linker.
-optlm ⟨option⟩
Pass ⟨option⟩ to the linker when merging object files. In the case of a standard ld-style
linker this should generally include the -r flag.
-optdll ⟨option⟩
Pass ⟨option⟩ to the DLL generator.
-optwindres ⟨option⟩
Pass ⟨option⟩ to windres when embedding manifests on Windows. See -fno-embed-
manifest in Options affecting linking (page 217).
-opti ⟨option⟩
Pass ⟨option⟩ to the interpreter sub-process (see Running the interpreter in a separate
process (page 67)). A common use for this is to pass RTS options e.g., -opti+RTS -opti-
A64m, or to enable verbosity with -opti-v to see what messages are being exchanged by
GHC and the interpreter.
So, for example, to force an -Ewurble option to the assembler, you would tell the driver -
opta-Ewurble (the dash before the E is required).
GHC is itself a Haskell program, so if you need to pass options directly to GHC’s runtime
system you can enclose them in +RTS ... -RTS (see Running a compiled program (page 155)).
CPP
Since 6.8.1
The CPP (page 213) language extension enables the C pre-processor. This can be turned
into a command-line flag by prefixing it with -X; For example:
The CPP (page 213) language extension can also be enabled using the LANGUAGE
(page 518) pragma; For example:
-cpp
The C pre-processor cpp is run over your Haskell code if the -cpp option or -XCPP exten-
sion are given. Unless you are building a large system with significant doses of condi-
tional compilation, you really shouldn’t need it.
-D⟨symbol⟩[=⟨value⟩]
Define macro ⟨symbol⟩ in the usual way. When no value is given, the value is taken to be
1. For instance, -DUSE_MYLIB is equivalent to -DUSE_MYLIB=1.
Note: -D⟨symbol⟩[=⟨value⟩] (page 213) does not affect -D macros passed to the
C compiler when compiling an unregisterised build! In this case use the -optc-Dfoo
hack… (see Forcing options to a particular phase (page 212)).
-U⟨symbol⟩
Undefine macro ⟨symbol⟩ in the usual way.
-I⟨dir⟩
Specify a directory in which to look for #include files, in the usual C way.
The GHC driver pre-defines several macros when processing Haskell source code (.hs or .lhs
files).
The symbols defined by GHC are listed below. To check which symbols are defined by your
local GHC installation, the following trick is useful:
Note: The comparable symbols for other systems are: __HUGS__ for Hugs, __NHC__ for
nhc98, and __HBC__ for hbc).
NB. This macro is set when pre-processing both Haskell source and C source, including
the C source generated from a Haskell module (i.e. .hs, .lhs, .c and .hc files).
__GLASGOW_HASKELL_FULL_VERSION__
__GLASGOW_HASKELL_PATCHLEVEL1__; __GLASGOW_HASKELL_PATCHLEVEL2__ These macros
are available starting with GHC 7.10.1.
For three-part GHC version numbers x.y.z, the value of __GLAS-
GOW_HASKELL_PATCHLEVEL1__ is the integer ⟨z⟩.
For four-part GHC version numbers x.y.z.z', the value of __GLAS-
GOW_HASKELL_PATCHLEVEL1__ is the integer ⟨z⟩ while the value of __GLAS-
GOW_HASKELL_PATCHLEVEL2__ is set to the integer ⟨z’⟩.
These macros are provided for allowing finer granularity than is provided by __GLAS-
GOW_HASKELL__. Usually, this should not be necessary as it’s expected for most APIs to
remain stable between patchlevel releases, but occasionally internal API changes are
necessary to fix bugs. Also conditional compilation on the patchlevel can be useful for
working around bugs in older releases.
Tip: These macros are set when pre-processing both Haskell source and C source,
including the C source generated from a Haskell module (i.e. .hs, .lhs, .c and .hc
files).
#if defined(MIN_VERSION_GLASGOW_HASKELL)
#if MIN_VERSION_GLASGOW_HASKELL(7,10,2,0)
/* code that applies only to GHC 7.10.2 or later */
#endif
#endif
Tip: This macro is set when pre-processing both Haskell source and C source, including
the C source generated from a Haskell module (i.e. .hs, .lhs, .c and .hc files).
__GLASGOW_HASKELL_TH__ This is set to 1 when the compiler supports Template Haskell, and
to 0 when not. The latter is the case for a stage-1 compiler during bootstrapping, or on
architectures where the interpreter is not available.
__GLASGOW_HASKELL_LLVM__ Only defined when -fllvm is specified. When GHC is using
version x.y.z of LLVM, the value of __GLASGOW_HASKELL_LLVM__ is the integer ⟨xyy⟩ (if
⟨y⟩ is a single digit, then a leading zero is added, so for example when using version 3.7
of LLVM, __GLASGOW_HASKELL_LLVM__==307).
__PARALLEL_HASKELL__ Only defined when -parallel is in use! This symbol is defined when
pre-processing Haskell (input) and pre-processing C (GHC output).
os_HOST_OS=1 This define allows conditional compilation based on the Operating System,
where⟨os⟩ is the name of the current Operating System (eg. linux, mingw32 for Win-
dows, solaris, etc.).
arch_HOST_ARCH=1 This define allows conditional compilation based on the host architecture,
where⟨arch⟩ is the name of the current architecture (eg. i386, x86_64, powerpc, sparc,
etc.).
VERSION_pkgname This macro is available starting GHC 8.0. It is defined for every exposed
package. This macro expands to a string recording the version of pkgname that is exposed
for module import. It is identical in behavior to the VERSION_pkgname macros that Cabal
defines.
MIN_VERSION_pkgname(x,y,z) This macro is available starting GHC 8.0. It is defined for
every exposed package. This macro is provided for convenience to write CPP condi-
tionals testing if a package version is x.y.z or later. It is identical in behavior to the
MIN_VERSION_pkgname macros that Cabal defines.
A small word of warning: -cpp (page 213) is not friendly to “string gaps”. In other words,
strings such as the following:
strmod = "\
\ p \
\ "
don’t work with -cpp (page 213); /usr/bin/cpp elides the backslash-newline pairs.
However, it appears that if you add a space at the end of the line, then cpp (at least GNU cpp
and possibly other cpps) leaves the backslash-space pairs alone and the string gap works as
expected.
-F
A custom pre-processor is run over your Haskell source file only if the -F option is given.
Running a custom pre-processor at compile-time is in some settings appropriate and
useful. The -F option lets you run a pre-processor as part of the overall GHC compilation
pipeline, which has the advantage over running a Haskell pre-processor separately in
that it works in interpreted mode and you can continue to take reap the benefits of
GHC’s recompilation checker.
The pre-processor is run just before the Haskell compiler proper processes the Haskell
input, but after the literate markup has been stripped away and (possibly) the C pre-
processor has washed the Haskell input.
Use -pgmF ⟨cmd⟩ (page 211) to select the program to use as the preprocessor. When
invoked, the ⟨cmd⟩ pre-processor is given at least three arguments on its command-line:
the first argument is the name of the original source file, the second is the name of the
file holding the input, and the third is the name of the file where ⟨cmd⟩ should write its
output to.
Additional arguments to the pre-processor can be passed in using the -optF ⟨option⟩
(page 212) option. These are fed to ⟨cmd⟩ on the command line after the three standard
input and output arguments.
An example of a pre-processor is to convert your source files to the input encoding that
GHC expects, i.e. create a script [Link] containing the lines:
#!/bin/sh
( echo "{-# LINE 1 \"$2\" #-}" ; iconv -f l1 -t utf-8 $2 ) > $3
and pass -F -pgmF [Link] to GHC. The -f l1 option tells iconv to convert your
Latin-1 file, supplied in argument $2, while the “-t utf-8” options tell iconv to return a
UTF-8 encoded file. The result is redirected into argument $3. The echo "{-# LINE 1
\"$2\" #-}" just makes sure that your error positions are reported as in the original
source file.
-fasm
Use GHC’s native code generator (page 209) rather than compiling via LLVM. -fasm is
the default.
-fllvm
Compile via LLVM (page 209) instead of using the native code generator. This will gen-
erally take slightly longer than the native code generator to compile. Produced code is
generally the same speed or faster than the other two code generators. Compiling via
LLVM requires LLVM’s opt and llc executables to be in PATH.
Note: Note that this GHC release expects an LLVM version in the @LlvmVersion@
release series.
-fno-code
Omit code generation (and all later phases) altogether. This is useful if you’re only inter-
ested in type checking code.
-fwrite-interface
Always write interface files. GHC will normally write interface files automatically, but
this flag is useful with -fno-code (page 216), which normally suppresses generation of
interface files. This is useful if you want to type check over multiple runs of GHC without
compiling dependencies.
-fobject-code
Generate object code. This is the default outside of GHCi, and can be used with GHCi to
cause object code to be generated in preference to bytecode.
-fbyte-code
Generate byte-code instead of object-code. This is the default in GHCi. Byte-code can
currently only be used in the interactive interpreter, not saved to disk. This option is
only useful for reversing the effect of -fobject-code (page 216).
-fPIC
Generate position-independent code (code that can be put into shared libraries). This
currently works on Linux x86 and x86-64. On Windows, position-independent code is
never used so the flag is a no-op on that platform.
-fexternal-dynamic-refs
When generating code, assume that entities imported from a different module might be
dynamically linked. This flag is enabled automatically by -dynamic (page 218).
-fPIE
Generate code in such a way to be linkable into a position-independent executable This
currently works on Linux x86 and x86-64. On Windows, position-independent code is
never used so the flag is a no-op on that platform. To link the final executable use -pie
(page 222).
-dynamic
Build code for dynamic linking. This can reduce code size tremendously, but may slow-
down cross-module calls of non-inlined functions. There can be some complications com-
bining -shared (page 218) with this flag relating to linking in the RTS under Linux. See
#10352.
Note that using this option when linking causes GHC to link against shared libraries.
-dynamic-too
Generates both dynamic and static object files in a single run of GHC. This option is
functionally equivalent to running GHC twice, the second time adding -dynamic -osuf
dyn_o -hisuf dyn_hi.
Although it is equivalent to running GHC twice, using -dynamic-too is more efficient,
because the earlier phases of the compiler up to code generation are performed just
once.
When using -dynamic-too, the options -dyno, -dynosuf, and -dynhisuf are the coun-
terparts of -o, -osuf, and -hisuf respectively, but applying to the dynamic compilation.
GHC has to link your code with various libraries, possibly including: user-supplied, GHC-
supplied, and system-supplied (-lm math library, for example).
-l ⟨lib⟩
Link in the ⟨lib⟩ library. On Unix systems, this will be in a file called liblib.a or
[Link] which resides somewhere on the library directories path.
Because of the sad state of most UNIX linkers, the order of such options does matter.
If library ⟨foo⟩ requires library ⟨bar⟩, then in general -l ⟨foo⟩ should come before -l
⟨bar⟩ on the command line.
There’s one other gotcha to bear in mind when using external libraries: if the library con-
tains a main() function, then this will be a link conflict with GHC’s own main() function
(eg. libf2c and libl have their own main()s).
You can use an external main function if you initialize the RTS manually and pass -no-
hs-main. See also Using your own main() (page 485).
-c
Omits the link step. This option can be used with --make (page 76) to avoid the automatic
linking that takes place if the program contains a Main module.
-package ⟨name⟩
If you are using a Haskell “package” (see Packages (page 193)), don’t forget to add the
relevant -package option when linking the program too: it will cause the appropriate
libraries to be linked in with the program. Forgetting the -package option will likely
result in several pages of link errors.
-framework ⟨name⟩
On Darwin/OS X/iOS only, link in the framework ⟨name⟩. This option corresponds to the
-framework option for Apple’s Linker. Please note that frameworks and packages are two
different things - frameworks don’t contain any Haskell code. Rather, they are Apple’s
way of packaging shared libraries. To link to Apple’s “Carbon” API, for example, you’d
use -framework Carbon.
-staticlib
Implies -flink-rts (page 219)
Link all passed files into a static library suitable for linking. To control the name, use
the -o ⟨file⟩ (page 176) option as usual. The default name is liba.a.
-L ⟨dir⟩
Where to find user-supplied libraries… Prepend the directory ⟨dir⟩ to the library directo-
ries path.
-fuse-rpaths
This flag is enabled by default and will set the rpath of the linked object to the library
directories of dependent packages.
When building binaries to distribute it can be useful to pass your own linker options to
control the rpath and disable the automatic injection of rpath entries by disabling this
flag.
-framework-path ⟨dir⟩
On Darwin/OS X/iOS only, prepend the directory ⟨dir⟩ to the framework directories path.
This option corresponds to the -F option for Apple’s Linker (-F already means something
else for GHC).
-split-sections
Place each generated function or data item into its own section in the output file if the
target supports arbitrary sections. The name of the function or the name of the data
item determines the section’s name in the output file.
When linking, the linker can automatically remove all unreferenced sections and thus
produce smaller executables.
-static
Tell the linker to avoid shared Haskell libraries, if possible. This is the default.
-dynamic
This flag tells GHC to link against shared Haskell libraries. This flag only affects the
selection of dependent libraries, not the form of the current target (see -shared). See
Using shared libraries (page 223) on how to create them.
Note that this option also has an effect on code generation (see above).
-shared
Instead of creating an executable, GHC produces a shared object with this linker flag.
Depending on the operating system target, this might be an ELF DSO, a Windows DLL,
or a Mac OS dylib. GHC hides the operating system details beneath this uniform flag.
The flags -dynamic (page 218) and -static (page 218) control whether the resulting
shared object links statically or dynamically to Haskell package libraries given as -
package ⟨pkg⟩ (page 194) option. Non-Haskell libraries are linked as gcc would reg-
ularly link it on your system, e.g. on most ELF system the linker uses the dynamic
libraries when found.
Object files linked into shared objects must be compiled with -fPIC (page 217), see
Options affecting code generation (page 216)
When creating shared objects for Haskell packages, the shared object must be named
properly, so that GHC recognizes the shared object when linking against this package.
See shared object name mangling (page 204) for details.
-dynload
This flag selects one of a number of modes for finding shared libraries at runtime. See
Finding shared libraries at runtime (page 225) for a description of each mode.
-flink-rts
When linking shared libraries (-shared (page 218)) GHC does not automatically link
the RTS. This is to allow choosing the RTS flavour (-threaded (page 220), -eventlog
(page 220), etc) when linking an executable. However when the shared library is the
intended product it is useful to be able to reverse this default. See Shared libraries that
export a C API (page 224) for an usage example.
When linking a static library (-staticlib (page 218)) GHC links the RTS automatically,
you can reverse this behaviour by reversing this flag: -fno-link-rts.
-main-is ⟨thing⟩
The normal rule in Haskell is that your program must supply a main function in module
Main. When testing, it is often convenient to change which function is the “main” one,
and the -main-is flag allows you to do so. The ⟨thing⟩ can be one of:
•A lower-case identifier foo. GHC assumes that the main function is [Link].
•A module name A. GHC assumes that the main function is [Link].
•A qualified name [Link]. GHC assumes that the main function is [Link].
Strictly speaking, -main-is is not a link-phase flag at all; it has no effect on the link
step. The flag must be specified when compiling the module containing the specified
main function (e.g. module A in the latter two items above). It has no effect for other
modules, and hence can safely be given to ghc --make. However, if all the modules are
otherwise up to date, you may need to force recompilation both of the module where the
new “main” is, and of the module where the “main” function used to be; ghc is not clever
enough to figure out that they both need recompiling. You can force recompilation by
removing the object file, or by using the -fforce-recomp (page 180) flag.
-no-hs-main
In the event you want to include ghc-compiled code as part of another (non-Haskell)
program, the RTS will not be supplying its definition of main() at link-time, you will
have to. To signal that to the compiler when linking, use -no-hs-main. See also Using
your own main() (page 485).
Notice that since the command-line passed to the linker is rather involved, you probably
want to use ghc to do the final link of your ‘mixed-language’ application. This is not a
requirement though, just try linking once with -v (page 79) on to see what options the
driver passes through to the linker.
The -no-hs-main flag can also be used to persuade the compiler to do the link step in
--make (page 76) mode when there is no Haskell Main module present (normally the
compiler will not attempt linking when there is no Main).
The flags -rtsopts[=⟨none|some|all|ignore|ignoreAll⟩] (page 220) and -with-
rtsopts=⟨opts⟩ (page 221) have no effect when used with -no-hs-main (page 219),
because they are implemented by changing the definition of main that GHC
generates. See Using your own main() (page 485) for how to get the ef-
fect of -rtsopts[=⟨none|some|all|ignore|ignoreAll⟩] (page 220) and -with-
rtsopts=⟨opts⟩ (page 221) when using your own main.
-debug
Link the program with a debugging version of the runtime system. The debugging run-
time turns on numerous assertions and sanity checks, and provides extra options for
producing debugging output at runtime (run the program with +RTS -? to see a list).
-threaded
Link the program with the “threaded” version of the runtime system. The threaded
runtime system is so-called because it manages multiple OS threads, as opposed to the
default runtime system which is purely single-threaded.
Note that you do not need -threaded in order to use concurrency; the single-threaded
runtime supports concurrency between Haskell threads just fine.
The threaded runtime system provides the following benefits:
•It enables the -N ⟨x⟩ (page 118) RTS option to be used, which allows threads to run
in parallel on a multiprocessor or multicore machine. See Using SMP parallelism
(page 118).
•If a thread makes a foreign call (and the call is not marked unsafe), then other
Haskell threads in the program will continue to run while the foreign call is in
progress. Additionally, foreign exported Haskell functions may be called from
multiple OS threads simultaneously. See Multi-threading and the FFI (page 489).
-eventlog
Link the program with the “eventlog” version of the runtime system. A program linked
in this way can generate a runtime trace of events (such as thread start/stop) to a binary
file [Link], which can then be interpreted later by various tools. See Tracing
(page 170) for more information.
-eventlog (page 220) can be used with -threaded (page 220). It is implied by -debug
(page 220).
-rtsopts[=⟨none|some|all|ignore|ignoreAll⟩]
Default some
This option affects the processing of RTS control options given either on the command
line or via the GHCRTS (page 157) environment variable. There are three possibilities:
-rtsopts=none Disable all processing of RTS options. If +RTS appears anywhere on the
command line, then the program will abort with an error message. If the GHCRTS
environment variable is set, then the program will emit a warning message, GHCRTS
will be ignored, and the program will run as normal.
-rtsopts=ignore Disables all processing of RTS options. Unlike none this treats all RTS
flags appearing on the command line the same way as regular arguments. (Passing
them on to your program as arguments). GHCRTS options will be processed normally.
-rtsopts=ignoreAll Same as ignore but also ignores GHCRTS.
-rtsopts=some [this is the default setting] Enable only the “safe” RTS options: (Cur-
rently only -? and --info.) Any other RTS options on the command line or in the
GHCRTS environment variable causes the program with to abort with an error mes-
sage.
-rtsopts=all or just -rtsopts Enable all RTS option processing, both on the com-
mand line and through the GHCRTS environment variable.
In GHC 6.12.3 and earlier, the default was to process all RTS options. However, since
RTS options can be used to write logging data to arbitrary files under the security context
of the running program, there is a potential security problem. For this reason, GHC 7.0.1
and later default to -rtsopts=some.
Note that -rtsopts has no effect when used with -no-hs-main (page 219); see Using
your own main() (page 485) for details.
-rtsopts does not affect RTS options passed via -with-rtsopts; those are used regard-
less of -rtsopts.
-with-rtsopts=⟨opts⟩
This option allows you to set the default RTS options at link-time. For example, -with-
rtsopts="-H128m" sets the default heap size to 128MB. This will always be the default
heap size for this program, unless the user overrides it. (Depending on the setting of the
-rtsopts option, the user might not have the ability to change RTS options at run-time,
in which case -with-rtsopts would be the only way to set them.)
Use the runtime flag --info (page 173) on the executable program to see the options
set with -with-rtsopts.
Note that -with-rtsopts has no effect when used with -no-hs-main; see Using your
own main() (page 485) for details.
-no-rtsopts-suggestions
This option disables RTS suggestions about linking with -
rtsopts[=⟨none|some|all|ignore|ignoreAll⟩] (page 220) when they are not
available. These suggestions would be unhelpful if the users have installed Haskell
programs through their package managers. With this option enabled, these suggestions
will not appear. It is recommended for people distributing binaries to build with either
-rtsopts or -no-rtsopts-suggestions.
-fno-gen-manifest
On Windows, GHC normally generates a manifest file when linking a binary. The manifest
is placed in the file [Link]` where ⟨[Link]⟩ is the name of the executable.
The manifest file currently serves just one purpose: it disables the “installer detection”
in Windows Vista that attempts to elevate privileges for executables with certain names
(e.g. names containing “install”, “setup” or “patch”). Without the manifest file to turn
off installer detection, attempting to run an executable that Windows deems to be an
installer will return a permission error code to the invoker. Depending on the invoker,
the result might be a dialog box asking the user for elevated permissions, or it might
simply be a permission denied error.
Installer detection can be also turned off globally for the system using the security con-
trol panel, but GHC by default generates binaries that don’t depend on the user having
disabled installer detection.
The -fno-gen-manifest disables generation of the manifest file. One reason to do this
would be if you had a manifest file of your own, for example.
In the future, GHC might use the manifest file for more things, such as supplying the
location of dependent DLLs.
-fno-gen-manifest (page 221) also implies -fno-embed-manifest (page 222), see be-
low.
-fno-embed-manifest
The manifest file that GHC generates when linking a binary on Windows is also embedded
in the executable itself, by default. This means that the binary can be distributed without
having to supply the manifest file too. The embedding is done by running windres; to
see exactly what GHC does to embed the manifest, use the -v (page 79) flag. A GHC
installation comes with its own copy of windres for this reason.
See also -pgmwindres ⟨cmd⟩ (page 211) (Replacing the program for one or more phases
(page 211)) and -optwindres ⟨option⟩ (page 212) (Forcing options to a particular
phase (page 212)).
-fno-shared-implib
DLLs on Windows are typically linked to by linking to a corresponding .lib or .dll.a
— the so-called import library. GHC will typically generate such a file for every DLL you
create by compiling in -shared (page 218) mode. However, sometimes you don’t want
to pay the disk-space cost of creating this import library, which can be substantial — it
might require as much space as the code itself, as Haskell DLLs tend to export lots of
symbols.
As long as you are happy to only be able to link to the DLL using GetProcAddress and
friends, you can supply the -fno-shared-implib (page 222) flag to disable the creation
of the import library entirely.
-dylib-install-name ⟨path⟩
On Darwin/OS X, dynamic libraries are stamped at build time with an “install name”,
which is the ultimate install path of the library file. Any libraries or executables that
subsequently link against it will pick up that path as their runtime search location for
it. By default, ghc sets the install name to the location where the library is built. This
option allows you to override it with the specified file path. (It passes -install_name to
Apple’s linker.) Ignored on other platforms.
-rdynamic
This instructs the linker to add all symbols, not only used ones, to the dynamic symbol
table. Currently Linux and Windows/MinGW32 only. This is equivalent to using -optl
-rdynamic on Linux, and -optl -export-all-symbols on Windows.
-fwhole-archive-hs-libs
When linking a binary executable, this inserts the flag -Wl,--whole-archive before any
-l flags for Haskell libraries, and -Wl,--no-whole-archive afterwards (on OS X, the flag
is -Wl,-all_load, there is no equivalent for -Wl,--no-whole-archive). This flag also
disables the use of -Wl,--gc-sections (-Wl,-dead_strip on OS X).
This is for specialist applications that may require symbols defined in these Haskell li-
braries at runtime even though they aren’t referenced by any other code linked into
the executable. If you’re using -fwhole-archive-hs-libs, you probably also want -
rdynamic.
-pie
Since 8.2.2
This instructs the linker to produce a position-independent executable. This flag is only
valid while producing executables and all object code being linked must have been pro-
duced with -fPIE (page 217).
Position independent executables are required by some platforms as they enable address-
space layout randomization (ASLR), a common security measure. They can also be useful
as they can be dynamically loaded and used as shared libraries by other executables.
Position independent executables should be dynamically-linked (e.g. built with -dynamic
(page 218) and only loaded into other dynamically-linked executables to ensure that only
one libHSrts is present if loaded into the address space of another Haskell process.
Also, you may need to use the -rdynamic (page 222) flag to ensure that that symbols are
not dropped from your PIE objects.
-fkeep-cafs
Since 8.8.1
Disables the RTS’s normal behaviour of garbage-collecting CAFs (Constant Applicative
Forms, in other words top-level expressions). This option is useful for specialised appli-
cations that do runtime dynamic linking, where code dynamically linked in the future
might require the value of a CAF that would otherwise be garbage-collected.
On some platforms GHC supports building Haskell code into shared libraries. Shared libraries
are also sometimes known as dynamic libraries, in particular on Windows they are referred
to as dynamic link libraries (DLLs).
Shared libraries allow a single instance of some pre-compiled code to be shared between sev-
eral programs. In contrast, with static linking the code is copied into each program. Using
shared libraries can thus save disk space. They also allow a single copy of code to be shared
in memory between several programs that use it. Shared libraries are often used as a way of
structuring large projects, especially where different parts are written in different program-
ming languages. Shared libraries are also commonly used as a plugin mechanism by various
applications. This is particularly common on Windows using COM.
In GHC version 6.12 building shared libraries is supported for Linux (on x86 and x86-64
architectures). GHC version 7.0 adds support on Windows (see Building and using Win32
DLLs (page 598)), FreeBSD and OpenBSD (x86 and x86-64), Solaris (x86) and Mac OS X (x86
and PowerPC).
Building and using shared libraries is slightly more complicated than building and using static
libraries. When using Cabal much of the detail is hidden, just use --enable-shared when
configuring a package to build it into a shared library, or to link it against other packages built
as shared libraries. The additional complexity when building code is to distinguish whether
the code will be used in a shared library or will use shared library versions of other packages
it depends on. There is additional complexity when installing and distributing shared libraries
or programs that use shared libraries, to ensure that all shared libraries that are required at
runtime are present in suitable locations.
To build a simple program and have it use shared libraries for the runtime system and the
base libraries use the -dynamic (page 218) flag:
This has two effects. The first is to compile the code in such a way that it can be linked against
shared library versions of Haskell packages (such as base). The second is when linking, to
link against the shared versions of the packages’ libraries rather than the static versions.
Obviously this requires that the packages were built with shared libraries. On supported
platforms GHC comes with shared libraries for all the core packages, but if you install extra
packages (e.g. with Cabal) then they would also have to be built with shared libraries (--
enable-shared for Cabal).
You can build Haskell code into a shared library and make a package to be used by other
Haskell programs. The easiest way is using Cabal, simply configure the Cabal package with
the --enable-shared flag.
If you want to do the steps manually or are writing your own build system then there are
certain conventions that must be followed. Building a shared library that exports Haskell
code, to be used by other Haskell code is a bit more complicated than it is for one that exports
a C API and will be used by C code. If you get it wrong you will usually end up with linker
errors.
In particular Haskell shared libraries must be made into packages. You cannot freely assign
which modules go in which shared libraries. The Haskell shared libraries must match the
package boundaries. The reason for this is that GHC handles references to symbols within
the same shared library (or main executable binary) differently from references to symbols
between different shared libraries. GHC needs to know for each imported module if that
module lives locally in the same shared lib or in a separate shared lib. The way it does this is
by using packages. When using -dynamic (page 218), a module from a separate package is
assumed to come from a separate shared lib, while modules from the same package (or the
default “main” package) are assumed to be within the same shared lib (or main executable
binary).
Most of the conventions GHC expects when using packages are described in Building a pack-
age from Haskell source (page 204). In addition note that GHC expects the .hi files to use the
extension .dyn_hi. The other requirements are the same as for C libraries and are described
below, in particular the use of the flags -dynamic (page 218), -fPIC (page 217) and -shared
(page 218).
Building Haskell code into a shared library is a good way to include Haskell code in a larger
mixed-language project. While with static linking it is recommended to use GHC to perform
the final link step, with shared libraries a Haskell library can be treated just like any other
shared library. The linking can be done using the normal system C compiler or linker.
It is possible to load shared libraries generated by GHC in other programs not written in
Haskell, so they are suitable for using as plugins. Of course to construct a plugin you will
have to use the FFI to export C functions and follow the rules about initialising the RTS. See
Making a Haskell library that can be called from foreign code (page 487). In particular you
will probably want to export a C function from your shared library to initialise the plugin
before any Haskell functions are called.
To build Haskell modules that export a C API into a shared library use the -dynamic (page 218),
-fPIC (page 217) and -shared (page 218) flags:
As before, the -dynamic (page 218) flag specifies that this library links against the shared
library versions of the base package. -flink-rts (page 219) additionally links against the
shared library version of the rts package (linking against the rts package is not enabled
by default when building shared libraries). You may also omit -flink-rts and link the RTS
library into your final executable.
The -fPIC (page 217) flag is required for all code that will end up in a shared library. The
-shared (page 218) flag specifies to make a shared library rather than a program. To make
this clearer we can break this down into separate compilation and link steps:
In principle you can use -shared (page 218) without -dynamic (page 218) in the link step.
That means to statically link the runtime system and all of the base libraries into your new
shared library. This would make a very big, but standalone shared library. On most platforms
however that would require all the static libraries to have been built with -fPIC (page 217) so
that the code is suitable to include into a shared library and we do not do that at the moment.
Warning: If your shared library exports a Haskell API then you cannot directly link it into
another Haskell program and use that Haskell API. You will get linker errors. You must
instead make it into a package as described in the section above.
The primary difficulty with managing shared libraries is arranging things such that programs
can find the libraries they need at runtime. The details of how this works varies between
platforms, in particular the three major systems: Unix ELF platforms, Windows and Mac OS
X.
Unix
On Unix there are two mechanisms. Shared libraries can be installed into standard locations
that the dynamic linker knows about. For example /usr/lib or /usr/local/lib on most
systems. The other mechanism is to use a “runtime path” or “rpath” embedded into programs
and libraries themselves. These paths can either be absolute paths or on at least Linux and
Solaris they can be paths relative to the program or library itself. In principle this makes it
possible to construct fully relocatable sets of programs and libraries.
GHC has a -dynload linking flag to select the method that is used to find shared libraries at
runtime. There are currently two modes:
sysdep A system-dependent mode. This is also the default mode. On Unix ELF systems this
embeds RPATH/RUNPATH entries into the shared library or executable. In particular it uses
absolute paths to where the shared libraries for the rts and each package can be found.
This means the program can immediately be run and it will be able to find the libraries
it needs. However it may not be suitable for deployment if the libraries are installed in
a different location on another machine.
deploy This does not embed any runtime paths. It relies on the shared libraries being avail-
able in a standard location or in a directory given by the LD_LIBRARY_PATH environment
variable.
To use relative paths for dependent libraries on Linux and Solaris you can pass a suitable
-rpath flag to the linker:
This assumes that the library [Link] is in the current directory and will be able to be
found in the same directory as the executable main once the program is deployed. Simi-
larly it would be possible to use a subdirectory relative to the executable e.g. -optl-Wl,-
rpath,'$ORIGIN/lib'.
This relative path technique can be used with either of the two -dynload modes, though it
makes most sense with the deploy mode. The difference is that with the deploy mode, the
above example will end up with an ELF RUNPATH of just $ORIGIN while with the sysdep mode
the RUNPATH will be $ORIGIN followed by all the library directories of all the packages that the
program depends on (e.g. base and rts packages etc.) which are typically absolute paths.
The unix tool readelf --dynamic is handy for inspecting the RPATH/RUNPATH entries in ELF
shared libraries and executables.
On most UNIX platforms it is also possible to build executables that can be dlopen‘d like
shared libraries using the -pie (page 222) flag during linking.
Mac OS X
Dump flags
-ddump-to-file
Causes the output from all of the flags listed below to be dumped to a file. The file name
depends upon the output produced; for instance, output from -ddump-simpl (page 230)
will end up in [Link]-simpl.
-ddump-file-prefix=⟨str⟩
Set the prefix of the filenames used for debugging output. For example, -ddump-file-
prefix=Foo will cause the output from -ddump-simpl (page 230) to be dumped to
[Link]-simpl.
-ddump-json
Dump error messages as JSON documents. This is intended to be consumed by external
tooling. A good way to use it is in conjunction with -ddump-to-file (page 227).
-dshow-passes
Print out each pass name, its runtime and heap allocations as it happens. Note that this
may come at a slight performance cost as the compiler will be a bit more eager in forcing
pass results to more accurately account for their costs.
Two types of messages are produced: Those beginning with *** do denote the beginning
of a compilation phase whereas those starting with !!! mark the end of a pass and are
accompanied by allocation and runtime statistics.
-dfaststring-stats
Show statistics on the usage of fast strings by the compiler.
-dppr-debug
Debugging output is in one of several “styles.” Take the printing of types, for example. In
the “user” style (the default), the compiler’s internal ideas about types are presented in
Haskell source-level syntax, insofar as possible. In the “debug” style (which is the default
for debugging output), the types are printed in with explicit foralls, and variables have
their unique-id attached (so you can check for things that look the same but aren’t). This
flag makes debugging output appear in the more verbose debug style.
-ddump-timings
Show allocation and runtime statistics for various stages of compilation. Allocations are
measured in bytes. Timings are measured in milliseconds.
GHC is a large program consisting of a number of stages. You can tell GHC to dump infor-
mation from various stages of compilation using the -ddump-⟨pass⟩ flags listed below. Note
that some of these tend to produce a lot of output. You can prevent them from clogging up
your standard output by passing -ddump-to-file (page 227).
Front-end
These flags dump various information from GHC’s frontend. This includes the parser and
interface file reader.
-ddump-parsed
Dump parser output
-ddump-parsed-ast
Dump parser output as a syntax tree
-ddump-if-trace
Make the interface loader be real chatty about what it is up to.
These flags dump various information from GHC’s typechecker and renamer.
-ddump-tc-trace
Make the type checker be real chatty about what it is up to.
-ddump-rn-trace
Make the renamer be real chatty about what it is up to.
-ddump-ec-trace
Make the pattern match exhaustiveness checker be real chatty about what it is up to.
-ddump-rn-stats
Print out summary of what kind of information the renamer had to bring in.
-ddump-rn
Dump renamer output
-ddump-rn-ast
Dump renamer output as a syntax tree
-ddump-tc
Dump typechecker output. Note that this hides a great deal of detail by default; you
might consider using this with -fprint-typechecker-elaboration (page 82).
-ddump-tc-ast
Dump typechecker output as a syntax tree
-ddump-hie
Dump the hie file syntax tree if we are generating extended interface files
-ddump-splices
Dump Template Haskell expressions that we splice in, and what Haskell code the expres-
sion evaluates to.
-dth-dec-file
Dump expansions of all top-level Template Haskell splices into [Link] for each
file [Link].
-ddump-types
Dump a type signature for each value defined at the top level of the module. The list is
sorted alphabetically. Using -dppr-debug (page 227) dumps a type signature for all the
imported and system-defined things as well; useful for debugging the compiler.
-ddump-deriv
Dump derived instances
These flags dump various phases of GHC’s Core-to-Core pipeline. This begins with the desug-
arer and includes the simplifier, worker-wrapper transformation, the rule engine, the spe-
cialiser, the strictness/occurrence analyser, and a common subexpression elimination pass.
-ddump-core-stats
Print a one-line summary of the size of the Core program at the end of the optimisation
pipeline.
-ddump-ds
-ddump-ds-preopt
Dump desugarer output. -ddump-ds (page 229) dumps the output after the very simple
optimiser has run (which discards a lot of clutter and hence is a sensible default. -ddump-
ds-preopt (page 229) shows the output after desugaring but before the very simple
optimiser.
-ddump-simpl-iterations
Show the output of each iteration of the simplifier (each run of the simplifier has a max-
imum number of iterations, normally 4).
-ddump-simpl-stats
Dump statistics about how many of each kind of transformation took place. If you add
-dppr-debug (page 227) you get more detailed information.
-dverbose-core2core
Show the output of the intermediate Core-to-Core pass. (lots of output!) So: when we’re
really desperate:
-ddump-spec
Dump output of specialisation pass
-ddump-rules
Dumps all rewrite rules specified in this module; see Controlling what’s going on in
rewrite rules (page 510).
-ddump-rule-firings
Dumps the names of all rules that fired in this module
-ddump-rule-rewrites
Dumps detailed information about all rules that fired in this module
-drule-check=⟨str⟩
This flag is useful for debugging why a rule you expect to be firing isn’t.
Rules are filtered by the user provided string, a rule is kept if a prefix of its name matches
the string. The pass then checks whether any of these rules could apply to the program
but which didn’t fire for some reason. For example, specifying -drule-check=SPEC will
check whether there are any applications which might be subject to a rule created by
specialisation.
-dinline-check=⟨str⟩
This flag is useful for debugging why a definition is not inlined.
When a string is passed to this flag we report information about all functions whose name
shares a prefix with the string.
For example, if you are inspecting the core of your program and you observe that foo
is not being inlined. You can pass -dinline-check foo and you will see a report about
why foo is not inlined.
-ddump-simpl
Dump simplifier output (Core-to-Core passes)
-ddump-inlinings
Dumps inlinings performed by the simplifier.
-ddump-verbose-inlinings
Dumps all inlinings considered by the simplifier, even those ultimately not performed.
This output includes various information that the simplifier uses to determine whether
the inlining is beneficial.
-ddump-stranal
Dump strictness analyser output
-ddump-str-signatures
Dump strictness signatures
-ddump-cpranal
Dump Constructed Product Result analysis output
-ddump-cpr-signatures
Dump Constructed Product Result signatures
-ddump-cse
Dump common subexpression elimination (CSE) pass output
-ddump-worker-wrapper
Dump worker/wrapper split output
-ddump-occur-anal
Dump “occurrence analysis” output
-ddump-prep
Dump output of Core preparation pass
STG representation
C-\- representation
-ddump-cmm-verbose-by-proc
Dump output from main C-\- pipeline stages. In case of .cmm compilation this also dumps
the result of file parsing. Not included are passes run by the chosen backend. Currently
only the NCG backends runs additional passes ( -ddump-opt-cmm (page 232) ).
Cmm dumps don’t include unreachable blocks since we print blocks in reverse post-
order.
-ddump-cmm-verbose
If used in conjunction with -ddump-to-file (page 227), writes dump output from main
C-\- pipeline stages to files (each stage per file).
-ddump-cmm-from-stg
Dump the result of STG-to-C-\- conversion
-ddump-cmm-raw
Dump the “raw” C-\-.
-ddump-cmm-cfg
Dump the results of the C-\- control flow optimisation pass.
-ddump-cmm-cbe
Dump the results of the C-\- Common Block Elimination (CBE) pass.
-ddump-cmm-switch
Dump the results of the C-\- switch lowering pass.
-ddump-cmm-proc
Dump the results of the C-\- proc-point analysis pass.
-ddump-cmm-sp
Dump the results of the C-\- stack layout pass.
-ddump-cmm-sink
Dump the results of the C-\- sinking pass.
-ddump-cmm-caf
Dump the results of the C-\- CAF analysis pass.
-ddump-cmm-procmap
Dump the results of the C-\- proc-point map pass.
-ddump-cmm-split
Dump the results of the C-\- proc-point splitting pass.
-ddump-cmm-info
Dump the results of the C-\- info table augmentation pass.
-ddump-cmm-cps
Dump the results of the CPS pass.
-ddump-cmm
Dump the result of the C-\- pipeline processing
-ddump-cfg-weights
Dumps the CFG with weights used by the new block layout code. Each CFG is dumped
in dot format graph making it easy to visualize them.
-ddump-llvm
These flags dump various stages of the native code generator’s (page 209) pipeline, which
starts with C-\- and produces native assembler.
-ddump-cmm-opt
Dump the results of C-\- to C-\- optimising passes performed by the NCG.
-ddump-opt-cmm
Alias for -ddump-cmm-opt (page 232)
-ddump-asm-native
Dump the initial assembler output produced from C-\-.
-ddump-asm-liveness
Dump the result of the register liveness pass.
-ddump-asm-regalloc
Dump the result of the register allocation pass.
-ddump-asm-regalloc-stages
Dump the build/spill stages of the -fregs-graph (page 111) register allocator.
-ddump-asm-stats
Dump statistics from the register allocator.
-ddump-asm-expanded
Dump the result of the synthetic instruction expansion pass.
-ddump-asm
Dump the final assembly produced by the native code generator.
-dppr-user-length
In error messages, expressions are printed to a certain “depth”, with subexpressions
beyond the depth replaced by ellipses. This flag sets the depth. Its default value is 5.
-dppr-cols=⟨n⟩
Set the width of debugging output. Use this if your code is wrapping too much. For
example: -dppr-cols=200.
-dppr-case-as-let
Print single alternative case expressions as though they were strict let expressions. This
is helpful when your code does a lot of unboxing.
-dhex-word-literals
Print values of type Word# and Word64# (but not values of type Int# and Int64#) in hex-
adecimal instead of decimal. The hexadecimal is zero-padded to make the length of the
representation a power of two. For example: 0x0A0A##, 0x000FFFFF##, 0xC##. This
flag may be helpful when you are producing a bit pattern that to expect to work correctly
on a 32-bit or a 64-bit architecture. Dumping hexadecimal literals after optimizations
and constant folding makes it easier to confirm that the generated bit pattern is correct.
-dno-debug-output
Suppress any unsolicited debugging output. When GHC has been built with the DEBUG
option it occasionally emits debug output of interest to developers. The extra output can
confuse the testing framework and cause bogus test failures, so this flag is provided to
turn it off.
Core dumps contain a large amount of information. Depending on what you are doing, not all
of it will be useful. Use these flags to suppress the parts that you are not interested in.
-dsuppress-all
Suppress everything that can be suppressed, except for unique ids as this often makes
the printout ambiguous. If you just want to see the overall structure of the code, then
start here.
-dsuppress-ticks
Suppress “ticks” in the pretty-printer output.
-dsuppress-uniques
Suppress the printing of uniques. This may make the printout ambiguous (e.g. unclear
where an occurrence of ‘x’ is bound), but it makes the output of two compiler runs have
many fewer gratuitous differences, so you can realistically apply diff. Once diff has
shown you where to look, you can try again without -dsuppress-uniques (page 233)
-dsuppress-idinfo
Suppress extended information about identifiers where they are bound. This includes
strictness information and inliner templates. Using this flag can cut the size of the core
dump in half, due to the lack of inliner templates
-dsuppress-unfoldings
Suppress the printing of the stable unfolding of a variable at its binding site.
-dsuppress-module-prefixes
Suppress the printing of module qualification prefixes. This is the [Link] in
[Link].
-dsuppress-timestamps
Suppress the printing of timestamps. This makes it easier to diff dumps.
-dsuppress-type-signatures
Suppress the printing of type signatures.
-dsuppress-type-applications
Suppress the printing of type applications.
-dsuppress-coercions
Suppress the printing of type coercions.
-dsuppress-var-kinds
Suppress the printing of variable kinds
-dsuppress-stg-free-vars
Suppress the printing of closure free variable lists in STG output
-dcore-lint
Turn on heavyweight intra-pass sanity-checking within GHC, at Core level. (It checks
GHC’s sanity, not yours.)
-dlinear-core-lint
Turn on linearity checking in GHC. Currently, some optimizations in GHC might not pre-
serve linearity and they valid programs might fail Linear Core Lint. In the near future,
this option will be removed and folded into normal Core Lint.
-dstg-lint
Ditto for STG level.
-dcmm-lint
Ditto for C-\- level.
-fllvm-fill-undef-with-garbage
Instructs the LLVM code generator to fill dead STG registers with garbage instead of
undef in calls. This makes it easier to catch subtle code generator and runtime system
bugs (e.g. see #11487).
-falignment-sanitisation
Compile with alignment checks for all info table dereferences. This can be useful when
finding pointer tagging issues.
-fproc-alignment
Align functions to multiples of the given value. Only valid values are powers of two.
-fproc-alignment=64 can be used to limit alignment impact on performance as each
function will start at a cache line. However forcing larger alignments in general reduces
performance.
-fcatch-bottoms
GHC generates case expressions without a default alternative in some cases:
•When the demand analysis thinks that the scrutinee does not return (i.e. a bottoming
expression)
•When the scrutinee is a GADT and its type rules out some constructors, and others
constructors are already handled by the case expression.
With this flag GHC generates a default alternative with error in these cases. This is
helpful when debugging demand analysis or type checker bugs which can sometimes
manifest as segmentation faults.
-dinitial-unique=⟨s⟩
Start UniqSupply allocation from ⟨s⟩.
-dunique-increment=⟨i⟩
Set the increment for the generated Unique‘s to ⟨i⟩.
This is useful in combination with -dinitial-unique=⟨s⟩ (page 235) to test if the gen-
erated files depend on the order of Unique‘s.
Some interesting values:
•-dinitial-unique=0 -dunique-increment=1 - current sequential UniqSupply
•-dinitial-unique=16777215 -dunique-increment=-1 - UniqSupply that gener-
ates in decreasing order
•-dinitial-unique=1 -dunique-increment=PRIME - where PRIME big enough to
overflow often - nonsequential order
5.13.6 Other
-dno-typeable-binds
This avoid generating Typeable-related bindings for modules and types. This is useful
when debugging because it gives smaller modules and dumps, but the compiler will panic
if you try to use Typeable instances of things that you built with this flag.
SIX
LANGUAGE EXTENSIONS
6.1 Introduction
As with all known Haskell systems, GHC implements some extensions to the standard Haskell
language. They can all be enabled or disabled by command line flags or language pragmas.
By default GHC understands the most recent Haskell version it supports, plus a handful of
extensions.
Some of the extensions serve to give you access to the underlying facilities with which we
implement Haskell. Thus, you can get at the Raw Iron, if you are willing to write some non-
portable code at a more primitive level. You need not be “stuck” on performance because
of the implementation costs of Haskell’s “high-level” features—you can always code “under”
them. In an extreme case, you can write all your time-critical code in C, and then just glue it
together with Haskell!
237
GHC User’s Guide Documentation, Release 9.0.2
Extension Description
AllowAmbiguousTypes (page 433) Allow the user to write ambiguous types, and the type inferen
ApplicativeDo (page 246) Enable Applicative do-notation desugaring
Arrows (page 273) Enable arrow notation extension
BangPatterns (page 462) Enable bang patterns.
BinaryLiterals (page 419) Enable support for binary literals.
BlockArguments (page 265) Allow do blocks and other constructs as function arguments.
CApiFFI (page 483) Enable the CAPI calling convention.
ConstrainedClassMethods (page 402) Enable constrained class methods.
ConstraintKinds (page 425) Enable a kind of constraints.
CPP (page 213) Enable the C preprocessor.
CUSKs (page 322) Enable detection of complete user-supplied kind signatures.
DataKinds (page 315) Enable datatype promotion.
DatatypeContexts (page 283) Allow contexts on data types.
DefaultSignatures (page 402) Enable default signatures.
DeriveAnyClass (page 384) Enable deriving for any class.
DeriveDataTypeable (page 376) Enable deriving for the Data class. Implied by (deprecated) A
DeriveFoldable (page 373) Enable deriving for the Foldable class. Implied by DeriveTra
DeriveFunctor (page 370) Enable deriving for the Functor class. Implied by DeriveTrav
DeriveGeneric (page 512) Enable deriving for the Generic class.
DeriveLift (page 377) Enable deriving for the Lift class
DeriveTraversable (page 375) Enable deriving for the Traversable class. Implies DeriveFun
DerivingStrategies (page 386) Enables deriving strategies.
DerivingVia (page 388) Enable deriving instances via types of the same runtime rep
DisambiguateRecordFields (page 358) Enable record field disambiguation. Implied by RecordWildC
DuplicateRecordFields (page 359) Allow definition of record types with identically-named fields
EmptyCase (page 263) Allow empty case alternatives.
EmptyDataDecls (page 283) Allow definition of empty data types.
EmptyDataDeriving (page 367) Allow deriving instances of standard type classes for empty d
ExistentialQuantification (page 286) Enable liberalised type synonyms.
ExplicitForAll (page 431) Enable explicit universal quantification. Implied by ScopedTy
ExplicitNamespaces (page 282) Enable using the keyword type to specify the namespace of e
ExtendedDefaultRules (page 36) Use GHCi’s extended default rules in a normal module.
FlexibleContexts (page 400) Enable flexible contexts.
FlexibleInstances (page 409) Enable flexible instances. Implies TypeSynonymInstances (pa
ForeignFunctionInterface (page 478) Enable foreign function interface.
FunctionalDependencies (page 404) Enable functional dependencies. Implies MultiParamTypeCla
GADTs (page 296) Enable generalised algebraic data types. Implies GADTSyntax
GADTSyntax (page 290) Enable generalised algebraic data type syntax.
GeneralisedNewtypeDeriving (page 378) Enable newtype deriving.
GHCForeignImportPrim (page 482) Enable prim calling convention. Intended for internal use onl
Haskell2010 (page 237) Use the Haskell 2010 language variant.
Haskell98 (page 237) Use the Haskell 98 language variant.
HexFloatLiterals (page 419) Enable support for hexadecimal floating point literals (page 4
ImplicitParams (page 441) Enable Implicit Parameters.
ImplicitPrelude (page 259) Don’t implicitly import Prelude. Implied by RebindableSynt
ImportQualifiedPost (page 282) ImportQualifiedPost allows the syntax import M qualifie
ImpredicativeTypes (page 346) Enable impredicative types. Implies RankNTypes (page 342).
IncoherentInstances (page 414) Enable incoherent instances. Implies OverlappingInstances
InstanceSigs (page 418) Enable instance signatures.
InterruptibleFFI (page 482) Enable interruptible FFI.
Extension Description
KindSignatures (page 435) Enable kind signatures. Implied by TypeFamilies (page 298)
LambdaCase (page 262) Enable lambda-case expressions.
LexicalNegation (page 279) Use whitespace to determine whether the minus sign stands
LiberalTypeSynonyms (page 285) Enable liberalised type synonyms.
LinearTypes (page 347) Enable linear types.
MagicHash (page 242) Allow # as a postfix modifier on identifiers.
MonadComprehensions (page 254) Enable monad comprehensions.
MonadFailDesugaring (page 257) Enable monadfail desugaring.
MonoLocalBinds (page 449) Enable do not generalise local bindings. Implied by TypeFami
MonomorphismRestriction (page 449) Disable the monomorphism restriction.
MultiParamTypeClasses (page 400) Enable multi parameter type classes. Implied by Functional
MultiWayIf (page 263) Enable multi-way if-expressions.
NamedFieldPuns (page 361) Enable record puns.
NamedWildCards (page 445) Enable named wildcards.
NegativeLiterals (page 419) Enable support for negative literals.
NondecreasingIndentation (page 604) Allow nested contexts to be at the same indentation level as i
NPlusKPatterns (page 392) Enable support for n+k patterns. Implied by Haskell98 (page
NullaryTypeClasses (page 404) Deprecated, does nothing. nullary (no parameter) type classe
NumDecimals (page 420) Enable support for ‘fractional’ integer literals.
NumericUnderscores (page 420) Enable support for numeric underscores (page 420).
OverlappingInstances (page 414) Enable overlapping instances.
OverloadedLabels (page 423) Enable overloaded labels.
OverloadedLists (page 257) Enable overloaded lists.
OverloadedStrings (page 422) Enable overloaded string literals.
PackageImports (page 281) Enable package-qualified imports.
ParallelListComp (page 252) Enable parallel list comprehensions.
PartialTypeSignatures (page 444) Enable partial type signatures.
PatternGuards (page 389) Disable pattern guards. Implied by Haskell98 (page 237).
PatternSynonyms (page 392) Enable pattern synonyms.
PolyKinds (page 319) Enable kind polymorphism. Implies KindSignatures (page 4
PostfixOperators (page 261) Enable postfix operators.
QualifiedDo (page 249) Enable qualified do-notation desugaring.
QuantifiedConstraints (page 426) Allow forall quantifiers in constraints.
QuasiQuotes (page 459) Enable quasiquotation.
Rank2Types (page 342) Enable rank-2 types. Synonym for RankNTypes (page 342).
RankNTypes (page 342) Enable rank-N types. Implied by ImpredicativeTypes (page
RebindableSyntax (page 259) Employ rebindable syntax. Implies NoImplicitPrelude (page
RecordWildCards (page 362) Enable record wildcards. Implies DisambiguateRecordField
RecursiveDo (page 243) Enable recursive do (mdo) notation.
RoleAnnotations (page 354) Enable role annotations.
Safe (page 502) Enable the Safe Haskell (page 493) Safe mode.
ScopedTypeVariables (page 436) Enable lexically-scoped type variables.
StandaloneDeriving (page 368) Enable standalone deriving.
StandaloneKindSignatures (page 324) Allow the use of standalone kind signatures.
StarIsType (page 331) Treat * as [Link].
StaticPointers (page 470) Enable static pointers.
Strict (page 464) Make bindings in the current module strict by default.
StrictData (page 463) Enable default strict datatype fields.
TemplateHaskell (page 450) Enable Template Haskell.
Extension Description
TemplateHaskellQuotes (page 450) Enable quotation subset of Template Haskell (page 450).
TraditionalRecordSyntax (page 356) Disable support for traditional record syntax (as supported b
TransformListComp (page 252) Enable generalised list comprehensions.
Trustworthy (page 502) Enable the Safe Haskell (page 493) Trustworthy mode.
TupleSections (page 261) Enable tuple sections.
TypeApplications (page 338) Enable type application syntax in terms and types.
TypeFamilies (page 298) Enable type families. Implies ExplicitNamespaces (page 282
TypeFamilyDependencies (page 314) Enable injective type families. Implies TypeFamilies (page 2
TypeInType (page 319) Deprecated. Enable kind polymorphism and datatype promot
TypeOperators (page 284) Enable type operators. Implies ExplicitNamespaces (page 2
TypeSynonymInstances (page 409) Enable type synonyms in instance heads. Implied by Flexibl
UnboxedSums (page 475) Enable unboxed sums.
UnboxedTuples (page 474) Enable the use of unboxed tuple syntax.
UndecidableInstances (page 412) Enable undecidable instances.
UndecidableSuperClasses (page 401) Allow all superclass constraints, including those that may res
UnicodeSyntax (page 242) Enable unicode syntax.
UnliftedFFITypes (page 479) Enable unlifted FFI types
UnliftedNewtypes (page 477) Enable unlifted newtypes.
Unsafe (page 502) Enable Safe Haskell (page 493) Unsafe mode.
ViewPatterns (page 390) Enable view patterns.
Turning on an option that enables special syntax might cause working Haskell 98 code to
fail to compile, perhaps because it uses a variable name which has become a reserved word.
This section lists the syntax that is “stolen” by language extensions. We use notation and
nonterminal names from the Haskell 98 lexical syntax (see the Haskell 98 Report). We only
list syntax changes here that might affect existing working programs (i.e. “stolen” syntax).
Many of these extensions will also enable new context-free syntax, but in all cases programs
written to use the new syntax would not be compilable without the option enabled.
There are two classes of special syntax:
• New reserved words and symbols: character sequences which are no longer available
for use as identifiers in the program.
• Other special syntax: sequences of characters that have a different meaning when this
particular option is turned on.
The following syntax is stolen:
forall Stolen (in types) by default (see Lexical syntax (page 603)). forall is a reserved
keyword and never a type variable, in accordance with GHC Proposal #43.
mdo Stolen by: RecursiveDo (page 243)
foreign Stolen by: ForeignFunctionInterface (page 478)
rec, proc, -<, >-, -<<, >>-, (|, |) Stolen by: Arrows (page 273)
?varid Stolen by: ImplicitParams (page 441)
[|, [e|, [p|, [d|, [t|, [||, [e|| Stolen by: QuasiQuotes (page 459). Moreover, this intro-
duces an ambiguity with list comprehension syntax. See the discussion on quasi-quoting
(page 460) for details.
6.2 Syntax
UnicodeSyntax
Since 6.8.1
Enable the use of Unicode characters in place of their equivalent ASCII sequences.
The language extension UnicodeSyntax (page 242) enables Unicode characters to be used to
stand for certain ASCII character sequences. The following alternatives are provided:
ASCII Unicode Code Name
alternative point
:: 0x2237 PROPORTION
=> ⇒ 0x21D2 RIGHTWARDS DOUBLE ARROW
-> → 0x2192 RIGHTWARDS ARROW
<- ← 0x2190 LEFTWARDS ARROW
>- ⤚ 0x291a RIGHTWARDS ARROW-TAIL
-< ⤙ 0x2919 LEFTWARDS ARROW-TAIL
>>- ⤜ 0x291C RIGHTWARDS DOUBLE ARROW-TAIL
-<< ⤛ 0x291B LEFTWARDS DOUBLE ARROW-TAIL
* 0x2605 BLACK STAR
forall ∀ 0x2200 FOR ALL
(| 0x2987 Z NOTATION LEFT IMAGE BRACKET
|) 0x2988 Z NOTATION RIGHT IMAGE BRACKET
[| 0x27E6 MATHEMATICAL LEFT WHITE SQUARE
BRACKET
|] 0x27E7 MATHEMATICAL RIGHT WHITE SQUARE
BRACKET
MagicHash
Since 6.8.1
Enables the use of the hash character (#) as an identifier suffix.
The language extension MagicHash (page 242) allows # as a postfix modifier to identifiers.
Thus, x# is a valid variable, and T# is a valid type constructor or data constructor.
The hash sign does not change semantics at all. We tend to use variable names ending in “#”
for unboxed values or types (e.g. Int#), but there is no requirement to do so; they are just
plain ordinary variables. Nor does the MagicHash (page 242) extension bring anything into
scope. For example, to bring Int# into scope you must import [Link] (see Unboxed types
and primitive operations (page 473)); the MagicHash (page 242) extension then allows you to
refer to the Int# that is now in scope. Note that with this option, the meaning of x#y = 0 is
changed: it defines a function x# taking a single argument y; to define the operator #, put a
space: x # y = 0.
The MagicHash (page 242) also enables some new forms of literals (see Unboxed types
(page 473)):
• 'x'# has type Char#
• "foo"# has type Addr#
• 3# has type Int#. In general, any Haskell integer lexeme followed by a # is an Int#
literal, e.g. -0x3A# as well as 32#.
• 3## has type Word#. In general, any non-negative Haskell integer lexeme followed by ##
is a Word#.
• 3.2# has type Float#.
• 3.2## has type Double#
RecursiveDo
Since 6.8.1
Allow the use of recursive do notation.
The do-notation of Haskell 98 does not allow recursive bindings, that is, the variables bound
in a do-expression are visible only in the textually following code block. Compare this to a
let-expression, where bound variables are visible in the entire binding group.
It turns out that such recursive bindings do indeed make sense for a variety of monads, but
not all. In particular, recursion in this sense requires a fixed-point operator for the underlying
monad, captured by the mfix method of the MonadFix class, defined in [Link]
as follows:
Haskell’s Maybe, [] (list), ST (both strict and lazy versions), IO, and many other monads have
MonadFix instances. On the negative side, the continuation monad, with the signature (a ->
r) -> r, does not.
For monads that do belong to the MonadFix class, GHC provides an extended version of the
do-notation that allows recursive bindings. The RecursiveDo (page 243) (language pragma:
RecursiveDo) provides the necessary syntactic support, introducing the keywords mdo and
rec for higher and lower levels of the notation respectively. Unlike bindings in a do expres-
sion, those introduced by mdo and rec are recursively defined, much like in an ordinary let-
expression. Due to the new keyword mdo, we also call this notation the mdo-notation.
or equivalently
The extension RecursiveDo (page 243) also introduces a new keyword rec, which wraps a
mutually-recursive group of monadic statements inside a do expression, producing a single
statement. Similar to a let statement inside a do, variables bound in the rec are visible
throughout the rec group, and below it. For example, compare
In both cases, r1 and r2 are available both throughout the let or rec block, and in the state-
ments that follow it. The difference is that let is non-monadic, while rec is monadic. (In
Haskell let is really letrec, of course.)
The semantics of rec is fairly straightforward. Whenever GHC finds a rec group, it will
compute its set of bound variables, and will introduce an appropriate call to the underlying
monadic value-recursion operator mfix, belonging to the MonadFix class. Here is an example:
As usual, the meta-variables b, c etc., can be arbitrary patterns. In general, the statement
rec ss is desugared to the statement
A rec-block tells the compiler where precisely the recursive knot should be tied. It turns out
that the placement of the recursive knots can be rather delicate: in particular, we would like
the knots to be wrapped around as minimal groups as possible. This process is known as
segmentation, and is described in detail in Section 3.2 of A recursive do for Haskell. Seg-
mentation improves polymorphism and reduces the size of the recursive knot. Most impor-
tantly, it avoids unnecessary interference caused by a fundamental issue with the so-called
right-shrinking axiom for monadic recursion. In brief, most monads of interest (IO, strict
state, etc.) do not have recursion operators that satisfy this axiom, and thus not performing
segmentation can cause unnecessary interference, changing the termination behavior of the
resulting translation. (Details can be found in Sections 3.1 and 7.2.2 of Value Recursion in
Monadic Computations.)
The mdo notation removes the burden of placing explicit rec blocks in the code. Unlike an
ordinary do expression, in which variables bound by statements are only in scope for later
statements, variables bound in an mdo expression are in scope for all statements of the ex-
pression. The compiler then automatically identifies minimal mutually recursively dependent
segments of statements, treating them as if the user had wrapped a rec qualifier around
them.
The definition is syntactic:
• A generator ⟨g⟩ depends on a textually following generator ⟨g’⟩, if
– ⟨g’⟩ defines a variable that is used by ⟨g⟩, or
– ⟨g’⟩ textually appears between ⟨g⟩ and ⟨g’‘⟩, where ⟨g⟩ depends on ⟨g’‘⟩.
• A segment of a given mdo-expression is a minimal sequence of generators such that no
generator of the sequence depends on an outside generator. As a special case, although
it is not a generator, the final expression in an mdo-expression is considered to form a
segment by itself.
Segments in this sense are related to strongly-connected components analysis, with the ex-
ception that bindings in a segment cannot be reordered and must be contiguous.
Here is an example mdo-expression, and its translation to rec blocks:
Note that a given mdo expression can cause the creation of multiple rec blocks. If there are no
recursive dependencies, mdo will introduce no rec blocks. In this latter case an mdo expression
is precisely the same as a do expression, as one would expect.
In summary, given an mdo expression, GHC first performs segmentation, introducing rec
blocks to wrap over minimal recursive groups. Then, each resulting rec is desugared, using
a call to [Link] as described in the previous section. The original mdo-
expression typechecks exactly when the desugared version would do so.
Here are some other important points in using the recursive-do notation:
• It is enabled with the extension RecursiveDo (page 243), or the LANGUAGE RecursiveDo
pragma. (The same extension enables both mdo-notation, and the use of rec blocks inside
do expressions.)
• rec blocks can also be used inside mdo-expressions, which will be treated as a single
statement. However, it is good style to either use mdo or rec blocks in a single expression.
• If recursive bindings are required for a monad, then that monad must be declared an
instance of the MonadFix class.
• The following instances of MonadFix are automatically provided: List, Maybe, IO. Fur-
thermore, the [Link] and [Link] modules provide the in-
stances of the MonadFix class for Haskell’s internal state monad (strict and lazy, respec-
tively).
• Like let and where bindings, name shadowing is not allowed within an mdo-expression
or a rec-block; that is, all the names bound in a single rec must be distinct. (GHC will
complain if this is not the case.)
ApplicativeDo
Since 8.0.1
Allow use of Applicative do notation.
The language option ApplicativeDo (page 246) enables an alternative translation for the do-
notation, which uses the operators <$>, <*>, along with join as far as possible. There are
two main reasons for wanting to do this:
• We can use do-notation with types that are an instance of Applicative and Functor, but
not Monad
• In some monads, using the applicative operators is more efficient than monadic bind.
For example, it may enable more parallelism.
Applicative do-notation desugaring preserves the original semantics, provided that the Ap-
plicative instance satisfies <*> = ap and pure = return (these are true of all the common
monadic types). Thus, you can normally turn on ApplicativeDo (page 246) without fear of
breaking your program. There is one pitfall to watch out for; see Things to watch out for
(page 248).
There are no syntactic changes with ApplicativeDo (page 246). The only way it shows up at
the source level is that you can have a do expression that doesn’t require a Monad constraint.
For example, in GHCi:
This example only requires Functor, because it is translated into (\x -> not x) <$> m. A
more complex example requires Applicative,
It is possible to see the actual translation by using -ddump-ds (page 229), but be warned, the
output is quite verbose.
Note that if the expression can’t be translated into uses of <$>, <*> only, then it will incur a
Monad constraint as usual. This happens when there is a dependency on a value produced by
an earlier statement in the do-block:
Here, m x depends on the value of x produced by the first statement, so the expression cannot
be translated using <*>.
In general, the rule for when a do statement incurs a Monad constraint is as follows. If the
do-expression has the following form:
where none of the variables defined by p1...pn are mentioned in E1...En, and p1...pn are
all variables or lazy patterns, then the expression will only require Applicative. Otherwise,
the expression will require Monad. The block may return a pure expression E depending upon
the results p1...pn with either return or pure.
Note: the final statement must match one of these patterns exactly:
• return E
• return $ E
• pure E
• pure $ E
otherwise GHC cannot recognise it as a return statement, and the transformation to use <$>
that we saw above does not apply. In particular, slight variations such as return . Just $
x or let x = e in return x would not be recognised.
If the final statement is not of one of these forms, GHC falls back to standard do desugaring,
and the expression will require a Monad constraint.
When the statements of a do expression have dependencies between them, and Applica-
tiveDo cannot infer an Applicative type, it uses a heuristic algorithm to try to use <*> as
much as possible. This algorithm usually finds the best solution, but in rare complex cases it
might miss an opportunity. There is an algorithm that finds the optimal solution, provided as
an option:
-foptimal-applicative-do
Since 8.0.1
Enables an alternative algorithm for choosing where to use <*> in conjunction with the
ApplicativeDo language extension. This algorithm always finds the optimal solution,
but it is expensive: O(n^3), so this option can lead to long compile times when there are
very large do expressions (over 100 statements). The default ApplicativeDo algorithm
is O(n^2).
Strict patterns
A strict pattern match in a bind statement prevents ApplicativeDo from transforming that
statement to use Applicative. This is because the transformation would change the seman-
tics by making the expression lazier.
For example, this code will require a Monad constraint:
> :t \m -> do { (x:xs) <- m; return x }
\m -> do { (x:xs) <- m; return x } :: Monad m => m [b] -> m b
but making the pattern match lazy allows it to have a Functor constraint:
> :t \m -> do { ~(x:xs) <- m; return x }
\m -> do { ~(x:xs) <- m; return x } :: Functor f => f [b] -> f b
A “strict pattern match” is any pattern match that can fail. For example, (), (x:xs), !z, and C
x are strict patterns, but x and ~(1,2) are not. For the purposes of ApplicativeDo, a pattern
match against a newtype constructor is considered strict.
When there’s a strict pattern match in a sequence of statements, ApplicativeDo places a
>>= between that statement and the one that follows it. The sequence may be transformed to
use <*> elsewhere, but the strict pattern match and the following statement will always be
connected with >>=, to retain the same strictness semantics as the standard do-notation. If
you don’t want this, simply put a ~ on the pattern match to make it lazy.
Your code should just work as before when ApplicativeDo (page 246) is enabled, provided
you use conventional Applicative instances. However, if you define a Functor or Applica-
tive instance using do-notation, then it will likely get turned into an infinite loop by GHC. For
example, if you do this:
instance Functor MyType where
fmap f m = do x <- m; return (f x)
And the program will loop at runtime. Similarly, an Applicative instance like this
instance Applicative MyType where
pure = return
x <*> y = do f <- x; a <- y; return (f a)
QualifiedDo
Since 9.0.1
Allow the use of qualified do notation.
QualifiedDo enables qualifying a do block with a module name, to control which operations
to use for the monadic combinators that the do notation desugars to. When -XQualifiedDo is
enabled, you can qualify the do notation by writing [Link], where modid is a module name
in scope:
{-# LANGAUGE QualifiedDo #-}
import qualified [Link] as M
action :: [Link] a
action = [Link] x <- u
res
[Link] x
The additional module name (here M) is called the qualifier of the do-expression.
The unqualified do syntax is convenient for writing monadic code, but it only works for data
types that provide an instance of the Monad type class. There are other types which are
“monad-like” but can’t provide an instance of Monad (e.g. indexed monads, graded monads or
relative monads), yet they could still use the do syntax if it weren’t hardwired to the methods
of the Monad type class. -XQualifiedDo comes to make the do syntax customizable in this
respect. It allows you to mix and match do blocks of different types with suitable operations
to use on each case:
{-# LANGUAGE QualifiedDo #-}
import qualified [Link] as L
f :: IO ()
f = do
x <- runMAC $ -- (Prelude.>>=)
-- (runMAC $
[Link] --
d <- label "y" -- label "y" MAC.>>= \d ->
box $ --
-- (box $
[Link] --
r <- L.f d -- L.f d L.>>= \r ->
L.g r -- L.g r L.>>
[Link] r -- [Link] r
-- ) MAC.>>
[Link] d -- ([Link] d)
-- )
print x -- (\x -> print x)
• The a pat <-u statement uses [Link] for the failing case, if such a case is needed
[Link] { pat <- u; stmts } = u M.>>= \case pat -> [Link] { stmts }
• The desugaring of -XApplicativeDo uses (M.<$>), (M.<*>), and [Link] (after the the
applicative-do grouping has been performed)
Note that [Link] is only needed if the final expression is not identifiably a re-
turn. With -XQualifiedDo enabled, -XApplicativeDo looks only for the qualified
return/pure in a qualified do-block.
• With -XRecursiveDo, rec and mdo blocks use [Link] and [Link]:
; stmts
}
If a name [Link] is required by the desugaring process (and only if it’s required!) but the name
is not in scope, it is reported as an error.
The types of the operations picked for desugaring must produce an expression which is ac-
cepted by the typechecker. But other than that, there are no specific requirements on the
types.
If no qualifier is specified with -XQualifiedDo enabled, it defaults to the operations defined
in the Prelude, or, if -XRebindableSyntax is enabled, to whatever operations are in scope.
Note that the operations to be qualified must be in scope for QualifiedDo to work. I.e. import
MAC (label) in the example above would result in an error, since MAC.>>= and MAC.>> would
not be in scope.
Examples
f :: M.M SomeType
f = [Link]
x <- f1 -- M.>>=
f2 (do y <- g1 -- Prelude.>>=
g2 x y)
where
f1 = ...
f2 m = ...
g1 = ...
g2 x y = ...
The type of (>>=) can also be modified, as seen here for a graded monad:
-----------------
module M where
ParallelListComp
Since 6.8.1
Allow parallel list comprehension syntax.
Parallel list comprehensions are a natural extension to list comprehensions. List comprehen-
sions can be thought of as a nice syntax for writing maps and filters. Parallel comprehensions
extend this to include the zipWith family.
A parallel list comprehension has multiple independent branches of qualifier lists, each sepa-
rated by a | symbol. For example, the following zips together two lists:
The behaviour of parallel list comprehensions follows that of zip, in that the resulting list will
have the same length as the shortest branch.
We can define parallel list comprehensions by translation to regular comprehensions. Here’s
the basic idea:
Given a parallel comprehension of the form:
[ e | ((p1,p2), (q1,q2), ...) <- zipN [(p1,p2) | p1 <- e11, p2 <- e12, ...]
[(q1,q2) | q1 <- e21, q2 <- e22, ...]
...
]
where zipN is the appropriate zip for the given number of branches.
TransformListComp
Since 6.10.1
Allow use of generalised list (SQL-like) comprehension syntax. This introduces the group,
by, and using keywords.
Generalised list comprehensions are a further enhancement to the list comprehension syn-
tactic sugar to allow operations such as sorting and grouping which are familiar from SQL.
They are fully described in the paper Comprehensive comprehensions: comprehensions with
“order by” and “group by”, except that the syntax we use differs slightly from the paper.
The extension is enabled with the extension TransformListComp (page 252).
Here is an example:
There are three new keywords: group, by, and using. (The functions sortWith and groupWith
are not keywords; they are ordinary functions that are exported by [Link].)
There are five new forms of comprehension qualifier, all introduced by the (existing) keyword
then:
• then f
This statement requires that f have the type forall a. [a] -> [a] . You can see an example
of its use in the motivating example, as this form is used to apply take 5 .
• then f by e
This form is similar to the previous one, but allows you to create a function which will be
passed as the first argument to f. As a consequence f must have the type forall a. (a
-> t) -> [a] -> [a]. As you can see from the type, this function lets f “project out”
some information from the elements of the list it is transforming.
An example is shown in the opening example, where sortWith is supplied with a function
that lets it find out the sum salary for any item in the list comprehension it transforms.
This is the most general of the grouping-type statements. In this form, f is required to
have type forall a. (a -> t) -> [a] -> [[a]]. As with the then f by e case above,
the first argument is a function supplied to f by the compiler which lets it compute e on
every element of the list being transformed. However, unlike the non-grouping case, f
additionally partitions the list into a number of sublists: this means that at every point
after this statement, binders occurring before it in the comprehension refer to lists of
possible values, not single values. To help understand this, let’s look at an example:
-- This works similarly to groupWith in [Link], but doesn't sort its input first
groupRuns :: Eq b => (a -> b) -> [a] -> [[a]]
output = [ (the x, y)
| x <- ([1..3] ++ [1..2])
, y <- [4..6]
, then group by x using groupRuns ]
[(1, [4, 5, 6]), (2, [4, 5, 6]), (3, [4, 5, 6]), (1, [4, 5, 6]), (2, [4, 5, 6])]
Note that we have used the the function to change the type of x from a list to its original
numeric type. The variable y, in contrast, is left unchanged from the list form introduced
by the grouping.
With this form of the group statement, f is required to simply have the type forall a.
[a] -> [[a]], which will be used to group up the comprehension so far directly. An
example of this form is as follows:
output = [ x
| y <- [1..5]
, x <- "hello"
, then group using inits]
This will yield a list containing every prefix of the word “hello” written out 5 times:
["","h","he","hel","hell","hello","helloh","hellohe","hellohel","hellohell",
,→"hellohello","hellohelloh",...]
MonadComprehensions
Since 7.2.1
Enable list comprehension syntax for arbitrary monads.
Monad comprehensions generalise the list comprehension notation, including parallel com-
prehensions (Parallel List Comprehensions (page 252)) and transform comprehensions (Gen-
eralised (SQL-like) List Comprehensions (page 252)) to work for any monad.
Monad comprehensions support:
• Bindings:
Bindings are translated with the (>>=) and return functions to the usual do-notation:
do x <- Just 1
y <- Just 2
return (x+y)
• Guards:
Guards are translated with the guard function, which requires a MonadPlus instance:
do x <- [1..10]
guard (x <= 5)
return x
Parallel statements are translated using the mzip function, which requires a MonadZip
instance defined in [Link]:
All these features are enabled by default if the MonadComprehensions (page 254) extension is
enabled. The types and more detailed examples on how to use comprehensions are explained
in the previous chapters Generalised (SQL-like) List Comprehensions (page 252) and Parallel
List Comprehensions (page 252). In general you just have to replace the type [a] with the
type Monad m => m a for monad comprehensions.
Note: Even though most of these examples are using the list monad, monad comprehensions
work for any monad. The base package offers all necessary instances for lists, which make
MonadComprehensions (page 254) backward compatible to built-in, transform and parallel list
comprehensions.
Expressions: e
Declarations: d
-- Basic forms
D[ e | ] = return e
D[ e | p <- e, Q ] = e >>= \p -> D[ e | Q ]
D[ e | e, Q ] = guard e >> \p -> D[ e | Q ]
D[ e | let d, Q ] = let d in D[ e | Q ]
-- Transform comprehensions
D[ e | Q then f, R ] = f D[ Qv | Q ] >>= \Qv -> D[ e | R ]
The comprehension should typecheck when its desugaring would typecheck, except that
(as discussed in Generalised (SQL-like) List Comprehensions (page 252)) in the “then f”
and “then group using f” clauses, when the “by b” qualifier is omitted, argument f should
have a polymorphic type. In particular, “then [Link]” and “then group using
[Link]” are insufficiently polymorphic.
Monad comprehensions support rebindable syntax (Rebindable syntax and the implicit Pre-
lude import (page 259)). Without rebindable syntax, the operators from the “standard bind-
ing” module are used; with rebindable syntax, the operators are looked up in the current
lexical scope. For example, parallel comprehensions will be typechecked and desugared us-
ing whatever “mzip” is in scope.
The rebindable operators must have the “Expected type” given in the table above. These
types are surprisingly general. For example, you can use a bind operator with the type
In the case of transform comprehensions, notice that the groups are parameterised over some
arbitrary type n (provided it has an fmap, as well as the comprehension being over an arbitrary
monad.
MonadFailDesugaring
Since 8.0.1
Use the [Link] instead of the legacy [Link] function when desugaring
refutable patterns in do blocks.
The -XMonadFailDesugaring extension switches the desugaring of do-blocks to use Monad-
[Link] instead of [Link].
This extension is enabled by default since GHC 8.6.1, under the MonadFail Proposal (MFP).
This extension is temporary, and will be deprecated in a future release.
OverloadedLists
Since 7.8.1
Enable overloaded list syntax (e.g. desugaring of lists via the IsList class).
GHC supports overloading of the list notation. Let us recap the notation for constructing lists.
In Haskell, the list notation can be used in the following seven ways:
[] -- Empty list
[x] -- x : []
[x,y,z] -- x : y : z : []
[x .. ] -- enumFrom x
[x,y ..] -- enumFromThen x y
[x .. y] -- enumFromTo x y
[x,y .. z] -- enumFromThenTo x y z
When the OverloadedLists extension is turned on, the aforementioned seven notations are
desugared as follows:
[] -- fromListN 0 []
[x] -- fromListN 1 (x : [])
[x,y,z] -- fromListN 3 (x : y : z : [])
[x .. ] -- fromList (enumFrom x)
[x,y ..] -- fromList (enumFromThen x y)
[x .. y] -- fromList (enumFromTo x y)
[x,y .. z] -- fromList (enumFromThenTo x y z)
This extension allows programmers to use the list notation for construction of structures like:
Set, Map, IntMap, Vector, Text and Array. The following code listing gives a few examples:
List patterns are also overloaded. When the OverloadedLists extension is turned on, these
definitions are desugared as follows
(Here we are using view-pattern syntax for the translation, see View patterns (page 390).)
In the above desugarings, the functions toList, fromList and fromListN are all methods of
the IsList class, which is itself exported from the [Link] module. The type class is defined
as follows:
class IsList l where
type Item l
The IsList class and its methods are intended to be used in conjunction with the Overload-
edLists extension.
• The type function Item returns the type of items of the structure l.
• The function fromList constructs the structure l from the given list of Item l.
• The function fromListN takes the input list’s length as a hint. Its behaviour should be
equivalent to fromList. The hint can be used for more efficient construction of the
structure l compared to fromList. If the given hint is not equal to the input list’s length
the behaviour of fromListN is not specified.
• The function toList should be the inverse of fromList.
It is perfectly fine to declare new instances of IsList, so that list notation becomes useful for
completely new data types. Here are several example instances:
instance IsList [a] where
type Item [a] = a
fromList = id
toList = id
Rebindable syntax
When desugaring list notation with OverloadedLists (page 257) GHC uses the fromList (etc)
methods from module [Link]. You do not need to import [Link] for this to happen.
However if you use RebindableSyntax (page 259), then GHC instead uses whatever is in
scope with the names of toList, fromList and fromListN. That is, these functions are re-
bindable; c.f. Rebindable syntax and the implicit Prelude import (page 259).
Defaulting
Currently, the IsList class is not accompanied with defaulting rules. Although feasible, not
much thought has gone into how to specify the meaning of the default declarations like:
default ([a])
NoImplicitPrelude
Since 6.8.1
Don’t import Prelude by default.
GHC normally imports [Link] files for you. If you’d rather it didn’t, then give it a -
XNoImplicitPrelude option. The idea is that you can then import a Prelude of your own.
(But don’t call it Prelude; the Haskell module namespace is flat, and you must not conflict
with any Prelude module.)
RebindableSyntax
Implies NoImplicitPrelude (page 259)
Since 7.0.1
Enable rebinding of a variety of usually-built-in operations.
Suppose you are importing a Prelude of your own in order to define your own numeric class
hierarchy. It completely defeats that purpose if the literal “1” means “[Link]
1”, which is what the Haskell Report specifies. So the RebindableSyntax (page 259) extension
causes the following pieces of built-in syntax to refer to whatever is in scope, not the Prelude
versions:
• An integer literal 368 means “fromInteger (368::Integer)”, rather than
“[Link] (368::Integer)”.
• Fractional literals are handled in just the same way, except that the translation is from-
Rational (3.68::Rational).
• String literals are also handled the same way, except that the translation is fromString
("368"::String).
• The equality test in an overloaded numeric pattern uses whatever (==) is in scope.
• The subtraction operation, and the greater-than-or-equal test, in n+k patterns use what-
ever (-) and (>=) are in scope.
• Negation (e.g. “-(f x)”) means “negate (f x)”, both in numeric patterns, and expres-
sions.
• Conditionals (e.g. “if e1 then e2 else e3”) means “ifThenElse e1 e2 e3”. However
case expressions are unaffected.
• “Do” notation is translated using whatever functions (>>=), (>>), and fail, are in
scope (not the Prelude versions). List comprehensions, mdo (The recursive do-notation
(page 243)), and parallel array comprehensions, are unaffected.
• Arrow notation (see Arrow notation (page 273)) uses whatever arr, (>>>), first, app,
(|||) and loop functions are in scope. But unlike the other constructs, the types of these
functions must match the Prelude types very closely. Details are in flux; if you want to
use this, ask!
• List notation, such as [x,y] or [m..n] can also be treated via rebindable syntax if you
use -XOverloadedLists; see Overloaded lists (page 257).
• An overloaded label “#foo” means “fromLabel @"foo"”, rather than
“[Link] @"foo"” (see Overloaded labels (page 423)).
RebindableSyntax (page 259) implies NoImplicitPrelude (page 259).
In all cases (apart from arrow notation), the static semantics should be that of the desugared
form, even if that is a little unexpected. For example, the static semantics of the literal 368
is exactly that of fromInteger (368::Integer); it’s fine for fromInteger to have any of the
types:
Be warned: this is an experimental facility, with fewer checks than usual. Use -dcore-lint
to typecheck the desugared program. If Core Lint is happy you should be all right.
RebindableSyntax (page 259) does not apply to any code generated from a deriving clause
or declaration. To see why, consider the following code:
But because RebindableSyntax (page 259) and OverloadedStrings (page 422) are enabled,
the "Foo" string literal would now be of type Text, not String, which showString doesn’t
accept! This causes the generated Show instance to fail to typecheck. It’s hard to imagine
any scenario where it would be desirable have RebindableSyntax (page 259) behavior within
derived code, so GHC simply ignores RebindableSyntax (page 259) entirely when checking
derived code.
PostfixOperators
Since 7.10.1
Allow the use of post-fix operators
The PostfixOperators (page 261) extension enables a small extension to the syntax of left
operator sections, which allows you to define postfix operators. The extension is this: the left
section
(e !)
is equivalent (from the point of view of both type checking and execution) to the expression
((!) e)
(for any expression e and operator (!). The strict Haskell 98 interpretation is that the section
is equivalent to
That is, the operator must be a function of two arguments. GHC allows it to take only one
argument, and that in turn allows you to write the function postfix.
The extension does not extend to the left-hand side of function definitions; you must define
such a function in prefix form.
TupleSections
Since 6.12
Allow the use of tuple section syntax
The TupleSections (page 261) extension enables partially applied tuple constructors. For
example, the following program
(, True)
You can omit any combination of arguments to the tuple, as in the following
(, "I", , , "Love", , 1337)
which translates to
\a b c d -> (a, "I", b, c, "Love", d, 1337)
If you have unboxed tuples (page ??) enabled, tuple sections will also be available for them,
like so
(# , True #)
6.2.14 Lambda-case
LambdaCase
Since 7.6.1
Allow the use of lambda-case syntax.
The LambdaCase (page 262) extension enables expressions of the form
\case { p1 -> e1; ...; pN -> eN }
which is equivalent to
\freshName -> case freshName of { p1 -> e1; ...; pN -> eN }
Additionally, since GHC 9.0.1, combining LambdaCase (page 262) with Arrows (page 273) al-
lows \case syntax to be used as a command in proc notation:
proc x -> (f -< x) `catchA` \case
p1 -> cmd1
...
pN -> cmdN
EmptyCase
Since 7.8.1
Allow empty case expressions.
The EmptyCase (page 263) extension enables case expressions, or lambda-case expressions,
that have no alternatives, thus:
case e of { } -- No alternatives
or
This can be useful when you know that the expression being scrutinised has no non-bottom
values. For example:
data Void
f :: Void -> Int
f x = case x of { }
With dependently-typed features it is more useful (see #2431). For example, consider these
two candidate definitions of absurd:
We much prefer (B). Why? Because GHC can figure out that (True :~: False) is an empty
type. So (B) has no partiality and GHC is able to compile with -Wincomplete-patterns
(page 94) and -Werror (page 87). On the other hand (A) looks dangerous, and GHC doesn’t
check to make sure that, in fact, the function can never get called.
MultiWayIf
Since 7.6.1
Allow the use of multi-way-if syntax.
With MultiWayIf (page 263) extension GHC accepts conditional expressions with multiple
branches:
case () of
_ | guard1 -> expr1
...
_ | guardN -> exprN
Multi-way if expressions introduce a new layout context. So the example above is equivalent
to:
if { | guard1 -> expr1
; | ...
; | guardN -> exprN
}
Layout with multi-way if works in the same way as other layout contexts, except that the
semi-colons between guards in a multi-way if are optional. So it is not necessary to line up
all the guards at the same column; this is consistent with the way guards work in function
definitions and case expressions.
A careful reading of the Haskell 98 Report reveals that fixity declarations (infix, infixl, and
infixr) are permitted to appear inside local bindings such those introduced by let and where.
However, the Haskell Report does not specify the semantics of such bindings very precisely.
In GHC, a fixity declaration may accompany a local binding:
let f = ...
infixr 3 `f`
in
...
and the fixity declaration applies wherever the binding is in scope. For example, in a let, it
applies in the right-hand sides of other let-bindings and the body of the letC. Or, in recursive
do expressions (The recursive do-notation (page 243)), the local fixity declarations of a let
statement scope over other statements in the group, just as the bound name does.
Moreover, a local fixity declaration must accompany a local binding of that name: it is not
possible to revise the fixity of name bound elsewhere, as in
let infixr 9 $ in ...
Because local fixity declarations are technically Haskell 98, no extension is necessary to en-
able them.
BlockArguments
Since 8.6.1
Allow do expressions, lambda expressions, etc. to be directly used as a function argu-
ment.
In Haskell 2010, certain kinds of expressions can be used without parentheses as an argument
to an operator, but not as an argument to a function. They include do, lambda, if, case, and
let expressions. Some GHC extensions also define language constructs of this type: mdo
(The recursive do-notation (page 243)), \case (Lambda-case (page 262)), and proc (Arrow
notation (page 273)).
The BlockArguments (page 265) extension allows these constructs to be directly used as a
function argument. For example:
when (x > 0) do
print x
exitFailure
and
The Haskell report defines the lexp nonterminal thus (* indicates a rule of interest)
The BlockArguments (page 265) extension moves these production rules under aexp
lexp → fexp
Now the lexp nonterminal is redundant and can be dropped from the grammar.
Note that this change relies on an existing meta-rule to resolve ambiguities:
The grammar is ambiguous regarding the extent of lambda abstractions, let expres-
sions, and conditionals. The ambiguity is resolved by the meta-rule that each of
these constructs extends as far to the right as possible.
For example, f \a -> a b will be parsed as f (\a -> a b), not as f (\a -> a) b.
Typed holes are a feature of GHC that allows special placeholders written with a leading
underscore (e.g., “_”, “_foo”, “_bar”), to be used as expressions. During compilation these
holes will generate an error message that describes which type is expected at the hole’s
location, information about the origin of any free type variables, and a list of local bindings
that might help fill the hole and bindings in scope that fit the type of the hole that might help
fill the hole with actual code. Typed holes are always enabled in GHC.
The goal of typed holes is to help with writing Haskell code rather than to change the type
system. Typed holes can be used to obtain extra information from the type checker, which
might otherwise be hard to get. Normally, using GHCi, users can inspect the (inferred) type
signatures of all top-level bindings. However, this method is less convenient with terms that
are not defined on top-level or inside complex expressions. Holes allow the user to check the
type of the term they are about to write.
For example, compiling the following module with GHC:
f :: a -> a
f x = _
[Link]:7:
Found hole `_' with type: a
Where: `a' is a rigid type variable bound by
the type signature for f :: a -> a at [Link]:6
In the expression: _
In an equation for `f': f x = _
cons z = z : True : _x : y
[Link]:21: error:
Found hole: _x :: Bool
Or perhaps ‘_x’ is mis-spelled, or not in scope
In the first argument of ‘(:)’, namely ‘_x’
In the second argument of ‘(:)’, namely ‘_x : y’
In the second argument of ‘(:)’, namely ‘True : _x : y’
Relevant bindings include
z :: Bool (bound at [Link]:6)
cons :: Bool -> [Bool] (bound at [Link]:1)
Valid hole fits include
z :: Bool (bound at [Link]:6)
otherwise :: Bool
(imported from ‘Prelude’ at [Link]:8-10
(and originally defined in ‘[Link]’))
False :: Bool
(imported from ‘Prelude’ at [Link]:8-10
(and originally defined in ‘[Link]’))
True :: Bool
(imported from ‘Prelude’ at [Link]:8-10
(and originally defined in ‘[Link]’))
maxBound :: forall a. Bounded a => a
with maxBound @Bool
(imported from ‘Prelude’ at [Link]:8-10
(and originally defined in ‘[Link]’))
minBound :: forall a. Bounded a => a
[Link]:26: error:
Variable not in scope: y :: [Bool]
More information is given for explicit holes (i.e. ones that start with an underscore),
than for out-of-scope variables, because the latter are often unintended typos, so the
extra information is distracting. If you want the detailed information, use a leading
underscore to make explicit your intent to use a hole.
• Unbound identifiers with the same name are never unified, even within the same function,
but shown individually. For example:
cons = _x : _x
[Link]:8:
Found hole '_x' with type: a
Where: `a' is a rigid type variable bound by
the inferred type of cons :: [a] at [Link]:1
In the first argument of `(:)', namely `_x'
In the expression: _x : _x
In an equation for `cons': cons = _x : _x
Relevant bindings include cons :: [a] (bound at [Link]:1)
[Link]:13:
Found hole: _x :: [a]
Where: ‘a’ is a rigid type variable bound by
the inferred type of cons :: [a]
at [Link]:1-12
Or perhaps ‘_x’ is mis-spelled, or not in scope
In the second argument of ‘(:)’, namely ‘_x’
In the expression: _x : _x
In an equation for ‘cons’: cons = _x : _x
Relevant bindings include cons :: [a] (bound at [Link]:1)
Valid hole fits include
cons :: forall a. [a]
with cons @a
(defined at [Link]:1)
mempty :: forall a. Monoid a => a
with mempty @[a]
(imported from ‘Prelude’ at [Link]:8-10
(and originally defined in ‘[Link]’))
Notice the two different types reported for the two different occurrences of _x.
• No language extension is required to use typed holes. The lexeme “_” was previously
illegal in Haskell, but now has a more informative error message. The lexeme “_x” is a
perfectly legal variable, and its behaviour is unchanged when it is in scope. For example
f _x = _x + 1
does not elicit any errors. Only a variable that is not in scope (whether or not it starts
with an underscore) is treated as an error (which it always was), albeit now with a more
informative error message.
• Unbound data constructors used in expressions behave exactly as above. However, un-
bound data constructors used in patterns cannot be deferred, and instead bring compi-
lation to a halt. (In implementation terms, they are reported by the renamer rather than
the type checker.)
• The list of valid hole fits is found by checking which bindings in scope would fit into the
hole. As an example, compiling the following module with GHC:
g :: [String]
g = _ "hello, world"
There are a few flags for controlling the amount of context information shown for typed holes:
-fshow-hole-constraints
When reporting typed holes, also print constraints that are in scope. Example:
show_constraints.hs:4:7: error:
• Found hole: _ :: Bool
• In the expression: _
In an equation for ‘f’: f x = _
• Relevant bindings include
x :: a (bound at show_constraints.hs:4:3)
f :: a -> Bool (bound at show_constraints.hs:4:1)
Constraints include Eq a (from show_constraints.hs:3:1-22)
Valid hole fits include
otherwise :: Bool
False :: Bool
True :: Bool
maxBound :: forall a. Bounded a => a
with maxBound @Bool
minBound :: forall a. Bounded a => a
with minBound @Bool
GHC sometimes suggests valid hole fits for typed holes, which is configurable by a few flags.
-fno-show-valid-hole-fits
Default off
This flag can be toggled to turn off the display of valid hole fits entirely.
-fmax-valid-hole-fits=⟨n⟩
Default 6
The list of valid hole fits is limited by displaying up to 6 hole fits per hole. The number of
hole fits shown can be set by this flag. Turning the limit off with -fno-max-valid-hole-
fits (page 270) displays all found hole fits.
-fshow-type-of-hole-fits
Default on
By default, the hole fits show the type of the hole fit. This can be turned off by the reverse
of this flag.
-fshow-type-app-of-hole-fits
Default on
By default, the hole fits show the type application needed to make this hole fit fit the
type of the hole, e.g. for the hole (_ :: Int -> [Int]), mempty is a hole fit with mempty
@(Int -> [Int]). This can be toggled off with the reverse of this flag.
-fshow-docs-of-hole-fits
Default off
It can sometime be the case that the name and type of a valid hole fit is not enough to
realize what the fit stands for. This flag adds the documentation of the fit to the message,
if the documentation is available (and the module from which the function comes was
compiled with the -haddock flag).
-fshow-type-app-vars-of-hole-fits
Default on
By default, the hole fits show the type application needed to make this hole fit fit the
type of the hole, e.g. for the hole (_ :: Int -> [Int]), mempty :: Monoid a => a is
a hole fit with mempty @(Int -> [Int]). This flag toggles whether to show a ~ (Int
-> [Int]) instead of mempty @(Int -> [Int]) in the where clause of the valid hole fit
message.
-fshow-provenance-of-hole-fits
Default on
By default, each hole fit shows the provenance information of its hole fit, i.e. where it
was bound or defined, and what module it was originally defined in if it was imported.
This can be toggled off using the reverse of this flag.
-funclutter-valid-hole-fits
Default off
This flag can be toggled to decrease the verbosity of the valid hole fit suggestions by not
showing the provenance nor type application of the suggestions.
When the refinement level is not set, it will only offer valid hole fits suggestions:
Which shows that the hole could be replaced with e.g. foldl1 _. While not fixing the hole,
this can help users understand what options they have.
-frefinement-level-hole-fits=⟨n⟩
Default off
The list of valid refinement hole fits is generated by considering hole fits with a varying
amount of additional holes. The amount of holes in a refinement can be set by this flag.
If the flag is set to 0 or not set at all, no valid refinement hole fits will be suggested.
-fabstract-refinement-hole-fits
Default off
Valid list of valid refinement hole fits can often grow large when the refinement level is
>= 2, with holes like head _ _ or fst _ _, which are valid refinements, but which are
unlikely to be relevant since one or more of the holes are still completely open, in that
neither the type nor kind of those holes are constrained by the proposed identifier at all.
By default, such holes are not reported. By turning this flag on, such holes are included
in the list of valid refinement hole fits.
-fmax-refinement-hole-fits=⟨n⟩
Default 6
The list of valid refinement hole fits is limited by displaying up to 6 hole fits per hole. The
number of hole fits shown can be set by this flag. Turning the limit off with -fno-max-
refinement-hole-fits (page 272) displays all found hole fits.
-fshow-hole-matches-of-hole-fits
Default on
The types of the additional holes in refinement hole fits are displayed in the output, e.g.
foldl1 (_ :: a -> a -> a) is a refinement for the hole _ :: [a] -> a. If this flag is
toggled off, the output will display only foldl1 _, which can be used as a direct replace-
ment for the hole, without requiring -XScopedTypeVariables.
There are currently two ways to sort valid hole fits. Sorting can be toggled with -fsort-
valid-hole-fits (page 273)
-fno-sort-valid-hole-fits
Default off
By default the valid hole fits are sorted to show the most relevant hole fits at the top of
the list of valid hole fits. This can be toggled off with this flag.
-fsort-by-size-hole-fits
Default on
Sorts by how big the types the quantified type variables in the type of the function would
have to be in order to match the type of the hole.
-fsort-by-subsumption-hole-fits
Default off
An alternative sort. Sorts by checking which hole fits subsume other hole fits, such that
if hole fit a could be used as hole fits for hole fit b, then b appears before a in the output.
It is more precise than the default sort, but also a lot slower, since a subsumption check
has to be run for each pair of valid hole fits.
Arrows
Since 6.8.1
Enable arrow notation.
Arrows are a generalisation of monads introduced by John Hughes. For more details, see
• “Generalising Monads to Arrows”, John Hughes, in Science of Computer Programming
37, pp. 67–111, May 2000. The paper that introduced arrows: a friendly introduction,
motivated with programming examples.
• “A New Notation for Arrows”, Ross Paterson, in ICFP, Sep 2001. Introduced the notation
described here.
• “Arrows and Computation”, Ross Paterson, in The Fun of Programming, Palgrave, 2003.
where proc is a new keyword. The variables of the pattern are bound in the body of the proc-
expression, which is a new sort of thing called a command. The syntax of commands is as
follows:
with ⟨cmd⟩0 up to ⟨cmd⟩9 defined using infix operators as for expressions, and
where ⟨calts⟩ are like ⟨alts⟩ except that the bodies are commands instead of expressions.
Commands produce values, but (like monadic computations) may yield more than one value,
or none, and may do other things as well. For the most part, familiarity with monadic notation
is a good guide to using commands. However the values of expressions, even monadic ones,
are determined by the values of the variables they contain; this is not necessarily the case for
commands.
A simple example of the new notation is the expression
We call this a procedure or arrow abstraction. As with a lambda expression, the variable x is
a new variable bound within the proc-expression. It refers to the input to the arrow. In the
above example, -< is not an identifier but a new reserved symbol used for building commands
from an expression of arrow type and an expression to be fed as input to that arrow. (The
weird look will make more sense later.) It may be read as analogue of application for arrows.
The above example is equivalent to the Haskell expression
That would make no sense if the expression to the left of -< involves the bound variable x.
More generally, the expression to the left of -< may not involve any local variable, i.e. a
variable bound in the current arrow abstraction. For such a situation there is a variant -<<,
as in
which is equivalent to
so in this case the arrow must belong to the ArrowApply class. Such an arrow is equivalent
to a monad, so if you’re using this form you may find a monadic formulation more convenient.
Another form of command is a form of do-notation. For example, you can write
proc x -> do
y <- f -< x+1
g -< 2*y
let z = x+y
t <- h -< x*z
returnA -< t+z
You can read this much like ordinary do-notation, but with commands in place of monadic
expressions. The first line sends the value of x+1 as an input to the arrow f, and matches its
output against y. In the next line, the output is discarded. The arrow returnA is defined in
the [Link] module as arr id. The above example is treated as an abbreviation for
Note that variables not used later in the composition are projected out. After simplification
using rewrite rules (see Rewrite rules (page 504)) defined in the [Link] module, this
reduces to
which is what you might have written by hand. With arrow notation, GHC keeps track of all
those tuples of variables for you.
Note that although the above translation suggests that let-bound variables like z must be
monomorphic, the actual translation produces Core, so polymorphic variables are allowed.
It’s also possible to have mutually recursive bindings, using the new rec keyword, as in the
following example:
The translation of such forms uses the loop combinator, so the arrow concerned must belong
to the ArrowLoop class.
Conditional commands
In the previous example, we used a conditional expression to construct the input for an arrow.
Sometimes we want to conditionally execute different commands, as in
which is translated to
Since the translation uses |||, the arrow concerned must belong to the ArrowChoice class.
There are also case commands, like
case input of
[] -> f -< ()
[x] -> g -< x+1
x1:x2:xs -> do
y <- h -< (x1, x2)
ys <- k -< xs
returnA -< y:ys
The syntax is the same as for case expressions, except that the bodies of the alternatives are
commands rather than expressions. The translation is similar to that of if commands.
As we’re seen, arrow notation provides constructs, modelled on those for expressions, for
sequencing, value recursion and conditionals. But suitable combinators, which you can define
in ordinary Haskell, may also be used to build new commands out of existing ones. The basic
idea is that a command defines an arrow from environments to values. These environments
assign values to the free local variables of the command. Thus combinators that produce
arrows from arrows may also be used to build commands from commands. For example, the
ArrowPlus class includes a combinator
(The do on the first line is needed to prevent the first <+> ... from being interpreted as part
of the expression on the previous line.) This is equivalent to
We are actually using <+> here with the more specific type
arr (first k) >>> (f <+> g) = (arr (first k) >>> f) <+> (arr (first k) >>> g)
at least for strict k. (This should be automatic if you’re not using seq.) This ensures that
environments seen by the subcommands are environments of the whole command, and also
allows the translation to safely trim these environments. (The second component of the input
pairs can contain unnamed input values, as described in the next section.) The operator must
also not use any variable defined within the current arrow abstraction.
We could define our own operator
and use it in the same way. Of course this infix syntax only makes sense for binary operators;
there is also a more general syntax involving special brackets:
proc x -> do
y <- f -< x+1
(|untilA (increment -< x+y) (within 0.5 -< x)|)
Primitive constructs
Some operators will need to pass additional inputs to their subcommands. For example, in an
arrow type supporting exceptions, the operator that attaches an exception handler will wish
to pass the exception that occurred to the handler. Such an operator might have a type
where Ex is the type of exceptions handled. You could then use this with arrow notation by
writing a command
so that if an exception is raised in the command body, the variable ex is bound to the value of
the exception and the command handler, which typically refers to ex, is entered. Though the
syntax here looks like a functional lambda, we are talking about commands, and something
different is going on. The input to the arrow represented by a command consists of values
for the free local variables in the command, plus a stack of anonymous values. In all the prior
examples, we made no assumptions about this stack. In the second argument to handleA, the
value of the exception has been added to the stack input to the handler. The command form
of lambda merely gives this value a name.
More concretely, the input to a command consists of a pair of an environment and a stack.
Each value on the stack is paired with the remainder of the stack, with an empty stack being
(). So operators like handleA that pass extra inputs to their subcommands can be designed
for use with the notation by placing the values on the stack paired with the environment in
this way. More precisely, the type of each argument of the operator (and its result) should
have the form
where ⟨e⟩ is a polymorphic variable (representing the environment) and ⟨ti⟩ are the types of
the values on the stack, with ⟨t1⟩ being the “top”. The polymorphic variable ⟨e⟩ must not occur
in ⟨a⟩, ⟨ti⟩ or ⟨t⟩. However the arrows involved need not be the same. Here are some more
examples of suitable operators:
bracketA :: ... => a (e,s) b -> a (e,(b,s)) c -> a (e,(c,s)) d -> a (e,s) d
runReader :: ... => a (e,s) c -> a' (e,(State,s)) c
runState :: ... => a (e,s) c -> a' (e,(State,s)) (c,State)
We can supply the extra input required by commands built with the last two by applying them
to ordinary expressions, as in
proc x -> do
s <- ...
(|runReader (do { ... })|) s
which adds s to the stack of inputs to the command built using runReader.
The command versions of lambda abstraction and application are analogous to the expression
versions. In particular, the beta and eta rules describe equivalences of commands. These
three features (operators, lambda abstraction and application) are the core of the notation;
everything else can be built using them, though the results would be somewhat clumsy. For
example, we could simulate do-notation by defining
bind :: Arrow a => a (e,s) b -> a (e,(b,s)) c -> a (e,s) c
u `bind` f = returnA &&& u >>> f
• Instead of a single form of arrow application (arrow tail) with two translations, the im-
plementation provides two forms -< (first-order) and -<< (higher-order).
• User-defined operators are flagged with banana brackets instead of a new form keyword.
• In the paper and the previous implementation, values on the stack were paired to the
right of the environment in a single argument, but now the environment and stack are
separate arguments.
Portability
Although only GHC implements arrow notation directly, there is also a preprocessor (available
from the arrows web page) that translates arrow notation into Haskell 98 for use with other
Haskell systems. You would still want to check arrow programs with GHC; tracing type errors
in the preprocessor output is not easy. Modules intended for both GHC and the preprocessor
must observe some additional restrictions:
• The module must import [Link].
• The preprocessor cannot cope with other Haskell extensions. These would have to go in
separate modules.
• Because the preprocessor targets Haskell (rather than Core), let-bound variables are
monomorphic.
LexicalNegation
Since 9.0.1
Detect if the minus sign stands for negation during lexical analysis by checking for the
surrounding whitespace.
In Haskell 2010, the minus sign stands for negation when it has no left-hand side. Consider x
= -5 and y = 2 -5. In x, there’s no expression between the = and -, so the minus stands for
negation, whereas in y, there’s 2 to the left of the minus, therefore it stands for subtraction.
This leads to certain syntactic anomalies:
• (% x) is an operator section for any operator (%) except for (-). (-x) is negated x
rather than the right operator section of subtraction. Consequently, it is impossible to
write such a section, and users are advised to write (subtract x) instead.
• Negative numbers must be parenthesized when they appear in function argument posi-
tion. f (-5) is correct, whereas f -5 is parsed as (-) f 5.
The latter issue is partly mitigated by NegativeLiterals (page 419). When it is enabled, -5
is parsed as negative 5 regardless of context, so f -5 works as expected. However, it only
applies to literals, so f -x or f -(a*2) are still parsed as subtraction.
With LexicalNegation (page 279), both anomalies are resolved:
• (% x) is an operator section for any operator (%), no exceptions, as long as there’s
whitespace between % and x.
• In f -x, the -x is parsed as the negation of x for any syntactically atomic expression x
(variable, literal, or parenthesized expression).
• The prefix - binds tighter than any infix operator. -a % b is parsed as (-a) % b regard-
less of the fixity of %.
This means that (-x) is the right operator section of subtraction, whereas (-x) is the negation
of x. Note that these expressions will often have different types ((-x) might have type Int
-> Int while (-x) will have type Int), and so users mistaking one for the other will likely get
a compile error.
Under LexicalNegation (page 279), negated literals are desugared without negate. That is,
-123 stands for fromInteger (-123) rather than negate (fromInteger 123). This makes
LexicalNegation (page 279) a valid replacement for NegativeLiterals (page 419).
module A( f ) where
f = True
module B where
import A hiding( g ) -- A does not export g
g = f
The import A hiding( g ) in module B is technically an error (Haskell Report, 5.3.1) be-
cause A does not export g. However GHC allows it, in the interests of supporting backward
compatibility; for example, a newer version of A might export g, and you want B to work in
either case.
The warning -Wdodgy-imports (page 92), which is off by default but included with -W
(page 86), warns if you hide something that the imported module does not export.
PackageImports
Since 6.10.1
Allow the use of package-qualified import syntax.
With the PackageImports (page 281) extension, GHC allows import declarations to be quali-
fied by the package name that the module is intended to be imported from. For example:
would import the module [Link] from the package network (any version). This may
be used to disambiguate an import when the same module is available from multiple packages,
or is present in both the current package being built and an external package.
The special package name this can be used to refer to the current package being built.
Note: You probably don’t need to use this feature, it was added mainly so that we can
build backwards-compatible versions of packages when APIs change. It can lead to fragile
dependencies in the common case: modules occasionally move from one package to another,
rendering any package-qualified imports broken. See also Thinning and renaming modules
(page 197) for an alternative way of disambiguating between module names.
Safe
Since 7.2.1
Declare the Safe Haskell state of the current module.
Trustworthy
Since 7.2.1
Declare the Safe Haskell state of the current module.
Unsafe
Since 7.4.1
Declare the Safe Haskell state of the current module.
With the Safe (page 502), Trustworthy (page 502) and Unsafe (page 502) language flags,
GHC extends the import declaration syntax to take an optional safe keyword after the import
keyword. This feature is part of the Safe Haskell GHC extension. For example:
would import the module [Link] with compilation only succeeding if Net-
[Link] can be safely imported. For a description of when a import is considered safe
see Safe Haskell (page 493).
ExplicitNamespaces
Since 7.6.1
Enable use of explicit namespaces in module export lists.
In an import or export list, such as
the entities f and (++) are values. However, with type operators (Type operators (page 284))
it becomes possible to declare (++) as a type constructor. In that case, how would you export
or import it?
The ExplicitNamespaces (page 282) extension allows you to prefix the name of a type con-
structor in an import or export list with “type” to disambiguate this case, thus:
The extension ExplicitNamespaces (page 282) is implied by TypeOperators (page 284) and
(for some reason) by TypeFamilies (page 298).
In addition, with PatternSynonyms (page 392) you can prefix the name of a data constructor
in an import or export list with the keyword pattern, to allow the import or export of a data
constructor without its parent type constructor (see Import and export of pattern synonyms
(page 396)).
ImportQualifiedPost
Since 8.10.1
ImportQualifiedPost allows the syntax import M qualified, that is, to annotate a
module as qualified by writing qualified after the module name.
To import a qualified module usually you must specify qualified in prepositive position :
import qualified M. This often leads to a “hanging indent” (which is automatically inserted
by some autoformatters and common in many code bases. For example:
import qualified A
import B
import C
import A qualified
import B
import C
6.4 Types
EmptyDataDecls
Since 6.8.1
Allow definition of empty data types.
With the EmptyDataDecls (page 283) extension, GHC lets you declare a data type with no
constructors.
You only need to enable this extension if the language you’re using is Haskell 98, in which
a data type must have at least one constructor. Haskell 2010 relaxed this rule to allow data
types with no constructors, and thus EmptyDataDecls (page 283) is enabled by default when
the language is Haskell 2010.
For example:
data S -- S :: Type
data T a -- T :: Type -> Type
Syntactically, the declaration lacks the “= constrs” part. The type can be parameterised over
types of any kind, but if the kind is not Type then an explicit kind annotation must be used
(see Explicitly-kinded quantification (page 435)).
Such data types have only one value, namely bottom. Nevertheless, they can be useful when
defining “phantom types”.
In conjunction with the EmptyDataDeriving (page 367) extension, empty data declarations
can also derive instances of standard type classes (see Deriving instances for empty data
types (page 367)).
DatatypeContexts
Since 7.0.1
Allow contexts on data types.
Haskell allows datatypes to be given contexts, e.g.
NilSet :: Set a
ConsSet :: Eq a => a -> Set a -> Set a
This is widely considered a misfeature, and is going to be removed from the language. In
GHC, it is controlled by the deprecated extension DatatypeContexts.
GHC allows type constructors, classes, and type variables to be operators, and to be written
infix, very much like expressions. More specifically:
• A type constructor or class can be any non-reserved operator. Symbols used in types are
always like capitalized identifiers; they are never variables. Note that this is different
from the lexical syntax of data constructors, which are required to begin with a :.
• Data type and type-synonym declarations can be written infix, parenthesised if you want
further arguments. E.g.
• Back-quotes work as for expressions, both for type constructors and type variables; e.g.
Int `Either` Bool, or Int `a` Bool. Similarly, parentheses work the same; e.g. (:*:)
Int Bool.
• Fixities may be declared for type constructors, or classes, just as for data constructors.
However, one cannot distinguish between the two in a fixity declaration; a fixity decla-
ration sets the fixity for a data constructor and the corresponding type constructor. For
example:
infixl 7 T, :*:
sets the fixity for both type constructor T and data constructor T, and similarly for :*:.
Int `a` Bool.
• The function arrow -> is infixr with fixity -1.
TypeOperators
Implies ExplicitNamespaces (page 282)
Since 6.8.1
Allow the use and definition of types with operator names.
In types, an operator symbol like (+) is normally treated as a type variable, just like a. Thus
in Haskell 98 you can say
As you can see, using operators in this way is not very useful, and Haskell 98 does not even
allow you to write them infix.
The language TypeOperators (page 284) changes this behaviour:
• Operator symbols become type constructors rather than type variables.
• Operator symbols in types can be written infix, both in definitions and uses. For example:
data a + b = Plus a b
type Foo = Int + Bool
• There is now some potential ambiguity in import and export lists; for example if you
write import M( (+) ) do you mean the function (+) or the type constructor (+)? The
default is the former, but with ExplicitNamespaces (page 282) (which is implied by
TypeOperators (page 284)) GHC allows you to specify the latter by preceding it with the
keyword type, thus:
LiberalTypeSynonyms
Implies ExplicitForAll (page 431)
Since 6.8.1
Relax many of the Haskell 98 rules on type synonym definitions.
Type synonyms are like macros at the type level, but Haskell 98 imposes many rules on in-
dividual synonym declarations. With the LiberalTypeSynonyms (page 285) extension, GHC
does validity checking on types only after expanding type synonyms. That means that GHC
can be very much more liberal about type synonyms than Haskell 98.
• You can write a forall (including overloading) in a type synonym, thus:
f :: Discard a
f x y = (x, show y)
• If you also use UnboxedTuples (page 474), you can write an unboxed tuple in a type
synonym:
h :: Int -> Pr
h x = (# x, x #)
After expanding the synonym, f has the legal (in GHC) type:
foo :: Generic Id []
After expanding the synonym, foo has the legal (in GHC) type:
GHC currently does kind checking before expanding synonyms (though even that could be
changed).
After expanding type synonyms, GHC does validity checking on types, looking for the following
malformedness which isn’t detected simply by kind checking:
• Type constructor applied to a type involving for-alls (if ImpredicativeTypes (page 346)
is off)
• Partially-applied type synonym.
So, for example, this will be rejected:
type Pr = forall a. a
h :: [Pr]
h = ...
because GHC does not allow type constructors applied to for-all types.
ExistentialQuantification
Implies ExplicitForAll (page 431)
Since 6.8.1
Allow existentially quantified type variables in types.
The idea of using existential quantification in data type declarations was suggested by Perry,
and implemented in Hope+ (Nigel Perry, The Implementation of Practical Functional Pro-
gramming Languages, PhD Thesis, University of London, 1991). It was later formalised by
Laufer and Odersky (Polymorphic type inference and abstract data types, TOPLAS, 16(5), pp.
1411-1430, 1994). It’s been in Lennart Augustsson’s hbc Haskell compiler for several years,
and proved very useful. Here’s the idea. Consider the declaration:
Notice that the type variable a in the type of MkFoo does not appear in the data type itself,
which is plain Foo. For example, the following expression is fine:
Here, (MkFoo 3 even) packages an integer with a function even that maps an integer to Bool;
and MkFoo 'c' isUpper packages a character with a compatible function. These two things
are each of type Foo and can be put in a list.
What can we do with a value of type Foo? In particular, what happens when we pattern-match
on MkFoo?
Since all we know about val and fn is that they are compatible, the only (useful) thing we
can do with them is to apply fn to val to get a boolean. For example:
What this allows us to do is to package heterogeneous values together with a bunch of func-
tions that manipulate them, and then treat that collection of packages in a uniform manner.
You can express quite a bit of object-oriented-like programming this way.
Why existential?
What has this to do with existential quantification? Simply that MkFoo has the (nearly) isomor-
phic type
But Haskell programmers can safely think of the ordinary universally quantified type given
above, thereby avoiding adding a new existential quantification construct.
An easy extension is to allow arbitrary contexts before the constructor. For example:
But when pattern matching on Baz1 the matched values can be compared for equality, and
when pattern matching on Baz2 the first matched value can be converted to a string (as well
as applying the function to it). So this program is legal:
Record Constructors
GHC allows existentials to be used with records syntax as well. For example:
Here tag is a public field, with a well-typed selector function tag :: Counter a -> a. See
Field selectors and TypeApplications (page 356) for a full description of how the types of
top-level field selectors are determined.
The self type is hidden from the outside; any attempt to apply _this, _inc or _display
as functions will raise a compile-time error. In other words, GHC defines a record selector
function only for fields whose type does not mention the existentially-quantified variables.
(This example used an underscore in the fields for which record selectors will not be defined,
but that is only programming style; GHC ignores them.)
To make use of these hidden fields, we need to create some helper functions:
main = do
display (inc counterA) -- prints "1"
display (inc (inc counterB)) -- prints "##"
Restrictions
There are several restrictions on the ways in which existentially-quantified constructors can
be used.
• When pattern matching, each pattern match introduces a new, distinct, type for each
existential type variable. These types cannot be unified with any other type, nor can
they escape from the scope of the pattern match. For example, these fragments are
incorrect:
f1 (MkFoo a f) = a
Here, the type bound by MkFoo “escapes”, because a is the result of f1. One way to see
why this is wrong is to ask what type f1 has:
What is this “a” in the result type? Clearly we don’t mean this:
The original program is just plain wrong. Here’s another sort of error
It’s ok to say a==b or p==q, but a==q is wrong because it equates the two distinct types
arising from the two Baz1 constructors.
• You can’t pattern-match on an existentially quantified constructor in a let or where group
of bindings. So this is illegal:
Reason: a value of type T must be represented as a pair of a dictionary for Ord t and
a value of type t. That contradicts the idea that newtype should have no concrete rep-
resentation. You can get just the same efficiency and effect by using data instead of
newtype. If there is no overloading involved, then there is more of a case for allowing
an existentially-quantified newtype, because the data version does carry an implemen-
tation cost, but single-field existentially quantified constructors aren’t much use. So the
simple restriction (no existential stuff on newtype) stands, unless there are convincing
reasons to change it.
• You can’t use deriving to define instances of a data type with existentially quantified
data constructors. Reason: in most cases it would not make sense. For example:;
data T = forall a. MkT [a] deriving( Eq )
To derive Eq in the standard way we would need to have equality between the single
component of two MkT constructors:
instance Eq T where
(MkT a) == (MkT b) = ???
But a and b have distinct types, and so can’t be compared. It’s just about possible to imag-
ine examples in which the derived instance would make sense, but it seems altogether
simpler simply to prohibit such declarations. Define your own instances!
GADTSyntax
Since 7.2.1
Allow the use of GADT syntax in data type definitions (but not GADTs themselves; for
this see GADTs (page 296))
When the GADTSyntax extension is enabled, GHC allows you to declare an algebraic data type
by giving the type signatures of constructors explicitly. For example:
data Maybe a where
Nothing :: Maybe a
Just :: a -> Maybe a
The form is called a “GADT-style declaration” because Generalised Algebraic Data Types, de-
scribed in Generalised Algebraic Data Types (GADTs) (page 296), can only be declared using
this form.
Notice that GADT-style syntax generalises existential types (Existentially quantified data con-
structors (page 286)). For example, these two declarations are equivalent:
Any data type that can be declared in standard Haskell 98 syntax can also be declared using
GADT-style syntax. The choice is largely stylistic, but GADT-style declarations differ in one
important respect: they treat class constraints on the data constructors differently. Specifi-
cally, if the constructor is given a type-class context, that context is made available by pattern
matching. For example:
A use of MkSet as a constructor (e.g. in the definition of makeSet) gives rise to a (Eq a)
constraint, as you would expect. The new feature is that pattern-matching on MkSet (as in the
definition of insert) makes available an (Eq a) context. In implementation terms, the MkSet
constructor has a hidden field that stores the (Eq a) dictionary that is passed to MkSet; so
when pattern-matching that dictionary becomes available for the right-hand side of the match.
In the example, the equality dictionary is used to satisfy the equality constraint generated by
the call to elem, so that the type of insert itself has no Eq constraint.
For example, one possible application is to reify dictionaries:
data NumInst a
= Num a => MkNumInst (NumInst a)
Notice that, unlike the situation when declaring an existential, there is no forall, because the
Num constrains the data type’s universally quantified type variable a. A constructor may have
both universal and existential type variables: for example, the following two declarations are
equivalent:
data T1 a
= forall b. (Num a, Eq b) => MkT1 a b
data T2 a where
MkT2 :: (Num a, Eq b) => a -> b -> T2 a
All this behaviour contrasts with Haskell 98’s peculiar treatment of contexts on a data type
declaration (Section 4.2.1 of the Haskell 98 Report). In Haskell 98 the definition
gives MkSet' the same type as MkSet above. But instead of making available an (Eq a) con-
straint, pattern-matching on MkSet' requires an (Eq a) constraint! GHC faithfully imple-
ments this behaviour, odd though it is. But for GADT-style declarations, GHC’s behaviour is
much more useful, as well as much more intuitive.
To make more precise what is and what is not permitted inside of a GADT-style constructor, we
provide a BNF-style grammar for GADT below. Note that this grammar is subject to change
in the future.
Where:
• btype is a type that is not allowed to have an outermost forall/=> unless it is surrounded
by parentheses. For example, forall a. a and Eq a => a are not legal btypes, but
(forall a. a) and (Eq a => a) are legal.
• ctype is a btype that has no restrictions on an outermost forall/=>, so forall a. a
and Eq a => a are legal ctypes.
• return_type is a type that is not allowed to have foralls, =>s, or ->s.
This is a simplified grammar that does not fully delve into all of the implementation details of
GHC’s parser (such as the placement of Haddock comments), but it is sufficient to attain an
understanding of what is syntactically allowed. Some further various observations about this
grammar:
• GADT constructor types are currently not permitted to have nested foralls or =>s.
(e.g., something like MkT :: Int -> forall a. a -> T would be rejected.) As a re-
sult, gadt_sig puts all of its quantification and constraints up front with opt_forall
and opt_context. Note that higher-rank foralls and =>s are only permitted if they do
not appear directly to the right of a function arrow in a prefix_gadt_body. (e.g., some-
thing like MkS :: Int -> (forall a. a) -> S is allowed, since parentheses separate
the forall from the ->.)
• Furthermore, GADT constructors do not permit outermost parentheses that surround the
opt_forall or opt_ctxt, if at least one of them are used. For example, MkU :: (forall
a. a -> U) would be rejected, since it would treat the forall as being nested.
Note that it is acceptable to use parentheses in a prefix_gadt_body. For instance, MkV1
:: forall a. (a) -> (V1) is acceptable, as is MkV2 :: forall a. (a -> V2).
• The function arrows in a prefix_gadt_body, as well as the function arrow in a
record_gadt_body, are required to be used infix. For example, MkA :: (->) Int A
would be rejected.
• GHC uses the function arrows in a prefix_gadt_body and prefix_gadt_body to syntac-
tically demarcate the function and result types. Note that GHC does not attempt to be
clever about looking through type synonyms here. If you attempt to do this, for instance:
data B where
MkB :: C
Then GHC will interpret the return type of MkB to be C, and since GHC requires that the
return type must be headed by B, this will be rejected. On the other hand, it is acceptable
to use type synonyms within the argument and result types themselves, so the following
is permitted:
type B1 = Int
type B2 = B
data B where
MkB :: B1 -> B2
• GHC will accept any combination of !/~ and {-# UNPACK #-}/{-# NOUNPACK #-}, al-
though GHC will ignore some combinations. For example, GHC will produce a warning
if you write {-# UNPACK #-} ~Int and proceed as if you had written Int.
The rest of this section gives further details about GADT-style data type declarations.
• The result type of each data constructor must begin with the type constructor being
defined. If the result type of all constructors has the form T a1 ... an, where a1 ...
an are distinct type variables, then the data type is ordinary; otherwise is a generalised
data type (Generalised Algebraic Data Types (GADTs) (page 296)).
• As with other type signatures, you can give a single signature for several data construc-
tors. In this example we give a single signature for T1 and T2:
data T a where
T1,T2 :: a -> T a
T3 :: T a
• The type signature of each constructor is independent, and is implicitly universally quan-
tified as usual. In particular, the type variable(s) in the “data T a where” header have
no scope, and different constructors may have different universally-quantified type vari-
ables:
• A constructor signature may mention type class constraints, which can differ for different
constructors. For example, this is fine:
data T a where
T1 :: Eq b => b -> b -> T b
T2 :: (Show c, Ix c) => c -> [c] -> T c
When pattern matching, these constraints are made available to discharge constraints
in the body of the match. For example:
f :: T a -> String
f (T1 x y) | x==y = "yes"
| otherwise = "no"
f (T2 a b) = show a
Note that f is not overloaded; the Eq constraint arising from the use of == is discharged
by the pattern match on T1 and similarly the Show constraint arising from the use of
show.
• Unlike a Haskell-98-style data type declaration, the type variable(s) in the “data Set a
where” header have no scope. Indeed, one can write a kind signature instead:
The type variables (if given) may be explicitly kinded, so we could also write the header
for Foo like this:
• You can use strictness annotations, in the obvious places in the constructor type:
• You can use a deriving clause on a GADT-style data type declaration. For example, these
two declarations are equivalent
• The type signature may have quantified type variables that do not appear in the result
type:
Here the type variable a does not appear in the result type of either constructor. Although
it is universally quantified in the type of the constructor, such a type variable is often
called “existential”. Indeed, the above declaration declares precisely the same type as
the data Foo in Existentially quantified data constructors (page 286).
The type may contain a class context too, of course:
As usual, for every constructor that has a field f, the type of field f must be the same
(modulo alpha conversion). The Child constructor above shows that the signature may
have a context, existentially-quantified variables, and strictness annotations, just as in
the non-record case. (NB: the “type” that follows the double-colon is not really a type,
because of the record syntax and strictness annotations. A “type” of this form can appear
only in a constructor signature.)
• Record updates are allowed with GADT-style declarations, only fields that have the fol-
lowing property: the type of the field mentions no existential type variables.
• As in the case of existentials declared using the Haskell-98-like record syntax (Record
Constructors (page 288)), record-selector functions are generated only for those fields
that have well-typed selectors. Here is the example of that section, in GADT-style syntax:
As before, only one selector function is generated here, that for tag. Nevertheless, you
can still use all the field names in pattern matching and record construction.
• In a GADT-style data type declaration there is no obvious way to specify that a data con-
structor should be infix, which makes a difference if you derive Show for the type. (Data
constructors declared infix are displayed infix by the derived show.) So GHC implements
the following design: a data constructor declared in a GADT-style data type declaration
is displayed infix by Show iff (a) it is an operator symbol, (b) it has two arguments, (c) it
has a programmer-supplied fixity declaration. For example
infix 6 (:--:)
data T a where
(:--:) :: Int -> Bool -> T Int
GADTs
Implies MonoLocalBinds (page 449), GADTSyntax (page 290)
Since 6.8.1
Allow use of Generalised Algebraic Data Types (GADTs).
Generalised Algebraic Data Types generalise ordinary algebraic data types by allowing con-
structors to have richer return types. Here is an example:
Notice that the return type of the constructors is not always Term a, as is the case with
ordinary data types. This generality allows us to write a well-typed eval function for these
Terms:
The key point about GADTs is that pattern matching causes type refinement. For example, in
the right hand side of the equation
the type a is refined to Int. That’s the whole point! A precise specification of the type rules is
beyond what this user manual aspires to, but the design closely follows that described in the
paper Simple unification-based type inference for GADTs, (ICFP 2006). The general principle
is this: type refinement is only carried out based on user-supplied type annotations. So if no
type signature is supplied for eval, no type refinement happens, and lots of obscure error
messages will occur. However, the refinement is quite general. For example, if we had:
the pattern match causes the type a to be refined to Int (because of the type of the construc-
tor Lit), and that refinement also applies to the type of j, and the result type of the case
expression. Hence the addition i+j is legal.
These and many other examples are given in papers by Hongwei Xi, and Tim Sheard. There is
a longer introduction on the wiki, and Ralf Hinze’s Fun with phantom types also has a number
of examples. Note that papers may use different notation to that implemented in GHC.
The rest of this section outlines the extensions to GHC that support GADTs. The extension
is enabled with GADTs (page 296). The GADTs (page 296) extension also sets GADTSyntax
(page 290) and MonoLocalBinds (page 449).
• A GADT can only be declared using GADT-style syntax (Declaring data types with explicit
constructor signatures (page 290)); the old Haskell 98 syntax for data declarations al-
ways declares an ordinary data type. The result type of each constructor must begin
with the type constructor being defined, but for a GADT the arguments to the type con-
structor can be arbitrary monotypes. For example, in the Term data type above, the type
of each constructor must end with Term ty, but the ty need not be a type variable (e.g.
the Lit constructor).
• It is permitted to declare an ordinary algebraic data type using GADT-style syntax. What
makes a GADT into a GADT is not the syntax, but rather the presence of data constructors
whose result type is not just T a b.
• You cannot use a deriving clause for a GADT; only for an ordinary data type.
• As mentioned in Declaring data types with explicit constructor signatures (page 290),
record syntax is supported. For example:
, tru :: Term a
, fls :: Term a
} -> Term a
However, for GADTs there is the following additional constraint: every constructor that
has a field f must have the same result type (modulo alpha conversion) Hence, in the
above example, we cannot merge the num and arg fields above into a single name. Al-
though their field types are both Term Int, their selector functions actually have differ-
ent types:
See Field selectors and TypeApplications (page 356) for a full description of how the
types of top-level field selectors are determined.
• When pattern-matching against data constructors drawn from a GADT, for example in a
case expression, the following rules apply:
– The type of the scrutinee must be rigid.
– The type of the entire case expression must be rigid.
– The type of any free variable mentioned in any of the case alternatives must be rigid.
A type is “rigid” if it is completely known to the compiler at its binding site. The easiest
way to ensure that a variable a rigid type is to give it a type signature. For more precise
details see Simple unification-based type inference for GADTs. The criteria implemented
by GHC are given in the Appendix.
TypeFamilies
Implies MonoLocalBinds (page 449), KindSignatures (page 435), Explicit-
Namespaces (page 282)
Since 6.8.1
Allow use and definition of indexed type and data families.
Indexed type families form an extension to facilitate type-level programming. Type families
are a generalisation of associated data types [AssocDataTypes2005] (page 637) and associ-
ated type synonyms [AssocTypeSyn2005] (page 637) Type families themselves are described
in Schrijvers 2008 [TypeFamilies2008] (page 637). Type families essentially provide type-
indexed data types and named functions on types, which are useful for generic programming
and highly parameterised library interfaces as well as interfaces with enhanced static infor-
mation, much like dependent types. They might also be regarded as an alternative to func-
tional dependencies, but provide a more functional style of type-level programming than the
relational style of functional dependencies.
Indexed type families, or type families for short, are type constructors that represent sets
of types. Set members are denoted by supplying the type family constructor with type pa-
rameters, which are called type indices. The difference between vanilla parametrised type
constructors and family constructors is much like between parametrically polymorphic func-
tions and (ad-hoc polymorphic) methods of type classes. Parametric polymorphic functions
behave the same at all type instances, whereas class methods can change their behaviour
in dependence on the class type parameters. Similarly, vanilla type constructors imply the
same data representation for all type instances, but family constructors can have varying
representation types for varying type indices.
Indexed type families come in three flavours: data families, open type synonym families, and
closed type synonym families. They are the indexed family variants of algebraic data types and
type synonyms, respectively. The instances of data families can be data types and newtypes.
Type families are enabled by the language extension TypeFamilies (page 298). Additional
information on the use of type families in GHC is available on the Haskell wiki page on type
families.
Data families
Data families appear in two flavours: (1) they can be defined on the toplevel or (2) they can
appear inside type classes (in which case they are known as associated types). The former is
the more general variant, as it lacks the requirement for the type-indexes to coincide with the
class parameters. However, the latter can lead to more clearly structured code and compiler
warnings if some type instances were - possibly accidentally - omitted. In the following, we
always discuss the general toplevel form first and then cover the additional constraints placed
on associated types.
The special family distinguishes family from standard data declarations. The result kind
annotation is optional and, as usual, defaults to Type if omitted. An example is
data family Array e
Named arguments can also be given explicit kind signatures if needed. Just as with GADT
declarations (page 296) named arguments are entirely optional, so that we can declare Array
alternatively with
data family Array :: Type -> Type
Unlike with ordinary data definitions, the result kind of a data family does not need to be Type.
It can alternatively be:
• Of the form TYPE r for some r (see Levity polymorphism (page 334)). For example:
data family DF1 :: TYPE IntRep
data family DF2 (r :: RuntimeRep) :: TYPE r
data family DF3 :: Type -> TYPE WordRep
• A bare kind variable (with PolyKinds (page 319) enabled). For example:
data family DF4 :: k
data family DF5 (a :: k) :: k
data family DF6 :: (k -> Type) -> k
Data instances’ kinds must end in Type, however. This restriction is slightly relaxed when the
UnliftedNewtypes (page 477) extension is enabled, as it permits a newtype instance‘s kind
to end in TYPE r for some r.
Instance declarations of data and newtype families are very similar to standard data and new-
type declarations. The only two differences are that the keyword data or newtype is followed
by instance and that some or all of the type arguments can be non-variable types, but may
not contain forall types or type synonym families. However, data families are generally al-
lowed in type parameters, and type synonyms are allowed as long as they are fully applied
and expand to a type that is itself admissible - exactly as this is required for occurrences of
type synonyms in class instance parameters. For example, the Either instance for GMap is
In this example, the declaration has only one variant. In general, it can be any number.
When ExplicitForAll (page 431) is enabled, type and kind variables used on the left hand
side can be explicitly bound. For example:
When an explicit forall is present, all type and kind variables mentioned which are not
already in scope must be bound by the forall:
When the flag -Wunused-type-patterns (page 101) is enabled, type variables that are men-
tioned in the patterns on the left hand side, but not used on the right hand side are reported.
Variables that occur multiple times on the left hand side are also considered used. To suppress
the warnings, unused variables should be either replaced or prefixed with underscores. Type
variables starting with an underscore (_x) are otherwise treated as ordinary type variables.
This resembles the wildcards that can be used in Partial Type Signatures (page 444). However,
there are some differences. No error messages reporting the inferred types are generated,
nor does the extension PartialTypeSignatures (page 444) have any effect.
A type or kind variable explicitly bound using ExplicitForAll (page 431) but not used on the
left hand side will generate an error, not a warning.
Data and newtype instance declarations are only permitted when an appropriate family dec-
laration is in scope - just as a class instance declaration requires the class declaration to be
visible. Moreover, each instance declaration has to conform to the kind determined by its
family declaration. This implies that the number of parameters of an instance declaration
matches the arity determined by the kind of the family.
A data family instance declaration can use the full expressiveness of ordinary data or newtype
declarations:
• Although, a data family is introduced with the keyword “data”, a data family instance
can use either data or newtype. For example:
data family T a
data instance T Int = T1 Int | T2 Bool
newtype instance T Char = TC Bool
• A data instance can use GADT syntax for the data constructors, and indeed can define
a GADT. For example:
data family G a b
data instance G [a] b where
G1 :: c -> G [Int] b
G2 :: G [a] Bool
• You can use a deriving clause on a data instance or newtype instance declaration.
Even if data families are defined as toplevel declarations, functions that perform different
computations for different family instances may still need to be defined as methods of type
classes. In particular, the following is not possible:
data family T a
data instance T Int = A
data instance T Char = B
foo :: T a -> Int
foo A = 1
foo B = 2
Given the functionality provided by GADTs (Generalised Algebraic Data Types), it might seem
as if a definition, such as the above, should be feasible. However, type families - in contrast
to GADTs - are open; i.e., new instances can always be added, possibly in other modules. Sup-
porting pattern matching across different data instances would require a form of extensible
case construct.
The instance declarations of a data family used in a single program may not overlap at all,
independent of whether they are associated or not. In contrast to type class instances, this is
not only a matter of consistency, but one of type safety.
Synonym families
Type families appear in three flavours: (1) they can be defined as open families on the toplevel,
(2) they can be defined as closed families on the toplevel, or (3) they can appear inside type
classes (in which case they are known as associated type synonyms). Toplevel families are
more general, as they lack the requirement for the type-indexes to coincide with the class
parameters. However, associated type synonyms can lead to more clearly structured code
and compiler warnings if some type instances were - possibly accidentally - omitted. In the
following, we always discuss the general toplevel forms first and then cover the additional
constraints placed on associated types. Note that closed associated type synonyms do not
exist.
The special family distinguishes family from standard type declarations. The result kind
annotation is optional and, as usual, defaults to Type if omitted. An example is
type family Elem c
Parameters can also be given explicit kind signatures if needed. We call the number of pa-
rameters in a type family declaration, the family’s arity, and all applications of a type family
must be fully saturated with respect to that arity. This requirement is unlike ordinary type
synonyms and it implies that the kind of a type family is not sufficient to determine a family’s
arity, and hence in general, also insufficient to determine whether a type family application
is well formed. As an example, consider the following declaration:
type family F a b :: Type -> Type
-- F's arity is 2,
-- although its overall kind is Type -> Type -> Type -> Type
Given this declaration the following are examples of well-formed and malformed types:
F Char [Int] -- OK! Kind: Type -> Type
F Char [Int] Bool -- OK! Kind: Type
F IO Bool -- WRONG: kind mismatch in the first argument
F Bool -- WRONG: unsaturated application
The result kind annotation is optional and defaults to Type (like argument kinds) if omitted.
Polykinded type families can be declared using a parameter in the kind annotation:
type family F a :: k
In this case the kind parameter k is actually an implicit parameter of the type family.
At definition site, the arity determines what inputs can be matched on:
data PT (a :: Type)
Both F1 and F0 have kind forall k. k -> Type, but their arity differs.
At use sites, the arity determines if the definition can be used in a higher-rank scenario:
type HRK (f :: forall k. k -> Type) = (f Int, f Maybe, f True)
type H1 = HRK F0 -- OK
type H2 = HRK F1
-- Error:
-- • Expected kind ‘forall k. k -> Type’,
-- but ‘F1’ has kind ‘k0 -> Type’
-- • In the first argument of ‘HRK’, namely ‘F1’
-- In the type ‘HRK F1’
-- In the type declaration for ‘H2’
This is a consequence of the requirement that all applications of a type family must be fully
saturated with respect to their arity.
Instance declarations of type families are very similar to standard type synonym declarations.
The only two differences are that the keyword type is followed by instance and that some
or all of the type arguments can be non-variable types, but may not contain forall types or
type synonym families. However, data families are generally allowed, and type synonyms are
allowed as long as they are fully applied and expand to a type that is admissible - these are
the exact same requirements as for data instances. For example, the [e] instance for Elem is
Type arguments can be replaced with underscores (_) if the names of the arguments don’t
matter. This is the same as writing type variables with unique names. Unused type arguments
can be replaced or prefixed with underscores to avoid warnings when the -Wunused-type-
patterns (page 101) flag is enabled. The same rules apply as for Data instance declarations
(page 300).
Also in the same way as Data instance declarations (page 300), when ExplicitForAll
(page 431) is enabled, type and kind variables can be explicitly bound in a type instance
declaration.
Type family instance declarations are only legitimate when an appropriate family declaration
is in scope - just like class instances require the class declaration to be visible. Moreover,
each instance declaration has to conform to the kind determined by its family declaration,
and the number of type parameters in an instance declaration must match the number of
type parameters in the family declaration. Finally, the right-hand side of a type instance must
be a monotype (i.e., it may not include foralls) and after the expansion of all saturated vanilla
type synonyms, no synonyms, except family synonyms may remain.
A type family can also be declared with a where clause, defining the full set of equations for
that family. For example:
A closed type family’s equations are tried in order, from top to bottom, when simplifying a type
family application. In this example, we declare an instance for F such that F Int simplifies
to Double, F Bool simplifies to Char, and for any other type a that is known not to be Int or
Bool, F a simplifies to String. Note that GHC must be sure that a cannot unify with Int or
Bool in that last case; if a programmer specifies just F a in their code, GHC will not be able
to simplify the type. After all, a might later be instantiated with Int.
A closed type family’s equations have the same restrictions and extensions as the equations
for open type family instances. For instance, when ExplicitForAll (page 431) is enabled,
type or kind variables used on the left hand side of an equation can be explicitly bound, such
as in:
A closed type family may be declared with no equations. Such closed type families are opaque
type-level definitions that will never reduce, are not necessarily injective (unlike empty data
types), and cannot be given any instances. This is different from omitting the equations of
a closed type family in a hs-boot file, which uses the syntax where .., as in that case there
may or may not be equations given in the hs file.
There must be some restrictions on the equations of type families, lest we define an ambiguous
rewrite system. So, equations of open type families are restricted to be compatible. Two type
patterns are compatible if
1. all corresponding types and implicit kinds in the patterns are apart, or
2. the two patterns unify producing a substitution, and the right-hand sides are equal under
that substitution.
Two types are considered apart if, for all possible substitutions, the types cannot reduce to a
common reduct.
The first clause of “compatible” is the more straightforward one. It says that the patterns of
two distinct type family instances cannot overlap. For example, the following is disallowed:
The second clause is a little more interesting. It says that two overlapping type family in-
stances are allowed if the right-hand sides coincide in the region of overlap. Some examples
help here:
Note that this compatibility condition is independent of whether the type family is associated
or not, and it is not only a matter of consistency, but one of type safety.
For a polykinded type family, the kinds are checked for apartness just like types. For example,
the following is accepted:
type family J a :: k
type instance J Int = Bool
type instance J Int = Maybe
These instances are compatible because they differ in their implicit kind parameter; the first
uses Type while the second uses Type -> Type.
The definition for “compatible” uses a notion of “apart”, whose definition in turn relies on type
family reduction. This condition of “apartness”, as stated, is impossible to check, so we use
this conservative approximation: two types are considered to be apart when the two types
cannot be unified, even by a potentially infinite unifier. Allowing the unifier to be infinite
disallows the following pair of instances:
The type patterns in this pair equal if x is replaced by an infinite nesting of lists. Rejecting
instances such as these is necessary for type soundness.
Compatibility also affects closed type families. When simplifying an application of a closed
type family, GHC will select an equation only when it is sure that no incompatible previous
equation will ever apply. Here are some examples:
In the definition for F, the two equations are incompatible – their patterns are not apart, and
yet their right-hand sides do not coincide. Thus, before GHC selects the second equation, it
must be sure that the first can never apply. So, the type F a does not simplify; only a type such
as F Double will simplify to Char. In G, on the other hand, the two equations are compatible.
Thus, GHC can ignore the first equation when looking at the second. So, G a will simplify to
a.
Incompatibilities between closed type family equations can be displayed in :info (page 55)
when -fprint-axiom-incomps (page 81) is enabled.
However see Type, class and other declarations (page 31) for the overlap rules in GHCi.
UndecidableInstances
Relax restrictions on the decidability of type synonym family instances.
In order to guarantee that type inference in the presence of type families is decidable, we need
to place a number of additional restrictions on the formation of type instance declarations (c.f.,
Definition 5 (Relaxed Conditions) of “Type Checking with Open Type Functions”). Instance
declarations have the general form
type instance F t1 .. tn = t
When the name of a type argument of a data or type instance declaration doesn’t matter, it
can be replaced with an underscore (_). This is the same as writing a type variable with a
unique name.
This use of underscore for wildcard in a type pattern is exactly like pattern matching in the
term language, but is rather different to the use of a underscore in a partial type signature
(see Type Wildcards (page 445)).
A type variable beginning with an underscore is not treated specially in a type or data instance
declaration. For example:
Contrast this with the special treatment of named wildcards in type signatures (Named Wild-
cards (page 445)).
A data or type synonym family can be declared as part of a type class, thus:
class C a b c where
type T c a x :: Type
Here c and a are class parameters, but the type is also indexed on a third parameter x.
Associated instances
When an associated data or type synonym family instance is declared within a type class
instance, we (optionally) may drop the instance keyword in the family instance:
The data or type family instance for an associated type must follow the rule that the type
indexes corresponding to class parameters must be precisely the same as types given in the
instance head. For example:
• The instance for an associated type can be omitted in class instances. In that case,
unless there is a default instance (see Associated type synonym defaults (page 309)), the
corresponding instance type is not inhabited; i.e., only diverging expressions, such as
undefined, can assume the type.
• Although it is unusual, there (currently) can be multiple instances for an associated fam-
ily in a single instance declaration. For example, this is legitimate:
Here we give two data instance declarations, one in which the last parameter is [v], and
one for which it is Int. Since you cannot give any subsequent instances for (GMap Flob
...), this facility is most useful when the free indexed parameter is of a kind with a finite
number of alternatives (unlike Type).
• When ExplicitForAll (page 431) is enabled, type and kind variables can be explic-
itly bound in associated data or type family instances in the same way (and with the
same restrictions) as Data instance declarations (page 300) or Type instance declara-
tions (page 303). For example, adapting the above, the following is accepted:
It is possible for the class defining the associated type to specify a default for associated type
instances. So for example, this is OK:
In an instance declaration for the class, if no explicit type instance declaration is given for
the associated type, the default declaration is used instead, just as with default class methods.
Note the following points:
• The instance keyword is optional.
• There can be at most one default declaration for an associated type synonym.
• A default declaration is not permitted for an associated data type.
• The default declaration must mention only type variables on the left hand side, and type
variables may not be repeated on the left-hand side. The right hand side must mention
only type variables that are explicitly bound on the left hand side. This restriction is
relaxed for kind variables, however, as the right hand side is allowed to mention kind
variables that are implicitly bound on the left hand side.
Like with Associated instances (page 307), it is possible to explicitly bind type and kind
variables in default declarations with a forall by using the ExplicitForAll (page 431)
language extension.
• Unlike the associated type family declaration itself, the type variables of the default
instance are independent of those of the parent class.
Here are some examples:
type F3 a
type F3 [b] = b -- BAD; only type variables allowed on the
-- LHS, and the argument to F3 is
-- instantiated to [b], which is not
-- a bare type variable
type F4 x y
type F4 x x = x -- BAD; the type variable x is repeated on
-- the LHS
type F5 a
type F6 a :: [k]
type F6 a = ('[] :: [x]) -- OK; the kind variable x is implicitly
-- bound by an invisible kind pattern
-- on the LHS
type F7 a
type F7 a =
Proxy ('[] :: [x]) -- BAD; the kind variable x is not bound,
-- even by an invisible kind pattern
type F8 (x :: a) :: [a]
type F8 x = ('[] :: [a]) -- OK; the kind variable a is implicitly
-- bound by the kind signature of the
-- LHS type pattern
type F9 (a :: k)
type F9 a = Maybe a -- BAD; the kind variable k is
-- instantiated to Type, which is not
-- a bare kind variable
type F10 (a :: j) (b :: k)
type F10 (a :: z) (b :: z)
= Proxy a -- BAD; the kind variable z is repeated,
-- as both j and k are instantiated to z
type F11 a b
type forall a b. F11 a b = a -- OK; LHS type variables can be
-- explicitly bound with 'forall'
type F12 (a :: k)
type F12 @k a = Proxy a -- OK; visible kind application syntax is
-- permitted in default declarations
The visibility of class parameters in the right-hand side of associated family instances depends
solely on the parameters of the family. As an example, consider the simple class declaration
class C a b where
data T a
Only one of the two class parameters is a parameter to the data family. Hence, the following
instance declaration is invalid:
instance C [c] d where
data T [c] = MkT (c, d) -- WRONG!! 'd' is not in scope
Here, the right-hand side of the data instance mentions the type variable d that does not occur
in its left-hand side. We cannot admit such data instances as they would compromise type
safety.
Bear in mind that it is also possible for the right-hand side of an associated family instance
to contain kind parameters (by using the PolyKinds (page 319) extension). For instance, this
class and instance are perfectly admissible:
class C k where
type T :: k
Here, although the right-hand side (Nothing :: Maybe a) mentions a kind variable a which
does not occur on the left-hand side, this is acceptable, because a is implicitly bound by T‘s
kind pattern.
A kind variable can also be bound implicitly in a LHS type pattern, as in this example:
class C a where
type T (x :: a) :: [a]
In ('[] :: [Maybe a]), the kind variable a is implicitly bound by the kind signature of the
LHS type pattern x.
Associated type and data instance declarations do not inherit any context specified on the
enclosing instance. For type instance declarations, it is unclear what the context would mean.
For data instance declarations, it is unlikely a user would want the context repeated for every
data constructor. The only place where the context might likely be useful is in a deriving
clause of an associated data instance. However, even here, the role of the outer instance
context is murky. So, for clarity, we just stick to the rule above: the enclosing instance context
is ignored. If you need to use a non-trivial context on a derived instance, use a standalone
deriving (page 368) clause (at the top level).
The rules for export lists (Haskell Report Section 5.2) need adjustment for type families:
• The form T(..), where T is a data family, names the family T and all the in-scope con-
structors (whether in scope qualified or unqualified) that are data instances of T.
• The form T(..,ci,..,fj,..), where T is a data family, names T and the specified con-
structors ci and fields fj as usual. The constructors and field names must belong to
some data instance of T, but are not required to belong to the same instance.
• The form C(..), where C is a class, names the class C and all its methods and associated
types.
• The form C(..,mi,..,type Tj,..), where C is a class, names the class C, and the speci-
fied methods mi and associated types Tj. The types need a keyword “type” to distinguish
them from data constructors.
• Whenever there is no export list and a data instance is defined, the corresponding data
family type constructor is exported along with the new data constructors, regardless of
whether the data family is defined locally or in another module.
Examples
Exports the class, the associated type GMap and the member functions empty, lookup,
and insert. The data constructors of GMap (in this case GMapEither) are not exported.
• module GMap( GMapKey( type GMap, empty, lookup, insert ) )
Same as previous item, but also exports all the data constructors for GMap, namely
GMapEither.
• module GMap ( GMapKey( empty, lookup, insert), GMap(..) )
module Y where
import X
data instance D Int = D1 | D2
Module Y exports all the entities defined in Y, namely the data constructors D1 and D2,
and implicitly the data family D, even though it’s defined in X. This means you can write
import Y( D(D1,D2) ) without giving an explicit export list like this:
Instances
Family instances are implicitly exported, just like class instances. However, this applies only
to the heads of instances, not to the data constructors an instance defines.
Type families require us to extend the rules for the form of instance heads, which are given
in Relaxed rules for the instance head (page 409). Specifically:
• Data type families may appear in an instance head
• Type synonym families may not appear (at all) in an instance head
The reason for the latter restriction is that there is no way to check for instance matching.
Consider
type family F a
type instance F Bool = Int
class C a
instance C Int
instance C (F a)
Now a constraint (C (F Bool)) would match both instances. The situation is especially bad
because the type instance for F Bool might be in another module, or even in a module that
is not yet written.
However, type class instances of instances of data families can be defined much like any other
data type. For example, we can say
Note that class instances are always for particular instances of a data family and never for
an entire family as a whole. This is for essentially the same reasons that we cannot define
a toplevel function that performs pattern matching on the data constructors of different in-
stances of a single type family. It would require a form of extensible case construct.
Data instance declarations can also have deriving clauses. For example, we can write
TypeFamilyDependencies
Implies TypeFamilies (page 298)
Since 8.0.1
Allow functional dependency annotations on type families. This allows one to define
injective type families.
Starting with GHC 8.0 type families can be annotated with injectivity information. This infor-
mation is then used by GHC during type checking to resolve type ambiguities in situations
where a type variable appears only under type family applications. Consider this contrived
example:
type family Id a
type instance Id Int = Int
type instance Id Bool = Bool
id :: Id t -> Id t
id x = x
Here the definition of id will be rejected because type variable t appears only under type
family applications and is thus ambiguous. But this code will be accepted if we tell GHC that
Id is injective, which means it will be possible to infer t at call sites from the type of the
argument:
The injectivity annotation is added after the type family head and consists of two parts:
• a type variable that names the result of a type family. Syntax: = tyvar or = (tyvar ::
kind). The type variable must be fresh.
• an injectivity annotation of the form | A -> B, where A is the result type variable (see
previous bullet) and B is a list of argument type and kind variables in which type family is
injective. It is possible to omit some variables if the type family is not injective in them.
Examples:
For open and closed type families it is OK to name the result but skip the injectivity annotation.
This is not the case for associated type synonyms, where the named result without injectivity
annotation will be interpreted as associated type synonym default.
Once the user declares type family to be injective GHC must verify that this declaration is
correct, i.e., that type family equations don’t violate the injectivity annotation. A general idea
is that if at least one equation (bullets (1), (2) and (3) below) or a pair of equations (bullets (4)
and (5) below) violates the injectivity annotation then a type family is not injective in a way
the user claims and an error is reported. In the bullets below RHS refers to the right-hand
side of the type family equation being checked for injectivity. LHS refers to the arguments of
that type family equation. Below are the rules followed when checking injectivity of a type
family:
1. If a RHS of a type family equation is a type family application GHC reports that the type
family is not injective.
2. If a RHS of a type family equation is a bare type variable we require that all LHS variables
(including implicit kind variables) are also bare. In other words, this has to be a sole
equation of that type family and it has to cover all possible patterns. If the patterns are
not covering GHC reports that the type family is not injective.
3. If a LHS type variable that is declared as injective is not mentioned on injective position in
the RHS GHC reports that the type family is not injective. Injective position means either
argument to a type constructor or injective argument to a type family. Type inference can
potentially loop when looking under injective type families in the RHS, so this requires
UndecidableInstances (page 412); GHC suggests enabling the flag when it is necessary.
4. Open type families Open type families are typechecked incrementally. This means that
when a module is imported type family instances contained in that module are checked
against instances present in already imported modules.
A pair of an open type family equations is checked by attempting to unify their RHSs.
If the RHSs don’t unify this pair does not violate injectivity annotation. If unification
succeeds with a substitution then LHSs of unified equations must be identical under
that substitution. If they are not identical then GHC reports that the type family is not
injective.
5. In a closed type family all equations are ordered and in one place. Equations are also
checked pair-wise but this time an equation has to be paired with all the preceding
equations. Of course a single-equation closed type family is trivially injective (unless (1),
(2) or (3) above holds).
When checking a pair of closed type family equations GHC tried to unify their RHSs. If
they don’t unify this pair of equations does not violate injectivity annotation. If the RHSs
can be unified under some substitution (possibly empty) then either the LHSs unify under
the same substitution or the LHS of the latter equation is subsumed by earlier equations.
If neither condition is met GHC reports that a type family is not injective.
Note that for the purpose of injectivity check in bullets (4) and (5) GHC uses a special variant
of unification algorithm that treats type family applications as possibly unifying with anything.
DataKinds
Since 7.4.1
Allow promotion of data types to kind level.
This section describes data type promotion, an extension to the kind system that complements
kind polymorphism. It is enabled by DataKinds (page 315), and described in more detail in
the paper Giving Haskell a Promotion, which appeared at TLDI 2012.
Motivation
Standard Haskell has a rich type language. Types classify terms and serve to avoid many
common programming mistakes. The kind language, however, is relatively simple, distin-
guishing only regular types (kind Type) and type constructors (e.g. kind Type -> Type ->
Type). In particular when using advanced type system features, such as type families (Type
families (page 298)) or GADTs (Generalised Algebraic Data Types (GADTs) (page 296)), this
simple kind system is insufficient, and fails to prevent simple errors. Consider the example
of type-level natural numbers, and length-indexed vectors:
data Ze
data Su n
The kind of Vec is Type -> Type -> Type. This means that, e.g., Vec Int Char is a well-
kinded type, even though this is not what we intend when defining length-indexed vectors.
With DataKinds (page 315), the example above can then be rewritten to:
data Nat = Ze | Su Nat
With the improved kind of Vec, things like Vec Int Char are now ill-kinded, and GHC will
report an error.
Overview
With DataKinds (page 315), GHC automatically promotes every datatype to be a kind and its
(value) constructors to be type constructors. The following types
data Nat = Zero | Succ Nat
data Sum a b = L a | R b
give rise to the following kinds and type constructors (where promoted constructors are pre-
fixed by a tick '):
Nat :: Type
'Zero :: Nat
'Succ :: Nat -> Nat
Virtually all data constructors, even those with rich kinds, can be promoted. There are only
a couple of exceptions to this rule:
• Data family instance constructors cannot be promoted at the moment. GHC’s type theory
just isn’t up to the task of promoting data families, which requires full dependent types.
• Data constructors with contexts that contain non-equality constraints cannot be pro-
moted. For example:
MkFoo1 and MkFoo2 can be promoted, since their contexts only involve equality-oriented
constraints. However, MkFoo3‘s context contains a non-equality constraint Show a, and
thus cannot be promoted.
In the examples above, all promoted constructors are prefixed with a single quote mark '.
This mark tells GHC to look in the data constructor namespace for a name, not the type
(constructor) namespace. Consider
data P = MkP -- 1
data Prom = P -- 2
We can thus distinguish the type P (which has a constructor MkP) from the promoted data
constructor 'P (of kind Prom).
As a convenience, GHC allows you to omit the quote mark when the name is unambiguous.
However, our experience has shown that the quote mark helps to make code more readable
and less error-prone. GHC thus supports -Wunticked-promoted-constructors (page 99)
that will warn you if you use a promoted data constructor without a preceding quote mark.
Just as in the case of Template Haskell (Syntax (page 450)), GHC gets confused if you put a
quote mark before a data constructor whose second character is a quote mark. In this case,
just put a space between the promotion quote and the data constructor:
data T = A'
type S = 'A' -- ERROR: looks like a character
type R = ' A' -- OK: promoted `A'`
With DataKinds (page 315), Haskell’s list and tuple types are natively promoted to kinds, and
enjoy the same convenient syntax at the type level, albeit prefixed with a quote:
For type-level lists of two or more elements, such as the signature of foo2 above, the quote
may be omitted because the meaning is unambiguous. But for lists of one or zero elements
(as in foo0 and foo1), the quote is required, because the types [] and [Int] have existing
meanings in Haskell.
Note: The declaration for HCons also requires TypeOperators (page 284) because of infix
type operator (':)
Note that we do promote existential data constructors that are otherwise suitable. For exam-
ple, consider the following:
Both the type Ex and the data constructor MkEx get promoted, with the polymorphic kind 'MkEx
:: forall k. k -> Ex. Somewhat surprisingly, you can write a type family to extract the
member of a type-level existential:
At first blush, UnEx seems poorly-kinded. The return kind k is not mentioned in the arguments,
and thus it would seem that an instance would have to return a member of k for any k. How-
ever, this is not the case. The type family UnEx is a kind-indexed type family. The return kind
k is an implicit parameter to UnEx. The elaborated definitions are as follows (where implicit
parameters are denoted by braces):
Thus, the instance triggers only when the implicit parameter to UnEx matches the implicit
parameter to MkEx. Because k is actually a parameter to UnEx, the kind is not escaping the
existential, and the above code is valid.
See also #7347.
TypeInType
Implies PolyKinds (page 319), DataKinds (page 315), KindSignatures
(page 435)
Since 8.0.1
The extension TypeInType (page 319) is now deprecated: its sole effect is to switch
on PolyKinds (page 319) (and hence KindSignatures (page 435)) and DataKinds
(page 315).
PolyKinds
Implies KindSignatures (page 435)
Since 7.4.1
Allow kind polymorphic types.
This section describes GHC’s kind system, as it appears in version 8.0 and beyond. The kind
system as described here is always in effect, with or without extensions, although it is a con-
servative extension beyond standard Haskell. The extensions above simply enable syntax and
tweak the inference algorithm to allow users to take advantage of the extra expressiveness
of GHC’s kind system.
In Haskell 98, the inferred kind for App is (Type -> Type) -> Type -> Type. But this
is overly specific, because another suitable Haskell 98 kind for App is ((Type -> Type) -
> Type) -> (Type -> Type) -> Type, where the kind assigned to a is Type -> Type. In-
deed, without kind signatures (KindSignatures (page 435)), it is necessary to use a dummy
constructor to get a Haskell compiler to infer the second kind. With kind polymorphism
(PolyKinds (page 319)), GHC infers the kind forall k. (k -> Type) -> k -> Type for App,
which is its most general kind.
Thus, the chief benefit of kind polymorphism is that we can now infer these most general
kinds and use App at a variety of kinds:
data T a = MkT (a Int) -- `a` is inferred to have kind (Type -> Type)
App T Maybe -- `k` is instantiated to (Type -> Type)
Overview of Type-in-Type
GHC 8 extends the idea of kind polymorphism by declaring that types and kinds are indeed
one and the same. Nothing within GHC distinguishes between types and kinds. Another way
of thinking about this is that the type Bool and the “promoted kind” Bool are actually identical.
(Note that term True and the type 'True are still distinct, because the former can be used
in expressions and the latter in types.) This lack of distinction between types and kinds is a
hallmark of dependently typed languages. Full dependently typed languages also remove the
difference between expressions and types, but doing that in GHC is a story for another day.
One simplification allowed by combining types and kinds is that the type of Type is just Type.
It is true that the Type :: Type axiom can lead to non-termination, but this is not a problem in
GHC, as we already have other means of non-terminating programs in both types and expres-
sions. This decision (among many, many others) does mean that despite the expressiveness
of GHC’s type system, a “proof” you write in Haskell is not an irrefutable mathematical proof.
GHC promises only partial correctness, that if your programs compile and run to completion,
their results indeed have the types assigned. It makes no claim about programs that do not
finish in a finite amount of time.
To learn more about this decision and the design of GHC under the hood please see the paper
introducing this kind system to GHC/Haskell.
Generally speaking, when PolyKinds (page 319) is on, GHC tries to infer the most general
kind for a declaration. In many cases (for example, in a datatype declaration) the definition
has a right-hand side to inform kind inference. But that is not always the case. Consider
type family F a
Type family declarations have no right-hand side, but GHC must still infer a kind for F. Since
there are no constraints, it could infer F :: forall k1 k2. k1 -> k2, but that seems too
polymorphic. So GHC defaults those entirely-unconstrained kind variables to Type and we get
F :: Type -> Type. You can still declare F to be kind-polymorphic using kind signatures:
type family F1 a -- F1 :: Type -> Type
type family F2 (a :: k) -- F2 :: forall k. k -> Type
type family F3 a :: k -- F3 :: forall k. Type -> k
type family F4 (a :: k1) :: k2 -- F4 :: forall k1 k2. k1 -> k2
The kind-polymorphism from the class declaration makes D1 kind-polymorphic, but not so D2;
and similarly F1, F2.
It is possible to get intricate dependencies among the type variables introduced in a type or
class declaration. Here is an example:
data T a (b :: k) c = MkT (a c)
After analysing this declaration, GHC will discover that a and c can be kind-polymorphic, with
a :: k2 -> Type and c :: k2. We thus infer the following kind:
T :: forall {k2 :: Type} (k :: Type). (k2 -> Type) -> k -> k2 -> Type
Note that k2 is placed before k, and that k is placed before a. Also, note that k2 is written
here in braces. As explained with TypeApplications (page 338) (Inferred vs. specified type
variables (page 338)), type and kind variables that GHC generalises over, but not written in
the original program, are not available for visible type application. (These are called inferred
variables.) Such variables are written in braces.
The general principle is this:
• Variables not available for type application come first.
• Then come variables the user has written, implicitly brought into scope in a type vari-
able’s kind.
• Lastly come the normal type variables of a declaration.
• Variables not given an explicit ordering by the user are sorted according to ScopedSort
(Ordering of specified variables (page 340)).
With the T example above, we could bind k after a; doing so would not violate dependency
concerns. However, it would violate our general principle, and so k comes first.
Sometimes, this ordering does not respect dependency. For example:
It must be that a and b have the same kind. Note also that b is implicitly declared in c‘s kind.
Thus, according to our general principle, b must come before k. However, b depends on k.
We thus reject T2 with a suitable error message.
In associated types, we order the type variables as if the type family was a top-level declara-
tion, ignoring the visibilities of the class’s type variable binders. Here is an example:
class C (a :: k) b where
type F (c :: j) (d :: Proxy m) a b
Note that the kind of a is specified in the kind of C but inferred in the kind of F.
The “general principle” described here is meant to make all this more predictable for users.
It would not be hard to extend GHC to relax this principle. If you should want a change here,
consider writing a proposal to do so.
CUSKs
Since 8.10.1
NB! This is a legacy feature, see StandaloneKindSignatures (page 324) for the modern re-
placement.
Just as in type inference, kind inference for recursive types can only use monomorphic recur-
sion. Consider this (contrived) example:
data T m a = MkT (m a) (T Maybe (m a))
-- GHC infers kind T :: (Type -> Type) -> Type -> Type
The recursive use of T forced the second argument to have kind Type. However, just as in
type inference, you can achieve polymorphic recursion by giving a complete user-supplied
kind signature (or CUSK) for T. A CUSK is present when all argument kinds and the result
kind are known, without any need for inference. For example:
data T (m :: k -> Type) :: k -> Type where
MkT :: m a -> T Maybe (m a) -> T m a
The complete user-supplied kind signature specifies the polymorphic kind for T, and this sig-
nature is used for all the calls to T including the recursive ones. In particular, the recursive
use of T is at kind Type.
What exactly is considered to be a “complete user-supplied kind signature” for a type con-
structor? These are the forms:
• For a datatype, every type variable must be annotated with a kind. In a GADT-style
declaration, there may also be a kind signature (with a top-level :: in the header), but
the presence or absence of this annotation does not affect whether or not the declaration
has a complete signature.
data T1 :: (k -> Type) -> k -> Type where ...
-- Yes; T1 :: forall k. (k->Type) -> k -> Type
• For a datatype with a top-level ::: all kind variables introduced after the :: must be
explicitly quantified.
• For a newtype, the rules are the same as they are for a data type unless UnliftedNew-
types (page 477) is enabled. With UnliftedNewtypes (page 477), the type constructor
only has a CUSK if a kind signature is present. As with a datatype with a top-level ::, all
kind variables introduced after the :: must be explicitly quantified
Note that in S2 and S3, the kind of the right-hand side is rather apparent, but it is still
not considered to have a complete signature – no inference can be done before detecting
the signature.
• An un-associated open type or data family declaration always has a CUSK; un-annotated
type variables default to kind Type:
• An associated type or data family declaration has a CUSK precisely if its enclosing class
has a CUSK.
• A closed type family has a complete signature when all of its type variables are annotated
and a return kind (with a top-level ::) is supplied.
It is possible to write a datatype that syntactically has a CUSK (according to the rules above)
but actually requires some inference. As a very contrived example, consider
data Proxy a -- Proxy :: forall k. k -> Type
data X (a :: Proxy k)
According to the rules above X has a CUSK. Yet, the kind of k is undetermined. It is thus
quantified over, giving X the kind forall k1 (k :: k1). Proxy k -> Type.
The detection of CUSKs is enabled by the CUSKs (page 322) flag, which is switched on by
default. This extension is scheduled for deprecation to be replaced with StandaloneKindSig-
natures (page 324).
StandaloneKindSignatures
Implies NoCUSKs (page 322)
Since 8.10.1
Just as in type inference, kind inference for recursive types can only use monomorphic recur-
sion. Consider this (contrived) example:
data T m a = MkT (m a) (T Maybe (m a))
-- GHC infers kind T :: (Type -> Type) -> Type -> Type
The recursive use of T forced the second argument to have kind Type. However, just as in
type inference, you can achieve polymorphic recursion by giving a standalone kind signature
for T:
type T :: (k -> Type) -> k -> Type
data T m a = MkT (m a) (T Maybe (m a))
The standalone kind signature specifies the polymorphic kind for T, and this signature is used
for all the calls to T including the recursive ones. In particular, the recursive use of T is at
kind Type.
While a standalone kind signature determines the kind of a type constructor, it does not deter-
mine its arity. This is of particular importance for type families and type synonyms, as they
cannot be partially applied. See Type family declarations (page 302) for more information
about arity.
The arity can be specified using explicit binders and inline kind annotations:
-- arity F0 = 0
type F0 :: forall k. k -> Type
type family F0 :: forall k. k -> Type
-- arity F1 = 1
type F1 :: forall k. k -> Type
type family F1 :: k -> Type
-- arity F2 = 2
type F2 :: forall k. k -> Type
type family F2 a :: Type
In absence of an inline kind annotation, the inferred arity includes all explicitly bound param-
eters and all immediately following invisible parameters:
-- arity FD1 = 1
type FD1 :: forall k. k -> Type
type FD1
-- arity FD2 = 2
type FD2 :: forall k. k -> Type
type FD2 a
Note that F0, F1, F2, FD1, and FD2 all have identical standalone kind signatures. The arity is
inferred from the type family header.
GHC requires that in the presence of a standalone kind signature, data declarations must
bind all their inputs. For example:
GADT-style data declarations may either bind their inputs or use an inline signature in addition
to the standalone kind signature:
On the other hand, type families are exempt from this rule:
Data families are tricky territory. Their headers are exempt from this rule, but their instances
are not:
Although all open type families are considered to have a complete user-supplied kind signa-
ture, we can relax this condition for closed type families, where we have equations on which
to perform kind inference. GHC will infer kinds for the arguments and result types of a closed
type family.
GHC supports kind-indexed type families, where the family matches both on the kind and
type. GHC will not infer this behaviour without a complete user-supplied kind signature, as
doing so would sometimes infer non-principal types. Indeed, we can see kind-indexing as a
form of polymorphic recursion, where a type is used at a kind other than its most general in
its own definition.
For example:
Consider the following example of a poly-kinded class and an instance for it:
class C a where
type F a
instance C b where
type F b = b -> b
In the class declaration, nothing constrains the kind of the type a, so it becomes a poly-kinded
type variable (a :: k). Yet, in the instance declaration, the right-hand side of the associated
type instance b -> b says that b must be of kind Type. GHC could theoretically propagate
this information back into the instance head, and make that instance declaration apply only
to type of kind Type, as opposed to types of any kind. However, GHC does not do this.
In short: GHC does not propagate kind information from the members of a class instance
declaration into the instance declaration head.
This lack of kind inference is simply an engineering problem within GHC, but getting it to work
would make a substantial change to the inference infrastructure, and it’s not clear the payoff
is worth it. If you want to restrict b‘s kind in the instance above, just use a kind signature in
the instance head.
When kind-checking a type, GHC considers only what is written in that type when figuring
out how to generalise the type’s kind.
For example, consider these definitions (with ScopedTypeVariables (page 436)):
GHC reports an error, saying that the kind of a should be a kind variable k, not Type. This is
because, by looking at the type signature forall a. Proxy a, GHC assumes a‘s kind should
be generalised, not restricted to be Type. The function definition is then rejected for being
more specific than its type signature.
Enabled by PolyKinds (page 319), GHC supports explicit kind quantification, as in these
examples:
Note that the second example has a forall that binds both a kind k and a type variable a of
kind k. In general, there is no limit to how deeply nested this sort of dependency can work.
However, the dependency must be well-scoped: forall (a :: k) k. ... is an error.
Consider the scoping rules for type synonyms and type family instances, such as these:
type TS a (b :: k) = <rhs>
type instance TF a (b :: k) = <rhs>
The basic principle is that all variables mentioned on the right hand side <rhs> must be bound
on the left hand side:
But there is one exception: free variables mentioned in the outermost kind signature on the
right hand side are quantified implicitly. Thus, in the following example the variables a, b,
and k are all in scope on the right hand side of S:
The reason for this exception is that there may be no other way to bind k. For example,
suppose we wanted S to have the following kind with an invisible parameter k:
In this case, we could not simply bind k on the left-hand side, as k would become a visible
parameter:
Note that we only look at the outermost kind signature to decide which variables to quantify
implicitly. As a counter-example, consider M1:
Here, the kind signature is hidden inside 'Just, and there is no outermost kind signature. We
can fix this example by providing an outermost kind signature:
Kind variables can also be quantified in visible positions. Consider the following two exam-
ples:
data ProxyKInvis (a :: k)
data ProxyKVis k (a :: k)
In the first example, the kind variable k is an invisible argument to ProxyKInvis. In other
words, a user does not need to instantiate k explicitly, as kind inference automatically deter-
mines what k should be. For instance, in ProxyKInvis True, k is inferred to be Bool. This is
reflected in the kind of ProxyKInvis:
This kind is similar to the kind of ProxyKInvis, but with a key difference: the type variables
quantified by the forall are followed by an arrow (->), not a dot (.). This is a visible, de-
pendent quantifier. It is visible in that the user must pass in a type for k explicitly, and it is
dependent in the sense that k appears later in the kind of ProxyKVis. As a counterpart, the
k binder in forall k. k -> Type can be thought of as an invisible, dependent quantifier.
GHC permits writing kinds with this syntax, provided that the ExplicitForAll and PolyKinds
language extensions are enabled. Just like the invisible forall, one can put explicit kind
signatures on visibly bound kind variables, so the following is syntactically valid:
Currently, the ability to write visible, dependent quantifiers is limited to kinds. Consequently,
visible dependent quantifiers are rejected in any context that is unambiguously the type of a
term. They are also rejected in the types of data constructors.
Kind-indexed GADTs
data G (a :: k) where
GInt :: G Int
GMaybe :: G Maybe
This datatype G is GADT-like in both its kind and its type. Suppose you have g :: G a, where
a :: k. Then pattern matching to discover that g is in fact GMaybe tells you both that k ~
(Type -> Type) and a ~ Maybe. The definition for G requires that PolyKinds (page 319) be
in effect, but pattern-matching on G requires no extension beyond GADTs (page 296). That
this works is actually a straightforward extension of regular GADTs and a consequence of the
fact that kinds and types are the same.
Note that the datatype G is used at different kinds in its body, and therefore that kind-indexed
GADTs use a form of polymorphic recursion. It is thus only possible to use this feature if
you have provided a complete user-supplied kind signature for the datatype (Complete user-
supplied kind signatures and polymorphic recursion (page 322)).
Higher-rank kinds
In concert with RankNTypes (page 342), GHC supports higher-rank kinds. Here is an example:
Note that hTestEquality takes two arguments where the type variable t is applied to types
of different kinds. That type variable must then be polykinded. Accordingly, the kind of
HTestEquality (the class) is (forall k. k -> Type) -> Constraint, a higher-rank kind.
A big difference with higher-rank kinds as compared with higher-rank types is that foralls
in kinds cannot be moved. This is best illustrated by example. Suppose we want to have an
instance of HTestEquality for (:~~:).
With the declaration of (:~~:) above, it gets kind forall k1 k2. k1 -> k2 -> Type. Thus,
the type (:~~:) a has kind k2 -> Type for some k2. GHC cannot then regeneralize this kind
to become forall k2. k2 -> Type as desired. Thus, the instance is rejected as ill-kinded.
To allow for such an instance, we would have to define (:~~:) as follows:
data (:~~:) :: forall k1. k1 -> forall k2. k2 -> Type where
HRefl :: a :~~: a
In this redefinition, we give an explicit kind for (:~~:), deferring the choice of k2 until after
the first argument (a) has been given. With this declaration for (:~~:), the instance for
HTestEquality is accepted.
Another difference between higher-rank kinds and types can be found in their treatment of
inferred and user-specified type variables. Consider the following program:
The kind of Foo‘s parameter is forall k. k -> Type, but the kind of Proxy is forall {k}.
k -> Type, where {k} denotes that the kind variable k is to be inferred, not specified by the
user. (See Visible type application (page 338) for more discussion on the inferred-specified
distinction). GHC does not consider forall k. k -> Type and forall {k}. k -> Type to
be equal at the kind level, and thus rejects Foo Proxy as ill-kinded.
Constraints in kinds
As kinds and types are the same, kinds can (with TypeInType (page 319)) contain type con-
straints. However, only equality constraints are supported.
Here is an example of a constrained kind:
The declarations above are accepted. However, if we add MkOther :: T Int, we get an error
that the equality constraint is not satisfied; Int is not a type literal. Note that explicitly quan-
tifying with forall a is necessary in order for T to typecheck (see Complete user-supplied
kind signatures and polymorphic recursion (page 322)).
StarIsType
Since 8.6.1
Treat the unqualified uses of the * type operator as nullary and desugar to
[Link].
The kind Type (imported from [Link]) classifies ordinary types. With StarIsType
(page 331) (currently enabled by default), * is desugared to Type, but using this legacy syntax
is not recommended due to conflicts with TypeOperators (page 284). This also applies to ★,
the Unicode variant of *.
If a type variable a in a datatype, class, or type family declaration depends on another such
variable k in the same declaration, two properties must hold:
• a must appear after k in the declaration, and
• k must appear explicitly in the kind of some type variable in that declaration.
The first bullet simply means that the dependency must be well-scoped. The second bullet
concerns GHC’s ability to infer dependency. Inferring this dependency is difficult, and GHC
currently requires the dependency to be made explicit, meaning that k must appear in the
kind of a type variable, making it obvious to GHC that dependency is intended. For example:
In the second declaration, GHC cannot immediately tell that k should be a dependent variable,
and so the declaration is rejected.
It is conceivable that this restriction will be relaxed in the future, but it is (at the time of writ-
ing) unclear if the difficulties around this scenario are theoretical (inferring this dependency
would mean our type system does not have principal types) or merely practical (inferring
this dependency is hard, given GHC’s implementation). So, GHC takes the easy way out and
requires a little help from the user.
A programmer may use forall in a type to introduce new quantified type variables. These
variables may depend on each other, even in the same forall. However, GHC requires that
the dependency be inferrable from the body of the forall. Here are some examples:
data Sing a
h :: forall k a. Sing k -> Sing a -> () -- No obvious relationship between k and a
h _ _ = g (MkProxy :: Proxy k a) -- This fails. We didn't know that a should have␣
,→kind k.
Note that in the last example, it’s impossible to learn that a depends on k in the body of the
forall (that is, the Sing k -> Sing a -> ()). And so GHC rejects the program.
Without PolyKinds (page 319), GHC refuses to generalise over kind variables. It thus defaults
kind variables to Type when possible; when this is not possible, an error is issued.
Here is an example of this in action:
In the last line, we use the promoted constructor 'MkCompose, which has kind
Now we must infer a type for z. To do so without generalising over kind variables, we must
default the kind variables of 'MkCompose. We can easily default a and b to Type, but f and g
would be ill-kinded if defaulted. The definition for z is thus an error.
With kind polymorphism, there is quite a bit going on behind the scenes that may be invisible
to a Haskell programmer. GHC supports several flags that control how types are printed in
error messages and at the GHCi prompt. See the discussion of type pretty-printing options
(page 80) for further details. If you are using kind polymorphism and are confused as to
why GHC is rejecting (or accepting) your program, we encourage you to turn on these flags,
especially -fprint-explicit-kinds (page 81).
With KindSignatures (page 435), we can give the kind of a datatype written in GADT-syntax
(see GADTSyntax (page 290)). For example:
There are a number of restrictions around these return kinds. The text below considers Un-
liftedNewtypes (page 477) and data families (enabled by TypeFamilies (page 298)). The
discussion also assumes familiarity with levity polymorphism (page 334).
1. data and data instance declarations must have return kinds that end in TYPE Lifte-
dRep. (Recall that Type is just a synonym for TYPE LiftedRep.) By “end in”, we refer to
the kind left over after all arguments (introduced either by forall or ->) are stripped
off and type synonyms expanded. Note that no type family expansion is done when per-
forming this check.
2. If UnliftedNewtypes (page 477) is enabled, then newtype and newtype instance decla-
rations must have return kinds that end in TYPE rep for some rep. The rep may mention
type families, but the TYPE must be apparent without type family expansion. (Type syn-
onym expansion is acceptable.)
If UnliftedNewtypes (page 477) is not enabled, then newtype and newtype instance
declarations have the same restrictions as data declarations.
3. A data or newtype instance actually can have two return kinds. The first is the kind
derived by applying the data family to the patterns provided in the instance declaration.
The second is given by a kind annotation. Both return kinds must satisfy the restrictions
above.
Examples:
type LR = LiftedRep
data T3 :: TYPE LR -- good: we look through type synonyms
-- assume -XUnliftedNewtypes
newtype T6 :: Type where ... -- good
newtype T7 :: TYPE (F Int) where ... -- good
newtype T8 :: G Int where ... -- bad
In order to allow full flexibility in how kinds are used, it is necessary to use the kind system
to differentiate between boxed, lifted types (normal, everyday types like Int and [Bool]) and
unboxed, primitive types (Unboxed types and primitive operations (page 473)) like Int#. We
thus have so-called levity polymorphism.
Here are the key definitions, all available from [Link]:
| ...
The idea is that we have a new fundamental type constant TYPE, which is parameterised by a
RuntimeRep. We thus get Int# :: TYPE 'IntRep and Bool :: TYPE 'LiftedRep. Anything
with a type of the form TYPE x can appear to either side of a function arrow ->. We can thus
say that -> has type TYPE r1 -> TYPE r2 -> TYPE 'LiftedRep. The result is always lifted
because all functions are lifted in GHC.
If GHC didn’t have to compile programs that run in the real world, that would be the end of
the story. But representation polymorphism can cause quite a bit of trouble for GHC’s code
generator. Consider
This seems like a generalisation of the standard $ operator. If we think about compiling this to
runnable code, though, problems appear. In particular, when we call bad, we must somehow
pass x into bad. How wide (that is, how many bits) is x? Is it a pointer? What kind of
register (floating-point or integral) should x go in? It’s all impossible to say, because x‘s type,
a :: TYPE r1 is levity polymorphic. We thus forbid such constructions, via the following
straightforward rule:
No variable may have a levity-polymorphic type.
This eliminates bad because the variable x would have a representation-polymorphic type.
However, not all is lost. We can still do this:
Here, only b is levity polymorphic. There are no variables with a levity-polymorphic type. And
the code generator has no trouble with this. Indeed, this is the true type of GHC’s $ operator,
slightly more general than the Haskell 98 version.
Because the code generator must store and move arguments as well as variables, the logic
above applies equally well to function arguments, which may not be levity-polymorphic.
Levity-polymorphic bottoms
We can use levity polymorphism to good effect with error and undefined, whose types are
given here:
These functions do not bind a levity-polymorphic variable, and so are accepted. Their poly-
morphism allows users to use these to conveniently stub out functions that return unboxed
types.
-fprint-explicit-runtime-reps
Print RuntimeRep parameters as they appear; otherwise, they are defaulted to 'Lifte-
dRep.
Most GHC users will not need to worry about levity polymorphism or unboxed types. For these
users, seeing the levity polymorphism in the type of $ is unhelpful. And thus, by default, it
is suppressed, by supposing all type variables of type RuntimeRep to be 'LiftedRep when
printing, and printing TYPE 'LiftedRep as Type (or * when StarIsType (page 331) is on).
Should you wish to see levity polymorphism in your types, enable the flag -fprint-explicit-
runtime-reps (page 336). For example,
ghci> :t ($)
($) :: (a -> b) -> a -> b
ghci> :set -fprint-explicit-runtime-reps
ghci> :t ($)
($)
:: forall (r :: [Link]) a (b :: TYPE r).
(a -> b) -> a -> b
GHC supports numeric and string literals at the type level, giving convenient access to a large
number of predefined type-level constants. Numeric literals are of kind Nat, while string
literals are of kind Symbol. This feature is enabled by the DataKinds (page 315) language
extension.
The kinds of the literals and all other low-level operations for this feature are defined in
modules [Link] and [Link]. Note that these modules define some type-level
operators that clash with their value-level counterparts (e.g. (+)). Import and export decla-
rations referring to these operators require an explicit namespace annotation (see Explicit
namespaces in import/export (page 282)).
Here is an example of using type-level numeric literals to provide a safe interface to a low-level
function:
import [Link]
import [Link]
import Foreign
Here is an example of using type-level string literals to simulate simple record operations:
data Label (l :: Symbol) = Get
Sometimes it is useful to access the value-level literal associated with a type-level literal. This
is done with the functions natVal and symbolVal. For example:
These functions are overloaded because they need to return a different result, depending on
the type at which they are instantiated.
-- instance KnownNat 0
-- instance KnownNat 1
-- instance KnownNat 2
-- ...
GHC discharges the constraint as soon as it knows what concrete type-level literal is being
used in the program. Note that this works only for literals and not arbitrary type expressions.
For example, a constraint of the form KnownNat (a + b) will not be simplified to (KnownNat
a,KnownNat b); instead, GHC will keep the constraint as is, until it can simplify a + b to a
constant value.
It is also possible to convert a run-time integer or string value to the corresponding type-level
literal. Of course, the resulting type literal will be unknown at compile-time, so it is hidden
in an existential type. The conversion may be performed using someNatVal for integers and
someSymbolVal for strings:
GHC 7.8 can evaluate arithmetic expressions involving type-level natural numbers. Such
expressions may be constructed using the type-families (+),(*),(^) for addition, multiplica-
tion, and exponentiation. Numbers may be compared using (<=?), which returns a promoted
boolean value, or (<=), which compares numbers as a constraint. For example:
At present, GHC is quite limited in its reasoning about arithmetic: it will only evaluate the
arithmetic type functions and compare the results— in the same way that it does for any other
type function. In particular, it does not know more general facts about arithmetic, such as
the commutativity and associativity of (+), for example.
However, it is possible to perform a bit of “backwards” evaluation. For example, here is how
we could get GHC to compute arbitrary logarithms at the type level:
TypeApplications
Since 8.0.1
Allow the use of type application syntax.
The TypeApplications (page 338) extension allows you to use visible type application in
expressions. Here is an example: show (read @Int "5"). The @Int is the visible type appli-
cation; it specifies the value of the type variable in read‘s type.
A visible type application is preceded with an @ sign. (To disambiguate the syntax, the @ must
be preceded with a non-identifier letter, usually a space. For example, read@Int 5 would
not parse.) It can be used whenever the full polymorphic type of the function is known. If
the function is an identifier (the common case), its type is considered known only when the
identifier has been given a type signature. If the identifier does not have a type signature,
visible type application cannot be used.
GHC also permits visible kind application, where users can declare the kind arguments to
be instantiated in kind-polymorphic cases. Its usage parallels visible type application in the
term level, as specified above.
GHC tracks a distinction between what we call inferred and specified type variables. Only
specified type variables are available for instantiation with visible type application. An exam-
ple illustrates this well:
g x y = (x == x) && (y == y)
The functions f and g have the same body, but only f is given a type signature. When GHC
is figuring out how to process a visible type application, it must know what variable to in-
stantiate. It thus must be able to provide an ordering to the type variables in a function’s
type.
If the user has supplied a type signature, as in f, then this is easy: we just take the ordering
from the type signature, going left to right and using the first occurrence of a variable to
choose its position within the ordering. Thus, the variables in f will be b, then a.
In contrast, there is no reliable way to do this for g; we will not know whether Eq a or Eq b
will be listed first in the constraint in g‘s type. In order to have visible type application be
robust between releases of GHC, we thus forbid its use with g.
We say that the type variables in f are specified, while those in g are inferred. The general
rule is this: if the user has written a type variable in the source program, it is specified; if not,
it is inferred.
This rule applies in datatype declarations, too. For example, if we have data Proxy a =
Proxy (and PolyKinds (page 319) is enabled), then a will be assigned kind k, where k is a
fresh kind variable. Because k was not written by the user, it will be unavailable for type
application in the type of the constructor Proxy; only the a will be available.
Inferred variables are printed in braces. Thus, the type of the data constructor Proxy from
the previous example is forall {k} (a :: k). Proxy a. We can observe this behavior in a
GHCi session:
<interactive>:1:1: error:
• Cannot apply expression of type ‘t0 a0 -> Int’
to a visible type argument ‘[]’
• In the expression: myLength2 @[]
Notice that since myLength1 was defined with an explicit type signature, :type +v (page 62)
reports that all of its type variables are available for type application. On the other hand,
myLength2 was not given a type signature. As a result, all of its type variables are surrounded
with braces, and trying to use visible type application with myLength2 fails.
Also note the use of :type +v (page 62) in the GHCi session above instead of :type (page 61).
This is because :type (page 61) gives you the type that would be inferred for a variable
assigned to the expression provided (that is, the type of x in let x = <expr>). As we saw
above with myLength2, this type will have no variables available to visible type application.
On the other hand, :type +v (page 62) gives you the actual type of the expression provided.
To illustrate this:
Using :type (page 61) might lead one to conclude that none of the type variables in
myLength1‘s type signature are available for type application. This isn’t true, however! Be
sure to use :type +v (page 62) if you want the most accurate information with respect to
visible type application properties.
In the simple case of the previous section, we can say that specified variables appear in left-
to-right order. However, not all cases are so simple. Here are the rules in the subtler cases:
• If an identifier’s type has a forall, then the order of type variables as written in the
forall is retained.
• If any of the variables depend on other variables (that is, if some of the variables are kind
variables), the variables are reordered so that kind variables come before type variables,
preserving the left-to-right order as much as possible. That is, GHC performs a stable
topological sort on the variables. Example:
While user-written type or kind variables are specified by default, GHC permits labelling these
variables as inferred. By writing the type variable binder in braces as {tyvar} or {tyvar
:: kind}, the new variable will be classified as inferred, not specified. Doing so gives the
programmer control over which variables can be manually instantiated and which can’t. Note
that the braces do not influence scoping: variables in braces are still brought into scope just
the same. Consider for example:
In this example, despite both variables appearing in a type signature, a is an inferred variable
while b is specified. This means that the expression myConst @Int has type forall {a}. a
-> Int -> a.
The braces are allowed in the following places:
• In the type signatures of functions, variables, class methods, as well as type annotations
on expressions. Consider the example above.
• In data constructor declarations, using the GADT syntax. Consider:
data T a where MkT :: forall {k} (a :: k). Proxy a -> T a
The constructor MkT defined in this example is kind polymorphic, which is emphasized
to the reader by explicitly abstracting over the k variable. As this variable is marked as
inferred, it can not be manually instantiated.
• In existential variable quantifications, e.g.:
data HList = HNil
| forall {a}. HCons a HList
Note that in this example, a is a universal variable in the data type T, where b is exis-
tential. When writing the pattern synonym, both types are allowed to be specified or
inferred.
• On the right-hand side of a type synonym, e.g.:
type Foo = forall a {b}. Either a b
The reason for this is, essentially, that none of these define a new construct. This means
that no new type is being defined where specificity could play a role.
• On the left-hand sides of type declarations, such as classes, data types, etc.
RankNTypes
Implies ExplicitForAll (page 431)
Since 6.8.1
Allow types of arbitrary rank.
Rank2Types
Since 6.8.1
A deprecated alias of RankNTypes (page 342).
GHC’s type system supports arbitrary-rank explicit universal quantification in types. For ex-
ample, all the following types are legal:
Here, f1 and g1 are rank-1 types, and can be written in standard Haskell (e.g. f1 :: a-
>b->a). The forall makes explicit the universal quantification that is implicitly added by
Haskell.
The functions f2 and g2 have rank-2 types; the forall is on the left of a function arrow. As
g2 shows, the polymorphic type on the left of the function arrow can be overloaded.
The function f3 has a rank-3 type; it has rank-2 types on the left of a function arrow.
The language option RankNTypes (page 342) (which implies ExplicitForAll (page 431)) en-
ables higher-rank types. That is, you can nest foralls arbitrarily deep in function arrows.
For example, a forall-type (also called a “type scheme”), including a type-class context, is
legal:
• On the left or right (see f4, for example) of a function arrow
• As the argument of a constructor, or type of a field, in a data type declaration. For
example, any of the f1,f2,f3,g1,g2 above would be valid field type signatures.
• As the type of an implicit parameter
• In a pattern type signature (see Lexically scoped type variables (page 436))
The RankNTypes (page 342) option is also required for any type with a forall or context to
the right of an arrow (e.g. f :: Int -> forall a. a->a, or g :: Int -> Ord a => a ->
a). Such types are technically rank 1, but are clearly not Haskell-98, and an extra extension
did not seem worth the bother.
In particular, in data and newtype declarations the constructor arguments may be polymor-
phic types of any rank; see examples in Examples (page 343). Note that the declared types
are nevertheless always monomorphic. This is important because by default GHC will not
instantiate type variables to a polymorphic type (Impredicative polymorphism (page 346)).
The obsolete language option Rank2Types (page 342) is a synonym for RankNTypes (page 342).
They used to specify finer distinctions that GHC no longer makes.
Examples
These are examples of data and newtype declarations whose data constructors have polymor-
phic argument types:
In earlier versions of GHC, it was possible to omit the forall in the type of the constructor if
there was an explicit context. For example:
Since GHC 8.0 declarations such as MkSwizzle' will cause an out-of-scope error.
You construct values of types T1,MonadT,Swizzle by applying the constructor to suitable
values, just as usual. For example,
a1 :: T Int
a1 = T1 (\x y->x) 3
a2, a3 :: Swizzle
a2 = MkSwizzle sort
a3 = MkSwizzle reverse
a4 :: MonadT Maybe
a4 = let r x = Just x
b m k = case m of
Just y -> k y
Nothing -> Nothing
in
MkMonad r b
The type of the argument can, as usual, be more general than the type required, as (MkSwiz-
zle reverse) shows. (reverse does not need the Ord constraint.)
When you use pattern matching, the bound variables may now have polymorphic types. For
example:
g :: (Ord a, Ord b) => Swizzle -> [a] -> (a -> b) -> [b]
g (MkSwizzle s) xs f = s (map f (s xs))
In the function h we use the record selectors return and bind to extract the polymorphic bind
and return functions from the MonadT data structure, rather than using pattern matching.
Subsumption
Suppose:
then f1 g1 and f2 g2 are both well typed, despite the different order of type variables and
constraints. What happens is that the argument is instantiated, and then re-generalised to
match the type expected by the function.
But this instantiation and re-generalisation happens only at the top level of a type. In partic-
ular, none of this happens if the foralls are underneath an arrow. For example:
Then the application f3 g3a is well-typed, because g3a has a type that matches the type
expected by f3. But f3 g3b is not well typed, because the foralls are in different places. Nor
is f3 g3c, where the foralls are in the same place but the variables are in a different order.
Similarly f4 g4 is not well typed, because the constraints appear in a different order.
These examples can be made to typecheck by eta-expansion. For example f3 (\x -> g3b x)
is well typed, and similarly f3 (\x -> g3c x) and f4 (\x -> g4 x).
Historical note. Earlier versions of GHC allowed these now-rejected applications, by inserting
automatic eta-expansions, as described in Section 4.6 of Practical type inference for arbitrary-
aank types, where it is called “deep skolemisation”. But these automatic eta-expansions may
silently change the semantics of the user’s program, and deep skolemisation was removed
from the language by GHC Proposal #287. This proposal has many more examples.
Type inference
In general, type inference for arbitrary-rank types is undecidable. GHC uses an algorithm
proposed by Odersky and Laufer (“Putting type annotations to work”, POPL‘96) to get a de-
cidable algorithm by requiring some help from the programmer. We do not yet have a formal
specification of “some help” but the rule is this:
For a lambda-bound or case-bound variable, x, either the programmer provides an
explicit polymorphic type for x, or GHC’s type inference will assume that x’s type
has no foralls in it.
What does it mean to “provide” an explicit type for x? You can do that by giving a type signa-
ture for x directly, using a pattern type signature (Lexically scoped type variables (page 436)),
thus:
\ f :: (forall a. a->a) -> (f True, f 'c')
Alternatively, you can give a type signature to the enclosing context, which GHC can “push
down” to find the type for the variable:
(\ f -> (f True, f 'c')) :: (forall a. a->a) -> (Bool,Char)
Here the type signature on the expression can be pushed inwards to give a type signature for
f. Similarly, and more commonly, one can give a type signature for the function itself:
h :: (forall a. a->a) -> (Bool,Char)
h f = (f True, f 'c')
You don’t need to give a type signature if the lambda bound variable is a constructor argument.
Here is an example we saw earlier:
f :: T a -> a -> (a, Char)
f (T1 w k) x = (w k x, w 'c' 'd')
Implicit quantification
GHC performs implicit quantification as follows. At the outermost level (only) of user-written
types, if and only if there is no explicit forall, GHC finds all the type variables mentioned
in the type that are not already in scope, and universally quantifies them. For example, the
following pairs are equivalent:
f :: a -> a
f :: forall a. a -> a
g (x::a) = let
h :: a -> b -> b
h x y = y
in ...
g (x::a) = let
h :: forall b. a -> b -> b
h x y = y
in ...
Notice that GHC always adds implicit quantifiers at the outermost level of a user-written type;
it does not find the inner-most possible quantification point. For example:
f :: (a -> a) -> Int
-- MEANS
f :: forall a. (a -> a) -> Int
-- NOT
f :: (forall a. a -> a) -> Int
If you want the latter type, you can write your foralls explicitly. Indeed, doing so is strongly
advised for rank-2 types.
Sometimes there is no “outermost level”, in which case no implicit quantification happens:
data PackMap a b s t = PackMap (Monad f => (a -> f b) -> s -> f t)
This is rejected because there is no “outermost level” for the types on the RHS (it would obvi-
ously be terrible to add extra parameters to PackMap), so no implicit quantification happens,
and the declaration is rejected (with “f is out of scope”). Solution: use an explicit forall:
data PackMap a b s t = PackMap (forall f. Monad f => (a -> f b) -> s -> f t)
ImpredicativeTypes
Implies RankNTypes (page 342)
Since 6.10.1
Allow impredicative polymorphic types.
In general, GHC will only instantiate a polymorphic function at a monomorphic type (one with
no foralls). For example,
runST :: (forall s. ST s a) -> a
id :: forall b. b -> b
The definition of foo is rejected because one would have to instantiate id‘s type with b :=
(forall s. ST s a) -> a, and that is not allowed. Instantiating polymorphic type variables
with polymorphic types is called impredicative polymorphism.
GHC has extremely flaky support for impredicative polymorphism, enabled with Impredica-
tiveTypes (page 346). If it worked, this would mean that you could call a polymorphic func-
tion at a polymorphic type, and parameterise data structures over polymorphic types. For
example:
Notice here that the Maybe type is parameterised by the polymorphic type (forall a. [a]
-> [a]). However the extension should be considered highly experimental, and certainly un-
supported. You are welcome to try it, but please don’t rely on it working consistently, or
working the same in subsequent releases. See this wiki page for more details.
If you want impredicative polymorphism, the main workaround is to use a newtype wrapper.
The id runST example can be written using this workaround like this:
runST :: (forall s. ST s a) -> a
id :: forall b. b -> b
LinearTypes
Since 9.0.1
Enable the linear arrow a %1 -> b and the multiplicity-polymorphic arrow a %m -> b.
This extension is currently considered experimental, expect bugs, warts, and bad
error messages; everything down to the syntax is subject to change. See, in particular,
Limitations (page 349) below. We encourage you to experiment with this extension and report
issues in the GHC bug tracker the GHC bug tracker, adding the tag LinearTypes.
A function f is linear if: when its result is consumed exactly once, then its argument is con-
sumed exactly once. Intuitively, it means that in every branch of the definition of f, its argu-
ment x must be used exactly once. Which can be done by
• Returning x unmodified
• Passing x to a linear function
• Pattern-matching on x and using each argument exactly once in the same fashion.
• Calling it as a function and using the result exactly once in the same fashion.
With -XLinearTypes, you can write f :: a %1 -> b to mean that f is a linear function from
a to b. If UnicodeSyntax (page 242) is enabled, the %1 -> arrow can be written as ⊸.
To allow uniform handling of linear a %1 -> b and unrestricted a -> b functions, there is a
new function type a %m -> b. Here, m is a type of new kind Multiplicity. We have:
data Multiplicity = One | Many -- Defined in [Link]
Data types
By default, all fields in algebraic data types are linear (even if -XLinearTypes is not turned
on). Given
data T1 a = MkT1 a
construct :: a %1 -> T1 a
construct x = MkT1 x
deconstruct :: T1 a %1 -> a
deconstruct (MkT1 x) = x -- must consume `x` exactly once
When used as a value, MkT1 is given a multiplicity-polymorphic type: MkT1 :: forall {m}
a. a %m -> T1 a. This makes it possible to use MkT1 in higher order functions. The addi-
tional multiplicity argument m is marked as inferred (see Inferred vs. specified type variables
(page 338)), so that there is no conflict with visible type application. When displaying types,
unless -XLinearTypes is enabled, multiplicity polymorphic functions are printed as regular
functions (see Printing multiplicity-polymorphic types (page 348)); therefore constructors ap-
pear to have regular function types.
data T2 a b c where
MkT2 :: a -> b %1 -> c %1 -> T2 a b -- Note unrestricted arrow in the first␣
,→argument
the value MkT2 x y z can be constructed only if x is unrestricted. On the other hand, a linear
function which is matching on MkT2 x y z must consume y and z exactly once, but there is
no restriction on x.
If LinearTypes (page 347) is disabled, all fields are considered to be linear fields, including
GADT fields defined with the -> arrow.
In a newtype declaration, the field must be linear. Attempting to write an unrestricted new-
type constructor with GADT syntax results in an error.
(page 336). In other words, without LinearTypes (page 347), multiplicity-polymorphic func-
tions a %m -> b are printed as normal Haskell2010 functions a -> b. This allows existing
libraries to be generalized to linear types in a backwards-compatible manner; the general
types are visible only if the user has enabled LinearTypes (page 347). (Note that a library
can declare a linear function in the contravariant position, i.e. take a linear function as an
argument. In this case, linearity cannot be hidden; it is an essential part of the exposed
interface.)
Limitations
Linear types are still considered experimental and come with several limitations. If you have
read the full design in the proposal (see Design and further reading (page 349) below), here
is a run down of the missing pieces.
• Multiplicity polymorphism is incomplete and experimental. You may have success using
it, or you may not. Expect it to be really unreliable.
• There is currently no support for multiplicity annotations such as x :: a %p, \(x :: a
%p) -> ....
• All case, let and where statements consume their right-hand side, or scrutiny, Many
times. That is, the following will not type check:
g :: A %1 -> (A, B)
h :: A %1 -> B %1 -> C
f :: A %1 -> C
f x =
case g x of
(y, z) -> h y z
This can be worked around by defining extra functions which are specified to be linear,
such as:
g :: A %1 -> (A, B)
h :: A %1 -> B %1 -> C
f :: A %1 -> C
f x = f' (g x)
where
f' :: (A, B) %1 -> C
f' (y, z) = h y z
• The design for this extension is described in details in the Linear types proposal
• This extension has been originally conceived of in the paper Linear Haskell: practical
linearity in a higher-order polymorphic language (POPL 2018)
When designing embedded domain specific languages in Haskell, it is useful to have some-
thing like error at the type level. In this way, the EDSL designer may show a type error that
is specific to the DSL, rather than the standard GHC type error.
For example, consider a type class that is not intended to be used with functions, but the user
accidentally used it at a function type, perhaps because they missed an argument to some
function. Then, instead of getting the standard GHC message about a missing instance, it
would be nicer to emit a more friendly message specific to the EDSL. Similarly, the reduction
of a type-level function may get stuck due to an error, at which point it would be nice to report
an EDSL specific error, rather than a generic error about an ambiguous type.
To solve this, GHC provides a single type-level function,
along with a small type-level language (via DataKinds (page 315)) for constructing pretty-
printed error messages,
import [Link]
[Link]:8: error:
• Cannot 'Show' functions.
Perhaps there is a missing argument?
• In the expression: print negate
In an equation for ‘main’: main = print negate
While developing, sometimes it is desirable to allow compilation to succeed even if there are
type errors in the code. Consider the following case:
a :: Int
a = 'a'
Even though a is ill-typed, it is not used in the end, so if all that we’re interested in is main it
can be useful to be able to ignore the problems in a.
For more motivation and details please refer to the Wiki page or the original paper.
The flag -fdefer-type-errors (page 88) controls whether type errors are deferred to run-
time. Type errors will still be emitted as warnings, but will not prevent compilation. You can
use -Wno-deferred-type-errors (page 88) to suppress these warnings.
This flag implies the -fdefer-typed-holes (page 89) and -fdefer-out-of-scope-variables
(page 89) flags, which enables this behaviour for typed holes (page ??) and variables. Should
you so wish, it is possible to enable -fdefer-type-errors (page 88) without enabling -
fdefer-typed-holes (page 89) or -fdefer-out-of-scope-variables (page 89), by explic-
itly specifying -fno-defer-typed-holes (page 89) or -fno-defer-out-of-scope-variables
(page 89) on the command-line after the -fdefer-type-errors (page 88) flag.
At runtime, whenever a term containing a type error would need to be evaluated, the error is
converted into a runtime exception of type TypeError. Note that type errors are deferred as
much as possible during runtime, but invalid coercions are never performed, even when they
would ultimately result in a value of the correct type. For example, given the following code:
x :: Int
x = 0
y :: Char
y = x
z :: Int
z = y
The flag -fdefer-type-errors (page 88) works in GHCi as well, with one exception: for
“naked” expressions typed at the prompt, type errors don’t get delayed, so for example:
<interactive>:2:12:
No instance for (Num Char) arising from the literal `1'
Possible fix: add an instance declaration for (Num Char)
Otherwise, in the common case of a simple type error such as typing reverse True at the
prompt, you would get a warning and then an immediately-following type error when the
expression is evaluated.
This exception doesn’t apply to statements, as the following example demonstrates:
<interactive>:3:16: Warning:
No instance for (Num Char) arising from the literal `1'
Possible fix: add an instance declaration for (Num Char)
In the first argument of `(==)', namely `1'
In the expression: 1 == 'a'
In the expression: (True, 1 == 'a')
Prelude> fst x
True
6.4.20 Roles
If the derived instance were allowed, what would the type of its method bad be? It would
seem to be Age -> Inspect Age, which is equivalent to Age -> Int, according to the type
family Inspect. Yet, if we simply adapt the implementation from the instance for Int, the
implementation for bad produces a Bool, and we have trouble.
The way to identify such situations is to have roles assigned to type variables of datatypes,
classes, and type synonyms.
Roles as implemented in GHC are a from a simplified version of the work described in Gener-
ative type abstraction and type-level computation, published at POPL 2011.
The goal of the roles system is to track when two types have the same underlying representa-
tion. In the example above, Age and Int have the same representation. But, the correspond-
ing instances of BadIdea would not have the same representation, because the types of the
implementations of bad would be different.
Suppose we have two uses of a type constructor, each applied to the same parameters except
for one difference. (For example, T Age Bool c and T Int Bool c for some type T.) The
role of a type parameter says what we need to know about the two differing type arguments
in order to know that the two outer types have the same representation (in the example,
what must be true about Age and Int in order to show that T Age Bool c has the same
representation as T Int Bool c).
GHC supports three different roles for type parameters: nominal, representational, and phan-
tom. If a type parameter has a nominal role, then the two types that differ must not actually
differ at all: they must be identical (after type family reduction). If a type parameter has
a representational role, then the two types must have the same representation. (If T‘s first
parameter’s role is representational, then T Age Bool c and T Int Bool c would have the
same representation, because Age and Int have the same representation.) If a type parameter
has a phantom role, then we need no further information.
Here are some examples:
type family F
type instance F Int = Bool
type instance F Age = Char
The type Simple has its parameter at role representational, which is generally the most com-
mon case. Simple Age would have the same representation as Simple Int. The type Complex,
on the other hand, has its parameter at role nominal, because Complex Age and Complex Int
are not the same. Lastly, Phant Age and Phant Bool have the same representation, even
though Age and Bool are unrelated.
Role inference
What role should a given type parameter should have? GHC performs role inference to de-
termine the correct role for every parameter. It starts with a few base facts: (->) has two
representational parameters; (~) has two nominal parameters; all type families’ parameters
are nominal; and all GADT-like parameters are nominal. Then, these facts are propagated
to all places where these types are used. The default role for datatypes and synonyms is
phantom; the default role for classes is nominal. Thus, for datatypes and synonyms, any pa-
rameters unused in the right-hand side (or used only in other types in phantom positions) will
be phantom. Whenever a parameter is used in a representational position (that is, used as
a type argument to a constructor whose corresponding variable is at role representational),
we raise its role from phantom to representational. Similarly, when a parameter is used in a
nominal position, its role is upgraded to nominal. We never downgrade a role from nominal
to phantom or representational, or from representational to phantom. In this way, we infer
the most-general role for each parameter.
Classes have their roles default to nominal to promote coherence of class instances. If a C
Int were stored in a datatype, it would be quite bad if that were somehow changed into a C
Age somewhere, especially if another C Age had been declared!
There is one particularly tricky case that should be explained:
data Tricky a b = MkTricky (a b)
What should Tricky‘s roles be? At first blush, it would seem that both a and b should be at
role representational, since both are used in the right-hand side and neither is involved in a
type family. However, this would be wrong, as the following example shows:
data Nom a = MkNom (F a) -- type family F from example above
Is Tricky Nom Age representationally equal to Tricky Nom Int? No! The former stores a
Char and the latter stores a Bool. The solution to this is to require all parameters to type
variables to have role nominal. Thus, GHC would infer role representational for a but role
nominal for b.
Role annotations
RoleAnnotations
Since 7.8.1
Allow role annotation syntax.
Sometimes the programmer wants to constrain the inference process. For example, the base
library contains the following definition:
data Ptr a = Ptr Addr#
The idea is that a should really be a representational parameter, but role inference assigns it
to phantom. This makes some level of sense: a pointer to an Int really is representationally
the same as a pointer to a Bool. But, that’s not at all how we want to use Ptrs! So, we want
to be able to say
The type role (enabled with RoleAnnotations (page 354)) declaration forces the parameter
a to be at role representational, not role phantom. GHC then checks the user-supplied roles
to make sure they don’t break any promises. It would be bad, for example, if the user could
make BadIdea‘s role be representational.
As another example, we can consider a type Set a that represents a set of data, ordered
according to a‘s Ord instance. While it would generally be type-safe to consider a to be at
role representational, it is possible that a newtype and its base type have different orderings
encoded in their respective Ord instances. This would lead to misbehavior at runtime. So,
the author of the Set datatype would like its parameter to be at role nominal. This would be
done with a declaration
Role annotations can also be used should a programmer wish to write a class with a repre-
sentational (or phantom) role. However, as a class with non-nominal roles can quickly lead to
class instance incoherence, it is necessary to also specify IncoherentInstances (page 414)
to allow non-nominal roles for classes.
The other place where role annotations may be necessary are in hs-boot files (How to compile
mutually recursive modules (page 181)), where the right-hand sides of definitions can be omit-
ted. As usual, the types/classes declared in an hs-boot file must match up with the definitions
in the hs file, including down to the roles. The default role for datatypes is representational
in hs-boot files, corresponding to the common use case.
Role annotations are allowed on data, newtype, and class declarations. A role annotation
declaration starts with type role and is followed by one role listing for each parameter of
the type. (This parameter count includes parameters implicitly specified by a kind signature
in a GADT-style data or newtype declaration.) Each role listing is a role (nominal, repre-
sentational, or phantom) or a _. Using a _ says that GHC should infer that role. The role
annotation may go anywhere in the same module as the datatype or class definition (much
like a value-level type signature). Here are some examples:
6.5 Records
NoTraditionalRecordSyntax
Since 7.4.1
Disallow use of record syntax.
Traditional record syntax, such as C {f = x}, is enabled by default. To disable it, you can
use the NoTraditionalRecordSyntax (page 356) extension.
Field selectors can be used in conjunction with TypeApplications (page 338), as described
in Visible type application (page 338). The type of a field selector is constructed by using the
surrounding definition as context. This section provides a specification for how this construc-
tion works. We will explain it by considering three different forms of field selector, each of
which is a minor variation of the same general theme.
This data type uses a Haskell98-style declaration. The only part of this data type that is
not Haskell98 code is unT, whose type uses higher-rank polymorphism (Arbitrary-rank poly-
morphism (page 342)). To construct the type of the unT field selector, we will assemble the
following:
1. The type variables quantified by the data type head (forall a b. <...>).
2. The return type of the data constructor (<...> T a b -> <...>). By virtue of this being
a Haskell98-style declaration, the order of type variables in the return type will always
coincide with the order in which they are quantified.
3. The type of the field (<...> forall e. Either e a).
The final type of unT is therefore forall a b. T a b -> forall e. Either e a. As a result,
one way to use unT with TypeApplications (page 338) is unT @Int @Bool (MkT (Right 1))
@Char.
Field selectors for GADT constructors (Declaring data types with explicit constructor signa-
tures (page 290)) are slightly more involved. Consider the following example:
data G a b where
MkG :: forall x n a. (Eq a, Show n)
=> { unG1 :: forall e. Either e (a, x), unG2 :: n } -> G a (Maybe x)
The MkG GADT constructor has two records, unG1 and unG2. However, only unG1 can be used
as a top-level field selector. unG2 cannot because it is a “hidden” selector (see Record Con-
structors (page 288)); its type mentions a free variable n that does not appear in the result
type G a (Maybe x). On the other hand, the only free type variables in the type of unG1 are
a and x, so unG1 is fine to use as a top-level function.
To construct the type of the unG1 field selector, we will assemble the following:
1. The subset of type variables quantified by the GADT constructor that are mentioned in
the return type. Note that the order of these variables follows the same principles as
in Ordering of specified variables (page 340). If the constructor explicitly quantifies its
type variables at the beginning of the type, then the field selector type will quantify them
in the same order (modulo any variables that are dropped due to not being mentioned in
the return type). If the constructor implicitly quantifies its type variables, then the field
selector type will quantify them in the left-to-right order that they appear in the field
itself.
In this example, MkG explicitly quantifies forall x n a., and of those type variables, a
and x are mentioned in the return type. Therefore, the type of unG1 starts as forall x
a. <...>. If MkG had not used an explicit forall, then they would have instead been
ordered as forall a x. <...>, since a appears to the left of x in the field type.
2. The GADT return type (<...> G a (Maybe x) -> ...).
3. The type of the field (<...> -> forall e. Either e (a,x)).
The final type of unG1 is therefore forall x a. G a (Maybe x) -> forall e. Either e
(a,x). As a result, one way to use unG1 with TypeApplications (page 338) is unG1 @Int
@Bool (MkG (Right (True,42)) ()) @Char.
Certain record pattern synonyms (Record Pattern Synonyms (page 394)) can give rise to top-
level field selectors. Consider the following example:
We can only make field selectors for pattern synonym records that do not mention any existen-
tial type variables whatsoever in their types, per Record Pattern Synonyms (page 394). (This
is a stronger requirement than for GADT records, whose types can mention existential type
variables provided that they are also mentioned in the return type.) We can see that unP2
cannot be used as a top-level field selector since its type has a free type variable n, which is
existential. unP1 is fine, on the other hand, as its type only has one free variable, the universal
type variable a.
To construct the type of the unP1 field selector, we will assemble the following:
1. The universal type variables (forall a. <...>).
2. The required constraints (<...> Read a => <...>).
3. The pattern synonym return type (<...> G a (Maybe Bool) -> <...>).
4. The type of the field (<...> -> forall e. Either e (a,Bool)).
The final type of unP1 is therefore forall a. Read a => G a (Maybe Bool) -> forall e.
Either e (a,Bool). As a result, one way to use unP1 with TypeApplications (page 338) is
unP1 @Double (MkG (Right (4.5,True)) ()) @Char.
DisambiguateRecordFields
Since 6.8.1
Allow the compiler to automatically choose between identically-named record selectors
based on type (if the choice is unambiguous).
In record construction and record pattern matching it is entirely unambiguous which field is
referred to, even if there are two different data types in scope with a common field name. For
example:
module M where
data S = MkS { x :: Int, y :: Bool }
bad1 k = k { x = 3 } -- Ambiguous
bad2 k = x k -- Ambiguous
Even though there are two x‘s in scope, it is clear that the x in the pattern in the definition
of ok1 can only mean the field x from type S. Similarly for the function ok2. However, in the
record update in bad1 and the record selection in bad2 it is not clear which of the two types
is intended.
Haskell 98 regards all four as ambiguous, but with the DisambiguateRecordFields (page 358)
extension, GHC will accept the former two. The rules are precisely the same as those for
instance declarations in Haskell 98, where the method names on the left-hand side of the
method bindings in an instance declaration refer unambiguously to the method of that class
(provided they are in scope at all), even if there are other variables in scope with the same
name. This reduces the clutter of qualified names when you import two records from different
modules that use the same field name.
Some details:
• Field disambiguation can be combined with punning (see Record puns (page 361)). For
example:
• With DisambiguateRecordFields (page 358) you can use unqualified field names even
if the corresponding selector is only in scope qualified For example, assuming the same
module M as in our earlier example, this is legal:
Since the constructor MkS is only in scope qualified, you must name it [Link], but the field
x does not need to be qualified even though M.x is in scope but x is not (In effect, it is
qualified by the constructor).
DuplicateRecordFields
Implies DisambiguateRecordFields (page 358)
Since 8.0.1
Allow definition of record types with identically-named fields.
Going beyond DisambiguateRecordFields (page 358) (see Record field disambiguation
(page 358)), the DuplicateRecordFields (page 359) extension allows multiple datatypes to
be declared using the same field names in a single module. For example, it allows this:
module M where
data S = MkS { x :: Int }
data T = MkT { x :: Bool }
Uses of fields that are always unambiguous because they mention the constructor, including
construction and pattern-matching, may freely use duplicated field names. For example, the
following are permitted (just as with DisambiguateRecordFields (page 358)):
s = MkS { x = 3 }
f (MkT { x = b }) = b
Field names used as selector functions or in record updates must be unambiguous, either
because there is only one such field in scope, or because a type signature is supplied, as
described in the following sections.
Selector functions
Fields may be used as selector functions only if they are unambiguous, so this is still not
allowed if both S(x) and T(x) are in scope:
bad r = x r
An ambiguous selector may be disambiguated by the type being “pushed down” to the occur-
rence of the selector (see Type inference (page 345) for more details on what “pushed down”
means). For example, the following are permitted:
ok1 = x :: S -> Int
In addition, the datatype that is meant may be given as a type signature on the argument to
the selector:
ok4 s = x (s :: S)
However, we do not infer the type of the argument to determine the datatype, or have any
way of deferring the choice to the constraint solver. Thus the following is ambiguous:
Even though a field label is duplicated in its defining module, it may be possible to use the
selector unambiguously elsewhere. For example, another module could import S(x) but not
T(x), and then use x unambiguously.
Record updates
In a record update such as e { x = 1 }, if there are multiple x fields in scope, then the type of
the context must fix which record datatype is intended, or a type annotation must be supplied.
Consider the following definitions:
Without DuplicateRecordFields (page 359), an update mentioning foo will always be am-
biguous if all these definitions were in scope. When the extension is enabled, there are several
options for disambiguating updates:
• Check for types that have all the fields being updated. For example:
f x = x { foo = 3, bar = 2 }
g1 :: T -> T
g1 x = x { foo = 3 }
g2 x = x { foo = 3 } :: T
h x = (x :: T) { foo = 3 }
The type of the expression being updated will not be inferred, and no constraint-solving will
be performed, so the following will be rejected as ambiguous:
let x :: T
x = blah
in x { foo = 3 }
\ (x :: T) -> x { foo = 3 }
NamedFieldPuns
Since 6.10.1
Allow use of record puns.
Record puns are enabled by the language extension NamedFieldPuns (page 361).
When using records, it is common to write a pattern that binds a variable with the same name
as a record field, such as:
data C = C {a :: Int}
f (C {a = a}) = a
Record punning permits the variable name to be elided, so one can simply write
f (C {a}) = a
to mean the same pattern as above. That is, in a record pattern, the pattern a expands into
the pattern a = a for the same name a.
Note that:
• Record punning can also be used in an expression, writing, for example,
let a = 1 in C {a}
instead of
let a = 1 in C {a = a}
The expansion is purely syntactic, so the expanded right-hand side expression refers to
the nearest enclosing variable that is spelled the same as the field name.
• Puns and other patterns can be mixed in the same record:
• Puns can be used wherever record patterns occur (e.g. in let bindings or at the top-
level).
• A pun on a qualified field name is expanded by stripping off the module qualifier. For
example:
f (C {M.a}) = a
means
(This is useful if the field selector a for constructor M.C is only in scope in qualified form.)
RecordWildCards
Implies DisambiguateRecordFields (page 358).
Since 6.8.1
Allow the use of wildcards in record construction and pattern matching.
Record wildcards are enabled by the language extension RecordWildCards (page 362). This
extension implies DisambiguateRecordFields (page 358).
For records with many fields, it can be tiresome to write out each field individually in a record
pattern, as in
Record wildcard syntax permits a “..” in a record pattern, where each elided field f is re-
placed by the pattern f = f. For example, the above pattern can be written as
f (C {a = 1, ..}) = b + c + d
More details:
• Record wildcards in patterns can be mixed with other patterns, including puns (Record
puns (page 361)); for example, in a pattern (C {a = 1,b,..}). Additionally, record
wildcards can be used wherever record patterns occur, including in let bindings and at
the top-level. For example, the top-level binding
C {a = 1, ..} = e
defines b, c, and d.
• Record wildcards can also be used in an expression, when constructing a record. For
example,
let {a = 1; b = 2; c = 3; d = 4} in C {..}
in place of
The expansion is purely syntactic, so the record wildcard expression refers to the nearest
enclosing variables that are spelled the same as the omitted field names.
• For both pattern and expression wildcards, the “..” expands to the missing in-scope
record fields. Specifically the expansion of “C {..}” includes f if and only if:
– f is a record field of constructor C.
– The record field f is in scope somehow (either qualified or unqualified).
These rules restrict record wildcards to the situations in which the user could have writ-
ten the expanded version. For example
module M where
data R = R { a,b,c :: Int }
module X where
import M( R(R,a,c) )
f a b = R { .. }
The R{..} expands to R{a=a}, omitting b since the record field is not in scope, and
omitting c since the variable c is not in scope (apart from the binding of the record
selector c, of course).
• When record wildcards are use in record construction, a field f is initialised only if f is
in scope, and is not imported or bound at top level. For example, f can be bound by an
enclosing pattern match or let/where-binding. For example
module M where
import A( a )
c = 3 :: Int
f b = R { .. } -- Expands to R { b = b, d = d }
where
d = b+1
Here, a is imported, and c is bound at top level, so neither contribute to the expansion of
the “..”. The motivation here is that it should be easy for the reader to figure out what
the “..” expands to.
• Record wildcards cannot be used (a) in a record update construct, and (b) for data con-
structors that are not declared with record fields. For example:
HasField is a magic built-in typeclass (similar to Coercible, for example). It is given special
treatment by the constraint solver (see Solving HasField constraints (page 364)). Users may
define their own instances of HasField also (see Virtual record fields (page 365)).
except that this instance is not actually generated anywhere, rather the constraint is solved
directly by the constraint solver.
A field must be in scope for the corresponding HasField constraint to be solved. This retains
the existing representation hiding mechanism, whereby a module may choose not to export
a field, preventing client modules from accessing or updating it directly.
Solving HasField constraints depends on the field selector functions that are generated for
each datatype definition:
• If a record field does not have a selector function because its type would allow an exis-
tential variable to escape, the corresponding HasField constraint will not be solved. For
example,
does not give rise to a selector unExists :: Exists t -> t x and we will not solve
HasField "unExists" (Exists t) a automatically.
• If a record field has a polymorphic type (and hence the selector function is higher-rank),
the corresponding HasField constraint will not be solved, because doing so would violate
the functional dependency on HasField and/or require impredicativity. For example,
gives rise to a selector unHigher :: Higher -> (forall t . t -> t) but does not
lead to solution of the constraint HasField "unHigher" Higher a.
• A record GADT may have a restricted type for a selector function, which may lead to
additional unification when solving HasField constraints. For example,
{-# LANGUAGE GADTs #-}
data Gadt t where
MkGadt :: { unGadt :: Maybe v } -> Gadt [v]
gives rise to a selector unGadt :: Gadt [v] -> Maybe v, so the solver will reduce the
constraint HasField "unGadt" (Gadt t) b by unifying t ~ [v] and b ~ Maybe v for
some fresh metavariable v, rather as if we had an instance
instance (t ~ [v], b ~ Maybe v) => HasField "unGadt" (Gadt t) b
• If a record type has an old-fashioned datatype context, the HasField constraint will be
reduced to solving the constraints from the context. For example,
{-# LANGUAGE DatatypeContexts #-}
data Eq a => Silly a = MkSilly { unSilly :: a }
gives rise to a selector unSilly :: Eq a => Silly a -> a, so the solver will reduce
the constraint HasField "unSilly" (Silly a) b to Eq a (and unify a with b), rather as
if we had an instance
instance (Eq a, a ~ b) => HasField "unSilly" (Silly a) b
Users may define their own instances of HasField, provided they do not conflict with the built-
in constraint solving behaviour. This allows “virtual” record fields to be defined for datatypes
that do not otherwise have them.
For example, this instance would make the name field of Person accessible using #fullname
as well:
instance HasField "fullname" Person String where
getField = name
More substantially, an anonymous records library could provide HasField instances for its
anonymous records, and thus be compatible with the polymorphic record selectors introduced
by this proposal. For example, something like this makes it possible to use getField to access
Record values with the appropriate string in the type-level list of fields:
data Record (xs :: [(k, Type)]) where
Nil :: Record '[]
Cons :: Proxy x -> a -> Record xs -> Record ('(x, a) ': xs)
x = getField @"name" r
Since representations such as this can support field labels with kinds other than Symbol, the
HasField class is poly-kinded (even though the built-in constraint solving works only at kind
Symbol). In particular, this allows users to declare scoped field labels such as in the following
example:
y = getField @Name s
In order to avoid conflicting with the built-in constraint solving, the following user-defined
HasField instances are prohibited (in addition to the usual rules, such as the prohibition on
type families appearing in instance heads):
• HasField _ r _ where r is a variable;
• HasField _ (T ...) _ if T is a data family (because it might have fields introduced later,
using data instance declarations);
• HasField x (T ...) _ if x is a variable and T has any fields at all (but this instance is
permitted if T has no fields);
• HasField "foo" (T ...) _ if T has a field foo (but this instance is permitted if it does
not).
If a field has a higher-rank or existential type, the corresponding HasField constraint will
not be solved automatically (as described above), but in the interests of simplicity we do not
permit users to define their own instances either. If a field is not in scope, the corresponding
instance is still prohibited, to avoid conflicts in downstream modules.
Haskell 98 allows the programmer to add a deriving clause to a data type declaration, to
generate a standard instance declaration for specified class. GHC extends this mechanism
along several axes:
• The derivation mechanism can be used separately from the data type declaration, using
the standalone deriving mechanism (page 368).
• In Haskell 98, the only derivable classes are Eq, Ord, Enum, Ix, Bounded, Read, and Show.
Various language extensions (page 369) extend this list.
• Besides the stock approach to deriving instances by generating all method definitions,
GHC supports two additional deriving strategies, which can derive arbitrary classes:
– Generalised newtype deriving (page 378) for newtypes and
– deriving any class (page 384) using an empty instance declaration.
The user can optionally declare the desired deriving strategy (page 386), especially if
the compiler chooses the wrong one by default (page 387).
EmptyDataDeriving
Since 8.4.1
Allow deriving instances of standard type classes for empty data types.
One can write data types with no constructors using the EmptyDataDecls (page 283) flag (see
Data types with no constructors (page 283)), which is on by default in Haskell 2010. What is
not on by default is the ability to derive type class instances for these types. This ability is
enabled through use of the EmptyDataDeriving (page 367) flag. For instance, this lets one
write:
The EmptyDataDeriving (page 367) flag is only required to enable deriving of these four
“standard” type classes (which are mentioned in the Haskell Report). Other extensions to
the deriving mechanism, which are explained below in greater detail, do not require Empty-
DataDeriving (page 367) to be used in conjunction with empty data types. These include:
• StandaloneDeriving (page 368) (see Stand-alone deriving declarations (page 368))
• Type classes which require their own extensions to be enabled to be derived, such as De-
riveFunctor (page 370) (see Deriving instances of extra classes (Data, etc.) (page 369))
• DeriveAnyClass (page 384) (see Deriving any other class (page 384))
The Haskell Report is vague about exactly when a deriving clause is legal. For example:
The first of these is obviously fine. The second is still fine, although less obviously. The third
is not Haskell 98, and risks losing termination of instances.
GHC takes a conservative position: it accepts the first two, but not the third. The rule is this:
each constraint in the inferred instance context must consist only of type variables, with no
repetitions.
This rule is applied regardless of flags. If you want a more exotic context, you can write it
yourself, using the standalone deriving mechanism (page ??).
StandaloneDeriving
Since 6.8.1
Allow the use of stand-alone deriving declarations.
GHC allows stand-alone deriving declarations, enabled by StandaloneDeriving (page 368):
data Foo a = Bar a | Baz String
The syntax is identical to that of an ordinary instance declaration apart from (a) the keyword
deriving, and (b) the absence of the where part.
However, standalone deriving differs from a deriving clause in a number of important ways:
• The standalone deriving declaration does not need to be in the same module as the data
type declaration. (But be aware of the dangers of orphan instances (Orphan modules
and instance declarations (page 191)).
• In most cases, you must supply an explicit context (in the example the context is (Eq
a)), exactly as you would in an ordinary instance declaration. (In contrast, in a deriving
clause attached to a data type declaration, the context is inferred.)
The exception to this rule is that the context of a standalone deriving declaration can
infer its context when a single, extra-wildcards constraint is used as the context, such
as in:
deriving instance _ => Eq (Foo a)
This is essentially the same as if you had written deriving Eq after the declaration for
data Foo a. Using this feature requires the use of PartialTypeSignatures (page 444)
(Partial Type Signatures (page 444)).
• Unlike a deriving declaration attached to a data declaration, the instance can be more
specific than the data type (assuming you also use FlexibleInstances (page 409), Re-
laxed rules for instance contexts (page 411)). Consider for example
data Foo a = Bar a | Baz String
This will generate a derived instance for (Foo [a]) and (Foo (Maybe a)), but other
types such as (Foo (Int,Bool)) will not be an instance of Eq.
• Unlike a deriving declaration attached to a data declaration, GHC does not restrict the
form of the data type. Instead, GHC simply generates the appropriate boilerplate code
for the specified class, and typechecks it. If there is a type error, it is your problem.
(GHC will show you the offending code if it has a type error.)
The merit of this is that you can derive instances for GADTs and other exotic data types,
providing only that the boilerplate code does indeed typecheck. For example:
data T a where
T1 :: T Int
T2 :: T Bool
In this example, you cannot say ... deriving( Show ) on the data type declaration for
T, because T is a GADT, but you can generate the instance declaration using stand-alone
deriving.
The down-side is that, if the boilerplate code fails to typecheck, you will get an error
message about that code, which you did not write. Whereas, with a deriving clause the
side-conditions are necessarily more conservative, but any error message may be more
comprehensible.
• Under most circumstances, you cannot use standalone deriving to create an instance for
a data type whose constructors are not all in scope. This is because the derived instance
would generate code that uses the constructors behind the scenes, which would break
abstraction.
The one exception to this rule is DeriveAnyClass (page 384), since deriving an instance
via DeriveAnyClass (page 384) simply generates an empty instance declaration, which
does not require the use of any constructors. See the deriving any class (page ??) section
for more details.
In other ways, however, a standalone deriving obeys the same rules as ordinary deriving:
• A deriving instance declaration must obey the same rules concerning form and ter-
mination as ordinary instance declarations, controlled by the same flags; see Instance
declarations and resolution (page 409).
• The stand-alone syntax is generalised for newtypes in exactly the same way that or-
dinary deriving clauses are generalised (Generalised derived instances for newtypes
(page 378)). For example:
GHC always treats the last parameter of the instance (Foo in this example) as the type
whose instance is being derived.
Haskell 98 allows the programmer to add “deriving( Eq,Ord )” to a data type declaration,
to generate a standard instance declaration for classes specified in the deriving clause. In
Haskell 98, the only classes that may appear in the deriving clause are the standard classes
Eq, Ord, Enum, Ix, Bounded, Read, and Show.
GHC extends this list with several more classes that may be automatically derived:
• With DeriveGeneric (page 512), you can derive instances of the classes Generic and
Generic1, defined in [Link]. You can use these to define generic functions, as
described in Generic programming (page 511).
• With DeriveFunctor (page 370), you can derive instances of the class Functor, defined
in [Link].
• With DeriveDataTypeable (page 376), you can derive instances of the class Data, defined
in [Link].
• With DeriveFoldable (page 373), you can derive instances of the class Foldable, defined
in [Link].
• With DeriveTraversable (page 375), you can derive instances of the class Traversable,
defined in [Link]. Since the Traversable instance dictates the instances of
Functor and Foldable, you’ll probably want to derive them too, so DeriveTraversable
(page 375) implies DeriveFunctor (page 370) and DeriveFoldable (page 373).
• With DeriveLift (page 377), you can derive instances of the class Lift, defined in the
[Link] module of the template-haskell package.
You can also use a standalone deriving declaration instead (see Stand-alone deriving declara-
tions (page 368)).
In each case the appropriate class must be in scope before it can be mentioned in the deriving
clause.
DeriveFunctor
Since 7.10.1
Allow automatic deriving of instances for the Functor typeclass.
With DeriveFunctor (page 370), one can derive Functor instances for data types of kind Type
-> Type. For example, this declaration:
data Example a = Ex a Char (Example a) (Example Char)
deriving Functor
The basic algorithm for DeriveFunctor (page 370) walks the arguments of each constructor
of a data type, applying a mapping function depending on the type of each argument. If a
plain type variable is found that is syntactically equivalent to the last type parameter of the
data type (a in the above example), then we apply the function f directly to it. If a type is
encountered that is not syntactically equivalent to the last type parameter but does mention
the last type parameter somewhere in it, then a recursive call to fmap is made. If a type is
found which doesn’t mention the last type parameter at all, then it is left alone.
The second of those cases, in which a type is unequal to the type parameter but does contain
the type parameter, can be surprisingly tricky. For example, the following example compiles:
Modifying the code slightly, however, produces code which will not compile:
The difference involves the placement of the last type parameter, a. In the Right case, a
occurs within the type Either Int a, and moreover, it appears as the last type argument of
Either. In the Wrong case, however, a is not the last type argument to Either; rather, Int is.
This distinction is important because of the way DeriveFunctor (page 370) works. The de-
rived Functor Right instance would be:
Given a value of type Right a, GHC must produce a value of type Right b. Since the argu-
ment to the Right constructor has type Either Int a, the code recursively calls fmap on it
to produce a value of type Either Int b, which is used in turn to construct a final value of
type Right b.
The generated code for the Functor Wrong instance would look exactly the same, except with
Wrong replacing every occurrence of Right. The problem is now that fmap is being applied
recursively to a value of type Either a Int. This cannot possibly produce a value of type
Either b Int, as fmap can only change the last type parameter! This causes the generated
code to be ill-typed.
As a general rule, if a data type has a derived Functor instance and its last type parameter
occurs on the right-hand side of the data declaration, then either it must (1) occur bare (e.g.,
newtype Id a = Id a), or (2) occur as the last argument of a type constructor (as in Right
above).
There are two exceptions to this rule:
1. Tuple types. When a non-unit tuple is used on the right-hand side of a data declaration,
DeriveFunctor (page 370) treats it as a product of distinct types. In other words, the
following code:
That is, DeriveFunctor (page 370) pattern-matches its way into tuples and maps over
each type that constitutes the tuple. The generated code is reminiscent of what would
be generated from data Triple a = Triple a Int [a], except with extra machinery
to handle the tuple.
2. Function types. The last type parameter can appear anywhere in a function type as long
as it occurs in a covariant position. To illustrate what this means, consider the following
three examples:
All three of these examples would compile without issue. On the other hand:
While these examples look similar, none of them would successfully compile. This is
because all occurrences of the last type parameter a occur in contravariant positions,
not covariant ones.
Intuitively, a covariant type is produced, and a contravariant type is consumed. Most
types in Haskell are covariant, but the function type is special in that the lefthand side
of a function arrow reverses variance. If a function type a -> b appears in a covariant
position (e.g., CovFun1 above), then a is in a contravariant position and b is in a covariant
position. Similarly, if a -> b appears in a contravariant position (e.g., CovFun2 above),
then a is in a covariant position and b is in a contravariant position.
To see why a data type with a contravariant occurrence of its last type parameter can-
not have a derived Functor instance, let’s suppose that a Functor ContraFun1 instance
exists. The implementation would look something like this:
We have f :: a -> b, g :: a -> Int, and x :: b. Using these, we must somehow fill
in the hole (denoted with an underscore) with a value of type Int. What are our options?
We could try applying g to x. This won’t work though, as g expects an argument of type
a, and x :: b. Even worse, we can’t turn x into something of type a, since f also needs
an argument of type a! In short, there’s no good way to make this work.
On the other hand, a derived Functor instances for the CovFuns are within the realm of
possibility:
There are some other scenarios in which a derived Functor instance will fail to compile:
1. A data type has no type parameters (e.g., data Nothing = Nothing).
2. A data type’s last type variable is used in a DatatypeContexts (page 283) constraint
(e.g., data Ord a => O a = O a).
3. A data type’s last type variable is used in an ExistentialQuantification (page 286)
constraint, or is refined in a GADT. For example,
data T a b where
T4 :: Ord b => b -> T a b
T5 :: b -> T b b
T6 :: T a (b,b)
When a type has no constructors, the derived Functor instance will simply force the (bottom)
value of the argument using EmptyCase (page 263).
will produce
instance Functor V where fmap _ z = case z of
DeriveFoldable
Since 7.10.1
Allow automatic deriving of instances for the Foldable typeclass.
With DeriveFoldable (page 373), one can derive Foldable instances for data types of kind
Type -> Type. For example, this declaration:
The algorithm for DeriveFoldable (page 373) is adapted from the DeriveFunctor (page 370)
algorithm, but it generates definitions for foldMap, foldr, and null instead of fmap. In addi-
tion, DeriveFoldable (page 373) filters out all constructor arguments on the RHS expression
whose types do not mention the last type parameter, since those arguments do not need to
be folded over.
When the type parameter has a phantom role (see Roles (page 352)), DeriveFoldable
(page 373) derives a trivial instance. For example, this declaration:
Similarly, when the type has no constructors, DeriveFoldable (page 373) will derive a trivial
instance:
data V a deriving Foldable
type role V nominal
Here are the differences between the generated code for Functor and Foldable:
#. When a bare type variable a is encountered, DeriveFunctor (page 370) would generate
f a for an fmap definition. DeriveFoldable (page 373) would generate f a z for foldr, f a
for foldMap, and False for null.
1. When a type that is not syntactically equivalent to a, but which does contain a, is encoun-
tered, DeriveFunctor (page 370) recursively calls fmap on it. Similarly, DeriveFoldable
(page 373) would recursively call foldr and foldMap. Depending on the context, null
may recursively call null or all null. For example, given
data F a = F (P a)
data G a = G (P (a, Int))
data H a = H (P (Q a))
2. DeriveFunctor (page 370) puts everything back together again at the end by invoking
the constructor. DeriveFoldable (page 373), however, builds up a value of some type.
For foldr, this is accomplished by chaining applications of f and recursive foldr calls
on the state value z. For foldMap, this happens by combining all values with mappend.
For null, the values are usually combined with &&. However, if any of the values is known
to be False, all the rest will be dropped. For example,
data SnocList a = Nil | Snoc (SnocList a) a
There are some other differences regarding what data types can have derived Foldable in-
stances:
1. Data types containing function types on the right-hand side cannot have derived Fold-
able instances.
2. Foldable instances can be derived for data types in which the last type parameter is
existentially constrained or refined in a GADT. For example, this data type:
data E a where
E1 :: (a ~ Int) => a -> E a
E2 :: Int -> E Int
E3 :: (a ~ Int) => a -> E Int
E4 :: (a ~ Int) => Int -> E a
foldMap f (E1 e) = f e
foldMap f (E2 e) = mempty
foldMap f (E3 e) = mempty
foldMap f (E4 e) = mempty
Notice how every constructor of E utilizes some sort of existential quantification, but
only the argument of E1 is actually “folded over”. This is because we make a deliberate
choice to only fold over universally polymorphic types that are syntactically equivalent
to the last type parameter. In particular:
• We don’t fold over the arguments of E1 or E4 because even though (a ~ Int), Int is not
syntactically equivalent to a.
• We don’t fold over the argument of E3 because a is not universally polymorphic. The a in
E3 is (implicitly) existentially quantified, so it is not the same as the last type parameter
of E.
DeriveTraversable
Implies DeriveFoldable (page 373), DeriveFunctor (page 370)
Since 7.10.1
Allow automatic deriving of instances for the Traversable typeclass.
With DeriveTraversable (page 375), one can derive Traversable instances for data types of
kind Type -> Type. For example, this declaration:
The algorithm for DeriveTraversable (page 375) is adapted from the DeriveFunctor
(page 370) algorithm, but it generates a definition for traverse instead of fmap. In addition,
DeriveTraversable (page 375) filters out all constructor arguments on the RHS expression
whose types do not mention the last type parameter, since those arguments do not produce
any effects in a traversal.
When the type parameter has a phantom role (see Roles (page 352)), DeriveTraversable
(page 375) coerces its argument. For example, this declaration:
When the type has no constructors, DeriveTraversable (page 375) will derive the laziest
instance it can.
Here are the differences between the generated code in each extension:
1. When a bare type variable a is encountered, both DeriveFunctor (page 370) and De-
riveTraversable (page 375) would generate f a for an fmap and traverse definition,
respectively.
2. When a type that is not syntactically equivalent to a, but which does contain a, is en-
countered, DeriveFunctor (page 370) recursively calls fmap on it. Similarly, Derive-
Traversable (page 375) would recursively call traverse.
3. DeriveFunctor (page 370) puts everything back together again at the end by invoking
the constructor. DeriveTraversable (page 375) does something similar, but it works in
an Applicative context by chaining everything together with (<*>).
Unlike DeriveFunctor (page 370), DeriveTraversable (page 375) cannot be used on data
types containing a function type on the right-hand side.
For a full specification of the algorithms used in DeriveFunctor (page 370), DeriveFoldable
(page 373), and DeriveTraversable (page 375), see this wiki page.
DeriveDataTypeable
Since 6.8.1
Enable automatic deriving of instances for the Data typeclass
This rule works for any concrete type constructor, including type constructors with
polymorphic kinds. The only restriction is that if the type constructor has a polymor-
phic kind, then it has to be applied to all of its kinds parameters, and these kinds
need to be concrete (i.e., they cannot mention kind variables).
– A type variable applied to some types:
DeriveLift
Since 8.0.1
Enable automatic deriving of instances for the Lift typeclass for Template Haskell.
The class Lift, unlike other derivable classes, lives in template-haskell instead of base.
Having a data type be an instance of Lift permits its values to be promoted to Template
Haskell expressions (of type ExpQ and Code Q a), which can then be spliced into Haskell
source code.
Here is an example of how one can derive Lift:
import [Link]
{-
-----
{-# LANGUAGE TemplateHaskell #-}
module Baz where
import Bar
import [Link]
Note that the Lift typeclass takes advantage of Levity polymorphism (page 334) in order to
support instances involving unboxed types. This means DeriveLift (page 377) also works
for these types:
import [Link]
import [Link]
{-
instance Lift IntHash where
lift (IntHash i) = [| IntHash i |]
liftTyped (IntHash i) = [|| IntHash i ||]
-}
GeneralisedNewtypeDeriving
GeneralizedNewtypeDeriving
Since 6.8.1. British spelling since 8.6.1.
Enable GHC’s cunning generalised deriving mechanism for newtypes
When you define an abstract type using newtype, you may want the new type to inherit some
instances from its representation. In Haskell 98, you can inherit instances of Eq, Ord, Enum
and Bounded by deriving them, but for any other classes you have to write an explicit instance
declaration. For example, if you define
and you want to use arithmetic on Dollars, you have to explicitly define an instance of Num:
All the instance does is apply and remove the newtype constructor. It is particularly galling
that, since the constructor doesn’t appear at run-time, this instance declaration defines a
dictionary which is wholly equivalent to the Int dictionary, only slower!
DerivingVia (page 388) (see Deriving via (page 388)) is a generalization of this idea.
GHC now permits such instances to be derived instead, using the extension GeneralizedNew-
typeDeriving (page 378), so one can write
and the implementation uses the same Num dictionary for Dollars as for Int. In other words,
GHC will generate something that resembles the following code
and then attempt to simplify the Num Int context as much as possible. GHC knows that there
is a Num Int instance in scope, so it is able to discharge the Num Int constraint, leaving the
code that GHC actually generates
One can think of this instance being implemented with the same code as the Num Int instance,
but with Dollars and getDollars added wherever necessary in order to make it typecheck.
(In practice, GHC uses a somewhat different approach to code generation. See the A more
precise specification (page 381) section below for more details.)
We can also derive instances of constructor classes in a similar way. For example, suppose
we have implemented state and failure monad transformers, such that
which is automatically a monad thanks to the instance declarations above. With the extension,
we can make the parser type abstract, without needing to write an instance of class Monad,
via
instance Monad (State [tok] (Failure m)) => Monad (Parser tok m)
Notice that, since Monad is a constructor class, the instance is a partial application of the
newtype, not the entire left hand side. We can imagine that the type declaration is “eta-
converted” to generate the context of the instance declaration.
We can even derive instances of multi-parameter classes, provided the newtype is the last
class parameter. In this case, a “partial application” of the class appears in the deriving
clause. For example, given the class
The derived instance is obtained by completing the application of the class to the new type:
As a result of this extension, all derived instances in newtype declarations are treated uni-
formly (and implemented just by reusing the dictionary for the representation type), except
Show and Read, which really behave differently for the newtype and its representation.
The following will fail with an “Illegal unboxed tuple” error, since the derived instance pro-
duced by the compiler makes use of unboxed tuple syntax,
import Lib
However, enabling the UnboxedTuples (page 474) extension allows the module to compile.
Similar errors may occur with a variety of extensions, including:
• UnboxedTuples (page 474)
• PolyKinds (page 319)
• MultiParamTypeClasses (page 400)
• FlexibleContexts (page 400)
A derived instance is derived only for declarations of these forms (after expansion of any type
synonyms)
where
• v1..vn are type variables, and t, s1..sk, t1..tj are types.
• The (C t1..tj) is a partial applications of the class C, where the arity of C is exactly
j+1. That is, C lacks exactly one type argument.
• k is chosen so that C t1..tj (T v1...vk) is well-kinded. (Or, in the case of a data
instance, so that C t1..tj (T s1..sk) is well kinded.)
• The type t is an arbitrary type.
• The type variables vk+1...vn do not occur in the types t, s1..sk, or t1..tj.
• C is not Read, Show, Typeable, or Data. These classes should not “look through” the
type or its constructor. You can still derive these classes for a newtype, but it happens
in the usual way, not via this new mechanism. Confer with Default deriving strategy
(page 387).
• It is safe to coerce each of the methods of C. That is, the missing last argument to C is
not used at a nominal role in any of the C‘s methods. (See Roles (page 352).)
• C is allowed to have associated type families, provided they meet the requirements laid
out in the section on GND and associated types (page 382).
Then the derived instance declaration is of the form
Note that if C does not contain any class methods, the instance context is wholly unnecessary,
and as such GHC will instead generate:
because the type variable s occurs in State s m, and so cannot be “eta-converted” away. It
is a good thing that this deriving clause is rejected, because NonMonad m is not, in fact, a
monad — for the same reason. Try defining >>= with the correct type: you won’t be able to.
Notice also that the order of class parameters becomes important, since we can only derive
instances for the last one. If the StateMonad class above were instead defined as
then we would not have been able to derive an instance for the Parser type above. We hy-
pothesise that multi-parameter classes usually have one “main” parameter for which deriving
new instances is most interesting.
Lastly, all of this applies only for classes other than Read, Show, Typeable, and Data, for
which the stock derivation applies (section 4.3.3. of the Haskell Report). (For the standard
classes Eq, Ord, Ix, and Bounded it is immaterial whether the stock method is used or the one
described here.)
GeneralizedNewtypeDeriving (page 378) also works for some type classes with associated
type families. Here is an example:
class HasRing a where
type Ring a
then you can derive a C c_1 c_2 ... c_(m-1) instance for N n_1 n_2 ... n_q, provided
that:
• The type parameter c_m occurs once in each of the type variables of T1 through Tk.
Imagine a class where this condition didn’t hold. For example:
class Bad a b where
type B a
For the derived Bad Int instance, GHC would need to generate something like this:
instance Bad Int (Foo a) where
type B Int = B ???
Now we’re stuck, since we have no way to refer to a on the right-hand side of the B family
instance, so this instance doesn’t really make sense in a GeneralizedNewtypeDeriving
(page 378) setting.
• C does not have any associated data families (only type families). To see why data families
are forbidden, imagine the following scenario:
class Ex a where
data D a
For the derived Ex instance, GHC would need to generate something like this:
instance Ex Age where
data D Age = ???
But it is not clear what GHC would fill in for ???, as each data family instance must
generate fresh data constructors.
If both of these conditions are met, GHC will generate this instance:
instance C c_1 c_2 ... c_(m-1) <rep-type> =>
C c_1 c_2 ... c_(m-1) (N n_1 n_2 ... n_q) where
type T1 t1_1 t1_2 ... (N n_1 n_2 ... n_q) ... t1_n
= T1 t1_1 t1_2 ... <rep-type> ... t1_n
...
type Tk tk_1 tk_2 ... (N n_1 n_2 ... n_q) ... tk_p
= Tk tk_1 tk_2 ... <rep-type> ... tk_p
Again, if C contains no class methods, the instance context will be redundant, so GHC will
instead generate instance C c_1 c_2 ... c_(m-1) (N n_1 n_2 ... n_q).
Beware that in some cases, you may need to enable the UndecidableInstances (page 412)
extension in order to use this feature. Here’s a pathological case that illustrates why this
might happen:
class C a where
type T a
Here, it is evident that attempting to use the type T Loop will throw the typechecker into
an infinite loop, as its definition recurses endlessly. In other cases, you might need to enable
UndecidableInstances (page 412) even if the generated code won’t put the typechecker into
a loop. For example:
instance C Int where
type C Int = Int
Although typechecking T MyInt will terminate, GHC’s termination checker isn’t sophisticated
enough to determine this, so you’ll need to enable UndecidableInstances (page 412) in order
to use this derived instance. If you do go down this route, make sure you can convince yourself
that all of the type family instances you’re deriving will eventually terminate if used!
Note that DerivingVia (page 388) (see Deriving via (page 388)) uses essentially the same
specification to derive instances of associated type families as well (except that it uses the
via type instead of the underlying rep-type of a newtype).
DeriveAnyClass
Since 7.10.1
Allow use of any typeclass in deriving clauses.
With DeriveAnyClass (page 384) you can derive any other class. The compiler will simply
generate an instance declaration with no explicitly-defined methods. This is mostly useful in
classes whose minimal set (page ??) is empty, and especially when writing generic functions
(page ??).
As an example, consider a simple pretty-printer class SPretty, which outputs pretty strings:
If a user does not provide a manual implementation for sPpr, then it will default to show. Now
we can leverage the DeriveAnyClass (page 384) extension to easily implement a SPretty
instance for a new data type:
That is, an SPretty Foo instance will be created with empty implementations for all methods.
Since we are using DefaultSignatures (page 402) in this example, a default implementation
of sPpr is filled in automatically.
Note the following details
• In case you try to derive some class on a newtype, and GeneralizedNewtypeDeriving
(page 378) is also on, DeriveAnyClass (page 384) takes precedence.
• The instance context is determined by the type signatures of the derived class’s methods.
For instance, if the class is:
Since the default type signatures for bar and baz require Show a and Ord a constraints,
respectively.
Constraints on the non-default type signatures can play a role in inferring the instance
context as well. For example, if you have this class:
That is because we require an Eq (Option a) instance from the default type signature
for (==#), which in turn requires an Eq a instance, which we don’t have in scope. But if
you tweak the definition of HigherEq slightly:
Then it becomes possible to derive a HigherEq Option instance. Note that the only dif-
ference is that now the non-default type signature for (==#) brings in an Eq a constraint.
Constraints from non-default type signatures never appear in the derived instance con-
text itself, but they can be used to discharge obligations that are demanded by the default
type signatures. In the example above, the default type signature demanded an Eq a in-
stance, and the non-default signature was able to satisfy that request, so the derived
instance is simply:
instance HigherEq Option
• DeriveAnyClass (page 384) can be used with partially applied classes, such as
data T a = MKT a deriving( D Int )
which generates
instance D Int a => D Int (T a) where {}
• DeriveAnyClass (page 384) can be used to fill in default instances for associated type
families:
{-# LANGUAGE DeriveAnyClass, TypeFamilies #-}
and then the normal rules for filling in associated types from the default will apply, mak-
ing Size Bar equal to Int.
DerivingStrategies
Since 8.2.1
Allow multiple deriving, each optionally qualified with a strategy.
In most scenarios, every deriving statement generates a typeclass instance in an unambigu-
ous fashion. There is a corner case, however, where simultaneously enabling both the Gen-
eralizedNewtypeDeriving (page 378) and DeriveAnyClass (page 384) extensions can make
deriving become ambiguous. Consider the following example
{-# LANGUAGE DeriveAnyClass, GeneralizedNewtypeDeriving #-}
newtype Foo = MkFoo Bar deriving C
One could either pick the DeriveAnyClass approach to deriving C or the GeneralizedNew-
typeDeriving approach to deriving C, both of which would be equally as valid. GHC defaults
to favoring DeriveAnyClass in such a dispute, but this is not a satisfying solution, since that
leaves users unable to use both language extensions in a single module.
To make this more robust, GHC has a notion of deriving strategies, which allow the user to
explicitly request which approach to use when deriving an instance. To enable this feature,
one must enable the DerivingStrategies (page 386) language extension. A deriving strategy
can be specified in a deriving clause
DerivingStrategies (page 386) also allows the use of multiple deriving clauses per data
declaration so that a user can derive some instance with one deriving strategy and other
instances with another deriving strategy. For example
If an explicit deriving strategy is not given, multiple strategies may apply. In that case, GHC
chooses the strategy as follows:
1. Stock type classes, i.e. those specified in the report and those enabled by language
extensions (page ??), are derived using the stock strategy, with the following exception:
• For newtypes, Eq, Ord, Ix and Bounded are always derived using the newtype strat-
egy, even without GeneralizedNewtypeDeriving enabled. (There should be no ob-
servable difference to instances derived using the stock strategy.)
• Also for newtypes, Functor, Foldable and Enum are derived using the newtype strat-
egy if GeneralizedNewtypeDeriving is enabled and the derivation succeeds.
2. For other any type class:
(a) When DeriveAnyClass (page 384) is enabled, use anyclass.
(b) When GeneralizedNewtypeDeriving (page 378) is enabled and we are deriving for
a newtype, then use newtype.
If both rules apply to a deriving clause, then anyclass is used and the user is warned
about the ambiguity. The warning can be avoided by explicitly stating the desired deriv-
ing strategy.
DerivingVia
Implies DerivingStrategies (page 386)
Since 8.6.1
This allows deriving a class instance for a type by specifying another type of equal runtime
representation (such that there exists a Coercible instance between the two: see The Co-
ercible constraint (page 425)) that is already an instance of the that class.
DerivingVia (page 388) is indicated by the use of the via deriving strategy. via requires
specifying another type (the via type) to coerce through. For example, this code:
import Numeric
-- >>> euroSign
-- 0x20ac
euroSign :: Unicode
euroSign = U 0x20ac
deriving Show
via (Hex Int)
euroSign :: Unicode
euroSign = 0x20ac
We can instead create a newtype App (where App f a and f a are represented the same in
memory) and use DerivingVia (page 388) to explicitly enable uses of this pattern:
import [Link]
Note that the via type does not have to be a newtype. The only restriction is that it is coercible
with the original data type. This means there can be arbitrary nesting of newtypes, as in the
following example:
6.7 Patterns
NoPatternGuards
Implied by Haskell98 (page 237)
Since 6.8.1
Disable pattern guards.
ViewPatterns
Since 6.10.1
Allow use of view pattern syntax.
View patterns are enabled by the language extension ViewPatterns (page 390). More infor-
mation and examples of view patterns can be found on the Wiki page.
View patterns are somewhat like pattern guards that can be nested inside of other patterns.
They are a convenient way of pattern-matching against values of abstract types. For example,
in a programming language implementation, we might represent the syntax of the types of
the language as follows:
type Typ
The representation of Typ is held abstract, permitting implementations to use a fancy repre-
sentation (e.g., hash-consing to manage sharing). Without view patterns, using this signature
is a little inconvenient:
It is necessary to iterate the case, rather than using an equational function definition. And the
situation is even worse when the matching against t is buried deep inside another pattern.
View patterns permit calling the view function inside the pattern and matching against the
result:
That is, we add a new form of pattern, written ⟨expression⟩ -> ⟨pattern⟩ that means “apply
the expression to whatever we’re trying to match against, and then match the result of that
application against the pattern”. The expression can be any Haskell expression of function
type, and view patterns can be used wherever patterns are used.
The semantics of a pattern ( ⟨exp⟩ -> ⟨pat⟩ ) are as follows:
• Scoping: The variables bound by the view pattern are the variables bound by ⟨pat⟩.
Any variables in ⟨exp⟩ are bound occurrences, but variables bound “to the left” in a
pattern are in scope. This feature permits, for example, one argument to a function to
be used in the view of another argument. For example, the function clunky from Pattern
guards (page 389) can be written using view patterns as follows:
clunky env (lookup env -> Just val1) (lookup env -> Just val2) = val1 + val2
...other equations for clunky...
That is, the scoping is the same as it would be if the curried arguments were collected
into a tuple.
– In mutually recursive bindings, such as let, where, or the top level, view patterns
in one declaration may not mention variables bound by other declarations. That is,
each declaration must be self-contained. For example, the following program is not
allowed:
That is, to match a variable ⟨v⟩ against a pattern ( ⟨exp⟩ -> ⟨pat⟩ ), evaluate ( ⟨exp⟩ ⟨v⟩ )
and match the result against ⟨pat⟩.
• Efficiency: When the same view function is applied in multiple branches of a function
definition or a case expression (e.g., in size above), GHC makes an attempt to collect
these applications into a single nested case expression, so that the view function is only
applied once. Pattern compilation in GHC follows the matrix algorithm described in
Chapter 4 of The Implementation of Functional Programming Languages. When the top
rows of the first column of a matrix are all view patterns with the “same” expression,
these patterns are transformed into a single nested case. This includes, for example,
adjacent view patterns that line up in a tuple, as in
The current notion of when two view pattern expressions are “the same” is very re-
stricted: it is not even full syntactic equality. However, it does include variables, literals,
applications, and tuples; e.g., two instances of view ("hi","there") will be collected.
However, the current implementation does not compare up to alpha-equivalence, so two
instances of (x,view x -> y) will not be coalesced.
NPlusKPatterns
Implied by Haskell98 (page 237)
Since 6.12.1
Enable use of n+k patterns.
PatternSynonyms
Since 7.8.1
Allow the definition of pattern synonyms.
Pattern synonyms are enabled by the language extension PatternSynonyms (page 392), which
is required for defining them, but not for using them. More information and examples of
pattern synonyms can be found on the Wiki page.
Pattern synonyms enable giving names to parametrized pattern schemes. They can also be
thought of as abstract constructors that don’t have a bearing on data representation. For ex-
ample, in a programming language implementation, we might represent types of the language
as follows:
Here are some examples of using said representation. Consider a few types of the Type
universe encoded like this:
This representation is very generic in that no types are given special treatment. However,
some functions might need to handle some known types specially, for example the following
two functions collect all argument types of (nested) arrow types, and recognize the Int type,
respectively:
Matching on App directly is both hard to read and error prone to write. And the situation is
even worse when the matching is nested:
Pattern synonyms permit abstracting from the representation to expose matchers that be-
have in a constructor-like manner with respect to pattern matching. We can create pattern
synonyms for the known types we care about, without committing the representation to them
(note that these don’t have to be defined in the same module as the Type type):
In general there are three kinds of pattern synonyms. Unidirectional, bidirectional and explic-
itly bidirectional. The examples given so far are examples of bidirectional pattern synonyms.
A bidirectional synonym behaves the same as an ordinary data constructor. We can use it in
a pattern context to deconstruct values and in an expression context to construct values. For
example, we can construct the value intEndo using the pattern synonyms Arrow and Int as
defined previously.
intEndo :: Type
intEndo = Arrow Int Int
This example is equivalent to the much more complicated construction if we had directly used
the Type constructors.
intEndo :: Type
intEndo = App "->" [App "Int" [], App "Int" []]
Unidirectional synonyms can only be used in a pattern context and are defined as follows:
In this case, Head ⟨x⟩ cannot be used in expressions, only patterns, since it wouldn’t specify
a value for the ⟨xs⟩ on the right-hand side. However, we can define an explicitly bidirectional
pattern synonym by separately specifying how to construct and deconstruct a type. The syntax
for doing this is as follows:
We can then use HeadC in both expression and pattern contexts. In a pattern context it will
match the head of any list with length at least one. In an expression context it will construct
a singleton list.
Explicitly bidirectional pattern synonyms offer greater flexibility than implicitly bidirectional
ones in terms of the syntax that is permitted. For instance, the following is not a legal implic-
itly bidirectional pattern synonym:
This is illegal because the use of BangPatterns (page 462) on the right-hand sides prevents
it from being a well formed expression. However, constructing a strict pattern synonym is
quite possible with an explicitly bidirectional pattern synonym:
Or using guards:
There is an extensive Haskell folk art of smart constructors, essentially functions that wrap
validation around a constructor, and avoid exposing its representation. The downside is that
the underlying constructor can’t be used as a matcher. Pattern synonyms can be used as
genuinely smart constructors, for both validation and matching.
The table below summarises where each kind of pattern synonym can be used.
Context Unidirectional Bidirectional Explicitly Bidirectional
Pattern Yes Yes Yes
Expression No Yes (Inferred) Yes (Explicit)
It is also possible to define pattern synonyms which behave just like record constructors. The
syntax for doing this is as follows:
The idea is that we can then use Point just as if we had defined a new datatype MyPoint with
two fields x and y.
Whilst a normal pattern synonym can be used in two ways, there are then seven ways in which
to use Point. Precisely the ways in which a normal record constructor can be used.
Usage Example
As a constructor zero = Point 0 0
As a constructor with record syntax zero = Point { x = 0,y = 0}
In a pattern context isZero (Point 0 0) = True
In a pattern context with record syntax isZero (Point { x = 0,y = 0 }
In a pattern context with field puns getX (Point {x}) = x
In a record update (0,0) { x = 1 } == (1,0)
Using record selectors x (0,0) == 0
For a unidirectional record pattern synonym we define record selectors but do not allow
record updates or construction.
The syntax and semantics of pattern synonyms are elaborated in the following subsections.
There are also lots more details in the paper.
See the Wiki page for more details.
We can define either prefix, infix or record pattern synonyms by modifying the form of pat_lhs.
The syntax for these is as follows:
Prefix Name args
Infix arg1 `Name` arg2 or arg1 op arg2
Record Name{arg1,arg2,...,argn}
The pat_lhs for explicitly bidirectional construction cannot use Record syntax. (Because the
rhs expr might be constructing different data constructors.) It can use guards with multiple
equations.
Pattern synonym declarations can only occur in the top level of a module. In particular, they
are not allowed as local definitions.
The variables in the left-hand side of the definition are bound by the pattern on the right-hand
side. For bidirectional pattern synonyms, all the variables of the right-hand side must also
occur on the left-hand side; also, wildcard patterns and view patterns are not allowed. For
unidirectional and explicitly bidirectional pattern synonyms, there is no restriction on the
right-hand side pattern.
Pattern synonyms cannot be defined recursively.
COMPLETE pragmas (page 529) can be specified in order to tell the pattern match exhaus-
tiveness checker that a set of pattern synonyms is complete.
The name of the pattern synonym is in the same namespace as proper data constructors. Like
normal data constructors, pattern synonyms can be imported and exported through associa-
tion with a type constructor or independently.
To export them on their own, in an export or import specification, you must prefix pattern
names with the pattern keyword, e.g.:
Without the pattern prefix, Zero would be interpreted as a type constructor in the export list.
You may also use the pattern keyword in an import/export specification to import or export
an ordinary data constructor. For example:
would bring into scope the data constructor Just from the Maybe type, without also bringing
the type constructor Maybe into scope.
As of GHC 8.0.1 you may also “bundle” pattern synonyms with an exported type constructor,
making that pattern appear as a data constructor of that type. To bundle a pattern synonym,
we list the pattern synonym in the export list of a module which exports the type constructor.
For example, to bundle Zero with MyNum we could write the following:
If a module was then to import MyNum from Example, it would also import the pattern synonym
Zero.
It is also possible to use the special token .. in an export list to mean all currently bundled
constructors. For example, we could write:
in which case, Example would export the type constructor MyNum with the data constructor
MkNum and also the pattern synonym Zero.
Bundled pattern synonyms are type checked to ensure that they are of the same type as the
type constructor which they are bundled with. A pattern synonym P can not be bundled with
a type constructor T if P‘s type is visibly incompatible with T.
A module which imports MyNum(..) from Example and then re-exports MyNum(..) will also
export any pattern synonyms bundled with MyNum in Example. A more complete specification
can be found on the wiki.
pattern P :: CReq => CProv => t1 -> t2 -> ... -> tN -> t
where ⟨CReq⟩ and ⟨CProv⟩ are type contexts, and ⟨t1⟩, ⟨t2⟩, ..., ⟨tN⟩ and ⟨t⟩ are types. Notice
the unusual form of the type, with two contexts ⟨CReq⟩ and ⟨CProv⟩:
• ⟨CReq⟩ are the constraints required to match the pattern.
• ⟨CProv⟩ are the constraints made available (provided) by a successful pattern match.
For example, consider
data T a where
MkT :: (Show b) => a -> b -> T a
Here f1 does not use pattern synonyms. To match against the numeric pattern 42 requires
the caller to satisfy the constraints (Num a,Eq a), so they appear in f1‘s type. The call to
show generates a (Show b) constraint, where b is an existentially type variable bound by the
pattern match on MkT. But the same pattern match also provides the constraint (Show b) (see
MkT‘s type), and so all is well.
Exactly the same reasoning applies to ExNumPat: matching against ExNumPat requires the
constraints (Num a,Eq a), and provides the constraint (Show b).
Note also the following points
• In the common case where CProv is empty, (i.e., ()), it can be omitted altogether in the
above pattern type signature for P.
• However, if CProv is non-empty, while CReq is, the above pattern type signature for P
must be specified as
• The GHCi :info (page 55) command shows pattern types in this format.
• You may specify an explicit pattern signature, as we did for ExNumPat above, to specify
the type of a pattern, just as you can for a function. As usual, the type signature can be
less polymorphic than the inferred type. For example
Just like signatures on value-level bindings, pattern synonym signatures can apply to
more than one pattern. For instance,
pattern Left', Right' :: a -> Either a a
pattern Left' x = Left x
pattern Right' x = Right x
• The rules for lexically-scoped type variables (see Lexically scoped type variables
(page 436)) apply to pattern-synonym signatures. As those rules specify, only the type
variables from an explicit, syntactically-visible outer forall (the universals) scope over
the definition of the pattern synonym; the existentials, bound by the inner forall, do not.
For example
data T a where
MkT :: Bool -> b -> (b->Int) -> a -> T a
Here the universal type variable a scopes over the definition of P, but the existential b
does not. (c.f. discussion on #14998.)
• For a bidirectional pattern synonym, a use of the pattern synonym as an expression has
the type
(CReq, CProv) => t1 -> t2 -> ... -> tN -> t
Notice that this is a tiny bit more restrictive than the expression MkT 42 x which would
not require (Eq a).
• Consider these two pattern synonyms:
data S a where
S1 :: Bool -> S Bool
g :: S a -> String
g (P2 b) = "yes yes yes" -- Fine
Pattern P1 can only match against a value of type Maybe Bool, so function f is rejected
because the type signature is Maybe a. (To see this, imagine expanding the pattern
synonym.)
On the other hand, function g works fine, because matching against P2 (which wraps the
GADT S) provides the local equality (a~Bool). If you were to give an explicit pattern
signature P2 :: Bool -> S Bool, then P2 would become less polymorphic, and would
behave exactly like P1 so that g would then be rejected.
In short, if you want GADT-like behaviour for pattern synonyms, then (unlike concrete
data constructors like S1) you must write its type with explicit provided equalities. For a
concrete data constructor like S1 you can write its type signature as either S1 :: Bool
-> S Bool or S1 :: (b~Bool) => Bool -> S b; the two are equivalent. Not so for pat-
tern synonyms: the two forms are different, in order to distinguish the two cases above.
(See #9953 for discussion of this choice.)
A pattern synonym occurrence in a pattern is evaluated by first matching against the pattern
synonym itself, and then on the argument patterns.
More precisely, the semantics of pattern matching is given in Section 3.17 of the Haskell 2010
report. To the informal semantics in Section 3.17.2 we add this extra rule:
• If the pattern is a constructor pattern (P p1 ... pn), where P is a pattern synonym
defined by P x1 ... xn = p or P x1 ... xn <-p, then:
1. Match the value v against p. If this match fails or diverges, so does the whole (pat-
tern synonym) match. Otherwise the match against p must bind the variables x1 ...
xn; let them be bound to values v1 ... vn.
2. Match v1 against p1, v2 against p2 and so on. If any of these matches fail or diverge,
so does the whole match.
3. If all the matches against the pi succeed, the match succeeds, binding the variables
bound by the pi . (The xi are not bound; they remain local to the pattern synonym
declaration.)
For example, in the following program, f and f' are equivalent:
*Main> f (False:undefined)
*** Exception: [Link]
*Main> g (False:undefined)
False
This section documents GHC’s type-class extensions. There’s lots of background in the paper
Type classes: exploring the design space (Simon Peyton Jones, Mark Jones, Erik Meijer).
MultiParamTypeClasses
Implies ConstrainedClassMethods (page 402)
Since 6.8.1
Allow the definition of typeclasses with more than one parameter.
Multi-parameter type classes are permitted, with extension MultiParamTypeClasses
(page 400). For example:
FlexibleContexts
Since 6.8.1
Allow the use of complex constraints in class declaration contexts.
In Haskell 98 the context of a class declaration (which introduces superclasses) must be sim-
ple; that is, each predicate must consist of a class applied to type variables. The extension
FlexibleContexts (page 400) (The context of a type signature (page 433)) lifts this restric-
tion, so that the only restriction on the context in a class declaration is that the class hierarchy
must be acyclic. So these class declarations are OK:
As in Haskell 98, the class hierarchy must be acyclic. However, the definition of “acyclic”
involves only the superclass relationships. For example, this is okay:
class C a where
op :: D b => a -> b -> b
Here, C is a superclass of D, but it’s OK for a class operation op of C to mention D. (It would
not be OK for D to be a superclass of C.)
With the extension that adds a kind of constraints (page 425), you can write more exotic
superclass definitions. The superclass cycle check is even more liberal in these cases. For
example, this is OK:
A superclass context for a class C is allowed if, after expanding type synonyms to their right-
hand-sides, and uses of classes (other than C) to their superclasses, C does not occur syntac-
tically in the context.
UndecidableSuperClasses
Since 8.0.1
Allow all superclass constraints, including those that may result in non-termination of
the typechecker.
The language extension UndecidableSuperClasses (page 401) allows much more flexible
constraints in superclasses.
A class cannot generally have itself as a superclass. So this is illegal
GHC implements this test conservatively when type functions, or type variables, are involved.
For example
GHC will complain about this, because you might later add
and now we’d be in a superclass loop. Here’s an example involving a type variable
class f (C f) => C f
class c => Id c
If we expanded the superclasses of C Id we’d get first Id (C Id) and thence C Id again.
But superclass constraints like these are sometimes useful, and the conservative check is
annoying where no actual recursion is involved.
Moreover genuinely-recursive superclasses are sometimes useful. Here’s a real-life example
(#10318)
Here the superclass cycle does terminate but it’s not entirely straightforward to see that it
does.
With the language extension UndecidableSuperClasses (page 401) GHC lifts all restrictions
on superclass constraints. If there really is a loop, GHC will only expand it to finite depth.
ConstrainedClassMethods
Since 6.8.1
Allows the definition of further constraints on individual class methods.
Haskell 98 prohibits class method types to mention constraints on the class type variable,
thus:
The type of elem is illegal in Haskell 98, because it contains the constraint Eq a, which con-
strains only the class type variable (in this case a). More precisely, a constraint in a class
method signature is rejected if
• The constraint mentions at least one type variable. So this is allowed:
class C a where
op1 :: HasCallStack => a -> a
op2 :: (?x::Int) => Int -> a
• All of the type variables mentioned are bound by the class declaration, and none is locally
quantified. Examples:
class C a where
op3 :: Eq a => a -> a -- Rejected: constrains class variable only
op4 :: D b => a -> b -- Accepted: constrains a locally-quantified variable␣
,→`b`
GHC lifts this restriction with language extension ConstrainedClassMethods (page 402). The
restriction is a pretty stupid one in the first place, so ConstrainedClassMethods (page 402)
is implied by MultiParamTypeClasses (page 400).
DefaultSignatures
Since 7.2.1
Allows the definition of default method signatures in class definitions.
Haskell 98 allows you to define a default implementation when declaring a class:
The type of the enum method is [a], and this is also the type of the default method. You can
change the type of the default method by requiring a different context using the extension
DefaultSignatures (page 402). For instance, if you have written a generic implementation
of enumeration in a class GEnum with method genum, you can specify a default method that
uses that generic implementation. But your default implementation can only be used if the
constraints are satisfied, therefore you need to change the type of the default method
We reuse the keyword default to signal that a signature applies to the default method only;
when defining instances of the Enum class, the original type [a] of enum still applies. When
giving an empty instance, however, the default implementation (map to genum) is filled-in,
and type-checked with the type (Generic a,GEnum (Rep a)) => [a].
The type signature for a default method of a type class must take on the same form as the
corresponding main method’s type signature. Otherwise, the typechecker will reject that
class’s definition. By “take on the same form”, we mean that the default type signature should
differ from the main type signature only in their contexts. Therefore, if you have a method
bar:
C is allowed to be different from C', but the right-hand sides of the type signatures must
coincide. We require this because when you declare an empty instance for a class that uses
DefaultSignatures (page 402), GHC implicitly fills in the default implementation like this:
Where @Int utilizes visible type application (Visible type application (page 338)) to instantiate
the b in default bar :: forall b. C' => a -> b -> b. In order for this type application
to work, the default type signature for bar must have the same type variable order as the non-
default signature! But there is no obligation for C and C' to be the same (see, for instance,
the Enum example above, which relies on this).
To further explain this example, the right-hand side of the default type signature for bar
must be something that is alpha-equivalent to forall b. a -> b -> b (where a is bound by
the class itself, and is thus free in the methods’ type signatures). So this would also be an
acceptable default type signature:
But not this (since the free variable a is in the wrong place):
Nor this, since we can’t match the type variable b with the concrete type Int:
That last one deserves a special mention, however, since a -> Int -> Int is a straightfor-
ward instantiation of forall b. a -> b -> b. You can still write such a default type signa-
ture, but you now must use type equalities to do so:
NullaryTypeClasses
Since 7.8.1
Allow use and definition of type classes with no parameters. This extension has been
replaced by MultiParamTypeClasses (page 400).
Nullary (no parameter) type classes are enabled with MultiParamTypeClasses (page 400);
historically, they were enabled with the (now deprecated) NullaryTypeClasses (page 404).
Since there are no available parameters, there can be at most one instance of a nullary class.
A nullary type class might be used to document some assumption in a type signature (such as
reliance on the Riemann hypothesis) or add some globally configurable settings in a program.
For example,
The type signature of isPrime informs users that its correctness depends on an unproven
conjecture. If the function is used, the user has to acknowledge the dependence with:
FunctionalDependencies
Implies MultiParamTypeClasses (page 400)
Since 6.8.1
Allow use of functional dependencies in class declarations.
Functional dependencies are implemented as described by Mark Jones in [Jones2000]
(page 637).
Functional dependencies are introduced by a vertical bar in the syntax of a class declaration;
e.g.
In a class declaration, all of the class type variables must be reachable (in the sense mentioned
in The context of a type signature (page 433)) from the free variables of each method type.
For example:
is not OK, because the type of empty doesn’t mention a. Functional dependencies can make
the type variable reachable:
which makes the connection between the type of a collection of a‘s (namely (s a)) and the
element type a. Occasionally this really doesn’t work, in which case you can split the class
like this:
The following description of the motivation and use of functional dependencies is taken from
the Hugs user manual, reproduced here (with minor changes) by kind permission of Mark
Jones.
Consider the following class, intended as part of a library for collection types:
The type variable e used here represents the element type, while ce is the type of the container
itself. Within this framework, we might want to define instances of this class for lists or
characteristic functions (both of which can be used to represent collections of any equality
type), bit sets (which can be used to represent collections of characters), or hash tables (which
can be used to represent any collection whose elements have a hash function). Omitting
standard implementation details, this would lead to the following declarations:
All this looks quite promising; we have a class and a range of interesting implementations.
Unfortunately, there are some serious problems with the class declaration. First, the empty
function has an ambiguous type:
By “ambiguous” we mean that there is a type variable e that appears on the left of the =>
symbol, but not on the right. The problem with this is that, according to the theoretical
foundations of Haskell overloading, we cannot guarantee a well-defined semantics for any
term with an ambiguous type.
We can sidestep this specific problem by removing the empty member from the class declara-
tion. However, although the remaining members, insert and member, do not have ambiguous
types, we still run into problems when we try to use them. For example, consider the following
two functions:
f x y = insert x . insert y
g = f True 'a'
Notice that the type for f allows the two parameters x and y to be assigned different types,
even though it attempts to insert each of the two values, one after the other, into the same
collection. If we’re trying to model collections that contain only one type of value, then this
is clearly an inaccurate type. Worse still, the definition for g is accepted, without causing a
type error. As a result, the error in this code will not be flagged at the point where it appears.
Instead, it will show up only when we try to use g, which might even be in a different module.
Faced with the problems described above, some Haskell programmers might be tempted to
use something like the following version of the class declaration:
The key difference here is that we abstract over the type constructor c that is used to form the
collection type c e, and not over that collection type itself, represented by ce in the original
class declaration. This avoids the immediate problems that we mentioned above: empty has
type Collects e c => c e, which is not ambiguous.
The function f from the previous section has a more accurate type:
The function g from the previous section is now rejected with a type error as we would hope
because the type of f does not allow the two arguments to have different types. This, then,
is an example of a multiple parameter class that does actually work quite well in practice,
without ambiguity problems. There is, however, a catch. This version of the Collects class is
nowhere near as general as the original class seemed to be: only one of the four instances for
Collects given above can be used with this version of Collects because only one of them—
the instance for lists—has a collection type that can be written in the form c e, for some type
constructor c, and element type e.
To get a more useful version of the Collects class, GHC provides a mechanism that allows
programmers to specify dependencies between the parameters of a multiple parameter class
(For readers with an interest in theoretical foundations and previous work: The use of depen-
dency information can be seen both as a generalisation of the proposal for “parametric type
classes” that was put forward by Chen, Hudak, and Odersky, or as a special case of Mark
Jones’s later framework for “improvement” of qualified types. The underlying ideas are also
discussed in a more theoretical and abstract setting in a manuscript [Jones1999] (page 637),
where they are identified as one point in a general design space for systems of implicit pa-
rameterisation). To start with an abstract example, consider a declaration such as:
which tells us simply that C can be thought of as a binary relation on types (or type construc-
tors, depending on the kinds of a and b). Extra clauses can be included in the definition
of classes to add information about dependencies between parameters, as in the following
examples:
The notation a -> b used here between the | and where symbols — not to be confused with
a function type — indicates that the a parameter uniquely determines the b parameter, and
might be read as “a determines b.” Thus D is not just a relation, but actually a (partial) function.
Similarly, from the two dependencies that are included in the definition of E, we can see that
E represents a (partial) one-to-one mapping between types.
More generally, dependencies take the form x1 ... xn -> y1 ... ym, where x1, ..., xn, and
y1, ..., yn are type variables with n>0 and m>=0, meaning that the y parameters are uniquely
determined by the x parameters. Spaces can be used as separators if more than one variable
appears on any single side of a dependency, as in t -> a b. Note that a class may be anno-
tated with multiple dependencies using commas as separators, as in the definition of E above.
Some dependencies that we can write in this notation are redundant, and will be rejected
because they don’t serve any useful purpose, and may instead indicate an error in the pro-
gram. Examples of dependencies like this include a -> a, a -> a a, a ->, etc. There can
also be some redundancy if multiple dependencies are given, as in a->b, b->c, a->c, and in
which some subset implies the remaining dependencies. Examples like this are not treated as
errors. Note that dependencies appear only in class declarations, and not in any other part of
the language. In particular, the syntax for instance declarations, class constraints, and types
is completely unchanged.
By including dependencies in a class declaration, we provide a mechanism for the program-
mer to specify each multiple parameter class more precisely. The compiler, on the other hand,
is responsible for ensuring that the set of instances that are in scope at any given point in
the program is consistent with any declared dependencies. For example, the following pair
of instance declarations cannot appear together in the same scope because they violate the
dependency for D, even though either one on its own would be acceptable:
Note also that the following declaration is not allowed, even by itself:
The problem here is that this instance would allow one particular choice of [a] to be asso-
ciated with more than one choice for b, which contradicts the dependency specified in the
definition of D. More generally, this means that, in any instance of the form:
for some particular types t and s, the only variables that can appear in s are the ones that
appear in t, and hence, if the type t is known, then s will be uniquely determined.
The benefit of including dependency information is that it allows us to define more general
multiple parameter classes, without ambiguity problems, and with the benefit of more accu-
rate types. To illustrate this, we return to the collection class example, and annotate the
original definition of Collects with a simple dependency:
The dependency ce -> e here specifies that the type e of elements is uniquely determined by
the type of the collection ce. Note that both parameters of Collects are of kind Type; there
are no constructor classes here. Note too that all of the instances of Collects that we gave
earlier can be used together with this new definition.
What about the ambiguity problems that we encountered with the original definition? The
empty function still has type Collects e ce => ce, but it is no longer necessary to regard
that as an ambiguous type: Although the variable e does not appear on the right of the =>
symbol, the dependency for class Collects tells us that it is uniquely determined by ce, which
does appear on the right of the => symbol. Hence the context in which empty is used can
still give enough information to determine types for both ce and e, without ambiguity. More
generally, we need only regard a type as ambiguous if it contains a variable on the left of the
=> that is not uniquely determined (either directly or indirectly) by the variables on the right.
Dependencies also help to produce more accurate types for user defined functions, and hence
to provide earlier detection of errors, and less cluttered types for programmers to work with.
Recall the previous definition for a function f:
Given the dependency information that we have for Collects, however, we can deduce that
a and b must be equal because they both appear as the second parameter in a Collects
constraint with the same first parameter c. Hence we can infer a shorter and more accurate
type for f:
In a similar way, the earlier definition of g will now be flagged as a type error.
Although we have given only a few examples here, it should be clear that the addition of
dependency information can help to make multiple parameter classes more useful in practice,
avoiding ambiguity problems, and allowing more general sets of instance declarations.
instance (assertion1, ..., assertionn) => class type1 ... typem where ...
The part before the “=>” is the context, while the part after the “=>” is the head of the instance
declaration.
When GHC tries to resolve, say, the constraint C Int Bool, it tries to match every instance
declaration against the constraint, by instantiating the head of the instance declaration. Con-
sider these declarations:
GHC’s default behaviour is that exactly one instance must match the constraint it is trying to
resolve. For example, the constraint C Int Bool matches instances (A) and (B), and hence
would be rejected; while C Int Char matches only (A) and hence (A) is chosen.
Notice that
• When matching, GHC takes no account of the context of the instance declaration
(context1 etc).
• It is fine for there to be a potential of overlap (by including both declarations (A) and (B),
say); an error is only reported if a particular constraint matches more than one.
See also Overlapping instances (page 414) for flags that loosen the instance resolution rules.
TypeSynonymInstances
Since 6.8.1
Allow definition of type class instances for type synonyms.
FlexibleInstances
Implies TypeSynonymInstances (page 409)
Since 6.8.1
Allow definition of type class instances with arbitrary nested types in the instance head.
In Haskell 98 the head of an instance declaration must be of the form C (T a1 ... an), where
C is the class, T is a data type constructor, and the a1 ... an are distinct type variables. In
the case of multi-parameter type classes, this rule applies to each parameter of the instance
head (Arguably it should be okay if just one has this form and the others are type variables,
but that’s the rules at the moment).
GHC relaxes this rule in two ways:
• With the TypeSynonymInstances (page 409) extension, instance heads may use type
synonyms. As always, using a type synonym is just shorthand for writing the RHS of the
type synonym definition. For example:
As always, type synonyms must be fully applied. You cannot, for example, write:
• The FlexibleInstances (page 409) extension allows the head of the instance decla-
ration to mention arbitrary nested types. For example, this becomes a legal instance
declaration
The top of an instance declaration only permits very specific forms of types. To make more
precise what forms of types are or are not permitted, we provide a BNF-style grammar for
the tops of instance declarations below:
Where:
• btype is a type that is not allowed to have an outermost forall/=> unless it is surrounded
by parentheses. For example, forall a. a and Eq a => a are not legal btype``s,but
``(forall a. a) and (Eq a => a) are legal.
• ctype is a btype that has no restrictions on an outermost forall/=>, so forall a. a
and Eq a => a are legal ‘‘ctype‘‘s.
• arg_type is a type that is not allowed to have ‘‘forall‘‘s or ‘‘=>‘‘s
• prefix_cls_tycon is a class type constructor written prefix (e.g., Show or (&&&)), while
infix_cls_tycon is a class type constructor written infix (e.g., `Show` or &&&).
This is a simplified grammar that does not fully delve into all of the implementation details of
GHC’s parser (such as the placement of Haddock comments), but it is sufficient to attain an
understanding of what is syntactically allowed. Some further various observations about this
grammar:
• Instance declarations are not allowed to be declared with nested ‘‘forall‘‘s or ‘‘=>‘‘s.
For example, this would be rejected:
As a result, inst_top puts all of its quantification and constraints up front with
opt_forall and opt_context.
• Furthermore, instance declarations types do not permit outermost parentheses that sur-
round the opt_forall or opt_ctxt, if at least one of them are used. For example, in-
stance (forall a. C a) would be rejected, since GHC would treat the forall as being
nested.
Note that it is acceptable to use parentheses in a inst_head. For instance, instance (C
a) is accepted, as is instance forall a. (C a).
In Haskell 98, the class constraints in the context of the instance declaration must be of the
form C a where a is a type variable that occurs in the head.
The FlexibleContexts (page 400) extension relaxes this rule, as well as relaxing the corre-
sponding rule for type signatures (see The context of a type signature (page 433)). Specifi-
cally, FlexibleContexts (page 400), allows (well-kinded) class constraints of form (C t1 ...
tn) in the context of an instance declaration.
Notice that the extension does not affect equality constraints in an instance context; they are
permitted by TypeFamilies (page 298) or GADTs (page 296).
However, the instance declaration must still conform to the rules for instance termination:
see Instance termination rules (page 412).
UndecidableInstances
Since 6.8.1
Permit definition of instances which may lead to type-checker non-termination.
Regardless of FlexibleInstances (page 409) and FlexibleContexts (page 400), instance
declarations must conform to some rules that ensure that instance resolution will terminate.
The restrictions can be lifted with UndecidableInstances (page 412) (see Undecidable in-
stances (page 413)).
The rules are these:
1. The Paterson Conditions: for each class constraint (C t1 ... tn) in the context
(a) No type variable has more occurrences in the constraint than in the head
(b) The constraint has fewer constructors and variables (taken together and counting
repetitions) than the head
(c) The constraint mentions no type functions. A type function application can in prin-
ciple expand to a type of arbitrary size, and so are rejected out of hand
2. The Coverage Condition. For each functional dependency, ⟨tvs⟩left -> ⟨tvs⟩right , of the
class, every type variable in S(⟨tvs⟩right ) must appear in S(⟨tvs⟩left ), where S is the substi-
tution mapping each type variable in the class declaration to the corresponding type in
the instance head.
These restrictions ensure that instance resolution terminates: each reduction step makes
the problem smaller by at least one constructor. You can find lots of background material
about the reason for these restrictions in the paper Understanding functional dependencies
via Constraint Handling Rules.
For example, these are okay:
The same restrictions apply to instances generated by deriving clauses. Thus the following
is accepted:
data MinHeap h a = H a (h a)
deriving (Show)
instance C a where
op = ... -- Default
Undecidable instances
Sometimes even the termination rules of Instance termination rules (page 412) are too oner-
ous. So GHC allows you to experiment with more liberal rules: if you use the experimental
extension UndecidableInstances (page 412), both the Paterson Conditions and the Coverage
Condition (described in Instance termination rules (page 412)) are lifted. Termination is still
ensured by having a fixed-depth recursion stack. If you exceed the stack depth you get a sort
of backtrace, and the opportunity to increase the stack depth with -freduction-depth=⟨n⟩.
However, if you should exceed the default reduction depth limit, it is probably best just to
disable depth checking, with -freduction-depth=0. The exact depth your program requires
depends on minutiae of your code, and it may change between minor GHC releases. The
safest bet for released code – if you’re sure that it should compile in finite time – is just to
disable the check.
For example, sometimes you might want to use the following to get the effect of a “class
synonym”:
f :: C a => ...
instead of
The restrictions on functional dependencies (Functional dependencies (page 404)) are par-
ticularly troublesome. It is tempting to introduce type variables in the context that do not
appear in the head, something that is excluded by the normal rules. For example:
This is dangerous territory, however. Here, for example, is a program that would make the
typechecker loop:
class D a
class F a b | a->b
instance F [a] [[a]]
instance (D c, F a c) => D [a] -- 'c' is not mentioned in the head
The third instance declaration does not obey the coverage condition; and indeed the (some-
what strange) definition:
makes instance inference go into a loop, because it requires the constraint (Mul a [b] b).
The UndecidableInstances (page 412) extension is also used to lift some of the restrictions
imposed on type family instances. See Decidability of type synonym instances (page 306).
Overlapping instances
OverlappingInstances
Deprecated extension to weaken checks intended to ensure instance resolution termina-
tion.
IncoherentInstances
Since 6.8.1
Deprecated extension to weaken checks intended to ensure instance resolution termina-
tion.
In general, as discussed in Instance declarations and resolution (page 409), GHC requires
that it be unambiguous which instance declaration should be used to resolve a type-class
constraint. GHC also provides a way to loosen the instance resolution, by allowing more than
one instance to match, provided there is a most specific one. Moreover, it can be loosened
further, by allowing more than one instance to match irrespective of whether there is a most
specific one. This section gives the details.
To control the choice of instance, it is possible to specify the overlap behavior for individ-
ual instances with a pragma, written immediately after the instance keyword. The pragma
may be one of: {-# OVERLAPPING #-}, {-# OVERLAPPABLE #-}, {-# OVERLAPS #-}, or {-#
INCOHERENT #-}.
The matching behaviour is also influenced by two module-level language extension flags:
OverlappingInstances (page 414) and IncoherentInstances (page 414). These extensions
are now deprecated (since GHC 7.10) in favour of the fine-grained per-instance pragmas.
A more precise specification is as follows. The willingness to be overlapped or incoherent is
a property of the instance declaration itself, controlled as follows:
• An instance is incoherent if: it has an INCOHERENT pragma; or if the instance has no
pragma and it appears in a module compiled with IncoherentInstances (page 414).
• An instance is overlappable if: it has an OVERLAPPABLE or OVERLAPS pragma; or if the in-
stance has no pragma and it appears in a module compiled with OverlappingInstances
(page 414); or if the instance is incoherent.
• An instance is overlapping if: it has an OVERLAPPING or OVERLAPS pragma; or if the in-
stance has no pragma and it appears in a module compiled with OverlappingInstances
(page 414); or if the instance is incoherent.
Now suppose that, in some client module, we are searching for an instance of the target
constraint (C ty1 .. tyn). The search works like this:
• Find all instances I that match the target constraint; that is, the target constraint is a
substitution instance of I. These instance declarations are the candidates.
• If no candidates remain, the search fails
• Eliminate any candidate IX for which there is another candidate IY such that both of
the following hold:
– IY is strictly more specific than IX. That is, IY is a substitution instance of IX but
not vice versa.
– Either IX is overlappable, or IY is overlapping. (This “either/or” design, rather than
a “both/and” design, allow a client to deliberately override an instance from a library,
without requiring a change to the library.)
• If all the remaining candidates are incoherent, the search succeeds, returning an arbi-
trary surviving candidate.
• If more than one non-incoherent candidate remains, the search fails.
• Otherwise there is exactly one non-incoherent candidate; call it the “prime candidate”.
• Now find all instances, or in-scope given constraints, that unify with the target con-
straint, but do not match it. Such non-candidate instances might match when the target
constraint is further instantiated. If all of them are incoherent top-level instances, the
search succeeds, returning the prime candidate. Otherwise the search fails.
Notice that these rules are not influenced by flag settings in the client module, where the
instances are used. These rules make it possible for a library author to design a library that
relies on overlapping instances without the client having to know.
Errors are reported lazily (when attempting to solve a constraint), rather than eagerly (when
the instances themselves are defined). Consider, for example
These potentially overlap, but GHC will not complain about the instance declarations them-
selves, regardless of flag settings. If we later try to solve the constraint (C Int Char) then
only the first instance matches, and all is well. Similarly with (C Bool Bool). But if we try
to solve (C Int Bool), both instances match and an error is reported.
instance {-# OVERLAPPABLE #-} context1 => C Int b where ... -- (A)
instance {-# OVERLAPPABLE #-} context2 => C a Bool where ... -- (B)
instance {-# OVERLAPPABLE #-} context3 => C a [b] where ... -- (C)
instance {-# OVERLAPPING #-} context4 => C Int [Int] where ... -- (D)
Now suppose that the type inference engine needs to solve the constraint C Int [Int]. This
constraint matches instances (A), (C) and (D), but the last is more specific, and hence is
chosen.
If (D) did not exist then (A) and (C) would still be matched, but neither is most specific. In that
case, the program would be rejected, unless IncoherentInstances (page 414) is enabled, in
which case it would be accepted and (A) or (C) would be chosen arbitrarily.
An instance declaration is more specific than another iff the head of former is a substitution
instance of the latter. For example (D) is “more specific” than (C) because you can get from
(C) to (D) by substituting a := Int.
The final bullet (about unifying instances) makes GHC conservative about committing to an
overlapping instance. For example:
Suppose that from the RHS of f we get the constraint C b [b]. But GHC does not commit to
instance (C), because in a particular call of f, b might be instantiated to Int, in which case
instance (D) would be more specific still. So GHC rejects the program.
If, however, you enable the extension IncoherentInstances (page 414) when compiling the
module that contains (D), GHC will instead pick (C), without complaining about the problem
of subsequent instantiations.
Notice that we gave a type signature to f, so GHC had to check that f has the specified type.
Suppose instead we do not give a type signature, asking GHC to infer it instead. In this case,
GHC will refrain from simplifying the constraint C Int [b] (for the same reason as before)
but, rather than rejecting the program, it will infer the type
That postpones the question of which instance to pick to the call site for f by which time
more is known about the type b. You can write this type signature yourself if you use the
FlexibleContexts (page 400) extension.
Exactly the same situation can arise in instance declarations themselves. Suppose we have
and, as before, the constraint C Int [b] arises from f‘s right hand side. GHC will reject the
instance, complaining as before that it does not know how to resolve the constraint C Int
[b], because it matches more than one instance declaration. The solution is to postpone the
choice by adding the constraint to the context of the instance declaration, thus:
instance C a Int
Here GHC will not solve the constraint (C c Int) from the top-level instance, because a
particular call of g might instantiate both b and c to the same type, which would allow the
constraint to be solved in a different way. This latter restriction is principally to make the
constraint-solver complete. (Interested folk can read Note [Instance and Given overlap]
in TcInteract.) It is easy to avoid: in a type signature avoid a constraint that matches a top-
level instance. The flag -Wsimplifiable-class-constraints (page 99) warns about such
signatures.
Warning: Overlapping instances must be used with care. They can give rise to inco-
herence (i.e. different instance choices are made in different parts of the program) even
without IncoherentInstances (page 414). Consider:
{-# LANGUAGE OverlappingInstances #-}
module Help where
data T = MkT
In function showHelp GHC sees no overlapping instances, and so uses the MyShow [a]
instance without complaint. In the call to myshow in main, GHC resolves the MyShow [T]
constraint using the overlapping instance declaration in module Main. As a result, the
program prints
"Used more specific instance"
"Used generic instance"
(An alternative possible behaviour, not currently implemented, would be to reject module
Help on the grounds that a later instance declaration might overlap the local one.)
InstanceSigs
Since 7.6.1
Allow type signatures for members in instance definitions.
In Haskell, you can’t write a type signature in an instance declaration, but it is sometimes
convenient to do so, and the language extension InstanceSigs (page 418) allows you to do
so. For example:
data T a = MkT a a
instance Eq a => Eq (T a) where
(==) :: T a -> T a -> Bool -- The signature
(==) (MkT x1 x2) (MkTy y1 y2) = x1==y1 && x2==y2
Some details
• The type signature in the instance declaration must be more polymorphic than (or the
same as) the one in the class declaration, instantiated with the instance type. For exam-
ple, this is fine:
Here the signature in the instance declaration is more polymorphic than that required
by the instantiated class method.
• The code for the method in the instance declaration is typechecked against the type
signature supplied in the instance declaration, as you would expect. So if the instance
signature is more polymorphic than required, the code must be too.
• One stylistic reason for wanting to write a type signature is simple documentation. An-
other is that you may want to bring scoped type variables into scope. For example:
class C a where
foo :: b -> a -> (a, [b])
Provided that you also specify ScopedTypeVariables (page 436) (Lexically scoped type
variables (page 436)), the forall b scopes over the definition of foo, and in particular
over the type signature for xs.
6.9 Literals
NegativeLiterals
Since 7.8.1
Enable negative numeric literals.
The literal -123 is, according to Haskell98 and Haskell 2010, two tokens, a unary minus (-)
and the number 123, and is desugared as negate (fromInteger 123). The language exten-
sion NegativeLiterals (page 419) causes it to be treated as a single token and desugared
as fromInteger (-123).
This can be useful when the positive and negative range of a numeric data type don’t match up.
For example, in 8-bit arithmetic -128 is representable, but +128 is not. So negate (fromInte-
ger 128) will elicit an unexpected integer-literal-overflow message.
Whitespace can be inserted, as in -123, to force interpretation as two tokens.
In 9.0, the behavior of this extension changed, and now we require that a negative literal must
not be preceded by a closing token (see GHC Proposal #229 for the definition of a closing
token). In other words, we parse f -123 as f (-123), but x-123 as (-) x 123. Before this
amendment, NegativeLiterals (page 419) caused x-123 to be parsed as x(-123).
NegativeLiterals (page 419) is a subset of LexicalNegation (page 279). That is, enabling
both of those extensions has the same effect as enabling LexicalNegation (page 279) alone.
BinaryLiterals
Since 7.10.1
Allow the use of binary notation in integer literals.
Haskell 2010 and Haskell 98 allows for integer literals to be given in decimal, octal (prefixed
by 0o or 0O), or hexadecimal notation (prefixed by 0x or 0X).
The language extension BinaryLiterals (page 419) adds support for expressing integer lit-
erals in binary notation with the prefix 0b or 0B. For instance, the binary integer literal
0b11001001 will be desugared into fromInteger 201 when BinaryLiterals (page 419) is
enabled.
HexFloatLiterals
Since 8.4.1
Allow writing floating point literals using hexadecimal notation.
The hexadecimal notation for floating point literals is useful when you need to specify floating
point constants precisely, as the literal notation corresponds closely to the underlying bit-
encoding of the number.
In this notation floating point numbers are written using hexadecimal digits, and so the digits
are interpreted using base 16, rather then the usual 10. This means that digits left of the
decimal point correspond to positive powers of 16, while the ones to the right correspond to
negative ones.
You may also write an explicit exponent, which is similar to the exponent in decimal notation
with the following differences:
• the exponent begins with p instead of e
• the exponent is written in base 10 (not 16)
• the base of the exponent is 2 (not 16).
In terms of the underlying bit encoding, each hexadecimal digit corresponds to 4 bits, and
you may think of the exponent as “moving” the floating point by one bit left (negative) or right
(positive). Here are some examples:
• 0x0.1 is the same as 1/16
• 0x0.01 is the same as 1/256
• [Link] is the same as 15 + 15/16 + 15/256
• 0x0.1p4 is the same as 1
• 0x0.1p-4 is the same as 1/256
• 0x0.1p12 is the same as 256
NumDecimals
Since 7.8.1
Allow the use of floating-point literal syntax for integral types.
Haskell 2010 and Haskell 98 define floating literals with the syntax 1.2e6. These literals have
the type Fractional a => a.
The language extension NumDecimals (page 420) allows you to also use the floating literal
syntax for instances of Integral, and have values like (1.2e6 :: Num a => a)
NumericUnderscores
Since 8.6.1
Allow the use of underscores in numeric literals.
GHC allows for numeric literals to be given in decimal, octal, hexadecimal, binary, or float
notation.
The language extension NumericUnderscores (page 420) adds support for expressing under-
scores in numeric literals. For instance, the numeric literal 1_000_000 will be parsed into
1000000 when NumericUnderscores (page 420) is enabled. That is, underscores in numeric
literals are ignored when NumericUnderscores (page 420) is enabled. See also #14473.
For example:
-- decimal
million = 1_000_000
billion = 1_000_000_000
lightspeed = 299_792_458
version = 8_04_1
date = 2017_12_31
-- hexadecimal
red_mask = 0xff_00_00
size1G = 0x3fff_ffff
-- binary
bit8th = 0b01_0000_0000
packbits = 0b1_11_01_0000_0_111
bigbits = 0b1100_1011__1110_1111__0101_0011
-- float
pi = 3.141_592_653_589_793
faraday = 96_485.332_89
avogadro = 6.022_140_857e+23
-- function
isUnderMillion = (< 1_000_000)
clip64M x
| x > 0x3ff_ffff = 0x3ff_ffff
| otherwise = x
About validity:
x0 = 1_000_000 -- valid
x1 = 1__000000 -- valid
x2 = 1000000_ -- invalid
x3 = _1000000 -- invalid
e0 = 0.0001 -- valid
e1 = 0.000_1 -- valid
e2 = 0_.0001 -- invalid
e3 = _0.0001 -- invalid
e4 = 0._0001 -- invalid
e5 = 0.0001_ -- invalid
f0 = 1e+23 -- valid
f1 = 1_e+23 -- valid
f2 = 1__e+23 -- valid
f3 = 1e_+23 -- invalid
g0 = 1e+23 -- valid
g1 = 1e+_23 -- invalid
g2 = 1e+23_ -- invalid
h0 = 0xffff -- valid
h1 = 0xff_ff -- valid
h2 = 0x_ffff -- valid
h3 = 0x__ffff -- valid
h4 = _0xffff -- invalid
OverloadedStrings
Since 6.8.1
Enable overloaded string literals (e.g. string literals desugared via the IsString class).
GHC supports overloaded string literals. Normally a string literal has type String, but with
overloaded string literals enabled (with OverloadedStrings (page 422)) a string literal has
type (IsString a) => a.
This means that the usual string syntax can be used, e.g., for ByteString, Text, and other
variations of string like types. String literals behave very much like integer literals, i.e., they
can be used in both expressions and patterns. If used in a pattern the literal will be replaced
by an equality test, in the same way as an integer literal is.
The class IsString is defined as:
The only predefined instance is the obvious one to make strings work as usual:
The class IsString is not in scope by default. If you want to mention it explicitly (for example,
to give an instance declaration for it), you can import it from module [Link].
Haskell’s defaulting mechanism (Haskell Report, Section 4.3.4) is extended to cover string
literals, when OverloadedStrings (page 422) is specified. Specifically:
• Each type in a default declaration must be an instance of Num or of IsString.
• If no default declaration is given, then it is just as if the module contained the declara-
tion default( Integer,Double,String).
• The standard defaulting rule is extended thus: defaulting applies when all the unresolved
constraints involve standard classes or IsString; and at least one is a numeric class or
IsString.
So, for example, the expression length "foo" will give rise to an ambiguous use of IsString
a0 which, because of the above rules, will default to String.
A small example:
main = do
Note that deriving Eq is necessary for the pattern matching to work since it gets translated
into an equality comparison.
OverloadedLabels
Since 8.0.1
Enable use of the #foo overloaded label syntax.
GHC supports overloaded labels, a form of identifier whose interpretation may depend both on
its type and on its literal text. When the OverloadedLabels (page 423) extension is enabled,
an overloaded label can be written with a prefix hash, for example #foo. The type of this
expression is IsLabel "foo" a => a.
The class IsLabel is defined as:
This is rather similar to the class IsString (see Overloaded string literals (page 422)), but
with an additional type parameter that makes the text of the label available as a type-level
string (see Type-Level Literals (page 336)). Note that fromLabel had an extra Proxy# x
argument in GHC 8.0, but this was removed in GHC 8.2 as a type application (see Visible type
application (page 338)) can be used instead.
There are no predefined instances of this class. It is not in scope by default, but can be
brought into scope by importing [Link]. Unlike IsString, there are no spe-
cial defaulting rules for IsLabel.
During typechecking, GHC will replace an occurrence of an overloaded label like #foo with
fromLabel @"foo". This will have some type alpha and require the solution of a class con-
straint IsLabel "foo" alpha.
The intention is for IsLabel to be used to support overloaded record fields and perhaps anony-
mous records. Thus, it may be given instances for base datatypes (in particular (->)) in the
future.
If RebindableSyntax (page 259) is enabled, overloaded labels will be desug-
ared using whatever fromLabel function is in scope, rather than always using
[Link].
When writing an overloaded label, there must be no space between the hash sign and the
following identifier. The MagicHash (page 242) extension makes use of postfix hash signs; if
OverloadedLabels (page 423) and MagicHash (page 242) are both enabled then x#y means
x# y, but if only OverloadedLabels (page 423) is enabled then it means x #y. The Unboxed-
Tuples (page 474) extension makes (# a single lexeme, so when UnboxedTuples (page 474)
is enabled you must write a space between an opening parenthesis and an overloaded label.
To avoid confusion, you are strongly encouraged to put a space before the hash when using
OverloadedLabels (page 423).
When using OverloadedLabels (page 423) (or other extensions that make use of hash signs) in
a .hsc file (see Writing Haskell interfaces to C code: hsc2hs (page 591)), the hash signs must
be doubled (write ##foo instead of #foo) to avoid them being treated as hsc2hs directives.
Here is an extension of the record access example in Type-Level Literals (page 336) showing
how an overloaded label can be used as a record selector:
example = #x (Point 1 2)
6.10 Constraints
Equality constraints
A type context can include equality constraints of the form t1 ~ t2, which denote that the
types t1 and t2 need to be the same. In the presence of type families, whether two types are
equal cannot generally be decided locally. Hence, the contexts of function signatures may
include equality constraints, as in the following example:
sumCollects :: (Collects c1, Collects c2, Elem c1 ~ Elem c2) => c1 -> c2 -> c2
where we require that the element type of c1 and c2 are the same. In general, the types t1
and t2 of an equality constraint may be arbitrary monotypes; i.e., they may not contain any
quantifiers, independent of whether higher-rank types are otherwise enabled.
Equality constraints can also appear in class and instance contexts. The former enable a
simple translation of programs using functional dependencies into programs using family
synonyms instead. The general idea is to rewrite a class declaration of the form
class C a b | a -> b
to
That is, we represent every functional dependency (FD) a1 .. an -> b by an FD type family
F a1 .. an and a superclass context equality F a1 .. an ~ b, essentially giving a name to
the functional dependency. In class instances, we define the type instances of FD families in
accordance with the class head. Method signatures are not affected by that process.
Heterogeneous equality
GHC also supports kind-heterogeneous equality, which relates two types of potentially differ-
ent kinds. Heterogeneous equality is spelled ~~. Here are the kinds of ~ and ~~ to better
understand their difference:
Users will most likely want ~, but ~~ is available if GHC cannot know, a priori, that the two
types of interest have the same kind. Evidence that (a :: k1) ~~ (b :: k2) tells GHC both
that k1 and k2 are the same and that a and b are the same.
Because ~ is the more common equality relation, GHC prints out ~~ like ~ unless -fprint-
equality-relations (page 82) is set.
Internal to GHC is yet a third equality relation (~#). It is heterogeneous (like ~~) and is
used only internally. It may appear in error messages and other output only when -fprint-
equality-relations (page 82) is enabled.
ConstraintKinds
Since 7.4.1
Allow types of kind Constraint to be used in contexts.
Normally, constraints (which appear in types to the left of the => arrow) have a very restricted
syntax. They can only be:
• Class constraints, e.g. Show a
• Implicit parameter (page 441) constraints, e.g. ?x::Int (with the ImplicitParams
(page 441) extension)
• Equality constraints (page 424), e.g. a ~ Int (with the TypeFamilies (page 298) or
GADTs (page 296) extensions)
With the ConstraintKinds (page 425) extension, GHC becomes more liberal in what it ac-
cepts as constraints in your program. To be precise, with this flag any type of the new kind
Constraint can be used as a constraint. The following things have kind Constraint:
• Anything which is already valid as a constraint without the flag: saturated applications
to type classes, implicit parameter and equality constraints.
• Tuples, all of whose component types have kind Constraint. So for example the type
(Show a,Ord a) is of kind Constraint.
• Anything whose form is not yet known, but the user has declared to have kind Constraint
(for which they need to import it from [Link]). So for example type Foo (f :: Type
-> Constraint) = forall b. f b => b -> b is allowed, as well as examples involving
type families:
Note that because constraints are just handled as types of a particular kind, this extension
allows type constraint synonyms:
Presently, only standard constraints, tuples and type synonyms for those two sorts of con-
straint are permitted in instance contexts and superclasses (without extra flags). The reason
is that permitting more general constraints can cause type checking to loop, as it would with
these two programs:
You may write programs that use exotic sorts of constraints in instance contexts and super-
classes, but to do so you must use UndecidableInstances (page 412) to signal that you don’t
mind if the type checker fails to terminate.
QuantifiedConstraints
Since 8.6.1
Allow constraints to quantify over types.
The extension QuantifiedConstraints (page 426) introduces quantified constraints,
which give a new level of expressiveness in constraints. For example, consider
From the x1==x2 we need Eq a, which is fine. From c1==c2 we need Eq (f (Rose f a))
which is not fine in Haskell today; we have no way to solve such a constraint.
QuantifiedConstraints (page 426) lets us write this
Here, the quantified constraint forall b. (Eq b) => Eq (f b) behaves a bit like a local
instance declaration, and makes the instance typeable.
The paper Quantified class constraints (by Bottu, Karachalias, Schrijvers, Oliveira, Wadler,
Haskell Symposium 2017) describes this feature in technical detail, with examples, and so is
a primary reference source for this feature.
Motivation
This extension allows us to write constraints of the form forall b. Eq b => Eq (f b),
which is needed to solve the Eq (f (Rose f x)) constraint arising from the second
usage of the (==) method.
• Secondly, quantified constraints allow for more concise and precise specifications. As
an example, consider the MTL type class for monad transformers:
The developer knows that a monad transformer takes a monad m into a new monad t
m. But this property is not formally specified in the above declaration. This omission
becomes an issue when defining monad transformer composition:
instance (Trans t1, Trans t2) => Trans (t1 * t2) where
lift = C . lift . lift
The goal here is to lift from monad m to t2 m and then lift this again into t1 (t2 m).
However, this second lift can only be accepted when (t2 m) is a monad and there is
no way of establishing that this fact universally holds.
Quantified constraints enable this property to be made explicit in the Trans class decla-
ration:
Syntax changes
Haskell 2010 defines a context (the bit to the left of => in a type) like this
We extend class (warning: this is a rather confusingly named non-terminal symbol) with two
extra forms, namely precisely what can appear in an instance declaration
The definition of inst is unchanged from the Haskell Report (roughly, just a type). The con-
text => part is optional. That is the only syntactic change to the language.
Notes:
• Where GHC allows extensions in instance declarations we allow exactly the same ex-
tensions to this new form of class. Specifically, with ExplicitForAll (page 431) and
MultiParamTypeClasses (page 400) the syntax becomes
Note that an explicit forall is often absolutely essential. Consider the rose-tree example
Without the forall b, the type variable b would be quantified over the whole instance
declaration, which is not what is intended.
• One of these new quantified constraints can appear anywhere that any other constraint
can, not just in instance declarations. Notably, it can appear in a type signature for a
value binding, data constructor, or expression. For example
f :: (Eq a, forall b. Eq b => Eq (f b)) => Rose f a -> Rose f a -> Bool
f t1 t2 = not (t1 == t2)
See Iceland Jack’s summary. The key point is that the bit to the right of the => may be
headed by a type variable (c in this case), rather than a class. It should not be one of the
forall’d variables, though.
(NB: this goes beyond what is described in the paper, but does not seem to introduce
any new technical difficulties.)
Typing changes
Superclasses
Suppose we have:
f :: forall m. (forall a. Ord a => Ord (m a)) => m Int -> Bool
f x = x == x
From the x==x we need an Eq (m Int) constraint, but the context only gives us a way to figure
out Ord (m a) constraints. But from the given constraint forall a. Ord a => Ord (m a)
we derive a second given constraint forall a. Ord a => Eq (m a), and from that we can
readily solve Eq (m Int). This process is very similar to the way that superclasses already
work: given an Ord a constraint we derive a second given Eq a constraint.
NB: This treatment of superclasses goes beyond the paper, but is specifically desired by users.
Overlap
Quantified constraints can potentially lead to overlapping local axioms. Consider for instance
the following example:
class A a where {}
class B a where {}
class C a where {}
class (A a => C a) => D a where {}
class (B a => C a) => E a where {}
When type checking the instance declaration for F a, we need to check that the superclass C
of F holds. We thus try to entail the constraint C a under the theory containing:
• The instance axioms : (B a,D a,E a) => F a
• The local axioms from the instance context : B a, D a and E a
• The closure of the superclass relation over these local axioms : A a => C a and B a =>
C a
However, the A a => C a and B a => C a axioms both match the wanted constraint C a.
There are several possible approaches for handling these overlapping local axioms:
• Pick first. We can simply select the first matching axiom we encounter. In the above
example, this would be A a => C a. We’d then need to entail A a, for which we have no
matching axioms available, causing the above program to be rejected.
But suppose we made a slight adjustment to the order of the instance context, putting E
a before D a:
Instance lookup
In the light of the overlap decision, instance lookup works like this when trying to solve a
class constraint C t
1. First see if there is a given un-quantified constraint C t. If so, use it to solve the con-
straint.
2. If not, look at all the available given quantified constraints; if exactly one matches C t,
choose it; if more than one matches, report an error.
3. If no quantified constraints match, look up in the global instances, as described in In-
stance declarations and resolution (page 409) and Overlapping instances (page 414).
Termination
GHC uses the Paterson Conditions (page 412) to ensure that instance resolution terminates.
How are those rules modified for quantified constraints? In two ways.
• Each quantified constraint, taken by itself, must satisfy the termination rules for an in-
stance declaration.
• After “for each class constraint (C t1 ... tn)”, add “or each quantified constraint
(forall as. context => C t1 .. tn)“
Note that the second item only at the head of the quantified constraint, not its context. Reason:
the head is the new goal that has to be solved if we use the instance declaration.
Coherence
Although quantified constraints are a little like local instance declarations, they differ in one
big way: the local instances are written by the compiler, not the user, and hence cannot
introduce incoherence. Consider
In ...rhs... there is, in effect a local instance for Eq (f a) for any a. But at a call site for f
the compiler itself produces evidence to pass to f. For example, if we called f Nothing, then
f is Maybe and the compiler must prove (at the call site) that forall a. Eq a => Eq (Maybe
a) holds. It can do this easily, by appealing to the existing instance declaration for Eq (Maybe
a).
In short, quantified constraints do not introduce incoherence.
ExplicitForAll
Since 6.12.1
Allow use of the forall keyword in places where universal quantification is implicit.
Haskell type signatures are implicitly quantified. When the language option ExplicitForAll
(page 431) is used, the keyword forall allows us to say exactly what this means. For example:
g :: b -> b
means this:
g :: forall b. (b -> b)
The two are treated identically, except that the latter may bring type variables into scope (see
Lexically scoped type variables (page 436)).
This extension also enables explicit quantification of type and kind variables in Data in-
stance declarations (page 300), Type instance declarations (page 303), Closed type families
(page 303), Associated instances (page 307), and Rewrite rules (page 504).
Notes:
• As well as in type signatures, you can also use an explicit forall in an instance declara-
tion:
Note that the use of ‘‘forall‘‘s in instance declarations is somewhat restricted in com-
parison to other types. For example, instance declarations are not allowed to contain
nested ‘‘forall‘‘s. See Formal syntax for instance declaration types (page 410) for more
information.
• If the -Wunused-foralls (page 102) flag is enabled, a warning will be emitted when
you write a type variable in an explicit forall statement that is otherwise unused. For
instance:
g :: forall a b. (b -> b)
In certain forms of types, type variables obey what is known as the “forall-or-nothing” rule:
if a type has an outermost, explicit forall, then all of the type variables in the type must be
explicitly quantified. These two examples illustrate how the rule works:
f :: forall a b. a -> b -> b -- OK, `a` and `b` are explicitly bound
g :: forall a. a -> forall b. b -> b -- OK, `a` and `b` are explicitly bound
h :: forall a. a -> b -> b -- Rejected, `b` is not in scope
The type signatures for f, g, and h all begin with an outermost forall, so every type variable
in these signatures must be explicitly bound by a forall. Both f and g obey the forall-or-
nothing rule, since they explicitly quantify a and b. On the other hand, h does not explicitly
quantify b, so GHC will reject its type signature for being improperly scoped.
In places where the forall-or-nothing rule takes effect, if a type does not have an outermost
forall, then any type variables that are not explicitly bound by a forall become implicitly
quantified. For example:
• Data instance declarations (page 300), Type instance declarations (page 303), Closed
type families (page 303), and Associated instances (page 307)
• Rewrite rules (page 504) in which the type variables are explicitly quantified
Notes:
• Pattern type signatures (page 439) are a notable example of a place where types do not
obey the forall-or-nothing rule. For example, GHC will accept the following:
f (g :: forall a. a -> b) x = g x :: b
Furthermore, Rewrite rules (page 504) do not obey the forall-or-nothing rule when
their type variables are not explicitly quantified:
• GADT constructors are extra particular about their foralls. In addition to adhering to
the forall-or-nothing rule, GADT constructors also forbid nested foralls. For example,
GHC would reject the following GADT:
data T where
MkT :: (forall a. a -> b -> T)
Because of the lack of an outermost forall in the type of MkT, the b would be implicitly
quantified. In effect, it would be as if one had written MkT :: forall b. (forall a. a
-> b -> T), which contains nested foralls. See Formal syntax for GADTs (page 292).
The FlexibleContexts (page 400) extension lifts the Haskell 98 restriction that the type-
class constraints in a type signature must have the form (class type-variable) or (class (type-
variable type1 type2 ... typen)). With FlexibleContexts (page 400) these type signatures
are perfectly okay
The flag FlexibleContexts (page 400) also lifts the corresponding restriction on class decla-
rations (Flexible contexts (page 400)) and instance declarations (Relaxed rules for instance
contexts (page 411)).
AllowAmbiguousTypes
Since 7.8.1
Allow type signatures which appear that they would result in an unusable binding.
Each user-written type signature is subjected to an ambiguity check. The ambiguity check
rejects functions that can never be called. For example:
f :: C a => Int
The idea is there can be no legal calls to f because every call will give rise to an ambiguous
constraint. Indeed, the only purpose of the ambiguity check is to report functions that cannot
possibly be called. We could soundly omit the ambiguity check on type signatures entirely,
at the expense of delaying ambiguity errors to call sites. Indeed, the language extension
AllowAmbiguousTypes (page 433) switches off the ambiguity check.
Ambiguity can be subtle. Consider this example which uses functional dependencies:
class D a b | a -> b where ..
h :: D Int b => Int
The Int may well fix b at the call site, so that signature should not be rejected. Moreover, the
dependencies might be hidden. Consider
class X a b where ...
class D a b | a -> b where ...
instance D a b => X [a] b where...
h :: X a b => a -> a
That gives rise to a (X [Bool] beta) constraint, and using the instance means we need (D
Bool beta) and that fixes beta via D‘s fundep!
Behind all these special cases there is a simple guiding principle. Consider
f :: type
f = ...blah...
g :: type
g = f
You would think that the definition of g would surely typecheck! After all f has exactly the
same type, and g=f. But in fact f‘s type is instantiated and the instantiated constraints are
solved against the constraints bound by g‘s signature. So, in the case an ambiguous type,
solving will fail. For example, consider the earlier definition f :: C a => Int:
f :: C a => Int
f = ...blah...
g :: C a => Int
g = f
In g‘s definition, we’ll instantiate to (C alpha) and try to deduce (C alpha) from (C a), and
fail.
So in fact we use this as our definition of ambiguity: a type ty is ambiguous if and only if
((undefined :: ty) :: ty) would fail to typecheck. We use a very similar test for inferred
types, to ensure that they too are unambiguous.
Switching off the ambiguity check. Even if a function has an ambiguous type according to the
“guiding principle”, it is possible that the function is callable. For example:
class D a b where ...
instance D Bool b where ...
strange = ...blah...
Here strange‘s type is ambiguous, but the call in foo is OK because it gives rise to a constraint
(D Bool beta), which is soluble by the (D Bool b) instance.
Another way of getting rid of the ambiguity at the call site is to use the TypeApplications
(page 338) extension to specify the types. For example:
class D a b where
h :: b
instance D Int Int where ...
Here a is ambiguous in the definition of D but later specified to be Int using type applications.
AllowAmbiguousTypes (page 433) allows you to switch off the ambiguity check. However,
even with ambiguity checking switched off, GHC will complain about a function that can
never be called, such as this one:
Sometimes AllowAmbiguousTypes (page 433) does not mix well with RankNTypes (page 342).
For example:
h :: Int
h = foo boo
This program will be rejected as ambiguous because GHC will not unify the type variables j
and i.
Unlike the previous examples, it is not currently possible to resolve the ambiguity manually
by using TypeApplications (page 338).
Note: A historical note. GHC used to impose some more restrictive and less principled
conditions on type signatures. For type forall tv1..tvn (c1,...,cn) => type GHC used
to require
1. that each universally quantified type variable tvi must be “reachable” from type, and
2. that every constraint ci mentions at least one of the universally quantified type variables
tvi. These ad-hoc restrictions are completely subsumed by the new ambiguity check.
KindSignatures
Since 6.8.1
The only use for the Unused constructor was to force the correct kind for the type variable
cxt.
GHC now instead allows you to specify the kind of a type variable directly, wherever a type
variable is explicitly bound, with the extension KindSignatures (page 435).
This extension enables kind signatures in the following places:
• data declarations:
• type declarations:
• class declarations:
The syntax is
ScopedTypeVariables
Implies ExplicitForAll (page 431)
Since 6.8.1
Enable lexical scoping of type variables explicitly introduced with forall.
Tip: ScopedTypeVariables (page 436) breaks GHC’s usual rule that explicit forall is op-
tional and doesn’t affect semantics. For the Declaration type signatures (page 438) (or Ex-
pression type signatures (page 439)) examples in this section, the explicit forall is required.
(If omitted, usually the program will not compile; in a few cases it will compile but the func-
tions get a different signature.) To trigger those forms of ScopedTypeVariables (page 436),
the forall must appear against the top-level signature (or outer expression) but not against
nested signatures referring to the same type variables.
Explicit forall is not always required – see pattern signature equivalent (page 437) for the
example in this section, or Pattern type signatures (page 439).
GHC supports lexically scoped type variables, without which some type signatures are simply
impossible to write. For example:
The type signature for f brings the type variable a into scope, because of the explicit forall
(Declaration type signatures (page 438)). The type variables bound by a forall scope over
the entire definition of the accompanying value declaration. In this example, the type variable
a scopes over the whole definition of f, including over the type signature for ys. In Haskell
98 it is not possible to declare a type for ys; a major benefit of scoped type variables is that
it becomes possible to do so. An equivalent form for that example, avoiding explicit forall
uses Pattern type signatures (page 439):
Unlike the forall form, type variable a from f‘s signature is not scoped over f‘s equation(s).
Type variable aa bound by the pattern signature is scoped over the right-hand side of f‘s equa-
tion. (Therefore there is no need to use a distinct type variable; using a would be equivalent.)
Overview
A declaration type signature that has explicit quantification (using forall) brings into scope
the explicitly-quantified type variables, in the definition of the named function. For example:
f :: forall a. [a] -> [a]
f (x:xs) = xs ++ [ x :: a ]
This program will be rejected, because “a” does not scope over the definition of “g”, so
“x::a” means “x::forall a. a” by Haskell’s usual implicit quantification rules.
• The type variable is quantified by the single, syntactically visible, outermost forall of
the type signature. For example, GHC will reject all of the following examples:
f1 :: forall a. forall b. a -> [b] -> [b]
f1 _ (x:xs) = xs ++ [ x :: b ]
f3 :: Foo
f3 (x:xs) = xs ++ [ x :: b ]
In f1 and f2, the type variable b is not quantified by the outermost forall, so it is not
in scope over the bodies of the functions. Neither is b in scope over the body of f3, as
the forall is tucked underneath the Foo type synonym.
• The signature gives a type for a function binding or a bare variable binding, not a pattern
binding. For example:
f1 :: forall a. [a] -> [a]
f1 (x:xs) = xs ++ [ x :: a ] -- OK
f1 is a function binding, and f2 binds a bare variable; in both cases the type signature
brings a into scope. However the binding for f3 is a pattern binding, and so f3 is a fresh
variable brought into scope by the pattern, not connected with top level f3. Then type
variable a is not in scope of the right-hand side of Just f3 = ....
An expression type signature that has explicit quantification (using forall) brings into scope
the explicitly-quantified type variables, in the annotated expression. For example:
Here, the type signature forall s. ST s Bool brings the type variable s into scope, in the
annotated expression (op >>= \(x :: STRef s Int) -> g x).
A type signature may occur in any pattern; this is a pattern type signature. For example:
g (x::a) = x
In the case where all the type variables in the pattern type signature are already in scope (i.e.
bound by the enclosing context), matters are simple: the signature simply constrains the type
of the pattern in the obvious way.
Unlike expression and declaration type signatures, pattern type signatures are not implicitly
generalised. The pattern in a pattern binding may only mention type variables that are already
in scope. For example:
Here, the pattern signatures for ys and zs are fine, but the one for v is not because b is not
in scope.
However, in all patterns other than pattern bindings, a pattern type signature may mention
a type variable that is not in scope; in this case, the signature brings that type variable into
scope. For example:
-- same f and g as above, now assuming that 'a' is not already in scope
f = \(x::Int, y::a) -> x -- 'a' is in scope on RHS of ->
g (x::a) = x :: a
hh (Just (v :: b)) = v :: b
The pattern type signature makes the type variable available on the right-hand side of the
equation.
Bringing type variables into scope is particularly important for existential data constructors.
For example:
k :: T -> T
k (MkT [t::a]) =
MkT t3
where
(t3::[a]) = [t,t,t]
Here, the pattern type signature [t::a] mentions a lexical type variable that is not already
in scope. Indeed, it must not already be in scope, because it is bound by the pattern match.
The effect is to bring it into scope, standing for the existentially-bound type variable.
It does seem odd that the existentially-bound type variable must not be already in scope.
Contrast that usually name-bindings merely shadow (make a ‘hole’) in a same-named outer
variable’s scope. But we must have some way to bring such type variables into scope, else
we could not name existentially-bound type variables in subsequent type signatures.
Compare the two (identical) definitions for examples f, g; they are both legal whether or not
a is already in scope. They differ in that if a is already in scope, the signature constrains the
pattern, rather than the pattern binding the variable.
ScopedTypeVariables (page 436) allow the type variables bound by the top of a class or
instance declaration to scope over the methods defined in the where part. Unlike :ref‘decl-
type-sigs‘, type variables from class and instance declarations can be lexically scoped without
an explicit forall (although you are allowed an explicit forall in an instance declaration;
see Explicit universal quantification (forall) (page 431)). For example:
class C a where
op :: [a] -> a
op xs = let ys::[a]
ys = reverse xs
in
head ys
While ScopedTypeVariables (page 436) is required for type variables from the top of a class
or instance declaration to scope over the /bodies/ of the methods, it is not required for the
type variables to scope over the /type signatures/ of the methods. For example, the following
will be accepted without explicitly enabling ScopedTypeVariables (page 436):
class D a where
m :: [a] -> a
Note that writing m :: [a] -> [a] requires the use of the InstanceSigs (page 418) exten-
sion.
Similarly, ScopedTypeVariables (page 436) is not required for type variables from the top of
the class or instance declaration to scope over associated type families, which only requires
the TypeFamilies (page 298) extension. For instance, the following will be accepted without
explicitly enabling ScopedTypeVariables (page 436):
class E a where
type T a
ImplicitParams
Since 6.8.1
Allow definition of functions expecting implicit parameters.
Implicit parameters are implemented as described in [Lewis2000] (page 637) and enabled
with the option ImplicitParams (page 441). (Most of the following, still rather incomplete,
documentation is due to Jeff Lewis.)
A variable is called dynamically bound when it is bound by the calling context of a function and
statically bound when bound by the callee’s context. In Haskell, all variables are statically
bound. Dynamic binding of variables is a notion that goes back to Lisp, but was later discarded
in more modern incarnations, such as Scheme. Dynamic binding can be very confusing in an
untyped language, and unfortunately, typed languages, in particular Hindley-Milner typed
languages like Haskell, only support static scoping of variables.
However, by a simple extension to the type class system of Haskell, we can support dynamic
binding. Basically, we express the use of a dynamically bound variable as a constraint on the
type. These constraints lead to types of the form (?x::t') => t, which says “this function
uses a dynamically-bound variable ?x of type t'”. For example, the following expresses the
type of a sort function, implicitly parameterised by a comparison function named cmp.
The dynamic binding constraints are just a new form of predicate in the type class system.
An implicit parameter occurs in an expression using the special form ?x, where x is any valid
identifier (e.g. ord ?x is a valid expression). Use of this construct also introduces a new
dynamic-binding constraint in the type of the expression. For example, the following def-
inition shows how we can define an implicitly parameterised sort function in terms of an
explicitly parameterised sortBy function:
sortBy :: (a -> a -> Bool) -> [a] -> [a]
Dynamic binding constraints behave just like other type class constraints in that they are
automatically propagated. Thus, when a function is used, its implicit parameters are inherited
by the function that called it. For example, our sort function might be used to pick out the
least value in a list:
least :: (?cmp :: a -> a -> Bool) => [a] -> a
least xs = head (sort xs)
Without lifting a finger, the ?cmp parameter is propagated to become a parameter of least
as well. With explicit parameters, the default is that parameters must always be explicit
propagated. With implicit parameters, the default is to always propagate them.
An implicit-parameter type constraint differs from other type class constraints in the following
way: All uses of a particular implicit parameter must have the same type. This means that
the type of (?x,?x) is (?x::a) => (a,a), and not (?x::a,?x::b) => (a,b), as would be
the case for type class constraints.
You can’t have an implicit parameter in the context of a class or instance declaration. For
example, both these declarations are illegal:
class (?x::Int) => C a where ...
instance (?x::a) => Foo [a] where ...
Reason: exactly which implicit parameter you pick up depends on exactly where you invoke
a function. But the “invocation” of instance declarations is done behind the scenes by the
compiler, so it’s hard to figure out exactly where it is done. Easiest thing is to outlaw the
offending types.
Implicit-parameter constraints do not cause ambiguity. For example, consider:
f :: (?x :: [a]) => Int -> Int
f n = n + length ?x
Here, g has an ambiguous type, and is rejected, but f is fine. The binding for ?x at f‘s call
site is quite unambiguous, and fixes the type a.
Implicit-parameter bindings
An implicit parameter is bound using the standard let or where binding forms. For example,
we define the min function by binding cmp.
A group of implicit-parameter bindings may occur anywhere a normal group of Haskell bind-
ings can occur, except at top level. That is, they can occur in a let (including in a list com-
prehension, or do-notation, or pattern guards), or a where clause. Note the following points:
• An implicit-parameter binding group must be a collection of simple bindings to implicit-
style variables (no function-style bindings, and no type signatures); these bindings are
neither polymorphic or recursive.
• You may not mix implicit-parameter bindings with ordinary bindings in a single let ex-
pression; use two nested lets instead. (In the case of where you are stuck, since you
can’t nest where clauses.)
• You may put multiple implicit-parameter bindings in a single binding group; but they are
not treated as a mutually recursive group (as ordinary let bindings are). Instead they
are treated as a non-recursive group, simultaneously binding all the implicit parameter.
The bindings are not nested, and may be re-ordered without changing the meaning of
the program. For example, consider:
f t = let { ?x = t; ?y = ?x+(1::Int) } in ?x + ?y
The use of ?x in the binding for ?y does not “see” the binding for ?x, so the type of f is
len_acc1 [] = ?acc
len_acc1 (x:xs) = let ?acc = ?acc + (1::Int) in len_acc1 xs
------------
The only difference between the two groups is that in the second group len_acc is given a
type signature. In the former case, len_acc1 is monomorphic in its own right-hand side, so
the implicit parameter ?acc is not passed to the recursive call. In the latter case, because
len_acc2 has a type signature, the recursive call is made to the polymorphic version, which
takes ?acc as an implicit parameter. So we get the following results in GHCi:
Adding a type signature dramatically changes the result! This is a rather counter-intuitive
phenomenon, worth watching out for.
GHC applies the dreaded Monomorphism Restriction (section 4.5.5 of the Haskell Report) to
implicit parameters. For example, consider:
Since the binding for y falls under the Monomorphism Restriction it is not generalised, so the
type of y is simply Int, not (?x::Int) => Int. Hence, (f 9) returns result 9. If you add a
type signature for y, then y will get type (?x::Int) => Int, so the occurrence of y in the
body of the let will see the inner binding of ?x, so (f 9) will return 14.
PartialTypeSignatures
Since 7.10.1
Type checker will allow inferred types for holes.
A partial type signature is a type signature containing special placeholders called wildcards.
A wildcard is written as an underscore (e.g. “_”) or, if NamedWildCards (page 445) is enabled,
any identifier with a leading underscore (e.g. “_foo”, “_bar”). Partial type signatures are to
type signatures what Typed Holes (page 266) are to expressions. During compilation these
wildcards or holes will generate an error message that describes which type was inferred at
the hole’s location, and information about the origin of any free type variables. GHC reports
such error messages by default.
Unlike Typed Holes (page 266), which make the program incomplete and will generate errors
when they are evaluated, this needn’t be the case for holes in type signatures. The type
checker is capable (in most cases) of type-checking a binding with or without a type signature.
A partial type signature bridges the gap between the two extremes, the programmer can
choose which parts of a type to annotate and which to leave over to the type-checker to infer.
By default, the type-checker will report an error message for each hole in a partial type sig-
nature, informing the programmer of the inferred type. When the PartialTypeSignatures
(page 444) extension is enabled, the type-checker will accept the inferred type for each hole,
generating warnings instead of errors. Additionally, these warnings can be silenced with the
-Wno-partial-type-signatures (page 89) flag.
However, because GHC must infer the type when part of a type is left out, it is unable to use
polymorphic recursion. The same restriction takes place when the type signature is omitted
completely.
Syntax
A (partial) type signature has the following form: forall a b .. . (C1,C2,..) => tau. It
consists of three parts:
Type Wildcards
Wildcards occurring within the monotype (tau) part of the type signature are type wildcards
(“type” is often omitted as this is the default kind of wildcard). Type wildcards can be instanti-
ated to any monotype like Bool or Maybe [Bool], including functions and higher-kinded types
like (Int -> Bool) or Maybe.
maybools :: _
maybools = Just [True]
-- Inferred: Maybe [Bool]
just1 :: _ Int
just1 = Just 1
-- Inferred: Maybe Int
For instance, the first wildcard in the type signature not' would produce the following error
message:
[Link]:17: error:
• Found type wildcard ‘_’ standing for ‘Bool’
To use the inferred type, enable PartialTypeSignatures
• In the type signature:
not' :: Bool -> _
• Relevant bindings include
not' :: Bool -> Bool (bound at [Link]:1)
When a wildcard is not instantiated to a monotype, it will be generalised over, i.e. replaced
by a fresh type variable, e.g.
foo :: _ -> _
foo x = x
-- Inferred: forall t. t -> t
filter' :: _
filter' = filter -- has type forall a. (a -> Bool) -> [a] -> [a]
-- Inferred: (a -> Bool) -> [a] -> [a]
Named Wildcards
NamedWildCards
Since 7.10.1
Allow naming of wildcards (e.g. _x) in type signatures.
Type wildcards can also be named by giving the underscore an identifier as suffix, i.e. _a.
These are called named wildcards. All occurrences of the same named wildcard within one
type signature will unify to the same type. For example:
f :: _x -> _x
f ('c', y) = ('d', error "Urk")
-- Inferred: forall t. (Char, t) -> (Char, t)
The named wildcard forces the argument and result types to be the same. Lacking a signature,
GHC would have inferred forall a b. (Char,a) -> (Char,b). A named wildcard can be
mentioned in constraints, provided it also occurs in the monotype part of the type signature
to make sure that it unifies with something:
foo :: _a -> _a
foo _ = False
Compiling this program without enabling NamedWildCards (page 445) produces the following
error message complaining about the type variable _a no matching the actual type Bool.
[Link]:9: error:
• Couldn't match expected type ‘_a’ with actual type ‘Bool’
‘_a’ is a rigid type variable bound by
the type signature for:
foo :: forall _a. _a -> _a
at [Link]:8
• In the expression: False
In an equation for ‘foo’: foo _ = False
• Relevant bindings include foo :: _a -> _a (bound at [Link]:1)
Compiling this program with NamedWildCards (page 445) (as well as PartialTypeSignatures
(page 444)) enabled produces the following error message reporting the inferred type of the
Extra-Constraints Wildcard
The third kind of wildcard is the extra-constraints wildcard. The presence of an extra-
constraints wildcard indicates that an arbitrary number of extra constraints may be inferred
during type checking and will be added to the type signature. In the example below, the
extra-constraints wildcard is used to infer three extra constraints.
An extra-constraints wildcard shouldn’t prevent the programmer from already listing the con-
straints he knows or wants to annotate, e.g.
An extra-constraints wildcard can also lead to zero extra constraints to be inferred, e.g.
As a single extra-constraints wildcard is enough to infer any number of constraints, only one
is allowed in a type signature and it should come last in the list of constraints.
Partial type signatures are allowed for bindings, pattern and expression signatures, except
that extra-constraints wildcards are not supported in pattern or expression signatures. In the
following example a wildcard is used in each of the three possible contexts.
{-# LANGUAGE ScopedTypeVariables #-}
foo :: _
foo (x :: _) = (x :: _)
-- Inferred: forall w_. w_ -> w_
Anonymous and named wildcards can occur on the left hand side of a type or data instance
declaration; see Wildcards on the LHS of data and type family instances (page 306).
Anonymous wildcards are also allowed in visible type applications/ visible kind applications
(Visible type application (page 338)). If you want to specify only the second type argument to
wurble, then you can say wurble @_ @Int where the first argument is a wildcard.
Standalone deriving declarations permit the use of a single, extra-constraints wildcard, like
so:
deriving instance _ => Eq (Foo a)
This denotes a derived Eq (Foo a) instance where the context is inferred, in much the same
way that ordinary deriving clauses do. Any other use of wildcards in a standalone deriving
declaration is prohibited.
In all other contexts, type wildcards are disallowed, and a named wildcard is treated as an
ordinary type variable. For example:
class C _ where ... -- Illegal
instance Eq (T _) -- Illegal (currently; would actually make sense)
instance Eq _a => Eq (T _a) -- Perfectly fine, same as Eq a => Eq (T a)
Partial type signatures can also be used in Template Haskell (page 450) splices.
• Declaration splices: partial type signature are fully supported.
{-# LANGUAGE TemplateHaskell, NamedWildCards #-}
$( [d| foo :: _ => _a -> _a -> _
foo x y = x == y|] )
• Expression splices: anonymous and named wildcards can be used in expression signa-
tures. Extra-constraints wildcards are not supported, just like in regular expression
signatures.
{-# LANGUAGE TemplateHaskell, NamedWildCards #-}
$( [e| foo = (Just True :: _m _) |] )
• Typed expression splices: the same wildcards as in (untyped) expression splices are
supported.
• Pattern splices: anonymous and named wildcards can be used in pattern signatures.
Note that ScopedTypeVariables (page 436) has to be enabled to allow pattern signa-
tures. Extra-constraints wildcards are not supported, just like in regular pattern signa-
tures.
• Type splices: only anonymous wildcards are supported in type splices. Named and extra-
constraints wildcards are not.
NoMonomorphismRestriction
Default on
Since 6.8.1
Prevents the compiler from applying the monomorphism restriction to bindings lacking
explicit type signatures.
Haskell’s monomorphism restriction (see Section 4.5.5 of the Haskell Report) can be com-
pletely switched off by NoMonomorphismRestriction (page 449). Since GHC 7.8.1, the
monomorphism restriction is switched off by default in GHCi’s interactive options (see Setting
options for interactive evaluation only (page 64)).
6.12.2 Let-generalisation
MonoLocalBinds
Since 6.12.1
Infer less polymorphic types for local bindings by default.
An ML-style language usually generalises the type of any let-bound or where-bound variable,
so that it is as polymorphic as possible. With the extension MonoLocalBinds (page 449) GHC
implements a slightly more conservative policy, using the following rules:
• A variable is closed if and only if
– the variable is let-bound
– one of the following holds:
∗ the variable has an explicit type signature that has no free type variables, or
∗ its binding group is fully generalised (see next bullet)
• A binding group is fully generalised if and only if
– each of its free variables is either imported or closed, and
– the binding is not affected by the monomorphism restriction (Haskell Report, Section
4.5.5)
For example, consider
f x = x + 1
g x = let h y = f y * 2
k z = z+x
in h x + k x
Here f is generalised because it has no free variables; and its binding group is unaffected
by the monomorphism restriction; and hence f is closed. The same reasoning applies to g,
except that it has one closed free variable, namely f. Similarly h is closed, even though it is
not bound at top level, because its only free variable f is closed. But k is not closed, because
it mentions x which is not closed (because it is not let-bound).
Notice that a top-level binding that is affected by the monomorphism restriction is not closed,
and hence may in turn prevent generalisation of bindings that mention it.
The rationale for this more conservative strategy is given in the papers “Let should not be
generalised” and “Modular type inference with local assumptions”, and a related blog post.
The extension MonoLocalBinds (page 449) is implied by TypeFamilies (page 298) and GADTs
(page 296). You can switch it off again with NoMonoLocalBinds (page 449) but type inference
becomes less predictable if you do so. (Read the papers!)
6.13.1 Syntax
TemplateHaskell
Implies TemplateHaskellQuotes (page 450)
Since 6.0. Typed splices introduced in GHC 7.8.1.
Enable Template Haskell’s splice and quotation syntax.
TemplateHaskellQuotes
Since 8.0.1
Enable only Template Haskell’s quotation syntax.
Template Haskell has the following new syntactic constructions. You need to use the exten-
sion TemplateHaskell (page 450) to switch these syntactic extensions on. Alternatively, the
TemplateHaskellQuotes (page 450) extension can be used to enable the quotation subset of
Template Haskell (i.e. without top-level splices). The TemplateHaskellQuotes (page 450) ex-
tension is considered safe under Safe Haskell (page 493) while TemplateHaskell (page 450)
is not.
• A splice is written $x, where x is an arbitrary expression. There must be no space be-
tween the “$” and the expression. This use of “$” overrides its meaning as an infix
operator, just as “M.x” overrides the meaning of ”.” as an infix operator. If you want the
infix operator, put spaces around it.
A top-level splice can occur in place of
– an expression; the spliced expression must have type Q Exp
– a pattern; the spliced pattern must have type Q Pat
– a type; the spliced expression must have type Q Type
– a list of declarations at top level; the spliced expression must have type Q [Dec]
Inside a splice you can only call functions defined in imported modules, not functions
defined elsewhere in the same module. Note that declaration splices are not allowed
anywhere except at top level (outside any other declarations).
The Q monad is a monad defined in [Link] which supports several
useful operations during code generation such as reporting errors or looking up identi-
fiers in the environment.
• A expression quotation is written in Oxford brackets, thus:
– [| ... |], or [e| ... |], where the ”...” is an expression; the quotation has type
Quote m => m Exp.
– [d| ... |], where the ”...” is a list of top-level declarations; the quotation has type
Quote m => m [Dec].
– [t| ... |], where the ”...” is a type; the quotation has type Quote m => m Type.
– [p| ... |], where the ”...” is a pattern; the quotation has type Quote m => m Pat.
The Quote type class ([Link]) is the minimal interface nec-
essary to implement the desugaring of quotations. The Q monad is an instance of Quote
but contains many more operations which are not needed for defining quotations.
See Where can they occur? (page 448) for using partial type signatures in quotations.
• Splices can be nested inside quotation brackets. For example the fragment representing
1 + 2 can be constructed using nested splices:
twoC = [| 2 |]
• The precise type of a quotation depends on the types of the nested splices inside it:
Remember, a top-level splice still requires its argument to be of type Q Exp. So then
splicing in g will cause m to be instantiated to Q:
h :: Int
h = $(g) -- m ~ Q
import [Link]
import Bar
two :: Int
two = $(add1 1)
Template Haskell cannot know what the argument to add1 will be at the function’s def-
inition site, so a lifting mechanism is used to promote x into a value of type Quote m
=> m Exp. This functionality is exposed to the user as the Lift typeclass in the Lan-
[Link] module. If a type has a Lift instance, then any of its values
can be lifted to a Template Haskell expression:
In general, if GHC sees an expression within Oxford brackets (e.g., [| foo bar |], then
GHC looks up each name within the brackets. If a name is global (e.g., suppose foo
comes from an import or a top-level declaration), then the fully qualified name is used
directly in the quotation. If the name is local (e.g., suppose bar is bound locally in the
function definition mkFoo bar = [| foo bar |]), then GHC uses lift on it (so GHC pre-
tends [| foo bar |] actually contains [| foo $(lift bar) |]). Local names, which
are not in scope at splice locations, are actually evaluated when the quotation is pro-
cessed.
The template-haskell library provides Lift instances for many common data types.
Furthermore, it is possible to derive Lift instances automatically by using the Deriv-
eLift (page 377) language extension. See Deriving Lift instances (page 377) for more
information.
• You may omit the $(...) in a top-level declaration splice. Simply writing an expression
(rather than a declaration) implies a splice. For example, you can write
f x = x
g y = y+1
h z = z-1
This abbreviation makes top-level declaration slices quieter and less intimidating.
• Pattern splices introduce variable binders but scoping of variables in expressions inside
the pattern’s scope is only checked when a splice is run. Note that pattern splices that oc-
cur outside of any quotation brackets are run at compile time. Pattern splices occurring
inside a quotation bracket are not run at compile time; they are run when the bracket is
spliced in, sometime later. For example,
-- in another module:
foo :: (Char, String) -> String
foo $(mkPat) = x : z
will fail with z being out of scope in the definition of foo but it will not fail with w being
out of scope in the definition of bar. That will only happen when bar is spliced.
• A pattern quasiquoter may generate binders that scope over the right-hand side of a
definition because these binders are in scope lexically. For example, given a quasiquoter
haskell that parses Haskell, in the following code, the y in the right-hand side of f refers
to the y bound by the haskell pattern quasiquoter, not the top-level y = 7.
y :: Int
y = 7
• Top-level declaration splices break up a source file into declaration groups. A declaration
group is the group of declarations created by a top-level declaration splice, plus those
following it, down to but not including the next top-level declaration splice. N.B. only
top-level splices delimit declaration groups, not expression splices. The first declaration
group in a module includes all top-level definitions down to but not including the first
top-level declaration splice.
Each declaration group is mutually recursive only within the group. Declaration groups
can refer to definitions within previous groups, but not later ones.
Accordingly, the type environment seen by reify includes all the top-level declarations
up to the end of the immediately preceding declaration group, but no more.
Unlike normal declaration splices, declaration quasiquoters do not cause a break. These
quasiquoters are expanded before the rest of the declaration group is processed, and
the declarations they generate are merged into the surrounding declaration group. Con-
sequently, the type environment seen by reify from a declaration quasiquoter will not
include anything from the quasiquoter’s declaration group.
Concretely, consider the following code
module M where
import ...
f x = x
$(th1 4)
h y = k y y $(blah1)
[qq|blah|]
k x y z = x + y + z
$(th2 10)
w z = $(blah2)
module M where
data D = C1 | C2
f1 = $(th1 ...)
$(return [])
f2 = $(th2 ...)
Here
1. The splice $(th1 ...) cannot refer to D - it is in the same declaration group.
2. The declaration group containing D is terminated by the empty top-level declaration
splice $(return []) (recall, Q is a Monad, so we may simply return the empty list
of declarations).
3. Since the declaration group containing D is in the previous declaration group, the
splice $(th2 ...) can refer to D.
• Expression quotations accept most Haskell language constructs. However, there are
some GHC-specific extensions which expression quotations currently do not support, in-
cluding
– Type holes in typed splices (see #10945 and #10946)
(Compared to the original paper, there are many differences of detail. The syntax for a dec-
laration splice uses “$” not “splice”. The type of the enclosed expression must be Quote m
=> m [Dec], not [Q Dec]. Typed expression splices and quotations are supported.)
-fenable-th-splice-warnings
Template Haskell splices won’t be checked for warnings, because the code causing
the warning might originate from a third-party library and possibly was not written by
the user. If you want to have warnings for splices anyway, pass -fenable-th-splice-
warnings (page 456).
• The data types and monadic constructor functions for Template Haskell are in the library
[Link].
• You can only run a function at compile time if it is imported from another module. That
is, you can’t define a function in a module, and call it from within a splice in the same
module. (It would make sense to do so, but it’s hard to implement.)
• You can only run a function at compile time if it is imported from another module that
is not part of a mutually-recursive group of modules that includes the module currently
being compiled. Furthermore, all of the modules of the mutually-recursive group must
be reachable by non-SOURCE imports from the module where the splice is to be run.
For example, when compiling module A, you can only run Template Haskell functions
imported from B if B does not import A (directly or indirectly). The reason should be
clear: to run B we must compile and run A, but we are currently type-checking A.
• If you are building GHC from source, you need at least a stage-2 bootstrap compiler to
run Template Haskell splices and quasi-quotes. A stage-1 compiler will only accept regu-
lar quotes of Haskell. Reason: TH splices and quasi-quotes compile and run a program,
and then looks at the result. So it’s important that the program it compiles produces
results whose representations are identical to those of the compiler itself.
Template Haskell works in any mode (--make (page 76), --interactive (page 76), or file-
at-a-time). There used to be a restriction to the former two, but that restriction has been
lifted.
The flag -ddump-splices (page 228) shows the expansion of all top-level declaration splices,
both typed and untyped, as they happen. As with all dump flags, the default is for this output
to be sent to stdout. For a non-trivial program, you may be interested in combining this
with the -ddump-to-file (page 227) flag (see Dumping out compiler intermediate structures
(page 227). For each file using Template Haskell, this will show the output in a .dump-splices
file.
The flag -dth-dec-file (page 228) dumps the expansions of all top-level TH declaration
splices, both typed and untyped, in the file [Link] for each module M being compiled. Note
that other types of splices (expressions, types, and patterns) are not shown. Application
developers can check this into their repository so that they can grep for identifiers that were
defined in Template Haskell. This is similar to using -ddump-to-file (page 227) with -ddump-
splices (page 228) but it always generates a file instead of being coupled to -ddump-to-file
(page 227). The format is also different: it does not show code from the original file, instead
it only shows generated code and has a comment for the splice location of the original file.
Below is the output of the same sample using -dth-dec-file (page 228)
-- TH_pragma.hs:(6,4)-(8,26): Splicing declarations
foo :: Int -> Int
foo x = (x + 1)
To help you get over the confidence barrier, try out this skeletal worked example. First cut
and paste the two modules below into [Link] and [Link]:
{- [Link] -}
module Main where
{- [Link] -}
module Printf where
gen [L s] = stringE s
$ ./main
Hello
Rebindable syntax does not play well with untyped TH quotes: applying the rebindable syntax
rules would go against the lax nature of untyped quotes that are accepted even in the presence
of unbound identifiers (see #18102). Applying the rebindable syntax rules to them would
force the code that defines the said quotes to have all the necessary functions (e.g ifThenElse
or fromInteger) in scope, instead of delaying the resolution of those symbols to the code that
splices the quoted Haskell syntax, as is usually done with untyped TH. For this reason, even if
a module has untyped TH quotes with RebindableSyntax enabled, GHC turns off rebindable
syntax while processing the quotes. The code that splices the quotes is however free to turn
on RebindableSyntax to have the usual rules applied to the resulting code.
Typed TH quotes on the other hand are perfectly compatible with the eager application of
rebindable syntax rules, and GHC will therefore process any such quotes according to the re-
bindable syntax rules whenever the RebindableSyntax extension is turned on in the modules
where such quotes appear.
Template Haskell relies on GHC’s built-in bytecode compiler and interpreter to run the splice
expressions. The bytecode interpreter runs the compiled expression on top of the same run-
time on which GHC itself is running; this means that the compiled code referred to by the
interpreted expression must be compatible with this runtime, and in particular this means
that object code that is compiled for profiling cannot be loaded and used by a splice expres-
sion, because profiled object code is only compatible with the profiling version of the runtime.
This causes difficulties if you have a multi-module program containing Template Haskell code
and you need to compile it for profiling, because GHC cannot load the profiled object code
and use it when executing the splices.
Fortunately GHC provides two workarounds.
The first option is to compile the program twice:
1. Compile the program or library first the normal way, without -prof (page 557).
2. Then compile it again with -prof (page 557), and additionally use -osuf p_o to name
the object files differently (you can choose any suffix that isn’t the normal object suffix
here). GHC will automatically load the object files built in the first step when executing
splice expressions. If you omit the -osuf ⟨suffix⟩ (page 178) flag when building with
-prof (page 557) and Template Haskell is used, GHC will emit an error message.
The second option is to add the flag -fexternal-interpreter (page 67) (see Running the
interpreter in a separate process (page 67)), which runs the interpreter in a separate process,
wherein it can load and run the profiled code directly. There’s no need to compile the code
twice, just add -fexternal-interpreter (page 67) and it should just work. (this option is
experimental in GHC 8.0.x, but it may become the default in future releases).
QuasiQuotes
Since 6.10.1
Enable Template Haskell Quasi-quotation syntax.
Quasi-quotation allows patterns and expressions to be written using programmer-defined con-
crete syntax; the motivation behind the extension and several examples are documented in
“Why It’s Nice to be Quoted: Quasiquoting for Haskell” (Proc Haskell Workshop 2007). The
example below shows how to write a quasiquoter for a simple expression language.
Here are the salient features
• A quasi-quote has the form [quoter| string |].
– The ⟨quoter⟩ must be the name of an imported quoter, either qualified or unqualified;
it cannot be an arbitrary expression.
– The ⟨quoter⟩ cannot be “e”, “t”, “d”, or “p”, since those overlap with Template
Haskell quotations.
– There must be no spaces in the token [quoter|.
– The quoted ⟨string⟩ can be arbitrary, and may contain newlines.
– The quoted ⟨string⟩ finishes at the first occurrence of the two-character sequence
"|]". Absolutely no escaping is performed. If you want to embed that character
sequence in the string, you must invent your own escape convention (such as, say,
using the string "|~]" instead), and make your quoter function interpret "|~]" as
"|]". One way to implement this is to compose your quoter with a pre-processing
pass to perform your escape conversion. See the discussion in #5348 for details.
• A quasiquote may appear in place of
– An expression
– A pattern
– A type
– A top-level declaration
(Only the first two are described in the paper.)
• A quoter is a value of type [Link], which is defined
thus:
That is, a quoter is a tuple of four parsers, one for each of the contexts in which a quasi-
quote can occur.
• A quasi-quote is expanded by applying the appropriate parser to the string enclosed by
the Oxford brackets. The context of the quasi-quote (expression, pattern, type, declara-
tion) determines which of the parsers is called.
• Unlike normal declaration splices of the form $(...), declaration quasi-quotes do not
cause a declaration group break. See Syntax (page 450) for more information.
Warning: QuasiQuotes (page 459) introduces an unfortunate ambiguity with list com-
prehension syntax. Consider the following,
let x = [v| v <- [0..10]]
Without QuasiQuotes (page 459) this is parsed as a list comprehension. With QuasiQuotes
(page 459) this is parsed as a quasi-quote; however, this parse will fail due to the lack of a
closing |]. See #11679.
The example below shows quasi-quotation in action. The quoter expr is bound to a value of
type QuasiQuoter defined in module Expr. The example makes use of an antiquoted variable
n, indicated by the syntax 'int:n (this syntax for anti-quotation was defined by the parser’s
author, not by GHC). This binds n to the integer value argument of the constructor IntExpr
when pattern matching. Please see the referenced paper for further details regarding anti-
quotation as well as the description of a technique that uses SYB to leverage a single parser
of type String -> a to generate both an expression parser that returns a value of type Q Exp
and a pattern parser that returns a value of type Q Pat.
Quasiquoters must obey the same stage restrictions as Template Haskell, e.g., in the example,
expr cannot be defined in [Link] where it is used, but must be imported.
import Expr
main :: IO ()
main = do { print $ eval [expr|1 + 2|]
; case IntExpr 1 of
{ [expr|'int:n|] -> print n
; _ -> return ()
}
}
$ ./main
3
1
In high-performance Haskell code (e.g. numeric code) eliminating thunks from an inner loop
can be a huge win. GHC supports three extensions to allow the programmer to specify use of
strict (call-by-value) evaluation rather than lazy (call-by-need) evaluation.
• Bang patterns (BangPatterns (page 462)) makes pattern matching and let bindings
stricter.
• Strict data types (StrictData (page 463)) makes constructor fields strict by default, on
a per-module basis.
• Strict pattern (Strict (page 464)) makes all patterns and let bindings strict by default,
on a per-module basis.
The latter two extensions are simply a way to avoid littering high-performance code with bang
patterns, making it harder to read.
Bang patterns and strict matching do not affect the type system in any way.
BangPatterns
Since 6.8.1
Allow use of bang pattern syntax.
GHC supports an extension of pattern matching called bang patterns, written !pat. Bang
patterns are under consideration for Haskell Prime. The Haskell prime feature description
contains more discussion and examples than the material below.
The main idea is to add a single new production to the syntax of patterns:
Matching an expression e against a pattern !p is done by first evaluating e (to WHNF) and
then matching the result against p. Example:
f1 !x = True
This definition makes f1 is strict in x, whereas without the bang it would be lazy. Bang
patterns can be nested of course:
f2 (!x, y) = [x,y]
f3 !(x,y) = [x,y]
f4 (x,y) = [x,y]
Here, f3 and f4 are identical; putting a bang before a pattern that forces evaluation
anyway does nothing.
• A bang pattern is allowed in a let or where clause, and makes the binding strict. For
example:
let !x = e in body
let !(p,q) = e in body
let (!x,[y]) = e in b
is equivalent to this:
The binding is lazy, but when either x or y is evaluated by b the entire pattern is matched,
including forcing the evaluation of x.
See Semantics of let bindings with bang patterns (page 466) for the detailed semantics.
• A pattern with a bang at the outermost level is not allowed at the top level of a module.
• Bang patterns work in case expressions too, of course:
g5 x = let y = f x in body
g6 x = case f x of { y -> body }
g7 x = case f x of { !y -> body }
The functions g5 and g6 mean exactly the same thing. But g7 evaluates (f x), binds y
to the result, and then evaluates body.
• There is one problem with syntactic ambiguity. Consider:
f !x = 3
Is this a definition of the infix function “(!)”, or of the “f” with a bang pattern? GHC
resolves this ambiguity by looking at the surrounding whitespace:
StrictData
Since 8.0.1
Make fields of data types defined in the current module strict by default.
Informally the StrictData language extension switches data type declarations to be strict by
default allowing fields to be lazy by adding a ~ in front of the field.
When the user writes
data T = C a
data T' = C' ~a
data T = C !a
data T' = C' a
Strict
Implies StrictData (page 463)
Since 8.0.1
Make bindings in the current module strict by default.
Informally the Strict language extension switches functions, data types, and bindings to be
strict by default, allowing optional laziness by adding ~ in front of a variable. This essentially
reverses the present situation where laziness is default and strictness can be optionally had
by adding ! in front of a variable.
Strict implies StrictData (page 463).
• Function definitions
When the user writes
f x = ...
f !x = ...
let x = ...
let pat = ...
let !x = ...
let !pat = ...
Adding ~ in front of x gives the regular lazy behavior. The general rule is that we add an
implicit bang on the outermost pattern, unless disabled with ~.
• Pattern matching in case expressions, lambdas, do-notation, etc
The outermost pattern of all pattern matches gets an implicit bang, unless disabled with
~. This applies to case expressions, patterns in lambda, do-notation, list comprehension,
and so on. For example
is interpreted as
Since the semantics of pattern matching in case expressions is strict, this usually has no
effect whatsoever. But it does make a difference in the degenerate case of variables and
newtypes. So
is lazy in Haskell; but with Strict the added bang makes it strict.
Similarly
\ x -> body
do { x <- rhs; blah }
[ e | x <- rhs; blah }
which will strictly evaluate the right hand side, and bind p and q to the components of
the pair. But the pair itself is lazy (unless we also compile the Prelude with Strict; see
Modularity (page 466) below). So p and q may end up bound to undefined. See also
Dynamic semantics of bang patterns (page 466) below.
• Top level bindings
are unaffected by Strict. For example:
x = factorial 20
(y,z) = if x > 10 then True else False
Here x and the pattern binding (y,z) remain lazy. Reason: there is no good moment to
force them, until first use.
• Newtypes
There is no effect on newtypes, which simply rename existing types. For example:
newtype T = C a
f (C x) = rhs1
g !(C x) = rhs2
In ordinary Haskell, f is lazy in its argument and hence in x; and g is strict in its argument
and hence also strict in x. With Strict, both become strict because f‘s argument gets
an implicit bang.
6.14.4 Modularity
Strict and StrictData only affects definitions in the module they are used in. Functions
and data types imported from other modules are unaffected. For example, we won’t evaluate
the argument to Just before applying the constructor. Similarly we won’t evaluate the first
argument to [Link] before applying the function.
This is crucial to preserve correctness. Entities defined in other modules might rely on lazi-
ness for correctness (whether functional or performance).
Tuples, lists, Maybe, and all the other types from Prelude continue to have their existing, lazy,
semantics.
The semantics of Haskell pattern matching is described in Section 3.17.2 of the Haskell Report.
To this description add one extra item 10, saying:
• Matching the pattern !pat against a value v behaves as follows:
– if v is bottom, the match diverges
– otherwise, pat is matched against v
Similarly, in Figure 4 of Section 3.17.3, add a new case (t):
That leaves let expressions, whose translation is given in Section 3.12 of the Haskell Report.
Replace the “Translation” there with the following one. Given let { bind1 ... bindn } in
body:
FORCE
Replace any binding !p = e with v = case e of p -> (x1,...,xn); (x1,...,xn) = v
and replace body with v seq body, where v is fresh. This translation works fine if p is al-
ready a variable x, but can obviously be optimised by not introducing a fresh variable v.
SPLIT
Replace any binding p = e, where p is not a variable, with v = e; x1 = case v of p ->
x1; ...; xn = case v of p -> xn, where v is fresh and x1.. xn are the bound variables of
p. Again if e is a variable, this can be optimised by not introducing a fresh variable.
The result will be a (possibly) recursive set of bindings, binding only simple variables on the
left hand side. (One could go one step further, as in the Haskell Report and make the recursive
bindings non-recursive using fix, but we do not do so in Core, and it only obfuscates matters,
so we do not do so here.)
The translation is carefully crafted to make bang patterns meaningful for recursive and poly-
morphic bindings as well as straightforward non-recursive bindings.
Here are some examples of how this translation works. The first expression of each sequence
is Haskell source; the subsequent ones are Core.
===> (FORCE)
let x = factorial y in x `seq` body
===> (inline x)
case factorial y of x -> body
===> (FORCE)
let v = case e of (Just x, Left y) -> (x,y)
(x,y) = v
in v `seq` body
===> (SPLIT)
let v = case e of (Just x, Left y) -> (x,y)
x = case v of (x,y) -> x
y = case v of (x,y) -> y
in v `seq` body
===> (FORCE)
letrec xs = factorial y : xs in xs `seq` body
===> (FORCE)
let f = /\a. fst (reverse a, True) in f `seq` body
===> (inline seq, inline f)
case (/\a. fst (reverse a, True)) of f -> body
Notice that the seq is added only in the translation to Core If we did it in Haskell source, thus
then f‘s polymorphic type would get instantiated, so the Core translation would be
===> (FORCE)
let f = /\a \(d::Eq a). fst (member, True) in f `seq` body
GHC implements some major extensions to Haskell to support concurrent and parallel pro-
gramming. Let us first establish terminology:
• Parallelism means running a Haskell program on multiple processors, with the goal of
improving performance. Ideally, this should be done invisibly, and with no semantic
changes.
Concurrent Haskell
Concurrent Haskell is the name given to GHC’s concurrency extension. It is enabled by de-
fault, so no special flags are required. The Concurrent Haskell paper is still an excellent
resource, as is Tackling the awkward squad.
To the programmer, Concurrent Haskell introduces no new language constructs; rather, it ap-
pears simply as a library, [Link]. The functions exported by this library include:
• Forking and killing threads.
• Sleeping.
• Synchronised mutable variables, called MVars
• Support for bound threads; see the paper Extending the FFI with concurrency.
Parallel Haskell
GHC includes support for running Haskell programs in parallel on symmetric, shared-memory
multi-processor (SMP). By default GHC runs your program on one processor; if you want it
to run in parallel you must link your program with the -threaded (page 220), and run it with
the RTS -N ⟨x⟩ (page 118) option; see Using SMP parallelism (page 118)). The runtime will
schedule the running Haskell threads among the available OS threads, running as many in
parallel as you specified with the -N ⟨x⟩ (page 118) RTS option.
Ordinary single-threaded Haskell programs will not benefit from enabling SMP parallelism
alone: you must expose parallelism to the compiler. One way to do so is forking threads
using Concurrent Haskell (Concurrent Haskell (page 469)), but the simplest mechanism for
extracting parallelism from pure code is to use the par combinator, which is closely related
to (and often used with) seq. Both of these are available from the parallel library:
infixr 0 `par`
infixr 1 `pseq`
The expression (x `par` y) sparks the evaluation of x (to weak head normal form) and re-
turns y. Sparks are queued for execution in FIFO order, but are not executed immediately.
If the runtime detects that there is an idle CPU, then it may convert a spark into a real
thread, and run the new thread on the idle CPU. In this way the available parallelism is
spread amongst the real CPUs.
For example, consider the following parallel version of our old nemesis, nfib:
import [Link]
For values of n greater than 1, we use par to spark a thread to evaluate nfib (n-1), and
then we use pseq to force the parent thread to evaluate nfib (n-2) before going on to add
together these two subexpressions. In this divide-and-conquer approach, we only spark a new
thread for one branch of the computation (leaving the parent to evaluate the other branch).
Also, we must use pseq to ensure that the parent will evaluate n2 before n1 in the expression
(n1 + n2 + 1). It is not sufficient to reorder the expression as (n2 + n1 + 1), because the
compiler may not generate code to evaluate the addends from left to right.
Note that we use pseq rather than seq. The two are almost equivalent, but differ in their
runtime behaviour in a subtle way: seq can evaluate its arguments in either order, but pseq
is required to evaluate its first argument before its second, which makes it more suitable for
controlling the evaluation order in conjunction with par.
When using par, the general rule of thumb is that the sparked computation should be required
at a later time, but not too soon. Also, the sparked computation should not be too small,
otherwise the cost of forking it in parallel will be too large relative to the amount of parallelism
gained. Getting these factors right is tricky in practice.
It is possible to glean a little information about how well par is working from the runtime
statistics; see RTS options to control the garbage collector (page 160).
More sophisticated combinators for expressing parallelism are available from the Con-
[Link] module in the parallel package. This module builds functionality
around par, expressing more elaborate patterns of parallel computation, such as parallel map.
GHC now supports a new way to coordinate the activities of Concurrent Haskell threads,
called Software Transactional Memory (STM). The STM papers are an excellent introduction
to what STM is, and how to use it.
The main library you need to use is the stm library. The main features supported are these:
• Atomic blocks.
• Transactional variables.
• Operations for composing transactions: retry, and orElse.
• Data invariants.
All these features are described in the papers mentioned earlier.
StaticPointers
Since 7.10.1
Each reference is given a key which can be used to locate it at runtime with
[Link] which uses a global and immutable table called the
Static Pointer Table. The compiler includes entries in this table for all static forms
found in the linked modules. The value can be obtained from the reference via
[Link].
The body e of a static e expression must be a closed expression. Where we say an expression
is closed when all of its free (type) variables are closed. And a variable is closed if it is let-
bound to a closed expression and its type is closed as well. And a type is closed if it has no
free variables.
All of the following are permissible:
ref1 = static 1
ref2 = static inc
ref3 = static (inc 1)
ref4 = static ((\x -> x + 1) (1 :: Int))
ref5 y = static (let x = 1 in x)
ref6 y = let x = 1 in static x
Note: While modules loaded in GHCi with the :load (page 57) command may use Static-
Pointers (page 470) and static expressions, statements entered on the REPL may not. This
is a limitation of GHCi; see #12356 for details.
Note: The set of keys used for locating static pointers in the Static Pointer Table is not
guaranteed to remain stable for different program binaries. Or in other words, only processes
launched from the same program binary are guaranteed to use the same set of keys.
A static form determines a value of type StaticPtr t, but just like OverloadedLists and
OverloadedStrings, this literal expression is overloaded to allow lifting a StaticPtr into
another type implicitly, via the IsStatic class:
The only predefined instance is the obvious one that does nothing:
See [Link].
Furthermore, type t is constrained to have a Typeable instance. The following are therefore
illegal:
That being said, with the appropriate use of wrapper datatypes, the above limitations induce
no loss of generality:
import [Link]
import [Link]
import [Link]
GHC is built on a raft of primitive data types and operations; “primitive” in the sense that
they cannot be defined in Haskell itself. While you really can use this stuff to write fast code,
we generally find it a lot less painful, and more satisfying in the long run, to use higher-level
language features and libraries. With any luck, the code you write will be optimised to the
efficient unboxed version in any case. And if it isn’t, we’d like to know about it.
All these primitive data types and operations are exported by the library [Link]. (This
documentation is generated from the file compiler/GHC/Builtin/[Link].)
If you want to mention any of the primitive data types or operations in your program, you
must first import [Link] to bring them into scope. Many of them have names ending in #,
and to mention such names you need the MagicHash (page 242) extension.
The primops make extensive use of unboxed types (page 473) and unboxed tuples (page 474),
which we briefly summarise here.
Most types in GHC are boxed, which means that values of that type are represented by a
pointer to a heap object. The representation of a Haskell Int, for example, is a two-word
heap object. An unboxed type, however, is represented by the value itself, no pointers or
heap allocation are involved.
Unboxed types correspond to the “raw machine” types you would use in C: Int# (long int),
Double# (double), Addr# (void *), etc. The primitive operations (PrimOps) on these types are
what you might expect; e.g., (+#) is addition on Int#s, and is the machine-addition that we
all know and love—usually one instruction.
Primitive (unboxed) types cannot be defined in Haskell, and are therefore built into the lan-
guage and compiler. Primitive types are always unlifted; that is, a value of a primitive type
cannot be bottom. (Note: a “boxed” type means that a value is represented by a pointer to a
heap object; a “lifted” type means that terms of that type may be bottom. See the next para-
graph for an example.) We use the convention (but it is only a convention) that primitive types,
values, and operations have a # suffix (see The magic hash (page 242)). For some primitive
types we have special syntax for literals, also described in the same section (page ??).
Primitive values are often represented by a simple bit-pattern, such as Int#, Float#, Double#.
But this is not necessarily the case: a primitive value might be represented by a pointer to a
heap-allocated object. Examples include Array#, the type of primitive arrays. Thus, Array#
is an unlifted, boxed type. A primitive array is heap-allocated because it is too big a value to
fit in a register, and would be too expensive to copy around; in a sense, it is accidental that it
is represented by a pointer. If a pointer represents a primitive value, then it really does point
to that value: no unevaluated thunks, no indirections. Nothing can be at the other end of the
pointer than the primitive value. A numerically-intensive program using unboxed types can
go a lot faster than its “standard” counterpart—we saw a threefold speedup on one example.
Because unboxed types are represented without the use of pointers, we cannot store them in
a polymorphic datatype. For example, the Just node of Just 42# would have to be different
from the Just node of Just 42; the former stores an integer directly, while the latter stores
a pointer. GHC currently does not support this variety of Just nodes (nor for any other
datatype). Accordingly, the kind of an unboxed type is different from the kind of a boxed type.
The Haskell Report describes that * (spelled Type and imported from [Link] in the GHC
dialect of Haskell) is the kind of ordinary datatypes, such as Int. Furthermore, type construc-
tors can have kinds with arrows; for example, Maybe has kind Type -> Type. Unboxed types
have a kind that specifies their runtime representation. For example, the type Int# has kind
TYPE 'IntRep and Double# has kind TYPE 'DoubleRep. These kinds say that the runtime rep-
resentation of an Int# is a machine integer, and the runtime representation of a Double# is a
machine double-precision floating point. In contrast, the kind Type is actually just a synonym
for TYPE 'LiftedRep. More details of the TYPE mechanisms appear in the section on runtime
representation polymorphism (page ??).
Given that Int#‘s kind is not Type, then it follows that Maybe Int# is disallowed. Similarly,
because type variables tend to be of kind Type (for example, in (.) :: (b -> c) -> (a ->
b) -> a -> c, all the type variables have kind Type), polymorphism tends not to work over
primitive types. Stepping back, this makes some sense, because a polymorphic function needs
to manipulate the pointers to its data, and most primitive types are unboxed.
There are some restrictions on the use of primitive types:
• You cannot define a newtype whose representation type (the argument type of the data
constructor) is an unboxed type. Thus, this is illegal:
newtype A = MkA Int#
However, this restriction can be relaxed by enabling UnliftedNewtypes (page 477). The
section on unlifted newtypes (page 477) details the behavior of such types.
• You cannot bind a variable with an unboxed type in a top-level binding.
• You cannot bind a variable with an unboxed type in a recursive binding.
• You may bind unboxed variables in a (non-recursive, non-top-level) pattern binding,
but you must make any such pattern-match strict. (Failing to do so emits a warning
-Wunbanged-strict-patterns (page 103).) For example, rather than:
data Foo = Foo Int Int#
UnboxedTuples
Since 6.8.1
Unboxed tuples aren’t really exported by [Link]; they are a syntactic extension (Unboxed-
Tuples (page 474)). An unboxed tuple looks like this:
(# e_1, ..., e_n #)
where e_1..e_n are expressions of any type (primitive or non-primitive). The type of an
unboxed tuple looks the same.
Note that when unboxed tuples are enabled, (# is a single lexeme, so for example when using
operators like # and #- you need to write ( # ) and ( #-) rather than (#) and (#-).
Unboxed tuples are used for functions that need to return multiple values, but they avoid the
heap allocation normally associated with using fully-fledged tuples. When an unboxed tuple
is returned, the components are put directly into registers or on the stack; the unboxed tuple
itself does not have a composite representation. Many of the primitive operations listed in
[Link] return unboxed tuples. In particular, the IO and ST monads use unboxed
tuples to avoid unnecessary allocation during sequences of operations.
There are some restrictions on the use of unboxed tuples:
• The typical use of unboxed tuples is simply to return multiple values, binding those mul-
tiple results with a case expression, thus:
f x y = (# x+1, y-1 #)
g x = case f x x of { (# a, b #) -> a + b }
If the types of p and q are not unboxed, the resulting binding is lazy like any other Haskell
pattern binding. The above example desugars like this:
UnboxedSums
Since 8.2.1
Enable the use of unboxed sum syntax.
-XUnboxedSums enables new syntax for anonymous, unboxed sum types. The syntax for an
unboxed sum type with N alternatives is
where t_1 ... t_N are types (which can be unlifted, including unboxed tuples and sums).
Unboxed tuples can be used for multi-arity alternatives. For example:
The term level syntax is similar. Leading and preceding bars (|) indicate which alternative it
is. Here are two terms of the type shown above:
case x of
(# (# i, str #) | #) -> ...
(# | bool #) -> ...
Unboxed sums are “unboxed” in the sense that, instead of allocating sums in the heap and
representing values as pointers, unboxed sums are represented as their components, just like
unboxed tuples. These “components” depend on alternatives of a sum type. Like unboxed
tuples, unboxed sums are lazy in their lifted components.
The code generator tries to generate as compact layout as possible for each unboxed sum. In
the best case, size of an unboxed sum is size of its biggest alternative plus one word (for a
tag). The algorithm for generating the memory layout for a sum type works like this:
• All types are classified as one of these classes: 32bit word, 64bit word, 32bit float, 64bit
float, pointer.
• For each alternative of the sum type, a layout that consists of these fields is generated.
For example, if an alternative has Int, Float# and String fields, the layout will have an
32bit word, 32bit float and pointer fields.
• Layout fields are then overlapped so that the final layout will be as compact as possible.
For example, suppose we have the unboxed sum:
The first Int32 is for the tag. There are two Float32 fields because floating point types
can’t overlap with other types, because of limitations of the code generator that we’re
hoping to overcome in the future. The second alternative needs two Float32 fields:
The Word32 field is for the Word32# in the first alternative. The Pointer field is shared
between String and Maybe Int values of the alternatives.
As another example, this is the layout for the unboxed version of Maybe a type, (# (#
#) | a #):
Int32, Pointer
The Pointer field is not used when tag says that it’s Nothing. Otherwise Pointer points
to the value in Just. As mentioned above, this type is lazy in its lifted field. Therefore,
the type
is precisely isomorphic to the type Maybe a, although its memory representation is dif-
ferent.
In the degenerate case where all the alternatives have zero width, such as the Bool-
like (# (# #) | (# #) #), the unboxed sum layout only has an Int32 tag field (i.e., the
whole thing is represented by an integer).
UnliftedNewtypes
Since 8.10.1
Enable the use of newtypes over types with non-lifted runtime representations.
GHC implements an UnliftedNewtypes (page 477) extension as specified in this GHC pro-
posal. UnliftedNewtypes (page 477) relaxes the restrictions around what types can appear
inside of a newtype. For example, the type
is accepted when this extension is enabled. This creates a type A :: TYPE 'IntRep and a data
constructor MkA :: Int# -> A. Although the kind of A is inferred by GHC, there is nothing
visually distinctive about this type that indicated that is it not of kind Type like newtypes
typically are. GADTSyntax (page ??) can be used to provide a kind signature for additional
clarity
The Coercible machinery works with unlifted newtypes just like it does with lifted types. In
either of the equivalent formulations of A given above, users would additionally have access
to a coercion between A and Int#.
As a consequence of the levity-polymorphic binder restriction (page ??), levity-polymorphic
fields are disallowed in data constructors of data types declared using data. However, since
newtype data constructor application is implemented as a coercion instead of as function
application, this restriction does not apply to the field inside a newtype data constructor. Thus,
the type checker accepts
newtype Maybe# :: forall (r :: RuntimeRep). TYPE r -> TYPE (SumRep '[r, TupleRep
,→'[]]) where
This extension also relaxes some of the restrictions around data family instances. In particu-
lar, UnliftedNewtypes (page 477) permits a newtype instance to be given a return kind of
TYPE r, not just Type. For example, the following newtype instance declarations would be
permitted:
It is worth noting that UnliftedNewtypes (page 477) is not required to give the data families
themselves return kinds involving TYPE, such as the FooKey and BarType examples above.
The extension is only required for newtype instance declarations, such as FooKeyBoolC and
BarTypeWorkRepC above.
This extension impacts the determination of whether or not a newtype has a Complete
User-Specified Kind Signature (CUSK). The exact impact is specified the section on CUSKs
(page ??).
ForeignFunctionInterface
Since 6.8.1
Allow use of the Haskell foreign function interface.
GHC (mostly) conforms to the Haskell Foreign Function Interface as specified in the Haskell
Report. Refer to the relevant chapter of the Haskell Report for more details.
FFI support is enabled by default, but can be enabled or disabled explicitly with the Foreign-
FunctionInterface (page 478) flag.
GHC implements a number of GHC-specific extensions to the FFI Chapter of the Haskell 2010
Report. These extensions are described in GHC extensions to the FFI Chapter (page 479), but
please note that programs using these features are not portable. Hence, these features should
be avoided where possible.
The FFI libraries are documented in the accompanying library documentation; see for exam-
ple the Foreign module.
The Haskell 2010 Report specifies that safe FFI calls must allow foreign calls to safely call
into Haskell code. In practice, this means that called functions also have to assume heap-
allocated Haskell values may move around arbitrarily in order to allow for GC.
This greatly constrains library authors since it implies that it is not safe to pass any heap object
reference to a safe foreign function call. For instance, it is often desirable to pass unpinned
(page 492) ByteArray#s directly to native code to avoid making an otherwise-unnecessary
copy. However, this can not be done safely for safe calls since the array might be moved by
the garbage collector in the middle of the call.
The Chapter does allow for implementations to move objects around during unsafe calls as
well. So strictly Haskell 2010-conforming programs cannot pass heap-allocated references
to unsafe FFI calls either.
GHC, since version 8.4, guarantees that garbage collection will never occur during an un-
safe call, even in the bytecode interpreter, and further guarantees that unsafe calls will
be performed in the calling thread. Making it safe to pass heap-allocated objects to unsafe
functions.
In previous releases, GHC would take advantage of the freedom afforded by the Chapter by
performing safe foreign calls in place of unsafe calls in the bytecode interpreter. This meant
that some packages which worked when compiled would fail under GHCi (e.g. #13730). But
this is no longer the case in recent releases.
A safe call calling into haskell is run on a bound thread by the RTS. This means any nesting
of safe calls will be executed on the same operating system thread. Sequential safe calls
however do not enjoy this luxury and may be run on arbitrary OS threads.
This behaviour is considered an implementation detail and code relying on thread local state
should instead use one of the interfaces provided in [Link] to make this explicit.
For information on what bound threads are, see the documentation for the Con-
[Link].
For more details on the implementation see the Paper: “Extending the Haskell Foreign Func-
tion Interface with Concurrency”. Last known to be accessible here.
Note that functions requiring varargs arguments are unsupported by the ccall calling con-
vention. Foreign imports needing to call such functions should rather use the capi convention,
giving an explicit signature for the needed call-pattern. For instance, one could write:
The FFI features that are described in this section are specific to GHC. Your code will not be
portable to other compilers if you use them.
UnliftedFFITypes
Since 6.8.1
The following unlifted unboxed types may be used as basic foreign types (see FFI Chapter,
Section 8.6) for both safe and unsafe foreign calls: Int#, Word#, Char#, Float#, Double#,
Addr#, and StablePtr# a. Several unlifted boxed types may be used as arguments to FFI
calls, subject to these restrictions:
• Valid arguments for foreign import unsafe FFI calls: Array#, SmallArray#, Arra-
yArray#, ByteArray#, and the mutable counterparts of these types.
• Valid arguments for foreign import safe FFI calls: ByteArray# and MutableByteAr-
ray#. The byte array must be pinned (page 492).
• Mutation: In both foreign import unsafe and foreign import safe FFI calls, it is
safe to mutate a MutableByteArray. Mutating any other type of array leads to unde-
fined behavior. Reason: Mutable arrays of heap objects record writes for the purpose of
garbage collection. An array of heap objects is passed to a foreign C function, the run-
time does not record any writes. Consequently, it is not safe to write to an array of heap
objects in a foreign function. Since the runtime has no facilities for tracking mutation of
a MutableByteArray#, these can be safely mutated in any foreign function.
None of these restrictions are enforced at compile time. Failure to heed these restrictions
will lead to runtime errors that can be very difficult to track down. (The errors likely will not
manifest until garbage collection happens.) In tabular form, these restrictions are:
Table 6.2: Restrictions on unlifted boxed arguments passed to foreign C calls. Cells
marked as “Unsound” represent combinations that lead to undefined runtime behavior.
GHC does not reject such unsound programs at compile time.
When value is used as argument to FFI call that is
foreign import safe foreign import unsafe
Argument Type reads are writes are reads are writes are
Array# Unsound Unsound Sound Unsound
MutableArray# Unsound Unsound Sound Unsound
SmallArray# Unsound Unsound Sound Unsound
MutableSmallArray# Unsound Unsound Sound Unsound
ArrayArray# Unsound Unsound Sound Unsound
MutableArrayArray# Unsound Unsound Sound Unsound
unpinned ByteArray# Unsound Unsound Sound Unsound
unpinned MutableByteArray# Unsound Unsound Sound Sound
pinned ByteArray# Sound Unsound Sound Unsound
pinned MutableByteArray# Sound Sound Sound Sound
When passing any of the unlifted array types as an argument to a foreign C call, a for-
eign function sees a pointer that refers to the payload of the array, not to the StgAr-
rBytes/StgMutArrPtrs/StgSmallMutArrPtrs heap object containing it 1 . By contrast, a for-
eign Cmm call (page 482), introduced by foreign import prim, sees the heap object, not
just the payload. This means that, in some situations, the foreign C function might not need
any knowledge of the RTS closure types. The following example sums the first three bytes in
a MutableByteArray# 2 without using anything from Rts.h:
// C source
uint8_t add_triplet(uint8_t* arr) {
return (arr[0] + arr[1] + arr[2]);
}
-- Haskell source
foreign import ccall unsafe "add_triplet"
addTriplet :: MutableByteArray# RealWorld -> IO Word8
In other situations, the C function may need knowledge of the RTS closure types. The follow-
ing example sums the first element of each ByteArray# (interpreting the bytes as an array of
CInt) element of an ArrayArray## 3 :
1 Prior to GHC 8.10, when passing an ArrayArray# argument to a foreign function, the foreign function would see
Although GHC allows the user to pass all unlifted boxed types to foreign functions, some of
them are not amenable to useful work. Although Array# is unlifted, the elements in its payload
are lifted, and a foreign C function cannot safely force thunks. Consequently, a foreign C
function may not dereference any of the addresses that comprise the payload of the Array#.
The FFI spec requires the IO monad to appear in various places, but it can sometimes be
convenient to wrap the IO monad in a newtype, thus:
(A reason for doing so might be to prevent the programmer from calling arbitrary IO proce-
dures in some part of the program.)
The Haskell FFI already specifies that arguments and results of foreign imports and exports
will be automatically unwrapped if they are newtypes (Section 3.2 of the FFI addendum).
GHC extends the FFI by automatically unwrapping any newtypes that wrap the IO monad
itself. More precisely, wherever the FFI specification requires an IO type, GHC will accept
any newtype-wrapping of an IO type. For example, these declarations are OK:
The type variables in the type of a foreign declaration may be quantified with an explicit
forall by using the ExplicitForAll (page 431) language extension, as in the following ex-
ample:
Note that an explicit forall must appear at the front of the type signature and is not permitted
to appear nested within the type, as in the following (erroneous) examples:
Primitive imports
GHCForeignImportPrim
Since 6.12.1
With GHCForeignImportPrim (page 482), GHC extends the FFI with an additional calling con-
vention prim, e.g.:
This is used to import functions written in Cmm code that follow an internal GHC calling
convention. The arguments and results must be unboxed types, except that an argument may
be of type Any (by way of unsafeCoerce#) and the result type is allowed to be an unboxed
tuple or the type Any.
This feature is not intended for use outside of the core libraries that come with GHC. For more
details see the GHC developer wiki.
InterruptibleFFI
Since 7.2.1
This concerns the interaction of foreign calls with [Link]. Normally
when the target of a throwTo is involved in a foreign call, the exception is not raised until the
call returns, and in the meantime the caller is blocked. This can result in unresponsiveness,
which is particularly undesirable in the case of user interrupt (e.g. Control-C). The default
behaviour when a Control-C signal is received (SIGINT on Unix) is to raise the UserInterrupt
exception in the main thread; if the main thread is blocked in a foreign call at the time, then
the program will not respond to the user interrupt.
The problem is that it is not possible in general to interrupt a foreign call safely. However,
GHC does provide a way to interrupt blocking system calls which works for most system calls
on both Unix and Windows.
When the InterruptibleFFI extension is enabled, a foreign call can be annotated with in-
terruptible instead of safe or unsafe:
interruptible behaves exactly as safe, except that when a throwTo is directed at a thread
in an interruptible foreign call, an OS-specific mechanism will be used to attempt to cause
the foreign call to return:
Unix systems The thread making the foreign call is sent a SIGPIPE signal using
pthread_kill(). This is usually enough to cause a blocking system call to return with
EINTR (GHC by default installs an empty signal handler for SIGPIPE, to override the
default behaviour which is to terminate the process immediately).
Windows systems [Vista and later only] The RTS calls the Win32 function CancelSyn-
chronousIo, which will cause a blocking I/O operation to return with the error ER-
ROR_OPERATION_ABORTED.
Once the system call is successfully interrupted, the surrounding code must return control
out of the foreign import, back into Haskell code, so that the throwTo Haskell exception
can be raised there.
If the foreign code simply retries the system call directly without returning back to
Haskell, then the intended effect of interruptible disappears and functions like Sys-
[Link] will not work.
Finally, after the interruptible foreign call returns into Haskell, the Haskell code should
allow exceptions to be raised ([Link]‘s allowInterrupt, or interruptible
yield for non--threaded, see [Link] and implement
the EINTR-retrying in Haskell (e.g. using e.g. [Link].throwErrnoIfMinus1Retry).
Be especially careful when using interruptible to check that the called foreign function is
prepared to deal with the consequences of the call being interrupted. On Unix it is considered
good practice to always check for EINTR after system calls, so you can expect it not to crash
(but in that case interruptible will not work as intended unless the code then returns all the
way up to Haskell as described above). But on Windows it is not typically common practice
to handle ERROR_OPERATION_ABORTED.
The approach works only for foreign code that does I/O (system calls), not for CPU-intensive
computations that do not do any system calls. This is because the only way by which the
foreign code can observe interruption is by system calls returning interruption error codes.
To be able to interrupt long-running foreign code doing no system calls, the code must likely
be changed to explicitly check for intended early termination.
CApiFFI
Since 7.10.1
The CApiFFI extension allows a calling convention of capi to be used in foreign declarations,
e.g.
Rather than generating code to call f according to the platform’s ABI, we instead call f using
the C API defined in the header header.h. Thus f can be called even if it may be defined as
a CPP #define rather than a proper function.
When using capi, it is also possible to import values, rather than functions. For example,
or with
#define pi 3.14
In order to tell GHC the C type that a Haskell type corresponds to when it is used with the
CAPI, a CTYPE pragma can be used on the type definition. The header which defines the type
can optionally also be specified. The syntax looks like:
hs_thread_done()
void hs_thread_done(void);
GHC allocates a small amount of thread-local memory when a thread calls a Haskell function
via a foreign export. This memory is not normally freed until hs_exit(); the memory is
cached so that subsequent calls into Haskell are fast. However, if your application is long-
running and repeatedly creates new threads that call into Haskell, you probably want to
arrange that this memory is freed in those threads that have finished calling Haskell functions.
To do this, call hs_thread_done() from the thread whose memory you want to free.
Calling hs_thread_done() is entirely optional. You can call it as often or as little as you like.
It is safe to call it from a thread that has never called any Haskell functions, or one that never
will. If you forget to call it, the worst that can happen is that some memory remains allocated
until hs_exit() is called. If you call it too often, the worst that can happen is that the next
call to a Haskell function incurs some extra overhead.
The standard function hs_free_stable_ptr locks the stable pointer table, frees the given
stable pointer, and then unlocks the stable pointer table again. When freeing many stable
pointers at once, it is usually more efficient to lock and unlock the table only once.
The following sections also give some hints and tips on the use of the foreign function interface
in GHC.
Using foreign export and foreign import ccall "wrapper" with GHC
When GHC compiles a module (say [Link]) which uses foreign export or foreign import
"wrapper", it generates a M_stub.h for use by C programs.
For a plain foreign export, the file M_stub.h contains a C prototype for the foreign exported
function. For example, if we compile the following module:
#include "HsFFI.h"
extern HsInt foo(HsInt a0);
Normally, GHC’s runtime system provides a main(), which arranges to invoke [Link] in
the Haskell program. However, you might want to link some Haskell code into a program
which has a main function written in another language, say C. In order to do this, you have
to initialize the Haskell runtime system explicitly.
Let’s take the example from above, and invoke it from a standalone C program. Here’s the C
code:
#include <stdio.h>
#include "HsFFI.h"
#if defined(__GLASGOW_HASKELL__)
#include "Foo_stub.h"
#endif
hs_init(&argc, &argv);
hs_exit();
return 0;
}
We’ve surrounded the GHC-specific bits with #if defined(__GLASGOW_HASKELL__); the rest
of the code should be portable across Haskell implementations that support the FFI standard.
The call to hs_init() initializes GHC’s runtime system. Do NOT try to invoke any Haskell
functions before calling hs_init(): bad things will undoubtedly happen.
We pass references to argc and argv to hs_init() so that it can separate out any arguments
for the RTS (i.e. those arguments between +RTS...-RTS).
After we’ve finished invoking our Haskell functions, we can call hs_exit(), which terminates
the RTS.
There can be multiple calls to hs_init(), but each one should be matched by one (and only
one) call to hs_exit(). The outermost hs_exit() will actually de-initialise the system. Note
that currently GHC’s runtime cannot reliably re-initialise after this has happened; see The
Foreign Function Interface (page 609).
Note: When linking the final program, it is normally easiest to do the link using GHC,
although this isn’t essential. If you do use GHC, then don’t forget the flag -no-hs-main
(page 219), otherwise GHC will try to link to the Main Haskell module.
Note: On Windows hs_init treats argv as UTF8-encoded. Passing other encodings might lead
to unexpected results. Passing NULL as argv is valid but can lead to <unknown> showing up
in error messages instead of the name of the executable.
To use +RTS flags with hs_init(), we have to modify the example slightly. By default, GHC’s
RTS will only accept “safe” +RTS flags (see Options affecting linking (page 217)), and the
-rtsopts[=⟨none|some|all|ignore|ignoreAll⟩] (page 220) link-time flag overrides this.
However, -rtsopts[=⟨none|some|all|ignore|ignoreAll⟩] (page 220) has no effect when
-no-hs-main (page 219) is in use (and the same goes for -with-rtsopts=⟨opts⟩ (page 221)).
To set these options we have to call a GHC-specific API instead of hs_init():
#include <stdio.h>
#include "HsFFI.h"
#if defined(__GLASGOW_HASKELL__)
#include "Foo_stub.h"
#include "Rts.h"
#endif
#endif
hs_exit();
return 0;
}
Note two changes: we included Rts.h, which defines the GHC-specific external RTS interface,
and we called hs_init_ghc() instead of hs_init(), passing an argument of type RtsConfig.
RtsConfig is a struct with various fields that affect the behaviour of the runtime system. Its
definition is:
typedef struct {
RtsOptsEnabledEnum rts_opts_enabled;
const char *rts_opts;
} RtsConfig;
typedef enum {
RtsOptsNone, // +RTS causes an error
RtsOptsSafeOnly, // safe RTS options allowed; others cause an error
RtsOptsAll // all RTS options allowed
} RtsOptsEnabledEnum;
There is a default value defaultRtsConfig that should be used to initialise variables of type
RtsConfig. More fields will undoubtedly be added to RtsConfig in the future, so in order to
keep your code forwards-compatible it is best to initialise with defaultRtsConfig and then
modify the required fields, as in the code sample above.
The scenario here is much like in Using your own main() (page 485), except that the aim is
not to link a complete program, but to make a library from Haskell code that can be deployed
in the same way that you would deploy a library of C code.
The main requirement here is that the runtime needs to be initialized before any Haskell code
can be called, so your library should provide initialisation and deinitialisation entry points,
implemented in C or C++. For example:
#include <stdlib.h>
#include "HsFFI.h"
HsBool mylib_init(void){
int argc = 2;
char *argv[] = { "+RTS", "-A32m", NULL };
char **pargv = argv;
return HS_BOOL_TRUE;
}
void mylib_end(void){
hs_exit();
}
The initialisation routine, mylib_init, calls hs_init() as normal to initialise the Haskell
runtime, and the corresponding deinitialisation function mylib_end() calls hs_exit() to shut
down the runtime.
C functions are normally declared using prototypes in a C header file. Earlier versions of GHC
(6.8.3 and earlier) #included the header file in the C source file generated from the Haskell
code, and the C compiler could therefore check that the C function being called via the FFI
was being called at the right type.
GHC no longer includes external header files when compiling via C, so this checking is not
performed. The change was made for compatibility with the native code generator (page 209)
(-fasm (page 216)) and to comply strictly with the FFI specification, which requires that FFI
calls are not subject to macro expansion and other CPP conversions that may be applied when
using C header files. This approach also simplifies the inlining of foreign calls across module
and package boundaries: there’s no need for the header file to be available when compiling
an inlined version of a foreign call, so the compiler is free to inline foreign calls in any context.
The -#include option is now deprecated, and the include-files field in a Cabal package
specification is ignored.
Memory Allocation
The FFI libraries provide several ways to allocate memory for use with the FFI, and it isn’t
always clear which way is the best. This decision may be affected by how efficient a particular
kind of allocation is on a given compiler/platform, so this section aims to shed some light on
how the different kinds of allocation perform with GHC.
alloca Useful for short-term allocation when the allocation is intended to scope over a given
IO computation. This kind of allocation is commonly used when marshalling data to and
from FFI functions.
In GHC, alloca is implemented using MutableByteArray#, so allocation and deallocation
are fast: much faster than C’s malloc/free, but not quite as fast as stack allocation in
C. Use alloca whenever you can.
mallocForeignPtr Useful for longer-term allocation which requires garbage collection. If
you intend to store the pointer to the memory in a foreign data structure, then malloc-
ForeignPtr is not a good choice, however.
In GHC, mallocForeignPtr is also implemented using MutableByteArray#. Although
the memory is pointed to by a ForeignPtr, there are no actual finalizers involved (unless
you add one with addForeignPtrFinalizer), and the deallocation is done using GC, so
mallocForeignPtr is normally very cheap.
malloc/free If all else fails, then you need to resort to [Link] and [Link].
These are just wrappers around the C functions of the same name, and their efficiency
will depend ultimately on the implementations of these functions in your platform’s C
library. We usually find malloc and free to be significantly slower than the other forms
of allocation above.
[Link] Pools are currently implemented using malloc/free, so while they
might be a more convenient way to structure your memory allocation than using one of
the other forms of allocation, they won’t be any more efficient. We do plan to provide an
improved-performance implementation of Pools in the future, however.
In order to use the FFI in a multi-threaded setting, you must use the -threaded (page 220)
option (see Options affecting linking (page 217)).
When you call a foreign imported function that is annotated as safe (the default), and the
program was linked using -threaded (page 220), then the call will run concurrently with other
running Haskell threads. If the program was linked without -threaded (page 220), then the
other Haskell threads will be blocked until the call returns.
This means that if you need to make a foreign call to a function that takes a long time or
blocks indefinitely, then you should mark it safe and use -threaded (page 220). Some library
functions make such calls internally; their documentation should indicate when this is the
case.
If you are making foreign calls from multiple Haskell threads and using -threaded (page 220),
make sure that the foreign code you are calling is thread-safe. In particularly, some GUI
libraries are not thread-safe and require that the caller only invokes GUI methods from a
single thread. If this is the case, you may need to restrict your GUI operations to a single
Haskell thread, and possibly also use a bound thread (see The relationship between Haskell
threads and OS threads (page 489)).
Note that foreign calls made by different Haskell threads may execute in parallel, even when
the +RTS -N flag is not being used (RTS options for SMP parallelism (page 118)). The -N ⟨x⟩
(page 118) flag controls parallel execution of Haskell threads, but there may be an arbitrary
number of foreign calls in progress at any one time, regardless of the +RTS -N value.
If a call is annotated as interruptible and the program was multithreaded, the call may be
interrupted in the event that the Haskell thread receives an exception. The mechanism by
which the interrupt occurs is platform dependent, but is intended to cause blocking system
calls to return immediately with an interrupted error code. The underlying operating system
thread is not to be destroyed. See Interruptible foreign calls (page 482) for more details.
Normally there is no fixed relationship between Haskell threads and OS threads. This means
that when you make a foreign call, that call may take place in an unspecified OS thread.
Furthermore, there is no guarantee that multiple calls made by one Haskell thread will be
made by the same OS thread.
This usually isn’t a problem, and it allows the GHC runtime system to make efficient use of
OS thread resources. However, there are cases where it is useful to have more control over
which OS thread is used, for example when calling foreign code that makes use of thread-
local state. For cases like this, we provide bound threads, which are Haskell threads tied
to a particular OS thread. For information on bound threads, see the documentation for the
[Link] module.
When the program is linked with -threaded (page 220), then you may invoke foreign ex-
ported functions from multiple OS threads concurrently. The runtime system must be ini-
tialised as usual by calling hs_init(), and this call must complete before invoking any for-
eign exported functions.
hs_exit() normally causes the termination of any running Haskell threads in the system,
and when hs_exit() returns, there will be no more Haskell threads running. The runtime
will then shut down the system in an orderly way, generating profiling output and statistics if
necessary, and freeing all the memory it owns.
It isn’t always possible to terminate a Haskell thread forcibly: for example, the thread might
be currently executing a foreign call, and we have no way to force the foreign call to complete.
What’s more, the runtime must assume that in the worst case the Haskell code and runtime
are about to be removed from memory (e.g. if this is a Windows DLL (page 598), hs_exit()
is normally called before unloading the DLL). So hs_exit() must wait until all outstanding
foreign calls return before it can return itself.
The upshot of this is that if you have Haskell threads that are blocked in foreign calls, then
hs_exit() may hang (or possibly busy-wait) until the calls return. Therefore it’s a good idea
to make sure you don’t have any such threads in the system when calling hs_exit(). This
includes any threads doing I/O, because I/O may (or may not, depending on the type of I/O
and the platform) be implemented using blocking foreign calls.
The GHC runtime treats program exit as a special case, to avoid the need to wait for blocked
threads when a standalone executable exits. Since the program and all its threads are about
to terminate at the same time that the code is removed from memory, it isn’t necessary to
ensure that the threads have exited first. If you want this fast and loose version of hs_exit(),
you can call:
void hs_exit_nowait(void);
instead. This is particularly useful if you have foreign libraries that need to call hs_exit() at
program exit (perhaps via a C++ destructor): in this case you should use hs_exit_nowait(),
because the thread that called exit() and is running C++ destructors is in a foreign call
from Haskell that will never return, so hs_exit() would deadlock.
Sometimes we want to be able to wake up a Haskell thread from some C code. For example,
when using a callback-based C API, we register a C callback and then we need to wait for the
callback to run.
One way to do this is to create a foreign export that will do whatever needs to be done to
wake up the Haskell thread - perhaps putMVar - and then call this from our C callback. There
are a couple of problems with this:
1. Calling a foreign export has a lot of overhead: it creates a complete new Haskell thread,
for example.
2. The call may block for a long time if a GC is in progress. We can’t use this method if the
C API we’re calling doesn’t allow blocking in the callback.
For these reasons GHC provides an external API to tryPutMVar, hs_try_putmvar, which you
can use to cheaply and asynchronously wake up a Haskell thread from C/C++.
The C call hs_try_putmvar(cap,mvar) is equivalent to the Haskell call tryPutMVar mvar (),
except that it is
• non-blocking: takes a bounded, short, amount of time
• asynchronous: the actual putMVar may be performed after the call returns (for example,
if the RTS is currently garbage collecting). That’s why hs_try_putmvar() doesn’t return
a result to say whether the put succeeded. It is your responsibility to ensure that the
MVar is empty; if it is full, hs_try_putmvar() will have no effect.
Example. Suppose we have a C/C++ function to call that will return and then invoke a
callback at some point in the future, passing us some data. We want to wait in Haskell for the
callback to be called, and retrieve the data. We can do it like this:
makeExternalCall = mask_ $ do
mvar <- newEmptyMVar
sp <- newStablePtrPrimMVar mvar
fp <- mallocForeignPtr
withForeignPtr fp $ \presult -> do
cap <- threadCapability =<< myThreadId
scheduleCallback sp cap presult
takeMVar mvar `onException`
forkIO (do takeMVar mvar; touchForeignPtr fp)
peek presult
And inside scheduleCallback, we create a callback that will in due course store the result
data in the Ptr Result, and then call hs_try_putmvar().
There are a few things to note here.
• There’s a special function to create the StablePtr: newStablePtrPrimMVar, because the
RTS needs a StablePtr to the primitive MVar# object, and we can’t create that directly.
Do not just use newStablePtr on the MVar: your program will crash.
• The StablePtr is freed by hs_try_putmvar(). This is because it would otherwise be
difficult to arrange to free the StablePtr reliably: we can’t free it in Haskell, because
if the takeMVar is interrupted by an asynchronous exception, then the callback will fire
at a later time. We can’t free it in C, because we don’t know when to free it (not when
hs_try_putmvar() returns, because that is an async call that uses the StablePtr at
some time in the future).
• The mask_ is to avoid asynchronous exceptions before the scheduleCallback call, which
would leak the StablePtr.
• We find out the current capability number and pass it to C. This is passed back to
hs_try_putmvar, and helps the RTS to know which capability it should try to perform the
tryPutMVar on. If you don’t care, you can pass -1 for the capability to hs_try_putmvar,
and it will pick an arbitrary one.
Picking the right capability will help avoid unnecessary context switches. Ideally you
should pass the capability that the thread that will be woken up last ran on, which you
can find by calling threadCapability in Haskell.
• If you want to also pass some data back from the C callback to Haskell, this is best done
by first allocating some memory in Haskell to receive the data, and passing the address
to C, as we did in the above example.
• takeMVar can be interrupted by an asynchronous exception. If this happens, the callback
in C will still run at some point in the future, will still write the result, and will still call
hs_try_putmvar(). Therefore we have to arrange that the memory for the result stays
alive until the callback has run, so if an exception is thrown during takeMVar we fork an-
other thread to wait for the callback and hold the memory alive using touchForeignPtr.
For a fully working example, see testsuite/tests/concurrent/should_run/hs_try_putmvar001.hs
in the GHC source tree.
The standard C99 fenv.h header provides operations for inspecting and modifying the state
of the floating point unit. In particular, the rounding mode used by floating point operations
can be changed, and the exception flags can be tested.
In Haskell, floating-point operations have pure types, and the evaluation order is unspecified.
So strictly speaking, since the fenv.h functions let you change the results of, or observe
the effects of floating point operations, use of fenv.h renders the behaviour of floating-point
operations anywhere in the program undefined.
Having said that, we can document exactly what GHC does with respect to the floating point
state, so that if you really need to use fenv.h then you can do so with full knowledge of the
pitfalls:
• GHC completely ignores the floating-point environment, the runtime neither modifies
nor reads it.
• The floating-point environment is not saved over a normal thread context-switch. So if
you modify the floating-point state in one thread, those changes may be visible in other
threads. Furthermore, testing the exception state is not reliable, because a context
switch may change it. If you need to modify or test the floating point state and use
threads, then you must use bound threads ([Link]), because a
bound thread has its own OS thread, and OS threads do save and restore the floating-
point state.
• It is safe to modify the floating-point unit state temporarily during a foreign call, because
foreign calls are never pre-empted by GHC.
A pinned byte array is one that the garbage collector is not allowed to move. Consequently,
it has a stable address that can be safely requested with byteArrayContents#. There are
a handful of primitive functions in [Link] used to enforce or check for pinnedness: is-
ByteArrayPinned#, isMutableByteArrayPinned#, and newPinnedByteArray#. A byte array
can be pinned as a result of three possible causes:
1. It was allocated by newPinnedByteArray#.
2. It is large. Currently, GHC defines large object to be one that is at least as large as 80%
of a 4KB block (i.e. at least 3277 bytes).
3. It has been copied into a compact region. The documentation for ghc-compact and com-
pact describes this process.
Safe Haskell is an extension to the Haskell language that is implemented in GHC as of version
7.2. It allows for unsafe code to be securely included in a trusted code base by restricting
the features of GHC Haskell the code is allowed to use. Put simply, it makes the types of
programs trustable.
While a primary use case of Safe Haskell is running untrusted code, Safe Haskell doesn’t
provide this directly. Instead, Safe Haskell provides strict type safety. Without Safe Haskell,
GHC allows many exceptions to the type system which can subvert any abstractions. By
providing strict type safety, Safe Haskell enables developers to build their own library level
sandbox mechanisms to run untrusted code.
While Safe Haskell is an extension, it actually runs in the background for every compila-
tion with GHC. It does this to track the type violations of modules to infer their safety, even
when they aren’t explicitly using Safe Haskell. Please refer to section Safe Haskell Inference
(page 501) for more details of this.
The design of Safe Haskell covers the following aspects:
• A safe language (page 496) dialect of Haskell that provides stricter guarantees about
the code. It allows types and module boundaries to be trusted.
• A safe import extension that specifies that the module being imported must be trusted.
• A definition of trust (or safety) and how it operates, along with ways of defining and
changing the trust of modules and packages.
Safe Haskell, however, does not offer compilation safety. During compilation time it is possible
for arbitrary processes to be launched, using for example the custom pre-processor (page 215)
flag. This can be manipulated to either compromise a user’s system at compilation time, or
to modify the source code just before compilation to try to alter Safe Haskell flags. This is
discussed further in section Safe Compilation (page 503).
Safe Haskell has been designed with two use cases in mind:
• Enforcing strict type safety at compile time
• Compiling and executing untrusted code
Haskell offers a powerful type system and separation of pure and effectual functions through
the IO monad. However, there are several loop holes in the type system, the most obvious be-
ing the unsafePerformIO :: IO a -> a function. The safe language dialect of Safe Haskell
disallows the use of such functions. This can be useful restriction as it makes Haskell code
easier to analyse and reason about. It also codifies the existing culture in the Haskell com-
munity of trying to avoid unsafe functions unless absolutely necessary. As such, using the
safe language (through the -XSafe flag) can be thought of as a way of enforcing good style,
similar to the function of -Wall.
Systems such as information flow control security, capability based security systems and DSLs
for working with encrypted data.. etc can be built in the Haskell language as a library. How-
ever they require guarantees about the properties of Haskell that aren’t true in general due to
the presence of functions like unsafePerformIO. Safe Haskell gives users enough guarantees
about the type system to allow them to build such secure systems.
As an example, let’s define an interface for a plugin system where the plugin authors are
untrusted, possibly malicious third-parties. We do this by restricting the plugin interface to
pure functions or to a restricted IO monad that we have defined. The restricted IO monad
will only allow a safe subset of IO actions to be executed. We define the plugin interface so
that it requires the plugin module, Danger, to export a single computation, [Link], of
type RIO (), where RIO is a monad defined as follows:
We then compile the Danger plugin using the new Safe Haskell -XSafe flag:
{-# LANGUAGE Safe #-}
module Danger ( runMe ) where
runMe :: RIO ()
runMe = ...
Before going into the Safe Haskell details, let’s point out some of the reasons this security
mechanism would fail without Safe Haskell:
• The design attempts to restrict the operations that Danger can perform by using types,
specifically the RIO type wrapper around IO . The author of Danger can subvert this
though by simply writing arbitrary IO actions and using unsafePerformIO :: IO a ->
a to execute them as pure functions.
• The design also relies on Danger not being able to access the UnsafeRIO constructor.
Unfortunately Template Haskell can be used to subvert module boundaries and so could
be used to gain access to this constructor.
• There is no way to place restrictions on the modules that Danger can import. This gives
the author of Danger a very large attack surface, essentially any package currently in-
stalled on the system. Should any of these packages have a vulnerability, then the Danger
module can exploit it.
Safe Haskell prevents all these attacks. This is done by compiling the RIO module with
the Safe (page 502) or Trustworthy (page 502) flag and compiling Danger with the Safe
(page 502) flag. We explain each below.
The use of Safe (page 502) to compile Danger restricts the features of Haskell that can be used
to a safe subset (page 496). This includes disallowing unsafePerformIO, Template Haskell,
pure FFI functions, RULES and restricting the operation of Overlapping Instances. The Safe
(page 502) flag also restricts the modules can be imported by Danger to only those that are
considered trusted. Trusted modules are those compiled with Safe (page 502), where GHC
provides a mechanical guarantee that the code is safe. Or those modules compiled with
Trustworthy (page 502), where the module author claims that the module is Safe.
This is why the RIO module is compiled with Safe (page 502) or Trustworthy (page 502)>,
to allow the Danger module to import it. The Trustworthy (page 502) flag doesn’t place any
restrictions on the module like Safe (page 502) does (expect to restrict overlapping instances
to safe overlapping instances (page 497)). Instead the module author claims that while code
may use unsafe features internally, it only exposes an API that can used in a safe manner.
However, the unrestricted use of Trustworthy (page 502) is a problem as an arbitrary module
can use it to mark themselves as trusted, yet Trustworthy (page 502) doesn’t offer any guar-
antees about the module, unlike Safe (page 502). To control the use of trustworthy modules it
is recommended to use the -fpackage-trust (page 502) flag. This flag adds an extra require-
ment to the trust check for trustworthy modules. It requires that for a trustworthy modules to
be considered trusted, and allowed to be used in Safe (page 502) compiled code, the client C
compiling the code must tell GHC that they trust the package the trustworthy module resides
in. This is essentially a way of for C to say, while this package contains trustworthy modules
that can be used by untrusted modules compiled with Safe (page 502), I trust the author(s)
of this package and trust the modules only expose a safe API. The trust of a package can be
changed at any time, so if a vulnerability found in a package, C can declare that package
untrusted so that any future compilation against that package would fail. For a more detailed
overview of this mechanism see Trust and Safe Haskell Modes (page 498).
In the example, Danger can import module RIO because RIO is compiled with Safe (page 502).
Thus, Danger can make use of the rioReadFile and rioWriteFile functions to access per-
mitted file names. The main application then imports both RIO and Danger. To run the plugin,
it calls [Link] [Link] within the IO monad. The application is safe in the knowl-
edge that the only IO to ensue will be to files whose paths were approved by the pathOK
test.
The Safe Haskell checks can be disabled for a module by passing the -fno-safe-haskell
(page 502) flag. This is useful in particular when compiling with source plugins as running a
plugin marks the module as unsafe and can then cause downstream modules to fail the safety
checks.
The Safe Haskell safe language (enabled by -XSafe) guarantees the following properties:
• Referential transparency — The types can be trusted. Any pure function, is guaranteed
to be pure. Evaluating them is deterministic and won’t cause any side effects. Functions
in the IO monad are still allowed and behave as usual. So, for example, the unsafePer-
formIO :: IO a -> a function is disallowed in the safe language to enforce this prop-
erty.
• Module boundary control — Only symbols that are publicly available through other mod-
ule export lists can be accessed in the safe language. Values using data constructors not
exported by the defining module, cannot be examined or created. As such, if a module
M establishes some invariants through careful use of its export list, then code written in
the safe language that imports M is guaranteed to respect those invariants.
• Semantic consistency — For any module that imports a module written in the safe lan-
guage, expressions that compile both with and without the safe import have the same
meaning in both cases. That is, importing a module written in the safe language cannot
change the meaning of existing code that isn’t dependent on that module. So, for exam-
ple, there are some restrictions placed on the use of OverlappingInstances (page 414),
as these can violate this property.
• Strict subset — The safe language is strictly a subset of Haskell as implemented by GHC.
Any expression that compiles in the safe language has the same meaning as it does when
compiled in normal Haskell.
These four properties guarantee that in the safe language you can trust the types, can trust
that module export lists are respected, and can trust that code that successfully compiles has
the same meaning as it normally would.
To achieve these properties, in the safe language dialect we disable completely the following
features:
• TemplateHaskell (page 450) — Can be used to gain access to constructors and abstract
data types that weren’t exported by a module, subverting module boundaries.
Furthermore, we restrict the following features:
• ForeignFunctionInterface (page 478) — Foreign import declarations that import a
function with a non-IO type are disallowed.
• RULES — Rewrite rules defined in a module M compiled with Safe (page 502) are dropped.
Rules defined in Trustworthy modules that M imports are still valid and will fire as usual.
• OverlappingInstances (page 414) — There is no restriction on the creation of overlap-
ping instances, but we do restrict their use at a particular call site. This is a detailed
restriction, please refer to Safe Overlapping Instances (page 497) for details.
Due to the semantic consistency guarantee of Safe Haskell, we must restrict the function
of overlapping instances. We don’t restrict their ability to be defined, as this is a global
property and not something we can determine by looking at a single module. Instead, when
a module calls a function belonging to a type-class, we check that the instance resolution
done is considered ‘safe’. This check is enforced for modules compiled with both -XSafe and
-XTrustworthy.
More specifically, consider the following modules:
instance
{-# OVERLAPS #-}
TC [Int] where { op _ = "[Int]" }
instance
TC [a] where { op _ = "[a]" }
f :: String
f = op ([1,2,3,4] :: [Int])
Both module Class and module Dangerous will compile under Safe (page 502) without issue.
However, in module TCB_Runner, we must check if the call to op in function f is safe.
What does it mean to be Safe? That importing a module compiled with Safe (page 502)
shouldn’t change the meaning of code that compiles fine without importing the module. This
is the Safe Haskell property known as semantic consistency.
In our situation, module TCB_Runner compiles fine without importing module Dangerous. So
when deciding which instance to use for the call to op, if we determine the instance TC [Int]
from module Dangerous is the most specific, this is unsafe. This prevents code written by
third-parties we don’t trust (which is compiled using -XSafe in Safe Haskell) from changing
the behaviour of our existing code.
Specifically, we apply the following rule to determine if a type-class method call is unsafe
when overlapping instances are involved:
• Most specific instance, Ix, defined in an -XSafe compiled module.
• Ix is an orphan instance or a multi-parameter-type-class.
• At least one overlapped instance, Iy, is both:
– From a different module than Ix
– Iy is not marked OVERLAPPABLE
This is a slightly involved heuristic, but captures the situation of an imported module N chang-
ing the behaviour of existing code. For example, if the second condition isn’t violated, then
the module author M must depend either on a type-class or type defined in N.
When a particular type-class method call is considered unsafe due to overlapping instances,
and the module being compiled is using Safe (page 502) or Trustworthy (page 502), then
compilation will fail. For Unsafe (page 502), no restriction is applied, and for modules using
safe inference, they will be inferred unsafe.
Safe Haskell enables a small extension to the usual import syntax of Haskell, adding a safe
keyword:
impdecl -> import [safe] [qualified] modid [as modid] [impspec]
When used, the module being imported with the safe keyword must be a trusted module,
otherwise a compilation error will occur. The safe import extension is enabled by either of
the -XSafe , -XTrustworthy , or -XUnsafe flags. When the -XSafe flag is used, the safe
keyword is allowed but meaningless, as every import is treated as a safe import.
• Unsafe (page 502) — Marks the module being compiled as unsafe so that modules com-
piled using Safe (page 502) can’t import it. You may want to explicitly mark a module
unsafe when it exports internal constructors that can be used to violate invariants.
While these are flags, they also correspond to Safe Haskell module types that a module can
have. You can think of using these as declaring an explicit contract (or type) that a module
must have. If it is invalid, then compilation will fail. GHC will also infer the correct type for
Safe Haskell, please refer to section Safe Haskell Inference (page 501) for more details.
The procedure to check if a module is trusted or not depends on if the -fpackage-trust
(page 502) flag is present. The check is similar in both cases with the -fpackage-trust
(page 502) flag enabling an extra requirement for trustworthy modules to be regarded as
trusted.
When the -fpackage-trust (page 502) flag is enabled, whether or not a module is trusted
depends on if certain packages are trusted. Package trust is determined by the client C
invoking GHC (i.e. you).
Specifically, a package P is trusted when one of these hold:
• C’s package database records that P is trusted (and no command-line arguments override
this)
• C’s command-line flags say to trust P regardless of what is recorded in the package
database.
In either case, C is the only authority on package trust. It is up to the client to decide which
packages they trust (page 501).
When the -fpackage-trust (page 502) flag is used a module M from package P is trusted by
a client C if and only if:
• Both of these hold:
– The module was compiled with Safe (page 502)
– All of M‘s direct imports are trusted by C
Example
Package Wuggle:
{-# LANGUAGE Safe #-}
module Buggle where
import Prelude
f x = ...blah...
Package P:
{-# LANGUAGE Trustworthy #-}
module M where
import [Link]
import safe Buggle
Suppose a client C decides to trust package P and package base. Then does C trust module
M? Well M is marked Trustworthy (page 502), so we don’t restrict the language. However, we
still must check M‘s imports:
• First, M imports [Link]. This is an unsafe module, however M was compiled
with Trustworthy (page 502) , so P‘s author takes responsibility for that import. C trusts
P‘s author, so this import is fine.
• Second, M safe imports Buggle. For this import P‘s author takes no responsibility for the
safety, instead asking GHC to check whether Buggle is trusted by C. Is it?
• Buggle, is compiled with -XSafe, so the code is machine-checked to be OK, but again
under the assumption that all of Buggle‘s imports are trusted by C. We must recursively
check all imports!
• Buggle only imports Prelude, which is compiled with Trustworthy (page 502). Prelude
resides in the base package, which C trusts, and (we’ll assume) all of Prelude‘s imports
are trusted. So C trusts Prelude, and so C also trusts Buggle. (While Prelude is typically
imported implicitly, it still obeys the same rules outlined here).
Notice that C didn’t need to trust package Wuggle; the machine checking is enough. C only
needs to trust packages that contain Trustworthy (page 502) modules.
Trustworthy Requirements
Module authors using the Trustworthy (page 502) language extension for a module M should
ensure that M‘s public API (the symbols exposed by its export list) can’t be used in an un-
safe manner. This mean that symbols exported should respect type safety and referential
transparency.
Package Trust
Safe Haskell gives packages a new Boolean property, that of trust. Several new options are
available at the GHC command-line to specify the trust property of packages:
-trust ⟨pkg⟩
Exposes package ⟨pkg⟩ if it was hidden and considers it a trusted package regardless of
the package database.
-distrust ⟨pkg⟩
Exposes package ⟨pkg⟩ if it was hidden and considers it an untrusted package regardless
of the package database.
-distrust-all-packages
Considers all packages distrusted unless they are explicitly set to be trusted by subse-
quent command-line options.
To set a package’s trust property in the package database please refer to Packages (page 193).
In the case where a module is compiled without one of Safe (page 502), Trustworthy
(page 502) or Unsafe (page 502) being used, GHC will try to figure out itself if the mod-
ule can be considered safe. This safety inference will never mark a module as trustworthy,
only as either unsafe or as safe. GHC uses a simple method to determine this for a module M:
If M would compile without error under the Safe (page 502) flag, then M is marked as safe.
Otherwise, it is marked as unsafe.
When should you use Safe Haskell inference and when should you use an explicit Safe
(page 502) flag? The later case should be used when you have a hard requirement that the
module be safe. This is most useful for the Uses of Safe Haskell (page 493) of Safe Haskell:
running untrusted code. Safe inference is meant to be used by ordinary Haskell programmers.
Users who probably don’t care about Safe Haskell.
Haskell library authors have a choice. Most should just use Safe inference. Assuming you
avoid any unsafe features of the language then your modules will be marked safe. Inferred
vs. Explicit has the following trade-offs:
• Inferred — This works well and adds no dependencies on the Safe Haskell type of any
modules in other packages. It does mean that the Safe Haskell type of your own modules
could change without warning if a dependency changes. One way to deal with this is
through the use of Safe Haskell warning flags (page 502) that will warn if GHC infers a
Safe Haskell type different from expected.
• Explicit — This gives your library a stable Safe Haskell type that others can depend on.
However, it will increase the chance of compilation failure when your package depen-
dencies change.
-fpackage-trust
When enabled, turn on an extra check for a trustworthy module M, requiring the package
that M resides in be considered trusted, for M to be considered trusted.
And five warning flags:
-Wunsafe
Issue a warning if the module being compiled is regarded to be unsafe. Should be used
to check the safety type of modules when using safe inference.
-Wsafe
Issue a warning if the module being compiled is regarded to be safe. Should be used to
check the safety type of modules when using safe inference. If the module is explicitly
marked as safe then no warning will be issued.
-Wtrustworthy-safe
Issue a warning if the module being compiled is marked as -XTrustworthy but it could
instead be marked as -XSafe , a more informative bound. Can be used to detect once a
Safe Haskell bound can be improved as dependencies are updated.
-Winferred-safe-imports
Since 8.10.1
The module A below is annotated to be explicitly Safe, but it imports Safe-Inferred
module.
import B (double)
module B where
The inferred status is volatile: if an unsafe import is added to the module B, it will cause
compilation error of A. When -Winferred-safe-imports (page 503) is enabled, the com-
piler will emit a warning about this. This option is off by default.
-Wmissing-safe-haskell-mode
Since 8.10.1
The compiler will warn when none of Safe (page 502), Trustworthy (page 502) or Unsafe
(page 502) is specified. This option is off by default.
GHC includes a variety of flags that allow arbitrary processes to be run at compilation time.
One such example is the custom pre-processor (page 215) flag. Another is the ability of
Template Haskell to execute Haskell code at compilation time, including IO actions. Safe
Haskell does not address this danger (although, Template Haskell is a disallowed feature).
Due to this, it is suggested that when compiling untrusted source code that has had no manual
inspection done, the following precautions be taken:
• Compile in a sandbox, such as a chroot or similar container technology. Or simply as a
user with very reduced system access.
• Compile untrusted code with the -XSafe flag being specified on the command line. This
will ensure that modifications to the source being compiled can’t disable the use of the
Safe Language as the command line flag takes precedence over a source level pragma.
• Ensure that all untrusted code is imported as a safe import (page 498) and that the
-fpackage-trust (page 502) flag (see flag (page 501)) is used with packages from un-
trusted sources being marked as untrusted.
There is a more detailed discussion of the issues involved in compilation safety and some
potential solutions on the GHC Wiki.
Additionally, the use of annotations (page 531) is forbidden, as that would allow bypassing
Safe Haskell restrictions. See #10826 for details.
6.19 Miscellaneous
{-# RULES "⟨name⟩" forall ⟨binder⟩ ... . ⟨expr⟩ = ⟨expr⟩ ... #-}
Where top-level
Define a rewrite rule to be used to optimize a source program.
The programmer can specify rewrite rules as part of the source program (in a pragma). Here
is an example:
{-# RULES
"map/map" forall f g xs. map f (map g xs) = map (f.g) xs
#-}
Use the debug flag -ddump-simpl-stats (page 229) to see what rules fired. If you need more
information, then -ddump-rule-firings (page 229) shows you each individual rule firing and
-ddump-rule-rewrites (page 229) also shows what the code looks like before and after the
rewrite.
-fenable-rewrite-rules
Allow the compiler to apply rewrite rules to the source program.
Syntax
{-# RULES
"map/map" forall f g xs. map f (map g xs) = map (f.g) xs
"map/append" forall f xs ys. map f (xs ++ ys) = map f xs ++ map f ys
#-}
Furthermore, the closing #-} should start in a column to the right of the opening {-#.
• Each rule has a name, enclosed in double quotes. The name itself has no significance at
all. It is only used when reporting how many times the rule fired.
• A rule may optionally have a phase-control number (see Phase control (page 523)), im-
mediately after the name of the rule. Thus:
{-# RULES
"map/map" [2] forall f g xs. map f (map g xs) = map (f.g) xs
#-}
The [2] means that the rule is active in Phase 2 and subsequent phases. The inverse
notation [~2] is also accepted, meaning that the rule is active up to, but not including,
Phase 2.
Rules support the special phase-control notation [~], which means the rule is never ac-
tive. This feature supports plugins (see Compiler Plugins (page 533)), by making it possi-
ble to define a RULE that is never run by GHC, but is nevertheless parsed, typechecked
etc, so that it is available to the plugin.
• Each (term) variable mentioned in a rule must either be in scope (e.g. map), or bound
by the forall (e.g. f, g, xs). The variables bound by the forall are called the pattern
variables. They are separated by spaces, just like in a type forall.
• A pattern variable may optionally have a type signature. If the type of the pattern variable
is polymorphic, it must have a type signature. For example, here is the foldr/build rule:
When a type-level explicit forall is present, each type/kind variable mentioned must
now also be either in scope or bound by the forall. In particular, unlike some other
places in Haskell, this means free kind variables will not be implicitly bound. For exam-
ple:
When bound type/kind variables are needed, both foralls must always be included,
though if no pattern variables are needed, the second can be left empty. For example:
{-# RULES "map/id" forall a. forall. map (id @a) = id @[a] #-}
• The left hand side of a rule must consist of a top-level variable applied to arbitrary ex-
pressions. For example, this is not OK:
"wrong1" forall e1 e2. case True of { True -> e1; False -> e2 } = e1
"wrong2" forall f. f True = True
"wrong3" forall x. Just x = Nothing
In "wrong1", the LHS is not an application; in "wrong2", the LHS has a pattern variable in
the head. In "wrong3", the LHS consists of a constructor, rather than a variable, applied
to an argument.
• A rule does not need to be in the same module as (any of) the variables it mentions,
though of course they need to be in scope.
• All rules are implicitly exported from the module, and are therefore in force in any mod-
ule that imports the module that defined the rule, directly or indirectly. (That is, if A
imports B, which imports C, then C’s rules are in force when compiling A.) The situation
is very similar to that for instance declarations.
• Inside a RULES (page 504) “forall” is treated as a keyword, regardless of any other
flag settings. Furthermore, inside a RULES (page 504), the language extension Scoped-
TypeVariables (page 436) is automatically enabled; see Lexically scoped type variables
(page 436).
• Like other pragmas, RULES (page 504) pragmas are always checked for scope errors, and
are typechecked. Typechecking means that the LHS and RHS of a rule are typechecked,
and must have the same type. However, rules are only enabled if the -fenable-rewrite-
rules (page 504) flag is on (see Semantics (page 506)).
Semantics
"loop" forall x y. f x y = f y x
syntactically equal modulo alpha conversion. The pattern (rule), but not the expression,
is eta-expanded if necessary. (Eta-expanding the expression can lead to laziness bugs.)
But not beta conversion (that’s called higher-order matching).
Matching is carried out on GHC’s intermediate language, which includes type abstrac-
tions and applications. So a rule only matches if the types match too. See Specialisation
(page 510) below.
• GHC keeps trying to apply the rules as it optimises the program. For example, consider:
let s = map f
t = map g
in
s (t xs)
The expression s (t xs) does not match the rule "map/map", but GHC will substitute
for s and t, giving an expression which does match. If s or t was (a) used more than
once, and (b) large or a redex, then it would not be substituted, and the rule would not
fire.
Ordinary inlining happens at the same time as rule rewriting, which may lead to unexpected
results. Consider this (artificial) example
f x = x
g y = f y
h z = g True
Now g is inlined into h, but f‘s RULE has no chance to fire. If instead GHC had first inlined g
into h then there would have been a better chance that f‘s RULES (page 504) might fire.
The way to get predictable behaviour is to use a NOINLINE (page 523) pragma, or an IN-
LINE[⟨phase⟩] pragma, on f, to ensure that it is not inlined until its RULES (page 504) have
had a chance to fire. The warning flag -Winline-rule-shadowing (page 103) (see Warnings
and sanity-checking (page 85)) warns about this situation.
Since xs is used twice, GHC does not fire the foldr/build rule. Rightly so, because it might
take a lot of work to compute xs, which would be duplicated if the rule fired.
Sometimes, however, this approach is over-cautious, and we do want the rule to fire, even
though doing so would duplicate redex. There is no way that GHC can work out when this is
a good idea, so we provide the CONLIKE pragma to declare it, thus:
class C a where
op :: a -> a -> a
In this example, op is not an ordinary top-level function; it is a class method. GHC rapidly
rewrites any occurrences of op-used-at-type-Bool to a specialised function, say opBool, where
So the RULE never has a chance to fire, for just the same reasons as in How rules interact
with INLINE/NOINLINE pragmas (page 507).
The solution is to define the instance-specific function yourself, with a pragma to prevent it
being inlined too early, and give a RULE for it:
If you want a RULE that truly applies to the overloaded class method, the only way to do it is
like this:
class C a where
op_c :: a -> a -> a
Now the inlining of op is delayed until the rule has a chance to fire. The down-side is that
instance declarations must define op_c, but all other uses should go via op.
List fusion
The RULES mechanism is used to implement fusion (deforestation) of common list functions.
If a “good consumer” consumes an intermediate list constructed by a “good producer”, the
intermediate list should be eliminated entirely.
The following are good producers:
• List comprehensions
• Enumerations of Int, Integer and Char (e.g. ['a'..'z']).
• Explicit lists (e.g. [True,False])
• The cons constructor (e.g 3:4:[])
• ++
• map
• take, filter
• iterate, repeat
• zip, zipWith
The following are good consumers:
• List comprehensions
• array (on its second argument)
• ++ (on its first argument)
• foldr
• map
• take, filter
• concat
• unzip, unzip2, unzip3, unzip4
• zip, zipWith (but on one argument only; if both are good producers, zip will fuse with
one but not the other)
• partition
• head
• and, or, any, all
• sequence_
• msum
So, for example, the following should generate no intermediate lists:
This list could readily be extended; if there are Prelude functions that you use a lot which are
not included, please tell us.
If you want to write your own good consumers or producers, look at the Prelude definitions
of the above functions to see how to do so.
Specialisation
Rewrite rules can be used to get the same effect as a feature present in earlier versions of
GHC. For example, suppose that:
where intLookup is an implementation of genericLookup that works very fast for keys of type
Int. You might wish to tell GHC to use intLookup instead of genericLookup whenever the
latter was called with type Table Int b -> Int -> b. It used to be possible to write
{-# SPECIALIZE genericLookup :: Table Int b -> Int -> b = intLookup #-}
This feature is no longer in GHC, but rewrite rules let you do the same thing:
This slightly odd-looking rule instructs GHC to replace genericLookup by intLookup when-
ever the types match. What is more, this rule does not need to be in the same file as gener-
icLookup, unlike the SPECIALIZE pragmas which currently do (so that they have an original
definition available to specialise).
It is Your Responsibility to make sure that intLookup really behaves as a specialised version
of genericLookup!!!
An example in which using RULES for specialisation will Win Big:
The i2d function is virtually one machine instruction; the default conversion—via an interme-
diate Rational-is obscenely expensive by comparison.
• Use -ddump-rules (page 229) to see the rules that are defined in this module. This
includes rules generated by the specialisation pass, but excludes rules imported from
other modules.
• Use -ddump-simpl-stats (page 229) to see what rules are being fired. If you add -dppr-
debug (page 227) you get a more detailed listing.
• Use -ddump-rule-firings (page 229) or -ddump-rule-rewrites (page 229) to see in
great detail what rules are being fired. If you add -dppr-debug (page 227) you get a still
more detailed listing.
• The definition of (say) build in GHC/[Link] looks like this:
Notice the INLINE (page 521)! That prevents (:) from being inlined when compiling
PrelBase, so that an importing module will “see” the (:), and can match it on the LHS
of a rule. INLINE prevents any inlining happening in the RHS of the INLINE thing. I
regret the delicacy of this.
• In libraries/base/GHC/[Link] look at the rules for map to see how to write rules that
will do fusion and yet give an efficient program even if fusion doesn’t happen. More rules
in GHC/[Link].
Note: GHC used to have an implementation of generic classes as defined in the paper
“Derivable type classes”, Ralf Hinze and Simon Peyton Jones, Haskell Workshop, Montreal
Sept 2000, pp. 94-105. These have been removed and replaced by the more general support
for generic programming.
Deriving representations
The first thing we need is generic representations. The [Link] module defines a couple
of primitive types that are used to represent Haskell datatypes:
The Generic and Generic1 classes mediate between user-defined datatypes and their internal
representation as a sum-of-products:
Generic1 is used for functions that can only be defined over type containers, such as map.
Note that Generic1 ranges over types of kind Type -> Type by default, but if the PolyKinds
(page 319) extension is enabled, then it can range of types of kind k -> Type, for any kind k.
DeriveGeneric
Since 7.2.1
Allow automatic deriving of instances for the Generic typeclass.
Instances of these classes can be derived by GHC with the DeriveGeneric (page 512) exten-
sion, and are necessary to be able to define generic instances automatically.
For example, a user-defined datatype of trees
in a Main module in a package named foo will get the following representation:
-- Conversion functions
from (Node x l r) = M1 (L1 (M1 (M1 (K1 x) :*: M1 (K1 l) :*: M1 (K1 r))))
from Leaf = M1 (R1 (M1 U1))
to (M1 (L1 (M1 (M1 (K1 x) :*: M1 (K1 l) :*: M1 (K1 r))))) = Node x l r
to (M1 (R1 (M1 U1))) = Leaf
A generic function is defined by creating a class and giving instances for each of the repre-
sentation types of [Link]. As an example we show generic serialization:
data Bin = O | I
A caveat: this encoding strategy may not be reliable across different versions of GHC. When
deriving a Generic instance is free to choose any nesting of :+: and :*: it chooses, so if GHC
chooses (a :+: b) :+: c, then the encoding for a would be [O,O], b would be [O,I], and c
would be [I]. However, if GHC chooses a :+: (b :+: c), then the encoding for a would be
[O], b would be [I,O], and c would be [I,I]. (In practice, the current implementation tries to
produce a more-or-less balanced nesting of :+: and :*: so that the traversal of the structure
of the datatype from the root to a particular component can be performed in logarithmic
rather than linear time.)
Typically this GSerialize class will not be exported, as it only makes sense to have instances
for the representation types.
The data family URec is provided to enable generic programming over datatypes with certain
unlifted arguments. There are six instances corresponding to common unlifted types:
A user could provide, for example, a GSerialize UInt instance so that a Serialize IntHash
instance could be easily defined in terms of GSerialize.
Generic defaults
The only thing left to do now is to define a “front-end” class, which is exposed to the user:
Here we use a default signature (page ??) to specify that the user does not have to provide
an implementation for put, as long as there is a Generic instance for the type to instantiate.
For the UserTree type, for instance, the user can just write:
The default method for put is then used, corresponding to the generic implementation of
serialization. If you are using DeriveAnyClass (page 384), the same instance is generated
by simply attaching a deriving Serialize clause to the UserTree datatype declaration. For
more examples of generic functions please refer to the generic-deriving package on Hackage.
More information
For more details please refer to the Haskell Wiki page or the original paper [Generics2010]
(page 637).
6.19.4 Assertions
If you want to make use of assertions in your standard Haskell code, you could define a
function like the following:
which works, but gives you back a less than useful error message – an assertion failed, but
which and where?
One way out is to define an extended assert function which also takes a descriptive string to
include in the error message and perhaps combine this with the use of a pre-processor which
inserts the source location where assert was used.
GHC offers a helping hand here, doing all of this for you. For every use of assert in the user’s
source:
GHC will rewrite this to also include the source location where the assertion was made,
The rewrite is only performed by the compiler when it spots applications of Con-
[Link], so you can still define and use your own versions of assert, should
you so wish. If not, import [Link] to make use assert in your code.
GHC ignores assertions when optimisation is turned on with the -O (page 105) flag. That is,
expressions of the form assert pred e will be rewritten to e. You can also disable assertions
using the -fignore-asserts (page 109) option. The option -fno-ignore-asserts (page 109)
allows enabling assertions even when optimisation is turned on.
Assertion failures can be caught, see the documentation for the [Link] library for
the details.
6.19.5 HasCallStack
A function can request its call-site with the HasCallStack constraint and access it as a Haskell
value by using callStack.
One can then use functions from [Link] to inspect or pretty print (as is done in f below)
the call stack.
f :: HasCallStack => IO () f = putStrLn (prettyCallStack callStack)
g :: HasCallStack => IO () g = f
Evaluating f directly shows a call stack with a single entry, while evaluating g, which also
requests its call-site, shows two entries, one for each computation “annotated” with HasCall-
Stack.
ghci> f
CallStack (from HasCallStack):
f, called at <interactive>:19:1 in interactive:Ghci1
ghci> g
CallStack (from HasCallStack):
f, called at <interactive>:17:5 in main:Main
g, called at <interactive>:20:1 in interactive:Ghci2
The error function from the Prelude supports printing the call stack that led to the error in
addition to the usual error message:
The call stack here consists of a single entry, pinpointing the source of the call to error.
However, by annotating several computations with HasCallStack, figuring out the exact cir-
cumstances and sequences of calls that lead to a call to error becomes a lot easier, as demon-
strated with the simple example below.
f :: HasCallStack => IO ()
f = error "bad bad bad"
g :: HasCallStack => IO ()
g = f
h :: HasCallStack => IO ()
h = g
ghci> h
*** Exception: bad bad bad
CallStack (from HasCallStack):
error, called at [Link]:5 in main:Main
f, called at [Link]:5 in main:Main
g, called at [Link]:5 in main:Main
h, called at <interactive>:28:1 in interactive:Ghci1
The CallStack will only extend as far as the types allow it, for example
bad :: Int
bad = myHead []
ghci> bad
*** Exception: empty
CallStack (from HasCallStack):
errorWithCallStack, called at [Link]:15 in main:Bad
myHead, called at [Link]:7 in main:Bad
includes the call-site of errorWithCallStack in myHead, and of myHead in bad, but not the
call-site of bad at the GHCi prompt.
GHC solves HasCallStack constraints in two steps:
1. If there is a CallStack in scope – i.e. the enclosing definition has a HasCallStack con-
straint – GHC will push the new call-site onto the existing CallStack.
2. Otherwise GHC will solve the HasCallStack constraint for the singleton CallStack con-
taining just the current call-site.
Importantly, GHC will never infer a HasCallStack constraint, you must request it explicitly.
CallStack is kept abstract, but GHC provides a function
to access the individual call-sites in the stack. The String is the name of the function that
was called, and the SrcLoc provides the package, module, and file name, as well as the line
and column numbers.
[Link] additionally exports a function withFrozenCallStack that allows users to freeze
the current CallStack, preventing any future push operations from having an effect. This can
be used by library authors to prevent CallStacks from exposing unnecessary implementation
details. Consider the myHead example above, the errorWithCallStack line in the printed
stack is not particularly enlightening, so we might choose to suppress it by freezing the Call-
Stack that we pass to errorWithCallStack.
ghci> myHead []
*** Exception: empty
CallStack (from HasCallStack):
myHead, called at [Link]:7 in main:Bad
NOTE: The intrepid user may notice that HasCallStack is just an alias for an implicit pa-
rameter ?callStack :: CallStack. This is an implementation detail and should not be
considered part of the CallStack API, we may decide to change the implementation in the
future.
HasCallStack does not interact with the RTS and does not require compilation with -prof.
On the other hand, as the CallStack is built up explicitly via the HasCallStack constraints,
it will generally not contain as much information as the simulated call-stacks maintained by
the RTS.
6.20 Pragmas
GHC supports several pragmas, or instructions to the compiler placed in the source code.
Pragmas don’t normally affect the meaning of the program, but they might affect the efficiency
of the generated code.
Pragmas all take the form {-# word ... #-} where ⟨word⟩ indicates the type of pragma, and
is followed optionally by information specific to that type of pragma. Case is ignored in ⟨word⟩.
The various values for ⟨word⟩ that GHC understands are described in the following sections;
any pragma encountered with an unrecognised ⟨word⟩ is ignored. The layout rule applies in
pragmas, so the closing #-} should start in a column to the right of the opening {-#.
Certain pragmas are file-header pragmas:
• A file-header pragma must precede the module keyword in the file.
• There can be as many file-header pragmas as you please, and they can be preceded or
followed by comments.
• File-header pragmas are read once only, before pre-processing the file (e.g. with cpp).
• The file-header pragmas are: {-# LANGUAGE #-}, {-# OPTIONS_GHC #-}, and {-# IN-
CLUDE #-}.
The OPTIONS_GHC pragma is used to specify additional options that are given to the compiler
when compiling this source file. See Command line options in source files (page 74) for details.
Previous versions of GHC accepted OPTIONS rather than OPTIONS_GHC, but that is now depre-
cated.
OPTIONS_GHC is a file-header pragma (see Pragmas (page 518)).
The INCLUDE used to be necessary for specifying header files to be included when using the
FFI and compiling via C. It is no longer required for GHC, but is accepted (and ignored) for
compatibility with other compilers.
Or:
When you compile any module that import Wibble, GHC will print the specified message.
• You can attach a warning to a function, class, type, or data constructor, with the following
top-level declarations:
When you compile any module that imports and uses any of the specified entities, GHC
will print the specified message.
You can only attach to entities declared at top level in the module being compiled, and
you can only use unqualified names in the list of entities. A capitalised name, such as T
refers to either the type constructor T or the data constructor T, or both if both are in
scope. If both are in scope, there is currently no way to specify one without the other
(c.f. fixities Infix type constructors, classes, and type variables (page 284)).
Also note that the argument to DEPRECATED and WARNING can also be a list of strings, in which
case the strings will be presented on separate lines in the resulting warning message,
{-# DEPRECATED foo, bar ["Don't use these", "Use gar instead"] #-}
Warnings and deprecations are not reported for (a) uses within the defining module, (b) defin-
ing a method in a class instance, and (c) uses in an export list. The latter reduces spurious
complaints within a library in which one module gathers together and re-exports the exports
of several others.
You can suppress the warnings with the flag -Wno-warnings-deprecations (page 90).
class Eq a where
(==) :: a -> a -> Bool
(/=) :: a -> a -> Bool
x == y = not (x /= y)
x /= y = not (x == y)
{-# MINIMAL (==) | (/=) #-}
Without the MINIMAL pragma no warning would be generated for an instance that implements
neither method.
The syntax for minimal complete definition is:
A vertical bar denotes disjunction, i.e. one of the two sides is required. A comma denotes
conjunction, i.e. both sides are required. Conjunction binds stronger than disjunction.
If no MINIMAL pragma is given in the class declaration, it is just as if a pragma {-# MINIMAL
op1,op2,...,opn #-} was given, where the opi are the methods that lack a default method
in the class declaration (c.f. -Wmissing-methods (page 96), Warnings and sanity-checking
(page 85)).
This warning can be turned off with the flag -Wno-missing-methods (page 96).
INLINE pragma
The major effect of an INLINE pragma is to declare a function’s “cost” to be very low. The
normal unfolding machinery will then be very keen to inline it. However, an INLINE pragma
for a function “f” has a number of other effects:
• While GHC is keen to inline the function, it does not do so blindly. For example, if you
write
map key_function xs
In general, GHC only inlines the function if there is some reason (no matter how slight)
to suppose that it is useful to do so.
• Moreover, GHC will only inline the function if it is fully applied, where “fully applied”
means applied to as many arguments as appear (syntactically) on the LHS of the function
definition. For example:
The two functions comp1 and comp2 have the same semantics, but comp1 will be inlined
when applied to two arguments, while comp2 requires three. This might make a big
difference if you say
See also the NOINLINE (NOINLINE pragma (page 523)) and INLINABLE (INLINABLE pragma
(page 522)) pragmas.
INLINABLE pragma
so that GHC guarantees to expose an unfolding regardless of how big it is. Moreover,
by annotating f as INLINABLE, you ensure that f‘s original RHS is inlined, rather than
whatever random optimised version of f GHC’s optimiser has produced.
• The INLINABLE pragma also works with SPECIALISE: if you mark function f as INLINABLE,
then you can subsequently SPECIALISE in another module (see SPECIALIZE pragma
(page 525)).
• Unlike INLINE, it is OK to use an INLINABLE pragma on a recursive function. The princi-
pal reason do to so to allow later use of SPECIALISE
The alternative spelling INLINEABLE is also accepted by GHC.
NOINLINE pragma
CONLIKE modifier
Phase control
Sometimes you want to control exactly when in GHC’s pipeline the INLINE (page 521) pragma
is switched on. Inlining happens only during runs of the simplifier. Each run of the simpli-
fier has a different phase number; the phase number decreases towards zero. If you use
-dverbose-core2core (page 229) you will see the sequence of phase numbers for successive
runs of the simplifier. In an INLINE (page 521) pragma you can optionally specify a phase
number, thus:
• “INLINE[k] f” means: do not inline f until phase k, but from phase k onwards be very
keen to inline it.
• “INLINE[~k] f” means: be very keen to inline f until phase k, but from phase k onwards
do not inline it.
• “NOINLINE[k] f” means: do not inline f until phase k, but from phase k onwards be
willing to inline it (as if there was no pragma).
• “NOINLINE[~k] f” means: be willing to inline f until phase k, but from phase k onwards
do not inline it.
The same information is summarised here:
By “Maybe” we mean that the usual heuristic inlining rules apply (if the function body is
small, or it is applied to interesting-looking arguments etc). Another way to understand the
semantics is this:
• For both INLINE (page 521) and NOINLINE (page 523), the phase number says when
inlining is allowed at all.
• The INLINE (page 521) pragma has the additional effect of making the function body look
small, so that when inlining is allowed it is very likely to happen.
The same phase-numbering control is available for RULE (page 504)s (Rewrite rules
(page 504)).
if you’d generated the current file from something called [Link] and this line corresponds
to line 42 in the original. GHC will adjust its error messages to refer to the line/file named in
the LINE pragma.
LINE pragmas generated from Template Haskell set the file and line position for the duration
of the splice and are limited to the splice. Note that because Template Haskell splices abstract
syntax, the file positions are not automatically advanced.
This is the analogue of the LINE pragma and is likewise intended for use in automatically gen-
erated Haskell code. It lets you specify the column number of the original code; for example
foo = do
{-# COLUMN 42 #-}pure ()
pure ()
This adjusts all column numbers immediately after the pragma to start at 42. The presence
of this pragma only affects the quality of the diagnostics and does not change the syntax of
the code itself.
The RULES (page 504) pragma lets you specify rewrite rules. It is described in Rewrite rules
(page 504).
If it is heavily used on lists with Widget keys, you could specialise it as follows:
{-# SPECIALIZE hammeredLookup :: [(Widget, value)] -> Widget -> value #-}
• A SPECIALIZE pragma for a function can be put anywhere its type signature could be
put. Moreover, you can also SPECIALIZE an imported function provided it was given an
INLINABLE pragma at its definition site (INLINABLE pragma (page 522)).
• A SPECIALIZE has the effect of generating (a) a specialised version of the function and
(b) a rewrite rule (see Rewrite rules (page 504)) that rewrites a call to the un-specialised
function into a call to the specialised one. Moreover, given a SPECIALIZE pragma for a
function f, GHC will automatically create specialisations for any type-class-overloaded
functions called by f, if they are in the same module as the SPECIALIZE pragma, or if
they are INLINABLE; and so on, transitively.
• You can add phase control (Phase control (page 523)) to the RULE generated by a SPE-
CIALIZE pragma, just as you can if you write a RULE directly. For example:
{-# SPECIALIZE [0] hammeredLookup :: [(Widget, value)] -> Widget -> value #-}
generates a specialisation rule that only fires in Phase 0 (the final phase). If you do not
specify any phase control in the SPECIALIZE pragma, the phase control is inherited from
the inline pragma (if any) of the function. For example:
foo :: Num a => a -> a
foo = ...blah...
{-# NOINLINE [0] foo #-}
{-# SPECIALIZE foo :: Int -> Int #-}
The NOINLINE pragma tells GHC not to inline foo until Phase 0; and this property is
inherited by the specialisation RULE, which will therefore only fire in Phase 0.
The main reason for using phase control on specialisations is so that you can write opti-
misation RULES that fire early in the compilation pipeline, and only then specialise the
calls to the function. If specialisation is done too early, the optimisation rules might fail
to fire.
• The type in a SPECIALIZE pragma can be any type that is less polymorphic than the type
of the original function. In concrete terms, if the original function is f then the pragma
f_spec :: <type>
f_spec = f
is valid. Here are some examples (where we only give the type signature for the original
function, not its code):
The last of these examples will generate a RULE with a somewhat-complex left-hand side
(try it yourself), so it might not fire very well. If you use this kind of specialisation, let us
know how well it works.
SPECIALIZE INLINE
Here, (!:) is a recursive function that indexes arrays of type Arr e. Consider a call to (!:)
at type (Int,Int). The second specialisation will fire, and the specialised function will be
inlined. It has two calls to (!:), both at type Int. Both these calls fire the first specialisation,
whose body is also inlined. The result is a type-based unrolling of the indexing function.
You can add explicit phase control (Phase control (page 523)) to SPECIALISE INLINE pragma,
just like on an INLINE (page 521) pragma; if you do so, the same phase is used for the rewrite
rule and the INLINE control of the specialised function.
Warning: You can make GHC diverge by using SPECIALISE INLINE on an ordinarily-
recursive function.
Generally, you can only give a SPECIALIZE (page 525) pragma for a function defined in the
same module. However if a function f is given an INLINABLE (page 522) pragma at its def-
inition site, then it can subsequently be specialised by importing modules (see INLINABLE
pragma (page 522)). For example
Here, lookup is declared INLINABLE (page 522), but it cannot be specialised for type T at its
definition site, because that type does not exist yet. Instead a client module can define T and
then specialise lookup at that type.
Moreover, every module that imports Client (or imports a module that imports Client, tran-
sitively) will “see”, and make use of, the specialised version of lookup. You don’t need to put
a SPECIALIZE (page 525) pragma in every module.
Moreover you often don’t even need the SPECIALIZE (page 525) pragma in the first place.
When compiling a module M, GHC’s optimiser (when given the -O (page 105) flag) automat-
ically considers each top-level overloaded function declared in M, and specialises it for the
different types at which it is called in M. The optimiser also considers each imported INLIN-
ABLE (page 522) overloaded function, and specialises it for the different types at which it is
called in M. So in our example, it would be enough for lookup to be called at type T:
However, sometimes there are no such calls, in which case the pragma can be useful.
The pragma must occur inside the where part of the instance declaration.
will create a constructor T containing two unboxed floats. This may not always be an opti-
misation: if the T constructor is scrutinised and the floats passed to a non-strict function for
example, they will have to be reboxed (this is done automatically by the compiler).
Unpacking constructor fields should only be used in conjunction with -O (page 105) 1 , in order
to expose unfoldings to the compiler so the reboxing can be removed as often as possible. For
example:
f :: T -> Float
f (T f1 f2) = f1 + f2
The compiler will avoid reboxing f1 and f2 by inlining + on floats, but only when -O (page 105)
is on.
Any single-constructor data is eligible for unpacking; for example
will store the two Ints directly in the T constructor, by flattening the pair. Multi-level unpack-
ing is also supported:
will store two unboxed Int#s directly in the T constructor. The unpacker can see through
newtypes, too.
See also the -funbox-strict-fields (page 116) flag, which essentially has the effect of
adding {-# UNPACK #-} to every strict constructor field.
Where top-level
Instructs the compiler not to unpack a constructor field.
The NOUNPACK pragma indicates to the compiler that it should not unpack the contents of a
constructor field. Example:
data T = T {-# NOUNPACK #-} !(Int,Int)
Even with the flags -funbox-strict-fields (page 116) and -O (page 105), the field of the
constructor T is not unpacked.
COMPLETE pragmas are only used by the pattern match checker. If a function definition
matches on all the constructors specified in the pragma then the compiler will produce no
warning.
COMPLETE pragmas can contain any data constructors or pattern synonyms which are in scope,
but must mention at least one data constructor or pattern synonym defined in the same mod-
ule. COMPLETE pragmas may only appear at the top level of a module. Once defined, they are
automatically imported and exported from modules. COMPLETE pragmas should be thought of
as asserting a universal truth about a set of patterns and as a result, should not be used to
silence context specific incomplete match warnings.
When specifying a COMPLETE pragma, the result types of all patterns must be consistent with
each other. This is a sanity check as it would be impossible to match on all the patterns if the
types were inconsistent.
The result type must also be unambiguous. Usually this can be inferred but when all the
pattern synonyms in a group are polymorphic in the constructor the user must provide a type
signature.
class LL f where
go :: f a -> ()
instance LL [] where
go _ = ()
pattern T :: LL f => f a
pattern T <- (go -> ())
-- No warning
foo :: [a] -> Int
foo T = 5
SEVEN
GHC exposes its internal APIs to users through the built-in ghc package. It allows you to
write programs that leverage GHC’s entire compilation driver, in order to analyze or compile
Haskell code programmatically. Furthermore, GHC gives users the ability to load compiler
plugins during compilation - modules which are allowed to view and change GHC’s internal
intermediate representation, Core. Plugins are suitable for things like experimental optimiza-
tions or analysis, and offer a lower barrier of entry to compiler development for many common
cases.
Furthermore, GHC offers a lightweight annotation mechanism that you can use to annotate
your source code with metadata, which you can later inspect with either the compiler API or
a compiler plugin.
Annotations are small pragmas that allow you to attach data to identifiers in source code,
which are persisted when compiled. These pieces of data can then inspected and utilized
when using GHC as a library or writing a compiler plugin.
Any expression that has both Typeable and Data instances may be attached to a top-level
value binding using an ANN pragma. In particular, this means you can use ANN to annotate
data constructors (e.g. Just) as well as normal values (e.g. take). By way of example, to
annotate the function foo with the annotation Just "Hello" you would do this:
531
GHC User’s Guide Documentation, Release 9.0.2
To be precise, the annotation {-# ANN x e #-} is well staged if and only if $(e) would
be (disregarding the usual type restrictions of the splice syntax, and the usual restriction
on splicing inside a splice - $([|1|]) is fine as an annotation, albeit redundant).
If you feel strongly that any of these restrictions are too onerous, please give the GHC team
a shout.
However, apart from these restrictions, many things are allowed, including expressions which
are not fully evaluated! Annotation expressions will be evaluated by the compiler just like
Template Haskell splices are. So, this annotation is fine:
{-# ANN f SillyAnnotation { foo = (id 10) + $([| 20 |]), bar = 'f } #-}
f = ...
You can annotate types with the ANN pragma by using the type keyword. For example:
{-# ANN type Foo (Just "A `Maybe String' annotation") #-}
data Foo = ...
You can annotate modules with the ANN pragma by using the module keyword. For example:
The ghc package exposes most of GHC’s frontend to users, and thus allows you to write
programs that leverage it. This library is actually the same library used by GHC’s internal,
frontend compilation driver, and thus allows you to write tools that programmatically compile
source code and inspect it. Such functionality is useful in order to write things like IDE or
refactoring tools. As a simple example, here’s a program which compiles a module, much like
ghc itself does by default when invoked:
import GHC
import [Link] ( libdir )
import [Link] ( defaultFatalMessager, defaultFlushOut )
main =
defaultErrorHandler defaultFatalMessager defaultFlushOut $ do
runGhc (Just libdir) $ do
dflags <- getSessionDynFlags
setSessionDynFlags dflags
target <- guessTarget "test_main.hs" Nothing
setTargets [target]
load LoadAllTargets
The argument to runGhc is a bit tricky. GHC needs this to find its libraries, so the argument
must refer to the directory that is printed by ghc --print-libdir for the same version of
GHC that the program is being compiled with. Above we therefore use the ghc-paths package
which provides this for us.
Compiling it results in:
$ cat test_main.hs
main = putStrLn "hi"
$ ghc -package ghc simple_ghc_api.hs
[1 of 1] Compiling Main ( simple_ghc_api.hs, simple_ghc_api.o )
Linking simple_ghc_api ...
$ ./simple_ghc_api
$ ./test_main
hi
$
For more information on using the API, as well as more samples and references, please see
this [Link] wiki page.
GHC has the ability to load compiler plugins at compile time. The feature is similar to the
one provided by GCC, and allows users to write plugins that can adjust the behaviour of
the constraint solver, inspect and modify the compilation pipeline, as well as transform and
inspect GHC’s intermediate language, Core. Plugins are suitable for experimental analysis
or optimization, and require no changes to GHC’s source code to use.
Plugins cannot optimize/inspect C-\-, nor can they implement things like parser/front-end mod-
ifications like GCC, apart from limited changes to the constraint solver. If you feel strongly
that any of these restrictions are too onerous, please give the GHC team a shout.
Plugins do not work with -fexternal-interpreter. If you need to run plugins with -
fexternal-interpreter let GHC developers know in #14335.
Plugins can be added on the command line with the -fplugin=⟨module⟩ (page 533) option
where ⟨module⟩ is a module in a registered package that exports the plugin. Arguments can
be passed to the plugins with the -fplugin-opt=⟨module⟩:⟨args⟩ (page 533) option. The
list of enabled plugins can be reset with the -fclear-plugins (page 533) option.
-fplugin=⟨module⟩
Load the plugin in the given module. The module must be a member of a package regis-
tered in GHC’s package database.
-fplugin-opt=⟨module⟩:⟨args⟩
Give arguments to a plugin module; module must be specified with -fplugin=⟨module⟩
(page 533).
-fplugin-trustworthy
By default, when a module is compiled with plugins, it will be marked as unsafe. With
this flag passed, all plugins are treated as trustworthy and the safety inference will no
longer be affected.
-fclear-plugins
Clear the list of plugins previously specified with -fplugin (page 533). This is useful in
GHCi where simply removing the -fplugin (page 533) options from the command line
is not possible. Instead :set -fclear-plugins can be used.
As an example, in order to load the plugin exported by [Link] in the package foo-ghc-
plugin, and give it the parameter “baz”, we would invoke GHC like this:
addCorePlugin "[Link]"
Plugins are modules that export at least a single identifier, plugin, of type
[Link]. All plugins should import [Link] as it defines the interface to
the compilation pipeline.
A Plugin effectively holds a function which installs a compilation pass into the
compiler pipeline. By default there is the empty plugin which does nothing,
[Link], which you should override with record syntax to specify your
installation function. Since the exact fields of the Plugin type are open to change, this is the
best way to ensure your plugins will continue to work in the future with minimal interface
impact.
Plugin exports a field, installCoreToDos which is a function of type [CommandLineOption]
-> [CoreToDo] -> CoreM [CoreToDo]. A CommandLineOption is effectively just String, and
a CoreToDo is basically a function of type Core -> Core. A CoreToDo gives your pass a name
and runs it over every compiled module when you invoke GHC.
As a quick example, here is a simple plugin that just does nothing and just returns the original
compilation pipeline, unmodified, and says ‘Hello’:
plugin :: Plugin
plugin = defaultPlugin {
installCoreToDos = install
}
Provided you compiled this plugin and registered it in a package (with cabal for instance,)
you can then use it by just specifying -fplugin=[Link] on the command line,
and during the compilation you should see GHC say ‘Hello’.
Running multiple plugins is also supported, by passing multiple -fplugin=... options. GHC
will load the plugins in the order in which they are specified on the command line and, when
appropriate, compose their effects in the same order. That is, if we had two Core plugins,
Plugin1 and Plugin2, each defining an install function like the one above, then GHC would
first run [Link] on the default [CoreToDo], take the result and feed it to Plu-
[Link]. -fplugin=Plugin1 -fplugin=Plugin2 will update the Core pipeline by ap-
plying [Link] opts1 >=> [Link] opts2 (where opts1 and opts2 are
the options passed to each plugin using -fplugin-opt=...). This is not specific to Core plu-
gins but holds for all the types of plugins that can be composed or sequenced in some way:
the first plugin to appear on the GHC command line will always act first.
CoreToDo is effectively a data type that describes all the kinds of optimization passes GHC
does on Core. There are passes for simplification, CSE, etc. There is a specific case for
plugins, CoreDoPluginPass :: String -> PluginPass -> CoreToDo which should be what
you always use when inserting your own pass into the pipeline. The first parameter is the
name of the plugin, and the second is the pass you wish to insert.
CoreM is a monad that all of the Core optimizations live and operate inside of.
A plugin’s installation function (install in the above example) takes a list of CoreToDos and
returns a list of CoreToDo. Before GHC begins compiling modules, it enumerates all the
needed plugins you tell it to load, and runs all of their installation functions, initially on a list
of passes that GHC specifies itself. After doing this for every plugin, the final list of passes is
given to the optimizer, and are run by simply going over the list in order.
You should be careful with your installation function, because the list of passes you give back
isn’t questioned or double checked by GHC at the time of this writing. An installation function
like the following:
is certainly valid, but also certainly not what anyone really wants.
Manipulating bindings
In the last section we saw that besides a name, a CoreDoPluginPass takes a pass of type
PluginPass. A PluginPass is a synonym for (ModGuts -> CoreM ModGuts). ModGuts is a
type that represents the one module being compiled by GHC at any given time.
A ModGuts holds all of the module’s top level bindings which we can examine. These bindings
are of type CoreBind and effectively represent the binding of a name to body of code. Top-
level module bindings are part of a ModGuts in the field mg_binds. Implementing a pass
that manipulates the top level bindings merely needs to iterate over this field, and return a
new ModGuts with an updated mg_binds field. Because this is such a common case, there
is a function provided named bindsOnlyPass which lifts a function of type ([CoreBind] ->
CoreM [CoreBind]) to type (ModGuts -> CoreM ModGuts).
Continuing with our example from the last section, we can write a simple plugin that just
prints out the name of all the non-recursive bindings in a module it compiles:
plugin :: Plugin
plugin = defaultPlugin {
installCoreToDos = install
}
Using Annotations
Previously we discussed annotation pragmas (Source annotations (page 531)), which we men-
tioned could be used to give compiler plugins extra guidance or information. Annotations for
a module can be retrieved by a plugin, but you must go through the modules ModGuts in order
to get it. Because annotations can be arbitrary instances of Data and Typeable, you need to
give a type annotation specifying the proper type of data to retrieve from the interface file,
and you need to make sure the annotation type used by your users is the same one your plugin
uses. For this reason, we advise distributing annotations as part of the package which also
provides compiler plugins if possible.
To get the annotations of a single binder, you can use getAnnotations and specify the proper
type. Here’s an example that will print out the name of any top-level non-recursive binding
with the SomeAnn annotation:
plugin :: Plugin
plugin = defaultPlugin {
installCoreToDos = install
}
return bndr
printAnn _ _ bndr = return bndr
Please see the GHC API documentation for more about how to use internal APIs, etc.
In addition to Core plugins, GHC has experimental support for typechecker plugins, which al-
low the behaviour of the constraint solver to be modified. For example, they make it possible
to interface the compiler to an SMT solver, in order to support a richer theory of type-level
arithmetic expressions than the theory built into GHC (see Computing With Type-Level Natu-
rals (page 337)).
The Plugin type has a field tcPlugin of type [CommandLineOption] -> Maybe TcPlugin,
where the TcPlugin type is defined thus:
type TcPluginSolver = [Ct] -> [Ct] -> [Ct] -> TcPluginM TcPluginResult
(The details of this representation are subject to change as we gain more experience writing
typechecker plugins. It should not be assumed to be stable between GHC releases.)
The basic idea is as follows:
• When type checking a module, GHC calls tcPluginInit once before constraint solving
starts. This allows the plugin to look things up in the context, initialise mutable state or
open a connection to an external process (e.g. an external SMT solver). The plugin can
return a result of any type it likes, and the result will be passed to the other two fields.
• During constraint solving, GHC repeatedly calls tcPluginSolve. This function is pro-
vided with the current set of constraints, and should return a TcPluginResult that in-
dicates whether a contradiction was found or progress was made. If the plugin solver
makes progress, GHC will re-start the constraint solving pipeline, looping until a fixed
point is reached.
• Finally, GHC calls tcPluginStop after constraint solving is finished, allowing the plugin
to dispose of any resources it has allocated (e.g. terminating the SMT solver process).
Plugin code runs in the TcPluginM monad, which provides a restricted interface to GHC
API functionality that is relevant for typechecker plugins, including IO and reading the en-
vironment. If you need functionality that is not exposed in the TcPluginM module, you can
use unsafeTcPluginTcM :: TcM a -> TcPluginM a, but are encouraged to contact the GHC
team to suggest additions to the interface. Note that TcPluginM can perform arbitrary IO via
tcPluginIO :: IO a -> TcPluginM a, although some care must be taken with side effects
(particularly in tcPluginSolve). In general, it is up to the plugin author to make sure that
any IO they do is safe.
The key component of a typechecker plugin is a function of type TcPluginSolver, like this:
This function will be invoked at two points in the constraint solving process: after simplifica-
tion of given constraints, and after unflattening of wanted constraints. The two phases can
be distinguished because the deriveds and wanteds will be empty in the first case. In each
case, the plugin should either
• return TcPluginContradiction with a list of impossible constraints (which must be a
subset of those passed in), so they can be turned into errors; or
• return TcPluginOk with lists of solved and new constraints (the former must be a subset
of those passed in and must be supplied with corresponding evidence terms).
If the plugin cannot make any progress, it should return TcPluginOk [] []. Otherwise, if
there were any new constraints, the main constraint solver will be re-invoked to simplify
them, then the plugin will be invoked again. The plugin is responsible for making sure that
this process eventually terminates.
Plugins are provided with all available constraints (including equalities and typeclass con-
straints), but it is easy for them to discard those that are not relevant to their domain, because
they need return only those constraints for which they have made progress (either by solving
or contradicting them).
Constraints that have been solved by the plugin must be provided with evidence in the form
of an EvTerm of the type of the constraint. This evidence is ignored for given and derived
constraints, which GHC “solves” simply by discarding them; typically this is used when they
are uninformative (e.g. reflexive equations). For wanted constraints, the evidence will form
part of the Core term that is generated after typechecking, and can be checked by -dcore-
lint. It is possible for the plugin to create equality axioms for use in evidence terms, but
GHC does not check their consistency, and inconsistent axiom sets may lead to segfaults or
other runtime misbehaviour.
In addition to core and type checker plugins, you can install plugins that can access different
representations of the source code. The main purpose of these plugins is to make it easier to
implement development tools.
There are several different access points that you can use for defining plugins that access
the representations. All these fields receive the list of CommandLineOption strings that are
passed to the compiler using the -fplugin-opt=⟨module⟩:⟨args⟩ (page 533) flags.
plugin :: Plugin
plugin = defaultPlugin {
parsedResultAction = parsed
, typeCheckResultAction = typechecked
, spliceRunAction = spliceRun
, interfaceLoadAction = interfaceLoad
, renamedResultAction = renamed
}
Parsed representation
When you want to define a plugin that uses the syntax tree of the source code, you would
like to override the parsedResultAction field. This access point enables you to get access to
information about the lexical tokens and comments in the source code as well as the original
syntax tree of the compiled module.
The ModSummary contains useful meta-information about the compiled module. The HsParsed-
Module contains the lexical and syntactical information we mentioned before. The result that
you return will change the result of the parsing. If you don’t want to change the result, just
return the HsParsedModule that you received as the argument.
When you want to define a plugin that needs semantic information about the source code, use
the typeCheckResultAction field. For example, if your plugin have to decide if two names are
referencing the same definition or it has to check the type of a function it is using semantic
information. In this case you need to access the renamed or type checked version of the
syntax tree with typeCheckResultAction or renamedResultAction.
By overriding the renamedResultAction field we can modify each HsGroup after it has been
renamed. A source file is separated into groups depending on the location of template haskell
splices so the contents of these groups may not be intuitive. In order to save the entire
renamed AST for inspection at the end of typechecking you can set renamedResultAction
to keepRenamedSource which is provided by the Plugins module. This is important because
some parts of the renamed syntax tree (for example, imports) are not found in the typechecked
one.
Evaluated code
When the compiler type checks the source code, Template Haskell (page 450) Splices and
Template Haskell Quasi-quotation (page 459) will be replaced by the syntax tree fragments
generated from them. However for tools that operate on the source code the code generator
is usually more interesting than the generated code. For this reason we included spliceRun-
Action. This field is invoked on each expression before they are evaluated. The input is type
checked, so semantic information is available for these syntax tree fragments. If you return
a different expression you can change the code that is generated.
However take care that the generated definitions are still in the input of typeCheckResultAc-
tion. If your don’t take care to filter the typechecked input, the behavior of your tool might
be inconsistent.
Interface files
Sometimes when you are writing a tool, knowing the source code is not enough, you also
have to know details about the modules that you import. In this case we suggest using the
interfaceLoadAction. This will be called each time when the code of an already compiled
module is loaded. It will be invoked for modules from installed packages and even modules
that are installed with GHC. It will NOT be invoked with your own modules.
In the ModIface datatype you can find lots of useful information, including the exported defi-
nitions and type class instances.
The ModIface datatype also contains facilities for extending it with extra data, stored in a
Map of serialised fields, indexed by field names and using GHC’s internal Binary class. The
interface to work with these fields is:
The FieldName is open-ended, but typically it should contain the producing package name,
along with the actual field name. Then, the version number can either be attached to the
serialised data for that field, or in cases where multiple versions of a field could exist in the
same interface file, included in the field name.
Depending on if the field version advances with the package version, or independently, the
version can be attached to either the package name or the field name. Examples of each case:
package/field
ghc-n.n.n/core
package/field-n
To read an interface file from an external tool without linking to GHC, the format is described
at Extensible Interface Files.
In this example, we inspect all available details of the compiled source code. We don’t change
any of the representation, but write out the details to the standard output. The pretty printed
representation of the parsed, renamed and type checked syntax tree will be in the output as
well as the evaluated splices and quasi quotes. The name of the interfaces that are loaded
will also be displayed.
module SourcePlugin where
import [Link]
import [Link] (getDynFlags)
import [Link]
import [Link]
import [Link]
import [Link]
import [Link]
import [Link]
import [Link]
import [Link]
import [Link]
import [Link]
plugin :: Plugin
plugin = defaultPlugin
{ parsedResultAction = parsedPlugin
, renamedResultAction = renamedAction
, typeCheckResultAction = typecheckPlugin
, spliceRunAction = metaPlugin
, interfaceLoadAction = interfaceLoadPlugin
}
parsedPlugin _ _ pm
= do dflags <- getDynFlags
liftIO $ putStrLn $ "parsePlugin: \n" ++ (showSDoc dflags $ ppr $ hpm_module␣
,→pm)
return pm
renamedAction :: [CommandLineOption] -> TcGblEnv -> HsGroup GhcRn -> TcM (TcGblEnv,␣
,→HsGroup GhcRn)
renamedAction _ tc gr = do
dflags <- getDynFlags
liftIO $ putStrLn $ "typeCheckPlugin (rn): " ++ (showSDoc dflags $ ppr gr)
return (tc, gr)
return tc
return iface
When you compile a simple module that contains Template Haskell splice
a = ()
$(return [])
with the compiler flags -fplugin SourcePlugin it will give the following output:
parsePlugin:
module A where
a = ()
$(return [])
typeCheckPlugin (rn): a = ()
interface loaded: [Link]
meta: return []
typeCheckPlugin (rn):
typeCheckPlugin (rn):
Nothing
typeCheckPlugin (tc):
{$trModule = Module (TrNameS "main"#) (TrNameS "A"#), a = ()}
Hole-fit plugins are plugins that are called when a typed-hole error message is being gener-
ated, and allows you to access information about the typed-hole at compile time, and allows
you to customize valid hole fit suggestions.
Using hole-fit plugins, you can extend the behavior of valid hole fit suggestions to use e.g.
Hoogle or other external tools to find and/or synthesize valid hole fits, with the same informa-
tion about the typed-hole that GHC uses.
There are two access points are bundled together for defining hole fit plugins, namely a candi-
date plugin and a fit plugin, for modifying the candidates to be checked and fits respectively.
Where TypedHole contains all the information about the hole available to GHC at error gen-
eration.
plugin :: Plugin
plugin = defaultPlugin {
holeFitPlugin = (fmap . fmap) fromPureHFPlugin hfPlugin
}
HoleFitPlugins are wrapped in a HoleFitPluginR, which provides a TcRef for the plugin
to use to track internal state, and to facilitate communication between the candidate and fit
plugin.
The plugin is then defined as by providing a value for the holeFitPlugin field, a function that
takes the CommandLineOption strings that are passed to the compiler using the -fplugin-
opt=⟨module⟩:⟨args⟩ (page 533) flags and returns a HoleFitPluginR. This function can be
used to pass the CommandLineOption strings along to the candidate and fit plugins respec-
tively.
The following plugins allows users to limit the search for valid hole fits to certain modules,
to sort the hole fits by where they originated (in ascending or descending order), as well as
allowing users to put a limit on how much time is spent on searching for valid hole fits, after
which new searches are aborted.
import [Link]
import [Link]
import [Link]
import [Link]
hpStartState :: HolePluginState
hpStartState = HPS Nothing zero undefined
where zero = fromInteger @NominalDiffTime 0
_ -> hfs
where orderByModule :: [HoleFit] -> [HoleFit]
orderByModule = sortOn (fmap fromModule . mbHFCand)
mbHFCand :: HoleFit -> Maybe HoleFitCandidate
mbHFCand HoleFit {hfCand = c} = Just c
mbHFCand _ = Nothing
msg = hang (text "Error: The time ran out, and the search was aborted for␣
,→this hole.")
plugin :: Plugin
plugin = defaultPlugin { holeFitPlugin = holeFitP, pluginRecompile = purePlugin}
main :: IO ()
main = return ()
[Link]:5: error:
• Found hole: _too_long :: [Int] -> Int
Or perhaps ‘_too_long’ is mis-spelled, or not in scope
• In the expression: _too_long
In an equation for ‘f’: f = _too_long
• Relevant bindings include
f :: [Int] -> Int (bound at [Link]:1)
Valid hole fits include
Error: The time ran out, and the search was aborted for this hole.
Try again with a longer timeout.
|
12 | f = _too_long
| ^^^^^^^^^
[Link]:5: error:
• Found hole: _ :: [Int] -> Int
• In the expression: _
In an equation for ‘j’: j = _
• Relevant bindings include
j :: [Int] -> Int (bound at [Link]:1)
Valid hole fits include
j :: [Int] -> Int
f :: [Int] -> Int
g :: [Int] -> Int
h :: [Int] -> Int
i :: [Int] -> Int
head :: forall a. [a] -> a
(Some hole fits suppressed; use -fmax-valid-hole-fits=N or -fno-max-valid-hole-
,→fits)
|
13 | j = _
| ^
[Link]:5: error:
• Found hole: _sort_by_mod_desc :: [Int] -> Int
Or perhaps ‘_sort_by_mod_desc’ is mis-spelled, or not in scope
• In the expression: _sort_by_mod_desc
In an equation for ‘i’: i = _sort_by_mod_desc
• Relevant bindings include
i :: [Int] -> Int (bound at [Link]:1)
Valid hole fits include
sum :: forall (t :: * -> *) a. (Foldable t, Num a) => t a -> a
product :: forall (t :: * -> *) a. (Foldable t, Num a) => t a -> a
minimum :: forall (t :: * -> *) a. (Foldable t, Ord a) => t a -> a
maximum :: forall (t :: * -> *) a. (Foldable t, Ord a) => t a -> a
length :: forall (t :: * -> *) a. Foldable t => t a -> Int
last :: forall a. [a] -> a
(Some hole fits suppressed; use -fmax-valid-hole-fits=N or -fno-max-valid-hole-
,→fits)
|
14 | i = _sort_by_mod_desc
| ^^^^^^^^^^^^^^^^^
[Link]:5: error:
• Found hole: _only_Data_List :: [Int] -> Int
Or perhaps ‘_only_Data_List’ is mis-spelled, or not in scope
• In the expression: _only_Data_List
In an equation for ‘g’: g = _only_Data_List
• Relevant bindings include
g :: [Int] -> Int (bound at [Link]:1)
Valid hole fits include
head :: forall a. [a] -> a
last :: forall a. [a] -> a
|
15 | g = _only_Data_List
| ^^^^^^^^^^^^^^^
[Link]:5: error:
• Found hole: _only_Prelude :: [Int] -> Int
Or perhaps ‘_only_Prelude’ is mis-spelled, or not in scope
• In the expression: _only_Prelude
In an equation for ‘h’: h = _only_Prelude
By default, modules compiled with plugins are always recompiled even if the source file is
unchanged. This most conservative option is taken due to the ability of plugins to perform
arbitrary IO actions. In order to control the recompilation behaviour you can modify the
pluginRecompile field in Plugin.
plugin :: Plugin
plugin = defaultPlugin {
installCoreToDos = install,
pluginRecompile = purePlugin
}
By inspecting the example plugin defined above, we can see that it is pure. This means that if
the two modules have the same fingerprint then the plugin will always return the same result.
Declaring a plugin as pure means that the plugin will never cause a module to be recompiled.
In general, the pluginRecompile field has the following type:
The PluginRecompile data type is an enumeration determining how the plugin should affect
recompilation.
A plugin which declares itself impure using ForceRecompile will always trigger a recompila-
tion of the current module. NoForceRecompile is used for “pure” plugins which don’t need
to be rerun unless a module would ordinarily be recompiled. MaybeRecompile computes a
Fingerprint and if this Fingerprint is different to a previously computed Fingerprint for
the plugin, then we recompile the module.
As such, purePlugin is defined as a function which always returns NoForceRecompile.
Users can use the same functions that GHC uses internally to compute fingerprints. The
[Link] module provides useful functions for constructing fingerprints. For example,
combining together fingerprintFingerprints and fingerprintString provides an easy to
to naively fingerprint the arguments to a plugin.
A frontend plugin allows you to add new major modes to GHC. You may prefer this over a
traditional program which calls the GHC API, as GHC manages a lot of parsing flags and
administrative nonsense which can be difficult to manage manually. To load a frontend plu-
gin exported by [Link], we just invoke GHC with the --frontend ⟨module⟩
(page 76) flag as follows:
Frontend plugins, like compiler plugins, are exported by registered plugins. However, un-
like compiler modules, frontend plugins are modules that export at least a single identifier
frontendPlugin of type [Link].
FrontendPlugin exports a field frontend, which is a function [String] -> [(String,Maybe
Phase)] -> Ghc (). The first argument is a list of extra flags passed to the frontend with
-ffrontend-opt; the second argument is the list of arguments, usually source files and mod-
ule names to be compiled (the Phase indicates if an -x flag was set), and a frontend simply
executes some operation in the Ghc monad (which, among other things, has a Session).
As a quick example, here is a frontend plugin that prints the arguments that were passed to
it, and then exits.
frontendPlugin :: FrontendPlugin
frontendPlugin = defaultFrontendPlugin {
frontend = doNothing
}
Provided you have compiled this plugin and registered it in a package, you can just use it by
specifying --frontend [Link] on the command line to GHC.
A DynFlags plugin allows you to modify the DynFlags that GHC is going to use when pro-
cessing a given (set of) file(s). DynFlags is a record containing all sorts of configuration
and command line data, from verbosity level to the integer library to use, including compiler
hooks, plugins and pretty-printing options. DynFlags plugins allow plugin authors to update
any of those values before GHC starts doing any actual work, effectively meaning that the
updates specified by the plugin will be taken into account and influence GHC’s behaviour.
One of the motivating examples was the ability to register compiler hooks from a plugin.
For example, one might want to modify the way Template Haskell code is executed. This is
achievable by updating the hooks field of the DynFlags type, recording our custom “meta
hook” in the right place. A simple application of this idea can be seen below:
import BasicTypes
import [Link]
import [Link]
import [Link]
import [Link]
import Hooks
import [Link]
plugin :: Plugin
plugin = defaultPlugin { dynflagsPlugin = hooksP }
This simple plugin takes over the execution of Template Haskell code, replacing any expres-
sion splice it encounters by 0 (at type Int), and errors out on any other type of splice.
Therefore, if we run GHC against the following code using the plugin from above:
main :: IO ()
main = print $( [|1|] )
This will not actually evaluate [|1|], but instead replace it with the 0 :: Int literal.
Just like the other types of plugins, you can write DynFlags plugins that can take and make use
of some options that you can then specify using the -fplugin-opt flag. In the DynFlagsPlugin
code from above, the said options would be available in the opts argument of hooksP.
Finally, since those DynFlags updates happen after the plugins are loaded, you cannot from a
DynFlags plugin register other plugins by just adding them to the plugins field of DynFlags.
In order to achieve this, you would have to load them yourself and store the result into the
cachedPlugins field of DynFlags.
EIGHT
PROFILING
GHC comes with a time and space profiling system, so that you can answer questions like
“why is my program so slow?”, or “why is my program using so much memory?”.
Profiling a program is a three-step process:
1. Re-compile your program for profiling with the -prof (page 557) option, and probably
one of the options for adding automatic annotations: -fprof-auto (page 558) is the most
common 1 .
If you are using external packages with cabal, you may need to reinstall these pack-
ages with profiling support; typically this is done with cabal install -p package --
reinstall.
2. Having compiled the program for profiling, you now need to run it to generate the profile.
For example, a simple time profile can be generated by running the program with +RTS
-p (see -p (page 558)), which generates a file named [Link] where ⟨prog⟩ is the name
of your program (without the .exe extension, if you are on Windows).
There are many different kinds of profile that can be generated, selected by different
RTS options. We will be describing the various kinds of profile throughout the rest of this
chapter. Some profiles require further processing using additional tools after running
the program.
3. Examine the generated profiling information, use the information to optimise your pro-
gram, and repeat as necessary.
GHC’s profiling system assigns costs to cost centres. A cost is simply the time or space
(memory) required to evaluate an expression. Cost centres are program annotations around
expressions; all costs incurred by the annotated expression are assigned to the enclosing cost
centre. Furthermore, GHC will remember the stack of enclosing cost centres for any given
expression at run-time and generate a call-tree of cost attributions.
Let’s take a look at an example:
553
GHC User’s Guide Documentation, Release 9.0.2
When a GHC-compiled program is run with the -p (page 558) RTS option, it generates a file
called [Link]. In this case, the file will contain something like this:
Wed Oct 12 16:14 2011 Time and Allocation Profiling Report (Final)
individual inherited
COST CENTRE MODULE no. entries %time %alloc %time %alloc
The first part of the file gives the program name and options, and the total time and total
memory allocation measured during the run of the program (note that the total memory al-
location figure isn’t the same as the amount of live memory needed by the program at any
one time; the latter can be determined using heap profiling, which we will describe later in
Profiling memory usage (page 561)).
The second part of the file is a break-down by cost centre of the most costly functions in the
program. In this case, there was only one significant function in the program, namely fib,
and it was responsible for 100% of both the time and allocation costs of the program.
The third and final section of the file gives a profile break-down by cost-centre stack. This is
roughly a call-tree profile of the program. In the example above, it is clear that the costly call
to fib came from main.
The time and allocation incurred by a given part of the program is displayed in two ways:
“individual”, which are the costs incurred by the code covered by this cost centre stack alone,
and “inherited”, which includes the costs incurred by all the children of this node.
The usefulness of cost-centre stacks is better demonstrated by modifying the example slightly:
main = print (f 30 + g 30)
where
f n = fib n
g n = fib (n `div` 2)
Compile and run this program as before, and take a look at the new profiling results:
Now although we had two calls to fib in the program, it is immediately clear that it was the
call from f which took all the time. The functions f and g which are defined in the where
clause in main are given their own cost centres, main.f and main.g respectively.
The actual meaning of the various columns in the output is:
The number of times this particular point in the call tree was entered.
The percentage of the total run time of the program spent at this point in the call
tree.
The percentage of the total memory allocations (excluding profiling overheads) of
the program made by this call.
The percentage of the total run time of the program spent below this point in the
call tree.
The percentage of the total memory allocations (excluding profiling overheads) of
the program made by this call and all of its sub-calls.
In addition you can use the -P (page 558) RTS option to get the following additional informa-
tion:
ticks The raw number of time “ticks” which were attributed to this cost-centre; from this,
we get the %time figure mentioned above.
bytes Number of bytes allocated in the heap while in this cost-centre; again, this is the raw
number from which we get the %alloc figure mentioned above.
What about recursive functions, and mutually recursive groups of functions? Where are the
costs attributed? Well, although GHC does keep information about which groups of functions
called each other recursively, this information isn’t displayed in the basic time and allocation
profile, instead the call-graph is flattened into a tree as follows: a call to a function that occurs
elsewhere on the current stack does not push another entry on the stack, instead the costs
for this call are aggregated into the caller 2 .
Cost centres are just program annotations. When you say -fprof-auto to the compiler, it
automatically inserts a cost centre annotation around every binding not marked INLINE in
your program, but you are entirely free to add cost centre annotations yourself.
The syntax of a cost centre annotation for expressions is
2 Note that this policy has changed slightly in GHC 7.4.1 relative to earlier versions, and may yet change further,
feedback is welcome.
where "name" is an arbitrary string, that will become the name of your cost centre as it ap-
pears in the profiling output, and <expression> is any Haskell expression. An SCC annotation
extends as far to the right as possible when parsing, having the same precedence as lambda
abstractions, let expressions, and conditionals. Additionally, an annotation may not appear
in a position where it would change the grouping of subexpressions:
a = 1 / 2 / 2 -- accepted (a=0.25)
b = 1 / {-# SCC "name" #-} / 2 / 2 -- rejected (instead of b=1.0)
This restriction is required to maintain the property that inserting a pragma, just like inserting
a comment, does not have unintended effects on the semantics of the program, in accordance
with GHC Proposal #176.
SCC stands for “Set Cost Centre”. The double quotes can be omitted if name is a Haskell
identifier starting with a lowercase letter, for example:
Cost centre annotations can also appear in the top-level or in a declaration context. In that
case you need to pass a function name defined in the same module or scope with the annota-
tion. Example:
f x y = ...
where
g z = ...
{-# SCC g #-}
If you want to give a cost centre different name than the function name, you can pass a string
to the annotation
f x y = ...
{-# SCC f "cost_centre_name" #-}
main :: IO ()
main = do let xs = [1..1000000]
let ys = [1..2000000]
print $ {-# SCC last_xs #-} last xs
print $ {-# SCC last_init_xs #-} last (init xs)
print $ {-# SCC last_ys #-} last ys
print $ {-# SCC last_init_ys #-} last (init ys)
While running a program with profiling turned on, GHC maintains a cost-centre stack behind
the scenes, and attributes any costs (memory allocation and time) to whatever the current
cost-centre stack is at the time the cost is incurred.
The mechanism is simple: whenever the program evaluates an expression with an SCC an-
notation, {-# SCC c -#} E, the cost centre c is pushed on the current stack, and the entry
count for this stack is incremented by one. The stack also sometimes has to be saved and
restored; in particular when the program creates a thunk (a lazy suspension), the current
cost-centre stack is stored in the thunk, and restored when the thunk is evaluated. In this
way, the cost-centre stack is independent of the actual evaluation order used by GHC at run-
time.
At a function call, GHC takes the stack stored in the function being called (which for a top-
level function will be empty), and appends it to the current stack, ignoring any prefix that is
identical to a prefix of the current stack.
We mentioned earlier that lazy computations, i.e. thunks, capture the current stack when they
are created, and restore this stack when they are evaluated. What about top-level thunks?
They are “created” when the program is compiled, so what stack should we give them? The
technical name for a top-level thunk is a CAF (“Constant Applicative Form”). GHC assigns
every CAF in a module a stack consisting of the single cost centre [Link], where M is the name
of the module. It is also possible to give each CAF a different stack, using the option -fprof-
cafs (page 558). This is especially useful when compiling with -ffull-laziness (page 109)
(as is default with -O (page 105) and higher), as constants in function bodies will be lifted to
the top-level and become CAFs. You will probably need to consult the Core (-ddump-simpl
(page 230)) in order to determine what these CAFs correspond to.
-prof
To make use of the profiling system all modules must be compiled and linked with the
-prof (page 557) option. Any SCC annotations you’ve put in your source will spring to
life.
Without a -prof (page 557) option, your SCCs are ignored; so you can compile SCC-laden
code without changing it.
There are a few other profiling-related compilation options. Use them in addition to -prof
(page 557). These do not have to be used consistently for all modules in a program.
-fprof-auto
All bindings not marked INLINE, whether exported or not, top level or nested, will be
given automatic SCC annotations. Functions marked INLINE must be given a cost centre
manually.
-fprof-auto-top
GHC will automatically add SCC annotations for all top-level bindings not marked INLINE.
If you want a cost centre on an INLINE function, you have to add it manually.
-fprof-auto-exported
GHC will automatically add SCC annotations for all exported functions not marked IN-
LINE. If you want a cost centre on an INLINE function, you have to add it manually.
-fprof-auto-calls
Adds an automatic SCC annotation to all call sites. This is particularly useful when
using profiling for the purposes of generating stack traces; see the function De-
[Link], or the -xc (page 172) RTS flag (RTS options for hackers, debug-
gers, and over-interested souls (page 171)) for more details.
-fprof-cafs
The costs of all CAFs in a module are usually attributed to one “big” CAF cost-centre.
With this option, all CAFs get their own cost-centre. An “if all else fails” option…
-fno-prof-auto
Disables any previous -fprof-auto (page 558), -fprof-auto-top (page 557), or -fprof-
auto-exported (page 558) options.
-fno-prof-cafs
Disables any previous -fprof-cafs (page 558) option.
-fno-prof-count-entries
Tells GHC not to collect information about how often functions are entered at runtime
(the “entries” column of the time profile), for this module. This tends to make the profiled
code run faster, and hence closer to the speed of the unprofiled code, because GHC is
able to optimise more aggressively if it doesn’t have to maintain correct entry counts.
This option can be useful if you aren’t interested in the entry counts (for example, if you
only intend to do heap profiling).
To generate a time and allocation profile, give one of the following RTS options to the compiled
program when you run it (RTS options should be enclosed between +RTS ... -RTS as usual):
-p
-P
-pa
The -p (page 558) option produces a standard time profile report. It is written into
the file <stem>.prof; the stem is taken to be the program name by default, but can be
overridden by the -po ⟨stem⟩ (page 558) flag.
The -P (page 558) option produces a more detailed report containing the actual time and
allocation data as well. (Not used much.)
The -pa (page 558) option produces the most detailed report containing all cost centres
in addition to the actual time and allocation data.
-pj
The -pj (page 558) option produces a time/allocation profile report in JSON format writ-
ten into the file <program>.prof.
-po ⟨stem⟩
The -po ⟨stem⟩ (page 558) option overrides the stem used to form the output file paths
for the cost-centre profiler (see -p (page 558) and -pj (page 558) flags above) and heap
profiler (see -h (page 170)).
For instance, running a program with +RTS -h -p -pohello-world would produce a
heap profile named [Link] and a cost-centre profile named [Link].
-V ⟨secs⟩
Default 0.02
Sets the interval that the RTS clock ticks at, which is also the sampling interval of the
time and allocation profile. The default is 0.02 seconds. The runtime uses a single timer
signal to count ticks; this timer signal is used to control the context switch timer (Using
Concurrent Haskell (page 117)) and the heap profiling timer RTS options for heap profil-
ing (page 562). Also, the time profiler uses the RTS timer signal directly to record time
profiling samples.
Normally, setting the -V ⟨secs⟩ (page 559) option directly is not necessary: the reso-
lution of the RTS timer is adjusted automatically if a short interval is requested with
the -C ⟨s⟩ (page 117) or -i ⟨secs⟩ (page 564) options. However, setting -V ⟨secs⟩
(page 559) is required in order to increase the resolution of the time profiler.
Using a value of zero disables the RTS clock completely, and has the effect of disabling
timers that depend on it: the context switch timer and the heap profiling timer. Context
switches will still happen, but deterministically and at a rate much faster than normal.
Disabling the interval timer is useful for debugging, because it eliminates a source of
non-determinism at runtime.
-xc
This option causes the runtime to print out the current cost-centre stack whenever an
exception is raised. This can be particularly useful for debugging the location of ex-
ceptions, such as the notorious [Link]: empty list error. See RTS options for
hackers, debuggers, and over-interested souls (page 171).
When invoked with the -pj (page 558) flag the runtime will emit the cost-centre profile in a
machine-readable JSON format. The top-level object of this format has the following proper-
ties,
program (string) The name of the program
arguments (list of strings) The command line arguments passed to the program
rts_arguments (list of strings) The command line arguments passed to the runtime system
initial_capabilities (integral number) How many capabilities the program was started
with (e.g. using the -N ⟨x⟩ (page 118) option). Note that the number of capabilities may
change during execution due to the setNumCapabilities function.
total_time (number) The total wall time of the program’s execution in seconds.
total_ticks (integral number) How many profiler “ticks” elapsed over the course of the
program’s execution.
end_time (number) The approximate time when the program finished execution as a UNIX
epoch timestamp.
tick_interval (float) How much time between profiler ticks.
total_alloc (integer) The cumulative allocations of the program in bytes.
{
"program": "Main",
"arguments": [
"nofib/shootout/n-body/Main",
"50000"
],
"rts_arguments": [
"-pj",
"-hy"
],
"end_time": "Thu Feb 23 17:15 2017",
"initial_capabilities": 0,
"total_time": 1.7,
"total_ticks": 1700,
"tick_interval": 1000,
"total_alloc": 3770785728,
"cost_centres": [
{
"id": 168,
"label": "IDLE",
"module": "IDLE",
"src_loc": "<built-in>",
"is_caf": false
},
{
"id": 156,
"label": "CAF",
"module": "[Link]",
"src_loc": "<entire-module>",
"is_caf": true
},
{
"id": 155,
"label": "CAF",
"module": "[Link]",
"src_loc": "<entire-module>",
"is_caf": true
},
{
"id": 154,
"label": "CAF",
"module": "[Link]",
"src_loc": "<entire-module>",
"is_caf": true
}
],
"profile": {
"id": 162,
"entries": 0,
"alloc": 688,
"ticks": 0,
"children": [
{
"id": 1,
"entries": 0,
"alloc": 208,
"ticks": 0,
"children": [
{
"id": 22,
"entries": 1,
"alloc": 80,
"ticks": 0,
"children": []
}
]
},
{
"id": 42,
"entries": 1,
"alloc": 1632,
"ticks": 0,
"children": []
}
]
}
}
In addition to profiling the time and allocation behaviour of your program, you can also gen-
erate a graph of its memory usage over time. This is useful for detecting the causes of space
leaks, when your program holds on to more memory at run-time that it needs to. Space leaks
lead to slower execution due to heavy garbage collector activity, and may even cause the
program to run out of memory altogether.
Main 100 +RTS -hc 9,661 bytes x seconds Fri Oct 2 15:01 2015
bytes
(54)PINNED
(92)[Link]
(77)[Link]
30k (84)[Link]
(103)[Link]
(109)ray/run/main.\/main/M...
25k (185)shade/tracepixel/ray....
(119)testspheres/[Link]
(217)vecsum/[Link]
20k
(80)[Link]
(110)rbg/pixels/ppm/run/ma...
(140)vecsub/[Link]...
15k
(157)vecscale/[Link]...
(147)vecscale/[Link]...
10k (221)vecadd/vecsum/shade.d...
(108)pixels/ppm/run/main.\...
(183)rbg.eight_bit/rbg/pix...
5k (122)sphereintersect/trace...
(112)tracepixel/ray.f/ray/...
OTHER
0k
0.0 0.1 0.1 0.2 0.2 0.2 seconds
You might also want to take a look at hp2any, a more advanced suite of tools (not distributed
with GHC) for displaying heap profiles.
There are several different kinds of heap profile that can be generated. All the different profile
types yield a graph of live heap against time, but they differ in how the live heap is broken
down into bands. The following RTS options select which break-down to use:
-hT
Breaks down the graph by heap closure type.
-hc
-h
Requires -prof (page 557). Breaks down the graph by the cost-centre stack which pro-
duced the data.
Note: The meaning of the shortened -h (page 170) is dependent on whether your
program was compiled for profiling. When compiled for profiling, -h (page 170) is equiv-
alent to -hc (page 563), but otherwise is equivalent to -hT (page 170) (see RTS options
for profiling (page 170)).
-hm
Requires -prof (page 557). Break down the live heap by the module containing the code
which produced the data.
-hd
Requires -prof (page 557). Breaks down the graph by closure description. For actual
data, the description is just the constructor name, for other closures it is a compiler-
generated string identifying the closure.
-hy
Requires -prof (page 557). Breaks down the graph by type. For closures which have
function type or unknown/polymorphic type, the string will represent an approximation
to the actual type.
-hr
Requires -prof (page 557). Break down the graph by retainer set. Retainer profiling is
described in more detail below (Retainer Profiling (page 564)).
-hb
Requires -prof (page 557). Break down the graph by biography. Biographical profiling
is described in more detail below (Biographical Profiling (page 565)).
-l
Emit profile samples to the GHC event log (page 170). This format is both more expres-
sive than the old .hp format and can be correlated with other events over the program’s
runtime. See Heap profiler event log output (page 621) for details on the produced event
structure.
In addition, the profile can be restricted to heap data which satisfies certain criteria - for
example, you might want to display a profile by type but only for data produced by a certain
module, or a profile by retainer for a certain type of data. Restrictions are specified as follows:
-hc ⟨name⟩
Restrict the profile to closures produced by cost-centre stacks with one of the specified
cost centres at the top.
-hC ⟨name⟩
Restrict the profile to closures produced by cost-centre stacks with one of the specified
cost centres anywhere in the stack.
-hm ⟨module⟩
Restrict the profile to closures produced by the specified modules.
-hd ⟨desc⟩
Restrict the profile to closures with the specified description strings.
-hy ⟨type⟩
Restrict the profile to closures with the specified types.
-hr ⟨cc⟩
Restrict the profile to closures with retainer sets containing cost-centre stacks with one
of the specified cost centres at the top.
-hb ⟨bio⟩
Restrict the profile to closures with one of the specified biographies, where ⟨bio⟩ is one
of lag, drag, void, or use.
For example, the following options will generate a retainer profile restricted to Branch and
Leaf constructors:
There can only be one “break-down” option (eg. -hr (page 563) in the example above), but
there is no limit on the number of further restrictions that may be applied. All the options may
be combined, with one exception: GHC doesn’t currently support mixing the -hr (page 563)
and -hb (page 563) options.
There are three more options which relate to heap profiling:
-i ⟨secs⟩
Set the profiling (sampling) interval to ⟨secs⟩ seconds (the default is 0.1 second). Frac-
tions are allowed: for example -i0.2 will get 5 samples per second. This only affects
heap profiling; time profiles are always sampled with the frequency of the RTS clock.
See Time and allocation profiling (page 558) for changing that.
-xt
Include the memory occupied by threads in a heap profile. Each thread takes up a small
area for its thread state in addition to the space allocated for its stack (stacks normally
start small and then grow as necessary).
This includes the main thread, so using -xt (page 564) is a good way to see how much
stack space the program is using.
Memory occupied by threads and their stacks is labelled as “TSO” and “STACK” respec-
tively when displaying the profile by closure description or type description.
-L ⟨num⟩
Sets the maximum length of a cost-centre stack name in a heap profile. Defaults to 25.
Retainer profiling is designed to help answer questions like “why is this data being retained?”.
We start by defining what we mean by a retainer:
A retainer is either the system stack, an unevaluated closure (thunk), or an explicitly
mutable object.
In particular, constructors are not retainers.
An object B retains object A if (i) B is a retainer object and (ii) object A can be reached by re-
cursively following pointers starting from object B, but not meeting any other retainer objects
on the way. Each live object is retained by one or more retainer objects, collectively called
its retainer set, or its retainer set, or its retainers.
When retainer profiling is requested by giving the program the -hr option, a graph is gener-
ated which is broken down by retainer set. A retainer set is displayed as a set of cost-centre
stacks; because this is usually too large to fit on the profile graph, each retainer set is num-
bered and shown abbreviated on the graph along with its number, and the full list of retainer
sets is dumped into the file [Link].
Retainer profiling requires multiple passes over the live heap in order to discover the full
retainer set for each object, which can be quite slow. So we set a limit on the maximum
size of a retainer set, where all retainer sets larger than the maximum retainer set size are
replaced by the special set MANY. The maximum set size defaults to 8 and can be altered with
the -R ⟨size⟩ (page 565) RTS option:
-R ⟨size⟩
Restrict the number of elements in a retainer set to ⟨size⟩ (default 8).
The definition of retainers is designed to reflect a common cause of space leaks: a large struc-
ture is retained by an unevaluated computation, and will be released once the computation
is forced. A good example is looking up a value in a finite map, where unless the lookup is
forced in a timely manner the unevaluated lookup will cause the whole mapping to be retained.
These kind of space leaks can often be eliminated by forcing the relevant computations to be
performed eagerly, using seq or strictness annotations on data constructor fields.
Often a particular data structure is being retained by a chain of unevaluated closures, only
the nearest of which will be reported by retainer profiling - for example A retains B, B retains
C, and C retains a large structure. There might be a large number of Bs but only a single A,
so A is really the one we’re interested in eliminating. However, retainer profiling will in this
case report B as the retainer of the large structure. To move further up the chain of retainers,
we can ask for another retainer profile but this time restrict the profile to B objects, so we get
a profile of the retainers of B:
This trick isn’t foolproof, because there might be other B closures in the heap which aren’t the
retainers we are interested in, but we’ve found this to be a useful technique in most cases.
A typical heap object may be in one of the following four states at each point in its lifetime:
• The lag stage, which is the time between creation and the first use of the object,
• the use stage, which lasts from the first use until the last use of the object, and
• The drag stage, which lasts from the final use until the last reference to the object is
dropped.
• An object which is never used is said to be in the void state for its whole lifetime.
A biographical heap profile displays the portion of the live heap in each of the four states
listed above. Usually the most interesting states are the void and drag states: live heap in
these states is more likely to be wasted space than heap in the lag or use states.
It is also possible to break down the heap in one or more of these states by a different criteria,
by restricting a profile by biography. For example, to show the portion of the heap in the drag
or void state by producer:
Once you know the producer or the type of the heap in the drag or void states, the next step
is usually to find the retainer(s):
prog +RTS -hr -hccc...
Note: This two stage process is required because GHC cannot currently profile using both
biographical and retainer information simultaneously.
How does the heap residency reported by the heap profiler relate to the actual memory res-
idency of your program when you run it? You might see a large discrepancy between the
residency reported by the heap profiler, and the residency reported by tools on your system
(eg. ps or top on Unix, or the Task Manager on Windows). There are several reasons for this:
• There is an overhead of profiling itself, which is subtracted from the residency figures
by the profiler. This overhead goes away when compiling without profiling support, of
course. The space overhead is currently 2 extra words per heap object, which probably
results in about a 30% overhead.
• Garbage collection requires more memory than the actual residency. The factor depends
on the kind of garbage collection algorithm in use: a major GC in the standard generation
copying collector will usually require 3L bytes of memory, where L is the amount of live
data. This is because by default (see the RTS -F ⟨factor⟩ (page 162) option) we allow
the old generation to grow to twice its size (2L) before collecting it, and we require
additionally L bytes to copy the live data into. When using compacting collection (see
the -c (page 162) option), this is reduced to 2L, and can further be reduced by tweaking
the -F ⟨factor⟩ (page 162) option. Also add the size of the allocation area (see -A
⟨size⟩ (page 160)).
• The stack isn’t counted in the heap profile by default. See the RTS -xt (page 564) option.
• The program text itself, the C stack, any non-heap data (e.g. data allocated by foreign
libraries, and data allocated by the RTS), and mmap()‘d memory are not counted in the
heap profile.
Usage:
hp2ps [flags] [<file>[.hp]]
The program hp2ps program converts a .hp file produced by the -h<break-down> runtime
option into a PostScript graph of the heap profile. By convention, the file to be processed by
hp2ps has a .hp extension. The PostScript output is written to file@.ps. If <file> is omitted
entirely, then the program behaves as a filter.
hp2ps is distributed in ghc/utils/hp2ps in a GHC source distribution. It was originally de-
veloped by Dave Wakeling as part of the HBC/LML heap profiler.
The flags are:
-d
In order to make graphs more readable, hp2ps sorts the shaded bands for each identifier.
The default sort ordering is for the bands with the largest area to be stacked on top of the
smaller ones. The -d option causes rougher bands (those representing series of values
with the largest standard deviations) to be stacked on top of smoother ones.
-b
Normally, hp2ps puts the title of the graph in a small box at the top of the page. However,
if the JOB string is too long to fit in a small box (more than 35 characters), then hp2ps
will choose to use a big box instead. The -b option forces hp2ps to use a big box.
-e⟨float⟩[in|mm|pt]
Generate encapsulated PostScript suitable for inclusion in LaTeX documents. Usually,
the PostScript graph is drawn in landscape mode in an area 9 inches wide by 6 inches
high, and hp2ps arranges for this area to be approximately centred on a sheet of a4 paper.
This format is convenient of studying the graph in detail, but it is unsuitable for inclusion
in LaTeX documents. The -e option causes the graph to be drawn in portrait mode, with
float specifying the width in inches, millimetres or points (the default). The resulting
PostScript file conforms to the Encapsulated PostScript (EPS) convention, and it can be
included in a LaTeX document using Rokicki’s dvi-to-PostScript converter dvips.
-g
Create output suitable for the gs PostScript previewer (or similar). In this case the graph
is printed in portrait mode without scaling. The output is unsuitable for a laser printer.
-l
Normally a profile is limited to 20 bands with additional identifiers being grouped into
an OTHER band. The -l flag removes this 20 band and limit, producing as many bands as
necessary. No key is produced as it won’t fit!. It is useful for creation time profiles with
many bands.
-m⟨int⟩
Normally a profile is limited to 20 bands with additional identifiers being grouped into
an OTHER band. The -m flag specifies an alternative band limit (the maximum is 20).
-m0 requests the band limit to be removed. As many bands as necessary are produced.
However no key is produced as it won’t fit! It is useful for displaying creation time
profiles with many bands.
-p
Use previous parameters. By default, the PostScript graph is automatically scaled both
horizontally and vertically so that it fills the page. However, when preparing a series
of graphs for use in a presentation, it is often useful to draw a new graph using the
same scale, shading and ordering as a previous one. The -p flag causes the graph to be
drawn using the parameters determined by a previous run of hp2ps on file. These are
extracted from file@.aux.
-s
Use a small box for the title.
-t⟨float⟩
Normally trace elements which sum to a total of less than 1% of the profile are removed
from the profile. The -t option allows this percentage to be modified (maximum 5%).
-t0 requests no trace elements to be removed from the profile, ensuring that all the data
will be displayed.
-c
Generate colour output.
-y
Ignore marks.
-?
Print out usage information.
The first four lines (JOB, DATE, SAMPLE_UNIT, VALUE_UNIT) form a header. Each block of lines
starting with BEGIN_SAMPLE and ending with END_SAMPLE forms a single sample (you can think
of this as a vertical slice of your heap profile). The hp2ps utility should accept any input with
a properly-formatted header followed by a series of complete samples.
You can look at particular regions of your profile simply by loading a copy of the .hp file into
a text editor and deleting the unwanted samples. The resulting .hp file can be run through
hp2ps and viewed or printed.
The .hp file is generated incrementally as your program runs. In principle, running hp2ps on
the incomplete file should produce a snapshot of your program’s heap usage. However, the
last sample in the file may be incomplete, causing hp2ps to fail. If you are using a machine with
UNIX utilities installed, it’s not too hard to work around this problem (though the resulting
command line looks rather Byzantine):
The command fgrep -n END_SAMPLE [Link] finds the end of every complete sample in
[Link], and labels each sample with its ending line number. We then select the line num-
ber of the last complete sample using tail and cut. This is used as a parameter to head; the
result is as if we deleted the final incomplete sample from [Link]. This results in a properly-
formatted .hp file which we feed directly to hp2ps.
The gv and ghostview programs have a “watch file” option can be used to view an up-to-
date heap profile of your program as it runs. Simply generate an incremental heap profile as
described in the previous section. Run gv on your profile:
gv -watch -orientation=seascape [Link]
If you forget the -watch flag you can still select “Watch file” from the “State” menu. Now
each time you generate a new profile [Link] the view will update automatically.
This can all be encapsulated in a little script:
#!/bin/sh
head -`fgrep -n END_SAMPLE [Link] | tail -1 | cut -d : -f 1` [Link] \
| hp2ps > [Link]
gv -watch -orientation=seascape [Link] &
while [ 1 ] ; do
sleep 10 # We generate a new profile every 10 seconds.
head -`fgrep -n END_SAMPLE [Link] | tail -1 | cut -d : -f 1` [Link] \
| hp2ps > [Link]
done
Occasionally gv will choke as it tries to read an incomplete copy of [Link] (because hp2ps
is still running as an update occurs). A slightly more complicated script works around this
problem, by using the fact that sending a SIGHUP to gv will cause it to re-read its input file:
#!/bin/sh
head -`fgrep -n END_SAMPLE [Link] | tail -1 | cut -d : -f 1` [Link] \
| hp2ps > [Link]
gv [Link] &
gvpsnum=$!
while [ 1 ] ; do
sleep 10
head -`fgrep -n END_SAMPLE [Link] | tail -1 | cut -d : -f 1` [Link] \
| hp2ps > [Link]
kill -HUP $gvpsnum
done
Combining -threaded (page 220) and -prof (page 557) is perfectly fine, and indeed it is
possible to profile a program running on multiple processors with the RTS -N ⟨x⟩ (page 118)
option. 3
Some caveats apply, however. In the current implementation, a profiled program is likely to
scale much less well than the unprofiled program, because the profiling implementation uses
3 This feature was added in GHC 7.4.1.
some shared data structures which require locking in the runtime system. Furthermore, the
memory allocation statistics collected by the profiled program are stored in shared memory
but not locked (for speed), which means that these figures might be inaccurate for parallel
programs.
We strongly recommend that you use -fno-prof-count-entries (page 558) when compiling
a program to be profiled on multiple cores, because the entry counts are also stored in shared
memory, and continuously updating them on multiple cores is extremely slow.
We also recommend using ThreadScope for profiling parallel programs; it offers a GUI for
visualising parallel execution, and is complementary to the time and space profiling features
provided with GHC.
Code coverage tools allow a programmer to determine what parts of their code have been
actually executed, and which parts have never actually been invoked. GHC has an option
for generating instrumented code that records code coverage as part of the Haskell Program
Coverage (HPC) toolkit, which is included with GHC. HPC tools can be used to render the
generated code coverage information into human understandable format.
Correctly instrumented code provides coverage information of two kinds: source coverage
and boolean-control coverage. Source coverage is the extent to which every part of the pro-
gram was used, measured at three different levels: declarations (both top-level and local),
alternatives (among several equations or case branches) and expressions (at every level).
Boolean coverage is the extent to which each of the values True and False is obtained in
every syntactic boolean context (ie. guard, condition, qualifier).
HPC displays both kinds of information in two primary ways: textual reports with summary
statistics (hpc report) and sources with color mark-up (hpc markup). For boolean coverage,
there are four possible outcomes for each guard, condition or qualifier: both True and False
values occur; only True; only False; never evaluated. In hpc-markup output, highlighting
with a yellow background indicates a part of the program that was never evaluated; a green
background indicates an always-True expression and a red background indicates an always-
False one.
For an example we have a program, called [Link], which computes exact decimal repre-
sentations of reciprocals, with recurring parts indicated in brackets.
main = do
number <- readLn
putStrLn (showRecip number)
main
GHC creates a subdirectory .hpc in the current directory, and puts HPC index (.mix) files in
there, one for each module compiled. You don’t need to worry about these files: they contain
information needed by the hpc tool to generate the coverage data for compiled modules after
the program is run.
$ ./Recip
1/3
= 0.(3)
Running the program generates a file with the .tix suffix, in this case [Link], which
contains the coverage data for this run of the program. The program may be run multiple
times (e.g. with different test data), and the coverage data from the separate runs is accumu-
lated in the .tix file. To reset the coverage data and start again, just remove the .tix file.
You can control where the .tix file is generated using the environment variable HPCTIXFILE
(page 571).
HPCTIXFILE
Set the HPC .tix file output path.
Having run the program, we can generate a textual summary of coverage:
This generates one file per Haskell module, and 4 index files, hpc_index.html,
hpc_index_alt.html, hpc_index_exp.html, hpc_index_fun.html.
-fhpc
Enable code coverage for the current module or modules being compiled.
Modules compiled with this option can be freely mixed with modules compiled without
it; indeed, most libraries will typically be compiled without -fhpc (page 572). When
the program is run, coverage data will only be generated for those modules that were
compiled with -fhpc (page 572), and the hpc tool will only show information about those
modules.
$ hpc
Usage: hpc COMMAND ...
Commands:
help Display help for hpc or a single command
Reporting Coverage:
report Output textual report about program coverage
markup Markup Haskell source with program coverage
Processing Coverage files:
sum Sum multiple .tix files in a single .tix file
combine Combine two .tix files in a single .tix file
map Map a function over a single .tix file
Coverage Overlays:
overlay Generate a .tix file from an overlay file
draft Generate draft overlay that provides 100% coverage
Others:
show Show .tix file in readable, verbose format
version Display version for hpc
In general, these options act on a .tix file after an instrumented binary has generated it.
The hpc tool assumes you are in the top-level directory of the location where you built your
application, and the .tix file is in the same top-level directory. You can use the flag --srcdir
to use hpc for any other directory, and use --srcdir multiple times to analyse programs
compiled from difference locations, as is typical for packages.
We now explain in more details the major modes of hpc.
hpc report
hpc report gives a textual report of coverage. By default, all modules and packages are
considered in generating report, unless include or exclude are used. The report is a summary
unless the --per-module flag is used. The --xml-output option allows for tools to use hpc to
glean coverage.
$ hpc help report
Usage: hpc report [OPTION] .. <TIX_FILE> [<MODULE> [<MODULE> ..]]
Options:
hpc markup
Options:
hpc sum
hpc sum adds together any number of .tix files into a single .tix file. hpc sum does not
change the original .tix file; it generates a new .tix file.
$ hpc help sum
Usage: hpc sum [OPTION] .. <TIX_FILE> [<TIX_FILE> [<TIX_FILE> ..]]
Sum multiple .tix files in a single .tix file
Options:
hpc combine
hpc combine is the swiss army knife of hpc. It can be used to take the difference between
.tix files, to subtract one .tix file from another, or to add two .tix files. hpc combine does
not change the original .tix file; it generates a new .tix file.
Options:
hpc map
hpc map inverts or zeros a .tix file. hpc map does not change the original .tix file; it
generates a new .tix file.
Options:
Overlays are an experimental feature of HPC, a textual description of coverage. hpc draft is
used to generate a draft overlay from a .tix file, and hpc overlay generates a .tix files from an
overlay.
Options:
Options:
HPC does not attempt to lock the .tix file, so multiple concurrently running binaries in the
same directory will exhibit a race condition. At compile time, there is no way to change
the name of the .tix file generated; at runtime, the name of the generated .tix file can
be changed using HPCTIXFILE (page 571); the name of the .tix file will also change if you
rename the binary. HPC does not work with GHCi.
-ticky
Enable ticky-ticky profiling.
Because ticky-ticky profiling requires a certain familiarity with GHC internals, we have moved
the documentation to the GHC developers wiki. Take a look at its overview of the profiling
options, which includes a link to the ticky-ticky profiling page.
NINE
Since the 7.10 release GHC can emit a debugging information to help debugging tools un-
derstand the code that GHC produces. This debugging information is useable by most UNIX
debugging tools.
-g
-g⟨n⟩
Since 7.10, numeric levels since 8.0
Emit debug information in object code. Currently only DWARF debug information is
supported on x86-64 and i386. Currently debug levels 0 through 3 are accepted:
•-g0: no debug information produced
•-g1: produces stack unwinding records for top-level functions (sufficient for basic
backtraces)
•-g2: produces stack unwinding records for top-level functions as well as inner blocks
(allowing more precise backtraces than with -g1).
•-g3: same as -g2.
If ⟨n⟩ is omitted, level 2 is assumed.
9.1 Tutorial
1 -- [Link]
2 fib :: Int -> Int
3 fib 0 = 0
4 fib 1 = 1
5 fib n = fib (n-1) + fib (n-2)
6
7 main :: IO ()
8 main = print $ fib 50
Let’s first see how execution flows through this program. We start by telling GHC that we
want debug information,
Here we used the -g option to inform GHC that it should add debugging information in the pro-
duced binary. There are three levels of debugging output: -g0 (no debugging information,
577
GHC User’s Guide Documentation, Release 9.0.2
the default), -g1 (sufficient for basic backtraces), -g2 (or just -g for short; emitting every-
thing GHC knows). Note that this debugging information does not affect the optimizations
performed by GHC.
Tip: Under Mac OS X debug information is kept apart from the executable. After compiling
the executable you’ll need to use the dsymutil utility to extract the debugging information
and place them in the debug archive,
$ dsymutil fib
Now let’s have a look at the flow of control. For this we can just start our program under gdb
(or an equivalent debugger) as we would any other native executable,
$ gdb --args ./Fib +RTS -V0
Reading symbols from Fib...done.
(gdb) run
Starting program: /opt/exp/ghc/ghc-dwarf/Fib
[Thread debugging using libthread_db enabled]
Using host libthread_db library "/lib/x86_64-linux-gnu/libthread_db.so.1".
^C
Program received signal SIGINT, Interrupt.
0x000000000064fc7c in cfy4_info () at libraries/integer-gmp/src/GHC/Integer/[Link]:
,→424
Here we have used the runtime system’s -V0 option to disable the RTS’s periodic timer which
may interfere with our debugging session. Upon breaking into the program gdb shows us a
location in our source program corresponding to the current point of execution.
Moreover, we can ask gdb to tell us the flow of execution that lead us to this point in the
program,
(gdb) bt
#0 0x000000000064fc7c in cfy4_info () at libraries/integer-gmp/src/GHC/Integer/Type.
,→hs:424
#1 0x00000000006eb0c0 in ?? ()
#2 0x000000000064301c in cbuV_info () at libraries/integer-gmp/src/GHC/Integer/Type.
,→hs:323
#7 0x00000000006eb0c0 in ?? ()
#8 0x000000000064f075 in cfru_info () at libraries/integer-gmp/src/GHC/Integer/Type.
,→hs:412
#9 0x00000000006eb0c0 in ?? ()
#10 0x000000000064eefe in integerzmgmp_GHCziIntegerziType_plusInteger_info () at␣
,→libraries/integer-gmp/src/GHC/Integer/[Link]
...
#64 0x0000000000643ac8 in integerzmgmp_GHCziIntegerziType_ltIntegerzh_info () at␣
,→libraries/integer-gmp/src/GHC/Integer/[Link]
Hint: Here we notice the first bit of the stack trace has many unidentified stack frames at
address 0x006eb0c0. If we ask gdb about this location, we find that these frames are actually
STG update closures,
The reason gdb doesn’t show this symbol name in the backtrace output is an infidelity in its in-
terpretation of debug information, which assumes an invariant preserved in C but not Haskell
programs. Unfortunately it is necessary to work around this manually until this behavior is
fixed upstream.
Note: Because of the aggressive optimization that GHC performs to the programs it compiles
it is quite difficult to pin-point exactly which point in the source program a given machine
instruction should be attributed to. In fact, internally GHC associates each instruction with
a set of source locations. When emitting the standard debug information used by gdb and
other language-agnostic debugging tools, GHC is forced to heuristically choose one location
from among this set.
For this reason we should be cautious when interpreting the source locations provided by
GDB. While these locations will usually be in some sense “correct”, they aren’t always useful.
This is why profiling tools targeting Haskell should supplement the standard source location
information with GHC-specific annotations (emitted with -g2) when assigning costs.
#7 0x00000000006ebcb0 in ?? () at rts/[Link]
#8 0x00000000006e7320 in ?? ()
(gdb)
Due to the nature of GHC’s heap and the heavy optimization that it performs, it is quite
difficult to probe the values of bindings at runtime. In this way, the debugging experience
of a Haskell program with DWARF support is still a bit impoverished compared to typical
imperative debuggers.
GHC’s runtime system has built-in support for collecting stack trace information from a run-
ning Haskell program. This currently requires that the libdw library from the elfutils pack-
age is available. Of course, the backtrace will be of little use unless debug information is
available in the executable and its dependent libraries.
Stack trace functionality is exposed for use by Haskell programs in the [Link]
module. See the Haddock documentation in this module for details regarding usage.
On POSIX-compatible platforms GHC’s runtime system (when built with libdw support) will
produce a stack trace on stderr when a SIGQUIT signal is received (on many systems this
signal can be sent using Ctrl-\). For instance (using the same [Link] as above),
Note: Most users don’t need to worry about the details described in this section. This
discussion is primarily targeted at tooling authors who need to interpret the GHC-specific
DWARF annotations contained in compiled binaries.
When invoked with the -g flag GHC will produce standard DWARF v4 debugging information.
This format is used by nearly all POSIX-compliant targets and can be used by debugging and
performance tools (e.g. gdb, lldb, and perf) to understand the structure of GHC-compiled
programs.
In particular GHC produces the following DWARF sections,
.debug_info Debug information entities (DIEs) describing all of the basic blocks in the com-
piled program.
.debug_line Line number information necessary to map instruction addresses to line num-
bers in the source program.
Note that the line information in this section is not nearly as rich as the information pro-
vided in .debug_info. Whereas .debug_line requires that each instruction is assigned
exactly one source location, the DIEs in .debug_info can be used to identify all relevant
sources locations.
.debug_frames Call frame information (CFI) necessary for stack unwinding to produce a call
stack trace.
.debug_arange Address range information necessary for efficient lookup in debug informa-
tion.
GHC may produce the following standard DIEs in the .debug_info section,
DW_TAG_compile_unit Represents a compilation unit (e.g. a Haskell module).
DW_TAG_subprogram Represents a C-\- top-level basic block.
DW_TAG_lexical_block Represents a C-\- basic block. Note that this is a slight departure
from the intended meaning of this DIE type as it does not necessarily reflect lexical
scope in the source program.
As GHC’s compilation products don’t map perfectly onto DWARF constructs, GHC takes ad-
vantage of the extensibility of the DWARF standard to provide additional information.
Unfortunately DWARF isn’t expressive enough to fully describe the code that GHC produces.
This is most apparent in the case of line information, where GHC is forced to choose some be-
tween a variety of possible originating source locations. This limits the usefulness of DWARF
information with traditional statistical profiling tools. For profiling it is recommended that
one use the extended debugging information. See the Profiling section below.
In addition to the usual DIEs specified by the DWARF specification, GHC produces a variety
of others using the vendor-extensibility regions of the tag and attribute space.
DW_TAG_ghc_src_note
For more information about the debug information produced by GHC see Peter Wortmann’s
PhD thesis, *Profiling Optimized Haskell: Causal Analysis and Implementation*.
TEN
If you still have a problem after consulting this section, then you may have found a bug—
please report it! See Reporting bugs in GHC (page 4) for details on how to report a bug and
a list of things we’d like to know about your bug. If in doubt, send a report — we love mail
from irate users :-!
(Haskell standards vs. Glasgow Haskell: language non-compliance (page 603), which de-
scribes Glasgow Haskell’s shortcomings vs. the Haskell language definition, may also be of
interest.)
“Help! The compiler crashed (or panic’d)!” These events are always bugs in the GHC
system—please report them.
“This is a terrible error message.” If you think that GHC could have produced a better
error message, please report it as a bug.
“What about this warning from the C compiler?” For example: …warning: \`Foo' de-
clared \`static' but never defined. Unsightly, but shouldn’t be a problem.
Sensitivity to .hi interface files GHC is very sensitive about interface files. For example, if
it picks up a non-standard [Link] file, pretty terrible things will happen. If you turn
on -XNoImplicitPrelude-XNoImplicitPrelude option, the compiler will almost surely die,
unless you know what you are doing.
Furthermore, as sketched below, you may have big problems running programs compiled
using unstable interfaces.
“I think GHC is producing incorrect code” Unlikely :-) A useful be-more-paranoid option
to give to GHC is -dcore-lint-dcore-lint option; this causes a “lint” pass to check for
errors (notably type errors) after each Core-to-Core transformation pass. We run with
-dcore-lint on all the time; it costs about 5% in compile time.
Why did I get a link error? If the linker complains about not finding _<something>_fast,
then something is inconsistent: you probably didn’t compile modules in the proper de-
pendency order.
“Is this line number right?” On this score, GHC usually does pretty well, especially if you
“allow” it to be off by one or two. In the case of an instance or class declaration, the line
number may only point you to the declaration, not to a specific method.
Please report line-number errors that you find particularly unhelpful.
583
GHC User’s Guide Documentation, Release 9.0.2
(For advice about overly slow or memory-hungry Haskell programs, please see Hints
(page 585)).
“Help! My program crashed!” (e.g., a “segmentation fault” or “core dumped”) segmenta-
tion fault
If your program has no foreign calls in it, and no calls to known-unsafe functions (such as
unsafePerformIO) then a crash is always a BUG in the GHC system, except in one case: If
your program is made of several modules, each module must have been compiled after
any modules on which it depends (unless you use .hi-boot files, in which case these
must be correct with respect to the module source).
For example, if an interface is lying about the type of an imported value then GHC may
well generate duff code for the importing module. This applies to pragmas inside inter-
faces too! If the pragma is lying (e.g., about the “arity” of a value), then duff code may
result. Furthermore, arities may change even if types do not.
In short, if you compile a module and its interface changes, then all the modules that
import that interface must be re-compiled.
A useful option to alert you when interfaces change is -ddump-hi-diffs option. It will
run diff on the changed interface file, before and after, when applicable.
If you are using make, GHC can automatically generate the dependencies required in
order to make sure that every module is up-to-date with respect to its imported interfaces.
Please see Dependency generation (page 190).
If you are down to your last-compile-before-a-bug-report, we would recommend that you
add a -dcore-lint option (for extra checking) to your compilation options.
So, before you report a bug because of a core dump, you should probably:
Of course, if you have foreign calls in your program then all bets are off, because you
can trash the heap, the stack, or whatever.
“My program entered an ‘absent’ argument.” This is definitely caused by a bug in GHC.
Please report it (see Reporting bugs in GHC (page 4)).
“What’s with this arithmetic (or floating-point) exception?” Int, Float, and Double
arithmetic is unchecked. Overflows, underflows and loss of precision are either silent or
reported as an exception by the operating system (depending on the platform). Divide-
by-zero may cause an untrapped exception (please report it if it does).
ELEVEN
HINTS
Don’t use -O (page 105) or (especially) -O2 (page 105): By using them, you are telling
GHC that you are willing to suffer longer compilation times for better-quality code.
GHC is surprisingly zippy for normal compilations without -O (page 105)!
Use more memory: Within reason, more memory for heap space means less garbage collec-
tion for GHC, which means less compilation time. If you use the -Rghc-timing option,
you’ll get a garbage-collector report. (Again, you can use the cheap-and-nasty +RTS -S
-RTS option to send the GC stats straight to standard error.)
If it says you’re using more than 20% of total time in garbage collecting, then more
memory might help: use the -H⟨size⟩ (see -H [⟨size⟩] (page 163)) option. Increasing
the default allocation area size used by the compiler’s RTS might also help: use the +RTS
-A⟨size⟩ -RTS option (see -A ⟨size⟩ (page 160)).
If GHC persists in being a bad memory citizen, please report it as a bug.
Don’t use too much memory! As soon as GHC plus its “fellow citizens” (other processes on
your machine) start using more than the real memory on your machine, and the machine
starts “thrashing,” the party is over. Compile times will be worse than terrible! Use
something like the csh builtin time command to get a report on how many page faults
you’re getting.
If you don’t know what virtual memory, thrashing, and page faults are, or you don’t
know the memory configuration of your machine, don’t try to be clever about memory
use: you’ll just make your life a misery (and for other people, too, probably).
Try to use local disks when linking: Because Haskell objects and libraries tend to be
large, it can take many real seconds to slurp the bits to/from a remote filesystem.
It would be quite sensible to compile on a fast machine using remotely-mounted disks;
then link on a slow machine that had your disks directly mounted.
Don’t derive/use Read unnecessarily: It’s ugly and slow.
GHC compiles some program constructs slowly: We’d rather you reported such be-
haviour as a bug, so that we can try to correct it.
To figure out which part of the compiler is badly behaved, the -v2 option is your friend.
585
GHC User’s Guide Documentation, Release 9.0.2
The key tool to use in making your Haskell program run faster are GHC’s profiling facilities,
described separately in Profiling (page 553). There is no substitute for finding where your
program’s time/space is really going, as opposed to where you imagine it is going.
Another point to bear in mind: By far the best way to improve a program’s performance
dramatically is to use better algorithms. Once profiling has thrown the spotlight on the guilty
time-consumer(s), it may be better to re-think your program than to try all the tweaks listed
below.
Another extremely efficient way to make your program snappy is to use library code that has
been Seriously Tuned By Someone Else. You might be able to write a better quicksort than
the one in [Link], but it will take you much longer than typing import [Link].
Please report any overly-slow GHC-compiled programs. Since GHC doesn’t have any credi-
ble competition in the performance department these days it’s hard to say what overly-slow
means, so just use your judgement! Of course, if a GHC compiled program runs slower than
the same program compiled with NHC or Hugs, then it’s definitely a bug.
Optimise, using -O or -O2: This is the most basic way to make your program go faster. Com-
pilation time will be slower, especially with -O2.
At present, -O2 is nearly indistinguishable from -O.
Compile via LLVM: The LLVM code generator (page 209) can sometimes do a far better job
at producing fast code than the native code generator (page 209). This is not universal
and depends on the code. Numeric heavy code seems to show the best improvement
when compiled via LLVM. You can also experiment with passing specific flags to LLVM
with the -optlo ⟨option⟩ (page 212) and -optlc ⟨option⟩ (page 212) flags. Be care-
ful though as setting these flags stops GHC from setting its usual flags for the LLVM
optimiser and compiler.
Overloaded functions are not your friend: Haskell’s overloading (using type classes) is
elegant, neat, etc., etc., but it is death to performance if left to linger in an inner loop.
How can you squash it?
Give explicit type signatures: Signatures are the basic trick; putting them on exported,
top-level functions is good software-engineering practice, anyway. (Tip: using the -
Wmissing-signatures (page 96) option can help enforce good signature-practice).
The automatic specialisation of overloaded functions (with -O) should take care of over-
loaded local and/or unexported functions.
Use SPECIALIZE pragmas: Specialize the overloading on key functions in your program.
See SPECIALIZE pragma (page 525) and SPECIALIZE instance pragma (page 527).
“But how do I know where overloading is creeping in?” A low-tech way: grep (search)
your interface files for overloaded type signatures. You can view interface files using
the --show-iface ⟨file⟩ (page 76) option (see Other options related to interface files
(page 179)).
Strict functions are your dear friends: And, among other things, lazy pattern-matching is
your enemy.
(If you don’t know what a “strict function” is, please consult a functional-programming
textbook. A sentence or two of explanation here probably would not do much good.)
f (Wibble x y)
= let
!(a1, b1, c1) = unpackFoo x
!(a2, b2, c2) = unpackFoo y
in ...
GHC loves single-constructor data-types: It’s all the better if a function is strict in a
single-constructor type (a type with only one data-constructor; for example, tuples are
single-constructor types).
Newtypes are better than datatypes: If your datatype has a single constructor with a sin-
gle field, use a newtype declaration instead of a data declaration. The newtype will be
optimised away in most cases.
“How do I find out a function’s strictness?” Don’t guess—look it up.
Look for your function in the interface file, then for the third field in the pragma; it
should say Strictness: ⟨string⟩. The ⟨string⟩ gives the strictness of the function’s
arguments: see the GHC Commentary for a description of the strictness notation.
For an “unpackable” U(...) argument, the info inside tells the strictness of its com-
ponents. So, if the argument is a pair, and it says U(AU(LSS)), that means “the first
component of the pair isn’t used; the second component is itself unpackable, with three
components (lazy in the first, strict in the second \& third).”
If the function isn’t exported, just compile with the extra flag -ddump-simpl (page 230);
next to the signature for any binder, it will print the self-same pragmatic information as
would be put in an interface file. (Besides, Core syntax is fun to look at!)
Force key functions to be INLINEd (esp. monads): Placing INLINE pragmas on certain
functions that are used a lot can have a dramatic effect. See INLINE pragma (page 521).
Explicit export list: If you do not have an explicit export list in a module, GHC must assume
that everything in that module will be exported. This has various pessimising effects.
For example, if a bit of code is actually unused (perhaps because of unfolding effects),
GHC will not be able to throw it away, because it is exported and some other module
may be relying on its existence.
GHC can be quite a bit more aggressive with pieces of code if it knows they are not
exported.
Look at the Core syntax! (The form in which GHC manipulates your code.) Just run your
compilation with -ddump-simpl (page 230) (don’t forget the -O (page 105)).
If profiling has pointed the finger at particular functions, look at their Core code. lets
are bad, cases are good, dictionaries (d.⟨Class⟩.⟨Unique⟩) [or anything overloading-
ish] are bad, nested lambdas are bad, explicit data constructors are good, primitive op-
erations (e.g., eqInt#) are good, ...
Use strictness annotations: Putting a strictness annotation (!) on a constructor field helps
in two ways: it adds strictness to the program, which gives the strictness analyser more
to work with, and it might help to reduce space leaks.
It can also help in a third way: when used with -funbox-strict-fields (page 116) (see
-f*: platform-independent flags (page 105)), a strict field can be unpacked or unboxed in
the constructor, and one or more levels of indirection may be removed. Unpacking only
happens for single-constructor datatypes (Int is a good candidate, for example).
Using -funbox-strict-fields (page 116) is only really a good idea in conjunction with
-O (page 105), because otherwise the extra packing and unpacking won’t be optimised
away. In fact, it is possible that -funbox-strict-fields (page 116) may worsen perfor-
mance even with -O (page 105), but this is unlikely (let us know if it happens to you).
Use unboxed types (a GHC extension): When you are really desperate for speed, and you
want to get right down to the “raw bits.” Please see Unboxed types (page 473) for some
information about using unboxed types.
Before resorting to explicit unboxed types, try using strict constructor fields and -
funbox-strict-fields (page 116) first (see above). That way, your code stays portable.
Use foreign import (a GHC extension) to plug into fast libraries: This may take real
work, but… There exist piles of massively-tuned library code, and the best thing is not
to compete with it, but link with it.
Foreign function interface (FFI) (page 478) describes the foreign function interface.
Don’t use Floats: If you’re using Complex, definitely use Complex Double rather than Com-
plex Float (the former is specialised heavily, but the latter isn’t).
Floats (probably 32-bits) are almost always a bad idea, anyway, unless you Really Know
What You Are Doing. Use Doubles. There’s rarely a speed disadvantage—modern ma-
chines will use the same floating-point unit for both. With Doubles, you are much less
likely to hang yourself with numerical errors.
One time when Float might be a good idea is if you have a lot of them, say a giant array
of Floats. They take up half the space in the heap compared to Doubles. However, this
isn’t true on a 64-bit machine.
Use unboxed arrays (UArray) GHC supports arrays of unboxed elements, for several basic
arithmetic element types including Int and Char: see the [Link] library
for details. These arrays are likely to be much faster than using standard Haskell 98
arrays from the [Link] library.
Use a bigger heap! If your program’s GC stats (-S [⟨file⟩] (page 167) RTS option) indi-
cate that it’s doing lots of garbage-collection (say, more than 20% of execution time),
more memory might help — with the -H [⟨size⟩] (page 163) or -A ⟨size⟩ (page 160)
RTS options (see RTS options to control the garbage collector (page 160)). As a rule of
thumb, try setting -H [⟨size⟩] (page 163) to the amount of memory you’re willing to
let your process consume, or perhaps try passing -H [⟨size⟩] (page 163) without any
argument to let GHC calculate a value based on the amount of live data.
Compact your data: The [Link] module provides a way to make garbage collection
more efficient for long-lived data structures. Compacting a data structure collects the
objects together in memory, where they are treated as a single object by the garbage
collector and not traversed individually.
Decrease the “go-for-it” threshold for unfolding smallish expressions. Give a -funfolding-
use-threshold=0 (page 116) option for the extreme case. (“Only unfoldings with zero cost
should proceed.”) Warning: except in certain specialised cases (like Happy parsers) this is
likely to actually increase the size of your program, because unfolding generally enables extra
simplifying optimisations to be performed.
Avoid [Link].
Use strip on your executables.
TWELVE
This section describes other program(s) which we distribute, that help with the Great Haskell
Programming Task.
Andy Gill and Simon Marlow have written a parser-generator for Haskell, called happy. Happy
is to Haskell what Yacc is to C.
You can get happy from the Happy Homepage.
Happy is at its shining best when compiled by GHC.
The hsc2hs command can be used to automate some parts of the process of writing Haskell
bindings to C code. It reads an almost-Haskell source with embedded special constructs, and
outputs a real Haskell file with these constructs processed, based on information taken from
some C headers. The extra constructs deal with accessing C data from Haskell.
It may also output a C file which contains additional C functions to be linked into the program,
together with a C header that gets included into the C code to which the Haskell module will
be compiled (when compiled via C) and into the C file. These two files are created when the
#def construct is used (see below).
Actually hsc2hs does not output the Haskell file directly. It creates a C program that includes
the headers, gets automatically compiled and run. That program outputs the Haskell code.
In the following, “Haskell file” is the main output (usually a .hs file), “compiled Haskell file”
is the Haskell file after ghc has compiled it to C (i.e. a .hc file), “C program” is the program
that outputs the Haskell file, “C file” is the optionally generated C file, and “C header” is its
header file.
hsc2hs takes input files as arguments, and flags that modify its behavior:
-o FILE, --output=FILE Name of the Haskell file.
-t FILE, --template=FILE The template file (see below).
-c PROG, --cc=PROG The C compiler to use (default: gcc)
591
GHC User’s Guide Documentation, Release 9.0.2
All special processing is triggered by the # operator. To output a literal #, write it twice: ##.
Inside string literals and comments # characters are not processed.
A # is followed by optional spaces and tabs, an alphanumeric keyword that describes the kind
of processing, and its arguments. Arguments look like C expressions separated by commas
(they are not written inside parens). They extend up to the nearest unmatched ), ] or }, or
to the end of line if it occurs outside any () [] {} '' "" /**/ and is not preceded by a
backslash. Backslash-newline pairs are stripped.
In addition #{stuff} is equivalent to #stuff except that it’s self-delimited and thus needs not
to be placed at the end of line or in some brackets.
Meanings of specific keywords:
#include <file.h>, #include "file.h" The specified file gets included into the C program,
the compiled Haskell file, and the C header. <HsFFI.h> is included automatically.
#define ⟨name⟩, #define ⟨name ⟨value⟩, #undef ⟨name⟩ Similar to #include. Note that
#includes and #defines may be put in the same file twice so they should not assume
otherwise.
#const, #type, #peek, #poke and #ptr are not hardwired into the hsc2hs, but are defined
in a C template that is included in the C program: template-hsc.h. Custom constructs and
templates can be used too. Any #-construct with unknown key is expected to be handled by a
C template.
A C template should define a macro or function with name prefixed by hsc_ that handles the
construct by emitting the expansion to stdout. See template-hsc.h for examples.
Such macros can also be defined directly in the source. They are useful for making a #let-
like macro whose expansion uses other #let macros. Plain #let prepends hsc_ to the macro
name and wraps the definition in a printf call.
12.2.4 Cross-compilation
hsc2hs normally operates by creating, compiling, and running a C program. That approach
doesn’t work when cross-compiling — in this case, the C compiler’s generates code for the
target machine, not the host machine. For this situation, there’s a special mode hsc2hs --
cross-compile which can generate the .hs by extracting information from compilations only
— specifically, whether or not compilation fails.
Only a subset of .hsc syntax is supported by --cross-compile. The following are unsup-
ported:
• #{const_str}
• #{let}
• #{def}
• Custom constructs
THIRTEEN
The installer that installs GHC on Win32 also sets up the file-suffix associations for ”.hs” and
”.lhs” files so that double-clicking them starts ghci.
Be aware of that ghc and ghci do require filenames containing spaces to be escaped using
quotes:
If the quotes are left off in the above command, ghci will interpret the filename as two,
c:\\\\Program and Files\\\\Haskell\\\\[Link].
We recommend running GHCi in a standard Windows console: select the GHCi option from
the start menu item added by the GHC installer, or use Start->Run->cmd to get a Windows
console and invoke ghci from there (as long as it’s in your PATH).
If you run GHCi in a Cygwin or MSYS shell, then the Control-C behaviour is adversely affected.
In one of these environments you should use the [Link] script to start GHCi, otherwise
when you hit Control-C you’ll be returned to the shell prompt but the GHCi process will still be
running. However, even using the [Link] script, if you hit Control-C then the GHCi process
will be killed immediately, rather than letting you interrupt a running program inside GHCi as
it should. This problem is caused by the fact that the Cygwin and MSYS shell environments
don’t pass Control-C events to non-Cygwin child processes, because in order to do that there
needs to be a Windows console.
There’s an exception: you can use a Cygwin shell if the CYGWIN environment variable does not
contain tty. In this mode, the Cygwin shell behaves like a Windows console shell and console
events are propagated to child processes. Note that the CYGWIN environment variable must
be set before starting the Cygwin shell; changing it afterwards has no effect on the shell.
This problem doesn’t just affect GHCi, it affects any GHC-compiled program that wants to
catch console events. See the [Link] module.
595
GHC User’s Guide Documentation, Release 9.0.2
By default GHC builds applications that open a console window when they start. If you want
to build a GUI-only application, with no console window, use the flag -optl-mwindows in the
link step.
Warning: Windows GUI-only programs have no stdin, stdout or stderr so using the ordi-
nary Haskell input/output functions will cause your program to fail with an IO exception,
such as:
Fail: <stdout>: hPutChar: failed (Bad file descriptor)
For some reason, Mingw ships with the readline library, but not with the readline headers.
As a result, GHC (like Hugs) does not use readline for interactive input on Windows. You
can get a close simulation by using an emacs shell buffer!
Windows paths are not all the same. The different kinds of paths each have different meanings.
The MAX_PATH limitation is not a limitation of the operating system nor the file system. It is a
limitation of the default namespace enforced by the Win32 API for backwards compatibility.
The NT kernel however allows you ways to opt out of this path preprocessing by the Win32
APIs. This is done by explicitly using the desired namespace in the path.
The namespaces are:
• file namespace: \\?\
• device namespace: \\.\
• NT namespace: \
Each of these turn off path processing completely by the Win32 API and the paths are passed
untouched to the filesystem.
Paths with a drive letter are legacy paths. The drive letters are actually meaningless to the
kernel. Just like Unix operating systems, drive letters are just a mount point. You can view
your mount points by using the mountvol command.
Since GHC 8.6.1, the Haskell I/O manager automatically promotes paths in the legacy format
to Win32 file namespace. By default the I/O manager will do two things to your paths:
• replace \ with \\
• expand relative paths to absolute paths
If you want to opt out of all preprocessing just explicitly use namespaces in your paths. Due
to this change, if you need to open raw devices (e.g. COM ports) you need to use the device
namespace explicitly. (e.g. \\.\COM1). GHC and Haskell programs in general no longer
support opening devices in the legacy format.
See the Windows documentation for more details.
13.6.1 Background
The Cygwin tools aim to provide a Unix-style API on top of the windows libraries, to facilitate
ports of Unix software to windows. To this end, they introduce a Unix-style directory hierarchy
under some root directory (typically / is C:\cygwin\). Moreover, everything built against the
Cygwin API (including the Cygwin tools and programs compiled with Cygwin’s GHC) will see
/ as the root of their file system, happily pretending to work in a typical unix environment, and
finding things like /bin and /usr/include without ever explicitly bothering with their actual
location on the windows system (probably C:\cygwin\bin and C:\cygwin\usr\include).
GHC, by default, no longer depends on cygwin, but is a native Windows program. It is built
using mingw, and it uses mingw’s GHC while compiling your Haskell sources (even if you
call it from cygwin’s bash), but what matters here is that - just like any other normal windows
program - neither GHC nor the executables it produces are aware of Cygwin’s pretended unix
hierarchy. GHC will happily accept either / or \\ as path separators, but it won’t know where
to find /home/joe/[Link] or /bin/bash or the like. This causes all kinds of fun when GHC
is used from within Cygwin’s bash, or in make-sessions running under Cygwin.
13.6.3 Things to do
• Don’t use absolute paths in make, configure & co if there is any chance that those might
be passed to GHC (or to GHC-compiled programs). Relative paths are fine because cyg-
win tools are happy with them and GHC accepts / as path-separator. And relative paths
don’t depend on where Cygwin’s root directory is located, or on which partition or net-
work drive your source tree happens to reside, as long as you cd there first.
• If you have to use absolute paths (beware of the innocent-looking ROOT=$(pwd) in make-
file hierarchies or configure scripts), Cygwin provides a tool called cygpath that can
convert Cygwin’s Unix-style paths to their actual Windows-style counterparts. Many
Cygwin tools actually accept absolute Windows-style paths (remember, though, that you
either need to escape \\ or convert \\ to /), so you should be fine just using those ev-
erywhere. If you need to use tools that do some kind of path-mangling that depends on
unix-style paths (one fun example is trying to interpret : as a separator in path lists),
13.6. Using GHC (and other GHC-compiled executables) with Cygwin 597
GHC User’s Guide Documentation, Release 9.0.2
you can still try to convert paths using cygpath just before they are passed to GHC and
friends.
• If you don’t have cygpath, you probably don’t have cygwin and hence no problems with
it... unless you want to write one build process for several platforms. Again, relative
paths are your friend, but if you have to use absolute paths, and don’t want to use differ-
ent tools on different platforms, you can simply write a short Haskell program to print
the current directory (thanks to George Russell for this idea): compiled with GHC, this
will give you the view of the file system that GHC depends on (which will differ depend-
ing on whether GHC is compiled with cygwin’s gcc or mingw’s gcc or on a real Unix
system..) - that little program can also deal with escaping \\ in paths. Apart from the
banner and the startup time, something like this would also do:
Dynamic link libraries, Win32 DLLs, Win32 On Win32 platforms, the compiler is capable of
both producing and using dynamic link libraries (DLLs) containing ghc-compiled code. This
section shows you how to make use of this facility.
There are two distinct ways in which DLLs can be used:
• You can turn each Haskell package into a DLL, so that multiple Haskell executables using
the same packages can share the DLL files. (As opposed to linking the libraries statically,
which in effect creates a new copy of the RTS and all libraries for each executable pro-
duced.)
That is the same as the dynamic linking on other platforms, and it is described in Using
shared libraries (page 223).
• You can package up a complete Haskell program as a DLL, to be called by some external
(usually non-Haskell) program. This is usually used to implement plugins and the like,
and is described below.
Creating a Win32 DLL -shared Sealing up your Haskell library inside a DLL is straightforward;
compile up the object files that make up the library, and then build the DLL by issuing a
command of the form:
By feeding the ghc compiler driver the option -shared, it will build a DLL rather than produce
an executable. The DLL will consist of all the object files and archives given on the command
line.
A couple of things to notice:
• By default, the entry points of all the object files will be exported from the DLL when
using -shared. Should you want to constrain this, you can specify the module definition
file to use on the command line as follows:
See Microsoft documentation for details, but a module definition file simply lists what
entry points you want to export. Here’s one that’s suitable when building a Haskell COM
server DLL:
EXPORTS
DllCanUnloadNow = DllCanUnloadNow@0
DllGetClassObject = DllGetClassObject@12
DllRegisterServer = DllRegisterServer@0
DllUnregisterServer = DllUnregisterServer@0
• In addition to creating a DLL, the -shared option also creates an import library. The
import library name is derived from the name of the DLL, as follows:
The naming scheme may look a bit weird, but it has the purpose of allowing the co-
existence of import libraries with ordinary static libraries (e.g., libHSfoo.a and libHS-
[Link].a. Additionally, when the compiler driver is linking in non-static mode, it will
rewrite occurrence of -lHSfoo on the command line to -[Link]. By doing this for
you, switching from non-static to static linking is simply a question of adding -static to
your command line.
This section describes how to create DLLs to be called from other languages, such as Visual
Basic or C++. This is a special case of Making a Haskell library that can be called from
foreign code (page 487); we’ll deal with the DLL-specific issues that arise below. Here’s an
example:
Use foreign export declarations to export the Haskell functions you want to call from the
outside. For example:
-- [Link]
{-# LANGUAGE ForeignFunctionInterface #-}
module Adder where
Add some helper code that starts up and shuts down the Haskell RTS:
// StartEnd.c
#include <Rts.h>
void HsStart()
{
int argc = 1;
char* argv[] = {"ghcDll", NULL}; // argv must end with NULL
void HsEnd()
{
hs_exit();
}
Here, Adder is the name of the root module in the module tree (as mentioned above, there
must be a single root module, and hence a single module tree in the DLL). Compile everything
up:
ghc -c [Link]
ghc -c StartEnd.c
ghc -shared -o [Link] Adder.o Adder_stub.o StartEnd.o
Now the file [Link] can be used from other programming languages. Before calling any
functions in Adder it is necessary to call HsStart, and at the very end call HsEnd.
Warning: It may appear tempting to use DllMain to call hs_init/hs_exit, but this won’t
work (particularly if you compile with -threaded). There are severe restrictions on which
actions can be performed during DllMain, and hs_init violates these restrictions, which
can lead to your DLL freezing during startup (see #3605).
This example uses the Document_Open/Close functions of Microsoft Word, but provided
HsStart is called before the first function, and HsEnd after the last, then it will work fine.
// [Link]
#include "HsFFI.h"
#include "Adder_stub.h"
#include <stdio.h>
extern "C" {
void HsStart();
void HsEnd();
}
int main()
{
HsStart();
// can now safely call functions from the DLL
printf("12 + 5 = %i\n", adder(12,5)) ;
HsEnd();
return 0;
}
FOURTEEN
This section lists Glasgow Haskell infelicities in its implementation of Haskell 98 and
Haskell 2010. See also the “when things go wrong” section (What to do when something
goes wrong (page 583)) for information about crashes, space leaks, and other undesirable
phenomena.
The limitations here are listed in Haskell Report order (roughly).
By default, GHC mainly aims to behave (mostly) like a Haskell 2010 compiler, although you
can tell it to try to behave like a particular version of the language with the Haskell98
(page 237) and Haskell2010 (page 237) flags. The known deviations from the standards are
described below. Unless otherwise stated, the deviation applies in Haskell 98, Haskell 2010
and the default modes.
Lexical syntax
• Certain lexical rules regarding qualified identifiers are slightly different in GHC com-
pared to the Haskell report. When you have ⟨module⟩.⟨reservedop⟩, such as M.\, GHC
will interpret it as a single qualified operator rather than the two lexemes M and .\.
• forall is always a reserved keyword at the type level, contrary to the Haskell Report,
which allows type variables to be named forall. Note that this does not imply that GHC
always enables the ExplicitForAll (page 431) extension. Even without this extension
enabled, reserving forall as a keyword has significance. For instance, GHC will not
parse the type signature foo :: forall x.
• The (!) operator, when written in prefix form (preceded by whitespace and not fol-
lowed by whitespace, as in f !x = ...), is interpreted as a bang pattern, contrary to
the Haskell Report, which prescribes to treat ! as an operator regardless of surround-
ing whitespace. Note that this does not imply that GHC always enables BangPatterns
(page 462). Without the extension, GHC will issue a parse error on f !x, asking to enable
the extension.
• Irrefutable patterns must be written in prefix form:
603
GHC User’s Guide Documentation, Release 9.0.2
When written in non-prefix form, (~) is treated by GHC as a regular infix operator.
See GHC Proposal #229 for the precise rules.
• Strictness annotations in data declarations must be written in prefix form:
data T = MkT !Int -- accepted by both GHC and the Haskell Report
data T = MkT ! Int -- accepted by the Haskell Report but not GHC
When surrounded by whitespace on both sides, (@) is treated by GHC as a regular infix
operator.
When preceded but not followed by whitespace, (@) is treated as a visible type applica-
tion.
See GHC Proposal #229 for the precise rules.
Context-free syntax
• In Haskell 98 mode and by default (but not in Haskell 2010 mode), GHC is a little less
strict about the layout rule when used in do expressions. Specifically, the restriction that
“a nested context must be indented further to the right than the enclosing context” is
relaxed to allow the nested context to be at the same level as the enclosing context, if
the enclosing context is a do expression.
For example, the following code is accepted by GHC:
let x = 42 in x == 42 == True
because according to the report, the let expression “extends as far to the right as possi-
ble”. Since it can’t extend past the second equals sign without causing a parse error (==
is non-fix), the let-expression must terminate there. GHC simply gobbles up the whole
expression, parsing like this:
(let x = 42 in x == 42 == True)
In its default mode, GHC makes some programs slightly more defined than they should be.
For example, consider
This should call error but actually prints True. Reason: GHC eta-expands f to
This improves efficiency slightly but significantly for most programs, and is bad for only a few.
To suppress this bogus “optimisation” use -fpedantic-bottoms.
In its default mode, GHC does not accept datatype contexts, as it has been decided to remove
them from the next version of the language standard. This behaviour can be controlled with
the DatatypeContexts extension. See Data type contexts (page 283).
The Haskell Report specifies that a group of bindings (at top level, or in a let or where) should
be sorted into strongly-connected components, and then type-checked in dependency order
(Haskell Report, Section 4.5.1). As each group is type-checked, any binders of the group that
have an explicit type signature are put in the type environment with the specified polymorphic
type, and all others are monomorphic until the group is generalised (Haskell Report, Section
4.5.2).
Following a suggestion of Mark Jones, in his paper Typing Haskell in Haskell, GHC implements
a more general scheme. In GHC the dependency analysis ignores references to variables
that have an explicit type signature. As a result of this refined dependency analysis, the
dependency groups are smaller, and more bindings will typecheck. For example, consider:
g y = (y <= y) || f True
This is rejected by Haskell 98, but under Jones’s scheme the definition for g is typechecked
first, separately from that for f, because the reference to f in g‘s right hand side is ignored
by the dependency analysis. Then g‘s type is generalised, to get
g :: Ord a => a -> Bool
Now, the definition for f is typechecked, with this type for g in the type environment.
The same refined dependency analysis also allows the type signatures of mutually-recursive
functions to have different contexts, something that is illegal in Haskell 98 (Section 4.5.2, last
sentence). GHC only insists that the type signatures of a refined group have identical type
signatures; in practice this means that only variables bound by the same pattern binding must
have the same context. For example, this is fine:
f :: Eq a => a -> Bool
f x = (x == x) || g True
GHC will successfully compile this module with ghc -main-is [Link] [Link], be-
cause the default export list will include program rather than main, as the Haskell Report
typically requires.
This change only applies to the main module. Other modules will still export main from a
default export list, regardless of the -main-is flag. This allows use of -main-is with existing
modules that export main via a default export list, even when -main-is points to a different
entry point, as in this example (compiled with -main-is [Link]).
-- file [Link]
module MainWrapper where
import Main
program :: IO ()
program = putStrLn "Redirecting..." >> main
-- file [Link]
main :: IO ()
main = putStrLn "I am main."
GHC requires the use of hs-boot files to cut the recursive loops among mutually recursive
modules as described in How to compile mutually recursive modules (page 181). This more
of an infelicity than a bug: the Haskell Report says (Section 5.7)
“Depending on the Haskell implementation used, separate compilation of mutually
recursive modules may require that imported modules contain additional informa-
tion so that they may be referenced before they are compiled. Explicit type signa-
tures for all exported values may be necessary to deal with mutual recursion. The
precise details of separate compilation are not defined by this Report.”
Num superclasses The Num class does not have Show or Eq superclasses.
You can make code that works with both Haskell98/Haskell2010 and GHC by:
• Whenever you make a Num instance of a type, also make Show and Eq in-
stances, and
• Whenever you give a function, instance or class a Num t constraint, also give
it Show t and Eq t constraints.
Bits superclass The Bits class does not have a Num superclass. It therefore does not have
default methods for the bit, testBit and popCount methods.
You can make code that works with both Haskell 2010 and GHC by:
• Whenever you make a Bits instance of a type, also make a Num instance, and
• Whenever you give a function, instance or class a Bits t constraint, also give
it a Num t constraint, and
• Always define the bit, testBit and popCount methods in Bits instances.
Read class methods The Read class has two extra methods, readPrec and readListPrec,
that are not found in the Haskell 2010 since they rely on the ReadPrec data type, which
requires the RankNTypes (page 342) extension. GHC also derives Read instances by im-
plementing readPrec instead of readsPrec, and relies on a default implementation of
readsPrec that is defined in terms of readPrec. GHC adds these two extra methods
simply because ReadPrec is more efficient than ReadS (the type on which readsPrec is
based).
Monad superclass The Monad class has an Applicative superclass. You cannot write Monad
instances that work for GHC and also for a Haskell 2010 implementation that does not
define Applicative.
Extra instances The following extra instances are defined:
Multiply-defined array elements not checked This code fragment should elicit a fatal er-
ror, but it does not:
GHC’s implementation of array takes the value of an array slot from the last (index,value)
pair in the list, and does no checking for duplicates. The reason for this is efficiency, pure
and simple.
In Prelude support
splitAt semantics [Link] is more strict than specified in the Report. Specifi-
cally, the Report specifies that
Showing records The Haskell 2010 definition of Show stipulates that the rendered string
should only include parentheses which are necessary to unambiguously parse the re-
sult. For historical reasons, Show instances derived by GHC include parentheses around
records despite the fact that record syntax binds more tightly than function application;
e.g.,
-- GHC produces...
show (Just (Hello {aField=42})) == "Just (Hello {aField=42})"
Reading integers GHC’s implementation of the Read class for integral types accepts hex-
adecimal and octal literals (the code in the Haskell 98 report doesn’t). So, for example,
works in GHC.
A possible reason for this is that readLitChar accepts hex and octal escapes, so it seems
inconsistent not to do so for integers too.
isAlpha The Haskell 98 definition of isAlpha is:
GHC’s implementation diverges from the Haskell 98 definition in the sense that Unicode
alphabetic characters which are neither upper nor lower case will still be identified as
alphabetic by isAlpha.
hs_init(), hs_exit() The FFI spec requires the implementation to support re-initialising
itself after being shut down with hs_exit(), but GHC does not currently support that.
See #13693.
Operator sections
The Haskell Report demands that, for infix operators %, the following identities hold:
The operator section is treated like function application of an undefined function, while the
lambda form is in WHNF that contains an application of an undefined function.
This section documents GHC’s take on various issues that are left undefined or implementa-
tion specific in Haskell 98.
Char Following the ISO-10646 standard, maxBound :: Char in GHC is 0x10FFFF.
Int In GHC the Int type follows the size of an address on the host architecture; in other
words it holds 32 bits on a 32-bit machine, and 64-bits on a 64-bit machine.
Arithmetic on Int is unchecked for overflowInt, so all operations on Int happen modulo
2⟨n⟩ where ⟨n⟩ is the size in bits of the Int type.
The fromInteger (and hence also fromIntegral) is a special case when converting to
Int. The value of fromIntegral x :: Int is given by taking the lower ⟨n⟩ bits of (abs
x), multiplied by the sign of x (in 2’s complement ⟨n⟩-bit arithmetic). This behaviour was
chosen so that for example writing 0xffffffff :: Int preserves the bit-pattern in the
resulting Int.
Negative literals, such as -3, are specified by (a careful reading of) the Haskell Re-
port as meaning [Link] ([Link] 3). So -2147483648 means
negate (fromInteger 2147483648). Since fromInteger takes the lower 32 bits of
the representation, fromInteger (2147483648::Integer), computed at type Int is -
2147483648::Int. The negate operation then overflows, but it is unchecked, so negate
(-2147483648::Int) is just -2147483648. In short, one can write minBound::Int as a
literal with the expected meaning (but that is not in general guaranteed).
The fromIntegral function also preserves bit-patterns when converting between the
sized integral types (Int8, Int16, Int32, Int64 and the unsigned Word variants), see the
modules [Link] and [Link] in the library documentation.
Unchecked floating-point arithmetic Operations on Float and Double numbers are
unchecked for overflow, underflow, and other sad occurrences. (note, however, that
some architectures trap floating-point overflow and loss-of-precision and report a
floating-point exception, probably terminating the program)
Large tuple support The Haskell Report only requires implementations to provide tuple
types and their accompanying standard instances up to size 15. GHC limits the size
of tuple types to 62 and provides instances of Eq, Ord, Bounded, Read, Show, and Ix for
tuples up to size 15.
The bug tracker lists bugs that have been reported in GHC but not yet fixed: see the GHC
issue tracker. In addition to those, GHC also has the following known bugs or infelicities.
These bugs are more permanent; it is unlikely that any of them will be fixed in the short term.
• GHC’s runtime system implements cooperative multitasking, with context switching po-
tentially occurring only when a program allocates. This means that programs that do
not allocate may never context switch. This is especially true of programs using STM,
which may deadlock after observing inconsistent state. See #367 for further discussion.
If you are hit by this, you may want to compile the affected module with -fno-omit-
yields (page 111) (see -f*: platform-independent flags (page 105)). This flag ensures
that yield points are inserted at every function entrypoint (at the expense of a bit of
performance).
• GHC does not allow you to have a data type with a context that mentions type variables
that are not data type parameters. For example:
In principle, with a suitable class declaration with a functional dependency, it’s possible
that this type is not ambiguous; but GHC nevertheless rejects it. The type variables
mentioned in the context of the data type declaration must be among the type parameters
of the data type.
• GHC’s inliner can be persuaded into non-termination using the standard way to encode
recursion via a data type:
x :: Bool
x = russel (MkU russel)
with the panic being reported no matter how high a -fsimpl-tick-factor (page 112)
you supply.
We have never found another class of programs, other than this contrived one, that makes
GHC diverge, and fixing the problem would impose an extra overhead on every compi-
lation. So the bug remains un-fixed. There is more background in Secrets of the GHC
inliner.
• On 32-bit x86 platforms when using the native code generator, the -fexcess-precision
(page 108) option is always on. This means that floating-point calculations are non-
deterministic, because depending on how the program is compiled (optimisation set-
tings, for example), certain calculations might be done at 80-bit precision instead of the
intended 32-bit or 64-bit precision. Floating-point results may differ when optimisation
is turned on. In the worst case, referential transparency is violated, because for example
let x = E1 in E2 can evaluate to a different value than E2[E1/x].
One workaround is to use the -msse2 (page 84) option (see Platform-specific Flags
(page 84)), which generates code to use the SSE2 instruction set instead of the x87
instruction set. SSE2 code uses the correct precision for all floating-point operations,
and so gives deterministic results. However, note that this only works with processors
that support SSE2 (Intel Pentium 4 or AMD Athlon 64 and later), which is why the option
is not enabled by default. The libraries that come with GHC are probably built without
this option, unless you built GHC yourself.
• The state hack (page 111) optimization can result in non-obvious changes in evaluation
ordering which may hide exceptions, even with -fpedantic-bottoms (page 111) (see,
e.g., #7411). For instance,
import [Link]
import [Link]
main = do
evaluate (('a' : undefined) `deepseq` return () :: IO ())
putStrLn "Hello"
Compiling this program with -O results in Hello to be printed, despite the fact that
evaluate should have bottomed. Compiling with -O -fno-state-hack results in the
exception one would expect.
• Programs compiled with -fdefer-type-errors (page 88) may fail a bit more eagerly
than one might expect. For instance,
Will emit no output, despite the fact that the ill-typed term appears after the well-typed
putStrLn "Hi there.". See #11197.
• Despite appearances * and Constraint aren’t really distinct kinds in the compiler’s in-
ternal representation and can be unified producing unexpected results. See #11715 for
one example.
• Because of a toolchain limitation we are unable to support full Unicode paths on Windows.
On Windows we support up to Latin-1. See #12971 for more.
• GHCi does not respect the default declaration in the module whose scope you are in.
Instead, for expressions typed at the command line, you always get the default default-
type behaviour; that is, default(Int,Double).
It would be better for GHCi to record what the default settings in each module are, and
use those of the ‘current’ module (whatever that is).
• On Windows, there’s a GNU ld/BFD bug whereby it emits bogus PE object files that have
more than 0xffff relocations. When GHCi tries to load a package affected by this bug,
you get an error message of the form
Loading package javavm ... linking ... WARNING: Overflown relocation field (#␣
,→relocs found: 30765)
The last time we looked, this bug still wasn’t fixed in the BFD codebase, and there wasn’t
any noticeable interest in fixing it when we reported the bug back in 2001 or so.
The workaround is to split up the .o files that make up your package into two or more
.o’s, along the lines of how the base package does it.
FIFTEEN
EVENTLOG ENCODINGS
This section documents the encodings of the events emitted to GHC’s event log (page 170).
These events can include information about the thread scheduling events, garbage collection
statistics, profiling information, user-defined tracing events.
This section is intended for implementors of tooling which consume these events. GHC ships
with a C header file (EventlogFormat.h) which provides symbolic names for the event type
IDs described in this file.
The log format is designed to be extensible: old tools should be able to parse (but not neces-
sarily understand all of) new versions of the format, and new tools will be able to understand
old log files.
• The format is endian-independent: all values are represented in big-endian order.
• The format is extensible:
– The header describes each event type and its length. Tools that don’t recognise a
particular event type can skip those events.
– There is room for extra information in the event type specification, which can be
ignored by older tools.
– Events can have extra information added, but existing fields cannot be changed.
Tools should ignore extra fields at the end of the event record.
The event-log stream begins with a header describing the event types present in the file.
The header is followed by the event records themselves, each of which consist of a 64-bit
timestamp
log : EVENT_HEADER_BEGIN
EventType*
EVENT_HEADER_END
EVENT_DATA_BEGIN
Event*
EVENT_DATA_END
EventType :
EVENT_ET_BEGIN
Word16 -- unique identifier for this event
Int16 -- >=0 size of the event in bytes (minus the header)
-- -1 variable size
Word32 -- length of the next field in bytes
613
GHC User’s Guide Documentation, Release 9.0.2
Event :
Word16 -- event_type
Word64 -- time (nanosecs)
[Word16] -- length of the rest (for variable-sized events only)
... extra event-specific info ...
• ThreadId ~ Word32
• CapNo ~ Word16
• CapSetId ~ Word32
TODO
These events are typically produced during program startup and describe the environment
which the program is being run in.
RTS_IDENTIFIER
Tag 29
Length variable
Field CapSetId Capability set
Field String Runtime system name and version.
Describes the name and version of the runtime system responsible for the indicated
capability set.
PROGRAM_ARGS
Tag 30
Length variable
Field CapSetId Capability set
Field [String] The command-line arguments passed to the program
Describes the command-line used to start the program.
PROGRAM_ENV
Tag 31
Length variable
Field CapSetId Capability set
Field [String] The environment variable name/value pairs. (TODO: encod-
ing?)
Describes the environment variables present in the program’s environment.
CREATE_THREAD
Tag 0
Length fixed
Field ThreadId thread id
Marks the creation of a Haskell thread.
RUN_THREAD
Tag 1
Length fixed
Field ThreadId thread id
The indicated thread has started running.
STOP_THREAD
Tag 2
Length fixed
Field ThreadId thread id
Field Word16 status
• 1: HeapOverflow
• 2: StackOverflow
• 3: ThreadYielding
• 4: ThreadBlocked
• 5: ThreadFinished
• 6: ForeignCall
• 7: BlockedOnMVar
• 8: BlockedOnBlackHole
• 9: BlockedOnRead
• 10: BlockedOnWrite
• 11: BlockedOnDelay
• 12: BlockedOnSTM
• 13: BlockedOnDoProc
• 16: BlockedOnMsgThrowTo
Field ThreadId thread id of thread being blocked on (only for some status val-
ues)
The indicated thread has stopped running for the reason given by status.
THREAD_RUNNABLE
Tag 3
Length fixed
Field ThreadId thread id
The indicated thread is has been marked as ready to run.
MIGRATE_THREAD
Tag 4
Length fixed
Field ThreadId thread id
Field CapNo capability
The indicated thread has been migrated to a new capability.
THREAD_WAKEUP
Tag 8
Length fixed
Field ThreadId thread id
Field CapNo other capability
The indicated thread has been woken up on another capability.
THREAD_LABEL
Tag 44
Length fixed
Field ThreadId thread id
Field String label
The indicated thread has been given a label (e.g. with Con-
[Link]).
GC_START
Tag 9
Length fixed
A garbage collection pass has been started.
GC_END
Tag 10
Length fixed
A garbage collection pass has been finished.
REQUEST_SEQ_GC
Tag 11
Length fixed
A sequential garbage collection has been requested by a capability.
REQUEST_PAR_GC
Tag 12
Length fixed
A parallel garbage collection has been requested by a capability.
GC_IDLE
Tag 20
Length fixed
An idle-time garbage collection has been started.
GC_WORK
Tag 21
Length fixed
Marks the start of concurrent scavenging.
GC_DONE
Tag 22
Length fixed
Marks the end of concurrent scavenging.
GC_STATS_GHC
Tag 53
Length fixed
Field CapSetId heap capability set
Field Word16 generation of collection
Field Word64 bytes copied
Field Word64 bytes of slop found
Field Word64 TODO
Field Word64 number of parallel garbage collection threads
Field Word64 maximum number of bytes copied by any single collector thread
Field Word64 total bytes copied by all collector threads
Report various information about the heap configuration. Typically produced during RTS
initialization..
GC_GLOBAL_SYNC
Tag 54
Length fixed
TODO
HEAP_ALLOCATED
Tag 49
Length fixed
Field CapSetId heap capability set
Field Word64 allocated bytes
A new chunk of heap has been allocated by the indicated capability set.
HEAP_SIZE
Tag 50
Length fixed
Field CapSetId heap capability set
Field Word64 heap size in bytes
Report the heap size.
HEAP_LIVE
Tag 51
Length fixed
Field CapSetId heap capability set
Field Word64 heap size in bytes
Report the live heap size.
HEAP_INFO_GHC
Tag 52
Length fixed
Field CapSetId heap capability set
Field Word16 number of garbage collection generations
Field Word64 maximum heap size
Field Word64 allocation area size
Field Word64 MBlock size
Field Word64 Block size
Report various information about the heap configuration. Typically produced during RTS
initialization..
CREATE_SPARK_THREAD
Tag 15
Length fixed
A thread has been created to perform spark evaluation.
SPARK_COUNTERS
Tag 34
Length fixed
A periodic reporting of various statistics of spark evaluation.
SPARK_CREATE
Tag 35
Length fixed
A spark has been added to the spark pool.
SPARK_DUD
Tag 36
Length fixed
TODO
SPARK_OVERFLOW
Tag 37
Length fixed
TODO
SPARK_RUN
Tag 38
Length fixed
Evaluation has started on a spark.
SPARK_STEAL
Tag 39
Length fixed
Field Word16 capability from which the spark was stolen
A spark has been stolen from another capability for evaluation.
SPARK_FIZZLE
Tag 40
Length fixed
A spark has been GC’d before being evaluated.
SPARK_GC
Tag 41
Length fixed
An unevaluated spark has been garbage collected.
CAP_CREATE
Tag 45
Length fixed
Field CapNo the capability number
A capability has been started.
CAP_DELETE
Tag 46
Length fixed
A capability has been deleted.
CAP_DISABLE
Tag 47
Length fixed
A capability has been disabled.
CAP_ENABLE
Tag 48
Length fixed
A capability has been enabled.
TASK_CREATE
Tag 55
Length fixed
Field TaskId task id
Field CapNo capability number
Field ThreadId TODO
Marks the creation of a task.
TASK_MIGRATE
Tag 56
Length fixed
Field TaskId task id
Field CapNo old capability
Field CapNo new capability
LOG_MSG
Tag 16
Length variable
Field String The message
A log message from the runtime system.
BLOCK_MARKER
Tag 18
Length variable
Field Word32 size
Field Word64 end time in nanoseconds
Field String marker name
TODO
USER_MSG
Tag 19
Length variable
Field String message
A user log message (from, e.g., [Link]).
USER_MARKER
Tag 58
Length variable
Field String marker name
A user marker (from [Link]).
The heap profiler can produce output to GHC’s event log, allowing samples to be correlated
with other event log events over the program’s lifecycle.
This section defines the layout of these events. The String type below is defined to be a
UTF-8 encoded NUL-terminated string.
A single fixed-width event emitted during program start-up describing the samples that follow.
HEAP_PROF_BEGIN
Tag 160
Length variable
Field Word8 profile ID
Field Word64 sampling period in nanoseconds
Field Word32 sample breadown type. One of,
• HEAP_PROF_BREAKDOWN_COST_CENTER (output from -hc (page 563))
• HEAP_PROF_BREAKDOWN_CLOSURE_DESCR (output from -hd (page 563))
• HEAP_PROF_BREAKDOWN_RETAINER (output from -hr (page 563))
• HEAP_PROF_BREAKDOWN_MODULE (output from -hm (page 563))
• HEAP_PROF_BREAKDOWN_TYPE_DESCR (output from -hy (page 563))
• HEAP_PROF_BREAKDOWN_BIOGRAPHY (output from -hb (page 563))
• HEAP_PROF_BREAKDOWN_CLOSURE_TYPE (output from -hT (page 170))
Field String module filter
Field String closure description filter
Field String type description filter
Field String cost centre filter
Field String cost centre stack filter
Field String retainer filter
Field String biography filter
A sample (consisting of a list of break-down classes, e.g. cost centres, and heap residency
sizes), is to be encoded in the body of one or more events.
We normally mark the beginning of a new sample with an EVENT_HEAP_PROF_SAMPLE_BEGIN
event,
HEAP_PROF_SAMPLE_BEGIN
Length fixed
Field Word64 sample number
Marks the beginning of a heap profile sample.
Biographical profiling samples start with the EVENT_HEAP_BIO_PROF_SAMPLE_BEGIN event.
These events also include a timestamp which indicates when the sample was taken. This
is because all these samples will appear at the end of the eventlog due to how the biograph-
ical profiling mode works. You can use the timestamp to reorder the samples relative to the
other events.
HEAP_BIO_PROF_SAMPLE_BEGIN
Tag 166
Length fixed
Field Word64 sample number
Field Word64 eventlog timestamp in ns
A heap residency census will follow. Since events may only be up to 2^16^ bytes in length
a single sample may need to be split among multiple EVENT_HEAP_PROF_SAMPLE events. The
precise format of the census entries is determined by the break-down type.
At the end of the sample period the EVENT_HEAP_PROF_SAMPLE_END event if emitted. This is
useful to properly delimit the sampling period and to record the total time spent profiling.
HEAP_PROF_SAMPLE_END
Tag 165
Length fixed
Field Word64 sample number
Marks the end of a heap profile sample.
Cost-centre break-down
Field Word32[] cost centre stack starting with inner-most (cost centre num-
bers)
String break-down
The time profiling mode enabled by -p (page 558) also emits sample events to the eventlog.
At the start of profiling the tick interval is emitted to the eventlog and then on each tick the
current cost centre stack is emitted. Together these enable a user to construct an approximate
track of the executation of their program.
PROF_BEGIN
Tag 168
Length fixed
Field Word64 tick interval, in nanoseconds
Marks the beginning of a time profile.
Field Word32[] cost centre stack starting with inner-most (cost centre num-
bers)
These events mark various stages of the non-moving collection (page 160) lifecycle. These
are enabled with the +RTS -lg event-set.
CONC_MARK_BEGIN
Tag 200
Length fixed
Marks the beginning of marking by the concurrent collector.
CONC_MARK_END
Tag 201
Length fixed
Marks the end of marking by the concurrent collector.
CONC_SYNC_BEGIN
Tag 202
Length fixed
Marks the beginning of the concurrent garbage collector’s post-mark synchronization
phase.
CONC_SYNC_END
Tag 203
Length fixed
Marks the end of the concurrent garbage collector’s post-mark synchronization phase.
CONC_SWEEP_BEGIN
Tag 204
Length fixed
Marks the beginning of the concurrent garbage collector’s sweep phase.
CONC_SWEEP_END
Tag 205
Length fixed
Marks the end of the concurrent garbage collector’s sweep phase.
CONC_UPD_REM_SET_FLUSH
Tag 206
Length fixed
Marks a capability flushing its local update remembered set accumulator.
The non-moving heap census events (enabled with the +RTS -ln event-set) are intended to
provide insight into fragmentation of the non-moving heap.
NONMOVING_HEAP_CENSUS
Tag 207
Length fixed
Field Word8 base-2 logarithm of blk_sz.
Field Word32 number of active segments.
Field Word32 number of filled segments.
Field Word32 number of live blocks.
Describes the occupancy of the blk_sz sub-heap.
SIXTEEN
The GHC User’s Guide is the primary reference documentation for the Glasgow Haskell Com-
piler. Even more than this, it at times serves (for better or for worse) as a de-facto language
standard, being the sole non-academic reference for many widely used language extensions.
Since GHC 8.0, the User’s Guide is authored in ReStructuredText (or ReST or RST, for short)
a rich but light-weight mark-up language aimed at producing documentation. The Sphinx tool
is used to produce the final PDF and HTML documentation.
This document (also written in ReST) serves as a brief introduction to ReST and to document
the conventions used in the User’s Guide. This document is not intended to be a thorough
guide to ReST. For this see the resources referenced below (page ??).
16.1 Basics
a. Followed by a sub-item
b. And another!
c. Now with ``a bit of code`` and some *emphasis*.
* Foo
* Fizzle
- Bar
- Blah
*Chelonii*
The taxonomic order consisting of modern turtles
627
GHC User’s Guide Documentation, Release 9.0.2
*Meiolaniidae*
The taxonomic order of an extinct variety of herbivorous turtles.
Note the blank lines between a list item and its sub-items. Sub-items should be on the same in-
dentation level as the content of their parent items. Also note that no whitespace is necessary
or desirable before the bullet or item number (lest the list be indented unnecessarily).
The above would be rendered as,
This is a paragraph containing a few sentences of text. Purple turtles walk through
green fields of lofty maize. Lorem ipsum dolor sit amet, consectetur adipiscing elit.
Some lists,
1. This is a list item
(a) Followed by a sub-item
(b) And another!
(c) Now with a bit of code and some emphasis.
2. Back to the first list
Or perhaps you are more of a bullet list person,
• Foo
• Fizzle
– Bar
– Blah
Or perhaps a definition list is in order,
Chelonii The taxonomic order consisting of modern turtles
Meiolaniidae The taxonomic order of an extinct variety of herbivorous turtles.
16.1.1 Headings
While ReST can accommodate a wide range of heading styles, we have standardized on this
convention in the User’s Guide,
Header level 1
==============
Header level 2
--------------
Header level 3
~~~~~~~~~~~~~~
Header level 4
^^^^^^^^^^^^^^
628 Chapter 16. Care and feeding of your GHC User’s Guide
GHC User’s Guide Documentation, Release 9.0.2
Haskell
Code snippets can be included as both inline and block elements. Inline code is denoted with
double-backticks whereas block of code are introduced by ending a paragraph with double-
colons and indentation,
Other languages
Double-colon blocks are syntax-highlighted as Haskell by default. To avoid this use a .. code-
block directive with explicit language designation,
.. code-block:: sh
#!/bin/bash
echo "Hello World!"
16.1.3 Links
Frequently we want to give a name to a section so it can be referred to from other points in
the document,
.. _options-platform:
Platform-specific Flags
-----------------------
To GHC resources
There are special macros for conveniently linking to GHC Wiki articles and tickets,
See the :ghc-ticket:`this bug <123>` for what happens when this fails.
To external resources
It is often useful to be able to refer to the Haddock documentation of the libraries shipped
with GHC. The users guide’s build system provides commands for referring to documentation
for the following core GHC packages,
• base: :base-ref:
• cabal: :cabal-ref:
• ghc-prim: :ghc-prim-ref:
These are defined in docs/users_guide/ghc_config.[Link].
For instance,
Math
630 Chapter 16. Care and feeding of your GHC User’s Guide
GHC User’s Guide Documentation, Release 9.0.2
Index entries can be included anywhere in the document as a block element. They look like,
.. index::
single: strict haskell
single: language extensions; StrictData
This would produce two entries in the index referring to the “Strict Haskell” section. One
would be a simple “strict haskell” heading whereas the other would be a “StrictData” sub-
heading under “language extensions”.
Sadly it is not possible to use inline elements (e.g. monotype inlines) inside index headings.
16.2 Citations
16.3 Admonitions
Admonitions are block elements used to draw the readers attention to a point. They should
not be over-used for the sake of readability but they can be quite effective in separating and
drawing attention to points of importance,
.. important::
[Link] defines a few Sphinx object types for GHCi commands (ghci-cmd), ghc command-line
options (ghc-flag), and runtime :system options (rts-flag),
The ghc-flag and rts-flag roles/directives can be used to document command-line argu-
ments to the ghc executable and runtime system, respectively. For instance,
.. rts-flag:: -C ⟨seconds⟩
:since: 8.2
:default: 20 milliseconds
.. ghc-flag:: -fasm
:shortdesc: Use the native code generator
:type: dynamic
:reverse: -fllvm
:category: codegen
Regular description...
When rendered, the extra parameters will be hidden, and the data stored for later use. For
more details, see the Sphinx extension [Link].
Note that, as in Style Conventions below, we use ⟨⟩ instead of less-than/greater-than signs.
To reference a ghc-flag or rts-flag, you must match the definition exactly, including the
arguments. A quick way to find the exact names and special characters is,
632 Chapter 16. Care and feeding of your GHC User’s Guide
GHC User’s Guide Documentation, Release 9.0.2
The ghci-cmd role and directive can be used to document GHCi directives. For instance, we
can describe the GHCi :module command,
Load a module
Like command-line options, GHCi commands will have associated index entries generated
automatically.
When describing user commands and the like it is common to need to denote user-
substitutable tokens. In this document we use the convention, ⟨subst⟩ (note that these are
angle brackets, U+27E8 and U+27E9, not less-than/greater-than signs).
634 Chapter 16. Care and feeding of your GHC User’s Guide
CHAPTER
SEVENTEEN
• genindex
• search
635
GHC User’s Guide Documentation, Release 9.0.2
637
GHC User’s Guide Documentation, Release 9.0.2
638 Bibliography
INDEX
639
GHC User’s Guide Documentation, Release 9.0.2
640 Index
GHC User’s Guide Documentation, Release 9.0.2
Index 641
GHC User’s Guide Documentation, Release 9.0.2
-Wmonomorphism-restriction -Wunsupported-calling-conventions
GHC option, 99 GHC option, 91
-Wname-shadowing -Wunsupported-llvm-version
GHC option, 97 GHC option, 99
-Wno-compat -Wunticked-promoted-constructors
GHC option, 87 GHC option, 99
-Wnoncanonical-monad-instances -Wunused-binds
GHC option, 90 GHC option, 100
-Wnoncanonical-monadfail-instances -Wunused-do-bind
GHC option, 90 GHC option, 101
-Wnoncanonical-monoid-instances -Wunused-foralls
GHC option, 91 GHC option, 102
-Worphans -Wunused-imports
GHC option, 97 GHC option, 101
-Woverflowed-literals -Wunused-local-binds
GHC option, 92 GHC option, 100
-Woverlapping-patterns -Wunused-matches
GHC option, 97 GHC option, 101
-Wpartial-fields -Wunused-packages
GHC option, 103 GHC option, 103
-Wpartial-type-signatures -Wunused-pattern-binds
GHC option, 89 GHC option, 100
-Wredundant-constraints -Wunused-record-wildcards
GHC option, 93 GHC option, 102
-Wredundant-record-wildcards -Wunused-top-binds
GHC option, 102 GHC option, 100
-Wsafe -Wunused-type-patterns
GHC option, 503 GHC option, 101
-Wsemigroup -Wwarn
GHC option, 91 GHC option, 87
-Wsimplifiable-class-constraints -Wwarnings-deprecations
GHC option, 99 GHC option, 90
-Wstar-binder -Wwrong-do-bind
GHC option, 98 GHC option, 102
-Wstar-is-type -XUndecidableInstances, 413
GHC option, 98 -Z
-Wtabs RTS option, 173
GHC option, 99 -b
-Wtrustworthy-safe hp2ps command line option, 567
GHC option, 503 -c, 79
-Wtype-defaults GHC option, 76, 217
GHC option, 99 hp2ps command line option, 567
-Wtyped-holes RTS option, 162
GHC option, 88 -c ⟨n⟩
-Wunbanged-strict-patterns RTS option, 162
GHC option, 103 -clear-package-db
-Wunicode-bidirectional-format-characters GHC option, 198
GHC option, 104 -cpp
-Wunrecognised-pragmas GHC option, 213
GHC option, 89 -cpp vs string gaps, 215
-Wunrecognised-warning-flags -d
GHC option, 88 hp2ps command line option, 566
-Wunsafe -dcmm-lint
GHC option, 503 GHC option, 234
642 Index
GHC User’s Guide Documentation, Release 9.0.2
-dcore-lint -ddump-core-stats
GHC option, 234 GHC option, 229
-ddump-asm -ddump-cpr-signatures
GHC option, 232 GHC option, 230
-ddump-asm-expanded -ddump-cpranal
GHC option, 232 GHC option, 230
-ddump-asm-liveness -ddump-cse
GHC option, 232 GHC option, 230
-ddump-asm-native -ddump-deriv
GHC option, 232 GHC option, 228
-ddump-asm-regalloc -ddump-ds
GHC option, 232 GHC option, 229
-ddump-asm-regalloc-stages -ddump-ds-preopt
GHC option, 232 GHC option, 229
-ddump-asm-stats -ddump-ec-trace
GHC option, 232 GHC option, 228
-ddump-bcos -ddump-file-prefix=⟨str⟩
GHC option, 232 GHC option, 227
-ddump-cfg-weights -ddump-foreign
GHC option, 231 GHC option, 232
-ddump-cmm -ddump-hi
GHC option, 231 GHC option, 179
-ddump-cmm-caf -ddump-hi-diffs, 584
GHC option, 231 GHC option, 179
-ddump-cmm-cbe -ddump-hie
GHC option, 231 GHC option, 228
-ddump-cmm-cfg -ddump-hpc
GHC option, 231 GHC option, 232
-ddump-cmm-cps -ddump-if-trace
GHC option, 231 GHC option, 228
-ddump-cmm-from-stg -ddump-inlinings
GHC option, 231 GHC option, 230
-ddump-cmm-info -ddump-json
GHC option, 231 GHC option, 227
-ddump-cmm-opt -ddump-llvm
GHC option, 232 GHC option, 231
-ddump-cmm-proc -ddump-minimal-imports
GHC option, 231 GHC option, 180
-ddump-cmm-procmap -ddump-mod-cycles
GHC option, 231 GHC option, 191
-ddump-cmm-raw -ddump-mod-map
GHC option, 231 GHC option, 232
-ddump-cmm-sink -ddump-occur-anal
GHC option, 231 GHC option, 230
-ddump-cmm-sp -ddump-opt-cmm
GHC option, 231 GHC option, 232
-ddump-cmm-split -ddump-parsed
GHC option, 231 GHC option, 227
-ddump-cmm-switch -ddump-parsed-ast
GHC option, 231 GHC option, 228
-ddump-cmm-verbose -ddump-prep
GHC option, 231 GHC option, 230
-ddump-cmm-verbose-by-proc -ddump-rn
GHC option, 230 GHC option, 228
Index 643
GHC User’s Guide Documentation, Release 9.0.2
644 Index
GHC User’s Guide Documentation, Release 9.0.2
Index 645
GHC User’s Guide Documentation, Release 9.0.2
646 Index
GHC User’s Guide Documentation, Release 9.0.2
Index 647
GHC User’s Guide Documentation, Release 9.0.2
648 Index
GHC User’s Guide Documentation, Release 9.0.2
-include-pkg-deps -msse4.2
GHC option, 191 GHC option, 84
-interactive-print ⟨name⟩ -m⟨int⟩
GHC option, 38 hp2ps command line option, 567
-i⟨dir⟩[:⟨dir⟩]* -n ⟨size⟩
GHC option, 176 RTS option, 161
-j[⟨n⟩] -no-auto-link-packages
GHC option, 78 GHC option, 196
-kb ⟨size⟩ -no-global-package-db
RTS option, 165 GHC option, 198
-kc ⟨size⟩ -no-hs-main
RTS option, 164 GHC option, 219
-keep-hc-file -no-rtsopts-suggestions
GHC option, 179 GHC option, 221
-keep-hc-files -no-user-package-db
GHC option, 179 GHC option, 198
-keep-hi-files -o ⟨file⟩
GHC option, 179 GHC option, 176
-keep-hscpp-file -odir ⟨dir⟩
GHC option, 179 GHC option, 177
-keep-hscpp-files -ohi ⟨file⟩
GHC option, 179 GHC option, 177
-keep-llvm-file -ol ⟨filename⟩
GHC option, 179 RTS option, 171
-keep-llvm-files -optF ⟨option⟩
GHC option, 179 GHC option, 212
-keep-o-files -optL ⟨option⟩
GHC option, 179 GHC option, 212
-keep-s-file -optP ⟨option⟩
GHC option, 179 GHC option, 212
-keep-s-files -opta ⟨option⟩
GHC option, 179 GHC option, 212
-keep-tmp-files -optc ⟨option⟩
GHC option, 179 GHC option, 212
-ki ⟨size⟩ -optcxx ⟨option⟩
RTS option, 164 GHC option, 212
-l -optdll ⟨option⟩
hp2ps command line option, 567 GHC option, 212
-l ⟨flags⟩ -opti ⟨option⟩
RTS option, 170 GHC option, 212
-l ⟨lib⟩ -optl ⟨option⟩
GHC option, 217 GHC option, 212
-m ⟨n⟩ -optlc ⟨option⟩
RTS option, 165 GHC option, 212
-m\* options, 84 -optlm ⟨option⟩
-main-is ⟨thing⟩ GHC option, 212
GHC option, 219 -optlo ⟨option⟩
-maxN ⟨x⟩ GHC option, 212
RTS option, 118 -optwindres ⟨option⟩
-mbmi2 GHC option, 212
GHC option, 85 -osuf ⟨suffix⟩
-msse2 GHC option, 178
GHC option, 84 -outputdir ⟨dir⟩
-msse2 option, 611 GHC option, 178
Index 649
GHC User’s Guide Documentation, Release 9.0.2
650 Index
GHC User’s Guide Documentation, Release 9.0.2
Index 651
GHC User’s Guide Documentation, Release 9.0.2
652 Index
GHC User’s Guide Documentation, Release 9.0.2
Index 653
GHC User’s Guide Documentation, Release 9.0.2
654 Index
GHC User’s Guide Documentation, Release 9.0.2
Index 655
GHC User’s Guide Documentation, Release 9.0.2
656 Index
GHC User’s Guide Documentation, Release 9.0.2
-Wdodgy-foreign-imports, 92 -Wtabs, 99
-Wdodgy-imports, 92 -Wtrustworthy-safe, 503
-Wduplicate-constraints, 93 -Wtype-defaults, 99
-Wduplicate-exports, 93 -Wtyped-holes, 88
-Wempty-enumerations, 92 -Wunbanged-strict-patterns, 103
-Werror, 87 -Wunicode-bidirectional-format-
-Weverything, 87 characters, 104
-Whi-shadowing, 93 -Wunrecognised-pragmas, 89
-Widentities, 94 -Wunrecognised-warning-flags, 88
-Wimplicit-kind-vars, 94 -Wunsafe, 503
-Wimplicit-prelude, 94 -Wunsupported-calling-conventions, 91
-Winaccessible-code, 97 -Wunsupported-llvm-version, 99
-Wincomplete-patterns, 94 -Wunticked-promoted-constructors, 99
-Wincomplete-record-updates, 95 -Wunused-binds, 100
-Wincomplete-uni-patterns, 94 -Wunused-do-bind, 101
-Winferred-safe-imports, 503 -Wunused-foralls, 102
-Winline-rule-shadowing, 103 -Wunused-imports, 101
-Winvalid-haddock, 103 -Wunused-local-binds, 100
-Wmissed-extra-shared-lib, 99 -Wunused-matches, 101
-Wmissed-specialisations, 89 -Wunused-packages, 103
-Wmissing-deriving-strategies, 95 -Wunused-pattern-binds, 100
-Wmissing-export-lists, 95 -Wunused-record-wildcards, 102
-Wmissing-exported-signatures, 96 -Wunused-top-binds, 100
-Wmissing-exported-sigs, 96 -Wunused-type-patterns, 101
-Wmissing-fields, 95 -Wwarn, 87
-Wmissing-home-modules, 103 -Wwarnings-deprecations, 90
-Wmissing-import-lists, 96 -Wwrong-do-bind, 102
-Wmissing-local-signatures, 96 -c, 76, 217
-Wmissing-local-sigs, 96 -clear-package-db, 198
-Wmissing-methods, 96 -cpp, 213
-Wmissing-monadfail-instances, 91 -dcmm-lint, 234
-Wmissing-pattern-synonym-signatures, -dcore-lint, 234
97 -ddump-asm, 232
-Wmissing-safe-haskell-mode, 503 -ddump-asm-expanded, 232
-Wmissing-signatures, 96 -ddump-asm-liveness, 232
-Wmissing-space-after-bang, 104 -ddump-asm-native, 232
-Wmonomorphism-restriction, 99 -ddump-asm-regalloc, 232
-Wname-shadowing, 97 -ddump-asm-regalloc-stages, 232
-Wno-compat, 87 -ddump-asm-stats, 232
-Wnoncanonical-monad-instances, 90 -ddump-bcos, 232
-Wnoncanonical-monadfail-instances, 90 -ddump-cfg-weights, 231
-Wnoncanonical-monoid-instances, 91 -ddump-cmm, 231
-Worphans, 97 -ddump-cmm-caf, 231
-Woverflowed-literals, 92 -ddump-cmm-cbe, 231
-Woverlapping-patterns, 97 -ddump-cmm-cfg, 231
-Wpartial-fields, 103 -ddump-cmm-cps, 231
-Wpartial-type-signatures, 89 -ddump-cmm-from-stg, 231
-Wredundant-constraints, 93 -ddump-cmm-info, 231
-Wredundant-record-wildcards, 102 -ddump-cmm-opt, 232
-Wsafe, 503 -ddump-cmm-proc, 231
-Wsemigroup, 91 -ddump-cmm-procmap, 231
-Wsimplifiable-class-constraints, 99 -ddump-cmm-raw, 231
-Wstar-binder, 98 -ddump-cmm-sink, 231
-Wstar-is-type, 98 -ddump-cmm-sp, 231
Index 657
GHC User’s Guide Documentation, Release 9.0.2
658 Index
GHC User’s Guide Documentation, Release 9.0.2
Index 659
GHC User’s Guide Documentation, Release 9.0.2
660 Index
GHC User’s Guide Documentation, Release 9.0.2
Index 661
GHC User’s Guide Documentation, Release 9.0.2
662 Index
GHC User’s Guide Documentation, Release 9.0.2
Index 663
GHC User’s Guide Documentation, Release 9.0.2
664 Index
GHC User’s Guide Documentation, Release 9.0.2
Index 665
GHC User’s Guide Documentation, Release 9.0.2
NumericUnderscores PartialTypeSignatures
Language Extension, 420 Language Extension, 444
PATH, 199, 216
object files, 175 patterns, incomplete, 94
old generation, size, 161 patterns, overlapping, 97
optimisation, 104 PatternSynonyms
optimise Language Extension, 392
aggressively, 105 phantom
normally, 105 role, 353
optimization platform-specific options, 84
and GHCi, 68 PolyKinds
options Language Extension, 319
for profiling, 557 PostfixOperators
GHCi, 63 Language Extension, 261
language, 237 postscript, from heap profiles, 566
OPTIONS_GHC pragma, 518
pragma, 518 ANN, 531
orphan instances, warning, 97 COLUMN, 524
orphan rules, warning, 97 COMPLETE, 529
OutOfHeapHook (C function), 157 CONLIKE, 523
output-directing options, 176 DEPRECATED, 519
OVERLAPPABLE, 530 INCOHERENT, 530
pragma, 530 INLINABLE, 522
OVERLAPPING, 530 INLINE, 521
pragma, 530 LANGUAGE, 518
overlapping patterns, warning, 97 LINE, 524
OverlappingInstances MINIMAL, 520
Language Extension, 414 NOINLINE, 523
OVERLAPS, 530 NOUNPACK, 528
pragma, 530 OPTIONS_GHC, 518
OverloadedLabels OVERLAPPABLE, 530
Language Extension, 423 OVERLAPPING, 530
OverloadedLists OVERLAPS, 530
Language Extension, 257 RULES, 504
OverloadedStrings SOURCE, 529
Language Extension, 422 SPECIALIZE, 525
overloading, death to, 525, 527, 586 SPECIALIZE-INLINE, 526
SPECIALIZE-instance, 527
package environments, 199 UNPACK, 528
package trust, 501 WARNING, 519
package-url pragma, SPECIALIZE, 525
package specification, 207 pre-processing: cpp, 213
PackageImports pre-processing: custom, 215
Language Extension, 281 pre-processor options, 215
packages, 193 problems, 583
building, 204 problems running your program, 584
management, 202 problems with the compiler, 583
using, 193 proc, 241
with GHCi, 50 PROF_BEGIN
parallel list comprehensions, 252 eventlog event type, 624
parallelism, 118, 468 PROF_SAMPLE_COST_CENTRE
ParallelListComp eventlog event type, 624
Language Extension, 252 profiling, 553
parser generator for Haskell, 591 options, 557
666 Index
GHC User’s Guide Documentation, Release 9.0.2
Index 667
GHC User’s Guide Documentation, Release 9.0.2
668 Index
GHC User’s Guide Documentation, Release 9.0.2
SPARK_CREATE StrictData
eventlog event type, 619 Language Extension, 463
SPARK_DUD string gaps vs -cpp., 215
eventlog event type, 619 structure, command-line, 74
SPARK_FIZZLE suffixes, file, 75
eventlog event type, 619 suppression
SPARK_GC of unwanted dump output, 233
eventlog event type, 619
SPARK_OVERFLOW tabs, warning, 99
eventlog event type, 619 TASK_CREATE
SPARK_RUN eventlog event type, 620
eventlog event type, 619 TASK_MIGRATE
SPARK_STEAL eventlog event type, 620
eventlog event type, 619 Template Haskell, 242
SPECIALIZE TemplateHaskell
pragma, 525 Language Extension, 450
SPECIALIZE pragma, 525, 586 TemplateHaskellQuotes
SPECIALIZE-INLINE Language Extension, 450
pragma, 526 temporary files
SPECIALIZE-instance keeping, 179
pragma, 527 redirecting, 179
specifying your own main function, 219 This macro exposes the full version string.,
SQL, 252 214
stability THREAD_LABEL
package specification, 207 eventlog event type, 616
stack THREAD_RUNNABLE
chunk buffer size, 165 eventlog event type, 616
chunk size, 165 THREAD_WAKEUP
stack, initial size, 164 eventlog event type, 616
stack, maximum size, 165 ticky ticky profiling, 172
StackOverflowHook (C function), 157 ticky-ticky profiling, 575
standalone kind signature, 324 time profile, 558
StandaloneDeriving TMPDIR, 179
Language Extension, 368 TMPDIR environment variable, 179
StandaloneKindSignatures tracing, 170
Language Extension, 324 TransformListComp
StarIsType Language Extension, 252
Language Extension, 331 trust, 498
startEventLogging (C function), 158 trust check, 499
startup trusted
files, GHCi, 65, 67 package specification, 208
statements Trustworthy
in GHCi, 28 Language Extension, 502
static trustworthy, 501
options, 64 TupleSections
Static pointers, 470 Language Extension, 261
StaticPointers TYPE, 334
Language Extension, 470 Type defaulting
STOP_THREAD in GHCi, 36
eventlog event type, 615 Type equality constraints
Strict kind heterogeneous, 425
Language Extension, 464 type patterns, unused, 101
strict constructor fields, 115, 116 type signatures, missing, 96, 97
strict haskell, 461
Index 669
GHC User’s Guide Documentation, Release 9.0.2
670 Index