diff options
author | Ben Gamari <ben@smart-cactus.org> | 2016-01-09 04:38:16 +0100 |
---|---|---|
committer | Ben Gamari <ben@smart-cactus.org> | 2016-01-09 04:38:54 +0100 |
commit | a6c3289d0aa0c520656e918dfc9f152548d940a4 (patch) | |
tree | 1c5aa8a05bec7dc626ce1b9c27163e93665db95d /docs | |
parent | 1cdf12c4f435262b93cb0173f9872f3f0f0da60a (diff) | |
download | haskell-a6c3289d0aa0c520656e918dfc9f152548d940a4.tar.gz |
users_guide: Use semantic directive/role for command line options
And GHCi commands. This makes cross-referencing much easier.
Also normalize markup a bit and add some missing flags.
Diffstat (limited to 'docs')
-rw-r--r-- | docs/users_guide/8.0.1-notes.rst | 4 | ||||
-rw-r--r-- | docs/users_guide/bugs.rst | 83 | ||||
-rw-r--r-- | docs/users_guide/conf.py | 49 | ||||
-rw-r--r-- | docs/users_guide/debugging.rst | 227 | ||||
-rw-r--r-- | docs/users_guide/editing-guide.rst | 67 | ||||
-rw-r--r-- | docs/users_guide/extending_ghc.rst | 50 | ||||
-rw-r--r-- | docs/users_guide/ffi-chap.rst | 40 | ||||
-rw-r--r-- | docs/users_guide/ghci.rst | 156 | ||||
-rw-r--r-- | docs/users_guide/glasgow_exts.rst | 3348 | ||||
-rw-r--r-- | docs/users_guide/packages.rst | 208 | ||||
-rw-r--r-- | docs/users_guide/phases.rst | 346 | ||||
-rw-r--r-- | docs/users_guide/profiling.rst | 393 | ||||
-rw-r--r-- | docs/users_guide/runtime_control.rst | 478 | ||||
-rw-r--r-- | docs/users_guide/safe_haskell.rst | 148 | ||||
-rw-r--r-- | docs/users_guide/separate_compilation.rst | 263 | ||||
-rw-r--r-- | docs/users_guide/shared_libs.rst | 28 | ||||
-rw-r--r-- | docs/users_guide/sooner.rst | 70 | ||||
-rw-r--r-- | docs/users_guide/using-concurrent.rst | 50 | ||||
-rw-r--r-- | docs/users_guide/using-optimisation.rst | 449 | ||||
-rw-r--r-- | docs/users_guide/using-warnings.rst | 529 | ||||
-rw-r--r-- | docs/users_guide/using.rst | 277 | ||||
-rw-r--r-- | docs/users_guide/win32-dlls.rst | 26 |
22 files changed, 3178 insertions, 4111 deletions
diff --git a/docs/users_guide/8.0.1-notes.rst b/docs/users_guide/8.0.1-notes.rst index 1d7fcd71a3..d3cdcdcdf4 100644 --- a/docs/users_guide/8.0.1-notes.rst +++ b/docs/users_guide/8.0.1-notes.rst @@ -22,14 +22,14 @@ The highlights, since the 7.10 branch, are: - More reliable DWARF debugging information -- Support for :ref:`injective type classes :ref:`injective-ty-fams` +- Support for :ref:`injective type classes <injective-ty-fams>` - Applicative ``do`` notation (see :ref:`applicative-do`) - Support for wildcards in data and type family instances - ``Strict`` and ``StrictData`` extensions, allowing modules to be compiled with - strict-by-default bindings (see :ref:`strict-haskell`) + strict-by-default bindings (see :ref:`strict-haskell`) - ``DuplicateRecordFields``, allowing multiple datatypes to declare the same record field names provided they are used unambiguously (see :ref:`duplicate-record-fields`) diff --git a/docs/users_guide/bugs.rst b/docs/users_guide/bugs.rst index cef03d42cf..8304e25e78 100644 --- a/docs/users_guide/bugs.rst +++ b/docs/users_guide/bugs.rst @@ -26,9 +26,9 @@ Divergence from Haskell 98 and Haskell 2010 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 ``-XHaskell98`` and ``-XHaskell2010`` -flags. The known deviations from the standards are described below. -Unless otherwise stated, the deviation applies in Haskell 98, +version of the language with the :ghc-flag:`-XHaskell98` and +:ghc-flag:`-XHaskell2010` 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. .. _infelicities-lexical: @@ -54,9 +54,7 @@ Context-free syntax 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: - - :: + For example, the following code is accepted by GHC: :: main = do args <- getArgs if null args then return [] else do @@ -69,15 +67,11 @@ Context-free syntax - GHC doesn't do the fixity resolution in expressions during parsing as required by Haskell 98 (but not by Haskell 2010). For example, according to the Haskell 98 report, the following expression is - legal: - - :: + legal: :: let x = 42 in x == 42 == True - and parses as: - - :: + and parses as: :: (let x = 42 in x == 42) == True @@ -85,11 +79,10 @@ Context-free syntax far to the right as possible”. 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: - - :: + whole expression, parsing like this: :: (let x = 42 in x == 42 == True) + - The Haskell Report allows you to put a unary ``-`` preceding certain expressions headed by keywords, allowing constructs like ``- case x of ...`` or ``- do { ... }``. GHC does not allow this. Instead, unary ``-`` is allowed @@ -102,9 +95,7 @@ Expressions and patterns ^^^^^^^^^^^^^^^^^^^^^^^^ In its default mode, GHC makes some programs slightly more defined than -they should be. For example, consider - -:: +they should be. For example, consider :: f :: [a] -> b -> b f [] = error "urk" @@ -188,9 +179,7 @@ Numbers, basic types, and built-in classes in ``Bits`` instances. Extra instances - The following extra instances are defined: - - :: + The following extra instances are defined: :: instance Functor ((->) r) instance Monad ((->) r) @@ -199,9 +188,7 @@ Extra instances instance Monad (Either e) Multiply-defined array elements not checked - This code fragment should elicit a fatal error, but it does not: - - :: + This code fragment should elicit a fatal error, but it does not: :: main = print (array (1,1) [(1,2), (1,3)]) @@ -223,31 +210,23 @@ Arbitrary-sized tuples stuck on it. ``splitAt`` semantics - ``Data.List.splitAt`` is stricter than specified in the Report. - Specifically, the Report specifies that - - .. + ``Data.List.splitAt`` is more strict than specified in the Report. + Specifically, the Report specifies that :: splitAt n xs = (take n xs, drop n xs) - which implies that - - .. + which implies that :: splitAt undefined undefined = (undefined, undefined) - but GHC's implementation is strict in its first argument, so + but GHC's implementation is strict in its first argument, so :: - .. - - splitAt undefined [] = undefined + splitAt undefined [] = undefined ``Read``\ ing integers GHC's implementation of the ``Read`` class for integral types accepts hexadecimal and octal literals (the code in the Haskell 98 - report doesn't). So, for example, - - :: + report doesn't). So, for example, :: read "0xf00" :: Int @@ -258,9 +237,7 @@ Arbitrary-sized tuples too. ``isAlpha`` - The Haskell 98 definition of ``isAlpha`` is: - - :: + The Haskell 98 definition of ``isAlpha`` is: :: isAlpha c = isUpper c || isLower c @@ -377,17 +354,17 @@ Bugs in GHC for further discussion. If you are hit by this, you may want to compile the affected module - with ``-fno-omit-yields`` (see :ref:`options-f`). This flag ensures that - yield points are inserted at every function entrypoint (at the expense of a - bit of performance). + with :ghc-flag:`-fno-omit-yields <-fomit-yields>` (see :ref:`options-f`). + This flag ensures that yield points are inserted at every function entrypoint + (at the expense of a bit of performance). - GHC's updated exhaustiveness and coverage checker (see :ref:`options-sanity`) is quite expressive but with a rather high performance cost (in terms of both time and memory consumption), mainly due to guards. Two flags have been introduced to give more control to - the user over guard reasoning: ``-Wtoo-many-guards`` - and ``-ffull-guard-reasoning`` (see :ref:`options-sanity`). - When ``-ffull-guard-reasoning`` is on, pattern match checking for guards + the user over guard reasoning: :ghc-flag:`-Wtoo-many-guards` + and :ghc-flag:`-ffull-guard-reasoning` (see :ref:`options-sanity`). + When :ghc-flag:`-ffull-guard-reasoning` is on, pattern match checking for guards runs in full power, which may run out of memory/substantially increase compilation time. @@ -426,7 +403,7 @@ Bugs in GHC The non-termination is reported like this: - :: + .. code-block:: none ghc: panic! (the 'impossible' happened) (GHC version 7.10.1 for x86_64-unknown-linux): @@ -435,7 +412,7 @@ Bugs in GHC To increase the limit, use -fsimpl-tick-factor=N (default 100) with the panic being reported no matter how high a - ``-fsimpl-tick-factor`` you supply. + :ghc-flag:`-fsimpl-tick-factor` you supply. We have never found another class of programs, other than this contrived one, that makes GHC diverge, and fixing the problem would @@ -444,7 +421,7 @@ Bugs in GHC inliner <http://research.microsoft.com/~simonpj/Papers/inlining/>`__. - On 32-bit x86 platforms when using the native code generator, the - ``-fexcess-precision``\ ``-fexcess-precision`` option is always on. + :ghc-flag:`-fexcess-precision` option is always on. This means that floating-point calculations are non-deterministic, because depending on how the program is compiled (optimisation settings, for example), certain calculations might be done at 80-bit @@ -457,8 +434,8 @@ Bugs in GHC .. index:: single: -msse2 option - One workaround is to use the ``-msse2`` option (see - :ref:`options-platform`, which generates code to use the SSE2 + One workaround is to use the :ghc-flag:`-msse2` option (see + :ref:`options-platform`), 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 @@ -490,7 +467,7 @@ Bugs in GHCi (the interactive GHC) 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 - :: + .. code-block:: none Loading package javavm ... linking ... WARNING: Overflown relocation field (# relocs found: 30765) diff --git a/docs/users_guide/conf.py b/docs/users_guide/conf.py index f7c6c14672..119223af69 100644 --- a/docs/users_guide/conf.py +++ b/docs/users_guide/conf.py @@ -111,16 +111,63 @@ texinfo_documents = [ 'Compilers'), ] +from sphinx import addnodes +from docutils import nodes + def parse_ghci_cmd(env, sig, signode): - from sphinx import addnodes name = sig.split(';')[0] sig = sig.replace(';', '') signode += addnodes.desc_name(name, sig) return name +def parse_flag(env, sig, signode): + import re + names = [] + for i, flag in enumerate(sig.split(',')): + flag = flag.strip() + equals = '=' + parts = flag.split('=') + if len(parts) == 1: + equals='' + parts = flag.split() + if len(parts) == 0: continue + + name = parts[0] + names.append(name) + sig = equals + ' '.join(parts[1:]) + sig = re.sub(ur'<([-a-zA-Z ]+)>', ur'⟨\1⟩', sig) + if i > 0: + signode += addnodes.desc_name(', ', ', ') + signode += addnodes.desc_name(name, name) + if len(sig) > 0: + signode += addnodes.desc_addname(sig, sig) + + return names[0] + def setup(app): + from sphinx.util.docfields import Field, TypedField + # the :ghci-cmd: directive used in ghci.rst app.add_object_type('ghci-cmd', 'ghci-cmd', parse_node=parse_ghci_cmd, objname='GHCi command', indextemplate='pair: %s; GHCi command') + + app.add_object_type('ghc-flag', 'ghc-flag', + objname='GHC command-line option', + parse_node=parse_flag, + indextemplate='pair: %s; GHC option', + doc_field_types=[ + Field('since', label='Introduced in GHC version', names=['since']), + Field('default', label='Default value', names=['default']), + Field('static') + ]) + + app.add_object_type('rts-flag', 'rts-flag', + objname='runtime system command-line option', + parse_node=parse_flag, + indextemplate='pair: %s; RTS option', + doc_field_types=[ + Field('since', label='Introduced in GHC version', names=['since']), + Field('static') + ]) diff --git a/docs/users_guide/debugging.rst b/docs/users_guide/debugging.rst index ddb3c2a832..f366d95679 100644 --- a/docs/users_guide/debugging.rst +++ b/docs/users_guide/debugging.rst @@ -25,259 +25,188 @@ Dumping out compiler intermediate structures need a short form…). You can get all of these at once (*lots* of output) by using ``-v5``, or most of them with ``-v4``. You can prevent them from clogging up your standard output by passing - ``-ddump-to-file``. Some of the most useful ones are: + :ghc-flag:`-ddump-to-file`. Some of the most useful ones are: - ``-ddump-parsed`` - .. index:: - single: -ddump-parsed + .. ghc-flag:: -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 :ghc-flag:`-ddump-simpl` will end up in + :file:`{module}.dump-simpl`. + + .. ghc-flag:: -ddump-parsed Dump parser output - ``-ddump-rn`` - .. index:: - single: -ddump-rn + .. ghc-flag:: -ddump-rn Dump renamer output - ``-ddump-tc`` - .. index:: - single: -ddump-tc + .. ghc-flag:: -ddump-tc Dump typechecker output - ``-ddump-splices`` - .. index:: - single: -ddump-splices + .. ghc-flag:: -ddump-splices Dump Template Haskell expressions that we splice in, and what Haskell code the expression evaluates to. - ``-ddump-types`` - .. index:: - single: -ddump-types + .. ghc-flag:: -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`` dumps a type signature for all the imported and + :ghc-flag:`-dppr-debug` dumps a type signature for all the imported and system-defined things as well; useful for debugging the compiler. - ``-ddump-deriv`` - .. index:: - single: -ddump-deriv + .. ghc-flag:: -ddump-deriv Dump derived instances - ``-ddump-ds`` - .. index:: - single: -ddump-ds + .. ghc-flag:: -ddump-ds Dump desugarer output - ``-ddump-spec`` - .. index:: - single: -ddump-spec + .. ghc-flag:: -ddump-spec Dump output of specialisation pass - ``-ddump-rules`` - .. index:: - single: -ddump-rules + .. ghc-flag:: -ddump-rules Dumps all rewrite rules specified in this module; see :ref:`controlling-rules`. - ``-ddump-rule-firings`` - .. index:: - single: -ddump-rule-firings + .. ghc-flag:: -ddump-rule-firings Dumps the names of all rules that fired in this module - ``-ddump-rule-rewrites`` - .. index:: - single: -ddump-rule-rewrites + .. ghc-flag:: -ddump-rule-rewrites Dumps detailed information about all rules that fired in this module - ``-ddump-vect`` - .. index:: - single: -ddump-vect + .. ghc-flag:: -ddump-vect Dumps the output of the vectoriser. - ``-ddump-simpl`` - .. index:: - single: -ddump-simpl + .. ghc-flag:: -ddump-simpl Dump simplifier output (Core-to-Core passes) - ``-ddump-inlinings`` - .. index:: - single: -ddump-inlinings + .. ghc-flag:: -ddump-inlinings Dumps inlining info from the simplifier - ``-ddump-stranal`` - .. index:: - single: -ddump-stranal + .. ghc-flag:: -ddump-stranal Dump strictness analyser output - ``-ddump-strsigs`` - .. index:: - single: -ddump-strsigs + .. ghc-flag:: -ddump-strsigs Dump strictness signatures - ``-ddump-cse`` - .. index:: - single: -ddump-cse + .. ghc-flag:: -ddump-cse Dump common subexpression elimination (CSE) pass output - ``-ddump-worker-wrapper`` - .. index:: - single: -ddump-worker-wrapper + .. ghc-flag:: -ddump-worker-wrapper Dump worker/wrapper split output - ``-ddump-occur-anal`` - .. index:: - single: -ddump-occur-anal + .. ghc-flag:: -ddump-occur-anal Dump "occurrence analysis" output - ``-ddump-prep`` - .. index:: - single: -ddump-prep + .. ghc-flag:: -ddump-prep Dump output of Core preparation pass - ``-ddump-stg`` - .. index:: - single: -ddump-stg + .. ghc-flag:: -ddump-stg Dump output of STG-to-STG passes - ``-ddump-cmm`` - .. index:: - single: -ddump-cmm + .. ghc-flag:: -ddump-cmm Print the C-- code out. - ``-ddump-opt-cmm`` - .. index:: - single: -ddump-opt-cmm + .. ghc-flag:: -ddump-opt-cmm Dump the results of C-- to C-- optimising passes. - ``-ddump-asm`` - .. index:: - single: -ddump-asm + .. ghc-flag:: -ddump-asm Dump assembly language produced by the :ref:`native code generator <native-code-gen>` - ``-ddump-llvm`` - .. index:: - single: -ddump-llvm + .. ghc-flag:: -ddump-llvm LLVM code from the :ref:`LLVM code generator <llvm-code-gen>` - ``-ddump-bcos`` - .. index:: - single: -ddump-bcos + .. ghc-flag:: -ddump-bcos Dump byte-code compiler output - ``-ddump-foreign`` - .. index:: - single: -ddump-foreign + .. ghc-flag:: -ddump-foreign dump foreign export stubs -``-ddump-simpl-iterations`` - .. index:: - single: -ddump-simpl-iterations +.. ghc-flag:: -ddump-simpl-iterations Show the output of each *iteration* of the simplifier (each run of the simplifier has a maximum number of iterations, normally 4). This outputs even more information than ``-ddump-simpl-phases``. -``-ddump-simpl-stats`` - .. index:: - single: -ddump-simpl-stats option +.. ghc-flag:: -ddump-simpl-stats Dump statistics about how many of each kind of transformation too place. If you add ``-dppr-debug`` you get more detailed information. -``-ddump-if-trace`` - .. index:: - single: -ddump-if-trace +.. ghc-flag:: -ddump-if-trace Make the interface loader be *real* chatty about what it is up to. -``-ddump-tc-trace`` - .. index:: - single: -ddump-tc-trace +.. ghc-flag:: -ddump-tc-trace Make the type checker be *real* chatty about what it is up to. -``-ddump-vt-trace`` - .. index:: - single: -ddump-tv-trace +.. ghc-flag:: -ddump-vt-trace Make the vectoriser be *real* chatty about what it is up to. -``-ddump-rn-trace`` - .. index:: - single: -ddump-rn-trace +.. ghc-flag:: -ddump-rn-trace Make the renamer be *real* chatty about what it is up to. -``-ddump-rn-stats`` - .. index:: - single: -dshow-rn-stats +.. ghc-flag:: -ddump-rn-stats Print out summary of what kind of information the renamer had to bring in. -``-dverbose-core2core``, ``-dverbose-stg2stg`` - .. index:: - single: -dverbose-core2core - single: -dverbose-stg2stg +.. ghc-flag:: -dverbose-core2core + -dverbose-stg2stg Show the output of the intermediate Core-to-Core and STG-to-STG passes, respectively. (*lots* of output!) So: when we're really desperate: - :: + .. code-block:: sh % ghc -noC -O -ddump-simpl -dverbose-core2core -dcore-lint Foo.hs -``-dshow-passes`` - .. index:: - single: -dshow-passes +.. ghc-flag:: -dshow-passes Print out each pass name as it happens. -``-ddump-core-stats`` - .. index:: - single: -ddump-core-stats +.. ghc-flag:: -ddump-core-stats Print a one-line summary of the size of the Core program at the end of the optimisation pipeline. -``-dfaststring-stats`` - .. index:: - single: -dfaststring-stats +.. ghc-flag:: -dfaststring-stats Show statistics on the usage of fast strings by the compiler. -``-dppr-debug`` - .. index:: - single: -dppr-debug +.. ghc-flag:: -dppr-debug Debugging output is in one of several "styles." Take the printing of types, for example. In the "user" style (the default), the @@ -342,63 +271,47 @@ 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`` - .. index:: - single: -dsuppress-all +.. ghc-flag:: -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-uniques`` - .. index:: - single: -dsuppress-uniques +.. ghc-flag:: -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`` + :ghc-flag:`-dsuppress-uniques` -``-dsuppress-idinfo`` - .. index:: - single: -dsuppress-idinfo +.. ghc-flag:: -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`` - .. index:: - single: -dsuppress-unfoldings +.. ghc-flag:: -dsuppress-unfoldings Suppress the printing of the stable unfolding of a variable at its binding site. -``-dsuppress-module-prefixes`` - .. index:: - single: -dsuppress-module-prefixes +.. ghc-flag:: -dsuppress-module-prefixes Suppress the printing of module qualification prefixes. This is the ``Data.List`` in ``Data.List.length``. -``-dsuppress-type-signatures`` - .. index:: - single: -dsuppress-type-signatures +.. ghc-flag:: -dsuppress-type-signatures Suppress the printing of type signatures. -``-dsuppress-type-applications`` - .. index:: - single: -dsuppress-type-applications +.. ghc-flag:: -dsuppress-type-applications Suppress the printing of type applications. -``-dsuppress-coercions`` - .. index:: - single: -dsuppress-coercions +.. ghc-flag:: -dsuppress-coercions Suppress the printing of type coercions. @@ -411,22 +324,16 @@ Checking for consistency single: consistency checks single: lint -``-dcore-lint`` - .. index:: - single: -dcore-lint +.. ghc-flag:: -dcore-lint Turn on heavyweight intra-pass sanity-checking within GHC, at Core level. (It checks GHC's sanity, not yours.) -``-dstg-lint`` - .. index:: - single: -dstg-lint +.. ghc-flag:: -dstg-lint Ditto for STG level. (note: currently doesn't work). -``-dcmm-lint`` - .. index:: - single: -dcmm-lint +.. ghc-flag:: -dcmm-lint Ditto for C-- level. @@ -438,19 +345,15 @@ Checking for determinism .. index:: single: deterministic builds -``-dinitial-unique=⟨s⟩`` - .. index:: - single: -dinitial-unique +.. ghc-flag:: -dinitial-unique=⟨s⟩ Start ``UniqSupply`` allocation from ⟨s⟩. -``-dunique-increment=⟨i⟩`` - .. index:: - single: -dunique-increment +.. ghc-flag:: -dunique-increment=⟨i⟩ Set the increment for the generated ``Unique``'s to ⟨i⟩. - This is useful in combination with ``-dinitial-unique`` to test if the + This is useful in combination with :ghc-flag:`-dinitial-unique` to test if the generated files depend on the order of ``Unique``'s. Some interesting values: diff --git a/docs/users_guide/editing-guide.rst b/docs/users_guide/editing-guide.rst index ff3d4b8592..6e5036ccbc 100644 --- a/docs/users_guide/editing-guide.rst +++ b/docs/users_guide/editing-guide.rst @@ -286,6 +286,7 @@ Would be rendered as, There are a number of admonitions types, .. hlist:: + :columns: 3 * attention * caution @@ -300,6 +301,66 @@ There are a number of admonitions types, .. _Admonitions: http://docutils.sourceforge.net/docs/ref/rst/directives.html#admonitions +Documenting command-line options and GHCi commands +-------------------------------------------------- + +:file:`conf.py` defines a few Sphinx object types for GHCi commands +(``ghci-cmd``), :program:`ghc` command-line options (``ghc-flag``), and runtime +:system options (``rts-flag``), + +Command-line options +~~~~~~~~~~~~~~~~~~~~ + +The ``ghc-flag`` and ``rts-flag`` roles/directives can be used to document +command-line arguments to the :program:`ghc` executable and runtime system, +respectively. For instance, + +.. code-block:: rest + + .. rts-flag:: -C <seconds> + + :default: 20 milliseconds + + Sets the context switch interval to ⟨s⟩ seconds. + +Will be rendered as, + + .. rts-flag:: -C <seconds> + + :default: 20 milliseconds + + Sets the context switch interval to ⟨s⟩ seconds. + +and will have an associated index entry generated automatically. + +GHCi commands +~~~~~~~~~~~~~ + +The ``ghci-cmd`` role and directive can be used to document GHCi directives. For +instance, we can describe the GHCi ``:module`` command, + +.. code-block:: rest + + .. ghci-cmd:: :module [*] <file> + + Load a module + +which will be rendered as, + + .. ghci-cmd:: :module [*] <file> + + Load a module + +And later refer to it by just the command name, ``:module``, + +.. code-block:: rest + + The GHCi :ghci-cmd:`:load` and :ghci-cmd:`:module` commands are used + to modify the modules in scope. + +Like command-line options, GHCi commands will have associated index entries +generated automatically. + Style Conventions ----------------- @@ -314,10 +375,10 @@ less-than/greater-than signs). GHC command-line options reference ---------------------------------- -The tabular nature of GHC flags reference (``flags.rst``) makes it very +The tabular nature of GHC flags reference (:file:`flags.rst`) makes it very difficult to maintain as ReST. For this reason it is generated by -``utils/mkUserGuidePart``. Any command-line options added to GHC should -be added to the appropriate file in ``utils/mkUserGuidePart/Options``. +:file:`utils/mkUserGuidePart`. Any command-line options added to GHC should +be added to the appropriate file in :file:`utils/mkUserGuidePart/Options`. ReST reference materials diff --git a/docs/users_guide/extending_ghc.rst b/docs/users_guide/extending_ghc.rst index 4cd15f5be1..74bba9140a 100644 --- a/docs/users_guide/extending_ghc.rst +++ b/docs/users_guide/extending_ghc.rst @@ -149,7 +149,7 @@ which provides this for us. Compiling it results in: -:: +.. code-block:: none $ cat test_main.hs main = putStrLn "hi" @@ -190,17 +190,25 @@ restrictions are too onerous, Using compiler plugins ~~~~~~~~~~~~~~~~~~~~~~ -Plugins can be specified on the command line with the option -``-fplugin=module`` where ⟨module⟩ is a module in a registered package +Plugins can be specified on the command line with the :ghc-flag:`-fplugin` +option. ``-fplugin=module`` where ⟨module⟩ is a module in a registered package that exports a plugin. Arguments can be given to plugins with the -command line option ``-fplugin-opt=module:args``, where ⟨args⟩ are -arguments interpreted by the plugin provided by ⟨module⟩. +:ghc-flag:`-fplugin-opt` option. + +.. ghc-flag:: -fplugin=<module> + + Load the plugin in the given module. The module must be a member of a package + registered in GHC's package database. + +.. ghc-flag:: -fplugin-opt=<module>:<args> + + Pass arguments ⟨args⟩ to the given plugin. As an example, in order to load the plugin exported by ``Foo.Plugin`` in the package ``foo-ghc-plugin``, and give it the parameter "baz", we would invoke GHC like this: -:: +.. code-block:: none $ ghc -fplugin Foo.Plugin -fplugin-opt Foo.Plugin:baz Test.hs [1 of 1] Compiling Main ( Test.hs, Test.o ) @@ -218,44 +226,38 @@ the user import namespace. By default, these two namespaces are the same; however, there are a few command line options which control specifically plugin packages: -``-plugin-package ⟨pkg⟩`` - .. index:: - single: -plugin-package +.. ghc-flag:: -plugin-package ⟨pkg⟩ This option causes the installed package ⟨pkg⟩ to be exposed - for plugins, such as ``-fplugin``. The + for plugins, such as :ghc-flag:`-fplugin`. The package ⟨pkg⟩ can be specified in full with its version number (e.g. ``network-1.0``) or the version number can be omitted if there is only one version of the package installed. If there are multiple - versions of ⟨pkg⟩ installed and ``-hide-all-plugin-packages`` was not - specified, then all other versions will become hidden. ``-plugin-package`` + versions of ⟨pkg⟩ installed and :ghc-flag:`-hide-all-plugin-packages` was not + specified, then all other versions will become hidden. :ghc-flag:`-plugin-package` supports thinning and renaming described in :ref:`package-thinning-and-renaming`. - Unlike ``-package``, this option does NOT cause package ⟨pkg⟩ to be linked + Unlike :ghc-flag:`-package`, this option does NOT cause package ⟨pkg⟩ to be linked into the resulting executable or shared object. -``-plugin-package-id ⟨pkg-id⟩`` - .. index:: - single: -plugin-package-id +.. ghc-flag:: -plugin-package-id ⟨pkg-id⟩ - Exposes a package in the plugin namespace like ``-plugin-package``, but the + Exposes a package in the plugin namespace like :ghc-flag:`-plugin-package`, but the package is named by its 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 ``-plugin-package-id`` flags to - GHC. ``-plugin-package-id`` supports thinning and renaming described in + would otherwise be shadowed. Cabal passes :ghc-flag:`-plugin-package-id` flags to + GHC. :ghc-flag:`-plugin-package-id` supports thinning and renaming described in :ref:`package-thinning-and-renaming`. -``-hide-all-plugin-packages`` - .. index:: - single: -hide-all-plugin-packages +.. ghc-flag:: -hide-all-plugin-packages By default, all exposed packages in the normal, source import namespace are also available for plugins. This causes those packages to be hidden by default. If you use this flag, then any packages with plugins you require need to be explicitly exposed using - ``-plugin-package`` options. + :ghc-flag:`-plugin-package` options. To declare a dependency on a plugin, add it to the ``ghc-plugins`` field in Cabal. You should only put a plugin in ``build-depends`` if you @@ -590,7 +592,7 @@ of parsing flags and administrative nonsense which can be difficult to manage manually. To load a frontend plugin exported by ``Foo.FrontendPlugin``, we just invoke GHC as follows: -:: +.. code-block:: none $ ghc --frontend Foo.FrontendPlugin ...other options... diff --git a/docs/users_guide/ffi-chap.rst b/docs/users_guide/ffi-chap.rst index 2cc24a4086..63324d1ff3 100644 --- a/docs/users_guide/ffi-chap.rst +++ b/docs/users_guide/ffi-chap.rst @@ -10,10 +10,10 @@ Foreign function interface (FFI) GHC (mostly) conforms to the Haskell Foreign Function Interface, whose definition is part of the Haskell Report on -``http://www.haskell.org/`` <http://www.haskell.org/>`__. +`http://www.haskell.org/ <http://www.haskell.org/>`__. FFI support is enabled by default, but can be enabled or disabled -explicitly with the ``-XForeignFunctionInterface`` flag. +explicitly with the :ghc-flag:`-XForeignFunctionInterface` flag. GHC implements a number of GHC-specific extensions to the FFI Addendum. These extensions are described in :ref:`ffi-ghcexts`, but please note @@ -248,7 +248,7 @@ the following module: Then ``Foo_stub.h`` will contain something like this: -:: +.. code-block:: c #include "HsFFI.h" extern HsInt foo(HsInt a0); @@ -273,7 +273,7 @@ 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: -:: +.. code-block:: c #include <stdio.h> #include "HsFFI.h" @@ -317,23 +317,23 @@ matched by one (and only one) call to ``hs_exit()`` [1]_. .. 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``\ ``-no-hs-main``, otherwise GHC + don't forget the flag :ghc-flag:`-no-hs-main`, otherwise GHC will try to link to the ``Main`` Haskell module. .. [1] The outermost ``hs_exit()`` will actually de-initialise the system. - NOTE that currently GHC's runtime cannot reliably re-initialise after + Note that currently GHC's runtime cannot reliably re-initialise after this has happened, see :ref:`infelicities-ffi`. 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 :ref:`options-linker`), and the ``-rtsopts``\ ``-rtsopts`` -link-time flag overrides this. However, ``-rtsopts`` has no effect when -``-no-hs-main`` is in use (and the same goes for ``-with-rtsopts``). To +(see :ref:`options-linker`), and the :ghc-flag:`-rtsopts` +link-time flag overrides this. However, :ghc-flag:`-rtsopts` has no effect when +:ghc-flag:`-no-hs-main` is in use (and the same goes for :ghc-flag:`-with-rtsopts`). To set these options we have to call a GHC-specific API instead of ``hs_init()``: -:: +.. code-block:: c #include <stdio.h> #include "HsFFI.h" @@ -371,7 +371,7 @@ external RTS interface, and we called ``hs_init_ghc()`` instead of is a struct with various fields that affect the behaviour of the runtime system. Its definition is: -:: +.. code-block:: c typedef struct { RtsOptsEnabledEnum rts_opts_enabled; @@ -407,7 +407,7 @@ before any Haskell code can be called, so your library should provide initialisation and deinitialisation entry points, implemented in C or C++. For example: -:: +.. code-block:: c #include <stdlib.h> #include "HsFFI.h" @@ -450,7 +450,7 @@ 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 :ref:`native code generator <native-code-gen>` (``-fasm``) and to +with the :ref:`native code generator <native-code-gen>` (:ghc-flag:`-fasm`) 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 @@ -513,24 +513,24 @@ Multi-threading and the FFI ~~~~~~~~~~~~~~~~~~~~~~~~~~~ In order to use the FFI in a multi-threaded setting, you must use the -``-threaded`` option (see :ref:`options-linker`). +:ghc-flag:`-threaded` option (see :ref:`options-linker`). Foreign imports and multi-threading ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ When you call a ``foreign import``\ ed function that is annotated as -``safe`` (the default), and the program was linked using ``-threaded``, +``safe`` (the default), and the program was linked using :ghc-flag:`-threaded`, then the call will run concurrently with other running Haskell threads. -If the program was linked without ``-threaded``, then the other Haskell +If the program was linked without :ghc-flag:`-threaded`, 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``. Some library functions make such calls +``safe`` and use :ghc-flag:`-threaded`. 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``, make sure that the foreign code you are calling is +:ghc-flag:`-threaded`, 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 @@ -539,7 +539,7 @@ single Haskell thread, and possibly also use a bound thread (see Note that foreign calls made by different Haskell threads may execute in *parallel*, even when the ``+RTS -N`` flag is not being used -(:ref:`parallel-options`). The ``+RTS -N`` flag controls parallel +(:ref:`parallel-options`). The :rts-flag:`-N` 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. @@ -574,7 +574,7 @@ threads, see the documentation for the :base-ref:`Control.Concurrent` module. Foreign exports and multi-threading ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -When the program is linked with ``-threaded``, then you may invoke +When the program is linked with :ghc-flag:`-threaded`, then you may invoke ``foreign export``\ ed functions from multiple OS threads concurrently. The runtime system must be initialised as usual by calling ``hs_init()``, and this call must complete before invoking any diff --git a/docs/users_guide/ghci.rst b/docs/users_guide/ghci.rst index c299fb27a9..c1ef93508f 100644 --- a/docs/users_guide/ghci.rst +++ b/docs/users_guide/ghci.rst @@ -151,7 +151,7 @@ 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 ``Main.hs``. -The search path for finding source files is specified with the ``-i`` +The search path for finding source files is specified with the :ghc-flag:`-i` option on the GHCi command line, like so: .. code-block:: none @@ -170,9 +170,9 @@ even if there are object and interface files for the module, you'll get an error message. .. [4] - Note that in GHCi, and ``--make`` mode, the ``-i`` option is used to + Note that in GHCi, and :ghc-flag:`--make` mode, the :ghc-flag:`-i` option is used to specify the search path for *source* files, whereas in standard - batch-compilation mode the ``-i`` option is used to specify the + batch-compilation mode the :ghc-flag:`-i` option is used to specify the search path for interface files, see :ref:`search-path`. @@ -240,7 +240,7 @@ In the messages from the compiler, we see that there is no line for source and everything it depends on is unchanged since the last compilation. -Note the ``-dynamic`` flag to GHC: GHCi uses dynamically-linked object +Note the :ghc-flag:`-dynamic` 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. @@ -329,7 +329,7 @@ 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`` option (see :ref:`ghci-obj`). +interpreter, use the :ghc-flag:`-fobject-code` option (see :ref:`ghci-obj`). .. hint:: Since GHCi will only use a compiled object file if it can be sure @@ -424,17 +424,16 @@ 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. -If ``-fprint-bind-result`` is set then GHCi will print the result of a -statement if and only if: +.. ghc-flag:: -fprint-bind-result -- The statement is not a binding, or it is a monadic binding - (``p <- e``) that binds exactly one variable. + If :ghc-flag:`-fprint-bind-result` is set then GHCi will print the result of a + statement if and only if: -- The variable's type is not polymorphic, is not ``()``, and is an - instance of ``Show``. + - The statement is not a binding, or it is a monadic binding + (``p <- e``) that binds exactly one variable. -.. index:: - single: -fprint-bind-result + - 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: @@ -502,7 +501,7 @@ not to replace module loading but to make definitions in .ghci-files 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 ``Control.Exception`` in -the libraries documentation). +the libraries :base-ref:`documentation <Control-Exception.html>`). Every new binding shadows any existing bindings of the same name, including entities that are in scope in the current module context. @@ -858,7 +857,7 @@ You can add a module to the scope (via :ghci-cmd:`:module` or ``import``) only if either (a) it is loaded, or (b) it is a module from a package that GHCi knows about. Using :ghci-cmd:`:module` or ``import`` to try bring into scope a non-loaded module may result in the message -“\ ``module M is not loaded``\ ”. +``module M is not loaded``. The ``:main`` and ``:run`` commands ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ @@ -1008,7 +1007,7 @@ and defaults the type variable if 3. At least one of the classes ``Ci`` is numeric. -At the GHCi prompt, or with GHC if the ``-XExtendedDefaultRules`` flag +At the GHCi prompt, or with GHC if the :ghc-flag:`-XExtendedDefaultRules` flag is given, the following additional differences apply: - Rule 2 above is relaxed thus: *All* of the classes ``Ci`` are @@ -1060,13 +1059,18 @@ 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`` flag allows to specify any function of type +The :ghc-flag:`-interactive-print` 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 :ghci-cmd:`:cd`, :ghci-cmd:`:add`, :ghci-cmd:`:load`, :ghci-cmd:`:reload` or, :ghci-cmd:`:set`. +.. ghc-flag:: -interactive-print <expr> + + Set the function used by GHCi to print evaluation results. Expression + must be of type ``C a => a -> IO ()``. + As an example, suppose we have following special printing module: :: module SpecPrinter where @@ -1094,7 +1098,7 @@ will start an interactive session where values with be printed using 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`` flag can also be used when running GHC in +The :ghc-flag:`-interactive-print` flag can also be used when running GHC in ``-e mode``: .. code-block:: none @@ -1304,7 +1308,7 @@ triggered (see :ref:`nested-breakpoints`). Rather than forcing thunks, :ghci-cmd:`:print` binds each thunk to a fresh variable beginning with an underscore, in this case ``_t1``. -The flag ``-fprint-evld-with-show`` instructs :ghci-cmd:`:print` to reuse +The flag :ghc-flag:`-fprint-evld-with-show` instructs :ghci-cmd:`:print` to reuse available ``Show`` instances when possible. This happens only when the contents of the variable being inspected are completely evaluated. @@ -1412,7 +1416,7 @@ 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`` in :ref:`options-sanity`). +altogether (see :ghc-flag:`-Wtabs` in :ref:`options-sanity`). If the module is omitted, then the most recently-loaded module is used. @@ -1469,10 +1473,10 @@ example: Stopped at qsort.hs:5:7-47 _result :: IO () -The command :ghci-cmd:`:step expr` begins the evaluation of ⟨expr⟩ in +The command :ghci-cmd:`:step expr <:step>` begins the evaluation of ⟨expr⟩ in single-stepping mode. If ⟨expr⟩ is omitted, then it single-steps from -the current breakpoint. :ghci-cmd:`:steplocal` and :ghci-cmd:`:stepmodule` work -similarly. +the current breakpoint. :ghci-cmd:`:steplocal` and :ghci-cmd:`:stepmodule` +commands work similarly. The :ghci-cmd:`:list` command is particularly useful when single-stepping, to see where you currently are: @@ -1649,11 +1653,13 @@ just like :ghci-cmd:`:step`. The history is only available when using :ghci-cmd:`:trace`; the reason for this is we found that logging each breakpoint in the history cuts performance -by a factor of 2 or more. By default, GHCi remembers the last 50 steps -in the history, but this can be changed with the ``-fghci-hist-size=n`` option). +by a factor of 2 or more. -.. index:: - single: -fghci-hist-size +.. ghc-flag:: -fghci-hist-size + + :default: 50 + + Modify the depth of the evaluation history tracked by GHCi. .. _ghci-debugger-exceptions: @@ -1666,7 +1672,7 @@ exception come from?". Exceptions such as those raised by ``error`` or particular call to ``head`` in your program resulted in the error can be a painstaking process, usually involving ``Debug.Trace.trace``, or compiling with profiling and using ``Debug.Trace.traceStack`` or -``+RTS -xc`` (see :ref:`prof-time-options`). +``+RTS -xc`` (see :rts-flag:`-xc`). The GHCi debugger offers a way to hopefully shed some light on these errors quickly and without modifying or recompiling the source code. One @@ -1674,8 +1680,8 @@ way would be to set a breakpoint on the location in the source code that throws the exception, and then use :ghci-cmd:`:trace` and :ghci-cmd:`:history` 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`` which causes the evaluator to stop when -an exception is thrown, and ``-fbreak-on-error``, which works similarly +flags :ghc-flag:`-fbreak-on-exception` which causes the evaluator to stop when +an exception is thrown, and :ghc-flag:`-fbreak-on-error`, 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 @@ -1713,6 +1719,14 @@ Breaking on exceptions is particularly useful for finding out what your program was doing when it was in an infinite loop. Just hit Control-C, and examine the history to find out what was going on. +.. ghc-flag:: -fbreak-on-exception + -fbreak-on-error + + Causes GHCi to halt evaluation and return to the interactive prompt + in the event of an exception. While :ghc-flag:`-fbreak-on-exception` breaks + on all exceptions, :ghc-flag:`-fbreak-on-error` breaks on only those which + would otherwise be uncaught. + Example: inspecting functions ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ @@ -1838,7 +1852,7 @@ Invoking GHCi 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 :ghci-cmd:`:load modules` +the modules they depend on), just as if you had said ``:load modules`` at the GHCi prompt (see :ref:`ghci-commands`). For example, to start GHCi and load the program whose topmost module is in the file ``Main.hs``, we could say: @@ -1862,7 +1876,7 @@ 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`` flag: +by using the :ghc-flag:`-package` flag: .. code-block:: none @@ -1900,10 +1914,10 @@ On systems with ``.so``-style shared libraries, the actual library loaded will the ``liblib.so``. GHCi searches the following places for libraries, in this order: -- Paths specified using the ``-Lpath`` command-line option, +- Paths specified using the :ghc-flag:`-L` command-line option, - the standard library search path for your system, which on some - systems may be overridden by setting the ``LD_LIBRARY_PATH`` + systems may be overridden by setting the :envvar:`LD_LIBRARY_PATH` environment variable. On systems with ``.dll``-style shared libraries, the actual library @@ -2022,8 +2036,8 @@ commonly used commands. 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 :ghci-cmd:`:show paths` command - for showing the current working directory. + environment variable :envvar:`HOME`. See also the :ghci-cmd:`:show paths` + 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 @@ -2179,8 +2193,8 @@ commonly used commands. Opens an editor to edit the file ⟨file⟩, or the most recently loaded module if ⟨file⟩ is omitted. If there were errors during the last loading, the cursor will be positioned at the line of the first - error. The editor to invoke is taken from the ``EDITOR`` environment - variable, or a default editor on your system if ``EDITOR`` is not + error. The editor to invoke is taken from the :envvar:`EDITOR` environment + variable, or a default editor on your system if :envvar:`EDITOR` is not set. You can change the editor using :ghci-cmd:`:set editor`. .. ghci-cmd:: :etags @@ -2202,6 +2216,7 @@ commonly used commands. :ghci-cmd:`:trace`, :ghci-cmd:`:history`, :ghci-cmd:`:back`. .. ghci-cmd:: :help + :? Displays a list of the available commands. @@ -2217,7 +2232,7 @@ commonly used commands. Display the history of evaluation steps. With a number, displays that many steps (default: 20). For use with :ghci-cmd:`:trace`; see :ref:`tracing`. To set the number of history entries stored by GHCi, - use ``-fghci-hist-size=n``. + use the :ghc-flag:`-fghci-hist-size` flag. .. ghci-cmd:: :info;[!] ⟨name⟩ @@ -2715,7 +2730,7 @@ Setting GHC command-line options in GHCi ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Normal GHC command-line options may also be set using :ghci-cmd:`:set`. For -example, to turn on ``-Wmissing-signatures``, you would say: +example, to turn on :ghc-flag:`-Wmissing-signatures`, you would say: .. code-block:: none @@ -2735,9 +2750,9 @@ option, you can set the reverse option: :ref:`flag-reference` lists the reverse for each option where applicable. -Certain static options (``-package``, ``-I``, ``-i``, and ``-l`` in -particular) will also work, but some may not take effect until the next -reload. +Certain static options (:ghc-flag:`-package`, :ghc-flag:`-I`, :ghc-flag:`-i`, +and :ghc-flag:`-l` in particular) will also work, but some may not take effect +until the next reload. .. index:: single: static; options @@ -2765,7 +2780,7 @@ that option apply to loaded modules too. For example :seti -XMonoLocalBinds -It would be undesirable if ``-XMonoLocalBinds`` were to apply to loaded +It would be undesirable if :ghc-flag:`-XMonoLocalBinds` 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. @@ -2816,7 +2831,7 @@ The ``.ghci`` files single: .ghci; file single: startup; files, GHCi -When it starts, unless the ``-ignore-dot-ghci`` flag is given, GHCi +When it starts, unless the :ghc-flag:`-ignore-dot-ghci` flag is given, GHCi reads and executes commands from the following files, in this order, if they exist: @@ -2842,14 +2857,14 @@ 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``: +:file:`.ghci`: .. code-block:: none :set -XMultiParamTypeClasses -XScopedTypeVariables -cpp :set -iA:B:C -(Note that strictly speaking the ``-i`` flag is a static one, but in +(Note that strictly speaking the :ghc-flag:`-i` flag is a static one, but in fact it works to set it using :ghci-cmd:`:set` like this. The changes won't take effect until the next :ghci-cmd:`:load`, though.) @@ -2866,22 +2881,18 @@ With this macro defined in your ``.ghci`` file, you can use contribute!-) other suggestions for ``.ghci`` files on this Haskell wiki page: `GHC/GHCi <http://haskell.org/haskellwiki/GHC/GHCi>`__ -Additionally, any files specified with ``-ghci-script`` flags will be +Additionally, any files specified with :ghc-flag:`-ghci-script` flags will be read after the standard files, allowing the use of custom .ghci files. Two command-line options control whether the startup files files are read: -``-ignore-dot-ghci`` - .. index:: - single: -ignore-dot-ghci +.. ghc-flag:: -ignore-dot-ghci - Don't read either ``./.ghci`` or the other startup files when + Don't read either :file:`./.ghci` or the other startup files when starting up. -``-ghci-script`` - .. index:: - single: -ghci-script +.. ghc-flag:: -ghci-script Read a specific file after the usual startup files. Maybe be specified repeatedly for multiple inputs. @@ -2941,15 +2952,15 @@ Compiling to object code inside GHCi By default, GHCi compiles Haskell source code into byte-code that is interpreted by the runtime system. GHCi can also compile Haskell code to -object code: to turn on this feature, use the ``-fobject-code`` flag -either on the command line or with :ghci-cmd:`:set` (the option ``-fbyte-code`` +object code: to turn on this feature, use the :ghc-flag:`-fobject-code` flag +either on the command line or with :ghci-cmd:`:set` (the option :ghc-flag:`-fbyte-code` 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 :ghci-cmd:`:reload` command -typically runs much faster than restarting GHC with ``--make`` from the +typically runs much faster than restarting GHC with :ghc-flag:`--make` from the command-line, because all the interface files are already cached in memory. @@ -2965,26 +2976,26 @@ Running the interpreter in a separate process 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`` is given, then GHC will spawn a +the flag :ghc-flag:`-fexternal-interpreter` is given, then GHC will spawn a separate process for running interpreted code, and communicate with it using messages over a pipe. -``-fexternal-interpreter`` - .. index:: - single: -fexternal-interpreter +.. ghc-flag:: -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`` is in effect, and in - dynamically-linked mode if ``-dynamic`` is in effect. + in profiling mode if :ghc-flag:`-prof` is in effect, and in + dynamically-linked mode if :ghc-flag:`-dynamic` 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``. + :ghc-flag:`-fexternal-interpreter`. - See also the ``-pgmi`` (:ref:`replacing-phases`) and ``-opti`` + See also the :ghc-flag:`-pgmi` (:ref:`replacing-phases`) and :ghc-flag:`-opti` (:ref:`forcing-options-through`) flags. Why might we want to do this? The main reason is that the RTS running @@ -2994,8 +3005,8 @@ dynamically-linked) from GHC itself. So for example: - We can use the profiler to collect stack traces when using GHCi (see :ref:`ghci-stack-traces`). -- When compiling Template Haskell code with ``-prof`` we don't need to - compile the modules without ``-prof`` first (see :ref:`th-profiling`) +- When compiling Template Haskell code with :ghc-flag:`-prof` we don't need to + compile the modules without :ghc-flag:`-prof` first (see :ref:`th-profiling`) 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 @@ -3010,9 +3021,10 @@ 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`` doesn't work with GHCi! +:ghc-flag:`-O` doesn't work with GHCi! + .. index:: - single: -O + single: optimization; and GHCi For technical reasons, the bytecode compiler doesn't interact well with one of the optimisation passes, so we have disabled @@ -3024,12 +3036,12 @@ The interpreter can't load modules with foreign export declarations! Unboxed tuples don't work with GHCi That's right. You can always compile a module that uses unboxed tuples and load it into GHCi, however. (Incidentally the previous - point, namely that ``-O`` is incompatible with GHCi, is because the + point, namely that :ghc-flag:`-O` is incompatible with GHCi, is because the bytecode compiler can't deal with unboxed tuples). 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`` switch, which is the default. Consult whoever supplied + :ghc-flag:`-threaded` switch, which is the default. Consult whoever supplied your GHCi installation. diff --git a/docs/users_guide/glasgow_exts.rst b/docs/users_guide/glasgow_exts.rst index 377c1b5690..9b5777047b 100644 --- a/docs/users_guide/glasgow_exts.rst +++ b/docs/users_guide/glasgow_exts.rst @@ -45,15 +45,18 @@ Language options can be controlled in two ways: :ref:`language-pragma`). -The flag ``-fglasgow-exts`` ``-fglasgow-exts`` is equivalent to enabling -the following extensions: +Although not recommended, the deprecated :ghc-flag:`-fglasgow-exts` flag enables +a large swath of the extensions supported by GHC at once. -.. include:: what_glasgow_exts_does.gen.rst +.. ghc-flag:: -fglasgow-exts -Enabling these -options is the *only* effect of ``-fglasgow-exts``. We are trying to -move away from this portmanteau flag, and towards enabling features -individually. + The flag ``-fglasgow-exts`` is equivalent to enabling the following extensions: + + .. include:: what_glasgow_exts_does.gen.rst + + Enabling these options is the *only* effect of ``-fglasgow-exts``. We are trying + to move away from this portmanteau flag, and towards enabling features + individually. .. _primitives: @@ -76,7 +79,7 @@ documentation is generated from the file ``compiler/prelude/primops.txt.pp``.) If you want to mention any of the primitive data types or operations in your program, you must first import ``GHC.Prim`` to bring them into scope. Many of them have names ending in ``#``, and to mention such names -you need the ``-XMagicHash`` extension (:ref:`magic-hash`). +you need the :ghc-flag:`-XMagicHash` extension (:ref:`magic-hash`). The primops make extensive use of `unboxed types <#glasgow-unboxed>`__ and `unboxed tuples <#unboxed-tuples>`__, which we briefly summarise @@ -174,11 +177,13 @@ There are some restrictions on the use of primitive types: Unboxed tuples -------------- -Unboxed tuples aren't really exported by ``GHC.Exts``; they are a -syntactic extension enabled by the language flag ``-XUnboxedTuples``. An -unboxed tuple looks like this: +.. ghc-flag:: -XUnboxedTuples -:: + Enable the use of unboxed tuple syntax. + +Unboxed tuples aren't really exported by ``GHC.Exts``; they are a +syntactic extension enabled by the language flag :ghc-flag:`-XUnboxedTuples`. An +unboxed tuple looks like this: :: (# e_1, ..., e_n #) @@ -242,7 +247,12 @@ Syntactic extensions Unicode syntax -------------- -The language extension ``-XUnicodeSyntax``\ ``-XUnicodeSyntax`` enables +.. ghc-flag:: -XUnicodeSyntax + + Enable the use of Unicode characters in place of their equivalent ASCII + sequences. + +The language extension :ghc-flag:`-XUnicodeSyntax` enables Unicode characters to be used to stand for certain ASCII character sequences. The following alternatives are provided: @@ -276,22 +286,26 @@ sequences. The following alternatives are provided: The magic hash -------------- -The language extension ``-XMagicHash`` allows "#" as a postfix modifier -to identifiers. Thus, "x#" is a valid variable, and "T#" is a valid type +.. ghc-flag:: -XMagicHash + + Enable the use of the hash character (``#``) as an identifier suffix. + +The language extension :ghc-flag:`-XMagicHash` 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 ``-XMagicHash`` extension bring anything into +variables. Nor does the :ghc-flag:`-XMagicHash` extension bring anything into scope. For example, to bring ``Int#`` into scope you must import -``GHC.Prim`` (see :ref:`primitives`); the ``-XMagicHash`` extension then +``GHC.Prim`` (see :ref:`primitives`); the :ghc-flag:`-XMagicHash` 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 ``-XMagicHash`` also enables some new forms of literals (see +The :ghc-flag:`-XMagicHash` also enables some new forms of literals (see :ref:`glasgow-unboxed`): - ``'x'#`` has type ``Char#`` @@ -314,9 +328,13 @@ The ``-XMagicHash`` also enables some new forms of literals (see Negative literals ----------------- +.. ghc-flag:: -XNegativeLiterals + + Enable the use of un-parenthesized negative numeric literals. + The literal ``-123`` is, according to Haskell98 and Haskell 2010, desugared as ``negate (fromInteger 123)``. The language extension -``-XNegativeLiterals`` means that it is instead desugared as +:ghc-flag:`-XNegativeLiterals` means that it is instead desugared as ``fromInteger (-123)``. This can make a difference when the positive and negative range of a @@ -329,10 +347,14 @@ elicit an unexpected integer-literal-overflow message. Fractional looking integer literals ----------------------------------- +.. ghc-flag:: -XNumDecimals + + 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 ``-XNumDecimals`` allows you to also use the +The language extension :ghc-flag:`-XNumDecimals` allows you to also use the floating literal syntax for instances of ``Integral``, and have values like ``(1.2e6 :: Num a => a)`` @@ -341,14 +363,18 @@ like ``(1.2e6 :: Num a => a)`` Binary integer literals ----------------------- +.. ghc-flag:: -XBinaryLiterals + + 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 ``-XBinaryLiterals`` adds support for expressing -integer literals in binary notation with the prefix ``0b`` or ``0B``. -For instance, the binary integer literal ``0b11001001`` will be -desugared into ``fromInteger 201`` when ``-XBinaryLiterals`` is enabled. +The language extension :ghc-flag:`-XBinaryLiterals` adds support for expressing +integer literals in binary notation with the prefix ``0b`` or ``0B``. For +instance, the binary integer literal ``0b11001001`` will be desugared into +``fromInteger 201`` when :ghc-flag:`-XBinaryLiterals` is enabled. .. _hierarchical-modules: @@ -366,16 +392,12 @@ names are *always* fully qualified, so you can just think of the fully qualified module name as “the module name”. In particular, this means that the full module name must be given after the ``module`` keyword at the beginning of the module; for example, the module ``A.B.C`` must -begin - -:: +begin :: module A.B.C It is a common strategy to use the ``as`` keyword to save some typing -when using qualified names with hierarchical modules. For example: - -:: +when using qualified names with hierarchical modules. For example: :: import qualified Control.Monad.ST.Strict as ST @@ -400,31 +422,26 @@ abbreviated version of Simon Peyton Jones's original implemented, so refers to them as unimplemented.) Suppose we have an abstract data type of finite maps, with a lookup -operation: - -:: +operation: :: lookup :: FiniteMap -> Int -> Maybe Int The lookup returns ``Nothing`` if the supplied key is not in the domain of the mapping, and ``(Just v)`` otherwise, where ``v`` is the value -that the key maps to. Now consider the following definition: - -:: - - clunky env var1 var2 | ok1 && ok2 = val1 + val2 - | otherwise = var1 + var2 - where - m1 = lookup env var1 - m2 = lookup env var2 - ok1 = maybeToBool m1 - ok2 = maybeToBool m2 - val1 = expectJust m1 - val2 = expectJust m2 +that the key maps to. Now consider the following definition: :: -The auxiliary functions are + clunky env var1 var2 + | ok1 && ok2 = val1 + val2 + | otherwise = var1 + var2 + where + m1 = lookup env var1 + m2 = lookup env var2 + ok1 = maybeToBool m1 + ok2 = maybeToBool m2 + val1 = expectJust m1 + val2 = expectJust m2 -:: +The auxiliary functions are :: maybeToBool :: Maybe a -> Bool maybeToBool (Just x) = True @@ -443,9 +460,7 @@ takes the ``otherwise`` case and returns the sum of its arguments. This is certainly legal Haskell, but it is a tremendously verbose and un-obvious way to achieve the desired effect. Arguably, a more direct -way to write clunky would be to use case expressions: - -:: +way to write clunky would be to use case expressions: :: clunky env var1 var2 = case lookup env var1 of Nothing -> fail @@ -464,9 +479,7 @@ of each other. This structure is hidden in the case version. Two of the right-hand sides are really the same (``fail``), and the whole expression tends to become more and more indented. -Here is how I would write clunky: - -:: +Here is how I would write ``clunky``: :: clunky env var1 var2 | Just val1 <- lookup env var1 @@ -486,9 +499,7 @@ introduced by pattern guards scope over all the remaining guard qualifiers, and over the right hand side of the equation. Just as with list comprehensions, boolean expressions can be freely -mixed with among the pattern guards. For example: - -:: +mixed with among the pattern guards. For example: :: f x | [y] <- x , y > 3 @@ -503,7 +514,11 @@ the qualifier list has just one element, a boolean expression. View patterns ------------- -View patterns are enabled by the flag ``-XViewPatterns``. More +.. ghc-flag:: -XViewPatterns + + Allow use of view pattern syntax. + +View patterns are enabled by the flag :ghc-flag:`-XViewPatterns`. More information and examples of view patterns can be found on the :ghc-wiki:`Wiki page <ViewPatterns>`. @@ -511,9 +526,7 @@ 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: - -:: +language as follows: :: type Typ @@ -526,9 +539,7 @@ language as follows: The representation of Typ is held abstract, permitting implementations to use a fancy representation (e.g., hash-consing to manage sharing). -Without view patterns, using this signature a little inconvenient: - -:: +Without view patterns, using this signature a little inconvenient: :: size :: Typ -> Integer size t = case view t of @@ -540,9 +551,7 @@ 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: - -:: +matching against the result: :: size (view -> Unit) = 1 size (view -> Arrow t1 t2) = size t1 + size t2 @@ -564,9 +573,7 @@ follows: 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 - :ref:`pattern-guards` can be written using view patterns as follows: - - :: + :ref:`pattern-guards` can be written using view patterns as follows: :: clunky env (lookup env -> Just val1) (lookup env -> Just val2) = val1 + val2 ...other equations for clunky... @@ -574,18 +581,14 @@ follows: More precisely, the scoping rules are: - In a single pattern, variables bound by patterns to the left of a - view pattern expression are in scope. For example: - - :: + view pattern expression are in scope. For example: :: example :: Maybe ((String -> Integer,Integer), String) -> Bool example Just ((f,_), f -> 4) = True Additionally, in function definitions, variables bound by matching earlier curried arguments may be used in view pattern expressions - in later arguments: - - :: + in later arguments: :: example :: (String -> Integer) -> String -> Bool example f (f -> 4) = True @@ -597,9 +600,7 @@ follows: 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: - - :: + allowed: :: let {(x -> y) = e1 ; (y -> x) = e2 } in x @@ -610,9 +611,7 @@ follows: then the whole view pattern matches a ⟨T1⟩. - Matching: To the equations in Section 3.17.3 of the `Haskell 98 - Report <http://www.haskell.org/onlinereport/>`__, add the following: - - :: + Report <http://www.haskell.org/onlinereport/>`__, add the following: :: case v of { (e -> p) -> e1 ; _ -> e2 } = @@ -653,7 +652,11 @@ follows: Pattern synonyms ---------------- -Pattern synonyms are enabled by the flag ``-XPatternSynonyms``, which is +.. ghc-flag:: -XPatternSynonyms + + Allow the definition of pattern synonyms. + +Pattern synonyms are enabled by the flag :ghc-flag:`-XPatternSynonyms`, which is required for defining them, but *not* for using them. More information and examples of view patterns can be found on the `Wiki page <PatternSynonyms>`. @@ -661,16 +664,12 @@ and examples of view patterns can be found on the 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 example, in a programming language -implementation, we might represent types of the language as follows: - -:: +implementation, we might represent types of the language as follows: :: data Type = App String [Type] Here are some examples of using said representation. Consider a few -types of the ``Type`` universe encoded like this: - -:: +types of the ``Type`` universe encoded like this: :: App "->" [t1, t2] -- t1 -> t2 App "Int" [] -- Int @@ -680,9 +679,7 @@ 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: - -:: +respectively: :: collectArgs :: Type -> [Type] collectArgs (App "->" [t1, t2]) = t1 : collectArgs t2 @@ -693,9 +690,7 @@ respectively: isInt _ = False 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: - -:: +write. And the situation is even worse when the matching is nested: :: isIntEndo :: Type -> Bool isIntEndo (App "->" [App "Int" [], App "Int" []]) = True @@ -705,17 +700,13 @@ Pattern synonyms permit abstracting from the representation to expose matchers that behave 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): - -:: +these don't have to be defined in the same module as the ``Type`` type): :: pattern Arrow t1 t2 = App "->" [t1, t2] pattern Int = App "Int" [] pattern Maybe t = App "Maybe" [t] -Which enables us to rewrite our functions in a much cleaner style: - -:: +Which enables us to rewrite our functions in a much cleaner style: :: collectArgs :: Type -> [Type] collectArgs (Arrow t1 t2) = t1 : collectArgs t2 @@ -735,17 +726,13 @@ 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. - -:: +`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. - -:: +directly used the `Type` constructors. :: intEndo :: Type intEndo = App "->" [App "Int" [], App "Int" []] @@ -784,7 +771,7 @@ The table below summarises where each kind of pattern synonym can be used. | Expression | No | Yes (Inferred)| Yes (Explicit) | +---------------+----------------+---------------+---------------------------+ -.. _record-patsyns: +.. _record-patsyn: Record Pattern Synonyms ~~~~~~~~~~~~~~~~~~~~~~~ @@ -832,21 +819,15 @@ Syntax and scoping of pattern synonyms A pattern synonym declaration can be either unidirectional, bidirectional or explicitly bidirectional. -The syntax for unidirectional pattern synonyms is: - -:: +The syntax for unidirectional pattern synonyms is: :: pattern pat_lhs <- pat -the syntax for bidirectional pattern synonyms is: - -:: +the syntax for bidirectional pattern synonyms is: :: pattern pat_lhs = pat -and the syntax for explicitly bidirectional pattern synonyms is: - -:: +and the syntax for explicitly bidirectional pattern synonyms is: :: pattern pat_lhs <- pat where pat_lhs = expr @@ -886,9 +867,7 @@ constructors. Like normal data constructors, pattern synonyms can be imported and exported through association 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.: - -:: +prefix pattern names with the ``pattern`` keyword, e.g.: :: module Example (pattern Zero) where @@ -902,9 +881,7 @@ 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: - -:: +example: :: import Data.Maybe( pattern Just ) @@ -913,9 +890,7 @@ type, without also bringing the type constructor ``Maybe`` into scope. To bundle a pattern synonym with a type constructor, 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: - -:: +For example, to bundle ``Zero`` with ``MyNum`` we could write the following: :: module Example ( MyNum(Zero) ) where @@ -923,9 +898,7 @@ 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: - -:: +all currently bundled constructors. For example, we could write: :: module Example ( MyNum(.., Zero) ) where @@ -934,8 +907,8 @@ the data constructor ``MkNum`` and also the pattern synonym ``Zero``. Bundled patterns synoyms 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`. +``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 @@ -945,15 +918,11 @@ A module which imports ``MyNum(..)`` from ``Example`` and then re-exports Typing of pattern synonyms ~~~~~~~~~~~~~~~~~~~~~~~~~~ -Given a pattern synonym definition of the form - -:: +Given a pattern synonym definition of the form :: pattern P var1 var2 ... varN <- pat -it is assigned a *pattern type* of the form - -:: +it is assigned a *pattern type* of the form :: pattern P :: CReq => CProf => t1 -> t2 -> ... -> tN -> t @@ -966,9 +935,7 @@ contexts ⟨CProv⟩ and ⟨CReq⟩: - ⟨CReq⟩ are the constraints *required* to match the pattern. -For example, consider - -:: +For example, consider :: data T a where MkT :: (Show b) => a -> b -> T a @@ -1010,7 +977,7 @@ Note also the following points pattern SinglePair :: (a, a) -> [(a, a)] pattern SinglePair x = [x] -- The GHCi ``:info`` command shows pattern types in this format. +- The GHCi :ghci-cmd:`:info` command shows pattern types in this format. - For a bidirectional pattern synonym, a use of the pattern synonym as an expression has the type @@ -1029,9 +996,7 @@ Note also the following points 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: - - :: +- Consider these two pattern synonyms: :: data S a where S1 :: Bool -> S Bool @@ -1073,9 +1038,7 @@ Matching of pattern synonyms A pattern synonym occurrence in a pattern is evaluated by first matching against the pattern synonym itself, and then on the argument patterns. -For example, in the following program, ``f`` and ``f'`` are equivalent: - -:: +For example, in the following program, ``f`` and ``f'`` are equivalent: :: pattern Pair x y <- [x, y] @@ -1088,7 +1051,7 @@ For example, in the following program, ``f`` and ``f'`` are equivalent: Note that the strictness of ``f`` differs from that of ``g`` defined below: -:: +.. code-block:: none g [True, True] = True g _ = False @@ -1103,17 +1066,19 @@ below: n+k patterns ------------ -.. index:: - single: -XNPlusKPatterns +.. ghc-flag:: -XNPlusKPatterns -``n+k`` pattern support is disabled by default. To enable it, you can -use the ``-XNPlusKPatterns`` flag. + Enable use of ``n+k`` patterns. .. _recursive-do-notation: The recursive do-notation ------------------------- +.. ghc-flag:: -XRecursiveDo + + 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 @@ -1123,9 +1088,7 @@ 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 -``Control.Monad.Fix`` as follows: - -:: +``Control.Monad.Fix`` as follows: :: class Monad m => MonadFix m where mfix :: (a -> m a) -> m a @@ -1137,7 +1100,7 @@ the negative side, the continuation monad, with the signature For monads that do belong to the ``MonadFix`` class, GHC provides an extended version of the do-notation that allows recursive bindings. The -``-XRecursiveDo`` (language pragma: ``RecursiveDo``) provides the +:ghc-flag:`-XRecursiveDo` (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`` expression, those introduced by ``mdo`` and ``rec`` @@ -1173,7 +1136,7 @@ lower level syntax flagged by the ``rec`` keyword, as we describe next. Recursive binding groups ~~~~~~~~~~~~~~~~~~~~~~~~ -The flag ``-XRecursiveDo`` also introduces a new keyword ``rec``, which +The flag :ghc-flag:`-XRecursiveDo` 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 @@ -1292,7 +1255,7 @@ version would do so. Here are some other important points in using the recursive-do notation: -- It is enabled with the flag ``-XRecursiveDo``, or the +- It is enabled with the flag :ghc-flag:`-XRecursiveDo`, or the ``LANGUAGE RecursiveDo`` pragma. (The same flag enables both ``mdo``-notation, and the use of ``rec`` blocks inside ``do`` expressions.) @@ -1323,9 +1286,12 @@ Applicative do-notation .. index:: single: Applicative do-notation single: do-notation; Applicative - single: -XApplicativeDo -The language option ``-XApplicativeDo`` enables an alternative translation for +.. ghc-flag:: -XApplicativeDo + + Allow use of ``Applicative`` ``do`` notation. + +The language option :ghc-flag:`-XApplicativeDo` 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: @@ -1337,14 +1303,12 @@ as far as possible. There are two main reasons for wanting to do this: Applicative do-notation desugaring preserves the original semantics, provided that the ``Applicative`` instance satisfies ``<*> = ap`` and ``pure = return`` (these are true of all the common monadic types). Thus, you can normally turn on -``-XApplicativeDo`` without fear of breaking your program. There is one pitfall +:ghc-flag:`-XApplicativeDo` without fear of breaking your program. There is one pitfall to watch out for; see :ref:`applicative-do-pitfall`. -There are no syntactic changes with ``-XApplicativeDo``. The only way it shows +There are no syntactic changes with :ghc-flag:`-XApplicativeDo`. 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: - -:: +require a ``Monad`` constraint. For example, in GHCi: :: Prelude> :set -XApplicativeDo Prelude> :t \m -> do { x <- m; return (not x) } @@ -1352,29 +1316,23 @@ require a ``Monad`` constraint. For example, in GHCi: :: Functor f => f Bool -> f Bool This example only requires ``Functor``, because it is translated into ``(\x -> -not x) <$> m``. A more complex example requires ``Applicative``, - -:: +not x) <$> m``. A more complex example requires ``Applicative``, :: Prelude> :t \m -> do { x <- m 'a'; y <- m 'b'; return (x || y) } \m -> do { x <- m 'a'; y <- m 'b'; return (x || y) } :: Applicative f => (Char -> f Bool) -> f Bool -Here GHC has translated the expression into - -:: +Here GHC has translated the expression into :: (\x y -> x || y) <$> m 'a' <*> m 'b' -It is possible to see the actual translation by using ``-ddump-ds``, but be +It is possible to see the actual translation by using :ghc-flag:`-ddump-ds`, 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: - -:: +``do``-block: :: Prelude> :t \m -> do { x <- m True; y <- m x; return (x || y) } \m -> do { x <- m True; y <- m x; return (x || y) } @@ -1384,9 +1342,7 @@ 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: - -:: +is as follows. If the do-expression has the following form: :: do p1 <- E1; ...; pn <- En; return E @@ -1400,27 +1356,21 @@ will require ``Monad``. Things to watch out for ~~~~~~~~~~~~~~~~~~~~~~~ -Your code should just work as before when ``-XApplicativeDo`` is enabled, +Your code should just work as before when :ghc-flag:`-XApplicativeDo` is enabled, provided you use conventional ``Applicative`` instances. However, if you define a ``Functor`` or ``Applicative`` instance using do-notation, then it will likely -get turned into an infinite loop by GHC. For example, if you do this: - -:: +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) -Then applicative desugaring will turn it into - -:: +Then applicative desugaring will turn it into :: instance Functor MyType where fmap f m = fmap (\x -> f x) m And the program will loop at runtime. Similarly, an ``Applicative`` instance -like this - -:: +like this :: instance Applicative MyType where pure = return @@ -1431,9 +1381,7 @@ will result in an infinte loop when ``<*>`` is called. Just as you wouldn't define a ``Monad`` instance using the do-notation, you shouldn't define ``Functor`` or ``Applicative`` instance using do-notation (when using ``ApplicativeDo``) either. The correct way to define these instances in -terms of ``Monad`` is to use the ``Monad`` operations directly, e.g. - -:: +terms of ``Monad`` is to use the ``Monad`` operations directly, e.g. :: instance Functor MyType where fmap f m = m >>= return . f @@ -1452,6 +1400,10 @@ Parallel List Comprehensions single: list comprehensions; parallel single: parallel list comprehensions +.. ghc-flag:: -XParallelListComp + + Allow parallel list comprehension syntax. + Parallel list comprehensions are a natural extension to list comprehensions. List comprehensions can be thought of as a nice syntax for writing maps and filters. Parallel comprehensions extend this to @@ -1459,9 +1411,7 @@ include the ``zipWith`` family. A parallel list comprehension has multiple independent branches of qualifier lists, each separated by a ``|`` symbol. For example, the -following zips together two lists: - -:: +following zips together two lists: :: [ (x, y) | x <- xs | y <- ys ] @@ -1472,18 +1422,14 @@ branch. We can define parallel list comprehensions by translation to regular comprehensions. Here's the basic idea: -Given a parallel comprehension of the form: - -:: +Given a parallel comprehension of the form: :: [ e | p1 <- e11, p2 <- e12, ... | q1 <- e21, q2 <- e22, ... ... ] -This will be translated to: - -:: +This will be translated to: :: [ e | ((p1,p2), (q1,q2), ...) <- zipN [(p1,p2) | p1 <- e11, p2 <- e12, ...] [(q1,q2) | q1 <- e21, q2 <- e22, ...] @@ -1494,7 +1440,7 @@ where ``zipN`` is the appropriate zip for the given number of branches. .. _generalised-list-comprehensions: -Generalised (SQL-Like) List Comprehensions +Generalised (SQL-like) List Comprehensions ------------------------------------------ .. index:: @@ -1503,6 +1449,11 @@ Generalised (SQL-Like) List Comprehensions single: group single: SQL +.. ghc-flag:: -XTransformListComp + + 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 syntactic sugar to allow operations such as sorting and grouping which are familiar from SQL. They are fully described in the @@ -1510,23 +1461,23 @@ paper `Comprehensive comprehensions: comprehensions with "order by" and "group by" <http://research.microsoft.com/~simonpj/papers/list-comp>`__, except that the syntax we use differs slightly from the paper. -The extension is enabled with the flag ``-XTransformListComp``. +The extension is enabled with the flag :ghc-flag:`-XTransformListComp`. Here is an example: :: employees = [ ("Simon", "MS", 80) - , ("Erik", "MS", 100) - , ("Phil", "Ed", 40) - , ("Gordon", "Ed", 45) - , ("Paul", "Yale", 60)] + , ("Erik", "MS", 100) + , ("Phil", "Ed", 40) + , ("Gordon", "Ed", 45) + , ("Paul", "Yale", 60) ] output = [ (the dept, sum salary) - | (name, dept, salary) <- employees - , then group by dept using groupWith - , then sortWith by (sum salary) - , then take 5 ] + | (name, dept, salary) <- employees + , then group by dept using groupWith + , then sortWith by (sum salary) + , then take 5 ] In this example, the list ``output`` would take on the value: @@ -1643,59 +1594,47 @@ work for any monad. Monad comprehensions support: -- Bindings: - - :: +- Bindings: :: [ x + y | x <- Just 1, y <- Just 2 ] Bindings are translated with the ``(>>=)`` and ``return`` functions - to the usual do-notation: - - :: + to the usual do-notation: :: do x <- Just 1 y <- Just 2 return (x+y) -- Guards: - - :: +- Guards: :: [ x | x <- [1..10], x <= 5 ] Guards are translated with the ``guard`` function, which requires a - ``MonadPlus`` instance: - - :: + ``MonadPlus`` instance: :: do x <- [1..10] guard (x <= 5) return x -- Transform statements (as with ``-XTransformListComp``): - - :: +- Transform statements (as with :ghc-flag:`-XTransformListComp`): :: [ x+y | x <- [1..10], y <- [1..x], then take 2 ] - This translates to: - - :: + This translates to: :: do (x,y) <- take 2 (do x <- [1..10] y <- [1..x] return (x,y)) return (x+y) -- Group statements (as with ``-XTransformListComp``): +- Group statements (as with :ghc-flag:`-XTransformListComp`): :: [ x | x <- [1,1,2,2,3], then group by x using GHC.Exts.groupWith ] [ x | x <- [1,1,2,2,3], then group using myGroup ] -- Parallel statements (as with ``-XParallelListComp``): +- Parallel statements (as with :ghc-flag:`-XParallelListComp`): :: @@ -1804,8 +1743,10 @@ parameterised over some arbitrary type ``n`` (provided it has an New monadic failure desugaring mechanism ---------------------------------------- -.. index:: - single: -XMonadFailDesugaring option +.. ghc-flag:: -XMonadFailDesugaring + + Use the ``MonadFail.fail`` instead of the legacy ``Monad.fail`` function + when desugaring refutable patterns in ``do`` blocks. The ``-XMonadFailDesugaring`` extension switches the desugaring of ``do``-blocks to use ``MonadFail.fail`` instead of ``Monad.fail``. This will @@ -1822,8 +1763,9 @@ will work with future GHC versions. Rebindable syntax and the implicit Prelude import ------------------------------------------------- -.. index:: - single: -XNoImplicitPrelude option +.. ghc-flag:: -XNoImplicitPrelude + + Don't import ``Prelude`` by default. GHC normally imports ``Prelude.hi`` files for you. If you'd rather it didn't, then give it a ``-XNoImplicitPrelude`` @@ -1831,10 +1773,16 @@ 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.) +.. ghc-flag:: -XRebindableSyntax + + :implies: :ghc-flag:`-XNoImplicitPrelude` + + 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 "``Prelude.fromInteger 1``", which is what the Haskell -Report specifies. So the ``-XRebindableSyntax`` flag causes the +Report specifies. So the :ghc-flag:`-XRebindableSyntax` flag causes the following pieces of built-in syntax to refer to *whatever is in scope*, not the Prelude versions: @@ -1868,15 +1816,13 @@ not the Prelude versions: functions must match the Prelude types very closely. Details are in flux; if you want to use this, ask! -``-XRebindableSyntax`` implies ``-XNoImplicitPrelude``. +:ghc-flag:`-XRebindableSyntax` implies :ghc-flag:`-XNoImplicitPrelude`. 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: - -:: +any of the types: :: fromInteger :: Integer -> Integer fromInteger :: forall a. Foo a => Integer -> a @@ -1892,25 +1838,23 @@ Lint is happy you should be all right. Postfix operators ----------------- -The ``-XPostfixOperators`` flag 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 +.. ghc-flag:: -XPostfixOperators -:: + Allow the use of post-fix operators + +The :ghc-flag:`-XPostfixOperators` flag 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 - -:: +execution) to the expression :: ((!) e) (for any expression ``e`` and operator ``(!)``. The strict Haskell 98 -interpretation is that the section is equivalent to - -:: +interpretation is that the section is equivalent to :: (\y -> (!) e y) @@ -1926,43 +1870,35 @@ definitions; you must define such a function in prefix form. Tuple sections -------------- -The ``-XTupleSections`` flag enables Python-style partially applied -tuple constructors. For example, the following program +.. ghc-flag:: -XTupleSections -:: + Allow the use of tuple section syntax + +The :ghc-flag:`-XTupleSections` flag enables Python-style partially applied +tuple constructors. For example, the following program :: (, True) is considered to be an alternative notation for the more unwieldy -alternative - -:: +alternative :: \x -> (x, True) You can omit any combination of arguments to the tuple, as in the -following - -:: +following :: (, "I", , , "Love", , 1337) -which translates to - -:: +which translates to :: \a b c d -> (a, "I", b, c, "Love", d, 1337) If you have `unboxed tuples <#unboxed-tuples>`__ enabled, tuple sections -will also be available for them, like so - -:: +will also be available for them, like so :: (# , True #) -Because there is no unboxed unit tuple, the following expression - -:: +Because there is no unboxed unit tuple, the following expression :: (# #) @@ -1973,21 +1909,19 @@ continues to stand for the unboxed singleton tuple data constructor. Lambda-case ----------- -The ``-XLambdaCase`` flag enables expressions of the form +.. ghc-flag:: -XLambdaCase -:: + Allow the use of lambda-case syntax. - \case { p1 -> e1; ...; pN -> eN } +The :ghc-flag:`-XLambdaCase` flag enables expressions of the form :: -which is equivalent to + \case { p1 -> e1; ...; pN -> eN } -:: +which is equivalent to :: \freshName -> case freshName of { p1 -> e1; ...; pN -> eN } -Note that ``\case`` starts a layout, so you can write - -:: +Note that ``\case`` starts a layout, so you can write :: \case p1 -> e1 @@ -1999,14 +1933,18 @@ Note that ``\case`` starts a layout, so you can write Empty case alternatives ----------------------- -The ``-XEmptyCase`` flag enables case expressions, or lambda-case -expressions, that have no alternatives, thus: +.. ghc-flag:: -XEmptyCase -:: + Allow empty case expressions. - case e of { } -- No alternatives - or - \case { } -- -XLambdaCase is also required +The :ghc-flag:`-XEmptyCase` flag enables case expressions, or lambda-case +expressions, that have no alternatives, thus: :: + + case e of { } -- No alternatives + +or :: + + \case { } -- -XLambdaCase is also required This can be useful when you know that the expression being scrutinised has no non-bottom values. For example: @@ -2031,7 +1969,7 @@ 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 -should be able to compile with ``-Wincomplete-patterns``. (Though +should be able to compile with :ghc-flag:`-Wincomplete-patterns`. (Though the pattern match checking is not yet clever enough to do that.) On the other hand (A) looks dangerous, and GHC doesn't check to make sure that, in fact, the function can never get called. @@ -2041,18 +1979,18 @@ in fact, the function can never get called. Multi-way if-expressions ------------------------ -With ``-XMultiWayIf`` flag GHC accepts conditional expressions with -multiple branches: +.. ghc-flag:: -XMultiWayIf -:: + Allow the use of multi-way-``if`` syntax. + +With :ghc-flag:`-XMultiWayIf` flag GHC accepts conditional expressions with +multiple branches: :: if | guard1 -> expr1 | ... | guardN -> exprN -which is roughly equivalent to - -:: +which is roughly equivalent to :: case () of _ | guard1 -> expr1 @@ -2060,26 +1998,20 @@ which is roughly equivalent to _ | guardN -> exprN Multi-way if expressions introduce a new layout context. So the example -above is equivalent to: - -:: +above is equivalent to: :: if { | guard1 -> expr1 ; | ... ; | guardN -> exprN } -The following behaves as expected: - -:: +The following behaves as expected: :: if | guard1 -> if | guard2 -> expr2 | guard3 -> expr3 | guard4 -> expr4 -because layout translates it as - -:: +because layout translates it as :: if { | guard1 -> if { | guard2 -> expr2 ; | guard3 -> expr3 @@ -2104,9 +2036,7 @@ 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: - -:: +In GHC, a fixity declaration may accompany a local binding: :: let f = ... infixr 3 `f` @@ -2122,9 +2052,7 @@ 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 - -:: +elsewhere, as in :: let infixr 9 $ in ... @@ -2139,9 +2067,7 @@ Import and export extensions Hiding things the imported module doesn't export ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -Technically in Haskell 2010 this is illegal: - -:: +Technically in Haskell 2010 this is illegal: :: module A( f ) where f = True @@ -2158,20 +2084,22 @@ 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``, which is off by default but -included with ``-W``, warns if you hide something that the imported -module does not export. +The warning :ghc-flag:`-Wdodgy-imports`, which is off by default but included +with :ghc-flag:`-W`, warns if you hide something that the imported module does +not export. .. _package-qualified-imports: Package-qualified imports ~~~~~~~~~~~~~~~~~~~~~~~~~ -With the ``-XPackageImports`` flag, GHC allows import declarations to be -qualified by the package name that the module is intended to be imported -from. For example: +.. ghc-flag:: -XPackageImports -:: + Allow the use of package-qualified ``import`` syntax. + +With the :ghc-flag:`-XPackageImports` flag, GHC allows import declarations to be +qualified by the package name that the module is intended to be imported +from. For example: :: import "network" Network.Socket @@ -2196,12 +2124,17 @@ package being built. Safe imports ~~~~~~~~~~~~ -With the ``-XSafe``, ``-XTrustworthy`` and ``-XUnsafe`` 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: +.. ghc-flag:: -XSafe + -XTrustworthy + -XUnsafe + :noindex: -:: + Declare the Safe Haskell state of the current module. + +With the :ghc-flag:`-XSafe`, :ghc-flag:`-XTrustworthy` and :ghc-flag:`-XUnsafe` +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: :: import safe qualified Network.Socket as NS @@ -2214,9 +2147,11 @@ when a import is considered safe see :ref:`safe-haskell`. Explicit namespaces in import/export ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -In an import or export list, such as +.. ghc-flag:: -XExplicitNamespaces -:: + Enable use of explicit namespaces in module export lists. + +In an import or export list, such as :: module M( f, (++) ) where ... import N( f, (++) ) @@ -2227,11 +2162,9 @@ operators (:ref:`type-operators`) it becomes possible to declare ``(++)`` as a *type constructor*. In that case, how would you export or import it? -The ``-XExplicitNamespaces`` extension allows you to prefix the name of +The :ghc-flag:`-XExplicitNamespaces` extension allows you to prefix the name of a type constructor in an import or export list with "``type``" to -disambiguate this case, thus: - -:: +disambiguate this case, thus: :: module M( f, type (++) ) where ... import N( f, type (++) ) @@ -2239,10 +2172,10 @@ disambiguate this case, thus: module N( f, type (++) ) where data family a ++ b = L a | R b -The extension ``-XExplicitNamespaces`` is implied by ``-XTypeOperators`` -and (for some reason) by ``-XTypeFamilies``. +The extension :ghc-flag:`-XExplicitNamespaces` is implied by +:ghc-flag:`-XTypeOperators` and (for some reason) by :ghc-flag:`-XTypeFamilies`. -In addition, with ``-XPatternSynonyms`` you can prefix the name of a +In addition, with :ghc-flag:`-XPatternSynonyms` 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 :ref:`patsyn-impexp`). @@ -2252,7 +2185,13 @@ its parent type constructor (see :ref:`patsyn-impexp`). Visible type application ~~~~~~~~~~~~~~~~~~~~~~~~ -The ``-XTypeApplications`` extension allows you to use +.. ghc-flag:: -XTypeApplications + + :since: 8.0 + + Allow the use of type application syntax. + +The :ghc-flag:`-XTypeApplications` extension allows you to use *visible type application* in expressions. Here is an example: ``show (read @Int "5")``. The ``@Int`` is the visible type application; it specifies the value of the type variable @@ -2281,7 +2220,7 @@ Here are the details: in. So, ``class Monad m where return :: a -> m a`` means that ``return``'s type arguments are ``m, a``. -- With the ``-XRankNTypes`` extension +- With the :ghc-flag:`-XRankNTypes` extension (:ref:`universal-quantification`), it is possible to declare type arguments somewhere other than the beginning of a type. For example, we can have ``pair :: forall a. a -> forall b. b -> (a, b)`` @@ -2294,7 +2233,7 @@ Here are the details: ``wurble``, then you can say ``wurble @_ @Int``. The first argument is a wildcard, just like in a partial type signature. However, if used in a visible type application, it is *not* - necessary to specify ``-XPartialTypeSignatures`` and your + necessary to specify :ghc-flag:`-XPartialTypeSignatures` and your code will not generate a warning informing you of the omitted type. .. _syntax-stolen: @@ -2326,57 +2265,57 @@ The following syntax is stolen: .. index:: single: forall - Stolen (in types) by: ``-XExplicitForAll``, and hence by - ``-XScopedTypeVariables``, ``-XLiberalTypeSynonyms``, - ``-XRankNTypes``, ``-XExistentialQuantification`` + Stolen (in types) by: :ghc-flag:`-XExplicitForAll`, and hence by + :ghc-flag:`-XScopedTypeVariables`, :ghc-flag:`-XLiberalTypeSynonyms`, + :ghc-flag:`-XRankNTypes`, :ghc-flag:`-XExistentialQuantification` ``mdo`` .. index:: single: mdo - Stolen by: ``-XRecursiveDo`` + Stolen by: :ghc-flag:`-XRecursiveDo` ``foreign`` .. index:: single: foreign - Stolen by: ``-XForeignFunctionInterface`` + Stolen by: :ghc-flag:`-XForeignFunctionInterface` ``rec``, ``proc``, ``-<``, ``>-``, ``-<<``, ``>>-``, ``(|``, ``|)`` .. index:: single: proc - Stolen by: ``-XArrows`` + Stolen by: :ghc-flag:`-XArrows` ``?varid`` .. index:: single: implicit parameters - Stolen by: ``-XImplicitParams`` + Stolen by: :ghc-flag:`-XImplicitParams` ``[|``, ``[e|``, ``[p|``, ``[d|``, ``[t|``, ``$(``, ``$$(``, ``[||``, ``[e||``, ``$varid``, ``$$varid`` .. index:: single: Template Haskell - Stolen by: ``-XTemplateHaskell`` + Stolen by: :ghc-flag:`-XTemplateHaskell` ``[varid|`` .. index:: single: quasi-quotation - Stolen by: ``-XQuasiQuotes`` + Stolen by: :ghc-flag:`-XQuasiQuotes` ⟨varid⟩, ``#``\ ⟨char⟩, ``#``, ⟨string⟩, ``#``, ⟨integer⟩, ``#``, ⟨float⟩, ``#``, ⟨float⟩, ``##`` - Stolen by: ``-XMagicHash`` + Stolen by: :ghc-flag:`-XMagicHash` ``(#``, ``#)`` - Stolen by: ``-XUnboxedTuples`` + Stolen by: :ghc-flag:`-XUnboxedTuples` ⟨varid⟩, ``!``, ⟨varid⟩ - Stolen by: ``-XBangPatterns`` + Stolen by: :ghc-flag:`-XBangPatterns` ``pattern`` - Stolen by: ``-XPatternSynonyms`` + Stolen by: :ghc-flag:`-XPatternSynonyms` .. _data-type-extensions: @@ -2388,10 +2327,12 @@ Extensions to data types and type synonyms Data types with no constructors ------------------------------- -With the ``-XEmptyDataDecls`` flag (or equivalent ``LANGUAGE`` pragma), GHC -lets you declare a data type with no constructors. For example: +.. ghc-flag:: -XEmptyDataDecls -:: + Allow definition of empty ``data`` types. + +With the :ghc-flag:`-XEmptyDataDecls` flag (or equivalent ``LANGUAGE`` pragma), GHC +lets you declare a data type with no constructors. For example: :: data S -- S :: * data T a -- T :: * -> * @@ -2408,15 +2349,15 @@ can be useful when defining "phantom types". Data type contexts ------------------ -Haskell allows datatypes to be given contexts, e.g. +.. ghc-flag:: -XDatatypeContexts -:: + Allow contexts on ``data`` types. + +Haskell allows datatypes to be given contexts, e.g. :: data Eq a => Set a = NilSet | ConsSet a (Set a) -give constructors with types: - -:: +give constructors with types: :: NilSet :: Set a ConsSet :: Eq a => a -> Set a -> Set a @@ -2441,9 +2382,7 @@ specifically: ``:``. - Data type and type-synonym declarations can be written infix, - parenthesised if you want further arguments. E.g. - - :: + parenthesised if you want further arguments. E.g. :: data a :*: b = Foo a b type a :+: b = Either a b @@ -2452,9 +2391,7 @@ specifically: data (a :**: b) x = Baz a b x type (a :++: b) y = Either (a,b) y -- Types, and class constraints, can be written infix. For example - - :: +- Types, and class constraints, can be written infix. For example :: x :: Int :*: Bool f :: (a :=: b) => a -> b @@ -2467,9 +2404,7 @@ specifically: for data constructors. However, one cannot distinguish between the two in a fixity declaration; a fixity declaration sets the fixity for a data constructor and the corresponding type constructor. For - example: - - :: + example: :: infixl 7 T, :*: @@ -2484,6 +2419,10 @@ specifically: Type operators -------------- +.. ghc-flag:: -XTypeOperators + + 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 @@ -2498,15 +2437,13 @@ In types, an operator symbol like ``(+)`` is normally treated as a type 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 ``-XTypeOperators`` changes this behaviour: +The language :ghc-flag:`-XTypeOperators` 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: - - :: + and uses. For example: :: data a + b = Plus a b type Foo = Int + Bool @@ -2514,11 +2451,9 @@ The language ``-XTypeOperators`` changes this behaviour: - 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 ``-XExplicitNamespaces`` (which is implied by - ``-XTypeOperators``) GHC allows you to specify the latter by - preceding it with the keyword ``type``, thus: - - :: + but with :ghc-flag:`-XExplicitNamespaces` (which is implied by + :ghc-flag:`-XTypeOperators`) GHC allows you to specify the latter by + preceding it with the keyword ``type``, thus: :: import M( type (+) ) @@ -2533,16 +2468,18 @@ The language ``-XTypeOperators`` changes this behaviour: Liberalised type synonyms ------------------------- +.. ghc-flag:: -XLiberalTypeSynonyms + + 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 individual synonym declarations. With the -``-XLiberalTypeSynonyms`` extension, GHC does validity checking on types +:ghc-flag:`-XLiberalTypeSynonyms` 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: - - :: + thus: :: type Discard a = forall b. Show b => a -> b -> (a, String) @@ -2552,42 +2489,32 @@ much more liberal about type synonyms than Haskell 98. g :: Discard Int -> (Int,String) -- A rank-2 type g f = f 3 True -- If you also use ``-XUnboxedTuples``, you can write an unboxed tuple - in a type synonym: - - :: +- If you also use :ghc-flag:`-XUnboxedTuples`, you can write an unboxed tuple + in a type synonym: :: type Pr = (# Int, Int #) h :: Int -> Pr h x = (# x, x #) -- You can apply a type synonym to a forall type: - - :: +- You can apply a type synonym to a forall type: :: type Foo a = a -> a -> Bool f :: Foo (forall b. b->b) - After expanding the synonym, ``f`` has the legal (in GHC) type: - - :: + After expanding the synonym, ``f`` has the legal (in GHC) type: :: f :: (forall b. b->b) -> (forall b. b->b) -> Bool -- You can apply a type synonym to a partially applied type synonym: - - :: +- You can apply a type synonym to a partially applied type synonym: :: type Generic i o = forall x. i x -> o x type Id x = x foo :: Generic Id [] - After expanding the synonym, ``foo`` has the legal (in GHC) type: - - :: + After expanding the synonym, ``foo`` has the legal (in GHC) type: :: foo :: forall x. x -> [x] @@ -2599,13 +2526,11 @@ looking for the following mal-formedness which isn't detected simply by kind checking: - Type constructor applied to a type involving for-alls (if - ``XImpredicativeTypes`` is off) + :ghc-flag:`-XImpredicativeTypes` is off) - Partially-applied type synonym. -So, for example, this will be rejected: - -:: +So, for example, this will be rejected: :: type Pr = forall a. a @@ -2619,6 +2544,10 @@ because GHC does not allow type constructors applied to for-all types. Existentially quantified data constructors ------------------------------------------ +.. ghc-flag:: -XExistentialQuantification + + Allow the use of ``forall`` syntax. + 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 Programming Languages*, PhD @@ -2626,25 +2555,19 @@ 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: - -:: +Here's the idea. Consider the declaration: :: data Foo = forall a. MkFoo a (a -> Bool) | Nil -The data type ``Foo`` has two constructors with types: - -:: +The data type ``Foo`` has two constructors with types: :: MkFoo :: forall a. a -> (a -> Bool) -> Foo Nil :: Foo 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: - -:: +following expression is fine: :: [MkFoo 3 even, MkFoo 'c' isUpper] :: [Foo] @@ -2654,17 +2577,13 @@ 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``? - -:: +happens when we pattern-match on ``MkFoo``? :: f (MkFoo val fn) = ??? 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: - -:: +``val`` to get a boolean. For example: :: f :: Foo -> Bool f (MkFoo val fn) = fn val @@ -2680,9 +2599,7 @@ Why existential? ~~~~~~~~~~~~~~~~ What has this to do with *existential* quantification? Simply that -``MkFoo`` has the (nearly) isomorphic type - -:: +``MkFoo`` has the (nearly) isomorphic type :: MkFoo :: (exists a . (a, a -> Bool)) -> Foo @@ -2696,16 +2613,12 @@ Existentials and type classes ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ An easy extension is to allow arbitrary contexts before the constructor. -For example: - -:: +For example: :: data Baz = forall a. Eq a => Baz1 a a | forall b. Show b => Baz2 b (b -> b) -The two constructors have the types you'd expect: - -:: +The two constructors have the types you'd expect: :: Baz1 :: forall a. Eq a => a -> a -> Baz Baz2 :: forall b. Show b => b -> (b -> b) -> Baz @@ -2713,9 +2626,7 @@ The two constructors have the types you'd expect: 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: - -:: +it). So this program is legal: :: f :: Baz -> String f (Baz1 p q) | p == q = "Yes" @@ -2732,9 +2643,7 @@ Record Constructors ~~~~~~~~~~~~~~~~~~~ GHC allows existentials to be used with records syntax as well. For -example: - -:: +example: :: data Counter a = forall self. NewCounter { _this :: self @@ -2753,9 +2662,7 @@ 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: - -:: +functions: :: inc :: Counter a -> Counter a inc (NewCounter x i d t) = NewCounter @@ -2764,9 +2671,7 @@ functions: display :: Counter a -> IO () display NewCounter{ _this = x, _display = d } = d x -Now we can define counters with different underlying implementations: - -:: +Now we can define counters with different underlying implementations: :: counterA :: Counter String counterA = NewCounter @@ -2780,23 +2685,19 @@ Now we can define counters with different underlying implementations: display (inc counterA) -- prints "1" display (inc (inc counterB)) -- prints "##" -Record update syntax is supported for existentials (and GADTs): - -:: +Record update syntax is supported for existentials (and GADTs): :: setTag :: Counter a -> a -> Counter a setTag obj t = obj{ tag = t } The rule for record update is this: - the types of the updated fields may - mention only the universally-quantified type variables of the data - constructor. For GADTs, the field may mention only types that appear as - a simple type-variable argument in the constructor's result type. + the types of the updated fields may mention only the universally-quantified + type variables of the data constructor. For GADTs, the field may mention + only types that appear as a simple type-variable argument in the + constructor's result type. -For example: - -:: +For example: :: data T a b where { T1 { f1::a, f2::b, f3::(b,c) } :: T a b } -- c is existential upd1 t x = t { f1=x } -- OK: upd1 :: T a b -> a' -> T a' b @@ -2817,30 +2718,22 @@ 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: - - :: + 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: - - :: + type ``f1`` has: :: f1 :: Foo -> a -- Weird! - What is this "``a``" in the result type? Clearly we don't mean this: - - :: + What is this "``a``" in the result type? Clearly we don't mean this: :: f1 :: forall a. Foo -> a -- Wrong! The original program is just plain wrong. Here's another sort of - error - - :: + error :: f2 (Baz1 a b) (Baz1 p q) = a==q @@ -2849,15 +2742,11 @@ constructors can be used. constructors. - You can't pattern-match on an existentially quantified constructor in - a ``let`` or ``where`` group of bindings. So this is illegal: - - :: + a ``let`` or ``where`` group of bindings. So this is illegal: :: f3 x = a==b where { Baz1 a b = x } - Instead, use a ``case`` expression: - - :: + Instead, use a ``case`` expression: :: f3 x = case x of Baz1 a b -> a==b @@ -2872,9 +2761,7 @@ constructors can be used. simple-to-state restriction. We'll see how annoying it is. - You can't use existential quantification for ``newtype`` - declarations. So this is illegal: - - :: + declarations. So this is illegal: :: newtype T = forall a. Ord a => MkT a @@ -2891,16 +2778,12 @@ constructors can be used. - 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:; - - :: + 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: - - :: + between the single component of two ``MkT`` constructors: :: instance Eq T where (MkT a) == (MkT b) = ??? @@ -2915,11 +2798,14 @@ constructors can be used. Declaring data types with explicit constructor signatures --------------------------------------------------------- +.. ghc-flag:: -XGADTSyntax + + Allow the use of GADT syntax in data type definitions (but not GADTs + themselves; for this see :ghc-flag:`-XGADTs`) + 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: - -:: +explicitly. For example: :: data Maybe a where Nothing :: Maybe a @@ -2931,9 +2817,7 @@ using this form. Notice that GADT-style syntax generalises existential types (:ref:`existential-quantification`). For example, these two declarations -are equivalent: - -:: +are equivalent: :: data Foo = forall a. MkFoo a (a -> Bool) data Foo' where { MKFoo :: a -> (a->Bool) -> Foo' } @@ -2943,9 +2827,7 @@ 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. Specifically, if the constructor is given a type-class context, that -context is made available by pattern matching. For example: - -:: +context is made available by pattern matching. For example: :: data Set a where MkSet :: Eq a => [a] -> Set a @@ -2968,9 +2850,7 @@ 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: - -:: +For example, one possible application is to reify dictionaries: :: data NumInst a where MkNumInst :: Num a => NumInst a @@ -2986,9 +2866,7 @@ Here, a value of type ``NumInst a`` is equivalent to an explicit All this applies to constructors declared using the syntax of :ref:`existential-with-context`. For example, the ``NumInst`` data type -above could equivalently be declared like this: - -:: +above could equivalently be declared like this: :: data NumInst a = Num a => MkNumInst (NumInst a) @@ -2997,9 +2875,7 @@ 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: - -:: +declarations are equivalent: :: data T1 a = forall b. (Num a, Eq b) => MkT1 a b @@ -3008,9 +2884,7 @@ declarations are equivalent: 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 - -:: +Report). In Haskell 98 the definition :: data Eq a => Set' a = MkSet' [a] @@ -3032,9 +2906,7 @@ type declarations. - As with other type signatures, you can give a single signature for several data constructors. In this example we give a single signature - for ``T1`` and ``T2``: - - :: + for ``T1`` and ``T2``: :: data T a where T1,T2 :: a -> T a @@ -3044,27 +2916,21 @@ type declarations. implicitly universally quantified 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 - variables: - - :: + variables: :: data T a where -- The 'a' has no scope T1,T2 :: b -> T b -- Means forall b. b -> T b T3 :: T a -- Means forall a. T a - A constructor signature may mention type class constraints, which can - differ for different constructors. For example, this is fine: - - :: + 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: - - :: + discharge constraints in the body of the match. For example: :: f :: T a -> String f (T1 x y) | x==y = "yes" @@ -3077,29 +2943,21 @@ type declarations. - 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: - - :: + write a kind signature instead: :: data Set :: * -> * where ... - or even a mixture of the two: - - :: + or even a mixture of the two: :: data Bar a :: (* -> *) -> * where ... The type variables (if given) may be explicitly kinded, so we could - also write the header for ``Foo`` like this: - - :: + also write the header for ``Foo`` like this: :: data Bar a (b :: * -> *) where ... - You can use strictness annotations, in the obvious places in the - constructor type: - - :: + constructor type: :: data Term a where Lit :: !Int -> Term Int @@ -3107,9 +2965,7 @@ type declarations. Pair :: Term a -> Term b -> Term (a,b) - You can use a ``deriving`` clause on a GADT-style data type - declaration. For example, these two declarations are equivalent - - :: + declaration. For example, these two declarations are equivalent :: data Maybe1 a where { Nothing1 :: Maybe1 a ; @@ -3120,9 +2976,7 @@ type declarations. deriving( Eq, Ord ) - The type signature may have quantified type variables that do not - appear in the result type: - - :: + appear in the result type: :: data Foo where MkFoo :: a -> (a->Bool) -> Foo @@ -3134,16 +2988,12 @@ type declarations. "existential". Indeed, the above declaration declares precisely the same type as the ``data Foo`` in :ref:`existential-quantification`. - The type may contain a class context too, of course: - - :: + The type may contain a class context too, of course: :: data Showable where MkShowable :: Show a => a -> Showable -- You can use record syntax on a GADT-style data type declaration: - - :: +- You can use record syntax on a GADT-style data type declaration: :: data Person where Adult :: { name :: String, children :: [Person] } -> Person @@ -3165,9 +3015,7 @@ type declarations. - As in the case of existentials declared using the Haskell-98-like record syntax (:ref:`existential-records`), 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: - - :: + Here is the example of that section, in GADT-style syntax: :: data Counter a where NewCounter :: { _this :: self @@ -3200,11 +3048,15 @@ type declarations. Generalised Algebraic Data Types (GADTs) ---------------------------------------- +.. ghc-flag:: -XGADTs + + :implies: :ghc-flag:`-XMonoLocalBinds` + + Allow use of Generalised Algebraic Data Types (GADTs). + Generalised Algebraic Data Types generalise ordinary algebraic data types by allowing constructors to have richer return types. Here is an -example: - -:: +example: :: data Term a where Lit :: Int -> Term Int @@ -3215,9 +3067,7 @@ 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``: - -:: +allows us to write a well-typed ``eval`` function for these ``Terms``: :: eval :: Term a -> a eval (Lit i) = i @@ -3227,9 +3077,7 @@ allows us to write a well-typed ``eval`` function for these ``Terms``: eval (Pair e1 e2) = (eval e1, eval e2) The key point about GADTs is that *pattern matching causes type -refinement*. For example, in the right hand side of the equation - -:: +refinement*. For example, in the right hand side of the equation :: eval :: Term a -> a eval (Lit i) = ... @@ -3243,9 +3091,7 @@ GADTs <http://research.microsoft.com/%7Esimonpj/papers/gadt/>`__, (ICFP 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: - -:: +example, if we had: :: eval :: Term a -> a -> a eval (Lit i) j = i+j @@ -3264,8 +3110,8 @@ 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 ``-XGADTs``. The ``-XGADTs`` flag -also sets ``-XGADTSyntax`` and ``-XMonoLocalBinds``. +GADTs. The extension is enabled with :ghc-flag:`-XGADTs`. The :ghc-flag:`-XGADTs` flag +also sets :ghc-flag:`-XGADTSyntax` and :ghc-flag:`-XMonoLocalBinds`. - A GADT can only be declared using GADT-style syntax (:ref:`gadt-style`); the old Haskell 98 syntax for data declarations @@ -3341,17 +3187,23 @@ Extensions to the record system Traditional record syntax ------------------------- -.. index:: - single: -XNoTraditionalRecordSyntax +.. ghc-flag:: -XNoTraditionalRecordSyntax + + Disallow use of record syntax. Traditional record syntax, such as ``C {f = x}``, is enabled by default. -To disable it, you can use the ``-XNoTraditionalRecordSyntax`` flag. +To disable it, you can use the :ghc-flag:`-XNoTraditionalRecordSyntax` flag. .. _disambiguate-fields: Record field disambiguation --------------------------- +.. ghc-flag:: -XDisambiguateRecordFields + + 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: @@ -3369,8 +3221,8 @@ data types in scope with a common field name. For example: ok1 (MkS { x = n }) = n+1 -- Unambiguous ok2 n = MkT { x = n+1 } -- Unambiguous - bad1 k = k { x = 3 } -- Ambiguous - bad2 k = x k -- Ambiguous + 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 @@ -3379,7 +3231,7 @@ 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 -``-XDisambiguateRecordFields`` flag, GHC will accept the former two. The +:ghc-flag:`-XDisambiguateRecordFields` flag, 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 @@ -3391,21 +3243,17 @@ use the same field name. Some details: - Field disambiguation can be combined with punning (see - :ref:`record-puns`). For example: - - :: + :ref:`record-puns`). For example: :: module Foo where import M x=True ok3 (MkS { x }) = x+1 -- Uses both disambiguation and punning -- With ``-XDisambiguateRecordFields`` you can use *unqualified* field +- With :ghc-flag:`-XDisambiguateRecordFields` 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: - - :: + example, this is legal: :: module Foo where import qualified M -- Note qualified @@ -3422,12 +3270,14 @@ Some details: Duplicate record fields ----------------------- -Going beyond ``-XDisambiguateRecordFields`` (see :ref:`disambiguate-fields`), -the ``-XDuplicateRecordFields`` extension allows multiple datatypes to be -declared using the same field names in a single module. For example, it allows -this: +.. ghc-flag:: -XDuplicateRecordFields -:: + Allow definition of record types with identically-named fields. + +Going beyond :ghc-flag:`-XDisambiguateRecordFields` (see :ref:`disambiguate-fields`), +the :ghc-flag:`-XDuplicateRecordFields` 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 } @@ -3436,9 +3286,7 @@ this: 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 -``-XDisambiguateRecordFields``): - -:: +:ghc-flag:`-XDisambiguateRecordFields`): :: s = MkS { x = 3 } @@ -3452,17 +3300,13 @@ 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: - -:: +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 occurrence of the selector (see :ref:`higher-rank-type-inference` for more -details on what "pushed down" means). For example, the following are permitted: - -:: +details on what "pushed down" means). For example, the following are permitted: :: ok1 = x :: S -> Int @@ -3472,17 +3316,13 @@ details on what "pushed down" means). For example, the following are permitted: ok3 = k x -- assuming we already have k :: (S -> Int) -> _ In addition, the datatype that is meant may be given as a type signature on the -argument to the selector: - -:: +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: - -:: +following is ambiguous: :: bad :: S -> Int bad s = x s @@ -3497,30 +3337,24 @@ 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: - -:: +definitions: :: data S = MkS { foo :: Int } data T = MkT { foo :: Int, bar :: Int } data U = MkU { bar :: Int, baz :: Int } -Without ``-XDuplicateRecordFields``, an update mentioning ``foo`` will always be +Without :ghc-flag:`-XDuplicateRecordFields`, an update mentioning ``foo`` will always be ambiguous 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: - - :: +- Check for types that have all the fields being updated. For example: :: f x = x { foo = 3, bar = 2 } Here ``f`` must be updating ``T`` because neither ``S`` nor ``U`` have both fields. -- Use the type being pushed in to the record update, as in the following: - - :: +- Use the type being pushed in to the record update, as in the following: :: g1 :: T -> T g1 x = x { foo = 3 } @@ -3529,17 +3363,13 @@ there are several options for disambiguating updates: g3 = k (x { foo = 3 }) -- assuming we already have k :: T -> _ -- Use an explicit type signature on the record expression, as in: - - :: +- Use an explicit type signature on the record expression, as in: :: 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: - -:: +ambiguous: :: let x :: T x = blah @@ -3552,19 +3382,15 @@ ambiguous: Import and export of record fields ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -When ``-XDuplicateRecordFields`` is enabled, an ambiguous field must be exported +When :ghc-flag:`-XDuplicateRecordFields` is enabled, an ambiguous field must be exported as part of its datatype, rather than at the top level. For example, the -following is legal: - -:: +following is legal: :: module M (S(x), T(..)) where data S = MkS { x :: Int } data T = MkT { x :: Bool } -However, this would not be permitted, because ``x`` is ambiguous: - -:: +However, this would not be permitted, because ``x`` is ambiguous: :: module M (x) where ... @@ -3575,20 +3401,20 @@ Similar restrictions apply on import. Record puns ----------- -Record puns are enabled by the flag ``-XNamedFieldPuns``. +.. ghc-flag:: -XNamedFieldPuns -When using records, it is common to write a pattern that binds a -variable with the same name as a record field, such as: + Allow use of record puns. -:: +Record puns are enabled by the flag :ghc-flag:`-XNamedFieldPuns`. + +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 - -:: +write :: f (C {a}) = a @@ -3599,15 +3425,11 @@ pattern ``a`` expands into the pattern ``a = a`` for the same name Note that: - Record punning can also be used in an expression, writing, for - example, - - :: + example, :: let a = 1 in C {a} - instead of - - :: + instead of :: let a = 1 in C {a = a} @@ -3615,9 +3437,7 @@ Note that: 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 and other patterns can be mixed in the same record: :: data C = C {a :: Int, b :: Int} f (C {a, b = 4}) = a @@ -3626,15 +3446,11 @@ Note that: bindings or at the top-level). - A pun on a qualified field name is expanded by stripping off the - module qualifier. For example: - - :: + module qualifier. For example: :: f (C {M.a}) = a - means - - :: + means :: f (M.C {M.a = a}) = a @@ -3646,22 +3462,24 @@ Note that: Record wildcards ---------------- -Record wildcards are enabled by the flag ``-XRecordWildCards``. This -flag implies ``-XDisambiguateRecordFields``. +.. ghc-flag:: -XRecordWildCards -For records with many fields, it can be tiresome to write out each field -individually in a record pattern, as in + :implies: :ghc-flag:`-XDisambiguateRecordFields`. -:: + Allow the use of wildcards in record construction and pattern matching. + +Record wildcards are enabled by the flag :ghc-flag:`-XRecordWildCards`. This +flag implies :ghc-flag:`-XDisambiguateRecordFields`. + +For records with many fields, it can be tiresome to write out each field +individually in a record pattern, as in :: data C = C {a :: Int, b :: Int, c :: Int, d :: Int} f (C {a = 1, b = b, c = c, d = d}) = b + c + d Record wildcard syntax permits a "``..``" in a record pattern, where each elided field ``f`` is replaced by the pattern ``f = f``. For -example, the above pattern can be written as - -:: +example, the above pattern can be written as :: f (C {a = 1, ..}) = b + c + d @@ -3671,24 +3489,18 @@ More details: including puns (:ref:`record-puns`); 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 - - :: + 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, - - :: + a record. For example, :: let {a = 1; b = 2; c = 3; d = 4} in C {..} - in place of - - :: + in place of :: let {a = 1; b = 2; c = 3; d = 4} in C {a=a, b=b, c=c, d=d} @@ -3697,9 +3509,7 @@ More details: as the omitted field names. - Record wildcards may *not* be used in record *updates*. For example - this is illegal: - - :: + this is illegal: :: f r = r { x = 3, .. } @@ -3717,9 +3527,7 @@ More details: selector itself. These rules restrict record wildcards to the situations in which the - user could have written the expanded version. For example - - :: + user could have written the expanded version. For example :: module M where data R = R { a,b,c :: Int } @@ -3734,9 +3542,7 @@ More details: - Record wildcards cannot be used (a) in a record update construct, and (b) for data constructors that are not declared with record fields. - For example: - - :: + For example: :: f x = x { v=True, .. } -- Illegal (a) @@ -3755,18 +3561,14 @@ Inferred context for deriving clauses ------------------------------------- The Haskell Report is vague about exactly when a ``deriving`` clause is -legal. For example: - -:: +legal. For example: :: data T0 f a = MkT0 a deriving( Eq ) data T1 f a = MkT1 (f a) deriving( Eq ) data T2 f a = MkT2 (f (f a)) deriving( Eq ) The natural generated ``Eq`` code would result in these instance -declarations: - -:: +declarations: :: instance Eq a => Eq (T0 f a) where ... instance Eq (f a) => Eq (T1 f a) where ... @@ -3789,10 +3591,12 @@ mechanism <#stand-alone-deriving>`__. Stand-alone deriving declarations --------------------------------- -GHC allows stand-alone ``deriving`` declarations, enabled by -``-XStandaloneDeriving``: +.. ghc-flag:: -XStandaloneDeriving -:: + Allow the use of stand-alone ``deriving`` declarations. + +GHC allows stand-alone ``deriving`` declarations, enabled by +:ghc-flag:`-XStandaloneDeriving`: :: data Foo a = Bar a | Baz String @@ -3816,10 +3620,8 @@ number of important ways: - Unlike a ``deriving`` declaration attached to a ``data`` declaration, the instance can be more specific than the data type (assuming you - also use ``-XFlexibleInstances``, :ref:`instance-rules`). Consider - for example - - :: + also use :ghc-flag:`-XFlexibleInstances`, :ref:`instance-rules`). Consider + for example :: data Foo a = Bar a | Baz String @@ -3838,9 +3640,7 @@ number of important ways: 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: - - :: + does indeed typecheck. For example: :: data T a where T1 :: T Int @@ -3867,9 +3667,7 @@ ordinary deriving: - The stand-alone syntax is generalised for newtypes in exactly the same way that ordinary ``deriving`` clauses are generalised - (:ref:`newtype-deriving`). For example: - - :: + (:ref:`newtype-deriving`). For example: :: newtype Foo a = MkFoo (State Int a) @@ -3883,6 +3681,26 @@ ordinary deriving: Deriving instances of extra classes (``Data``, etc.) ---------------------------------------------------- +.. ghc-flag:: -XDeriveGeneric + + Allow automatic deriving of instances for the ``Generic`` typeclass. + +.. ghc-flag:: -XDeriveFunctor + + Allow automatic deriving of instances for the ``Functor`` typeclass. + +.. ghc-flag:: -XDeriveFoldable + + :implies: :ghc-flag:`-XDeriveFunctor` + + Allow automatic deriving of instances for the ``Foldable`` typeclass. + +.. ghc-flag:: -XDeriveTraversable + + :implies: :ghc-flag:`-XDeriveFoldable`, :ghc-flag:`-XDeriveFunctor` + + Allow automatic deriving of instances for the ``Traversable`` typeclass. + 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 @@ -3893,32 +3711,32 @@ classes ``Eq``, ``Ord``, ``Enum``, ``Ix``, ``Bounded``, ``Read``, and GHC extends this list with several more classes that may be automatically derived: -- With ``-XDeriveGeneric``, you can derive instances of the classes +- With :ghc-flag:`-XDeriveGeneric`, you can derive instances of the classes ``Generic`` and ``Generic1``, defined in ``GHC.Generics``. You can use these to define generic functions, as described in :ref:`generic-programming`. -- With ``-XDeriveFunctor``, you can derive instances of the class +- With :ghc-flag:`-XDeriveFunctor`, you can derive instances of the class ``Functor``, defined in ``GHC.Base``. See :ref:`deriving-functor`. -- With ``-XDeriveDataTypeable``, you can derive instances of the class +- With :ghc-flag:`-XDeriveDataTypeable`, you can derive instances of the class ``Data``, defined in ``Data.Data``. See :ref:`deriving-typeable` for deriving ``Typeable``. -- With ``-XDeriveFoldable``, you can derive instances of the class +- With :ghc-flag:`-XDeriveFoldable`, you can derive instances of the class ``Foldable``, defined in ``Data.Foldable``. See :ref:`deriving-foldable`. -- With ``-XDeriveTraversable``, you can derive instances of the class +- With :ghc-flag:`-XDeriveTraversable`, you can derive instances of the class ``Traversable``, defined in ``Data.Traversable``. Since the ``Traversable`` instance dictates the instances of ``Functor`` and ``Foldable``, you'll probably want to derive them too, so - ``-XDeriveTraversable`` implies ``-XDeriveFunctor`` and - ``-XDeriveFoldable``. See :ref:`deriving-traversable`. + :ghc-flag:`-XDeriveTraversable` implies :ghc-flag:`-XDeriveFunctor` and + :ghc-flag:`-XDeriveFoldable`. See :ref:`deriving-traversable`. -- With ``-XDeriveLift``, you can derive instances of the class ``Lift``, defined - in the ``Language.Haskell.TH.Syntax`` module of the ``template-haskell`` - package. See :ref:`deriving-lift`. +- With :ghc-flag:`-XDeriveLift`, you can derive instances of the class ``Lift``, + defined in the ``Language.Haskell.TH.Syntax`` module of the + ``template-haskell`` package. See :ref:`deriving-lift`. You can also use a standalone deriving declaration instead (see :ref:`stand-alone-deriving`). @@ -3931,7 +3749,7 @@ mentioned in the ``deriving`` clause. Deriving ``Functor`` instances ------------------------------ -With ``-XDeriveFunctor``, one can derive ``Functor`` instances for data types +With :ghc-flag:`-XDeriveFunctor`, one can derive ``Functor`` instances for data types of kind ``* -> *``. For example, this declaration:: data Example a = Ex a Char (Example a) (Example Char) @@ -3942,7 +3760,7 @@ would generate the following instance: :: instance Functor Example where fmap f (Ex a1 a2 a3 a4) = Ex (f a1) a2 (fmap f a3) a4 -The basic algorithm for ``-XDeriveFunctor`` walks the arguments of each +The basic algorithm for :ghc-flag:`-XDeriveFunctor` 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 @@ -3967,7 +3785,7 @@ The difference involves the placement of the last type parameter, ``a``. In the 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 ``-XDeriveFunctor`` works. The +This distinction is important because of the way :ghc-flag:`-XDeriveFunctor` works. The derived ``Functor Right`` instance would be:: instance Functor Right where @@ -3994,7 +3812,7 @@ last argument of a type constructor (as in ``Right`` above). There are two exceptions to this rule: #. Tuple types. When a non-unit tuple is used on the right-hand side of a data - declaration, ``-XDeriveFunctor`` treats it as a product of distinct types. + declaration, :ghc-flag:`-XDeriveFunctor` treats it as a product of distinct types. In other words, the following code:: newtype Triple a = Triple (a, Int, [a]) deriving Functor @@ -4006,7 +3824,7 @@ There are two exceptions to this rule: Triple (case a of (a1, a2, a3) -> (f a1, a2, fmap f a3)) - That is, ``-XDeriveFunctor`` pattern-matches its way into tuples and maps + That is, :ghc-flag:`-XDeriveFunctor` pattern-matches its way into tuples and maps over each type that constitutes the tuple. The generated code is reminiscient of what would be generated from ``data Triple a = Triple a Int [a]``, except with extra machinery to handle @@ -4072,11 +3890,11 @@ fail to compile: #. A data type has no type parameters (e.g., ``data Nothing = Nothing``). -#. A data type's last type variable is used in a ``-XDatatypeContexts`` +#. A data type's last type variable is used in a :ghc-flag:`-XDatatypeContexts` constraint (e.g., ``data Ord a => O a = O a``). #. A data type's last type variable is used in an - ``-XExistentialQuantification`` constraint, or is refined in a GADT. For + :ghc-flag:`-XExistentialQuantification` constraint, or is refined in a GADT. For example, :: data T a b where @@ -4093,7 +3911,7 @@ fail to compile: Deriving ``Foldable`` instances ------------------------------- -With ``-XDeriveFoldable``, one can derive ``Foldable`` instances for data types +With :ghc-flag:`-XDeriveFoldable`, one can derive ``Foldable`` instances for data types of kind ``* -> *``. For example, this declaration:: data Example a = Ex a Char (Example a) (Example Char) @@ -4105,26 +3923,26 @@ would generate the following instance:: foldr f z (Ex a1 a2 a3 a4) = f a1 (foldr f z a3) foldMap f (Ex a1 a2 a3 a4) = mappend (f a1) (foldMap f a3) -The algorithm for ``-XDeriveFoldable`` is adapted from the ``-XDeriveFunctor`` +The algorithm for :ghc-flag:`-XDeriveFoldable` is adapted from the :ghc-flag:`-XDeriveFunctor` algorithm, but it generates definitions for ``foldMap`` and ``foldr`` instead of ``fmap``. Here are the differences between the generated code in each extension: -#. When a bare type variable ``a`` is encountered, ``-XDeriveFunctor`` would - generate ``f a`` for an ``fmap`` definition. ``-XDeriveFoldable`` would +#. When a bare type variable ``a`` is encountered, :ghc-flag:`-XDeriveFunctor` would + generate ``f a`` for an ``fmap`` definition. :ghc-flag:`-XDeriveFoldable` would generate ``f a z`` for ``foldr``, and ``f a`` for ``foldMap``. #. When a type that is not syntactically equivalent to ``a``, but which does - contain ``a``, is encountered, ``-XDeriveFunctor`` recursively calls - ``fmap`` on it. Similarly, ``-XDeriveFoldable`` would recursively call + contain ``a``, is encountered, :ghc-flag:`-XDeriveFunctor` recursively calls + ``fmap`` on it. Similarly, :ghc-flag:`-XDeriveFoldable` would recursively call ``foldr`` and ``foldMap``. -#. When a type that does not mention ``a`` is encountered, ``-XDeriveFunctor`` - leaves it alone. On the other hand, ``-XDeriveFoldable`` would generate +#. When a type that does not mention ``a`` is encountered, :ghc-flag:`-XDeriveFunctor` + leaves it alone. On the other hand, :ghc-flag:`-XDeriveFoldable` would generate ``z`` (the state value) for ``foldr`` and ``mempty`` for ``foldMap``. -#. ``-XDeriveFunctor`` puts everything back together again at the end by - invoking the constructor. ``-XDeriveFoldable``, however, builds up a value +#. :ghc-flag:`-XDeriveFunctor` puts everything back together again at the end by + invoking the constructor. :ghc-flag:`-XDeriveFoldable`, 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``. @@ -4178,7 +3996,7 @@ There are some other differences regarding what data types can have derived Deriving ``Traversable`` instances ---------------------------------- -With ``-XDeriveTraversable``, one can derive ``Traversable`` instances for data +With :ghc-flag:`-XDeriveTraversable`, one can derive ``Traversable`` instances for data types of kind ``* -> *``. For example, this declaration:: data Example a = Ex a Char (Example a) (Example Char) @@ -4190,34 +4008,34 @@ would generate the following ``Traversable`` instance:: traverse f (Ex a1 a2 a3 a4) = fmap Ex (f a1) <*> traverse f a3 -The algorithm for ``-XDeriveTraversable`` is adapted from the -``-XDeriveFunctor`` algorithm, but it generates a definition for ``traverse`` +The algorithm for :ghc-flag:`-XDeriveTraversable` is adapted from the +:ghc-flag:`-XDeriveFunctor` algorithm, but it generates a definition for ``traverse`` instead of ``fmap``. Here are the differences between the generated code in each extension: -#. When a bare type variable ``a`` is encountered, both ``-XDeriveFunctor`` and - ``-XDeriveTraversable`` would generate ``f a`` for an ``fmap`` and +#. When a bare type variable ``a`` is encountered, both :ghc-flag:`-XDeriveFunctor` and + :ghc-flag:`-XDeriveTraversable` would generate ``f a`` for an ``fmap`` and ``traverse`` definition, respectively. #. When a type that is not syntactically equivalent to ``a``, but which does - contain ``a``, is encountered, ``-XDeriveFunctor`` recursively calls - ``fmap`` on it. Similarly, ``-XDeriveTraversable`` would recursively call + contain ``a``, is encountered, :ghc-flag:`-XDeriveFunctor` recursively calls + ``fmap`` on it. Similarly, :ghc-flag:`-XDeriveTraversable` would recursively call ``traverse``. -#. When a type that does not mention ``a`` is encountered, ``-XDeriveFunctor`` - leaves it alone. On the other hand, ``-XDeriveTravserable`` would call +#. When a type that does not mention ``a`` is encountered, :ghc-flag:`-XDeriveFunctor` + leaves it alone. On the other hand, :ghc-flag:`-XDeriveTraversable` would call ``pure`` on the value of that type. -#. ``-XDeriveFunctor`` puts everything back together again at the end by - invoking the constructor. ``-XDeriveTraversable`` does something similar, +#. :ghc-flag:`-XDeriveFunctor` puts everything back together again at the end by + invoking the constructor. :ghc-flag:`-XDeriveTraversable` does something similar, but it works in an ``Applicative`` context by chaining everything together with ``(<*>)``. -Unlike ``-XDeriveFunctor``, ``-XDeriveTraversable`` cannot be used on data +Unlike :ghc-flag:`-XDeriveFunctor`, :ghc-flag:`-XDeriveTraversable` cannot be used on data types containing a function type on the right-hand side. -For a full specification of the algorithms used in ``-XDeriveFunctor``, -``-XDeriveFoldable``, and ``-XDeriveTraversable``, see +For a full specification of the algorithms used in :ghc-flag:`-XDeriveFunctor`, +:ghc-flag:`-XDeriveFoldable`, and :ghc-flag:`-XDeriveTraversable`, see :ghc-wiki:`this wiki page <Commentary/Compiler/DeriveFunctor>`. .. _deriving-typeable: @@ -4225,6 +4043,10 @@ For a full specification of the algorithms used in ``-XDeriveFunctor``, Deriving ``Typeable`` instances ------------------------------- +.. ghc-flag:: -XDeriveDataTypeable + + Enable automatic deriving of instances for the ``Typeable`` typeclass + The class ``Typeable`` is very special: - ``Typeable`` is kind-polymorphic (see :ref:`kind-polymorphism`). @@ -4239,9 +4061,7 @@ The class ``Typeable`` is very special: - The rules for solving \`Typeable\` constraints are as follows: - - A concrete type constructor applied to some types. - - :: + - A concrete type constructor applied to some types. :: instance (Typeable t1, .., Typeable t_n) => Typeable (T t1 .. t_n) @@ -4269,6 +4089,11 @@ The class ``Typeable`` is very special: Deriving ``Lift`` instances --------------------------- +.. ghc-flag:: -XDeriveLift + + 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 @@ -4313,7 +4138,7 @@ Here is an example of how one can derive ``Lift``: fooExp :: Lift a => Foo a -> Q Exp fooExp f = [| f |] -``-XDeriveLift`` also works for certain unboxed types (``Addr#``, ``Char#``, +:ghc-flag:`-XDeriveLift` also works for certain unboxed types (``Addr#``, ``Char#``, ``Double#``, ``Float#``, ``Int#``, and ``Word#``): :: @@ -4342,20 +4167,21 @@ Here is an example of how one can derive ``Lift``: Generalised derived instances for newtypes ------------------------------------------ +.. ghc-flag:: -XGeneralisedNewtypeDeriving + -XGeneralizedNewtypeDeriving + + Enable GHC's cunning generalised deriving mechanism for ``newtype``\s + 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 - -:: +explicit instance declaration. For example, if you define :: newtype Dollars = Dollars Int and you want to use arithmetic on ``Dollars``, you have to explicitly -define an instance of ``Num``: - -:: +define an instance of ``Num``: :: instance Num Dollars where Dollars a + Dollars b = Dollars (a+b) @@ -4372,17 +4198,13 @@ Generalising the deriving clause ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ GHC now permits such instances to be derived instead, using the flag -``-XGeneralizedNewtypeDeriving``, so one can write - -:: +:ghc-flag:`-XGeneralizedNewtypeDeriving`, so one can write :: newtype Dollars = Dollars Int deriving (Eq,Show,Num) and the implementation uses the *same* ``Num`` dictionary for ``Dollars`` as for ``Int``. Notionally, the compiler derives an instance -declaration of the form - -:: +declaration of the form :: instance Num Int => Num Dollars @@ -4391,31 +4213,23 @@ type. 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 - -:: +transformers, such that :: instance Monad m => Monad (State s m) instance Monad m => Monad (Failure m) -In Haskell 98, we can define a parsing monad by - -:: +In Haskell 98, we can define a parsing monad by :: type Parser tok m a = State [tok] (Failure m) a 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 - -:: +needing to write an instance of class ``Monad``, via :: newtype Parser tok m a = Parser (State [tok] (Failure m) a) deriving Monad -In this case the derived instance declaration is of the form - -:: +In this case the derived instance declaration is of the form :: instance Monad (State [tok] (Failure m)) => Monad (Parser tok m) @@ -4427,24 +4241,18 @@ 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 - -:: +example, given the class :: class StateMonad s m | m -> s where ... instance Monad m => StateMonad s (State s m) where ... -then we can derive an instance of ``StateMonad`` for ``Parser`` by - -:: +then we can derive an instance of ``StateMonad`` for ``Parser`` by :: newtype Parser tok m a = Parser (State [tok] (Failure m) a) deriving (Monad, StateMonad [tok]) The derived instance is obtained by completing the application of the -class to the new type: - -:: +class to the new type: :: instance StateMonad [tok] (State [tok] (Failure m)) => StateMonad [tok] (Parser tok m) @@ -4458,9 +4266,7 @@ A more precise specification ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ A derived instance is derived only for declarations of these forms -(after expansion of any type synonyms) - -:: +(after expansion of any type synonyms) :: newtype T v1..vn = MkT (t vk+1..vn) deriving (C t1..tj) newtype instance T s1..sk vk+1..vn = MkT (t vk+1..vn) deriving (C t1..tj) @@ -4492,21 +4298,15 @@ where missing last argument to ``C`` is not used at a nominal role in any of the ``C``'s methods. (See :ref:`roles`.) -Then the derived instance declaration is of the form - -:: +Then the derived instance declaration is of the form :: instance C t1..tj t => C t1..tj (T v1...vk) -As an example which does *not* work, consider - -:: +As an example which does *not* work, consider :: newtype NonMonad m s = NonMonad (State s m s) deriving Monad -Here we cannot derive the instance - -:: +Here we cannot derive the instance :: instance Monad (State s m) => Monad (NonMonad m) @@ -4518,9 +4318,7 @@ 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 - -:: +``StateMonad`` class above were instead defined as :: class StateMonad m s | m -> s where ... @@ -4540,7 +4338,11 @@ whether the standard method is used or the one described here.) Deriving any other class ------------------------ -With ``-XDeriveAnyClass`` you can derive any other class. The compiler +.. ghc-flag:: -XDeriveAnyClass + + Allow use of any typeclass in ``deriving`` clauses. + +With :ghc-flag:`-XDeriveAnyClass` you can derive any other class. The compiler will simply generate an instance declaration with no explicitly-defined methods. This is @@ -4559,7 +4361,7 @@ pretty strings: :: sPpr = show If a user does not provide a manual implementation for ``sPpr``, then it will -default to ``show``. Now we can leverage the ``-XDeriveAnyClass`` extension to +default to ``show``. Now we can leverage the :ghc-flag:`-XDeriveAnyClass` extension to easily implement a ``SPretty`` instance for a new data type: :: data Foo = Foo deriving (Show, SPretty) @@ -4570,16 +4372,16 @@ The above code is equivalent to: :: instance SPretty Foo That is, an ``SPretty Foo`` instance will be created with empty implementations -for all methods. Since we are using ``-XDefaultSignatures`` in this example, a +for all methods. Since we are using :ghc-flag:`-XDefaultSignatures` 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 ``-XGeneralizedNewtypeDeriving`` is also on, - ``-XDeriveAnyClass`` takes precedence. + class on a newtype, and :ghc-flag:`-XGeneralizedNewtypeDeriving` is also on, + :ghc-flag:`-XDeriveAnyClass` takes precedence. -- ``-XDeriveAnyClass`` is allowed only when the last argument of the class +- :ghc-flag:`-XDeriveAnyClass` is allowed only when the last argument of the class has kind ``*`` or ``(* -> *)``. So this is not allowed: :: data T a b = MkT a b deriving( Bifunctor ) @@ -4603,7 +4405,7 @@ Note the following details The constraints `C a` and `C (a,b)` are generated from the data constructor arguments, but the latter simplifies to `C a`. -- ``-XDeriveAnyClass`` can be used with partially applied classes, +- :ghc-flag:`-XDeriveAnyClass` can be used with partially applied classes, such as :: data T a = MKT a deriving( D Int ) @@ -4612,7 +4414,7 @@ Note the following details instance D Int a => D Int (T a) where {} -- ``-XDeriveAnyClass`` can be used to fill in default instances for +- :ghc-flag:`-XDeriveAnyClass` can be used to fill in default instances for associated type families: :: {-# LANGUAGE DeriveAnyClass, TypeFamilies #-} @@ -4652,28 +4454,32 @@ space <http://research.microsoft.com/~simonpj/Papers/type-class-design-space/>`_ Multi-parameter type classes ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -Multi-parameter type classes are permitted, with flag -``-XMultiParamTypeClasses``. For example: +.. ghc-flag:: -XMultiParamTypeClasses -:: + Allow the definition of typeclasses with more than one parameter. + +Multi-parameter type classes are permitted, with flag +:ghc-flag:`-XMultiParamTypeClasses`. For example: :: class Collection c a where - union :: c a -> c a -> c a - ...etc. + union :: c a -> c a -> c a + ...etc. .. _superclass-rules: The superclasses of a class declaration ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +.. ghc-flag:: -XFlexibleContexts + + Allow the use of complex constraints in class declaration contexts. + In Haskell 98 the context of a class declaration (which introduces superclasses) must be simple; that is, each predicate must consist of a -class applied to type variables. The flag ``-XFlexibleContexts`` +class applied to type variables. The flag :ghc-flag:`-XFlexibleContexts` (:ref:`flexible-contexts`) lifts this restriction, 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: - -:: +hierarchy must be acyclic. So these class declarations are OK: :: class Functor (m k) => FiniteMap m k where ... @@ -4681,17 +4487,14 @@ hierarchy must be acyclic. So these class declarations are OK: class (Monad m, Monad (t m)) => Transform t m where lift :: m a -> (t m) a -As in Haskell 98, The class hierarchy must be acyclic. However, the +As in Haskell 98, the class hierarchy must be acyclic. However, the definition of "acyclic" involves only the superclass relationships. For -example, this is OK: +example, this is okay: :: -:: - - class C a where { + class C a where op :: D b => a -> b -> b - } - class C a => D a where { ... } + class C a => D a where ... 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 @@ -4700,9 +4503,7 @@ superclass of ``C``.) With the extension that adds a `kind of constraints <#constraint-kind>`__, you can write more exotic superclass definitions. The superclass cycle check is even more liberal in these -case. For example, this is OK: - -:: +case. For example, this is OK: :: class A cls c where meth :: cls c => c -> c @@ -4719,10 +4520,12 @@ context. Class method types ~~~~~~~~~~~~~~~~~~ -Haskell 98 prohibits class method types to mention constraints on the -class type variable, thus: +.. ghc-flag:: -XConstrainedClassMethods -:: + 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: :: class Seq s a where fromList :: [a] -> s a @@ -4733,19 +4536,21 @@ constraint ``Eq a``, which constrains only the class type variable (in this case ``a``). GHC lifts this restriction with language extension -``-XConstrainedClassMethods``. The restriction is a pretty stupid one in -the first place, so ``-XConstrainedClassMethods`` is implied by -``-XMultiParamTypeClasses``. +:ghc-flag:`-XConstrainedClassMethods`. The restriction is a pretty stupid one in +the first place, so :ghc-flag:`-XConstrainedClassMethods` is implied by +:ghc-flag:`-XMultiParamTypeClasses`. .. _class-default-signatures: Default method signatures ~~~~~~~~~~~~~~~~~~~~~~~~~ -Haskell 98 allows you to define a default implementation when declaring -a class: +.. ghc-flag:: -XDefaultSignatures -:: + Allows the definition of default method signatures in class definitions. + +Haskell 98 allows you to define a default implementation when declaring +a class: :: class Enum a where enum :: [a] @@ -4753,12 +4558,10 @@ a class: The type of the ``enum`` method is ``[a]``, and this is also the type of the default method. You can lift this restriction and give another type -to the default method using the flag ``-XDefaultSignatures``. For +to the default method using the flag :ghc-flag:`-XDefaultSignatures`. For instance, if you have written a generic implementation of enumeration in a class ``GEnum`` with method ``genum`` in terms of ``GHC.Generics``, -you can specify a default method that uses that generic implementation: - -:: +you can specify a default method that uses that generic implementation: :: class Enum a where enum :: [a] @@ -4780,14 +4583,19 @@ We use default signatures to simplify generic programming in GHC Nullary type classes ~~~~~~~~~~~~~~~~~~~~ -Nullary (no parameter) type classes are enabled with ``-XMultiTypeClasses``; -historically, they were enabled with the (now deprecated) -``-XNullaryTypeClasses``. 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, -:: +.. ghc-flag:: -XNullaryTypeClasses + + Allows the use definition of type classes with no parameters. This flag + has been replaced by :ghc-flag:`-XMultiParamTypeClasses`. + + +Nullary (no parameter) type classes are enabled with +:ghc-flag:`-XMultiParamTypeClasses`; historically, they were enabled with the +(now deprecated) :ghc-flag:`-XNullaryTypeClasses`. 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, :: class RiemannHypothesis where assumeRH :: a -> a @@ -4799,8 +4607,7 @@ 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: -:: +dependence with: :: instance RiemannHypothesis where assumeRH = id @@ -4810,16 +4617,14 @@ dependence with: Functional dependencies ----------------------- -Functional dependencies are implemented as described by Mark Jones in -“`Type Classes with Functional -Dependencies <http://citeseer.ist.psu.edu/jones00type.html>`__”, Mark -P. Jones, In Proceedings of the 9th European Symposium on Programming, -ESOP 2000, Berlin, Germany, March 2000, Springer-Verlag LNCS 1782, . +.. ghc-flag:: -XFunctionalDependencies -Functional dependencies are introduced by a vertical bar in the syntax -of a class declaration; e.g. + Allow use of functional dependencies in class declarations. -:: +Functional dependencies are implemented as described by [Jones2000]_.Mark Jones in + +Functional dependencies are introduced by a vertical bar in the syntax +of a class declaration; e.g. :: class (Monad m) => MonadState s m | m -> s where ... @@ -4828,31 +4633,31 @@ of a class declaration; e.g. There should be more documentation, but there isn't (yet). Yell if you need it. +.. [Jones2000] + "`Type Classes with Functional + Dependencies <http://citeseer.ist.psu.edu/jones00type.html>`__", + Mark P. Jones, In *Proceedings of the 9th European Symposium on Programming*, + ESOP 2000, Berlin, Germany, March 2000, Springer-Verlag LNCS 1782, . + Rules for functional dependencies ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ In a class declaration, all of the class type variables must be reachable (in the sense mentioned in :ref:`flexible-contexts`) from the -free variables of each method type. For example: - -:: +free variables of each method type. For example: :: class Coll s a where empty :: s insert :: s -> a -> s is not OK, because the type of ``empty`` doesn't mention ``a``. -Functional dependencies can make the type variable reachable: - -:: +Functional dependencies can make the type variable reachable: :: class Coll s a | s -> a where empty :: s insert :: s -> a -> s -Alternatively ``Coll`` might be rewritten - -:: +Alternatively ``Coll`` might be rewritten :: class Coll s a where empty :: s a @@ -4860,9 +4665,7 @@ Alternatively ``Coll`` might be rewritten 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: - -:: +doesn't work, in which case you can split the class like this: :: class CollE s where empty :: s @@ -4878,9 +4681,7 @@ 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: - -:: +collection types: :: class Collects e ce where empty :: ce @@ -4893,9 +4694,7 @@ 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: - -:: +standard implementation details, this would lead to the following declarations: :: instance Eq e => Collects e [e] where ... instance Eq e => Collects e (e -> Bool) where ... @@ -4906,9 +4705,7 @@ 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: - -:: +ambiguous type: :: empty :: Collects e ce => ce @@ -4921,16 +4718,12 @@ with an ambiguous type. We can sidestep this specific problem by removing the empty member from the class declaration. 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: - -:: +we try to use them. For example, consider the following two functions: :: f x y = insert x . insert y g = f True 'a' -for which GHC infers the following types: - -:: +for which GHC infers the following types: :: f :: (Collects a c, Collects b c) => a -> b -> c -> c g :: (Collects Bool c, Collects Char c) => c -> c @@ -4950,9 +4743,7 @@ An attempt to use constructor classes Faced with the problems described above, some Haskell programmers might be tempted to use something like the following version of the class -declaration: - -:: +declaration: :: class Collects e c where empty :: c e @@ -4965,9 +4756,7 @@ 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 ``f`` from the previous section has a more accurate type: :: f :: (Collects e c) => e -> e -> c e -> c e @@ -4996,18 +4785,14 @@ Odersky, or as a special case of Mark Jones's later framework for discussed in a more theoretical and abstract setting in a manuscript [implparam], where they are identified as one point in a general design space for systems of implicit parameterisation). To start with an -abstract example, consider a declaration such as: - -:: +abstract example, consider a declaration such as: :: class C a b where ... which tells us simply that ``C`` can be thought of as a binary relation on types (or type constructors, 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: - -:: +about dependencies between parameters, as in the following examples: :: class D a b | a -> b where ... class E a b | a -> b, b -> a where ... @@ -5045,25 +4830,19 @@ 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: - -:: +one on its own would be acceptable: :: instance D Bool Int where ... instance D Bool Char where ... -Note also that the following declaration is not allowed, even by itself: - -:: +Note also that the following declaration is not allowed, even by itself: :: instance D [a] b where ... The problem here is that this instance would allow one particular choice of ``[a]`` to be associated 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: - -:: +generally, this means that, in any instance of the form: :: instance D t s where ... @@ -5075,9 +4854,7 @@ 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 accurate types. To illustrate this, we return to the collection class example, and annotate the -original definition of ``Collects`` with a simple dependency: - -:: +original definition of ``Collects`` with a simple dependency: :: class Collects e ce | ce -> e where empty :: ce @@ -5105,24 +4882,18 @@ 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``: - -:: +definition for a function ``f``: :: f x y = insert x y = insert x . insert y -for which we originally obtained a type: - -:: +for which we originally obtained a type: :: f :: (Collects a c, Collects b c) => a -> b -> c -> c 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``: - -:: +``c``. Hence we can infer a shorter and more accurate type for ``f``: :: f :: (Collects a c) => a -> a -> c -> c @@ -5139,9 +4910,7 @@ and allowing more general sets of instance declarations. Instance declarations --------------------- -An instance declaration has the form - -:: +An instance declaration has the form :: instance ( assertion1, ..., assertionn) => class type1 ... typem where ... @@ -5156,9 +4925,7 @@ Instance resolution 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. Consider these -declarations: - -:: +declarations: :: instance context1 => C Int a where ... -- (A) instance context2 => C a Bool where ... -- (B) @@ -5185,6 +4952,15 @@ resolution rules. Relaxed rules for the instance head ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +.. ghc-flag:: -XTypeSynonymInstances + + Allow definition of type class instances for type synonyms. + +.. ghc-flag:: -XFlexibleInstances + + 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 @@ -5195,39 +4971,32 @@ the moment). GHC relaxes this rule in two ways: -- With the ``-XTypeSynonymInstances`` flag, instance heads may use type +- With the :ghc-flag:`-XTypeSynonymInstances` flag, 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: - - :: + writing the RHS of the type synonym definition. For example: :: type Point a = (a,a) instance C (Point a) where ... - is legal. The instance declaration is equivalent to - - :: + is legal. The instance declaration is equivalent to :: instance C (a,a) where ... As always, type synonyms must be fully applied. You cannot, for - example, write: - - :: + example, write: :: instance Monad Point where ... -- The ``-XFlexibleInstances`` flag allows the head of the instance +- The :ghc-flag:`-XFlexibleInstances` flag allows the head of the instance declaration to mention arbitrary nested types. For example, this - becomes a legal instance declaration - - :: + becomes a legal instance declaration :: instance C (Maybe Int) where ... See also the `rules on overlap <#instance-overlap>`__. - The ``-XFlexibleInstances`` flag implies ``-XTypeSynonymInstances``. + The :ghc-flag:`-XFlexibleInstances` flag implies + :ghc-flag:`-XTypeSynonymInstances`. However, the instance declaration must still conform to the rules for instance termination: see :ref:`instance-termination`. @@ -5241,14 +5010,14 @@ 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 ``-XFlexibleContexts`` flag relaxes this rule, as well as relaxing +The :ghc-flag:`-XFlexibleContexts` flag relaxes this rule, as well as relaxing the corresponding rule for type signatures (see -:ref:`flexible-contexts`). Specifically, ``-XFlexibleContexts``, allows +:ref:`flexible-contexts`). Specifically, :ghc-flag:`-XFlexibleContexts`, allows (well-kinded) class constraints of form ``(C t1 ... tn)`` in the context of an instance declaration. Notice that the flag does not affect equality constraints in an instance -context; they are permitted by ``-XTypeFamilies`` or ``-XGADTs``. +context; they are permitted by :ghc-flag:`-XTypeFamilies` or :ghc-flag:`-XGADTs`. However, the instance declaration must still conform to the rules for instance termination: see :ref:`instance-termination`. @@ -5258,10 +5027,14 @@ instance termination: see :ref:`instance-termination`. Instance termination rules ~~~~~~~~~~~~~~~~~~~~~~~~~~ -Regardless of ``-XFlexibleInstances`` and ``-XFlexibleContexts``, +.. ghc-flag:: -XUndecidableInstances + + Permit definition of instances which may lead to type-checker non-termination. + +Regardless of :ghc-flag:`-XFlexibleInstances` and :ghc-flag:`-XFlexibleContexts`, instance declarations must conform to some rules that ensure that instance resolution will terminate. The restrictions can be lifted with -``-XUndecidableInstances`` (see :ref:`undecidable-instances`). +:ghc-flag:`-XUndecidableInstances` (see :ref:`undecidable-instances`). The rules are these: @@ -5357,7 +5130,7 @@ Undecidable instances Sometimes even the termination rules of :ref:`instance-termination` are too onerous. So GHC allows you to experiment with more liberal rules: if -you use the experimental flag ``-XUndecidableInstances``, both the Paterson +you use the experimental flag :ghc-flag:`-XUndecidableInstances`, both the Paterson Conditions and the Coverage Condition (described in :ref:`instance-termination`) are lifted. Termination is still ensured by having a fixed-depth recursion stack. If @@ -5438,7 +5211,7 @@ indeed the (somewhat strange) definition: makes instance inference go into a loop, because it requires the constraint ``(Mul a [b] b)``. -The ``-XUndecidableInstances`` flag is also used to lift some of the +The :ghc-flag:`-XUndecidableInstances` flag is also used to lift some of the restrictions imposed on type family instances. See :ref:`type-family-decidability`. @@ -5447,6 +5220,12 @@ restrictions imposed on type family instances. See Overlapping instances ~~~~~~~~~~~~~~~~~~~~~ +.. ghc-flag:: -XOverlappingInstances + -XIncoherentInstances + + Deprecated flags to weaken checks intended to ensure instance resolution + termination. + In general, as discussed in :ref:`instance-resolution`, *GHC requires that it be unambiguous which instance declaration should be used to resolve a type-class constraint*. GHC also provides a way to to loosen @@ -5462,8 +5241,8 @@ after the ``instance`` keyword. The pragma may be one of: or ``{-# INCOHERENT #-}``. The matching behaviour is also influenced by two module-level language -extension flags: ``-XOverlappingInstances`` -XOverlappingInstances and -``-XIncoherentInstances`` -XIncoherentInstances. These flags are now +extension flags: :ghc-flag:`-XOverlappingInstances` and +:ghc-flag:`-XIncoherentInstances`. These flags are now deprecated (since GHC 7.10) in favour of the fine-grained per-instance pragmas. @@ -5473,16 +5252,16 @@ 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 ``-XIncoherentInstances``. + with :ghc-flag:`-XIncoherentInstances`. - An instance is *overlappable* if: it has an ``OVERLAPPABLE`` or ``OVERLAPS`` pragma; or if the instance has no pragma and it appears - in a module compiled with ``-XOverlappingInstances``; or if the + in a module compiled with :ghc-flag:`-XOverlappingInstances`; or if the instance is incoherent. - An instance is *overlapping* if: it has an ``OVERLAPPING`` or ``OVERLAPS`` pragma; or if the instance has no pragma and it appears - in a module compiled with ``-XOverlappingInstances``; or if the + in a module compiled with :ghc-flag:`-XOverlappingInstances`; or if the instance is incoherent. Now suppose that, in some client module, we are searching for an @@ -5524,9 +5303,7 @@ 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 - -:: +Consider, for example :: instance C Int b where .. instance C a Bool where .. @@ -5538,9 +5315,7 @@ 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. -As a more substantial example of the rules in action, consider - -:: +As a more substantial example of the rules in action, consider :: instance {-# OVERLAPPABLE #-} context1 => C Int b where ... -- (A) instance {-# OVERLAPPABLE #-} context2 => C a Bool where ... -- (B) @@ -5553,7 +5328,7 @@ 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 ``-XIncoherentInstances`` is enabled, in which case it would be +unless :ghc-flag:`-XIncoherentInstances` 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 @@ -5562,9 +5337,7 @@ former is a substitution instance of the latter. For example (D) is substituting ``a := Int``. GHC is conservative about committing to an overlapping instance. For -example: - -:: +example: :: f :: [b] -> [b] f x = ... @@ -5574,7 +5347,7 @@ But GHC does not commit to instance (C), because in a particular call of ``f``, ``b`` might be instantiate to ``Int``, in which case instance (D) would be more specific still. So GHC rejects the program. -If, however, you add the flag ``-XIncoherentInstances`` when compiling +If, however, you add the flag :ghc-flag:`-XIncoherentInstances` when compiling the module that contains (D), GHC will instead pick (C), without complaining about the problem of subsequent instantiations. @@ -5583,21 +5356,17 @@ 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 - -:: +the type :: f :: C b [b] => [b] -> [b] 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 -`-XFlexibleContexts <#flexible-contexts>`__ flag. +:ghc-flag:`-XFlexibleContexts` flag. Exactly the same situation can arise in instance declarations -themselves. Suppose we have - -:: +themselves. Suppose we have :: class Foo a where f :: a -> a @@ -5609,22 +5378,18 @@ 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: - -:: +declaration, thus: :: instance C Int [b] => Foo [b] where f x = ... -(You need `-XFlexibleInstances <#instance-rules>`__ to do this.) +(You need :ghc-flag:`-XFlexibleInstances` to do this.) .. warning:: Overlapping instances must be used with care. They can give rise to incoherence (i.e. different instance choices are made in - different parts of the program) even without ``-XIncoherentInstances``. - Consider: - - :: + different parts of the program) even without :ghc-flag:`-XIncoherentInstances`. + Consider: :: {-# LANGUAGE OverlappingInstances #-} module Help where @@ -5658,7 +5423,7 @@ declaration, thus: overlapping instance declaration in module ``Main``. As a result, the program prints - :: + .. code-block:: none "Used more specific instance" "Used generic instance" @@ -5672,11 +5437,13 @@ declaration, thus: Instance signatures: type signatures in instance declarations ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +.. ghc-flag:: -XInstanceSigs + + 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 -``-XInstanceSigs`` allows you to do so. For example: - -:: +:ghc-flag:`-XInstanceSigs` allows you to do so. For example: :: data T a = MkT a a instance Eq a => Eq (T a) where @@ -5687,9 +5454,7 @@ 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 example, this is fine: - - :: + instantiated with the instance type. For example, this is fine: :: instance Eq a => Eq (T a) where (==) :: forall b. b -> b -> Bool @@ -5705,9 +5470,7 @@ Some details - One stylistic reason for wanting to write a type signature is simple documentation. Another is that you may want to bring scoped type - variables into scope. For example: - - :: + variables into scope. For example: :: class C a where foo :: b -> a -> (a, [b]) @@ -5719,7 +5482,7 @@ Some details xs :: [b] xs = [x,x,x] - Provided that you also specify ``-XScopedTypeVariables`` + Provided that you also specify :ghc-flag:`-XScopedTypeVariables` (:ref:`scoped-type-variables`), the ``forall b`` scopes over the definition of ``foo``, and in particular over the type signature for ``xs``. @@ -5729,9 +5492,14 @@ Some details Overloaded string literals -------------------------- +.. ghc-flag:: -XOverloadedStrings + + 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 -``-XOverloadedStrings``) a string literal has type +:ghc-flag:`-XOverloadedStrings`) a string literal has type ``(IsString a) => a``. This means that the usual string syntax can be used, e.g., for @@ -5741,17 +5509,13 @@ be used in both expressions and patterns. If used in a pattern the literal with be replaced by an equality test, in the same way as an integer literal is. -The class ``IsString`` is defined as: - -:: +The class ``IsString`` is defined as: :: class IsString a where fromString :: String -> a The only predefined instance is the obvious one to make strings work as -usual: - -:: +usual: :: instance IsString [Char] where fromString cs = cs @@ -5762,7 +5526,7 @@ it), you can import it from module ``GHC.Exts``. Haskell's defaulting mechanism (`Haskell Report, Section 4.3.4 <http://www.haskell.org/onlinereport/decls.html#sect4.3.4>`__) is -extended to cover string literals, when ``-XOverloadedStrings`` is +extended to cover string literals, when :ghc-flag:`-XOverloadedStrings` is specified. Specifically: - Each type in a ``default`` declaration must be an instance of ``Num`` @@ -5808,9 +5572,13 @@ since it gets translated into an equality comparison. Overloaded labels ----------------- +.. ghc-flag:: -XOverloadedLabels + + 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 -``-XOverloadedLabels`` extension is enabled, an overloaded label can written +:ghc-flag:`-XOverloadedLabels` extension is enabled, an overloaded label can written with a prefix hash, for example ``#foo``. The type of this expression is ``IsLabel "foo" a => a``. @@ -5889,6 +5657,11 @@ showing how an overloaded label can be used as a record selector: Overloaded lists ---------------- +.. ghc-flag:: -XOverloadedLists + + 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 be used in the following seven ways: @@ -6015,11 +5788,11 @@ several example instances: Rebindable syntax ~~~~~~~~~~~~~~~~~ -When desugaring list notation with ``-XOverloadedLists`` GHC uses the +When desugaring list notation with :ghc-flag:`-XOverloadedLists` GHC uses the ``fromList`` (etc) methods from module ``GHC.Exts``. You do not need to import ``GHC.Exts`` for this to happen. -However if you use ``-XRebindableSyntax``, then GHC instead uses +However if you use :ghc-flag:`-XRebindableSyntax`, then GHC instead uses whatever is in scope with the names of ``toList``, ``fromList`` and ``fromListN``. That is, these functions are rebindable; c.f. :ref:`rebindable-syntax`. @@ -6029,9 +5802,7 @@ 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: - -:: +the meaning of the default declarations like: :: default ([a]) @@ -6051,7 +5822,12 @@ representation). Undecidable (or recursive) superclasses --------------------------------------- -The language extension ``-XUndecidableSuperClasses`` allows much more flexible +.. ghc-flag:: -XUndecidableSuperClasses + + Allow all superclass constraints, including those that may result in + non-termination of the typechecker. + +The language extension :ghc-flag:`-XUndecidableSuperClasses` allows much more flexible constraints in superclasses. A class cannot generally have itself as a superclass. So this is illegal :: @@ -6092,7 +5868,7 @@ example (Trac #10318) :: Here the superclass cycle does terminate but it's not entirely straightforward to see that it does. -With the language extension ``-XUndecidableSuperClasses`` GHC lifts all restrictions +With the language extension :ghc-flag:`-XUndecidableSuperClasses` GHC lifts all restrictions on superclass constraints. If there really *is* a loop, GHC will only expand it to finite depth. @@ -6102,6 +5878,12 @@ expand it to finite depth. Type families ============= +.. ghc-flag:: -XTypeFamilies + + :implies: :ghc-flag:`-XMonoLocalBinds` + + 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]_ and associated type synonyms @@ -6131,7 +5913,7 @@ 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 flag ``-XTypeFamilies``. Additional +Type families are enabled by the flag :ghc-flag:`-XTypeFamilies`. Additional information on the use of type families in GHC is available on `the Haskell wiki page on type families <http://www.haskell.org/haskellwiki/GHC/Indexed_types>`__. @@ -6180,25 +5962,19 @@ placed on associated types. Data family declarations ~~~~~~~~~~~~~~~~~~~~~~~~ -Indexed data families are introduced by a signature, such as - -:: +Indexed data families are introduced by a signature, such as :: data family GMap k :: * -> * The special ``family`` distinguishes family from standard data declarations. The result kind annotation is optional and, as usual, -defaults to ``*`` if omitted. An example is - -:: +defaults to ``*`` if omitted. An example is :: data family Array e Named arguments can also be given explicit kind signatures if needed. Just as with :ref:`GADT declarations <gadt>` named arguments are -entirely optional, so that we can declare ``Array`` alternatively with - -:: +entirely optional, so that we can declare ``Array`` alternatively with :: data family Array :: * -> * @@ -6216,9 +5992,7 @@ families are generally allowed 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 - -:: +instance for ``GMap`` is :: data instance GMap (Either a b) v = GMapEither (GMap a v) (GMap b v) @@ -6227,16 +6001,14 @@ can be any number. When the name of a type argument of a data or newtype 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 is the same as writing a type variable with a unique name. :: data family F a b :: * data instance F Int _ = Int -- Equivalent to data instance F Int b = Int -When the flag ``-fwarn-unused-matches`` is enabled, type variables that are +When the flag :ghc-flag:`-fwarn-unused-matches` is enabled, type variables that are mentioned 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 @@ -6246,7 +6018,7 @@ an underscore (``_x``) are otherwise treated as ordinary type variables. This resembles the wildcards that can be used in :ref:`partial-type-signatures`. However, there are some differences. No error messages reporting the inferred types are generated, nor does -the flag ``-XPartialTypeSignatures`` have any effect. +the flag :ghc-flag:`-XPartialTypeSignatures` have any effect. Data and newtype instance declarations are only permitted when an appropriate family declaration is in scope - just as a class instance @@ -6260,18 +6032,14 @@ 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: - - :: + 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: - - :: + and indeed can define a GADT. For example: :: data family G a b data instance G [a] b where @@ -6284,9 +6052,7 @@ ordinary ``data`` or ``newtype`` declarations: 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: - -:: +following is not possible: :: data family T a data instance T Int = A @@ -6295,9 +6061,7 @@ following is not possible: foo A = 1 -- WRONG: These two equations together... foo B = 2 -- ...will produce a type error. -Instead, you would have to write ``foo`` as a class operation, thus: - -:: +Instead, you would have to write ``foo`` as a class operation, thus: :: class Foo a where foo :: T a -> Int @@ -6345,17 +6109,13 @@ associated type synonyms do not exist. Type family declarations ~~~~~~~~~~~~~~~~~~~~~~~~ -Open indexed type families are introduced by a signature, such as - -:: +Open indexed type families are introduced by a signature, such as :: type family Elem c :: * The special ``family`` distinguishes family from standard type declarations. The result kind annotation is optional and, as usual, -defaults to ``*`` if omitted. An example is - -:: +defaults to ``*`` if omitted. An example is :: type family Elem c @@ -6366,17 +6126,13 @@ with respect to 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: - -:: +example, consider the following declaration: :: type family F a b :: * -> * -- F's arity is 2, -- although its overall kind is * -> * -> * -> * Given this declaration the following are examples of well-formed and -malformed types: - -:: +malformed types: :: F Char [Int] -- OK! Kind: * -> * F Char [Int] Bool -- OK! Kind: * @@ -6385,9 +6141,7 @@ malformed types: The result kind annotation is optional and defaults to ``*`` (like argument kinds) if omitted. Polykinded type families can be declared -using a parameter in the kind annotation: - -:: +using a parameter in the kind annotation: :: type family F a :: k @@ -6406,9 +6160,7 @@ 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 - -:: +for data instances. For example, the ``[e]`` instance for ``Elem`` is :: type instance Elem [e] = e @@ -6435,9 +6187,7 @@ Closed type families ~~~~~~~~~~~~~~~~~~~~ A type family can also be declared with a ``where`` clause, defining the -full set of equations for that family. For example: - -:: +full set of equations for that family. For example: :: type family F a where F Int = Double @@ -6470,9 +6220,7 @@ file. Type family examples ~~~~~~~~~~~~~~~~~~~~ -Here are some examples of admissible and illegal type instances: - -:: +Here are some examples of admissible and illegal type instances: :: type family F a :: * type instance F [Int] = Int -- OK! @@ -6514,18 +6262,14 @@ 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: - -:: +overlap. For example, the following is disallowed: :: type instance F Int = Bool type instance F Int = Char The second clause is a little more interesting. It says that two overlapping type family instances are allowed if the right-hand sides -coincide in the region of overlap. Some examples help here: - -:: +coincide in the region of overlap. Some examples help here: :: type instance F (a, Int) = [a] type instance F (Int, b) = [b] -- overlap permitted @@ -6538,9 +6282,7 @@ 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: - -:: +like types. For example, the following is accepted: :: type family J a :: k type instance J Int = Bool @@ -6555,9 +6297,7 @@ definition in turn relies on type family reduction. This condition of 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: - -:: +instances: :: type instance H x x = Int type instance H [x] x = Bool @@ -6569,9 +6309,7 @@ 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: - -:: +Here are some examples: :: type family F a where F Int = Bool @@ -6597,14 +6335,16 @@ However see :ref:`ghci-decls` for the overlap rules in GHCi. Decidability of type synonym instances ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +.. ghc-flag:: -XUndeciableInstances + + Relax restrictions on the decidability of type synonym family instances. + In order to guarantee that type inference in the presence of type families 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 <http://www.cse.unsw.edu.au/~chak/papers/SPCS08.html>`__\ ”). -Instance declarations have the general form - -:: +Instance declarations have the general form :: type instance F t1 .. tn = t @@ -6627,10 +6367,9 @@ as ``a ~ [F a]``, where a recursive occurrence of a type variable is underneath a family application and data constructor application - see the above mentioned paper for details. -If the option ``-XUndecidableInstances`` is passed to the compiler, the -above restrictions are not enforced and it is on the programmer to -ensure termination of the normalisation of type families during type -inference. +If the option :ghc-flag:`-XUndecidableInstances` is passed to the compiler, the +above restrictions are not enforced and it is on the programmer to ensure +termination of the normalisation of type families during type inference. .. _assoc-decl: @@ -6638,9 +6377,7 @@ Associated data and type families --------------------------------- A data or type synonym family can be declared as part of a type class, -thus: - -:: +thus: :: class GMapKey k where data GMap k :: * -> * @@ -6656,9 +6393,7 @@ The type parameters must all be type variables, of course, and some (but not necessarily all) of then can be the class parameters. Each class parameter may only be used at most once per associated type, but some may be omitted and they may be in an order other than in the class head. -Hence, the following contrived example is admissible: - -:: +Hence, the following contrived example is admissible: :: class C a b c where type T c a x :: * @@ -6673,9 +6408,7 @@ 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: - -:: +keyword in the family instance: :: instance (GMapKey a, GMapKey b) => GMapKey (Either a b) where data GMap (Either a b) v = GMapEither (GMap a v) (GMap b v) @@ -6690,9 +6423,7 @@ Note the following points: - The type indexes corresponding to class parameters must have precisely the same shape the type given in the instance head. To have the same "shape" means that the two types are identical modulo - renaming of type variables. For example: - - :: + renaming of type variables. For example: :: instance Eq (Elem [e]) => Collects [e] where -- Choose one of the following alternatives: @@ -6713,9 +6444,7 @@ Note the following points: - Although it is unusual, there (currently) can be *multiple* instances for an associated family in a single instance declaration. For - example, this is legitimate: - - :: + example, this is legitimate: :: instance GMapKey Flob where data GMap Flob [v] = G1 v @@ -6735,9 +6464,7 @@ Associated type synonym defaults ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ It is possible for the class defining the associated type to specify a -default for associated type instances. So for example, this is OK: - -:: +default for associated type instances. So for example, this is OK: :: class IsBoolMap v where type Key v @@ -6793,17 +6520,13 @@ Scoping of class parameters 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 - -:: +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: - -:: +Hence, the following instance declaration is invalid: :: instance C [c] d where data T [c] = MkT (c, d) -- WRONG!! 'd' is not in scope @@ -6824,8 +6547,8 @@ 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 <#stand-alone-deriving>`__ clause (at the top level). +a derived instance, use a :ghc-flag:`standalone deriving <-XStandaloneDeriving>` +clause (at the top level). .. _data-family-import-export: @@ -7001,30 +6724,29 @@ instances 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 - -:: +example, we can write :: data GMap () v = GMapUnit (Maybe v) deriving Show -which implicitly defines an instance of the form - -:: +which implicitly defines an instance of the form :: instance Show v => Show (GMap () v) where ... + .. _injective-ty-fams: Injective type families ----------------------- +.. ghc-flag:: -XInjectiveTypeFamilies + + Allow injectivity annotations on type families. + Starting with GHC 8.0 type families can be annotated with injectivity information. This information 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: - -:: +only under type family applications. Consider this contrived example: :: type family Id a type instance Id Int = Int @@ -7036,9 +6758,7 @@ only under type family applications. Consider this contrived example: 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: - -:: +will be possible to infer ``t`` at call sites from the type of the argument: :: type family Id a = r | r -> a @@ -7063,9 +6783,7 @@ two parts: It is possible to omit some variables if type family is not injective in them. -Examples: - -:: +Examples: :: type family Id a = result | result -> a where type family F a b c = d | d -> a c b @@ -7107,7 +6825,7 @@ injectivity of a type family: Injective position means either argument to a type constructor or injective argument to a type family. -4. *Open type families*\ Open type families are typechecked +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. @@ -7142,8 +6860,14 @@ family applications as possibly unifying with anything. Kind polymorphism ================= +.. ghc-flag:: -XPolyKinds + + :implies: :ghc-flag:`-XKindSignatures` + + Allow kind polymorphic types. + This section describes *kind polymorphism*, and extension enabled by -``-XPolyKinds``. It is described in more detail in the paper `Giving +:ghc-flag:`-XPolyKinds`. It is described in more detail in the paper `Giving Haskell a Promotion <http://dreixel.net/research/pdf/ghp.pdf>`__, which appeared at TLDI 2012. @@ -7151,9 +6875,7 @@ Overview of kind polymorphism ----------------------------- Currently there is a lot of code duplication in the way ``Typeable`` is -implemented (:ref:`deriving-typeable`): - -:: +implemented (:ref:`deriving-typeable`): :: class Typeable (t :: *) where typeOf :: t -> TypeRep @@ -7164,10 +6886,8 @@ implemented (:ref:`deriving-typeable`): class Typeable2 (t :: * -> * -> *) where typeOf2 :: t a b -> TypeRep -Kind polymorphism (with ``-XPolyKinds``) allows us to merge all these -classes into one: - -:: +Kind polymorphism (with :ghc-flag:`-XPolyKinds`) allows us to merge all these +classes into one: :: data Proxy t = Proxy @@ -7183,11 +6903,9 @@ by GHC), and the new ``Typeable`` class has kind Note the following specific points: -- Generally speaking, with ``-XPolyKinds``, GHC will infer a +- Generally speaking, with :ghc-flag:`-XPolyKinds`, GHC will infer a polymorphic kind for un-decorated declarations, whenever possible. - For example, in GHCi - - :: + For example, in GHCi :: ghci> :set -XPolyKinds ghci> data T m a = MkT (m a) @@ -7196,9 +6914,7 @@ Note the following specific points: - GHC does not usually print explicit ``forall``\ s, including kind ``forall``\ s. You can make GHC show them explicitly with - ``-fprint-explicit-foralls`` (see :ref:`options-help`): - - :: + :ghc-flag:`-fprint-explicit-foralls` (see :ref:`options-help`): :: ghci> :set -XPolyKinds ghci> :set -fprint-explicit-foralls @@ -7207,31 +6923,25 @@ Note the following specific points: T :: forall (k :: BOX). (k -> *) -> k -> * - Just as in the world of terms, you can restrict polymorphism using a - kind signature (sometimes called a kind annotation) - - :: + kind signature (sometimes called a kind annotation) :: data T m (a :: *) = MkT (m a) -- GHC now infers kind T :: (* -> *) -> * -> * - NB: ``-XPolyKinds`` implies ``-XKindSignatures`` (see + NB: :ghc-flag:`-XPolyKinds` implies :ghc-flag:`-XKindSignatures` (see :ref:`kinding`). - The source language does not support an explicit ``forall`` for kind variables. Instead, when binding a type variable, you can simply mention a kind variable in a kind annotation for that type-variable - binding, thus: - - :: + binding, thus: :: data T (m :: k -> *) a = MkT (m a) -- GHC now infers kind T :: forall k. (k -> *) -> k -> * - The (implicit) kind "forall" is placed just outside the outermost type-variable binding whose kind annotation mentions the kind - variable. For example - - :: + variable. For example :: f1 :: (forall a m. m a -> Int) -> Int -- f1 :: forall (k::BOX). @@ -7263,18 +6973,14 @@ Note the following specific points: Principles of kind inference ---------------------------- -Generally speaking, when ``-XPolyKinds`` is on, GHC tries to infer the -most general kind for a declaration. For example: - -:: +Generally speaking, when :ghc-flag:`-XPolyKinds` is on, GHC tries to infer the +most general kind for a declaration. For example: :: data T f a = MkT (f a) -- GHC infers: -- T :: forall k. (k->*) -> k -> * In this case the definition has a right-hand side to inform kind -inference. But that is not always the case. Consider - -:: +inference. But that is not always the case. Consider :: type family F a @@ -7283,9 +6989,7 @@ 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 ``*`` and we get ``F :: * -> *``. You can still declare ``F`` to be kind-polymorphic -using kind signatures: - -:: +using kind signatures: :: type family F1 a -- F1 :: * -> * type family F2 (a :: k) -- F2 :: forall k. k -> * @@ -7305,9 +7009,7 @@ The general principle is this: Examples: data and type family declarations. This rule has occasionally-surprising consequences (see -:ghc-ticket:`10132`. - -:: +:ghc-ticket:`10132`. :: class C a where -- Class declarations are generalised -- so C :: forall k. k -> Constraint @@ -7327,9 +7029,7 @@ Polymorphic kind recursion and complete kind signatures ------------------------------------------------------- Just as in type inference, kind inference for recursive types can only -use *monomorphic* recursion. Consider this (contrived) example: - -:: +use *monomorphic* recursion. Consider this (contrived) example: :: data T m a = MkT (m a) (T Maybe (m a)) -- GHC infers kind T :: (* -> *) -> * -> * @@ -7338,9 +7038,7 @@ The recursive use of ``T`` forced the second argument to have kind ``*``. However, just as in type inference, you can achieve polymorphic recursion by giving a *complete kind signature* for ``T``. A complete kind signature is present when all argument kinds and the result kind -are known, without any need for inference. For example: - -:: +are known, without any need for inference. For example: :: data T (m :: k -> *) :: k -> * where MkT :: m a -> T Maybe (m a) -> T m a @@ -7357,9 +7055,7 @@ signature" for a type constructor? These are the forms: 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. - - :: + complete signature. :: data T1 :: (k -> *) -> k -> * where ... -- Yes T1 :: forall k. (k->*) -> k -> * @@ -7382,9 +7078,7 @@ signature" for a type constructor? These are the forms: - For a class, every type variable must be annotated with a kind. - For a type synonym, every type variable and the result type must all - be annotated with kinds. - - :: + be annotated with kinds: :: type S1 (a :: k) = (a :: k) -- Yes S1 :: forall k. k -> k type S2 (a :: k) = a -- No kind is inferred @@ -7396,9 +7090,7 @@ signature" for a type constructor? These are the forms: - An open type or data family declaration *always* has a complete user-specified kind signature; un-annotated type variables default to - kind ``*``. - - :: + kind ``*``: :: data family D1 a -- D1 :: * -> * data family D2 (a :: k) -- D2 :: forall k. k -> * @@ -7431,9 +7123,7 @@ 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. -For example: - -:: +For example: :: type family F1 a where F1 True = False @@ -7457,9 +7147,7 @@ Kind inference in class instance declarations --------------------------------------------- Consider the following example of a poly-kinded class and an instance -for it: - -:: +for it: :: class C a where type F a @@ -7489,9 +7177,13 @@ signature in the instance head. Datatype promotion ================== +.. ghc-flag:: -XDataKinds + + 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 -``-XDataKinds``, and described in more detail in the paper `Giving +:ghc-flag:`-XDataKinds`, and described in more detail in the paper `Giving Haskell a Promotion <http://dreixel.net/research/pdf/ghp.pdf>`__, which appeared at TLDI 2012. @@ -7506,9 +7198,7 @@ types (:ref:`glasgow-unboxed`). In particular when using advanced type system features, such as type families (:ref:`type-families`) or GADTs (:ref:`gadt`), this simple kind system is insufficient, and fails to prevent simple errors. Consider the example of type-level natural -numbers, and length-indexed vectors: - -:: +numbers, and length-indexed vectors: :: data Ze data Su n @@ -7521,9 +7211,7 @@ The kind of ``Vec`` is ``* -> * -> *``. This means that eg. ``Vec Int Char`` is a well-kinded type, even though this is not what we intend when defining length-indexed vectors. -With ``-XDataKinds``, the example above can then be rewritten to: - -:: +With :ghc-flag:`-XDataKinds`, the example above can then be rewritten to: :: data Nat = Ze | Su Nat @@ -7537,11 +7225,9 @@ ill-kinded, and GHC will report an error. Overview -------- -With ``-XDataKinds``, GHC automatically promotes every suitable datatype +With :ghc-flag:`-XDataKinds`, GHC automatically promotes every suitable datatype to be a kind, and its (value) constructors to be type constructors. The -following types - -:: +following types :: data Nat = Ze | Su Nat @@ -7551,9 +7237,7 @@ following types data Sum a b = L a | R b -give rise to the following kinds and type constructors: - -:: +give rise to the following kinds and type constructors: :: Nat :: BOX Ze :: Nat @@ -7595,9 +7279,7 @@ Distinguishing between types and constructors --------------------------------------------- Since constructors and types share the same namespace, with promotion -you can get ambiguous type names: - -:: +you can get ambiguous type names: :: data P -- 1 @@ -7606,9 +7288,7 @@ you can get ambiguous type names: type T = P -- 1 or promoted 2? In these cases, if you want to refer to the promoted constructor, you -should prefix its name with a quote: - -:: +should prefix its name with a quote: :: type T1 = P -- 1 @@ -7626,11 +7306,9 @@ character is a single quote. Promoted list and tuple types ----------------------------- -With ``-XDataKinds``, Haskell's list and tuple types are natively +With :ghc-flag:`-XDataKinds`, 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: - -:: +level, albeit prefixed with a quote: :: data HList :: [*] -> * where HNil :: HList '[] @@ -7648,23 +7326,24 @@ level, albeit prefixed with a quote: foo2 :: HList [Int, Bool] foo2 = ... -(Note: the declaration for ``HCons`` also requires ``-XTypeOperators`` -because of infix type operator ``(:')``.) 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 +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 :ghc-flag:`-XTypeOperators` + because of infix type operator ``(:')`` + + .. _promotion-existentials: Promoting existential data constructors --------------------------------------- Note that we do promote existential data constructors that are otherwise -suitable. For example, consider the following: - -:: +suitable. For example, consider the following: :: data Ex :: * where MkEx :: forall a. a -> Ex @@ -7672,9 +7351,7 @@ suitable. For example, 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: - -:: +type-level existential: :: type family UnEx (ex :: Ex) :: k type instance UnEx (MkEx x) = x @@ -7684,9 +7361,7 @@ not mentioned in the arguments, and thus it would seem that an instance would have to return a member of ``k`` *for any* ``k``. However, 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: - -:: +elaborated definitions are as follows: :: type family UnEx (k :: BOX) (ex :: Ex) :: k type instance UnEx k (MkEx k x) = x @@ -7708,6 +7383,7 @@ tried to write ``Either * Bool``, would it be ``Either`` applied to ``Bool``. To avoid this quagmire, we simply forbid promoting type operators to the kind level. + .. _type-level-literals: Type-Level Literals @@ -7716,7 +7392,7 @@ Type-Level Literals 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 ``XDataKinds`` language +``Symbol``. This feature is enabled by the :ghc-flag:`-XDataKinds` language extension. The kinds of the literals and all other low-level operations for this @@ -7727,9 +7403,7 @@ these operators require an explicit namespace annotation (see :ref:`explicit-namespaces`). Here is an example of using type-level numeric literals to provide a -safe interface to a low-level function: - -:: +safe interface to a low-level function: :: import GHC.TypeLits import Data.Word @@ -7741,9 +7415,7 @@ safe interface to a low-level function: clearPage (ArrPtr p) = ... Here is an example of using type-level string literals to simulate -simple record operations: - -:: +simple record operations: :: data Label (l :: Symbol) = Get @@ -7757,6 +7429,7 @@ simple record operations: example = from (Point 1 2) (Get :: Label "x") + .. _typelit-runtime: Runtime Values for Type-Level Literals @@ -7764,17 +7437,13 @@ Runtime Values for Type-Level Literals 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: - -:: +``symbolVal``. For example: :: GHC.TypeLits> natVal (Proxy :: Proxy 2) 2 These functions are overloaded because they need to return a different -result, depending on the type at which they are instantiated. - -:: +result, depending on the type at which they are instantiated. :: natVal :: KnownNat n => proxy n -> Integer @@ -7794,9 +7463,7 @@ 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: - -:: +``someSymbolVal`` for strings: :: someNatVal :: Integer -> Maybe SomeNat SomeNat :: KnownNat n => Proxy n -> SomeNat @@ -7815,7 +7482,7 @@ Numbers may be compared using ``(<=?)``, which returns a promoted boolean value, or ``(<=)``, which compares numbers as a constraint. For example: -:: +.. code-block:: none GHC.TypeLits> natVal (Proxy :: Proxy (2 + 3)) 5 @@ -7830,7 +7497,7 @@ 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: -:: +.. code-block:: none lg :: Proxy base -> Proxy (base ^ pow) -> Proxy pow lg _ _ = Proxy @@ -7847,9 +7514,7 @@ 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: - -:: +may include equality constraints, as in the following example: :: sumCollects :: (Collects c1, Collects c2, Elem c1 ~ Elem c2) => c1 -> c2 -> c2 @@ -7861,15 +7526,11 @@ 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 - -:: +idea is to rewrite a class declaration of the form :: class C a b | a -> b -to - -:: +to :: class (F a ~ b) => C a b where type F a @@ -7899,18 +7560,22 @@ the paper The ``Constraint`` kind ======================= +.. ghc-flag:: -XConstraintKinds + + 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 <#implicit-parameters>`__ constraints, e.g. - ``?x::Int`` (with the ``-XImplicitParams`` flag) +- :ghc-flag:`Implicit parameter <-XImplicitParams>` constraints, e.g. + ``?x::Int`` (with the :ghc-flag:`-XImplicitParams` flag) -- `Equality constraints <#equality-constraints>`__, e.g. ``a ~ Int`` - (with the ``-XTypeFamilies`` or ``-XGADTs`` flag) +- :ref:`Equality constraints <equality-constraints>`, e.g. ``a ~ Int`` + (with the :ghc-flag:`-XTypeFamilies` or :ghc-flag:`-XGADTs` flag) -With the ``-XConstraintKinds`` flag, GHC becomes more liberal in what it +With the :ghc-flag:`-XConstraintKinds` flag, GHC becomes more liberal in what it accepts 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``: @@ -7926,9 +7591,7 @@ The following things have kind ``Constraint``: have kind ``Constraint`` (for which they need to import it from ``GHC.Exts``). So for example ``type Foo (f :: \* -> Constraint) = forall b. f b => b -> b`` - is allowed, as well as examples involving type families: - - :: + is allowed, as well as examples involving type families: :: type family Typ a b :: Constraint type instance Typ Int b = Show b @@ -7938,9 +7601,7 @@ The following things have kind ``Constraint``: func = ... Note that because constraints are just handled as types of a particular -kind, this extension allows type constraint synonyms: - -:: +kind, this extension allows type constraint synonyms: :: type Stringy a = (Read a, Show a) foo :: Stringy a => a -> (String, String -> a) @@ -7968,7 +7629,7 @@ these two programs: You may write programs that use exotic sorts of constraints in instance contexts and superclasses, but to do so you must use -``-XUndecidableInstances`` to signal that you don't mind if the type +:ghc-flag:`-XUndecidableInstances` to signal that you don't mind if the type checker fails to terminate. .. _other-type-extensions: @@ -7981,19 +7642,20 @@ Other type system extensions Explicit universal quantification (forall) ------------------------------------------ -Haskell type signatures are implicitly quantified. When the language -option ``-XExplicitForAll`` is used, the keyword ``forall`` allows us to -say exactly what this means. For example: +.. ghc-flag:: -XExplicitForAll -:: + Allow use of the ``forall`` keyword in places where universal quantification + is implicit. - g :: b -> b +Haskell type signatures are implicitly quantified. When the language +option :ghc-flag:`-XExplicitForAll` is used, the keyword ``forall`` allows us to +say exactly what this means. For example: :: -means this: + g :: b -> b -:: +means this: :: - g :: forall b. (b -> b) + g :: forall b. (b -> b) The two are treated identically. @@ -8005,18 +7667,16 @@ type variable any more! The context of a type signature ------------------------------- -The ``-XFlexibleContexts`` flag 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 ``-XFlexibleContexts`` these type signatures are -perfectly okay - +The :ghc-flag:`-XFlexibleContexts` flag 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 +:ghc-flag:`-XFlexibleContexts` these type signatures are perfectly okay :: g :: Eq [a] => ... g :: Ord (T a ()) => ... -The flag ``-XFlexibleContexts`` also lifts the corresponding restriction +The flag :ghc-flag:`-XFlexibleContexts` also lifts the corresponding restriction on class declarations (:ref:`superclass-rules`) and instance declarations (:ref:`instance-rules`). @@ -8025,11 +7685,14 @@ declarations (:ref:`instance-rules`). Ambiguous types and the ambiguity check --------------------------------------- +.. ghc-flag:: -XAllowAmbiguousTypes + + 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: - -:: +example: :: f :: C a => Int @@ -8038,42 +7701,34 @@ 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 ``-XAllowAmbiguousTypes`` switches off the ambiguity +language extension :ghc-flag:`-XAllowAmbiguousTypes` switches off the ambiguity check. Ambiguity can be subtle. Consider this example which uses functional -dependencies: - -:: +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 - -:: +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 -Here ``h``\ 's type looks ambiguous in ``b``, but here's a legal call: - -:: +Here ``h``\'s type looks ambiguous in ``b``, but here's a legal call: :: ...(h [True])... 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! +``D``\'s fundep! Behind all these special cases there is a simple guiding principle. -Consider - -:: +Consider :: f :: type f = ...blah... @@ -8083,12 +7738,10 @@ Consider 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 +``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``: - -:: +definition ``f :: C a => Int``: :: f :: C a => Int f = ...blah... @@ -8096,7 +7749,7 @@ definition ``f :: C a => Int``: g :: C a => Int g = f -In ``g``'s definition, we'll instantiate to ``(C alpha)`` and try to +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`` @@ -8106,9 +7759,7 @@ that they too are unambiguous. *Switching off the ambiguity check.* Even if a function is has an ambiguous type according the "guiding principle", it is possible that -the function is callable. For example: - -:: +the function is callable. For example: :: class D a b where ... instance D Bool b where ... @@ -8118,39 +7769,45 @@ the function is callable. For example: foo = strange True -Here ``strange``'s type is ambiguous, but the call in ``foo`` is OK +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. So the language extension -``-XAllowAmbiguousTypes`` allows you to switch off the ambiguity check. +:ghc-flag:`-XAllowAmbiguousTypes` allows you to switch off the ambiguity check. But even with ambiguity checking switched off, GHC will complain about a -function that can *never* be called, such as this one: - -:: +function that can *never* be called, such as this one: :: f :: (Int ~ Bool) => a -> a .. note:: *A historical note.* GHC used to impose some more restrictive and less - principled conditions on type signatures. For type type - ``forall tv1..tvn (c1, ...,cn) => type`` GHC used to require (a) that - each universally quantified type variable ``tvi`` must be "reachable" - from ``type``, and (b) 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. + principled conditions on type signatures. For type + ``forall tv1..tvn (c1, ...,cn) => type`` GHC used to require + + a. that each universally quantified type variable ``tvi`` must be "reachable" + from ``type``, and + + b. 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. .. _implicit-parameters: Implicit parameters ------------------- -Implicit parameters are implemented as described in "Implicit -parameters: dynamic scoping with static types", J Lewis, MB Shields, E -Meijer, J Launchbury, 27th ACM Symposium on Principles of Programming -Languages (POPL'00), Boston, Jan 2000. (Most of the following, still -rather incomplete, documentation is due to Jeff Lewis.) +.. ghc-flag:: -XImplicitParams + + Allow definition of functions expecting implicit parameters. -Implicit parameter support is enabled with the option -``-XImplicitParams``. +Implicit parameters are implemented as described in [Lewis2000]_ and enabled +with the option :ghc-flag:`-XImplicitParams`. (Most of the following, still rather +incomplete, documentation is due to Jeff Lewis.) + +.. [Lewis2000] + "Implicit parameters: dynamic scoping with static types", + J Lewis, MB Shields, E Meijer, J Launchbury, + *27th ACM Symposium on Principles of Programming Languages (POPL'00)*, + Boston, Jan 2000. 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 @@ -8167,9 +7824,7 @@ 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``. - -:: +implicitly parameterised by a comparison function named ``cmp``. :: sort :: (?cmp :: a -> a -> Bool) => [a] -> [a] @@ -8181,9 +7836,7 @@ An implicit parameter occurs in an expression using the special form expression). Use of this construct also introduces a new dynamic-binding constraint in the type of the expression. For example, the following definition shows how we can define an implicitly parameterised sort -function in terms of an explicitly parameterised ``sortBy`` function: - -:: +function in terms of an explicitly parameterised ``sortBy`` function: :: sortBy :: (a -> a -> Bool) -> [a] -> [a] @@ -8197,9 +7850,7 @@ 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: - -:: +out the least value in a list: :: least :: (?cmp :: a -> a -> Bool) => [a] -> a least xs = head (sort xs) @@ -8217,9 +7868,7 @@ parameter must have the same type. This means that the type of constraints. You can't have an implicit parameter in the context of a class or -instance declaration. For example, both these declarations are illegal: - -:: +instance declaration. For example, both these declarations are illegal: :: class (?x::Int) => C a where ... instance (?x::a) => Foo [a] where ... @@ -8231,9 +7880,7 @@ 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: - -:: +consider: :: f :: (?x :: [a]) => Int -> Int f n = n + length ?x @@ -8250,9 +7897,7 @@ 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``. - -:: +``cmp``. :: min :: [a] -> a min = let ?cmp = (<=) in least @@ -8277,25 +7922,19 @@ or pattern guards), or a ``where`` clause. Note the following points: 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: - - :: + 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 - - :: + binding for ``?x``, so the type of ``f`` is :: f :: (?x::Int) => Int -> Int Implicit parameters and polymorphic recursion ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -Consider these two definitions: - -:: +Consider these two definitions: :: len1 :: [a] -> Int len1 xs = let ?acc = 0 in len_acc1 xs @@ -8320,7 +7959,7 @@ 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: -:: +.. code-block:: none Prog> len1 "hello" 0 @@ -8334,9 +7973,7 @@ Implicit parameters and monomorphism ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ GHC applies the dreaded Monomorphism Restriction (section 4.5.5 of the -Haskell Report) to implicit parameters. For example, consider: - -:: +Haskell Report) to implicit parameters. For example, consider: :: f :: Int -> Int f v = let ?x = 0 in @@ -8379,7 +8016,7 @@ parameter does not matter, but within ``base`` we call it The ``CallStack`` will only extend as far as the types allow it, for example -:: +.. code-block:: none head :: (?callStack :: CallStack) => [a] -> a head [] = myerror "empty" @@ -8400,9 +8037,7 @@ includes the call-site of ``myerror`` in ``head``, and of ``head`` in GHC will never report an unbound implicit ``CallStack``, and will instead default such occurrences to the empty ``CallStack``. -``CallStack`` is kept abstract, but GHC provides a function - -:: +``CallStack`` is kept abstract, but GHC provides a function :: getCallStack :: CallStack -> [(String, SrcLoc)] @@ -8420,7 +8055,7 @@ details. Consider the ``head`` example above, the ``myerror`` line in the printed stack is not particularly enlightening, so we might choose to surpress it by freezing the ``CallStack`` that we pass to ``myerror``. -:: +.. code-block:: none head :: (?callStack :: CallStack) => [a] -> a head [] = let ?callStack = freezeCallStack ?callStack in myerror "empty" @@ -8437,66 +8072,58 @@ to surpress it by freezing the ``CallStack`` that we pass to ``myerror``. Explicitly-kinded quantification -------------------------------- +.. ghc-flag:: -XKindSignatures + + Allow explicit kind signatures on type variables. + Haskell infers the kind of each type variable. Sometimes it is nice to be able to give the kind explicitly as (machine-checked) documentation, just as it is nice to give a type signature for a function. On some occasions, it is essential to do so. For example, in his paper "Restricted Data Types in Haskell" (Haskell Workshop 1999) John Hughes -had to define the data type: +had to define the data type: :: -:: - - data Set cxt a = Set [a] - | Unused (cxt a -> ()) + data Set cxt a = Set [a] + | Unused (cxt a -> ()) 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 flag -``-XKindSignatures``. +:ghc-flag:`-XKindSignatures`. This flag enables kind signatures in the following places: -- ``data`` declarations: - - :: +- ``data`` declarations: :: data Set (cxt :: * -> *) a = Set [a] -- ``type`` declarations: - - :: +- ``type`` declarations: :: type T (f :: * -> *) = f Int -- ``class`` declarations: - - :: +- ``class`` declarations: :: class (Eq a) => C (f :: * -> *) a where ... -- ``forall``\'s in type signatures: - - :: +- ``forall``\'s in type signatures: :: f :: forall (cxt :: * -> *). Set cxt Int The parentheses are required. Some of the spaces are required too, to -separate the lexemes. If you write "``(f::*->*)``" you will get a parse -error, because "``::*->*``" is a single lexeme in Haskell. +separate the lexemes. If you write ``(f::*->*)`` you will get a parse +error, because ``::*->*`` is a single lexeme in Haskell. As part of the same extension, you can put kind annotations in types as -well. Thus: - -:: +well. Thus: :: f :: (Int :: *) -> Int g :: forall a. a -> (a :: *) The syntax is -:: +.. code-block:: none atype ::= '(' ctype '::' kind ') @@ -8507,10 +8134,19 @@ The parentheses are required. Arbitrary-rank polymorphism --------------------------- -GHC's type system supports *arbitrary-rank* explicit universal -quantification in types. For example, all the following types are legal: +.. ghc-flag:: -XRankNTypes -:: + + :implies: :ghc-flag:`-XExplicitForAll` + + Allow types of arbitrary rank. + +.. ghc-flag:: -XRank2Types + + A deprecated alias of :ghc-flag:`-XRankNTypes`. + +GHC's type system supports *arbitrary-rank* explicit universal +quantification in types. For example, all the following types are legal: :: f1 :: forall a b. a -> b -> a g1 :: forall a b. (Ord a, Eq b) => a -> b -> a @@ -8533,8 +8169,8 @@ 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 ``-XRankNTypes`` (which implies -``-XExplicitForAll``, :ref:`explicit-foralls`) enables higher-rank +The language option :ghc-flag:`-XRankNTypes` (which implies +:ghc-flag:`-XExplicitForAll`) enables higher-rank types. That is, you can nest ``forall``\ s arbitrarily deep in function arrows. For example, a forall-type (also called a "type scheme"), including a type-class context, is legal: @@ -8549,7 +8185,7 @@ including a type-class context, is legal: - In a pattern type signature (see :ref:`scoped-type-variables`) -The ``-XRankNTypes`` option is also required for any type with a +The :ghc-flag:`-XRankNTypes` 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 @@ -8562,11 +8198,11 @@ monomorphic. This is important because by default GHC will not instantiate type variables to a polymorphic type (:ref:`impredicative-polymorphism`). -The obsolete language options ``-XPolymorphicComponents`` and -``-XRank2Types`` are synonyms for ``-XRankNTypes``. They used to specify -finer distinctions that GHC no longer makes. (They should really elicit -a deprecation warning, but they don't, purely to avoid the need to -library authors to change their old flags specifications.) +The obsolete language options :ghc-flag:`-XPolymorphicComponents` and +:ghc-flag:`-XRank2Types` are synonyms for :ghc-flag:`-XRankNTypes`. They used to +specify finer distinctions that GHC no longer makes. (They should really elicit +a deprecation warning, but they don't, purely to avoid the need to library +authors to change their old flags specifications.) .. _univ: @@ -8574,9 +8210,7 @@ Examples ~~~~~~~~ These are examples of ``data`` and ``newtype`` declarations whose data -constructors have polymorphic argument types: - -:: +constructors have polymorphic argument types: :: data T a = T1 (forall b. b -> b -> b) a @@ -8586,39 +8220,33 @@ constructors have polymorphic argument types: newtype Swizzle = MkSwizzle (forall a. Ord a => [a] -> [a]) -The constructors have rank-2 types: - -:: +The constructors have rank-2 types: :: T1 :: forall a. (forall b. b -> b -> b) -> a -> T a + MkMonad :: forall m. (forall a. a -> m a) -> (forall a b. m a -> (a -> m b) -> m b) -> MonadT m + MkSwizzle :: (forall a. Ord a => [a] -> [a]) -> Swizzle 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: - -:: +example: :: newtype Swizzle' = MkSwizzle' (Ord a => [a] -> [a]) As of GHC 7.10, this is deprecated. The -``-Wcontext-quantification`` flag detects this situation and issues +:ghc-flag:`-Wcontext-quantification` flag detects this situation and issues a warning. In GHC 8.0 this flag was deprecated and declarations such as ``MkSwizzle'`` will cause an out-of-scope error. As for type signatures, implicit quantification happens for -non-overloaded types too. So if you write this: - -:: +non-overloaded types too. So if you write this: :: f :: (a -> a) -> a -it's just as if you had written this: - -:: +it's just as if you had written this: :: f :: forall a. (a -> a) -> a @@ -8626,9 +8254,7 @@ That is, since the type variable ``a`` isn't in scope, it's implicitly universally quantified. You construct values of types ``T1, MonadT, Swizzle`` by applying the -constructor to suitable values, just as usual. For example, - -:: +constructor to suitable values, just as usual. For example, :: a1 :: T Int a1 = T1 (\xy->x) 3 @@ -8653,9 +8279,7 @@ required, as ``(MkSwizzle reverse)`` shows. (``reverse`` does not need the ``Ord`` constraint.) When you use pattern matching, the bound variables may now have -polymorphic types. For example: - -:: +polymorphic types. For example: :: f :: T a -> a -> (a, Char) f (T1 w k) x = (w k x, w 'c' 'd') @@ -8673,6 +8297,7 @@ 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. + .. _higher-rank-type-inference: Type inference @@ -8684,45 +8309,38 @@ annotations to work", POPL'96) to get a decidable 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*. + 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 signature for x directly, using a pattern type -signature (:ref:`scoped-type-variables`), thus: - -:: +signature (:ref:`scoped-type-variables`), thus: :: - \ f :: (forall a. a->a) -> (f True, f 'c') + \ 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: +which GHC can "push down" to find the type for the variable: :: -:: - - (\ f -> (f True, f 'c')) :: (forall a. a->a) -> (Bool,Char) + (\ 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: +type signature for the function itself: :: -:: - - h :: (forall a. a->a) -> (Bool,Char) - h f = (f True, f 'c') + 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: +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') + f :: T a -> a -> (a, Char) + f (T1 w k) x = (w k x, w 'c' 'd') Here we do not need to give a type signature to ``w``, because it is an argument of constructor ``T1`` and that tells GHC all it needs to know. + .. _implicit-quant: Implicit quantification @@ -8732,9 +8350,7 @@ GHC performs implicit quantification as follows. At the top 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: - -:: +the following pairs are equivalent: :: f :: a -> a f :: forall a. a -> a @@ -8749,9 +8365,7 @@ the following pairs are equivalent: in ... Notice that GHC does *not* find the inner-most possible quantification -point. For example: - -:: +point. For example: :: f :: (a -> a) -> Int -- MEANS @@ -8776,10 +8390,12 @@ rank-2 types. Impredicative polymorphism -------------------------- -In general, GHC will only instantiate a polymorphic function at a -monomorphic type (one with no foralls). For example, +.. ghc-flag:: -XImpredicativeTypes -:: + 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 @@ -8792,11 +8408,9 @@ 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 ``-XImpredicativeTypes``. If it worked, this would mean +enabled with :ghc-flag:`-XImpredicativeTypes`. If it worked, this would mean that you *could* call a polymorphic function at a polymorphic type, and -parameterise data structures over polymorphic types. For example: - -:: +parameterise data structures over polymorphic types. For example: :: f :: Maybe (forall a. [a] -> [a]) -> Maybe ([Int], [Char]) f (Just g) = Just (g [3], g "hello") @@ -8811,9 +8425,7 @@ consistently, or working the same in subsequent releases. See If you want impredicative polymorphism, the main workaround is to use a newtype wrapper. The ``id runST`` example can be written using theis -workaround like this: - -:: +workaround like this: :: runST :: (forall s. ST s a) -> a id :: forall b. b -> b @@ -8829,10 +8441,13 @@ workaround like this: Lexically scoped type variables ------------------------------- -GHC supports *lexically scoped type variables*, without which some type -signatures are simply impossible to write. For example: +.. ghc-flag:: -XScopedTypeVariables -:: + Enable lexical scoping of type variables explicitly introduced with + ``forall``. + +GHC supports *lexically scoped type variables*, without which some type +signatures are simply impossible to write. For example: :: f :: forall a. [a] -> [a] f xs = ys ++ ys @@ -8850,7 +8465,7 @@ for ``ys``; a major benefit of scoped type variables is that it becomes possible to do so. Lexically-scoped type variables are enabled by -``-XScopedTypeVariables``. This flag implies ``-XRelaxedPolyRec``. +:ghc-flag:`-XScopedTypeVariables`. This flag implies :ghc-flag:`-XRelaxedPolyRec`. Overview ~~~~~~~~ @@ -8885,9 +8500,7 @@ over its free type variables (`Section the Haskell Report). Lexically scoped type variables affect this implicit quantification rules as follows: any type variable that is in scope is *not* universally quantified. For example, if type variable -``a`` is in scope, then - -:: +``a`` is in scope, then :: (e :: a -> a) means (e :: a -> a) (e :: b -> b) means (e :: forall b. b->b) @@ -8900,9 +8513,7 @@ Declaration type signatures 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: - -:: +in the definition of the named function. For example: :: f :: forall a. [a] -> [a] f (x:xs) = xs ++ [ x :: a ] @@ -8913,9 +8524,7 @@ The "``forall a``" brings "``a``" into scope in the definition of This only happens if: - The quantification in ``f``\'s type signature is explicit. For - example: - - :: + example: :: g :: [a] -> [a] g (x:xs) = xs ++ [ x :: a ] @@ -8925,9 +8534,7 @@ This only happens if: by Haskell's usual implicit quantification rules. - The signature gives a type for a function binding or a bare variable - binding, not a pattern binding. For example: - - :: + binding, not a pattern binding. For example: :: f1 :: forall a. [a] -> [a] f1 (x:xs) = xs ++ [ x :: a ] -- OK @@ -8950,11 +8557,9 @@ Expression type signatures An expression type signature that has *explicit* quantification (using ``forall``) brings into scope the explicitly-quantified type variables, -in the annotated expression. For example: +in the annotated expression. For example: :: -:: - - f = runST ( (op >>= \(x :: STRef s Int) -> g x) :: forall s. ST s Bool ) + f = runST ( (op >>= \(x :: STRef s Int) -> g x) :: forall s. ST s Bool ) Here, the type signature ``forall s. ST s Bool`` brings the type variable ``s`` into scope, in the annotated expression @@ -8966,14 +8571,14 @@ Pattern type signatures ~~~~~~~~~~~~~~~~~~~~~~~ A type signature may occur in any pattern; this is a *pattern type -signature*. For example: +signature*. For example: :: -:: + -- f and g assume that 'a' is already in scope + f = \(x::Int, y::a) -> x - -- f and g assume that 'a' is already in scope - f = \(x::Int, y::a) -> x - g (x::a) = x - h ((x,y) :: (Int,Bool)) = (y,x) + g (x::a) = x + + h ((x,y) :: (Int,Bool)) = (y,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 @@ -8983,17 +8588,15 @@ 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: +example: :: -:: - - f :: forall a. [a] -> (Int, [a]) - f xs = (n, zs) - where - (ys::[a], n) = (reverse xs, length xs) -- OK - zs::[a] = xs ++ ys -- OK + f :: forall a. [a] -> (Int, [a]) + f xs = (n, zs) + where + (ys::[a], n) = (reverse xs, length xs) -- OK + zs::[a] = xs ++ ys -- OK - Just (v::b) = ... -- Not OK; b is not in scope + Just (v::b) = ... -- Not OK; b is not in scope Here, the pattern signatures for ``ys`` and ``zs`` are fine, but the one for ``v`` is not because ``b`` is not in scope. @@ -9001,16 +8604,15 @@ 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*. This is -particularly important for existential data constructors. For example: - -:: +particularly important for existential data constructors. For example: :: - data T = forall a. MkT [a] + data T = forall a. MkT [a] - k :: T -> T - k (MkT [t::a]) = MkT t3 - where - t3::[a] = [t,t,t] + 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 *cannot* already be in @@ -9040,9 +8642,7 @@ Class and instance declarations The type variables in the head of a ``class`` or ``instance`` declaration scope over the methods defined in the ``where`` part. You do -not even need an explicit ``forall``. For example: - -:: +not even need an explicit ``forall``. For example: :: class C a where op :: [a] -> a @@ -9063,13 +8663,17 @@ Bindings and generalisation Switching off the dreaded Monomorphism Restriction ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.. index:: - single: -XNoMonomorphismRestriction +.. ghc-flag:: -XNoMonomorphismRestriction + + :default: on + + Prevents the compiler from applying the monomorphism restriction to + bindings lacking explicit type signatures. Haskell's monomorphism restriction (see `Section 4.5.5 <http://www.haskell.org/onlinereport/decls.html#sect4.5.5>`__ of the Haskell Report) can be completely switched off by -``-XNoMonomorphismRestriction``. Since GHC 7.8.1, the monomorphism +:ghc-flag:`-XNoMonomorphismRestriction`. Since GHC 7.8.1, the monomorphism restriction is switched off by default in GHCi's interactive options (see :ref:`ghci-interactive-options`). @@ -9078,6 +8682,11 @@ restriction is switched off by default in GHCi's interactive options Generalised typing of mutually recursive bindings ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +.. ghc-flag:: -XRelaxedPolyRec + + Allow the typechecker to ignore references to bindings with + explicit type signatures. + 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 @@ -9091,13 +8700,11 @@ group is generalised (`Haskell Report, Section Following a suggestion of Mark Jones, in his paper `Typing Haskell in Haskell <http://citeseer.ist.psu.edu/424440.html>`__, GHC implements a -more general scheme. If ``-XRelaxedPolyRec`` is specified: *the +more general scheme. If :ghc-flag:`-XRelaxedPolyRec` is specified: *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: - -:: +typecheck. For example, consider: :: f :: Eq a => a -> Bool f x = (x == x) || g True || g "Yes" @@ -9107,9 +8714,7 @@ typecheck. For example, consider: 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 - -:: +dependency analysis. Then ``g``\'s type is generalised, to get :: g :: Ord a => a -> Bool @@ -9119,12 +8724,10 @@ 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). With -``-XRelaxedPolyRec`` GHC only insists that the type signatures of a +:ghc-flag:`-XRelaxedPolyRec` 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: - -:: +context. For example, this is fine: :: f :: Eq a => a -> Bool f x = (x == x) || g True @@ -9137,9 +8740,13 @@ context. For example, this is fine: Let-generalisation ~~~~~~~~~~~~~~~~~~ +.. ghc-flag:: -XMonoLocalBinds + + 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 -flag ``-XMonoLocalBinds`` GHC implements a slightly more conservative +flag :ghc-flag:`-XMonoLocalBinds` GHC implements a slightly more conservative policy, using the following rules: - A variable is *closed* if and only if @@ -9161,9 +8768,7 @@ policy, using the following rules: (`Haskell Report, Section 4.5.5 <http://www.haskell.org/onlinereport/decls.html#sect4.5.5>`__) -For example, consider - -:: +For example, consider :: f x = x + 1 g x = let h y = f y * 2 @@ -9187,10 +8792,10 @@ papers <http://research.microsoft.com/~simonpj/papers/constraints/index.htm>`__ "Let should not be generalised" and "Modular type inference with local assumptions", and a related `blog post <http://ghc.haskell.org/trac/ghc/blog/LetGeneralisationInGhc7>`__. -The flag ``-XMonoLocalBinds`` is implied by ``-XTypeFamilies`` and -``-XGADTs``. You can switch it off again with ``-XNoMonoLocalBinds`` but -type inference becomes less predicatable if you do so. (Read the -papers!) +The flag :ghc-flag:`-XMonoLocalBinds` is implied by :ghc-flag:`-XTypeFamilies` +and :ghc-flag:`-XGADTs`. You can switch it off again with +:ghc-flag:`-XNoMonoLocalBinds <-XMonoLocalBinds>` but type inference becomes +less predicatable if you do so. (Read the papers!) .. _typed-holes: @@ -9214,16 +8819,12 @@ 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: - -:: +For example, compiling the following module with GHC: :: f :: a -> a f x = _ -will fail with the following error: - -:: +will fail with the following error: :: hole.hs:2:7: Found hole `_' with type: a @@ -9240,28 +8841,26 @@ Here are some more details: - A "``Found hole``" error usually terminates compilation, like any other type error. After all, you have omitted some code from your program. Nevertheless, you can run and test a piece of code - containing holes, by using the ``-fdefer-typed-holes`` flag. This + containing holes, by using the :ghc-flag:`-fdefer-typed-holes` flag. This flag defers errors produced by typed holes until runtime, and converts them into compile-time warnings. These warnings can in turn - be suppressed entirely by ``-fnowarn-typed-holes``). + be suppressed entirely by :ghc-flag:`-fno-warn-typed-holes`). The result is that a hole will behave like ``undefined``, but with the added benefits that it shows a warning at compile time, and will show the same message if it gets evaluated at runtime. This behaviour - follows that of the ``-fdefer-type-errors`` option, which implies - ``-fdefer-typed-holes``. See :ref:`defer-type-errors`. + follows that of the :ghc-flag:`-fdefer-type-errors` option, which implies + :ghc-flag:`-fdefer-typed-holes`. See :ref:`defer-type-errors`. - All unbound identifiers are treated as typed holes, *whether or not they start with an underscore*. The only difference is in the error - message: - - :: + message: :: cons z = z : True : _x : y yields the errors - :: + .. code-block:: none Foo.hs:5:15: error: Found hole: _x :: Bool @@ -9279,15 +8878,13 @@ Here are some more details: 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: - - :: + the same function, but shown individually. For example: :: cons = _x : _x results in the following errors: - :: + .. code-block:: none unbound.hs:1:8: Found hole '_x' with type: a @@ -9315,9 +8912,7 @@ Here are some more details: "``_``" 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 - - :: + example :: f _x = _x + 1 @@ -9332,11 +8927,16 @@ Here are some more details: implementation terms, they are reported by the renamer rather than the type checker.) + .. _partial-type-signatures: Partial Type Signatures ======================= +.. ghc-flag:: -XPartialTypeSignatures + + Type checker will allow inferred types for holes. + A partial type signature is a type signature containing special placeholders written with a leading underscore (e.g., "``_``", "``_foo``", "``_bar``") called *wildcards*. Partial type signatures are @@ -9356,10 +8956,11 @@ type-checker to infer. By default, the type-checker will report an error message for each hole in a partial type signature, informing the programmer of the inferred -type. When the ``-XPartialTypeSignatures`` flag is enabled, the +type. When the :ghc-flag:`-XPartialTypeSignatures` flag 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`` flag. +with the :ghc-flag:`-Wno-partial-type-signatures <-Wpartial-type-signatures>` +flag. .. _pts-syntax: @@ -9436,12 +9037,14 @@ name will often start with ``w_``), e.g. Named Wildcards ~~~~~~~~~~~~~~~ +.. ghc-flag:: -XNamedWildCards + + 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: - -:: +unify to the same type. For example: :: f :: _x -> _x f ('c', y) = ('d', error "Urk") @@ -9451,9 +9054,7 @@ 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: - -:: +of the type signature to make sure that it unifies with something: :: somethingShowable :: Show _x => _x -> _ somethingShowable x = show x @@ -9479,19 +9080,17 @@ simplified away. By default, GHC (as the Haskell 2010 standard prescribes) parses identifiers starting with an underscore in a type as type variables. To -treat them as named wildcards, the ``-XNamedWildCards`` flag should be -enabled. The example below demonstrated the effect. - -:: +treat them as named wildcards, the :ghc-flag:`-XNamedWildCards` flag should be +enabled. The example below demonstrated the effect. :: foo :: _a -> _a foo _ = False -Compiling this program without enabling ``-XNamedWildCards`` produces +Compiling this program without enabling :ghc-flag:`-XNamedWildCards` produces the following error message complaining about the type variable ``_a`` no matching the actual type ``Bool``. -:: +.. code-block:: none Test.hs:5:9: Couldn't match expected type ‘_a’ with actual type ‘Bool’ @@ -9501,11 +9100,11 @@ no matching the actual type ``Bool``. In the expression: False In an equation for ‘foo’: foo _ = False -Compiling this program with ``-XNamedWildCards`` enabled produces the +Compiling this program with :ghc-flag:`-XNamedWildCards` enabled produces the following error message reporting the inferred type of the named wildcard ``_a``. -:: +.. code-block:: none Test.hs:4:8: Warning: Found hole ‘_a’ with type: Bool @@ -9648,8 +9247,7 @@ To solve this, GHC provides a single type-level function, :: type family TypeError (msg :: ErrorMessage) :: k -along with a small type-level language (via -``DataKinds`` :ref:`promotion <promotion>`) +along with a small type-level language (via :ghc-flag:`-XDataKinds`) for constructing pretty-printed error messages, :: -- ErrorMessage is intended to be used as a kind @@ -9695,9 +9293,7 @@ Deferring type errors to runtime While developing, sometimes it is desirable to allow compilation to succeed even if there are type errors in the code. Consider the -following case: - -:: +following case: :: module Main where @@ -9717,26 +9313,25 @@ paper <http://research.microsoft.com/en-us/um/people/simonpj/papers/ext-f/>`__. Enabling deferring of type errors --------------------------------- -The flag ``-fdefer-type-errors`` controls whether type errors are +The flag :ghc-flag:`-fdefer-type-errors` controls whether type errors are deferred to runtime. Type errors will still be emitted as warnings, but will not prevent compilation. You can use -``-Wno-deferred-type-errors`` to suppress these warnings. +:ghc-flag:`-Wno-deferred-type-errors <-Wdeferred-type-errors>` to suppress these +warnings. -This flag implies the ``-fdefer-typed-holes`` flag, which enables this +This flag implies the :ghc-flag:`-fdefer-typed-holes` flag, which enables this behaviour for `typed holes <#typed-holes>`__. Should you so wish, it is -possible to enable ``-fdefer-type-errors`` without enabling -``-fdefer-typed-holes``, by explicitly specifying -``-fno-defer-typed-holes`` on the command-line after the -``-fdefer-type-errors`` flag. +possible to enable :ghc-flag:`-fdefer-type-errors` without enabling +:ghc-flag:`-fdefer-typed-holes`, by explicitly specifying +:ghc-flag:`-fno-defer-typed-holes` on the command-line after the +:ghc-flag:`-fdefer-type-errors` 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: - -:: +example, given the following code: :: x :: Int x = 0 @@ -9752,11 +9347,9 @@ evaluating ``z`` will result in a runtime ``TypeError``. Deferred type errors in GHCi ---------------------------- -The flag ``-fdefer-type-errors`` works in GHCi as well, with one +The flag :ghc-flag:`-fdefer-type-errors` works in GHCi as well, with one exception: for "naked" expressions typed at the prompt, type errors -don't get delayed, so for example: - -:: +don't get delayed, so for example: :: Prelude> fst (True, 1 == 'a') @@ -9772,9 +9365,7 @@ Otherwise, in the common case of a simple type error such as typing immediately-following type error when the expression is evaluated. This exception doesn't apply to statements, as the following example -demonstrates: - -:: +demonstrates: :: Prelude> let x = (True, 1 == 'a') @@ -9820,17 +9411,20 @@ GHC. It is not detailed enough to understand Template Haskell; see the Syntax ------ -.. index:: - single: -XTemplateHaskell - single: -XTemplateHaskellQuotes +.. ghc-flag:: -XTemplateHaskell + + Enable Template Haskell's splice and quotation syntax. + +.. ghc-flag:: -XTemplateHaskellQuotes + + Enable only Template Haskell's quotation syntax. -Template Haskell has the following new syntactic constructions. You -need to use the flag ``-XTemplateHaskell`` to switch these syntactic -extensions on. Alternatively, the ``-XTemplateHaskellQuotes`` flag can -be used to enable the quotation subset of Template Haskell -(i.e. without splice syntax). The ``-XTemplateHaskellQuotes`` -extension is considered safe under :ref:`safe-haskell` while -``-XTemplateHaskell`` is not. +Template Haskell has the following new syntactic constructions. You need to use +the flag :ghc-flag:`-XTemplateHaskell` to switch these syntactic extensions on. +Alternatively, the :ghc-flag:`-XTemplateHaskellQuotes` flag can be used to +enable the quotation subset of Template Haskell (i.e. without splice syntax). +The :ghc-flag:`-XTemplateHaskellQuotes` extension is considered safe under +:ref:`safe-haskell` while :ghc-flag:`-XTemplateHaskell` is not. - A splice is written ``$x``, where ``x`` is an identifier, or ``$(...)``, where the "..." is an arbitrary expression. There must be @@ -9917,9 +9511,7 @@ extension is considered safe under :ref:`safe-haskell` while - It is possible for a splice to expand to an expression that contain names which are not in scope at the site of the splice. As an - example, consider the following code: - - :: + example, consider the following code: :: module Bar where @@ -9929,9 +9521,7 @@ extension is considered safe under :ref:`safe-haskell` while add1 x = [| x + 1 |] Now consider a splice using <literal>add1</literal> in a separate - module: - - :: + module: :: module Foo where @@ -9945,9 +9535,7 @@ extension is considered safe under :ref:`safe-haskell` while ``x`` into a value of type ``Q Exp``. This functionality is exposed to the user as the ``Lift`` typeclass in the ``Language.Haskell.TH.Syntax`` module. If a type has a ``Lift`` instance, then any of its values can be - lifted to a Template Haskell expression: - - :: + lifted to a Template Haskell expression: :: class Lift t where lift :: t -> Q Exp @@ -9964,14 +9552,12 @@ extension is considered safe under :ref:`safe-haskell` while The ``template-haskell`` library provides ``Lift`` instances for many common data types. Furthermore, it is possible to derive ``Lift`` - instances automatically by using the ``-XDeriveLift`` language extension. + instances automatically by using the :ghc-flag:`-XDeriveLift` language extension. See :ref:`deriving-lift` 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 - - :: + For example, you can write :: module Foo where import Bar @@ -9994,9 +9580,7 @@ extension is considered safe under :ref:`safe-haskell` while run. Note that pattern splices that occur 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, - - :: + bracket is spliced in, sometime later. For example, :: mkPat :: Q Pat mkPat = [p| (x, y) |] @@ -10017,9 +9601,7 @@ extension is considered safe under :ref:`safe-haskell` while 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``. - - :: + quasiquoter, *not* the top-level ``y = 7``. :: y :: Int y = 7 @@ -10050,19 +9632,19 @@ extension is considered safe under :ref:`safe-haskell` while type environment seen by ``reify`` from a declaration quasiquoter will not include anything from the quasiquoter's declaration group. - Concretely, consider the following code - - :: + 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 = x + y - $(th2 10) - w z = $(blah2) + + import ... + + f x = x + $(th1 4) + h y = k y y $(blah1) + [qq|blah|] + k x y = x + y + $(th2 10) + w z = $(blah2) In this example @@ -10138,37 +9720,35 @@ Using Template Haskell compiles produces results whose representations are identical to those of the compiler itself. -Template Haskell works in any mode (``--make``, ``--interactive``, or -file-at-a-time). There used to be a restriction to the former two, but -that restriction has been lifted. +Template Haskell works in any mode (:ghc-flag:`--make`, +:ghc-flag:`--interactive`, or file-at-a-time). There used to be a restriction to +the former two, but that restriction has been lifted. .. _th-view-gen-code: Viewing Template Haskell generated code --------------------------------------- -The flag ``-ddump-splices`` shows the expansion of all top-level +The flag :ghc-flag:`-ddump-splices` 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 flag`` (see :ref:`dumping-output`. For each file using +:ghc-flag:`-ddump-to-file` flag (see :ref:`dumping-output`. For each file using Template Haskell, this will show the output in a ``.dump-splices`` file. -The flag ``-dth-dec-file`` shows the expansions of all top-level TH -declaration splices, both typed and untyped, in the file ``M.th.hs`` +The flag :ghc-flag:`-dth-dec-file` shows the expansions of all top-level TH +declaration splices, both typed and untyped, in the file :file:`M.th.hs` where M is the name of the module 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`` with ``-ddump-splices`` but it always -generates a file instead of being coupled to ``-ddump-to-file``. The +to using :ghc-flag:`-ddump-to-file` with :ghc-flag:`-ddump-splices` but it always +generates a file instead of being coupled to :ghc-flag:`-ddump-to-file`. 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 a sample output of ``-ddump-splices`` - -:: +Below is a sample output of :ghc-flag:`-ddump-splices` :: TH_pragma.hs:(6,4)-(8,26): Splicing declarations [d| foo :: Int -> Int @@ -10177,9 +9757,7 @@ Below is a sample output of ``-ddump-splices`` foo :: Int -> Int foo x = (x + 1) -Below is the output of the same sample using ``-dth-dec-file`` - -:: +Below is the output of the same sample using :ghc-flag:`-dth-dec-file` :: -- TH_pragma.hs:(6,4)-(8,26): Splicing declarations foo :: Int -> Int @@ -10191,8 +9769,8 @@ A Template Haskell Worked Example --------------------------------- To help you get over the confidence barrier, try out this skeletal -worked example. First cut and paste the two modules below into "Main.hs" -and "Printf.hs": +worked example. First cut and paste the two modules below into :file:`Main.hs` +and :file:`Printf.hs`: :: @@ -10241,15 +9819,15 @@ and "Printf.hs": pr :: String -> Q Exp pr s = gen (parse s) -Now run the compiler (here we are a Cygwin prompt on Windows): +Now run the compiler, -:: +.. code-block:: none - $ ghc --make -XTemplateHaskell main.hs -o main.exe + $ ghc --make -XTemplateHaskell main.hs -o main -Run "main.exe" and here is your output: +Run :file:`main` and here is your output: -:: +.. code-block:: none $ ./main Hello @@ -10281,27 +9859,24 @@ 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``. +1. Compile the program or library first the normal way, without :ghc-flag:`-prof`. - .. index:: - single : ``-prof`` - -2. Then compile it again with ``-prof``, and additionally use ``-osuf p_o`` +2. Then compile it again with :ghc-flag:`-prof`, 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`` flag when - building with ``-prof`` and Template Haskell is used, GHC will emit + executing splice expressions. If you omit the :ghc-flag:`-osuf` flag when + building with :ghc-flag:`-prof` and Template Haskell is used, GHC will emit an error message. .. index:: - single : ``-osuf`` + single : -osuf; using with profiling -The second option is to add the flag ``-fexternal-interpreter`` (see +The second option is to add the flag :ghc-flag:`-fexternal-interpreter` (see :ref:`external-interpreter`), 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`` and it should just work. (this option is +:ghc-flag:`-fexternal-interpreter` and it should just work. (this option is experimental in GHC 8.0.x, but it may become the default in future releases). @@ -10310,6 +9885,10 @@ releases). Template Haskell Quasi-quotation -------------------------------- +.. ghc-flag:: -XQuasiQuotes + + Enable Template Haskell Quasi-quotation syntax. + Quasi-quotation allows patterns and expressions to be written using programmer-defined concrete syntax; the motivation behind the extension and several examples are documented in "`Why It's Nice to be Quoted: @@ -10354,9 +9933,7 @@ Here are the salient features (Only the first two are described in the paper.) - A quoter is a value of type - ``Language.Haskell.TH.Quote.QuasiQuoter``, which is defined thus: - - :: + ``Language.Haskell.TH.Quote.QuasiQuoter``, which is defined thus: :: data QuasiQuoter = QuasiQuoter { quoteExp :: String -> Q Exp, quotePat :: String -> Q Pat, @@ -10450,13 +10027,13 @@ is used, but must be imported. Now run the compiler: -:: +.. code-block:: none $ ghc --make -XQuasiQuotes Main.hs -o main Run "main" and here is your output: -:: +.. code-block:: none $ ./main 3 @@ -10467,6 +10044,10 @@ Run "main" and here is your output: Arrow notation ============== +.. ghc-flag:: -XArrows + + Enable arrow notation. + Arrows are a generalisation of monads introduced by John Hughes. For more details, see @@ -10499,7 +10080,7 @@ more details, see - The arrows web page at ``http://www.haskell.org/arrows/`` <http://www.haskell.org/arrows/>`__. -With the ``-XArrows`` flag, GHC supports the arrow notation described in +With the :ghc-flag:`-XArrows` flag, GHC supports the arrow notation described in the second of these papers, translating it using combinators from the :base-ref:`Control.Arrow <Control-Arrow.html>` module. What follows is a brief introduction to the notation; it won't make much @@ -10507,7 +10088,7 @@ sense unless you've read Hughes's paper. The extension adds a new kind of expression for defining arrows: -:: +.. code-block:: none exp10 ::= ... | proc apat -> cmd @@ -10516,7 +10097,7 @@ 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: -:: +.. code-block:: none cmd ::= exp10 -< exp | exp10 -<< exp @@ -10525,7 +10106,7 @@ called a command. The syntax of commands is as follows: with ⟨cmd⟩\ :sup:`0` up to ⟨cmd⟩\ :sup:`9` defined using infix operators as for expressions, and -:: +.. code-block:: none cmd10 ::= \ apat ... apat -> cmd | let decls in cmd @@ -10553,9 +10134,7 @@ 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 - -:: +A simple example of the new notation is the expression :: proc x -> f -< x+1 @@ -10566,9 +10145,7 @@ example, ``-<`` is not an identifier but an 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 - -:: +example is equivalent to the Haskell expression :: arr (\ x -> x+1) >>> f @@ -10576,15 +10153,11 @@ 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 - -:: +variant ``-<<``, as in :: proc x -> f x -<< x+1 -which is equivalent to - -:: +which is equivalent to :: arr (\ x -> (f x, x+1)) >>> app @@ -10596,9 +10169,7 @@ do-notation for commands ------------------------ Another form of command is a form of ``do``-notation. For example, you -can write - -:: +can write :: proc x -> do y <- f -< x+1 @@ -10612,9 +10183,7 @@ 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 :base-ref:`Control.Arrow <Control-Arrow.html>` module as ``arr -id``. The above example is treated as an abbreviation for - -:: +id``. The above example is treated as an abbreviation for :: arr (\ x -> (x, x)) >>> first (arr (\ x -> x+1) >>> f) >>> @@ -10629,9 +10198,7 @@ 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 :ref:`rewrite-rules`) defined in the :base-ref:`Control.Arrow <Control-Arrow.html>` module, this -reduces to - -:: +reduces to :: arr (\ x -> (x+1, x)) >>> first f >>> @@ -10649,9 +10216,7 @@ 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: - -:: +``rec`` keyword, as in the following example: :: counter :: ArrowCircuit a => a Bool Int counter = proc reset -> do @@ -10667,18 +10232,14 @@ 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 - -:: +different commands, as in :: proc (x,y) -> if f x y then g -< x+1 else h -< y+2 -which is translated to - -:: +which is translated to :: arr (\ (x,y) -> if f x y then Left x else Right y) >>> (arr (\x -> x+1) >>> g) ||| (arr (\y -> y+2) >>> h) @@ -10686,9 +10247,7 @@ which is translated to Since the translation uses ``|||``, the arrow concerned must belong to the ``ArrowChoice`` class. -There are also ``case`` commands, like - -:: +There are also ``case`` commands, like :: case input of [] -> f -< () @@ -10713,15 +10272,11 @@ 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 - -:: +includes a combinator :: ArrowPlus a => (<+>) :: a b c -> a b c -> a b c -so we can use it to build commands: - -:: +so we can use it to build commands: :: expr' = proc x -> do returnA -< x @@ -10736,9 +10291,7 @@ so we can use it to build commands: (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 - -:: +This is equivalent to :: expr' = (proc x -> returnA -< x) <+> (proc x -> do @@ -10750,17 +10303,13 @@ This is equivalent to y <- term -< () expr' -< x - y) -We are actually using ``<+>`` here with the more specific type - -:: +We are actually using ``<+>`` here with the more specific type :: ArrowPlus a => (<+>) :: a (e,()) c -> a (e,()) c -> a (e,()) c It is essential that this operator be polymorphic in ``e`` (representing the environment input to the command and thence to its subcommands) and -satisfy the corresponding naturality property - -:: +satisfy the corresponding naturality property :: arr (first k) >>> (f <+> g) = (arr (first k) >>> f) <+> (arr (first k) >>> g) @@ -10772,9 +10321,7 @@ 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 - -:: +We could define our own operator :: untilA :: ArrowChoice a => a (e,s) () -> a (e,s) Bool -> a (e,s) () untilA body cond = proc x -> @@ -10786,9 +10333,7 @@ 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: - -:: +special brackets: :: proc x -> do y <- f -< x+1 @@ -10800,16 +10345,12 @@ 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 - -:: +occurred to the handler. Such an operator might have a type :: handleA :: ... => a (e,s) c -> a (e,(Ex,s)) c -> a (e,s) c where ``Ex`` is the type of exceptions handled. You could then use this -with arrow notation by writing a command - -:: +with arrow notation by writing a command :: body `handleA` \ ex -> handler @@ -10831,9 +10372,7 @@ 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 - -:: +each argument of the operator (and its result) should have the form :: a (e, (t1, ... (tn, ())...)) t @@ -10841,18 +10380,14 @@ 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: - -:: +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 - -:: +two by applying them to ordinary expressions, as in :: proc x -> do s <- ... @@ -10867,9 +10402,7 @@ 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 - -:: +defining :: bind :: Arrow a => a (e,s) b -> a (e,(b,s)) c -> a (e,s) c u `bind` f = returnA &&& u >>> f @@ -10877,9 +10410,7 @@ defining bind_ :: Arrow a => a (e,s) b -> a (e,s) c -> a (e,s) c u `bind_` f = u `bind` (arr fst >>> f) -We could simulate ``if`` by defining - -:: +We could simulate ``if`` by defining :: cond :: ArrowChoice a => a (e,s) b -> a (e,s) b -> a (e,(Bool,s)) b cond f g = arr (\ (e,(b,s)) -> if b then Left (e,s) else Right (e,s)) >>> f ||| g @@ -10888,8 +10419,8 @@ Differences with the paper -------------------------- - Instead of a single form of arrow application (arrow tail) with two - translations, the implementation provides two forms “``-<``” - (first-order) and “``-<<``” (higher-order). + translations, the implementation provides two forms ``-<`` + (first-order) and ``-<<`` (higher-order). - User-defined operators are flagged with banana brackets instead of a new ``form`` keyword. @@ -10925,6 +10456,10 @@ Bang patterns .. index:: single: Bang patterns +.. ghc-flag:: -XBangPatterns + + 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 @@ -10941,7 +10476,7 @@ new bullet 10, saying: Matching the pattern ``!``\ ⟨pat⟩ against a value - otherwise, ⟨pat⟩ is matched against ⟨v⟩ -Bang patterns are enabled by the flag ``-XBangPatterns``. +Bang patterns are enabled by the flag :ghc-flag:`-XBangPatterns`. .. _bang-patterns-informal: @@ -10949,31 +10484,23 @@ Informal description of bang patterns ------------------------------------- The main idea is to add a single new production to the syntax of -patterns: - -:: +patterns: :: pat ::= !pat Matching an expression ``e`` against a pattern ``!p`` is done by first evaluating ``e`` (to WHNF) and then matching the result against ``p``. -Example: - -:: +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: - -:: +bang it would be lazy. Bang patterns can be nested of course: :: f2 (!x, y) = [x,y] Here, ``f2`` is strict in ``x`` but not in ``y``. A bang only really has -an effect if it precedes a variable or wild-card pattern: - -:: +an effect if it precedes a variable or wild-card pattern: :: f3 !(x,y) = [x,y] f4 (x,y) = [x,y] @@ -10992,15 +10519,11 @@ polymorphic let bindings <recursive-and-polymorphic-let-bindings>` for how bang-pattern bindings are compiled. However, *nested* bangs in a pattern binding behave uniformly with all -other forms of pattern matching. For example - -:: +other forms of pattern matching. For example :: let (!x,[y]) = e in b -is equivalent to this: - -:: +is equivalent to this: :: let { t = case e of (x,[y]) -> x `seq` (x,y) x = fst t @@ -11011,9 +10534,7 @@ 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``. -Bang patterns work in ``case`` expressions too, of course: - -:: +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 } @@ -11028,24 +10549,18 @@ evaluates ``(f x)``, binds ``y`` to the result, and then evaluates Syntax and semantics -------------------- -We add a single new production to the syntax of patterns: - -:: +We add a single new production to the syntax of patterns: :: pat ::= !pat -There is one problem with syntactic ambiguity. Consider: - -:: +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 in favour of the latter. If you want to define ``(!)`` with bang-patterns enabled, you -have to do so using prefix notation: - -:: +have to do so using prefix notation: :: (!) f x = 3 @@ -11062,9 +10577,7 @@ the Haskell Report. To this description add one extra item 10, saying: Similarly, in Figure 4 of `Section 3.17.3 <http://www.haskell.org/onlinereport/exps.html#sect3.17.3>`__, -add a new case (t): - -:: +add a new case (t): :: case v of { !pat -> e; _ -> e' } = v `seq` case v of { pat -> e; _ -> e' } @@ -11079,9 +10592,7 @@ bang at the top, apply the rules in the existing box. The effect of the let rule is to force complete matching of the pattern ``qi`` before evaluation of the body is begun. The bang is retained in -the translated form in case ``qi`` is a variable, thus: - -:: +the translated form in case ``qi`` is a variable, thus: :: let !y = f x in b @@ -11102,9 +10613,7 @@ Assertions single: Assertions If you want to make use of assertions in your standard Haskell code, you -could define a function like the following: - -:: +could define a function like the following: :: assert :: Bool -> a -> a assert False x = error "assertion failed!" @@ -11119,17 +10628,13 @@ 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: - -:: +of ``assert`` in the user's source: :: kelvinToC :: Double -> Double kelvinToC k = assert (k >= 0.0) (k+273.15) GHC will rewrite this to also include the source location where the -assertion was made, - -:: +assertion was made, :: assert pred val ==> assertError "Main.hs|15" pred val @@ -11139,17 +10644,17 @@ own versions of ``assert``, should you so wish. If not, import ``Control.Exception`` to make use ``assert`` in your code. .. index:: - single: -O flag - single: -fignore-asserts + pair: assertions; disabling GHC ignores assertions when optimisation is turned on with the -``-O`` flag. That is, expressions of the form ``assert pred e`` +:ghc-flag:`-O` flag. That is, expressions of the form ``assert pred e`` will be rewritten to ``e``. You can also disable assertions using the -``-fignore-asserts`` option. The option ``-fno-ignore-asserts`` allows enabling -assertions even when optimisation is turned on. +:ghc-flag:`-fignore-asserts` option. The option +:ghc-flag:`-fno-ignore-asserts <-fignore-asserts>` +allows enabling assertions even when optimisation is turned on. Assertion failures can be caught, see the documentation for the -``Control.Exception`` library for the details. +:base-ref:`Control.Exception <Control-Exception.html>` library for the details. .. _static-pointers: @@ -11159,7 +10664,11 @@ Static pointers .. index:: single: Static pointers -The language extension ``-XStaticPointers`` adds a new syntactic form +.. ghc-flag:: -XStaticPointers + + Allow use of static pointer syntax. + +The language extension :ghc-flag:`-XStaticPointers` adds a new syntactic form ``static e``, which stands for a reference to the closed expression ⟨e⟩. This reference is stable and portable, in the sense that it remains valid across different processes on possibly different machines. Thus, a @@ -11191,9 +10700,7 @@ The body ``e`` of a ``static e`` expression must be a closed expression. That is, there can be no free variables occurring in ``e``, i.e. lambda- or let-bound variables bound locally in the context of the expression. -All of the following are permissible: - -:: +All of the following are permissible: :: inc :: Int -> Int inc x = x + 1 @@ -11204,9 +10711,7 @@ All of the following are permissible: ref4 = static ((\x -> x + 1) (1 :: Int)) ref5 y = static (let x = 1 in x) -While the following definitions are rejected: - -:: +While the following definitions are rejected: :: ref6 = let x = 1 in static x ref7 y = static (let x = 1 in y) @@ -11216,30 +10721,22 @@ While the following definitions are rejected: Static semantics of static pointers ----------------------------------- -Informally, if we have a closed expression - -:: +Informally, if we have a closed expression :: e :: forall a_1 ... a_n . t -the static form is of type - -:: +the static form is of type :: static e :: (Typeable a_1, ... , Typeable a_n) => StaticPtr t Furthermore, type ``t`` is constrained to have a ``Typeable`` instance. -The following are therefore illegal: - -:: +The following are therefore illegal: :: static show -- No Typeable instance for (Show a => a -> String) static Control.Monad.ST.runST -- No Typeable instance for ((forall s. ST s a) -> a) That being said, with the appropriate use of wrapper datatypes, the -above limitations induce no loss of generality: - -:: +above limitations induce no loss of generality: :: {-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE DeriveDataTypeable #-} @@ -11314,9 +10811,7 @@ portable way. It is the intention that all Haskell compilers support the are supported by all compilers, of course. The ``LANGUAGE`` pragma should be used instead of ``OPTIONS_GHC``, if possible. -For example, to enable the FFI and preprocessing with CPP: - -:: +For example, to enable the FFI and preprocessing with CPP: :: {-# LANGUAGE ForeignFunctionInterface, CPP #-} @@ -11327,7 +10822,7 @@ prefixing it with "``-X``"; for example ``-XForeignFunctionInterface``. (Similarly, all "``-X``" flags can be written as ``LANGUAGE`` pragmas.) A list of all supported language extensions can be obtained by invoking -``ghc --supported-extensions`` (see :ref:`modes`). +``ghc --supported-extensions`` (see :ghc-flag:`--supported-extensions`). Any extension from the ``Extension`` type defined in :cabal-ref:`Language.Haskell.Extension <Language-Haskell-Extension.html>` @@ -11376,16 +10871,12 @@ particular function, class, or type. A ``DEPRECATED`` pragma lets you specify that a particular function, class, or type is deprecated. There are two ways of using these pragmas. -- You can work on an entire module thus: - - :: +- You can work on an entire module thus: :: module Wibble {-# DEPRECATED "Use Wobble instead" #-} where ... - Or: - - :: + Or: :: module Wibble {-# WARNING "This is an unstable interface." #-} where ... @@ -11394,9 +10885,7 @@ are two ways of using these pragmas. the specified message. - You can attach a warning to a function, class, type, or data - constructor, with the following top-level declarations: - - :: + constructor, with the following top-level declarations: :: {-# DEPRECATED f, C, T "Don't use these" #-} {-# WARNING unsafePerformIO "This is unsafe; I hope you know what you're doing" #-} @@ -11418,7 +10907,7 @@ 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``. +:ghc-flag:`-Wno-warnings-deprecations <-Wwarnings-deprecations>`. .. _minimal-pragma: @@ -11433,9 +10922,7 @@ The ``MINIMAL`` pragma is used to specify the minimal complete definition of a class, i.e. specify which methods must be implemented by all instances. If an instance does not satisfy the minimal complete definition, then a warning is generated. This can be useful when a class -has methods with circular defaults. For example - -:: +has methods with circular defaults. For example :: class Eq a where (==) :: a -> a -> Bool @@ -11447,9 +10934,7 @@ has methods with circular defaults. For example Without the ``MINIMAL`` pragma no warning would be generated for an instance that implements neither method. -The syntax for minimal complete definition is: - -:: +The syntax for minimal complete definition is: :: mindef ::= name | '(' mindef ')' @@ -11464,10 +10949,10 @@ 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 (a) that lack a default method in the class declaration, and (b) whose name that does not start with an underscore -(c.f. ``-Wmissing-methods``, :ref:`options-sanity`). +(c.f. :ghc-flag:`-Wmissing-methods`, :ref:`options-sanity`). This warning can be turned off with the flag -``-Wno-missing-methods``. +:ghc-flag:`-Wno-missing-methods <-Wmissing-methods>`. .. _inline-noinline-pragma: @@ -11485,7 +10970,7 @@ INLINE pragma single: INLINE single: pragma; ``INLINE`` -GHC (with ``-O``, as always) tries to inline (or "unfold") +GHC (with :ghc-flag:`-O`, as always) tries to inline (or "unfold") functions/values that are "small enough," thus avoiding the call overhead and possibly exposing other more-wonderful optimisations. GHC has a set of heuristics, tuned over a long period of time using many @@ -11503,9 +10988,7 @@ override the default behaviour. For example, if you have a key function that is important to inline because it leads to further optimisations, but GHC judges it to be too big to inline. -The sledgehammer you can bring to bear is the ``INLINE`` pragma, used thusly: - -:: +The sledgehammer you can bring to bear is the ``INLINE`` pragma, used thusly: :: key_function :: Int -> String -> (Bool, Double) {-# INLINE key_function #-} @@ -11516,15 +10999,11 @@ 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 - - :: + For example, if you write :: map key_function xs - there really isn't any point in inlining ``key_function`` to get - - :: + there really isn't any point in inlining ``key_function`` to get :: map (\x -> body) xs @@ -11533,9 +11012,7 @@ has a number of other effects: - 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: - - :: + (syntactically) on the LHS of the function definition. For example: :: comp1 :: (b -> c) -> (a -> b) -> a -> c {-# INLINE comp1 #-} @@ -11548,9 +11025,7 @@ has a number of other effects: 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 - - :: + say :: map (not `comp1` not) xs @@ -11588,9 +11063,7 @@ its type signature could be put. ``INLINE`` pragmas are a particularly good idea for the ``then``/``return`` (or ``bind``/``unit``) functions in a monad. For -example, in GHC's own ``UniqueSupply`` monad code, we have: - -:: +example, in GHC's own ``UniqueSupply`` monad code, we have: :: {-# INLINE thenUs #-} {-# INLINE returnUs #-} @@ -11862,9 +11335,7 @@ A ``SPECIALIZE`` pragma can optionally be followed with a ``INLINE`` or ``NOINLINE`` pragma, optionally followed by a phase, as described in :ref:`inline-noinline-pragma`. The ``INLINE`` pragma affects the specialised version of the function (only), and applies even if the -function is recursive. The motivating example is this: - -:: +function is recursive. The motivating example is this: :: -- A GADT for arrays with type-indexed representation data Arr e where @@ -11898,10 +11369,7 @@ control of the specialised function. Generally, you can only give a ``SPECIALIZE`` pragma for a function defined in the same module. However if a function ``f`` is given an ``INLINABLE`` pragma at its definition site, then it can subsequently be -specialised by importing modules (see :ref:`inlinable-pragma`). For -example - -:: +specialised by importing modules (see :ref:`inlinable-pragma`). For example :: module Map( lookup, blah blah ) where lookup :: Ord key => [(key,a)] -> key -> Maybe a @@ -11926,7 +11394,7 @@ specialised version of ``lookup``. You don't need to put a Moreover you often don't even need the ``SPECIALIZE`` pragma in the first place. When compiling a module ``M``, GHC's optimiser (when given the -``-O`` flag) automatically considers each top-level overloaded function declared +:ghc-flag:`-O` flag) automatically 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* ``INLINABLE`` overloaded function, and specialises it for the different types at which @@ -11990,9 +11458,7 @@ declaration. The ``UNPACK`` indicates to the compiler that it should unpack the contents of a constructor field into the constructor itself, removing a -level of indirection. For example: - -:: +level of indirection. For example: :: data T = T {-# UNPACK #-} !Float {-# UNPACK #-} !Float @@ -12003,27 +11469,21 @@ 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`` [1]_, in order to expose unfoldings to the compiler so the -reboxing can be removed as often as possible. For example: - -:: +:ghc-flag:`-O` [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`` is on. - -Any single-constructor data is eligible for unpacking; for example +floats, but only when :ghc-flag:`-O` is on. -:: +Any single-constructor data is eligible for unpacking; for example :: data T = T {-# UNPACK #-} !(Int,Int) will store the two ``Int``\ s directly in the ``T`` constructor, by -flattening the pair. Multi-level unpacking is also supported: - -:: +flattening the pair. Multi-level unpacking is also supported: :: data T = T {-# UNPACK #-} !S data S = S {-# UNPACK #-} !Int {-# UNPACK #-} !Int @@ -12031,7 +11491,7 @@ flattening the pair. Multi-level unpacking 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`` flag, which essentially has the +See also the :ghc-flag:`-funbox-strict-fields` flag, which essentially has the effect of adding ``{-# UNPACK #-}`` to every strict constructor field. .. [1] @@ -12050,14 +11510,12 @@ effect of adding ``{-# UNPACK #-}`` to every strict constructor field. single: NOUNPACK The ``NOUNPACK`` pragma indicates to the compiler that it should not -unpack the contents of a constructor field. Example: - -:: +unpack the contents of a constructor field. Example: :: data T = T {-# NOUNPACK #-} !(Int,Int) -Even with the flags ``-funbox-strict-fields`` and ``-O``, the field of -the constructor ``T`` is not unpacked. +Even with the flags :ghc-flag:`-funbox-strict-fields` and :ghc-flag:`-O`, the +field of the constructor ``T`` is not unpacked. .. _source-pragma: @@ -12107,19 +11565,21 @@ Rewrite rules single: rewrite rules The programmer can specify rewrite rules as part of the source program -(in a pragma). Here is an example: - -:: +(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`` to see what rules fired. If -you need more information, then ``-ddump-rule-firings`` shows you each -individual rule firing and ``-ddump-rule-rewrites`` also shows what the +Use the debug flag :ghc-flag:`-ddump-simpl-stats` to see what rules fired. If +you need more information, then :ghc-flag:`-ddump-rule-firings` shows you each +individual rule firing and :ghc-flag:`-ddump-rule-rewrites` also shows what the code looks like before and after the rewrite. +.. ghc-flag:: -fenable-rewrite-rules + + Allow the compiler to apply rewrite rules to the source program. + Syntax ------ @@ -12131,9 +11591,7 @@ From a syntactic point of view: - The layout rule applies in a pragma. Currently no new indentation level is set, so if you put several rules in single RULES pragma and wish to use layout to separate them, you must lay out the starting in - the same column as the enclosing definitions. - - :: + the same column as the enclosing definitions. :: {-# RULES "map/map" forall f g xs. map f (map g xs) = map (f.g) xs @@ -12148,19 +11606,17 @@ From a syntactic point of view: the rule fired. - A rule may optionally have a phase-control number (see - :ref:`phase-control`), immediately after the name of the rule. Thus: - - :: + :ref:`phase-control`), immediately 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 ``[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 + Rules support the special phase-control notation ``[~]``, which means the rule is never active. This feature supports plugins (see :ref:`compiler-plugins`), by making it possible to define a RULE that is never run by GHC, but is nevertheless parsed, typechecked etc, so @@ -12173,9 +11629,7 @@ From a syntactic point of view: - 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: - - :: + signature. For example, here is the ``foldr/build`` rule: :: "fold/build" forall k z (g::forall b. (a->b->b) -> b -> b) . foldr k z (build g) = g k z @@ -12183,9 +11637,7 @@ From a syntactic point of view: Since ``g`` has a polymorphic type, it must have a type signature. - The left hand side of a rule must consist of a top-level variable - applied to arbitrary expressions. For example, this is *not* OK: - - :: + applied to arbitrary expressions. For example, this is *not* OK: :: "wrong1" forall e1 e2. case True of { True -> e1; False -> e2 } = e1 "wrong2" forall f. f True = True @@ -12204,13 +11656,13 @@ From a syntactic point of view: - Inside a RULE "``forall``" is treated as a keyword, regardless of any other flag settings. Furthermore, inside a RULE, the language - extension ``-XScopedTypeVariables`` is automatically enabled; see + extension :ghc-flag:`-XScopedTypeVariables` is automatically enabled; see :ref:`scoped-type-variables`. - Like other pragmas, RULE 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`` flag is on (see + only *enabled* if the :ghc-flag:`-fenable-rewrite-rules` flag is on (see :ref:`rule-semantics`). .. _rule-semantics: @@ -12221,14 +11673,14 @@ Semantics From a semantic point of view: - Rules are enabled (that is, used during optimisation) by the - ``-fenable-rewrite-rules`` flag. This flag is implied by ``-O``, and - may be switched off (as usual) by ``-fno-enable-rewrite-rules``. (NB: - enabling ``-fenable-rewrite-rules`` without ``-O`` may not do what - you expect, though, because without ``-O`` GHC ignores all - optimisation information in interface files; see - ``-fignore-interface-pragmas``, :ref:`options-f`.) Note that - ``-fenable-rewrite-rules`` is an *optimisation* flag, and has no - effect on parsing or typechecking. + :ghc-flag:`-fenable-rewrite-rules` flag. This flag is implied by + :ghc-flag:`-O`, and may be switched off (as usual) by + :ghc-flag:`-fno-enable-rewrite-rules <-f-enable-rewrite-rules>`. (NB: enabling + :ghc-flag:`-fenable-rewrite-rules` without :ghc-flag:`-O` may not do what you + expect, though, because without :ghc-flag:`-O` GHC ignores all optimisation + information in interface files; see :ghc-flag:`-fignore-interface-pragmas`). + Note that :ghc-flag:`-fenable-rewrite-rules` is an + *optimisation* flag, and has no effect on parsing or typechecking. - Rules are regarded as left-to-right rewrite rules. When GHC finds an expression that is a substitution instance of the LHS of a rule, it @@ -12242,9 +11694,7 @@ From a semantic point of view: the programmer's! - GHC makes no attempt to make sure that the rules are confluent or - terminating. For example: - - :: + terminating. For example: :: "loop" forall x y. f x y = f y x @@ -12266,9 +11716,7 @@ From a semantic point of view: if the types match too. See :ref:`rule-spec` below. - GHC keeps trying to apply the rules as it optimises the program. For - example, consider: - - :: + example, consider: :: let s = map f t = map g @@ -12287,9 +11735,7 @@ How rules interact with ``INLINE``/``NOINLINE`` pragmas ------------------------------------------------------- Ordinary inlining happens at the same time as rule rewriting, which may -lead to unexpected results. Consider this (artificial) example - -:: +lead to unexpected results. Consider this (artificial) example :: f x = x g y = f y @@ -12298,9 +11744,7 @@ lead to unexpected results. Consider this (artificial) example {-# RULES "f" f True = False #-} Since ``f``\'s right-hand side is small, it is inlined into ``g``, to -give - -:: +give :: g y = y @@ -12311,7 +11755,7 @@ been a better chance that ``f``\'s RULE might fire. The way to get predictable behaviour is to use a NOINLINE pragma, or an INLINE[⟨phase⟩] pragma, on ``f``, to ensure that it is not inlined until its RULEs have had a chance to fire. The warning flag -``-Winline-rule-shadowing`` (see :ref:`options-sanity`) warns about +:ghc-flag:`-Winline-rule-shadowing` (see :ref:`options-sanity`) warns about this situation. .. _conlike: @@ -12319,9 +11763,7 @@ this situation. How rules interact with CONLIKE pragmas --------------------------------------- -GHC is very cautious about duplicating work. For example, consider - -:: +GHC is very cautious about duplicating work. For example, consider :: f k z xs = let xs = build g in ...(foldr k z xs)...sum xs... @@ -12334,9 +11776,7 @@ 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: - -:: +CONLIKE pragma to declare it, thus: :: {-# INLINE CONLIKE [1] f #-} f x = blah @@ -12356,9 +11796,7 @@ before the rule has a chance to fire. How rules interact with class methods ------------------------------------- -Giving a RULE for a class method is a bad idea: - -:: +Giving a RULE for a class method is a bad idea: :: class C a where op :: a -> a -> a @@ -12371,9 +11809,7 @@ Giving a RULE for a class method is a bad idea: 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 - -:: +where :: opBool :: Bool -> Bool -> Bool opBool x y = ..rhs for op at Bool... @@ -12382,9 +11818,7 @@ So the RULE never has a chance to fire, for just the same reasons as in :ref:`rules-inline`. 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: - -:: +a pragma to prevent it being inlined too early, and give a RULE for it: :: instance C Bool where op x y = opBool @@ -12396,9 +11830,7 @@ a pragma to prevent it being inlined too early, and give a RULE for it: {-# RULES "f" opBool True y = False #-} If you want a RULE that truly applies to the overloaded class method, -the only way to do it is like this: - -:: +the only way to do it is like this: :: class C a where op_c :: a -> a -> a @@ -12473,9 +11905,7 @@ The following are good consumers: - ``msum`` -So, for example, the following should generate no intermediate lists: - -:: +So, for example, the following should generate no intermediate lists: :: array (1,10) [(i,i*i) | i <- map (+ 1) [0..9]] @@ -12491,9 +11921,7 @@ Specialisation -------------- Rewrite rules can be used to get the same effect as a feature present in -earlier versions of GHC. For example, suppose that: - -:: +earlier versions of GHC. For example, suppose that: :: genericLookup :: Ord a => Table a b -> a -> b intLookup :: Table Int b -> Int -> b @@ -12502,16 +11930,12 @@ 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 - -:: +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: - -:: +thing: :: {-# RULES "genericLookup/Int" genericLookup = intLookup #-} @@ -12524,9 +11948,7 @@ more, this rule does not need to be in the same file as 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: - -:: +An example in which using ``RULES`` for specialisation will Win Big: :: toDouble :: Real a => a -> Double toDouble = fromRational . toRational @@ -12543,21 +11965,19 @@ comparison. Controlling what's going on in rewrite rules -------------------------------------------- -- Use ``-ddump-rules`` to see the rules that are defined *in this +- Use :ghc-flag:`-ddump-rules` 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`` to see what rules are being fired. If you - add ``-dppr-debug`` you get a more detailed listing. +- Use :ghc-flag:`-ddump-simpl-stats` to see what rules are being fired. If you + add :ghc-flag:`-dppr-debug` you get a more detailed listing. -- Use ``-ddump-rule-firings`` or ``-ddump-rule-rewrites`` to see in - great detail what rules are being fired. If you add ``-dppr-debug`` +- Use :ghc-flag:`-ddump-rule-firings` or :ghc-flag:`-ddump-rule-rewrites` to see in + great detail what rules are being fired. If you add :ghc-flag:`-dppr-debug` you get a still more detailed listing. - The definition of (say) ``build`` in ``GHC/Base.lhs`` looks like - this: - - :: + this: :: build :: forall a. (forall b. (a -> b -> b) -> b -> b) -> [a] {-# INLINE build #-} @@ -12606,11 +12026,12 @@ programming <#generic-programming>`__. Generic programming =================== -Using a combination of ``-XDeriveGeneric`` (:ref:`deriving-typeable`), -``-XDefaultSignatures`` (:ref:`class-default-signatures`), and -``-XDeriveAnyClass`` (:ref:`derive-any-class`), you can easily do -datatype-generic programming using the ``GHC.Generics`` framework. This -section gives a very brief overview of how to do it. +Using a combination of :ghc-flag:`-XDeriveGeneric`, +:ghc-flag:`-XDefaultSignatures`, and +:ghc-flag:`-XDeriveAnyClass`, you can easily do +datatype-generic programming using the :base-ref:`GHC.Generics +<GHC-Generics.html>` framework. This section gives a very brief overview of how +to do it. Generic programming support in GHC allows defining classes with methods that do not need a user specification when instantiating: the method @@ -12623,9 +12044,7 @@ Deriving representations The first thing we need is generic representations. The ``GHC.Generics`` module defines a couple of primitive types that are used to represent -Haskell datatypes: - -:: +Haskell datatypes: :: -- | Unit: used for constructors without arguments data U1 p = U1 @@ -12645,9 +12064,7 @@ Haskell datatypes: data (:*:) f g p = f p :*: g p The ``Generic`` and ``Generic1`` classes mediate between user-defined -datatypes and their internal representation as a sum-of-products: - -:: +datatypes and their internal representation as a sum-of-products: :: class Generic a where -- Encode the representation of a user datatype @@ -12665,18 +12082,15 @@ 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``. Instances of these classes can be derived -by GHC with the ``-XDeriveGeneric`` (:ref:`deriving-typeable`), and are +by GHC with the :ghc-flag:`-XDeriveGeneric`, and are necessary to be able to define generic instances automatically. -For example, a user-defined datatype of trees +For example, a user-defined datatype of trees :: -:: data UserTree a = Node a (UserTree a) (UserTree a) | Leaf in a ``Main`` module in a package named ``foo`` will get the following -representation: - -:: +representation: :: instance Generic (UserTree a) where -- Representation type @@ -12715,9 +12129,7 @@ Writing generic functions A generic function is defined by creating a class and giving instances for each of the representation types of ``GHC.Generics``. As an example -we show generic serialization: - -:: +we show generic serialization: :: data Bin = O | I @@ -12793,9 +12205,7 @@ Generic defaults ---------------- The only thing left to do now is to define a "front-end" class, which is -exposed to the user: - -:: +exposed to the user: :: class Serialize a where put :: a -> [Bin] @@ -12807,15 +12217,13 @@ Here we use a `default signature <#class-default-signatures>`__ 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: - -:: +write: :: instance (Serialize a) => Serialize (UserTree a) The default method for ``put`` is then used, corresponding to the generic implementation of serialization. If you are using -``-XDeriveAnyClass``, the same instance is generated by simply attaching +:ghc-flag:`-XDeriveAnyClass`, 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 <http://hackage.haskell.org/package/generic-deriving>`__ @@ -12842,7 +12250,7 @@ Roles .. index:: single: roles -Using ``-XGeneralizedNewtypeDeriving`` +Using :ghc-flag:`-XGeneralizedNewtypeDeriving` (:ref:`generalized-newtype-deriving`), a programmer can take existing instances of classes and "lift" these into instances of that class for a newtype. However, this is not always safe. For example, consider the @@ -12914,9 +12322,7 @@ 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: - -:: +Here are some examples: :: data Simple a = MkSimple a -- a has role representational @@ -12963,18 +12369,14 @@ 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: - -:: +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: - -:: +However, this would be wrong, as the following example shows: :: data Nom a = MkNom (F a) -- type family F from example above @@ -12986,13 +12388,15 @@ role nominal for ``b``. .. _role-annotations: -Role annotations -XRoleAnnotations ----------------------------------- +Role annotations +---------------- -Sometimes the programmer wants to constrain the inference process. For -example, the base library contains the following definition: +.. ghc-flag:: -XRoleAnnotations -:: + 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# @@ -13000,14 +12404,12 @@ 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 -``Ptr``\ s! So, we want to be able to say - -:: +``Ptr``\ s! So, we want to be able to say :: type role Ptr representational data Ptr a = Ptr Addr# -The ``type role`` (enabled with ``-XRoleAnnotations``) declaration +The ``type role`` (enabled with :ghc-flag:`-XRoleAnnotations`) 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 @@ -13020,16 +12422,14 @@ 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 - -:: +This would be done with a declaration :: type role Set nominal Role annotations can also be used should a programmer wish to write a class with a representational (or phantom) role. However, as a class with non-nominal roles can quickly lead to class instance incoherence, -it is necessary to also specify ``-XIncoherentInstances`` to allow +it is necessary to also specify :ghc-flag:`-XIncoherentInstances` to allow non-nominal roles for classes. The other place where role annotations may be necessary are in @@ -13048,9 +12448,7 @@ GADT-style data or newtype declaration.) Each role listing is a role (``nominal``, ``representational``, 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: - -:: +like a value-level type signature). Here are some examples: :: type role T1 _ phantom data T1 a b = MkT1 a -- b is not used; annotation is fine but unnecessary @@ -13082,7 +12480,7 @@ High-performance Haskell code (e.g. numeric code) can sometimes be littered with bang patterns, making it harder to read. The reason is that lazy evaluation isn't the right default in this particular code but the programmer has no way to say that except by repeatedly adding -bang patterns. Below ``-XStrictData`` and ``-XStrict`` are detailed +bang patterns. Below :ghc-flag:`-XStrictData` and :ghc-flag:`-XStrict` are detailed that allows the programmer to switch the default behavior on a per-module basis. @@ -13091,20 +12489,20 @@ per-module basis. Strict-by-default data types ---------------------------- +.. ghc-flag:: -XStrictData + + 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 - -:: +When the user writes :: data T = C a data T' = C' ~a -we interpret it as if they had written - -:: +we interpret it as if they had written :: data T = C !a data T' = C' a @@ -13117,6 +12515,10 @@ The extension only affects definitions in this module. Strict-by-default pattern bindings ---------------------------------- +.. ghc-flag:: -XStrict + + 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 diff --git a/docs/users_guide/packages.rst b/docs/users_guide/packages.rst index c2e2709e9c..02d9cc6992 100644 --- a/docs/users_guide/packages.rst +++ b/docs/users_guide/packages.rst @@ -38,7 +38,7 @@ Using Packages GHC only knows about packages that are *installed*. To see which packages are installed, use the ``ghc-pkg list`` command: -:: +.. code-block:: none $ ghc-pkg list /usr/lib/ghc-6.12.1/package.conf.d: @@ -109,7 +109,7 @@ when compiling code using GHC's Safe Haskell feature (see To see which modules are provided by a package use the ``ghc-pkg`` command (see :ref:`package-management`): -:: +.. code-block:: none $ ghc-pkg field network exposed-modules exposed-modules: Network.BSD, @@ -120,25 +120,23 @@ command (see :ref:`package-management`): The GHC command line options that control packages are: -``-package ⟨pkg⟩`` - .. index:: - single: -package +.. ghc-flag:: -package ⟨pkg⟩ This option causes the installed package ⟨pkg⟩ to be exposed. The package ⟨pkg⟩ can be specified in full with its version number (e.g. ``network-1.0``) or the version number can be omitted if there is only one version of the package installed. If there are multiple - versions of ⟨pkg⟩ installed and ``-hide-all-packages`` was not - specified, then all other versions will become hidden. ``-package`` + versions of ⟨pkg⟩ installed and :ghc-flag:`-hide-all-packages` was not + specified, then all other versions will become hidden. :ghc-flag:`-package` supports thinning and renaming described in :ref:`package-thinning-and-renaming`. The ``-package ⟨pkg⟩`` option also causes package ⟨pkg⟩ to be linked into the resulting executable or shared object. Whether a packages' library is linked statically or dynamically is controlled by the - flag pair ``-static``/``-dynamic``. + flag pair :ghc-flag:`-static`\/ :ghc-flag:`-dynamic`. - In ``--make`` mode and ``--interactive`` mode (see :ref:`modes`), + In :ghc-flag:`--make` mode and :ghc-flag:`--interactive` mode (see :ref:`modes`), the compiler normally determines which packages are required by the current Haskell modules, and links only those. In batch mode however, the dependency information isn't available, and explicit @@ -152,47 +150,41 @@ The GHC command line options that control packages are: ``Main.o``, where we made use of the ``network`` package, we need to give GHC the ``-package`` flag thus: - :: + .. code-block:: sh $ ghc -o myprog Foo.o Main.o -package network The same flag is necessary even if we compiled the modules from source, because GHC still reckons it's in batch mode: - :: + .. code-block:: sh $ ghc -o myprog Foo.hs Main.hs -package network -``-package-id ⟨pkg-id⟩`` - .. index:: - single: -package-id +.. ghc-flag:: -package-id ⟨pkg-id⟩ - Exposes a package like ``-package``, but the package is named by its + Exposes a package like :ghc-flag:`-package`, but the package is named by its 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 :ref:`package-thinning-and-renaming`. -``-hide-all-packages`` - .. index:: - single: -hide-all-packages +.. ghc-flag:: -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`` options. + :ghc-flag:`-package` 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⟩`` - .. index:: - single: -hide-package +.. ghc-flag:: -hide-package ⟨pkg⟩ - This option does the opposite of ``-package``: it causes the + This option does the opposite of :ghc-flag:`-package`: it causes the specified package to be hidden, which means that none of its modules will be available for import by Haskell ``import`` directives. @@ -200,37 +192,29 @@ The GHC command line options that control packages are: program, if it is a dependency (direct or indirect) of another exposed package. -``-ignore-package ⟨pkg⟩`` - .. index:: - single: -ignore-package +.. ghc-flag:: -ignore-package ⟨pkg⟩ Causes the compiler to behave as if package ⟨pkg⟩, and any packages that depend on ⟨pkg⟩, are not installed at all. - Saying ``-ignore-package ⟨pkg⟩`` is the same as giving ``-hide-package`` + Saying ``-ignore-package ⟨pkg⟩`` is the same as giving :ghc-flag:`-hide-package` flags for ⟨pkg⟩ and all the packages that depend on ⟨pkg⟩. Sometimes we don't know ahead of time which packages will be installed that - depend on ⟨pkg⟩, which is when the ``-ignore-package`` flag can be + depend on ⟨pkg⟩, which is when the :ghc-flag:`-ignore-package` flag can be useful. -``-no-auto-link-packages`` - .. index:: - single: -no-auto-link-packages +.. ghc-flag:: -no-auto-link-packages By default, GHC will automatically link in the ``base`` and ``rts`` packages. This flag disables that behaviour. -``-this-package-key ⟨pkg-key⟩`` - .. index:: - single: -this-package-key +.. ghc-flag:: -this-package-key ⟨pkg-key⟩ Tells GHC the the module being compiled forms part of unit ID ⟨pkg-key⟩; internally, these keys are used to determine type equality and linker symbols. -``-library-name ⟨hash⟩`` - .. index:: - single: -library-name +.. ghc-flag:: -library-name ⟨hash⟩ Tells GHC that the source of a Backpack file and its textual dependencies is uniquely identified by ⟨hash⟩. Library names are @@ -239,36 +223,30 @@ The GHC command line options that control packages are: version hashes of all its textual dependencies. GHC will then use this library name to generate more unit IDs. -``-trust ⟨pkg⟩`` - .. index:: - single: -trust +.. ghc-flag:: -trust ⟨pkg⟩ This option causes the install package ⟨pkg⟩ to be both exposed and trusted by GHC. This command functions in the in a very similar way - to the ``-package`` command but in addition sets the selected + to the :ghc-flag:`-package` command but in addition sets the selected packaged to be trusted by GHC, regardless of the contents of the package database. (see :ref:`safe-haskell`). -``-distrust ⟨pkg⟩`` - .. index:: - single: -distrust +.. ghc-flag:: -distrust ⟨pkg⟩ This option causes the install package ⟨pkg⟩ to be both exposed and distrusted by GHC. This command functions in the in a very similar - way to the ``-package`` command but in addition sets the selected + way to the :ghc-flag:`-package` command but in addition sets the selected packaged to be distrusted by GHC, regardless of the contents of the package database. (see :ref:`safe-haskell`). -``-distrust-all`` - .. index:: - single: -distrust-all +.. ghc-flag:: -distrust-all Ignore the trusted flag on installed packages, and distrust them by default. If you use this flag and Safe Haskell then any packages you require to be trusted (including ``base``) need to be explicitly - trusted using ``-trust`` options. This option does not change the + trusted using :ghc-flag:`-trust` options. This option does not change the exposed/hidden status of a package, so it isn't equivalent to - applying ``-distrust`` to all packages on the system. (see + applying :ghc-flag:`-distrust` to all packages on the system. (see :ref:`safe-haskell`). .. _package-main: @@ -277,11 +255,11 @@ The ``main`` package -------------------- Every complete Haskell program must define ``main`` in module ``Main`` -in package ``main``. Omitting the ``-this-package-key`` flag compiles +in package ``main``. Omitting the :ghc-flag:`-this-package-key` flag compiles code for package ``main``. Failure to do so leads to a somewhat obscure link-time error of the form: -:: +.. code-block:: none /usr/bin/ld: Undefined symbols: _ZCMain_main_closure @@ -318,7 +296,7 @@ When incorporating packages from multiple sources, you may end up in a situation where multiple packages publish modules with the same name. Previously, the only way to distinguish between these modules was to use :ref:`package-qualified-imports`. However, since GHC 7.10, the -``-package`` flags (and their variants) have been extended to allow a +:ghc-flag:`-package` 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. @@ -360,9 +338,9 @@ Package Databases A package database is where the details about installed packages are stored. It is a directory, usually called ``package.conf.d``, that contains a file for each package, together with a binary cache of the -package data in the file ``package.cache``. Normally you won't need to +package data in the file :file:`package.cache`. 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 +management of package databases can be done through the :command:`ghc-pkg` tool (see :ref:`package-management`). GHC knows about two package databases in particular: @@ -379,7 +357,7 @@ GHC knows about two package databases in particular: When GHC starts up, it reads the contents of these two package databases, and builds up a list of the packages it knows about. You can -see GHC's package table by running GHC with the ``-v`` flag. +see GHC's package table by running GHC with the :ghc-flag:`-v` flag. Package databases may overlap, and they are arranged in a stack structure. Packages closer to the top of the stack will override @@ -389,51 +367,39 @@ global and the user's package databases, in that order. You can control GHC's package database stack using the following options: -``-package-db ⟨file⟩`` - .. index:: - single: -package-db +.. ghc-flag:: -package-db ⟨file⟩ Add the package database ⟨file⟩ on top of the current stack. Packages in additional databases read this way will override those in the initial stack and those in previously specified databases. -``-no-global-package-db`` - .. index:: - single: -no-global-package-db +.. ghc-flag:: -no-global-package-db Remove the global package database from the package database stack. -``-no-user-package-db`` - .. index:: - single: -no-user-package-db +.. ghc-flag:: -no-user-package-db Prevent loading of the user's local package database in the initial stack. -``-clear-package-db`` - .. index:: - single: -clear-package-db +.. ghc-flag:: -clear-package-db Reset the current package database stack. This option removes every previously specified package database (including those read from the - ``GHC_PACKAGE_PATH`` environment variable) from the package database + :envvar:`GHC_PACKAGE_PATH` environment variable) from the package database stack. -``-global-package-db`` - .. index:: - single: -global-package-db +.. ghc-flag:: -global-package-db Add the global package database on top of the current stack. This - option can be used after ``-no-global-package-db`` to specify the + option can be used after :ghc-flag:`-no-global-package-db` to specify the position in the stack where the global package database should be loaded. -``-user-package-db`` - .. index:: - single: -user-package-db +.. ghc-flag:: -user-package-db Add the user's package database on top of the current stack. This - option can be used after ``-no-user-package-db`` to specify the + option can be used after :ghc-flag:`-no-user-package-db` to specify the position in the stack where the user's package database should be loaded. @@ -442,32 +408,30 @@ options: The ``GHC_PACKAGE_PATH`` environment variable ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.. index:: - single: Environment variable; ``GHC_PACKAGE_PATH`` - single: 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 is used by GHC and -ghc-pkg, with earlier databases in the list overriding later ones. This -order was chosen to match the behaviour of the ``PATH`` environment -variable; think of it as a list of package databases that are searched -left-to-right for packages. - -If ``GHC_PACKAGE_PATH`` ends in a separator, then the default package -database stack (i.e. the user and global package databases, in that -order) is appended. For example, to augment the usual set of packages -with a database of your own, you could say (on Unix): +.. envvar:: GHC_PACKAGE_PATH -:: + The :envvar:`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 is used by GHC and + ghc-pkg, with earlier databases in the list overriding later ones. This + order was chosen to match the behaviour of the :envvar:`PATH` environment + variable; think of it as a list of package databases that are searched + left-to-right for packages. + + If :envvar:`GHC_PACKAGE_PATH` ends in a separator, then the default package + database stack (i.e. the user and global package databases, in that + order) is appended. For example, to augment the usual set of packages + with a database of your own, you could say (on Unix): - $ export GHC_PACKAGE_PATH=$HOME/.my-ghc-packages.conf: + .. code-block:: none -(use ``;`` instead of ``:`` on Windows). + $ export GHC_PACKAGE_PATH=$HOME/.my-ghc-packages.conf: -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. + (use ``;`` instead of ``:`` on Windows). + + To check whether your :envvar:`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-ids: @@ -479,7 +443,7 @@ ID"), which distinguishes 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``: -:: +.. code-block:: none $ ghc-pkg list -v using cache: /usr/lib/ghc-6.12.1/package.conf.d/package.cache @@ -497,7 +461,7 @@ 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: -:: +.. code-block:: none $ ghc-pkg field haskell98 depends depends: array-0.2.0.1-9cbf76a576b6ee9c1f880cf171a0928d @@ -522,7 +486,7 @@ in red (if possible) or otherwise 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: -:: +.. code-block:: none $ ghc-pkg list WARNING: there are broken packages. Run 'ghc-pkg check' for more details. @@ -536,7 +500,7 @@ 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: -:: +.. code-block:: none $ ghc-pkg check There are problems in package ghc-6.12.1: @@ -580,11 +544,11 @@ Package management (the ``ghc-pkg`` command) .. index:: single: packages; management -The ``ghc-pkg`` tool is for querying and modifying package databases. To +The :command:`ghc-pkg` tool is for querying and modifying package databases. To see what package 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`` environment variable (see :ref:`ghc-package-path`, -and using ``--package-db`` options on the ``ghc-pkg`` command line. +of databases that :command:`ghc-pkg` knows about can be modified using the +:envvar:`GHC_PACKAGE_PATH` environment variable (see :ref:`ghc-package-path`, +and using :ghc-flag:`-package-db` options on the :command:`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 @@ -597,7 +561,7 @@ 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`` is set, and its value +If the environment variable :envvar:`GHC_PACKAGE_PATH` 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 @@ -867,9 +831,9 @@ 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: +- Building a static library is done by using the :command:`ar` tool, like so: - :: + .. code-block:: sh ar cqs libHSfoo-1.0.a A.o B.o C.o ... @@ -883,9 +847,9 @@ extra indirection). ``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-objs`` then building the + package were compiled with :ghc-flag:`-split-objs` then building the ``HSfoo.o`` is worthwhile because it saves time when loading the - package into GHCi. Without ``-split-objs``, there is not much + package into GHCi. Without :ghc-flag:`-split-objs`, 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 @@ -895,7 +859,7 @@ extra indirection). ``--disable-library-for-ghci`` to disable it. To build one manually, the following GNU ``ld`` command can be used: - :: + .. code-block:: sh ld -r --whole-archive -o HSfoo.o libHSfoo.a @@ -911,10 +875,10 @@ extra indirection). versions of GHC and that therefore are most likely incompatible with respect to calling conventions, (2) it must be different from the static name otherwise we would not be able to control the linker as - precisely as necessary to make the ``-static``/``-dynamic`` flags - work, see :ref:`options-linker`. + precisely as necessary to make the :ghc-flag:`-static`\/:ghc-flag:`-dynamic` + flags work, see :ref:`options-linker`. - :: + .. code-block:: sh ghc -shared libHSfoo-1.0-ghcGHCVersion.so A.o B.o C.o @@ -957,7 +921,7 @@ functions ``parseInstalledPackageInfo`` and ``showInstalledPackageInfo`` read and write this syntax respectively. Here's an example of the ``InstalledPackageInfo`` for the ``unix`` package: -:: +.. code-block:: none $ ghc-pkg describe unix name: unix @@ -1320,7 +1284,7 @@ They are intended to be managed by build/package tools, to enable ``ghc`` and The file contains package IDs and optionally package databases, one directive per line: -:: +.. code-block:: none clear-package-db global-package-db @@ -1334,7 +1298,7 @@ per line: If such a package environment is found, it is equivalent to passing these command line arguments to ``ghc``: -:: +.. code-block:: none -hide-all-packages -clear-package-db @@ -1346,9 +1310,9 @@ command line arguments to ``ghc``: ... -package-id id_n -Note the implicit ``-hide-all-packages`` and the fact that it is -``-package-id``, not ``-package``. This is because the environment specifies -precisely which packages should be visible. +Note the implicit :ghc-flag:`-hide-all-packages` and the fact that it is +:ghc-flag:`-package-id`, not :ghc-flag:`-package`. This is because the +environment specifies precisely which packages should be visible. Note that for the ``package-db`` directive, if a relative path is given it must be relative to the location of the package environment file. diff --git a/docs/users_guide/phases.rst b/docs/users_guide/phases.rst index cc4244eff3..0428956276 100644 --- a/docs/users_guide/phases.rst +++ b/docs/users_guide/phases.rst @@ -17,84 +17,58 @@ 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⟩`` - .. index:: - single: -pgmL +.. ghc-flag:: -pgmL ⟨cmd⟩ Use ⟨cmd⟩ as the literate pre-processor. -``-pgmP ⟨cmd⟩`` - .. index:: - single: -pgmP +.. ghc-flag:: -pgmP ⟨cmd⟩ Use ⟨cmd⟩ as the C pre-processor (with ``-cpp`` only). -``-pgmc ⟨cmd⟩`` - .. index:: - single: -pgmc +.. ghc-flag:: -pgmc ⟨cmd⟩ Use ⟨cmd⟩ as the C compiler. -``-pgmlo ⟨cmd⟩`` - .. index:: - single: -pgmlo +.. ghc-flag:: -pgmlo ⟨cmd⟩ Use ⟨cmd⟩ as the LLVM optimiser. -``-pgmlc ⟨cmd⟩`` - .. index:: - single: -pgmlc +.. ghc-flag:: -pgmlc ⟨cmd⟩ Use ⟨cmd⟩ as the LLVM compiler. -``-pgms ⟨cmd⟩`` - .. index:: - single: -pgms +.. ghc-flag:: -pgms ⟨cmd⟩ Use ⟨cmd⟩ as the splitter. -``-pgma ⟨cmd⟩`` - .. index:: - single: -pgma +.. ghc-flag:: -pgma ⟨cmd⟩ Use ⟨cmd⟩ as the assembler. -``-pgml ⟨cmd⟩`` - .. index:: - single: -pgml +.. ghc-flag:: -pgml ⟨cmd⟩ Use ⟨cmd⟩ as the linker. -``-pgmdll ⟨cmd⟩`` - .. index:: - single: -pgmdll +.. ghc-flag:: -pgmdll ⟨cmd⟩ Use ⟨cmd⟩ as the DLL generator. -``-pgmF ⟨cmd⟩`` - .. index:: - single: -pgmF +.. ghc-flag:: -pgmF ⟨cmd⟩ Use ⟨cmd⟩ as the pre-processor (with ``-F`` only). -``-pgmwindres ⟨cmd⟩`` - .. index:: - single: -pgmwindres +.. ghc-flag:: -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 :ref:`options-linker`. -``-pgmlibtool ⟨cmd⟩`` - .. index:: - single: -pgmlibtool +.. ghc-flag:: -pgmlibtool ⟨cmd⟩ Use ⟨cmd⟩ as the libtool command (when using ``-staticlib`` only). -``-pgmi ⟨cmd⟩`` - .. index:: - single: -pgmi +.. ghc-flag:: -pgmi ⟨cmd⟩ Use ⟨cmd⟩ as the external interpreter command (see: :ref:`external-interpreter`). Default: ``ghc-iserv-prof`` if @@ -112,71 +86,49 @@ Forcing options to a particular phase Options can be forced through to a particular compilation phase, using the following flags: -``-optL ⟨option⟩`` - .. index:: - single: -optL +.. ghc-flag:: -optL ⟨option⟩ Pass ⟨option⟩ to the literate pre-processor -``-optP ⟨option⟩`` - .. index:: - single: -optP +.. ghc-flag:: -optP ⟨option⟩ Pass ⟨option⟩ to CPP (makes sense only if ``-cpp`` is also on). -``-optF ⟨option⟩`` - .. index:: - single: -optF +.. ghc-flag:: -optF ⟨option⟩ Pass ⟨option⟩ to the custom pre-processor (see :ref:`pre-processor`). -``-optc ⟨option⟩`` - .. index:: - single: -optc +.. ghc-flag:: -optc ⟨option⟩ Pass ⟨option⟩ to the C compiler. -``-optlo ⟨option⟩`` - .. index:: - single: -optlo +.. ghc-flag:: -optlo ⟨option⟩ Pass ⟨option⟩ to the LLVM optimiser. -``-optlc ⟨option⟩`` - .. index:: - single: -optlc +.. ghc-flag:: -optlc ⟨option⟩ Pass ⟨option⟩ to the LLVM compiler. -``-opta ⟨option⟩`` - .. index:: - single: -opta +.. ghc-flag:: -opta ⟨option⟩ Pass ⟨option⟩ to the assembler. -``-optl ⟨option⟩`` - .. index:: - single: -optl +.. ghc-flag:: -optl ⟨option⟩ Pass ⟨option⟩ to the linker. -``-optdll ⟨option⟩`` - .. index:: - single: -optdll +.. ghc-flag:: -optdll ⟨option⟩ Pass ⟨option⟩ to the DLL generator. -``-optwindres ⟨option⟩`` - .. index:: - single: -optwindres +.. ghc-flag:: -optwindres ⟨option⟩ Pass ⟨option⟩ to ``windres`` when embedding manifests on Windows. See ``-fno-embed-manifest`` in :ref:`options-linker`. -``-opti ⟨option⟩`` - .. index:: - single: -opti +.. ghc-flag:: -opti ⟨option⟩ Pass ⟨option⟩ to the interpreter sub-process (see :ref:`external-interpreter`). A common use for this is to pass @@ -202,32 +154,24 @@ Options affecting the C pre-processor single: C pre-processor options single: cpp, pre-processing with -``-cpp`` - .. index:: - single: -cpp +.. ghc-flag:: -cpp - The C pre-processor ``cpp`` is run over your Haskell code only if + The C pre-processor :command:`cpp` is run over your Haskell code only if the ``-cpp`` option -cpp option is given. Unless you are building a large system with significant doses of conditional compilation, you really shouldn't need it. -``-D ⟨symbol⟩[=⟨value⟩]`` - .. index:: - single: -D +.. ghc-flag:: -D ⟨symbol⟩[=⟨value⟩] Define macro ⟨symbol⟩ in the usual way. NB: does *not* affect ``-D`` macros passed to the C compiler when compiling via C! For those, use the ``-optc-Dfoo`` hack… (see :ref:`forcing-options-through`). -``-U ⟨symbol⟩`` - .. index:: - single: -U +.. ghc-flag:: -U ⟨symbol⟩ Undefine macro ⟨symbol⟩ in the usual way. -``-I ⟨dir⟩`` - .. index:: - single: -I +.. ghc-flag:: -I ⟨dir⟩ Specify a directory in which to look for ``#include`` files, in the usual C way. @@ -238,7 +182,7 @@ 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: -:: +.. code-block:: sh $ ghc -E -optP-dM -cpp foo.hs $ cat foo.hspp @@ -311,7 +255,7 @@ defined by your local GHC installation, the following trick is useful: is required, the presence of the ``MIN_VERSION_GLASGOW_HASKELL`` macro needs to be ensured before it is called, e.g.: - :: + .. code-block: c #ifdef MIN_VERSION_GLASGOW_HASKELL #if MIN_VERSION_GLASGOW_HASKELL(7,10,2,0) @@ -384,16 +328,14 @@ CPP and string gaps single: -cpp vs string gaps single: string gaps vs -cpp. -A small word of warning: ``-cpp`` is not friendly to "string gaps". -In other words, strings such as the following: - -:: +A small word of warning: :ghc-flag:`-cpp` is not friendly to "string gaps". +In other words, strings such as the following: :: strmod = "\ \ p \ \ " -don't work with ``-cpp``; ``/usr/bin/cpp`` elides the backslash-newline +don't work with :ghc-flag:`-cpp`; :command:`/usr/bin/cpp` elides the backslash-newline pairs. However, it appears that if you add a space at the end of the line, then @@ -409,9 +351,7 @@ Options affecting a Haskell pre-processor single: pre-processing: custom single: pre-processor options -``-F`` - .. index:: - single: -F +.. ghc-flag:: -F A custom pre-processor is run over your Haskell source file only if the ``-F`` option is given. @@ -428,7 +368,7 @@ Options affecting a Haskell pre-processor stripped away and (possibly) the C pre-processor has washed the Haskell input. - Use ``-pgmF ⟨cmd⟩`` to select the program to use as the preprocessor. + Use :ghc-flag:`-pgmF` 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 @@ -436,14 +376,14 @@ Options affecting a Haskell pre-processor write its output to. Additional arguments to the pre-processor can be passed in using the - ``-optF`` option. These are fed to ⟨cmd⟩ on the command line after + :ghc-flag:`-optF` 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 ``convert.sh`` containing the lines: - :: + .. code-block:: sh #!/bin/sh ( echo "{-# LINE 1 \"$2\" #-}" ; iconv -f l1 -t utf-8 $2 ) > $3 @@ -460,67 +400,55 @@ Options affecting a Haskell pre-processor Options affecting code generation --------------------------------- -``-fasm`` - .. index:: - single: -fasm +.. ghc-flag:: -fasm Use GHC's :ref:`native code generator <native-code-gen>` rather than compiling via LLVM. ``-fasm`` is the default. -``-fllvm`` - .. index:: - single: -fllvm +.. ghc-flag:: -fllvm Compile via :ref:`LLVM <llvm-code-gen>` instead of using the native code generator. This will generally 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``. + via LLVM requires LLVM's :command:`opt` and :command:`llc` executables to be + in :envvar:`PATH`. -``-fno-code`` - .. index:: - single: -fno-code +.. ghc-flag:: -fno-code Omit code generation (and all later phases) altogether. This is useful if you're only interested in type checking code. -``-fwrite-interface`` - .. index:: - single: -fwrite-interface +.. ghc-flag:: -fwrite-interface Always write interface files. GHC will normally write interface - files automatically, but this flag is useful with ``-fno-code``, + files automatically, but this flag is useful with :ghc-flag:`-fno-code`, 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`` - .. index:: - single: -fobject-code +.. ghc-flag:: -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`` - .. index:: - single: -fbyte-code +.. ghc-flag:: -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``. + reversing the effect of :ghc-flag:`-fobject-code`. -``-fPIC`` - .. index:: - single: -fPIC +.. ghc-flag:: -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. -``-dynamic`` +.. ghc-flag:: -dynamic + When generating code, assume that entities imported from a different package will reside in a different shared library or binary. @@ -540,12 +468,10 @@ 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⟩`` - .. index:: - single: -l +.. ghc-flag:: -l ⟨lib⟩ Link in the ⟨lib⟩ library. On Unix systems, this will be in a file - called ``liblib.a`` or ``liblib.so`` which resides somewhere on the + called :file:`lib{lib}.a` or :file:`lib{lib}.so` which resides somewhere on the library directories path. Because of the sad state of most UNIX linkers, the order of such @@ -563,64 +489,50 @@ for example). any other ``main()``\ s from external libraries, just add the option ``-lHSrts`` before any other libraries on the command line. -``-c`` - .. index:: - single: -c +.. ghc-flag:: -c - Omits the link step. This option can be used with ``--make`` to + Omits the link step. This option can be used with :ghc-flag:`--make` to avoid the automatic linking that takes place if the program contains a ``Main`` module. -``-package ⟨name⟩`` - .. index:: - single: -package +.. ghc-flag:: -package ⟨name⟩ - If you are using a Haskell “package” (see :ref:`packages`), don't + If you are using a Haskell "package" (see :ref:`packages`), 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⟩`` - .. index:: - single: -framework +.. ghc-flag:: -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, + way of packaging shared libraries. To link to Apple's "Carbon" API, for example, you'd use ``-framework Carbon``. -``-staticlib`` - .. index:: - single: -staticlib +.. ghc-flag:: -staticlib On Darwin/OS X/iOS only, link all passed files into a static library suitable for linking into an iOS (when using a cross-compiler) or - Mac Xcode project. To control the name, use the ``-o`` ⟨name⟩ option + Mac Xcode project. To control the name, use the :ghc-flag:`-o` ⟨name⟩ option as usual. The default name is ``liba.a``. This should nearly always be passed when compiling for iOS with a cross-compiler. -``-L ⟨dir⟩`` - .. index:: - single: -L +.. ghc-flag:: -L ⟨dir⟩ Where to find user-supplied libraries… Prepend the directory ⟨dir⟩ to the library directories path. -``-framework-path ⟨dir⟩`` - .. index:: - single: -framework-path +.. ghc-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-objs`` - .. index:: - single: -split-objs +.. ghc-flag:: -split-objs Tell the linker to split the single object file that would normally be generated into multiple object files, one per top-level Haskell @@ -632,9 +544,7 @@ for example). the library itself (the ``.a`` file) can be a factor of 2 to 2.5 larger. We use this feature for building GHC's libraries. -``-split-sections`` - .. index:: - single: -split-sections +.. ghc-flag:: -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 @@ -643,19 +553,15 @@ for example). When linking, the linker can automatically remove all unreferenced sections and thus produce smaller executables. The effect is similar to - ``-split-objs``, but somewhat more efficient - the generated library files - are about 30% smaller than with ``-split-objs``. + :ghc-flag:`-split-objs`, but somewhat more efficient - the generated library + files are about 30% smaller than with :ghc-flag:`-split-objs`. -``-static`` - .. index:: - single: -static +.. ghc-flag:: -static Tell the linker to avoid shared Haskell libraries, if possible. This is the default. -``-dynamic`` - .. index:: - single: -dynamic +.. ghc-flag:: -dynamic This flag tells GHC to link against shared Haskell libraries. This flag only affects the selection of dependent libraries, not the form @@ -665,39 +571,35 @@ for example). Note that this option also has an effect on code generation (see above). -``-shared`` - .. index:: - single: -shared +.. ghc-flag:: -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``/``-static`` control whether the resulting + The flags :ghc-flag:`-dynamic` and :ghc-flag:`-static` control whether the resulting shared object links statically or dynamically to Haskell package - libraries given as ``-package`` option. Non-Haskell libraries are + libraries given as :ghc-flag:`-package` option. Non-Haskell libraries are linked as gcc would regularly 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``, see :ref:`options-codegen` + :ghc-flag:`-fPIC`, see :ref:`options-codegen` When creating shared objects for Haskell packages, the shared object must be named properly, so that GHC recognizes the shared object when linked against this package. See shared object name mangling. -``-dynload`` - .. index:: - single: -dynload +.. ghc-flag:: -dynload This flag selects one of a number of modes for finding shared libraries at runtime. See :ref:`finding-shared-libs` for a description of each mode. -``-main-is ⟨thing⟩`` +.. ghc-flag:: -main-is ⟨thing⟩ + .. index:: - single: -main-is single: specifying your own main function The normal rule in Haskell is that your program must supply a @@ -724,11 +626,11 @@ for example). 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`` flag. + :ghc-flag:`-fforce-recomp` flag. + +.. ghc-flag:: -no-hs-main -``-no-hs-main`` .. index:: - single: -no-hs-main single: linking Haskell libraries with foreign code In the event you want to include ghc-compiled code as part of @@ -740,32 +642,28 @@ for example). 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`` on to see what options the + though, just try linking once with :ghc-flag:`-v` 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`` mode when there is no Haskell + to do the link step in :ghc-flag:`--make` mode when there is no Haskell ``Main`` module present (normally the compiler will not attempt linking when there is no ``Main``). - The flags ``-rtsopts`` and ``-with-rtsopts`` have no effect when - used with ``-no-hs-main``, because they are implemented by changing + The flags :ghc-flag:`-rtsopts` and :ghc-flag:`-with-rtsopts` have no effect when + used with :ghc-flag:`-no-hs-main`, because they are implemented by changing the definition of ``main`` that GHC generates. See - :ref:`using-own-main` for how to get the effect of ``-rtsopts`` and - ``-with-rtsopts`` when using your own ``main``. + :ref:`using-own-main` for how to get the effect of :ghc-flag:`-rtsopts` and + :ghc-flag:`-with-rtsopts` when using your own ``main``. -``-debug`` - .. index:: - single: -debug +.. ghc-flag:: -debug Link the program with a debugging version of the runtime system. The debugging runtime 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`` - .. index:: - single: -threaded +.. ghc-flag:: -threaded Link the program with the "threaded" version of the runtime system. The threaded runtime system is so-called because it manages multiple @@ -778,7 +676,7 @@ for example). The threaded runtime system provides the following benefits: - - It enables the ``-N``\ ``-Nx``\ RTS option RTS option to be used, + - It enables the :rts-flag:`-N` RTS option to be used, which allows threads to run in parallelparallelism on a multiprocessormultiprocessorSMP or multicoremulticore machine. See :ref:`using-smp`. @@ -790,25 +688,21 @@ for example). called from multiple OS threads simultaneously. See :ref:`ffi-threads`. -``-eventlog`` - .. index:: - single: -eventlog +.. ghc-flag:: -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 ``program.eventlog``, + (such as thread start/stop) to a binary file :file:`{program}.eventlog`, which can then be interpreted later by various tools. See :ref:`rts-eventlog` for more information. - ``-eventlog`` can be used with ``-threaded``. It is implied by - ``-debug``. + :ghc-flag:`-eventlog` can be used with :ghc-flag:`-threaded`. It is implied by + :ghc-flag:`-debug`. -``-rtsopts`` - .. index:: - single: -rtsopts +.. ghc-flag:: -rtsopts This option affects the processing of RTS control options given - either on the command line or via the ``GHCRTS`` environment + either on the command line or via the :envvar:`GHCRTS` environment variable. There are three possibilities: ``-rtsopts=none`` @@ -832,14 +726,12 @@ for example). 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 ``-rtsops=some``. + 7.0.1 and later default to ``-rtsopts=some``. - Note that ``-rtsopts`` has no effect when used with ``-no-hs-main``; + Note that ``-rtsopts`` has no effect when used with :ghc-flag:`-no-hs-main`; see :ref:`using-own-main` for details. -``-with-rtsopts`` - .. index:: - single: -with-rtsopts +.. ghc-flag:: -with-rtsopts This option allows you to set the default RTS options at link-time. For example, ``-with-rtsopts="-H128m"`` sets the default heap size @@ -852,26 +744,22 @@ for example). Note that ``-with-rtsopts`` has no effect when used with ``-no-hs-main``; see :ref:`using-own-main` for details. -``-no-rtsopts-suggestions`` - .. index:: - single: -no-rtsopts-suggestions +.. ghc-flag:: -no-rtsopts-suggestions - This option disables RTS suggestions about linking with ``-rtsopts`` + This option disables RTS suggestions about linking with :ghc-flag:`-rtsopts` 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`` - .. index:: - single: -fno-gen-manifest +.. ghc-flag:: -fno-gen-manifest On Windows, GHC normally generates a manifestmanifest file when linking a binary. The manifest is placed in the file - ``prog.exe.manifest`` where ⟨prog.exe⟩ is the name of the + :file:`{prog}.exe.manifest`` where ⟨prog.exe⟩ is the name of the executable. The manifest file currently serves just one purpose: it - disables the "installer detection"installer detectionin Windows + 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, @@ -893,45 +781,41 @@ 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`` also implies ``-fno-embed-manifest``, see + :ghc-flag:`-fno-gen-manifest` also implies :ghc-flag:`-fno-embed-manifest`, see below. -``-fno-embed-manifest`` +.. ghc-flag:: -fno-embed-manifest + .. index:: - single: -fno-embed-manifest single: windres 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`` flag. A GHC installation comes with its own + :command:`windres`; to see exactly what GHC does to embed the + manifest, use the :ghc-flag:`-v` flag. A GHC installation comes with its own copy of ``windres`` for this reason. - See also ``-pgmwindres`` (:ref:`replacing-phases`) and - ``-optwindres`` (:ref:`forcing-options-through`). + See also :ghc-flag:`-pgmwindres` (:ref:`replacing-phases`) and + :ghc-flag:`-optwindres` (:ref:`forcing-options-through`). -``-fno-shared-implib`` - .. index:: - single: -fno-shared-implib +.. ghc-flag:: -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`` mode. However, sometimes you don't want to + compiling in :ghc-flag:`-shared` 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`` flag to disable the creation of the import + :ghc-flag:`-fno-shared-implib` flag to disable the creation of the import library entirely. -``-dylib-install-name path`` - .. index:: - single: -dylib-install-name +.. ghc-flag:: -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 @@ -942,9 +826,7 @@ for example). file path. (It passes ``-install_name`` to Apple's linker.) Ignored on other platforms. -``-rdynamic`` - .. index:: - single: -rdynamic +.. ghc-flag:: -rdynamic This instructs the linker to add all symbols, not only used ones, to the dynamic symbol table. Currently Linux and Windows/MinGW32 only. diff --git a/docs/users_guide/profiling.rst b/docs/users_guide/profiling.rst index 34525d12b8..a163173e37 100644 --- a/docs/users_guide/profiling.rst +++ b/docs/users_guide/profiling.rst @@ -14,19 +14,19 @@ so much memory?". Profiling a program is a three-step process: -1. Re-compile your program for profiling with the ``-prof`` option, and +1. Re-compile your program for profiling with the :ghc-flag:`-prof` option, and probably one of the options for adding automatic annotations: - ``-fprof-auto`` is the most common [1]_. ``-fprof-auto`` + :ghc-flag:`-fprof-auto` is the most common [1]_. - If you are using external packages with ``cabal``, you may need to + If you are using external packages with :command:`cabal`, you may need to reinstall these packages 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``, which generates a file - named ``⟨prog⟩.prof`` where ⟨prog⟩ is the name of your program (without the - ``.exe`` extension, if you are on Windows). + generated by running the program with ``+RTS -p`` (see :rts-flag:`-p`), which + generates a file named :file:`{prog}.prof` 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 @@ -50,27 +50,25 @@ 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: - -:: +Let's take a look at an example: :: main = print (fib 30) fib n = if n < 2 then 1 else fib (n-1) + fib (n-2) Compile and run this program as follows: -:: +.. code-block:: none $ ghc -prof -fprof-auto -rtsopts Main.hs $ ./Main +RTS -p 121393 $ -When a GHC-compiled program is run with the ``-p`` RTS option, it -generates a file called ``prog.prof``. In this case, the file will -contain something like this: +When a GHC-compiled program is run with the :rts-flag:`-p` RTS option, it +generates a file called :file:`prog.prof`. In this case, the file will contain +something like this: -:: +.. code-block:: none Wed Oct 12 16:14 2011 Time and Allocation Profiling Report (Final) @@ -119,9 +117,7 @@ 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: - -:: +the example slightly: :: main = print (f 30 + g 30) where @@ -133,7 +129,7 @@ the example slightly: Compile and run this program as before, and take a look at the new profiling results: -:: +.. code-block:: none COST CENTRE MODULE no. entries %time %alloc %time %alloc @@ -172,7 +168,7 @@ The actual meaning of the various columns in the output is: overheads) of the program made by this call and all of its sub-calls. -In addition you can use the ``-P`` RTS option ``-P`` to get the +In addition you can use the :rts-flag:`-P` RTS option to get the following additional information: ``ticks`` @@ -203,9 +199,7 @@ 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 is - -:: +The syntax of a cost centre annotation is :: {-# SCC "name" #-} <expression> @@ -214,15 +208,11 @@ your cost centre as it appears in the profiling output, and ``<expression>`` is any Haskell expression. An ``SCC`` annotation extends as far to the right as possible when parsing. (SCC stands for "Set Cost Centre"). The double quotes can be omitted if ``name`` is a -Haskell identifier, for example: - -:: +Haskell identifier, for example: :: {-# SCC my_function #-} <expression> -Here is an example of a program with a couple of SCCs: - -:: +Here is an example of a program with a couple of SCCs: :: main :: IO () main = do let xs = [1..1000000] @@ -234,7 +224,7 @@ Here is an example of a program with a couple of SCCs: which gives this profile when run: -:: +.. code-block:: none COST CENTRE MODULE no. entries %time %alloc %time %alloc @@ -283,11 +273,11 @@ 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 ``M.CAF``, where ``M`` is the name of the module. It is also possible to give each CAF a different stack, using the option -``-fprof-cafs``. This is especially useful when -compiling with ``-ffull-laziness`` (as is default with ``-O`` and -higher), as constants in function bodies will be lifted to the top-level +:ghc-flag:`-fprof-cafs`. This is especially useful when +compiling with :ghc-flag:`-ffull-laziness` (as is default with :ghc-flag:`-O` +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``) in order to determine what these CAFs correspond to. +(:ghc-flag:`-ddump-simpl`) in order to determine what these CAFs correspond to. .. index:: single: -fprof-cafs @@ -301,41 +291,35 @@ Compiler options for profiling single: profiling; options single: options; for profiling -``-prof`` - .. index:: - single: -prof +.. ghc-flag:: -prof To make use of the profiling system *all* modules must be compiled - and linked with the ``-prof`` option. Any ``SCC`` annotations you've + and linked with the :ghc-flag:`-prof` option. Any ``SCC`` annotations you've put in your source will spring to life. - Without a ``-prof`` option, your ``SCC``\ s are ignored; so you can + Without a :ghc-flag:`-prof` option, your ``SCC``\ s 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``. These do not have to be used consistently +*in addition to* :ghc-flag:`-prof`. These do not have to be used consistently for all modules in a program. -``-fprof-auto`` - .. index:: - single: -fprof-auto +.. ghc-flag:: -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-flag:: -fprof-auto-top + .. index:: - single: -fprof-auto-top single: cost centres; automatically inserting 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`` - .. index:: - single: -fprof-auto-top +.. ghc-flag:: -fprof-auto-exported .. index:: single: cost centres; automatically inserting @@ -344,38 +328,34 @@ for all modules in a program. functions not marked INLINE. If you want a cost centre on an INLINE function, you have to add it manually. -``-fprof-auto-calls`` +.. ghc-flag:: -fprof-auto-calls + .. index:: single: -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 ``traceStack`` in the - module ``Debug.Trace``, or the ``-xc`` RTS flag + module ``Debug.Trace``, or the :rts-flag:`-xc` RTS flag (:ref:`rts-options-debugging`) for more details. -``-fprof-cafs`` - .. index:: - single: -fprof-cafs +.. ghc-flag:: -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 + "big" CAF cost-centre. With this option, all CAFs get their own cost-centre. An “if all else fails” option… -``-fno-prof-auto`` - .. index:: - single: -no-fprof-auto +.. ghc-flag:: -fno-prof-auto - Disables any previous ``-fprof-auto``, ``-fprof-auto-top``, or - ``-fprof-auto-exported`` options. + Disables any previous :ghc-flag:`-fprof-auto`, :ghc-flag:`-fprof-auto-top`, or + :ghc-flag:`-fprof-auto-exported` options. -``-fno-prof-cafs`` - .. index:: - single: -fno-prof-cafs +.. ghc-flag:: -fno-prof-cafs - Disables any previous ``-fprof-cafs`` option. + Disables any previous :ghc-flag:`-fprof-cafs` option. + +.. ghc-flag:: -fno-prof-count-entries -``-fno-prof-count-entries`` .. index:: single: -fno-prof-count-entries @@ -397,33 +377,29 @@ 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`` +.. rts-flag:: -p + -P + -pa + .. index:: - single: -p; RTS option - single: -P; RTS option - single: -pa; RTS option single: time profile - The ``-p`` option produces a standard *time profile* report. It is - written into the file ``program.prof``. + The :rts-flag:`-p` option produces a standard *time profile* report. It is + written into the file :file:`program.prof`. - The ``-P`` option produces a more detailed report containing the + The :rts-flag:`-P` option produces a more detailed report containing the actual time and allocation data as well. (Not used much.) - The ``-pa`` option produces the most detailed report containing all + The :rts-flag:`-pa` option produces the most detailed report containing all cost centres in addition to the actual time and allocation data. -``-Vsecs`` - .. index:: - single: -V; RTS option +.. rts-flag:: -V <secs> 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. -``-xc`` - .. index:: - single: -xc; RTS option +.. rts-flag:: -xc This option causes the runtime to print out the current cost-centre stack whenever an exception is raised. This can be particularly @@ -448,7 +424,7 @@ To generate a heap profile from your program: 1. Compile the program for profiling (:ref:`prof-compiler-options`). 2. Run it with one of the heap profiling options described below (eg. - ``-h`` for a basic producer profile). This generates the file + :rts-flag:`-h` for a basic producer profile). This generates the file ``prog.hp``. 3. Run ``hp2ps`` to produce a Postscript file, ``prog.ps``. The @@ -476,46 +452,35 @@ 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: -``-hc`` - .. index:: - single: -hc; RTS option +.. rts-flag:: -hc + -h - (can be shortened to ``-h``). Breaks down the graph by the + (can be shortened to :rts-flag:`-h`). Breaks down the graph by the cost-centre stack which produced the data. -``-hm`` - .. index:: - single: -hm; RTS option +.. rts-flag:: -hm Break down the live heap by the module containing the code which produced the data. -``-hd`` - .. index:: - single: -hd; RTS option +.. rts-flag:: -hd 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`` - .. index:: - single: -hy; RTS option +.. rts-flag:: -hy 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`` - .. index:: - single: -hr; RTS option +.. rts-flag:: -hr Break down the graph by retainer set. Retainer profiling is described in more detail below (:ref:`retainer-prof`). -``-hb`` - .. index:: - single: -hb; RTS option +.. rts-flag:: -hb Break down the graph by biography. Biographical profiling is described in more detail below (:ref:`biography-prof`). @@ -526,50 +491,48 @@ 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⟩`` - .. index:: - single: -hc; RTS option +.. comment + + The flags below are marked with ``:noindex:`` to avoid duplicate + ID warnings from Sphinx. + +.. rts-flag:: -hc <name> + :noindex: Restrict the profile to closures produced by cost-centre stacks with one of the specified cost centres at the top. -``-hC ⟨name⟩`` - .. index:: - single: -hC; RTS option +.. rts-flag:: -hC <name> + :noindex: Restrict the profile to closures produced by cost-centre stacks with one of the specified cost centres anywhere in the stack. -``-hm ⟨module⟩`` - .. index:: - single: -hm; RTS option +.. rts-flag:: -hm <module> + :noindex: Restrict the profile to closures produced by the specified modules. -``-hd ⟨desc⟩`` - .. index:: - single: -hd; RTS option +.. rts-flag:: -hd <desc> + :noindex: Restrict the profile to closures with the specified description strings. -``-hy ⟨type⟩`` - .. index:: - single: -hy; RTS option +.. rts-flag:: -hy <type> + :noindex: Restrict the profile to closures with the specified types. -``-hr ⟨cc⟩`` - .. index:: - single: -hr; RTS option +.. rts-flag:: -hr <cc> + :noindex: Restrict the profile to closures with retainer sets containing cost-centre stacks with one of the specified cost centres at the top. -``-hb ⟨bio⟩`` - .. index:: - single: -hb; RTS option +.. rts-flag:: -hb <bio> + :noindex: Restrict the profile to closures with one of the specified biographies, where ⟨bio⟩ is one of ``lag``, ``drag``, ``void``, or @@ -578,20 +541,18 @@ follows: For example, the following options will generate a retainer profile restricted to ``Branch`` and ``Leaf`` constructors: -:: +.. code-block:: none prog +RTS -hr -hdBranch,Leaf -There can only be one "break-down" option (eg. ``-hr`` in the example +There can only be one "break-down" option (eg. :rts-flag:`-hr` 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`` and ``-hb`` options. +doesn't currently support mixing the :rts-flag:`-hr` and :rts-flag:`-hb` options. There are three more options which relate to heap profiling: -``-isecs`` - .. index:: - single: -i +.. rts-flag:: -i <secs> Set the profiling (sampling) interval to ⟨secs⟩ seconds (the default is 0.1 second). Fractions are allowed: for example ``-i0.2`` will @@ -599,25 +560,21 @@ There are three more options which relate to heap profiling: profiles are always sampled with the frequency of the RTS clock. See :ref:`prof-time-options` for changing that. -``-xt`` - .. index:: - single: -xt; RTS option +.. rts-flag:: -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`` is a good way to see + This includes the main thread, so using :rts-flag:`-xt` 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” respectively when displaying the profile by closure description or type description. -``-Lnum`` - .. index:: - single: -L; RTS option +.. rts-flag:: -L <num> Sets the maximum length of a cost-centre stack name in a heap profile. Defaults to 25. @@ -636,9 +593,9 @@ retainer: 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 recursively following pointers starting from -object B, but not meeting any other retainer objects on the way. Each +An object ``B`` retains object ``A`` if (i) ``B`` is a retainer object and (ii) +object ``A`` can be reached by recursively 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. @@ -654,9 +611,10 @@ 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`` RTS option: +altered with the :rts-flag:`-R` RTS option: + +.. rts-flag:: -R <size> -``-R ⟨size⟩`` Restrict the number of elements in a retainer set to ⟨size⟩ (default 8). @@ -674,19 +632,19 @@ 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: +retainer profiling - for example ``A`` retains ``B``, ``B`` retains ``C``, and +``C`` retains a large structure. There might be a large number of ``B``\s 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``: -:: +.. code-block:: none prog +RTS -hr -hcB -This trick isn't foolproof, because there might be other B closures in +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. @@ -720,14 +678,14 @@ 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: -:: +.. code-block:: none prog +RTS -hc -hbdrag,void 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): -:: +.. code-block:: none prog +RTS -hr -hccc... @@ -757,16 +715,16 @@ reasons for this: 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`` option) we + data. This is because by default (see the RTS :rts-flag:`-F` 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 ``+RTS -c`` + data into. When using compacting collection (see the :rts-flag:`-c` option), this is reduced to 2L, and can further be reduced by - tweaking the ``-F`` option. Also add the size of the allocation area + tweaking the :rts-flag:`-F` option. Also add the size of the allocation area (currently a fixed 512Kb). - The stack isn't counted in the heap profile by default. See the - ``+RTS -xt`` option. + RTS :rts-flag:`-xt` 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 @@ -785,23 +743,26 @@ reasons for this: Usage: -:: +.. code-block:: none hp2ps [flags] [<file>[.hp]] -The program ``hp2ps`` program converts a heap profile as produced +The program :command:`hp2ps` program converts a heap profile as 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``. +heap profile. By convention, the file to be processed by :command:`hp2ps` has a +``.hp`` extension. The PostScript output is written to :file:`{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 +:command:`hp2ps` is distributed in :file:`ghc/utils/hp2ps` in a GHC source distribution. It was originally developed by Dave Wakeling as part of the HBC/LML heap profiler. The flags are: -``-d`` +.. program:: hp2ps + +.. option:: -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 @@ -809,14 +770,16 @@ The flags are: series of values with the largest standard deviations) to be stacked on top of smoother ones. -``-b`` +.. option:: -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]`` +.. option:: -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 @@ -829,19 +792,22 @@ The flags are: (EPS) convention, and it can be included in a LaTeX document using Rokicki's dvi-to-PostScript converter ``dvips``. -``-g`` +.. option:: -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`` +.. option:: -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>`` +.. option:: -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). @@ -850,7 +816,8 @@ The flags are: 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`` +.. option:: -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 @@ -860,10 +827,12 @@ The flags are: previous run of ``hp2ps`` on ``file``. These are extracted from ``file@.aux``. -``-s`` +.. option:: -s + Use a small box for the title. -``-t<float>`` +.. option:: -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%). @@ -871,13 +840,16 @@ The flags are: ``-t0`` requests no trace elements to be removed from the profile, ensuring that all the data will be displayed. -``-c`` +.. option:: -c + Generate colour output. -``-y`` +.. option:: -y + Ignore marks. -``-?`` +.. option:: -? + Print out usage information. .. _manipulating-hp: @@ -891,7 +863,7 @@ The ``FOO.hp`` file produced when you ask for the heap profile of a program ``FOO`` is a text file with a particularly simple structure. Here's a representative example, with much of the actual data omitted: -:: +.. code-block:: none JOB "FOO -hC" DATE "Thu Dec 26 18:17 2002" @@ -928,13 +900,13 @@ Viewing the heap profile of a running program ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The ``.hp`` file is generated incrementally as your program runs. In -principle, running ``hp2ps`` on the incomplete file should produce a +principle, running :command:`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 +file may be incomplete, causing :command:`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): -:: +.. code-block:: sh head -`fgrep -n END_SAMPLE FOO.hp | tail -1 | cut -d : -f 1` FOO.hp \ | hp2ps > FOO.ps @@ -942,20 +914,20 @@ this problem (though the resulting command line looks rather Byzantine): The command ``fgrep -n END_SAMPLE FOO.hp`` finds the end of every complete sample in ``FOO.hp``, and labels each sample with its ending line number. We then select the line number 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 ``FOO.hp``. +using :command:`tail` and :command:`cut`. This is used as a parameter to :command:`head`; the +result is as if we deleted the final incomplete sample from :file:`FOO.hp`. This results in a properly-formatted .hp file which we feed directly to -``hp2ps``. +:command:`hp2ps`. Viewing a heap profile in real time ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -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. +The :command:`gv` and :command:`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: +section. Run :command:`gv` on your profile: -:: +.. code-block:: sh gv -watch -orientation=seascape FOO.ps @@ -965,7 +937,7 @@ the view will update automatically. This can all be encapsulated in a little script: -:: +.. code-block:: sh #!/bin/sh head -`fgrep -n END_SAMPLE FOO.hp | tail -1 | cut -d : -f 1` FOO.hp \ @@ -977,13 +949,13 @@ This can all be encapsulated in a little script: | hp2ps > FOO.ps done -Occasionally ``gv`` will choke as it tries to read an incomplete copy of -``FOO.ps`` (because ``hp2ps`` is still running as an update occurs). A +Occasionally :command:`gv` will choke as it tries to read an incomplete copy of +:file:`FOO.ps` (because :command:`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: -:: +.. code-block:: sh #!/bin/sh head -`fgrep -n END_SAMPLE FOO.hp | tail -1 | cut -d : -f 1` FOO.hp \ @@ -1002,9 +974,9 @@ file: Profiling Parallel and Concurrent Programs ------------------------------------------ -Combining ``-threaded`` and ``-prof`` is perfectly fine, and indeed it -is possible to profile a program running on multiple processors with the -``+RTS -N`` option. [3]_ +Combining :ghc-flag:`-threaded` and :ghc-flag:`-prof` is perfectly fine, and +indeed it is possible to profile a program running on multiple processors with +the RTS :rts-flag:`-N` option. [3]_ Some caveats apply, however. In the current implementation, a profiled program is likely to scale much less well than the unprofiled program, @@ -1014,7 +986,7 @@ 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`` when +We strongly recommend that you use :ghc-flag:`-fno-prof-count-entries` 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. @@ -1064,11 +1036,9 @@ one. A small example: Reciprocation ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -For an example we have a program, called ``Recip.hs``, which computes +For an example we have a program, called :file:`Recip.hs`, which computes exact decimal representations of reciprocals, with recurring parts -indicated in brackets. - -:: +indicated in brackets. :: reciprocal :: Int -> (String, Int) reciprocal n | n > 1 = ('0' : '.' : digits, recur) @@ -1101,9 +1071,9 @@ indicated in brackets. putStrLn (showRecip number) main -HPC instrumentation is enabled with the -fhpc flag: +HPC instrumentation is enabled with the :ghc-flag:`-fhpc` flag: -:: +.. code-block:: sh $ ghc -fhpc Recip.hs @@ -1113,14 +1083,14 @@ 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. -:: +.. code-block:: sh $ ./Recip 1/3 = 0.(3) Running the program generates a file with the ``.tix`` suffix, in this -case ``Recip.tix``, which contains the coverage data for this run of the +case :file:`Recip.tix`, 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 accumulated in the ``.tix`` file. To reset the coverage data and start again, just @@ -1128,7 +1098,7 @@ remove the ``.tix`` file. Having run the program, we can generate a textual summary of coverage: -:: +.. code-block:: none $ hpc report Recip 80% expressions used (81/101) @@ -1144,27 +1114,30 @@ Having run the program, we can generate a textual summary of coverage: We can also generate a marked-up version of the source. -:: +.. code-block:: none $ hpc markup Recip writing Recip.hs.html 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``. +:file:`hpc_index.html`, :file:`hpc_index_alt.html`, :file:`hpc_index_exp.html`, +:file:`hpc_index_fun.html`. Options for instrumenting code for coverage ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -``-fhpc`` +.. program:: hpc + +.. ghc-flag:: -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``. When the program is run, coverage data + compiled without :ghc-flag:`-fhpc`. When the program is run, coverage data will only be generated for those modules that were compiled with - ``-fhpc``, and the ``hpc`` tool will only show information about + :ghc-flag:`-fhpc`, and the :command:`hpc` tool will only show information about those modules. The hpc toolkit @@ -1172,7 +1145,7 @@ The hpc toolkit The hpc command has several sub-commands: -:: +.. code-block:: none $ hpc Usage: hpc COMMAND ... @@ -1213,7 +1186,7 @@ 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. -:: +.. code-block:: none $ hpc help report Usage: hpc report [OPTION] .. <TIX_FILE> [<MODULE> [<MODULE> ..]] @@ -1237,7 +1210,7 @@ hpc markup ``hpc markup`` marks up source files into colored html. -:: +.. code-block:: none $ hpc help markup Usage: hpc markup [OPTION] .. <TIX_FILE> [<MODULE> [<MODULE> ..]] @@ -1263,7 +1236,7 @@ hpc sum ``.tix`` file. ``hpc sum`` does not change the original ``.tix`` file; it generates a new ``.tix`` file. -:: +.. code-block:: none $ hpc help sum Usage: hpc sum [OPTION] .. <TIX_FILE> [<TIX_FILE> [<TIX_FILE> ..]] @@ -1284,7 +1257,7 @@ 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. -:: +.. code-block:: none $ hpc help combine Usage: hpc combine [OPTION] .. <TIX_FILE> <TIX_FILE> @@ -1305,7 +1278,7 @@ 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. -:: +.. code-block:: none $ hpc help map Usage: hpc map [OPTION] .. <TIX_FILE> @@ -1327,7 +1300,7 @@ 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. -:: +.. code-block:: none % hpc help overlay Usage: hpc overlay [OPTION] .. <OVERLAY_FILE> [<OVERLAY_FILE> [...]] @@ -1379,7 +1352,7 @@ Take a look at its which includeds a link to the ticky-ticky profiling page. .. [1] - ``-fprof-auto`` was known as ``-auto-all``\ ``-auto-all`` prior to + :ghc-flag:`-fprof-auto` was known as ``-auto-all`` prior to GHC 7.4.1. .. [2] diff --git a/docs/users_guide/runtime_control.rst b/docs/users_guide/runtime_control.rst index 4a05291612..db983fa8e8 100644 --- a/docs/users_guide/runtime_control.rst +++ b/docs/users_guide/runtime_control.rst @@ -32,10 +32,10 @@ There are four ways to set RTS options: - on the command line between ``+RTS ... -RTS``, when running the program (:ref:`rts-opts-cmdline`) -- at compile-time, using ``--with-rtsopts`` +- at compile-time, using :ghc-flag:`-with-rtsopts` (:ref:`rts-opts-compile-time`) -- with the environment variable ``GHCRTS`` +- with the environment variable :envvar:`GHCRTS` (:ref:`rts-options-environment`) - by overriding "hooks" in the runtime system (:ref:`rts-hooks`) @@ -50,14 +50,14 @@ Setting RTS options on the command line single: -RTS single: --RTS -If you set the ``-rtsopts`` flag appropriately when linking (see +If you set the :ghc-flag:`-rtsopts` flag appropriately when linking (see :ref:`options-linker`), you can give RTS options on the command line when running your program. When your Haskell program starts up, the RTS extracts command-line arguments bracketed between ``+RTS`` and ``-RTS`` as its own. For example: -:: +.. code-block:: none $ ghc prog.hs -rtsopts [1 of 1] Compiling Main ( prog.hs, prog.o ) @@ -71,7 +71,7 @@ calls ``System.Environment.getArgs``. No ``-RTS`` option is required if the runtime-system options extend to the end of the command line, as in this example: -:: +.. code-block:: none % hls -ltr /usr/etc +RTS -A5m @@ -115,18 +115,20 @@ Setting RTS options with the ``GHCRTS`` environment variable single: environment variable; for setting RTS options single: GHCRTS environment variable -If the ``-rtsopts`` flag is set to something other than ``none`` when -linking, RTS options are also taken from the environment variable -``GHCRTS``. For example, to set the maximum heap size to 2G -for all GHC-compiled programs (using an ``sh``\-like shell): +.. envvar:: GHCRTS -:: + If the ``-rtsopts`` flag is set to something other than ``none`` when + linking, RTS options are also taken from the environment variable + :envvar:`GHCRTS`. For example, to set the maximum heap size to 2G + for all GHC-compiled programs (using an ``sh``\-like shell): - GHCRTS='-M2G' - export GHCRTS + .. code-block:: sh -RTS options taken from the ``GHCRTS`` environment variable can be -overridden by options given on the command line. + GHCRTS='-M2G' + export GHCRTS + + RTS options taken from the :envvar:`GHCRTS` environment variable can be + overridden by options given on the command line. .. tip:: Setting something like ``GHCRTS=-M2G`` in your environment is a @@ -180,9 +182,7 @@ e.g., on stack overflow. The hooks for these are as follows: Miscellaneous RTS options ------------------------- -``-Vsecs`` - .. index:: - single: -V; RTS option +.. rts-flag:: -V <secs> Sets the interval that the RTS clock ticks at. The runtime uses a single timer signal to count ticks; this timer signal is used to @@ -191,10 +191,10 @@ Miscellaneous RTS options profiler uses the RTS timer signal directly to record time profiling samples. - Normally, setting the ``-V`` option directly is not necessary: the - resolution of the RTS timer is adjusted automatically if a short - interval is requested with the ``-C`` or ``-i`` options. However, - setting ``-V`` is required in order to increase the resolution of + Normally, setting the :rts-flag:`-V` option directly is not necessary: the + resolution of the RTS timer is adjusted automatically if a short interval is + requested with the :rts-flag:`-C` or :rts-flag:`-i` options. However, + setting :rts-flag:`-V` 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 @@ -204,9 +204,7 @@ Miscellaneous RTS options Disabling the interval timer is useful for debugging, because it eliminates a source of non-determinism at runtime. -``--install-signal-handlers=yes|no`` - .. index:: - single: --install-signal-handlers; RTS option +.. rts-flag:: --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 @@ -219,14 +217,17 @@ Miscellaneous RTS options capabilities. To disable the timer signal, use the ``-V0`` RTS option (see above). -``-xmaddress`` +.. rts-flag:: -xm <address> + .. index:: single: -xm; RTS option - 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``\ ”. If you need to use this - option to get GHCi working on your machine, please file a bug. + .. 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``\ ”. 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 @@ -238,12 +239,11 @@ Miscellaneous RTS options support for allocating memory in the low 2Gb if available (e.g. ``mmap`` with ``MAP_32BIT`` on Linux), or otherwise ``-xm40000000``. -``-xqsize`` - .. index:: - single: -xq; RTS option +.. rts-flag:: -xq <size> + + :default: 100k - [Default: 100k] This option relates to allocation limits; for more - about this see + This option relates to allocation limits; for more about this see :base-ref:`enableAllocationLimit <GHC-Conc.html#v%3AenableAllocationLimit>`. When a thread hits its allocation limit, the RTS throws an exception to the thread, and the thread gets an additional quota of allocation @@ -265,42 +265,46 @@ collection. Hopefully, you won't need any of these in normal operation, but there are several things that can be tweaked for maximum performance. -``-A ⟨size⟩`` +.. rts-flag:: -A ⟨size⟩ + + :default: 512k + .. index:: - single: -A; RTS option single: allocation area, size - [Default: 512k] Set the allocation area size used by the garbage + 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``, below). + fixed and is never resized (unless you use :rts-flag:`-H`, 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 (``-G1``) the ``-A`` option specifies 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``, below). + With only 1 generation (e.g. ``-G1``, see :rts-flag:`-G`) the ``-A`` option + specifies 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 :rts-flag:`-F`, below). + +.. rts-flag:: -O ⟨size⟩ + + :default: 1m -``-O ⟨size⟩`` .. index:: - single: -O; RTS option single: old generation, size - [Default: 1m] Set the minimum size of the old generation. The old + 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`` option multiplied by the size of the live data at the + of the :rts-flag:`-F` option multiplied by the size of the live data at the previous major collection, whichever is larger. -``-n ⟨size⟩`` - .. index:: - single: -n; RTS option +.. rts-flag:: -n ⟨size⟩ + + :default: 0 .. index:: single: allocation area, chunk size - [Default: 0, Example: ``-n4m``\ ] When set to a non-zero value, this + [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 @@ -322,14 +326,10 @@ performance. values, for example ``-A64m -n4m`` is a useful combination on larger core counts (8+). -``-c`` - .. index:: - single: -c; RTS option +.. rts-flag:: -c .. index:: single: garbage collection; compacting - - .. index:: single: compacting garbage collection Use a compacting algorithm for collecting the oldest generation. By @@ -338,7 +338,7 @@ performance. 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`` option), compaction can in + For a given heap size (using the :ghc-flag:`-H` 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%. @@ -347,19 +347,25 @@ performance. 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 maximum heap size (see the ``-M`` +.. rts-flag:: -c ⟨n⟩ + :noindex: + + :default: 30 + + Automatically enable compacting collection when the + live data exceeds ⟨n⟩% of the maximum heap size (see the :rts-flag:`-M` 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⟩.`` -``-F ⟨factor⟩`` +.. rts-flag:: -F ⟨factor⟩ + + :default: 2 + .. index:: - single: -F; RTS option single: heap size, factor - [Default: 2] This option controls the amount of memory reserved for + 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 @@ -367,19 +373,21 @@ performance. 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⟩`` than to increase - ``-F ⟨factor⟩.`` + it is usually better to use ``-H ⟨size⟩`` (see :rts-flag:`-H`) than to + increase ``-F ⟨factor⟩.`` The ``-F`` setting will be automatically reduced by the garbage - collector when the maximum heap size (the ``-M ⟨size⟩`` setting) is - approaching. + collector when the maximum heap size (the ``-M ⟨size⟩`` setting, see + :rts-flag:`-M`) is approaching. + +.. rts-flag:: -G ⟨generations⟩ + + :default: 2 -``-G ⟨generations⟩`` .. index:: - single: -G; RTS option single: generations, number of - [Default: 2] Set the number of generations used by the garbage + 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 @@ -387,19 +395,19 @@ performance. 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`` - option (see above) 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`` option, see below). + collector, as you would expect. In a 2-space collector, the :rts-flag:`-A` + 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 :rts-flag:`-H` option). -``-qggen`` - .. index:: - single: -qg; RTS option +.. rts-flag:: -qg <gen> - [New in GHC 6.12.1] [Default: 0] Use parallel GC in generation ⟨gen⟩ - and higher. Omitting ⟨gen⟩ turns off the parallel GC completely, - reverting to sequential GC. + :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 ``par``, Strategies, or with multiple @@ -407,17 +415,17 @@ performance. GC for a single-threaded sequential program too, especially 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`` option, and + enable the parallel runtime with a suitable :rts-flag:`-N` option, and additionally it might be beneficial to restrict parallel GC to the old generation with ``-qg1``. -``-qbgen`` - .. index:: - single: -qb; RTS option +.. rts-flag:: -qb <gen> - [New in GHC 6.12.1] [Default: 1] Use load-balancing in the parallel - GC in generation ⟨gen⟩ and higher. Omitting ⟨gen⟩ disables - load-balancing entirely. + :default: 1 + :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 @@ -429,13 +437,15 @@ performance. program it is sometimes beneficial to disable load-balancing entirely with ``-qb``. -``-H [⟨size⟩]`` +.. rts-flag:: -H [⟨size⟩] + + :default: 0 + .. index:: - single: -H; RTS option single: heap size, suggested - [Default: 0] This option provides a “suggested heap size” for the - garbage collector. Think of ``-Hsize`` as a variable ``-A`` option. + This option provides a "suggested heap size" for the + garbage collector. Think of ``-Hsize`` as a variable :rts-flag:`-A` option. It says: I want to use at least ⟨size⟩ bytes, so use whatever is left over to increase the ``-A`` value. @@ -449,13 +459,15 @@ performance. the default small ``-A`` value is suboptimal, as it can be in programs that create large amounts of long-lived data. -``-I ⟨seconds⟩`` +.. rts-flag:: -I ⟨seconds⟩ + + :default: 0.3 seconds + .. index:: - single: -I; RTS option single: idle GC - (default: 0.3) In the threaded and SMP versions of the RTS (see - ``-threaded``, :ref:`options-linker`), a major GC is automatically + In the threaded and SMP versions of the RTS (see + :ghc-flag:`-threaded`, :ref:`options-linker`), 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⟩`` @@ -474,12 +486,14 @@ performance. This is an experimental feature, please let us know if it causes problems and/or could benefit from further tuning. -``-ki ⟨size⟩`` +.. rts-flag:: -ki ⟨size⟩ + + :default: 1k + .. index:: - single: -k; RTS option single: stack, initial size - [Default: 1k] Set the initial stack size for new threads. + 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 @@ -494,14 +508,16 @@ performance. GHC 7.2.1. The old name is still accepted for backwards compatibility, but that may be removed in a future version. -``-kc ⟨size⟩`` +.. rts-flag:: -kc ⟨size⟩ + + :default: 32k + .. index:: - single: -kc; RTS option single: stack; chunk size - [Default: 32k] Set the size of “stack chunks”. When a thread's + 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`` is reached. + the thread's stack, until the limit set by :rts-flag:`-K` 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 @@ -512,28 +528,32 @@ performance. overflow/underflow between chunks. The default setting of 32k appears to be a reasonable compromise in most cases. -``-kb ⟨size⟩`` +.. rts-flag:: -kb ⟨size⟩ + + :default: 1k + .. index:: - single: -kc; RTS option single: stack; chunk buffer size - [Default: 1k] Sets the stack chunk buffer size. When a stack chunk + 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``), because in a + less than 10% of the size of a stack chunk (:rts-flag:`-kc`), because in a chain of stack chunks, each chunk will have a gap of unused space of this size. -``-K ⟨size⟩`` +.. rts-flag:: -K ⟨size⟩ + + :default: 80% of physical memory + .. index:: - single: -K; RTS option single: stack, maximum size - [Default: 80% physical memory size] Set the maximum stack size for + Set the maximum stack size for an individual thread to ⟨size⟩ bytes. If the thread attempts to exceed this limit, it will be sent the ``StackOverflow`` exception. The limit can be disabled entirely by specifying a size of zero. @@ -541,20 +561,23 @@ performance. 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⟩`` +.. rts-flag:: -m ⟨n⟩ + + :default: 3% + .. index:: - single: -m; RTS option single: heap, minimum free - Minimum % ⟨n⟩ of heap which must be available for allocation. The - default is 3%. + Minimum % ⟨n⟩ of heap which must be available for allocation. + +.. rts-flag:: -M ⟨size⟩ + + :default: unlimited -``-M ⟨size⟩`` .. index:: - single: -M; RTS option single: heap size, maximum - [Default: unlimited] Set the maximum heap size to ⟨size⟩ bytes. The + Set the maximum heap size to ⟨size⟩ bytes. The heap normally grows and shrinks according 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 @@ -573,13 +596,11 @@ performance. RTS options to produce runtime statistics ----------------------------------------- -``-T``, ``-t [⟨file⟩]``, ``-s [⟨file⟩]``, ``-S [⟨file⟩]``, ``--machine-readable`` - .. index:: - single: -T; RTS option - single: -t; RTS option - single: -s; RTS option - single: -S; RTS option - single: --machine-readable; RTS option +.. rts-flag:: -T + -t [<file>] + -s [<file>] + -S [<file>] + --machine-readable These options produce runtime-system statistics, such as the amount of time spent executing the program and in the garbage collector, @@ -600,7 +621,7 @@ RTS options to produce runtime statistics If you use the ``-t`` flag then, when your program finishes, you will see something like this: - :: + .. code-block:: none <<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>> @@ -648,7 +669,7 @@ RTS options to produce runtime statistics on what sort of RTS you have, e.g. you will only see profiling data if your RTS is compiled for profiling): - :: + .. code-block:: none 36,169,392 bytes allocated in the heap 4,057,632 bytes copied during GC @@ -727,7 +748,7 @@ RTS options to produce runtime statistics The ``-S`` flag, as well as giving the same output as the ``-s`` flag, prints information about each GC as it happens: - :: + .. code-block:: none Alloc Copied Live GC GC TOT TOT Page Flts bytes bytes bytes user elap user elap @@ -774,12 +795,10 @@ program for profiling (see :ref:`prof-compiler-options`, and one profiling option that is available for ordinary non-profiled executables: -``-hT`` - .. index:: - single: -hT; RTS option +.. rts-flag:: -hT (can be shortened to ``-h``.) Generates a basic heap profile, in the - file ``prog.hp``. To produce the heap profile graph, use ``hp2ps`` + file :file:`prog.hp`. To produce the heap profile graph, use :command:`hp2ps` (see :ref:`hp2ps`). 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 @@ -796,22 +815,20 @@ Tracing single: events single: eventlog files -When the program is linked with the ``-eventlog`` option +When the program is linked with the :ghc-flag:`-eventlog` option (:ref:`options-linker`), runtime events can be logged in two ways: - In binary format to a file for later analysis by a variety of tools. One such tool is - `ThreadScope <http://www.haskell.org/haskellwiki/ThreadScope>`__\ ThreadScope, + `ThreadScope <http://www.haskell.org/haskellwiki/ThreadScope>`__, which interprets the event log to produce a visual parallel execution profile of the program. - As text to standard output, for debugging purposes. -``-lflags`` - .. index:: - single: -l; RTS option +.. rts-flag:: -l <flags> - Log events in binary format to the file ``program.eventlog``. + Log events in binary format to the file :file:`{program}.eventlog`. Without any ⟨flags⟩ specified, this logs a default set of events, suitable for use with tools like ThreadScope. @@ -859,9 +876,7 @@ When the program is linked with the ``-eventlog`` option `ghc-events <http://hackage.haskell.org/package/ghc-events>`__ package. -``-v [⟨flags⟩]`` - .. index:: - single: -v; RTS option +.. rts-flag:: -v [⟨flags⟩] Log events as text to standard output, instead of to the ``.eventlog`` file. The ⟨flags⟩ are the same as for ``-l``, with the @@ -886,9 +901,7 @@ 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`` - .. index:: - single: -B; RTS option +.. rts-flag:: -B Sound the bell at the start of each (major) garbage collection. @@ -900,37 +913,33 @@ recommended for everyday use! [the program] is in by the beep pattern. But the major use is for annoying others in the same office…” -``-D ⟨x⟩`` - .. index:: - single: -D; RTS option +.. rts-flag:: -D ⟨x⟩ An RTS debugging flag; only available if the program was linked with - the ``-debug`` option. Various values of ⟨x⟩ are provided to enable + the :ghc-flag:`-debug` 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. Debug messages will be sent to the binary event log file instead of - stdout if the ``-l`` option is added. This might be useful for + stdout if the :rts-flag:`-l` option is added. This might be useful for reducing the overhead of debug tracing. -``-r ⟨file⟩`` +.. rts-flag:: -r ⟨file⟩ + .. index:: - single: -r; RTS option single: ticky ticky profiling single: profiling; ticky ticky Produce "ticky-ticky" statistics at the end of the program run (only - available if the program was linked with ``-debug``). The ⟨file⟩ - business works just like on the ``-S`` RTS option, above. + available if the program was linked with :ghc-flag:`-debug`). The ⟨file⟩ + business works just like on the :rts-flag:`-S` RTS option, above. For more information on ticky-ticky profiling, see :ref:`ticky-ticky`. -``-xc`` - .. index:: - single: -xc; RTS option +.. rts-flag:: -xc (Only available when the program is compiled for profiling.) When an exception is raised in the program, this option causes a stack trace @@ -939,14 +948,15 @@ recommended for everyday use! 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`` and running with ``+RTS -xc -RTS`` will tell - you exactly the call stack at the point the error was raised. + ``-prof -fprof-auto`` (see :ghc-flag:`-prof`) 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: - :: + .. code-block:: none *** Exception raised (reporting due to +RTS -xc), stack trace: GHC.List.CAF @@ -977,9 +987,7 @@ recommended for everyday use! See also the function ``traceStack`` in the module ``Debug.Trace`` for another way to view call stacks. -``-Z`` - .. index:: - single: -Z; RTS option +.. rts-flag:: -Z Turn *off* "update-frame squeezing" at garbage-collection time. (There's no particularly good reason to turn it off, except to @@ -994,77 +1002,79 @@ Getting information about the RTS .. index:: single: RTS -It is possible to ask the RTS to give some information about itself. To -do this, use the ``--info`` flag, e.g. - -:: - - $ ./a.out +RTS --info - [("GHC RTS", "YES") - ,("GHC version", "6.7") - ,("RTS way", "rts_p") - ,("Host platform", "x86_64-unknown-linux") - ,("Host architecture", "x86_64") - ,("Host OS", "linux") - ,("Host vendor", "unknown") - ,("Build platform", "x86_64-unknown-linux") - ,("Build architecture", "x86_64") - ,("Build OS", "linux") - ,("Build vendor", "unknown") - ,("Target platform", "x86_64-unknown-linux") - ,("Target architecture", "x86_64") - ,("Target OS", "linux") - ,("Target vendor", "unknown") - ,("Word size", "64") - ,("Compiler unregisterised", "NO") - ,("Tables next to code", "YES") - ] - -The information is formatted such that it can be read as a of type -``[(String, String)]``. Currently the following fields are present: - -``GHC RTS`` - Is this program linked against the GHC RTS? (always "YES"). - -``GHC version`` - The version of GHC used to compile this program. - -``RTS way`` - The variant (“way”) of the runtime. The most common values are - ``rts_v`` (vanilla), ``rts_thr`` (threaded runtime, i.e. linked - using the ``-threaded`` option) and ``rts_p`` (profiling runtime, - i.e. linked using the ``-prof`` option). Other variants include - ``debug`` (linked using ``-debug``), and ``dyn`` (the RTS is linked - in dynamically, i.e. a shared library, rather than statically linked - into the executable itself). These can be combined, e.g. you might - have ``rts_thr_debug_p``. - -``Target platform``\ ``Target architecture``\ ``Target OS``\ ``Target vendor`` - These are the platform the program is compiled to run on. - -``Build platform``\ ``Build architecture``\ ``Build OS``\ ``Build vendor`` - These are the platform where the program was built on. (That is, the - target platform of GHC itself.) Ordinarily this is identical to the - target platform. (It could potentially be different if - cross-compiling.) - -``Host platform``\ ``Host architecture``\ ``Host OS``\ ``Host vendor`` - These are the platform where GHC itself was compiled. Again, this - would normally be identical to the build and target platforms. - -``Word size`` - Either ``"32"`` or ``"64"``, reflecting the word size of the target - platform. - -``Compiler unregistered`` - Was this program compiled with an :ref:`"unregistered" <unreg>` - version of GHC? (I.e., a version of GHC that has no - platform-specific optimisations compiled in, usually because this is - a currently unsupported platform.) This value will usually be no, - unless you're using an experimental build of GHC. - -``Tables next to code`` - Putting info tables directly next to entry code is a useful - performance optimisation that is not available on all platforms. - This field tells you whether the program has been compiled with this - optimisation. (Usually yes, except on unusual platforms.) +.. rts-flag:: --info + + It is possible to ask the RTS to give some information about itself. To + do this, use the :rts-flag:`--info` flag, e.g. + + .. code-block:: none + + $ ./a.out +RTS --info + [("GHC RTS", "YES") + ,("GHC version", "6.7") + ,("RTS way", "rts_p") + ,("Host platform", "x86_64-unknown-linux") + ,("Host architecture", "x86_64") + ,("Host OS", "linux") + ,("Host vendor", "unknown") + ,("Build platform", "x86_64-unknown-linux") + ,("Build architecture", "x86_64") + ,("Build OS", "linux") + ,("Build vendor", "unknown") + ,("Target platform", "x86_64-unknown-linux") + ,("Target architecture", "x86_64") + ,("Target OS", "linux") + ,("Target vendor", "unknown") + ,("Word size", "64") + ,("Compiler unregisterised", "NO") + ,("Tables next to code", "YES") + ] + + The information is formatted such that it can be read as a of type + ``[(String, String)]``. Currently the following fields are present: + + ``GHC RTS`` + Is this program linked against the GHC RTS? (always "YES"). + + ``GHC version`` + The version of GHC used to compile this program. + + ``RTS way`` + The variant (“way”) of the runtime. The most common values are + ``rts_v`` (vanilla), ``rts_thr`` (threaded runtime, i.e. linked + using the :ghc-flag:`-threaded` option) and ``rts_p`` (profiling runtime, + i.e. linked using the :ghc-flag:`-prof` option). Other variants include + ``debug`` (linked using :ghc-flag:`-debug`), and ``dyn`` (the RTS is linked + in dynamically, i.e. a shared library, rather than statically linked + into the executable itself). These can be combined, e.g. you might + have ``rts_thr_debug_p``. + + ``Target platform``\ ``Target architecture``\ ``Target OS``\ ``Target vendor`` + These are the platform the program is compiled to run on. + + ``Build platform``\ ``Build architecture``\ ``Build OS``\ ``Build vendor`` + These are the platform where the program was built on. (That is, the + target platform of GHC itself.) Ordinarily this is identical to the + target platform. (It could potentially be different if + cross-compiling.) + + ``Host platform``\ ``Host architecture``\ ``Host OS``\ ``Host vendor`` + These are the platform where GHC itself was compiled. Again, this + would normally be identical to the build and target platforms. + + ``Word size`` + Either ``"32"`` or ``"64"``, reflecting the word size of the target + platform. + + ``Compiler unregistered`` + Was this program compiled with an :ref:`"unregistered" <unreg>` + version of GHC? (I.e., a version of GHC that has no + platform-specific optimisations compiled in, usually because this is + a currently unsupported platform.) This value will usually be no, + unless you're using an experimental build of GHC. + + ``Tables next to code`` + Putting info tables directly next to entry code is a useful + performance optimisation that is not available on all platforms. + This field tells you whether the program has been compiled with this + optimisation. (Usually yes, except on unusual platforms.) diff --git a/docs/users_guide/safe_haskell.rst b/docs/users_guide/safe_haskell.rst index b54b1ec2a8..efa6188b1c 100644 --- a/docs/users_guide/safe_haskell.rst +++ b/docs/users_guide/safe_haskell.rst @@ -158,40 +158,40 @@ reasons this security mechanism would fail without Safe Haskell: it. Safe Haskell prevents all these attacks. This is done by compiling the -RIO module with the ``-XSafe`` or ``-XTrustworthy`` flag and compiling -``Danger`` with the ``-XSafe`` flag. We explain each below. +RIO module with the :ghc-flag:`-XSafe` or :ghc-flag:`-XTrustworthy` flag and compiling +``Danger`` with the :ghc-flag:`-XSafe` flag. We explain each below. -The use of ``-XSafe`` to compile ``Danger`` restricts the features of +The use of :ghc-flag:`-XSafe` to compile ``Danger`` restricts the features of Haskell that can be used to a `safe subset <#safe-language>`__. This includes disallowing ``unsafePerformIO``, Template Haskell, pure FFI functions, RULES and restricting the operation of Overlapping Instances. -The ``-XSafe`` flag also restricts the modules can be imported by +The :ghc-flag:`-XSafe` flag also restricts the modules can be imported by ``Danger`` to only those that are considered trusted. Trusted modules -are those compiled with ``-XSafe``, where GHC provides a mechanical +are those compiled with :ghc-flag:`-XSafe`, where GHC provides a mechanical guarantee that the code is safe. Or those modules compiled with -``-XTrustworthy``, where the module author claims that the module is +:ghc-flag:`-XTrustworthy`, where the module author claims that the module is Safe. -This is why the RIO module is compiled with ``-XSafe`` or -``-XTrustworthy``>, to allow the ``Danger`` module to import it. The -``-XTrustworthy`` flag doesn't place any restrictions on the module like -``-XSafe`` does (expect to restrict overlapping instances to `safe +This is why the RIO module is compiled with :ghc-flag:`-XSafe` or +:ghc-flag:`-XTrustworthy`>, to allow the ``Danger`` module to import it. The +:ghc-flag:`-XTrustworthy` flag doesn't place any restrictions on the module like +:ghc-flag:`-XSafe` does (expect to restrict overlapping instances to `safe overlapping instances <#safe-overlapping-instances>`__). 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 ``-XTrustworthy`` is a problem as an +However, the unrestricted use of :ghc-flag:`-XTrustworthy` is a problem as an arbitrary module can use it to mark themselves as trusted, yet -``-XTrustworthy`` doesn't offer any guarantees about the module, unlike -``-XSafe``. To control the use of trustworthy modules it is recommended -to use the ``-fpackage-trust`` flag. This flag adds an extra requirement +:ghc-flag:`-XTrustworthy` doesn't offer any guarantees about the module, unlike +:ghc-flag:`-XSafe`. To control the use of trustworthy modules it is recommended +to use the :ghc-flag:`-fpackage-trust` flag. This flag adds an extra requirement to the trust check for trustworthy modules. It requires that for a trustworthy modules to be considered trusted, and allowed to be used in -``-XSafe`` compiled code, the client C compiling the code must tell GHC +:ghc-flag:`-XSafe` 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 -``-XSafe``, I trust the author(s) of this package and trust the modules +:ghc-flag:`-XSafe`, 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 @@ -199,7 +199,7 @@ would fail. For a more detailed overview of this mechanism see :ref:`safe-trust`. In the example, ``Danger`` can import module ``RIO`` because ``RIO`` is -compiled with ``-XSafe``. Thus, ``Danger`` can make use of the +compiled with :ghc-flag:`-XSafe`. Thus, ``Danger`` can make use of the ``rioReadFile`` and ``rioWriteFile`` functions to access permitted file names. The main application then imports both ``RIO`` and ``Danger``. To run the plugin, it calls ``RIO.runRIO Danger.runMe`` within the ``IO`` @@ -258,7 +258,7 @@ Furthermore, we restrict the following features: - ``ForeignFunctionInterface`` — Foreign import declarations that import a function with a non-``IO`` type are disallowed. -- ``RULES`` — Rewrite rules defined in a module M compiled with ``-XSafe`` are +- ``RULES`` — Rewrite rules defined in a module M compiled with :ghc-flag:`-XSafe` are dropped. Rules defined in Trustworthy modules that ``M`` imports are still valid and will fire as usual. @@ -275,7 +275,7 @@ Furthermore, we restrict the following features: - ``Data.Typeable`` — Hand crafted instances of the Typeable type class are not allowed in Safe Haskell as this can easily be abused to unsafely coerce - between types. Derived instances (through the ``-XDeriveDataTypeable`` + between types. Derived instances (through the :ghc-flag:`-XDeriveDataTypeable` extension) are still allowed. .. _safe-overlapping-instances: @@ -318,12 +318,12 @@ More specifically, consider the following modules: f :: String f = op ([1,2,3,4] :: [Int]) -Both module ``Class`` and module ``Dangerous`` will compile under ``-XSafe`` +Both module ``Class`` and module ``Dangerous`` will compile under :ghc-flag:`-XSafe` 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 -``-XSafe`` shouldn't change the meaning of code that compiles fine +:ghc-flag:`-XSafe` shouldn't change the meaning of code that compiles fine without importing the module. This is the Safe Haskell property known as *semantic consistency*. @@ -350,8 +350,8 @@ 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 an particular type-class method call is considered unsafe due to -overlapping instances, and the module being compiled is using ``-XSafe`` -or ``-XTrustworthy``, then compilation will fail. For ``-XUnsafe``, no +overlapping instances, and the module being compiled is using :ghc-flag:`-XSafe` +or :ghc-flag:`-XTrustworthy`, then compilation will fail. For :ghc-flag:`-XUnsafe`, no restriction is applied, and for modules using safe inference, they will be inferred unsafe. @@ -387,13 +387,13 @@ Trust and Safe Haskell Modes Safe Haskell introduces the following three language flags: -- ``-XSafe`` — Enables the safe language dialect, asking GHC to guarantee trust. +- :ghc-flag:`-XSafe` — Enables the safe language dialect, asking GHC to guarantee trust. The safe language dialect requires that all imports be trusted or a compilation error will occur. Safe Haskell will also infer this safety type for modules automatically when possible. Please refer to section :ref:`safe-inference` for more details of this. -- ``-XTrustworthy`` — Means that while this module may invoke unsafe functions +- :ghc-flag:`-XTrustworthy` — Means that while this module may invoke unsafe functions internally, the module's author claims that it exports an API that can't be used in an unsafe way. This doesn't enable the safe language. It does however restrict the resolution of overlapping instances to only allow :ref:`safe @@ -403,8 +403,8 @@ Safe Haskell introduces the following three language flags: An import statement without the keyword behaves as usual and can import any module whether trusted or not. -- ``-XUnsafe`` — Marks the module being compiled as unsafe so that modules - compiled using ``-XSafe`` can't import it. You may want to explicitly mark a +- :ghc-flag:`-XUnsafe` — Marks the module being compiled as unsafe so that modules + compiled using :ghc-flag:`-XSafe` 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. @@ -416,8 +416,8 @@ Safe Haskell, please refer to section :ref:`safe-inference` for more details. The procedure to check if a module is trusted or not depends on if the -``-fpackage-trust`` flag is present. The check is similar in both cases -with the ``-fpackage-trust`` flag enabling an extra requirement for +:ghc-flag:`-fpackage-trust` flag is present. The check is similar in both cases +with the :ghc-flag:`-fpackage-trust` flag enabling an extra requirement for trustworthy modules to be regarded as trusted. Trust check (``-fpackage-trust`` disabled) @@ -430,18 +430,18 @@ A module ``M`` in a package ``P`` is trusted by a client C if and only if: - Both of these hold: - - The module was compiled with ``-XSafe`` + - The module was compiled with :ghc-flag:`-XSafe` - All of M's direct imports are trusted by C - *or* all of these hold: - - The module was compiled with ``-XTrustworthy`` + - The module was compiled with :ghc-flag:`-XTrustworthy` - All of ``M``\'s direct *safe imports* are trusted by C The above definition of trust has an issue. Any module can be compiled -with ``-XTrustworthy`` and it will be trusted. To control this, there is +with :ghc-flag:`-XTrustworthy` and it will be trusted. To control this, there is an additional definition of package trust (enabled with the -``-fpackage-trust`` flag). The point of package trust is to require that +:ghc-flag:`-fpackage-trust` flag). The point of package trust is to require that the client C explicitly say which packages are allowed to contain trustworthy modules. Trustworthy packages are only trusted if they reside in a package trusted by C. @@ -453,7 +453,7 @@ Trust check (``-fpackage-trust`` enabled) single: trust check single: -fpackage-trust -When the ``-fpackage-trust`` flag is enabled, whether or not a module is +When the :ghc-flag:`-fpackage-trust` 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). @@ -467,17 +467,17 @@ Specifically, a package *P is trusted* when one of these hold: In either case, C is the only authority on package trust. It is up to the client to decide which `packages they trust <#safe-package-trust>`__. -When the ``-fpackage-trust`` flag is used a *module M from package P is +When the :ghc-flag:`-fpackage-trust` 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 ``-XSafe`` + - The module was compiled with :ghc-flag:`-XSafe` - All of ``M``\'s direct imports are trusted by C - *or* all of these hold: - - The module was compiled with ``-XTrustworthy`` + - The module was compiled with :ghc-flag:`-XTrustworthy` - All of ``M``\'s direct safe imports are trusted by C - Package ``P`` is trusted by C @@ -486,17 +486,17 @@ through the restrictions imposed by the safe language. For the second definition of trust, the guarantee is provided initially by the module author. The client C then establishes that they trust the module author by indicating they trust the package the module resides in. This trust -chain is required as GHC provides no guarantee for ``-XTrustworthy`` +chain is required as GHC provides no guarantee for :ghc-flag:`-XTrustworthy` compiled modules. The reason there are two modes of checking trust is that the extra -requirement enabled by ``-fpackage-trust`` causes the design of Safe +requirement enabled by :ghc-flag:`-fpackage-trust` causes the design of Safe Haskell to be invasive. Packages using Safe Haskell when the flag is enabled may or may not compile depending on the state of trusted packages on a users machine. This is both fragile, and causes compilation failures for everyone, even if they aren't trying to use any of the guarantees provided by Safe Haskell. Disabling -``-fpackage-trust`` by default and turning it into a flag makes Safe +:ghc-flag:`-fpackage-trust` by default and turning it into a flag makes Safe Haskell an opt-in extension rather than an always on feature. .. _safe-trust-example: @@ -519,11 +519,11 @@ Example 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 ``-XTrustworthy``, so we don't +does C trust module ``M``? Well ``M`` is marked :ghc-flag:`-XTrustworthy`, so we don't restrict the language. However, we still must check ``M``\'s imports: - First, ``M`` imports ``System.IO.Unsafe``. This is an unsafe module, however - ``M`` was compiled with ``-XTrustworthy`` , so ``P``\'s author takes + ``M`` was compiled with :ghc-flag:`-XTrustworthy` , so ``P``\'s author takes responsibility for that import. ``C`` trusts ``P``\'s author, so this import is fine. @@ -535,14 +535,14 @@ restrict the language. However, we still must check ``M``\'s imports: 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 ``-XTrustworthy``. +- Buggle only imports ``Prelude``, which is compiled with :ghc-flag:`-XTrustworthy`. ``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 ``-XTrustworthy`` +is enough. C only needs to trust packages that contain :ghc-flag:`-XTrustworthy` modules. .. _trustworthy-guarantees: @@ -553,7 +553,7 @@ Trustworthy Requirements .. index:: single: trustworthy -Module authors using the ``-XTrustworthy`` language extension for a module ``M`` +Module authors using the :ghc-flag:`-XTrustworthy` 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 unsafe manner. This mean that symbols exported should respect type safety and referential transparency. @@ -570,14 +570,20 @@ 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. +.. ghc-flag:: -trust ⟨pkg⟩ -- ``-distrust ⟨pkg⟩`` — Exposes package ⟨pkg⟩ if it was hidden and considers it - an untrusted package regardless of the package database. + Exposes package ⟨pkg⟩ if it was hidden and considers it a + trusted package regardless of the package database. -- ``-distrust-all-packages`` — Considers all packages distrusted unless they are - explicitly set to be trusted by subsequent command-line options. +.. ghc-flag:: -distrust ⟨pkg⟩ + + Exposes package ⟨pkg⟩ if it was hidden and considers it + an untrusted package regardless of the package database. + +.. ghc-flag:: -distrust-all-packages + + Considers all packages distrusted unless they are + explicitly set to be trusted by subsequent command-line options. To set a package's trust property in the package database please refer to :ref:`packages`. @@ -590,16 +596,16 @@ Safe Haskell Inference .. index:: single: safe inference -In the case where a module is compiled without one of ``-XSafe``, -``-XTrustworthy`` or ``-XUnsafe`` being used, GHC will try to figure out +In the case where a module is compiled without one of :ghc-flag:`-XSafe`, +:ghc-flag:`-XTrustworthy` or :ghc-flag:`-XUnsafe` being used, GHC will try to figure out itself if the module 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 ``-XSafe`` flag, then M is marked as +compile without error under the :ghc-flag:`-XSafe` 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 ``-XSafe`` flag? The later case should be used when you have a +explicit :ghc-flag:`-XSafe` flag? The later case should be used when you have a hard requirement that the module be safe. This is most useful for the :ref:`safe-use-cases` of Safe Haskell: running untrusted code. Safe inference is meant to be used by ordinary Haskell programmers. Users who @@ -631,9 +637,7 @@ Safe Haskell Flag Summary In summary, Safe Haskell consists of the following three language flags: -``-XSafe`` - .. index:: - single: -XSafe +.. ghc-flag:: -XSafe Restricts the module to the safe language. All of the module's direct imports must be trusted, but the module itself need not @@ -646,33 +650,29 @@ In summary, Safe Haskell consists of the following three language flags: - *Haskell Language* — Restricted to Safe Language - *Imported Modules* — All forced to be safe imports, all must be trusted. -``-XTrustworthy`` - .. index:: - single: -XTrustworthy +.. ghc-flag:: -XTrustworthy This establishes that the module is trusted, but the guarantee is provided by the module's author. A client of this module then specifies that they trust the module author by specifying they trust - the package containing the module. ``-XTrustworthy`` doesn't restrict the + the package containing the module. :ghc-flag:`-XTrustworthy` doesn't restrict the module to the safe language. It does however restrict the resolution of overlapping instances to only allow :ref:`safe overlapping instances <safe-overlapping-instances>`. It also allows the use of the safe import keyword. - *Module Truste* — Yes. - - *Module Truste* (``-fpackage-trust`` enabled) — Yes but only if the package + - *Module Truste* (:ghc-flag:`-fpackage-trust` enabled) — Yes but only if the package the module resides in is also trusted. - *Haskell Languag* — Unrestricted, except only safe overlapping instances allowed. - *Imported Modules* — Under control of module author which ones must be trusted. -``-XUnsafe`` - .. index:: - single: -XUnsafe +.. ghc-flag:: -XUnsafe Mark a module as unsafe so that it can't be imported by code - compiled with ``-XSafe``. Also enable the Safe Import extension so that a + compiled with :ghc-flag:`-XSafe`. Also enable the Safe Import extension so that a module can require a dependency to be trusted. @@ -683,24 +683,24 @@ In summary, Safe Haskell consists of the following three language flags: And one general flag: -``-fpackage-trust`` +.. ghc-flag:: -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 three warning flags: -``-Wunsafe`` +.. ghc-flag:: -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`` +.. ghc-flag:: -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. -``-Wtrustworthy-safe`` +.. ghc-flag:: -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 @@ -735,9 +735,9 @@ taken: source level pragma. - Ensure that all untrusted code is imported as a - :ref:`safe import <safe-imports>` - and that the ``-fpackage-trust`` :ref:`flag <safe-package-trust>` is used - with packages from untrusted sources being marked as untrusted. + :ref:`safe import <safe-imports>` and that the :ghc-flag:`-fpackage-trust` + flag (see :ref:`flag <safe-package-trust>`) is used with packages from + untrusted sources being marked as untrusted. There is a more detailed discussion of the issues involved in compilation safety and some potential solutions on the diff --git a/docs/users_guide/separate_compilation.rst b/docs/users_guide/separate_compilation.rst index 074aad047f..0f5f029e98 100644 --- a/docs/users_guide/separate_compilation.rst +++ b/docs/users_guide/separate_compilation.rst @@ -75,7 +75,7 @@ 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`` option +binary format, so don't try to read one; use the :ghc-flag:`--show-iface` option instead (see :ref:`hi-options`). You should think of the object file and the interface file as a pair, @@ -105,8 +105,8 @@ changed with the ``-osuf`` option). 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`` and ``-hisuf`` instead of ``-odir`` -and ``-osuf`` respectively. +the relevant options are :ghc-flag:`-hidir` and :ghc-flag:`-hisuf` instead of +:ghc-flag:`-odir` and :ghc-flag:`-osuf` respectively. For example, if GHC compiles the module ``A.B.C`` in the file ``src/A/B/C.hs``, with no ``-odir`` or ``-hidir`` flags, the interface @@ -126,8 +126,8 @@ 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`` option, and the name of the interface file -can be specified directly using the ``-ohi`` option. +overridden using the :ghc-flag:`-o` option, and the name of the interface file +can be specified directly using the :ghc-flag:`-ohi` option. .. _search-path: @@ -140,8 +140,8 @@ The search path single: finding interface files In your program, you import a module ``Foo`` by saying ``import Foo``. -In ``--make`` mode or GHCi, GHC will look for a source file for ``Foo`` -and arrange to compile it first. Without ``--make``, GHC will look for +In :ghc-flag:`--make` mode or GHCi, GHC will look for a source file for ``Foo`` +and arrange to compile it first. Without :ghc-flag:`--make`, 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. @@ -152,10 +152,10 @@ search path. For each of these directories, it tries appending 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`` mode or GHCi, or ⟨hisuf⟩ otherwise. +are in :ghc-flag:`--make` mode or GHCi, or ⟨hisuf⟩ otherwise. For example, suppose the search path contains directories ``d1``, -``d2``, and ``d3``, and we are in ``--make`` mode looking for the source +``d2``, and ``d3``, and we are in :ghc-flag:`--make` mode looking for the source file for a module ``A.B.C``. GHC will look in ``d1/A/B/C.hs``, ``d1/A/B/C.lhs``, ``d2/A/B/C.hs``, and so on. @@ -163,14 +163,15 @@ 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⟩]*`` +.. ghc-flag:: -i⟨dir⟩[:⟨dir⟩]* + .. index:: - single: -idirs; GHC option + single: search path; source code This flag appends a colon-separated list of ``dirs`` to the search path. -``-i`` +.. ghc-flag:: -i resets the search path back to nothing. This isn't the whole story: GHC also looks for modules in pre-compiled @@ -186,9 +187,7 @@ Redirecting the compilation output(s) single: output-directing options single: redirecting compilation output -``-o ⟨file⟩`` - .. index:: - single: -o; GHC option +.. ghc-flag:: -o ⟨file⟩ GHC's compiled output normally goes into a ``.hc``, ``.o``, etc., file, depending on the last-run compilation phase. The option @@ -202,7 +201,7 @@ Redirecting the compilation output(s) This option is most often used when creating an executable file, to set the filename of the executable. For example: - :: + .. code-block:: none ghc -o prog --make Main @@ -213,7 +212,7 @@ Redirecting the compilation output(s) "``.exe``" is added if the specified filename does not already have an extension. Thus - :: + .. code-block:: none ghc -o foo Main.hs @@ -225,25 +224,23 @@ Redirecting the compilation output(s) containing the module ``Main``. Note that with GHC the ``Main`` module doesn't have to be put in file ``Main.hs``. Thus both - :: + .. code-block:: none ghc --make Prog and - :: + .. code-block:: none ghc --make Prog.hs will produce ``Prog`` (or ``Prog.exe`` if you are on Windows). -``-odir ⟨dir⟩`` - .. index:: - single: -odir; GHC option +.. ghc-flag:: -odir ⟨dir⟩ Redirects object files to directory ⟨dir⟩. For example: - :: + .. code-block:: none $ ghc -c parse/Foo.hs parse/Bar.hs gurgle/Bumble.hs -odir `uname -m` @@ -256,9 +253,7 @@ Redirecting the compilation output(s) example, they would still be put in ``parse/Foo.hi``, ``parse/Bar.hi``, and ``gurgle/Bumble.hi``. -``-ohi ⟨file⟩`` - .. index:: - single: -ohi; GHC option +.. ghc-flag:: -ohi ⟨file⟩ The interface output may be directed to another file ``bar2/Wurble.iface`` with the option ``-ohi bar2/Wurble.iface`` @@ -275,16 +270,12 @@ Redirecting the compilation output(s) to redirect the interface into the bit bucket: ``-ohi /dev/null``, for example. -``-hidir ⟨dir⟩`` - .. index:: - single: -hidir; GHC option +.. ghc-flag:: -hidir ⟨dir⟩ Redirects all generated interface files into ⟨dir⟩, instead of the default. -``-stubdir ⟨dir⟩`` - .. index:: - single: -stubdir +.. ghc-flag:: -stubdir ⟨dir⟩ Redirects all generated FFI stub files into ⟨dir⟩. Stub files are generated when the Haskell source contains a ``foreign export`` or @@ -293,29 +284,19 @@ Redirecting the compilation output(s) exactly the same way as ``-odir`` and ``-hidir`` with respect to hierarchical modules. -``-dumpdir ⟨dir⟩`` - .. index:: - single: -dumpdir +.. ghc-flag:: -dumpdir ⟨dir⟩ Redirects all dump files into ⟨dir⟩. Dump files are generated when ``-ddump-to-file`` is used with other ``-ddump-*`` flags. -``-outputdir ⟨dir⟩`` - .. index:: - single: -outputdir +.. ghc-flag:: -outputdir ⟨dir⟩ The ``-outputdir`` option is shorthand for the combination of - ``-odir``, ``-hidir``, ``-stubdir`` and ``-dumpdir``. - -``-osuf ⟨suffix⟩; \ ``-hisuf``\ ⟨suffix⟩; \ ``-hcsuf``\ ⟨suffix⟩`` - .. index:: - single: -osuf + :ghc-flag:`-odir`, :ghc-flag:`-hidir`, :ghc-flag:`-stubdir` and :ghc-flag:`-dumpdir`. - .. index:: - single: -hisuf - - .. index:: - single: -hcsuf +.. ghc-flag:: -osuf ⟨suffix⟩ + -hisuf ⟨suffix⟩ + -hcsuf ⟨suffix⟩ The ``-osuf`` ⟨suffix⟩ will change the ``.o`` file suffix for object files to whatever you specify. We use this when compiling libraries, @@ -332,13 +313,13 @@ Redirecting the compilation output(s) compile a program both with and without profiling, in the same directory. You can say: - :: + .. code-block:: none ghc ... to get the ordinary version, and - :: + .. code-block:: none ghc ... -osuf prof.o -hisuf prof.hi -prof -auto-all @@ -358,35 +339,26 @@ Keeping Intermediate Files The following options are useful for keeping certain intermediate files around, when normally GHC would throw these away after compilation: -``-keep-hc-file`` - .. index:: - single: -keep-hc-file - single: -keep-hc-files +.. ghc-flag:: -keep-hc-file Keep intermediate ``.hc`` files when doing ``.hs``-to-``.o`` compilations via :ref:`C <c-code-gen>` (Note: ``.hc`` files are only generated by :ref:`unregisterised <unreg>` compilers). -``-keep-llvm-file`` - .. index:: - single: -keep-llvm-file - single: -keep-llvm-files +.. ghc-flag:: -keep-llvm-file Keep intermediate ``.ll`` files when doing ``.hs``-to-``.o`` compilations via :ref:`LLVM <llvm-code-gen>` (Note: ``.ll`` files aren't generated when using the native code generator, you may need - to use ``-fllvm`` to force them to be produced). + to use :ghc-flag:`-fllvm` to force them to be produced). -``-keep-s-file`` - .. index:: - single: -keep-s-file - single: -keep-s-files +.. ghc-flag:: -keep-s-file Keep intermediate ``.s`` files. -``-keep-tmp-files`` +.. ghc-flag:: -keep-tmp-files + .. index:: - single: -keep-tmp-files single: temporary files; keeping Instructs the GHC driver not to delete any of its temporary files, @@ -402,9 +374,7 @@ Redirecting temporary files .. index:: single: temporary files; redirecting -``-tmpdir`` - .. index:: - single: -tmpdir +.. ghc-flag:: -tmpdir If you have trouble because of running out of space in ``/tmp`` (or wherever your installation thinks temporary files should go), you @@ -412,13 +382,15 @@ Redirecting temporary files alternate directory. For example, ``-tmpdir .`` says to put temporary files in the current working directory. - Alternatively, use your ``TMPDIR`` environment variable.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. + .. index:: + single: TMPDIR environment variable + + Alternatively, use your :envvar:`TMPDIR` environment variable. Set it to the + name of the directory where temporary files should be put. GCC and other + programs will honour the :envvar:`TMPDIR` variable as well. - Even better idea: Set the ``DEFAULT_TMPDIR`` make variable when - building GHC, and never worry about ``TMPDIR`` again. (see the build + Even better idea: Set the :envvar:`DEFAULT_TMPDIR` :command:`make` variable when + building GHC, and never worry about :envvar:`TMPDIR` again. (see the build documentation). .. _hi-options: @@ -429,41 +401,33 @@ Other options related to interface files .. index:: single: interface files, options -``-ddump-hi`` - .. index:: - single: -ddump-hi +.. ghc-flag:: -ddump-hi Dumps the new interface to standard output. -``-ddump-hi-diffs`` - .. index:: - single: -ddump-hi-diffs +.. ghc-flag:: -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 enlightening to - be informed. The ``-ddump-hi-diffs`` option will make GHC report the + :command:`make`. When an interface does change, it is often enlightening to + be informed. The :ghc-flag:`-ddump-hi-diffs` option will make GHC report the differences between the old and new ``.hi`` files. -``-ddump-minimal-imports`` - .. index:: - single: -ddump-minimal-imports +.. ghc-flag:: -ddump-minimal-imports - Dump to the file ``M.imports`` (where ⟨M⟩ is the name of the module + Dump to the file :file:`{M}.imports` (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`` option. + via the :ghc-flag:`-dumpdir` option. - You can safely replace all the import declarations in ``M.hs`` with + You can safely replace all the import declarations in :file:`{M}.hs` with those found in its respective ``.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⟩`` - .. index:: - single: --show-iface +.. ghc-flag:: --show-iface ⟨file⟩ where ⟨file⟩ is the name of an interface file, dumps the contents of that interface in a human-readable format. See :ref:`modes`. @@ -476,10 +440,7 @@ The recompilation checker .. index:: single: recompilation checker -``-fforce-recomp`` - .. index:: - single: -fforce-recomp - single: -fno-force-recomp +.. ghc-flag:: -fforce-recomp Turn off recompilation checking (which is on by default). Recompilation checking normally stops compilation early, leaving an @@ -530,9 +491,7 @@ explains how. Every cycle in the module import graph must be broken by a ``hs-boot`` file. Suppose that modules ``A.hs`` and ``B.hs`` are Haskell source -files, thus: - -:: +files, thus: :: module A where import B( TB(..) ) @@ -558,16 +517,14 @@ import graph must be acyclic if ``{-# SOURCE #-}`` imports are ignored. For every module ``A.hs`` that is ``{-# SOURCE #-}``-imported in this way there must exist a source file ``A.hs-boot``. This file contains an -abbreviated version of ``A.hs``, thus: - -:: +abbreviated version of ``A.hs``, thus: :: module A where newtype TA = MkTA Int To compile these three files, issue the following commands: -:: +.. code-block:: none ghc -c A.hs-boot -- Produces A.hi-boot, A.o-boot ghc -c B.hs -- Consumes A.hi-boot, produces B.hi, B.o @@ -583,7 +540,7 @@ There are several points to note here: - A ``hs-boot`` file is compiled by GHC, just like a ``hs`` file: - :: + .. code-block:: none ghc -c A.hs-boot @@ -630,9 +587,7 @@ A hs-boot file is written in a subset of Haskell: 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: - - :: + for values. For example: :: double :: Int -> Int @@ -643,9 +598,7 @@ A hs-boot file is written in a subset of Haskell: - Open type and data family declarations are exactly as in Haskell. - A closed type family may optionally omit its equations, as in the - following example: - - :: + following example: :: type family ClosedFam a where .. @@ -657,9 +610,7 @@ A hs-boot file is written in a subset of Haskell: - 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: - - :: + everything that follows. For example: :: data T a b @@ -674,9 +625,7 @@ A hs-boot file is written in a subset of Haskell: annotation (:ref:`kinding`), to tell GHC the kind of the type variable, if it is not "\*". (In source files, this is worked out from the way the type variable is used in the constructors.) For - example: - - :: + example: :: data R (x :: * -> *) y @@ -710,9 +659,7 @@ Interfaces <http://plv.mpi-sws.org/backpack/>`__. Signature files are somewhat similar to ``hs-boot`` files, but have the ``hsig`` extension and behave slightly differently. -Suppose that I have modules ``String.hs`` and ``A.hs``, thus: - -:: +Suppose that I have modules ``String.hs`` and ``A.hs``, thus: :: module Text where data Text = Text String @@ -730,10 +677,8 @@ Suppose that I have modules ``String.hs`` and ``A.hs``, thus: Presently, module ``A`` depends explicitly on a concrete implementation of ``Text``. What if we wanted to a signature ``Text``, so we could vary the implementation with other possibilities (e.g. packed UTF-8 encoded -bytestrings)? To do this, we can write a signature ``TextSig.hsig``, and -modify ``A`` to include the signature instead: - -:: +bytestrings)? To do this, we can write a signature :file:`TextSig.hsig`, and +modify ``A`` to include the signature instead: :: module TextSig where data Text @@ -746,10 +691,10 @@ modify ``A`` to include the signature instead: To compile these two files, we need to specify what module we would like to use to implement the signature. This can be done by compiling the -implementation, and then using the ``-sig-of`` flag to specify the +implementation, and then using the :ghc-flag:`-sig-of` flag to specify the implementation backing a signature: -:: +.. code-block:: none ghc -c Text.hs ghc -c TextSig.hsig -sig-of "TextSig is main:Text" @@ -762,6 +707,11 @@ you must specify the full module name (unit ID, colon, and then module name), although in the future we may support more user-friendly syntax. +.. ghc-flag:: -sig-of "<sig> is <package>:<module>" + + Specify the module to be used at the implementation for the + given signature. + To just type-check an interface file, no ``-sig-of`` is necessary; instead, just pass the options ``-fno-code -fwrite-interface``. ``hsig`` files will generate normal interface files which other files can also @@ -792,7 +742,7 @@ Using ``make`` 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: -:: +.. code-block:: makefile HC = ghc HC_OPTS = -cpp $(EXTRA_HC_OPTS) @@ -830,11 +780,11 @@ GHC, assuming you name your source files the same as your modules. Thus: Main.o Main.hc Main.s : Foo.hi Baz.hi # 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 + Sophisticated :command:`make` variants may achieve some of the above more + elegantly. Notably, :command:`gmake`\'s pattern rules let you write the more comprehensible: - :: + .. code-block:: make %.o : %.lhs $(HC) -c $< $(HC_OPTS) @@ -852,7 +802,7 @@ Haskell source files, and once for ``hs-boot`` files (see Note also the inter-module dependencies at the end of the Makefile, which take the form -:: +.. code-block:: make Foo.o Foo.hc Foo.s : Baz.hi # Foo imports Baz @@ -877,7 +827,7 @@ Putting inter-dependencies of the form ``Foo.o : Bar.hi`` into your for automatically generating the required dependencies. Add the following to your ``Makefile``: -:: +.. code-block:: make depend : ghc -M $(HC_OPTS) $(SRCS) @@ -893,7 +843,7 @@ Makefile: - A line recording the dependence of the object file on the source file. - :: + .. code-block:: make M.o : M.hs @@ -902,14 +852,14 @@ Makefile: - For each import declaration ``import X`` in ``M``, a line recording the dependence of ``M`` on ``X``: - :: + .. code-block:: make M.o : X.hi - For each import declaration ``import {-# SOURCE #-} X`` in ``M``, a line recording the dependence of ``M`` on ``X``: - :: + .. code-block:: make M.o : X.hi-boot @@ -946,23 +896,28 @@ 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`` +.. ghc-flag:: -ddump-mod-cycles + Display a list of the cycles in the module graph. This is useful when trying to eliminate such cycles. -``-v2`` +.. ghc-flag:: -v2 + :noindex: + 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``; :ref:`options-help`.) + ``-v3`` and ``-v4``; see :ref:`options-help`.) + +.. ghc-flag:: -dep-makefile ⟨file⟩ -``-dep-makefile ⟨file⟩`` Use ⟨file⟩ as the makefile, rather than ``makefile`` or ``Makefile``. If ⟨file⟩ doesn't exist, ``mkdependHS`` creates it. We often use ``-dep-makefile .depend`` to put the dependencies in ``.depend`` and then ``include`` the file ``.depend`` into ``Makefile``. -``-dep-suffix <suf>`` +.. ghc-flag:: -dep-suffix <suf> + Make extra dependencies that declare that files with suffix ``.<suf>_<osuf>`` depend on interface files with suffix ``.<suf>_hi``, or (for ``{-# SOURCE #-}`` imports) on ``.hi-boot``. @@ -971,11 +926,13 @@ generation are: on ``.hi``, ``.a_hs`` on ``.a_hi``, and ``.b_hs`` on ``.b_hi``. (Useful in conjunction with NoFib "ways".) -``--exclude-module=<file>`` +.. ghc-flag:: --exclude-module=<file> + Regard ``<file>`` as "stable"; i.e., exclude it from having dependencies on it. -``-include-pkg-deps`` +.. ghc-flag:: -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 @@ -1000,9 +957,7 @@ 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 :ref:`instance-rules`), then GHC -has to visit that interface file anyway. Example: - -:: +has to visit that interface file anyway. Example: :: module A where instance C a => D (T a) where ... @@ -1012,32 +967,26 @@ 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: - -:: +and GHC has no other reason for visiting the module. Example: :: module Orphan where instance C a => D (T a) where ... class C a where ... Here, neither ``D`` nor ``T`` is declared in module ``Orphan``. We call such modules -“orphan modules”. GHC identifies orphan modules, and visits the +"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: - -:: +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: - -:: +the same module. But suppose class ``E`` had a functional dependency: :: module Lib where class E x y | y -> x where ... @@ -1071,13 +1020,13 @@ module: 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``, GHC will warn you if you are +If you use the flag :ghc-flag:`-Worphans`, GHC will warn you if you are creating an orphan module. Like any warning, you can switch the warning -off with ``-Wno-orphans``, and ``-Werror`` will make the -compilation fail if the warning is issued. +off with :ghc-flag:`-Wno-orphans <-Worphans>`, and :ghc-flag:`-Werror` will make +the compilation fail if the warning is issued. You can identify an orphan module by looking in its interface file, -``M.hi``, using the ``--show-iface`` :ref:`mode <modes>`. If there is a +``M.hi``, using the :ghc-flag:`--show-iface` :ref:`mode <modes>`. If there is a ``[orphan module]`` on the first line, GHC considers it an orphan module. diff --git a/docs/users_guide/shared_libs.rst b/docs/users_guide/shared_libs.rst index 62822382ce..1d294b8c88 100644 --- a/docs/users_guide/shared_libs.rst +++ b/docs/users_guide/shared_libs.rst @@ -43,9 +43,9 @@ Building programs that use shared libraries ------------------------------------------- To build a simple program and have it use shared libraries for the -runtime system and the base libraries use the ``-dynamic`` flag: +runtime system and the base libraries use the :ghc-flag:`-dynamic` flag: -:: +.. code-block:: none ghc --make -dynamic Main.hs @@ -81,7 +81,7 @@ 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``, a module from a separate package is assumed to +When using :ghc-flag:`-dynamic`, 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). @@ -90,7 +90,7 @@ Most of the conventions GHC expects when using packages are described in :ref:`building-packages`. 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``, ``-fPIC`` and ``-shared``. +of the flags :ghc-flag:`-dynamic`, :ghc-flag:`-fPIC` and :ghc-flag:`-shared`. Shared libraries that export a C API ------------------------------------ @@ -111,9 +111,9 @@ 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``, ``-fPIC`` and ``-shared`` flags: +the :ghc-flag:`-dynamic`, :ghc-flag:`-fPIC` and :ghc-flag:`-shared` flags: -:: +.. code-block:: none ghc --make -dynamic -shared -fPIC Foo.hs -o libfoo.so @@ -124,16 +124,16 @@ library. The ``-shared`` 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: -:: +.. code-block:: none ghc -dynamic -fPIC -c Foo.hs ghc -dynamic -shared Foo.o -o libfoo.so -In principle you can use ``-shared`` without ``-dynamic`` in the link -step. That means to statically link the rts all the base libraries into +In principle you can use :ghc-flag:`-shared` without :ghc-flag:`-dynamic` in the +link step. That means to statically link the rts all 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`` so that the code is +static libraries to have been built with :ghc-flag:`-fPIC` so that the code is suitable to include into a shared library and we do not do that at the moment. @@ -172,7 +172,7 @@ 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 + systems this embeds :envvar:`RPATH`\/:envvar:`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 @@ -183,12 +183,12 @@ find shared libraries at runtime. There are currently two modes: ``deploy`` This does not embed any runtime paths. It relies on the shared libraries being available in a standard location or in a directory - given by the ``LD_LIBRARY_PATH`` environment variable. + given by the :envvar:`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: -:: +.. code-block:: none ghc -dynamic Main.hs -o main -lfoo -L. -optl-Wl,-rpath,'$ORIGIN' @@ -220,7 +220,7 @@ that subsequently link against it (even if it hasn't been installed yet) will pick up that path as their runtime search location for it. When compiling with ghc directly, the install name is set by default to the location where it is built. You can override this with the -``-dylib-install-name`` option (which passes ``-install_name`` to the +:ghc-flag:`-dylib-install-name` option (which passes ``-install_name`` to the Apple linker). Cabal does this for you. It automatically sets the install name for dynamic libraries to the absolute path of the ultimate install location. diff --git a/docs/users_guide/sooner.rst b/docs/users_guide/sooner.rst index 87daefdd1e..fb9d626865 100644 --- a/docs/users_guide/sooner.rst +++ b/docs/users_guide/sooner.rst @@ -14,11 +14,11 @@ Sooner: producing a program more quickly single: compiling faster single: faster compiling -Don't use ``-O`` or (especially) ``-O2``: +Don't use :ghc-flag:`-O` or (especially) :ghc-flag:`-O2`: 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``! + GHC is surprisingly zippy for normal compilations without :ghc-flag:`-O`! Use more memory: Within reason, more memory for heap space means less garbage @@ -31,10 +31,10 @@ Use more memory: single: -H; RTS option If it says you're using more than 20% of total time in garbage - collecting, then more memory might help: use the ``-H⟨size⟩`` - option. Increasing the default allocation area size used by the - compiler's RTS might also help: use the ``+RTS -A⟨size⟩ -RTS`` - option. + collecting, then more memory might help: use the ``-H⟨size⟩`` (see + :rts-flag:`-H`) option. Increasing the default allocation area size used by + the compiler's RTS might also help: use the ``+RTS -A⟨size⟩ -RTS`` + option (see :rts-flag:`-A`). .. index:: single: -A⟨size⟩; RTS option @@ -47,7 +47,7 @@ Don't use too much memory! 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 + builtin :command:`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 @@ -118,8 +118,8 @@ Compile via LLVM: generator <native-code-gen>`. 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`` and ``-optlc`` flags. Be - careful though as setting these flags stops GHC from setting its + specific flags to LLVM with the :ghc-flag:`-optlo` and :ghc-flag:`-optlc` + flags. Be careful though as setting these flags stops GHC from setting its usual flags for the LLVM optimiser and compiler. Overloaded functions are not your friend: @@ -130,7 +130,7 @@ Overloaded functions are not your friend: Give explicit type signatures: Signatures are the basic trick; putting them on exported, top-level functions is good software-engineering practice, anyway. (Tip: using - ``-Wmissing-signatures``-Wmissing-signatures option can + the :ghc-flag:`-Wmissing-signatures` option can help enforce good signature-practice). The automatic specialisation of overloaded functions (with ``-O``) @@ -149,11 +149,11 @@ Use ``SPECIALIZE`` pragmas: "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`` option (see :ref:`hi-options`). + :ghc-flag:`--show-iface` option (see :ref:`hi-options`). - :: + .. code-block:: sh - % ghc --show-iface Foo.hi | egrep '^[a-z].*::.*=>' + $ ghc --show-iface Foo.hi | egrep '^[a-z].*::.*=>' Strict functions are your dear friends: And, among other things, lazy pattern-matching is your enemy. @@ -166,9 +166,9 @@ Strict functions are your dear friends: :: - f (Wibble x y) = ... # strict + f (Wibble x y) = ... # strict - f arg = let { (Wibble x y) = arg } in ... # lazy + f arg = let { (Wibble x y) = arg } in ... # lazy The former will result in far better code. @@ -177,17 +177,17 @@ Strict functions are your dear friends: :: - f (Wibble x y) # beautiful but slow - = let + f (Wibble x y) # beautiful but slow + = let (a1, b1, c1) = unpackFoo x (a2, b2, c2) = unpackFoo y - in ... + in ... - f (Wibble x y) # ugly, and proud of it - = case (unpackFoo x) of { (a1, b1, c1) -> + f (Wibble x y) # ugly, and proud of it + = case (unpackFoo x) of { (a1, b1, c1) -> case (unpackFoo y) of { (a2, b2, c2) -> - ... - }} + ... + }} GHC loves single-constructor data-types: It's all the better if a function is strict in a single-constructor @@ -215,7 +215,7 @@ Newtypes are better than datatypes: components (lazy in the first, strict in the second \\& third).” If the function isn't exported, just compile with the extra flag - ``-ddump-simpl``; next to the signature for any binder, it will + :ghc-flag:`-ddump-simpl`; 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!) @@ -236,7 +236,7 @@ Explicit ``export`` list: Look at the Core syntax! (The form in which GHC manipulates your code.) Just run your - compilation with ``-ddump-simpl`` (don't forget the ``-O``). + compilation with :ghc-flag:`-ddump-simpl` (don't forget the :ghc-flag:`-O`). If profiling has pointed the finger at particular functions, look at their Core code. ``lets`` are bad, ``cases`` are good, dictionaries @@ -251,16 +251,16 @@ Use strictness annotations: space leaks. It can also help in a third way: when used with - ``-funbox-strict-fields`` (see :ref:`options-f`), a strict field can + :ghc-flag:`-funbox-strict-fields` (see :ref:`options-f`), 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`` is only really a good idea in - conjunction with ``-O``, because otherwise the extra packing and + Using :ghc-flag:`-funbox-strict-fields` is only really a good idea in + conjunction with :ghc-flag:`-O`, because otherwise the extra packing and unpacking won't be optimised away. In fact, it is possible that - ``-funbox-strict-fields`` may worsen performance even *with* ``-O``, + :ghc-flag:`-funbox-strict-fields` may worsen performance even *with* :ghc-flag:`-O`, but this is unlikely (let us know if it happens to you). Use unboxed types (a GHC extension): @@ -269,7 +269,7 @@ Use unboxed types (a GHC extension): information about using unboxed types. Before resorting to explicit unboxed types, try using strict - constructor fields and ``-funbox-strict-fields`` first (see above). + constructor fields and :ghc-flag:`-funbox-strict-fields` first (see above). That way, your code stays portable. Use ``foreign import`` (a GHC extension) to plug into fast libraries: @@ -303,12 +303,12 @@ Use unboxed arrays (``UArray``) ``Data.Array`` library. Use a bigger heap! - If your program's GC stats (``-S`` RTS option) indicate that + If your program's GC stats (:rts-flag:`-S` RTS option) indicate that it's doing lots of garbage-collection (say, more than 20% of execution time), more memory might help — with the ``-H⟨size⟩`` or ``-A⟨size⟩`` RTS options (see :ref:`rts-options-gc`). As a rule of thumb, try setting ``-H⟨size⟩`` to the amount of memory you're willing to let your process - consume, or perhaps try passing ``-H`` without any argument to let GHC + consume, or perhaps try passing :ghc-flag:`-H` without any argument to let GHC calculate a value based on the amount of live data. .. _smaller: @@ -320,7 +320,7 @@ Smaller: producing a program that is smaller single: smaller programs, how to produce single: -funfolding-use-threshold0 option -Decrease the “go-for-it” threshold for unfolding smallish expressions. +Decrease the "go-for-it" threshold for unfolding smallish expressions. Give a ``-funfolding-use-threshold0`` 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 @@ -329,7 +329,7 @@ generally enables extra simplifying optimisations to be performed. Avoid ``Read``. -Use ``strip`` on your executables. +Use :command:`strip` on your executables. .. _thriftier: @@ -344,8 +344,8 @@ Thriftier: producing a program that gobbles less heap space "I think I have a space leak..." Re-run your program with ``+RTS -S``, and remove all doubt! (You'll see the -heap usage get bigger and bigger...) [Hmmm... this might be even easier with -the ``-G1`` RTS option; so... ``./a.out +RTS -S -G1``...] +heap usage get bigger and bigger...) (Hmmm... this might be even easier with +the ``-G1`` RTS option; so... ``./a.out +RTS -S -G1``) .. index:: single: -G RTS option diff --git a/docs/users_guide/using-concurrent.rst b/docs/users_guide/using-concurrent.rst index b2b235ad3e..c5179c7333 100644 --- a/docs/users_guide/using-concurrent.rst +++ b/docs/users_guide/using-concurrent.rst @@ -13,19 +13,17 @@ support libraries for Concurrent Haskell, just import More information on Concurrent Haskell is provided in the documentation for that module. -Optionally, the program may be linked with the ``-threaded`` option (see +Optionally, the program may be linked with the :ghc-flag:`-threaded` option (see :ref:`options-linker`. This provides two benefits: -- It enables the ``-N``\ ``-Nx``\ RTS option RTS option to be used, - which allows threads to run in parallelparallelism on a - multiprocessormultiprocessorSMP or multicoremulticore machine. See - :ref:`using-smp`. +- It enables the :rts-flag:`-N` to be used, which allows threads to run in + parallelism on a multi-processor or multi-core machine. See :ref:`using-smp`. -- 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 export``\ ed Haskell functions may be called from multiple - OS threads simultaneously. See :ref:`ffi-threads`. +- 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 export``\ ed Haskell functions may be called from multiple + OS threads simultaneously. See :ref:`ffi-threads`. The following RTS option(s) affect the behaviour of Concurrent Haskell programs: @@ -33,16 +31,15 @@ programs: .. index:: single: RTS options; concurrent -``-Cs`` - .. index:: - single: -Cs; RTS option +.. rts-flag:: -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). By default, - context switches occur every 20ms. + often as possible (at every heap block allocation). .. _using-smp: @@ -76,10 +73,11 @@ Compile-time options for SMP parallelism ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ In order to make use of multiple CPUs, your program must be linked with -the ``-threaded`` option (see :ref:`options-linker`). Additionally, the +the :ghc-flag:`-threaded` option (see :ref:`options-linker`). Additionally, the following compiler options affect parallelism: -``-feager-blackholing`` +.. ghc-flag:: -feager-blackholing + Blackholing is the act of marking a thunk (lazy computuation) as being under evaluation. It is useful for three reasons: firstly it lets us detect certain kinds of infinite loop (the @@ -109,12 +107,8 @@ There are two ways to run a program on multiple processors: call ``Control.Concurrent.setNumCapabilities`` from your program, or use the RTS ``-N`` options. -``-N⟨x⟩`` -``-maxN⟨x⟩`` - - .. index:: - single: -N⟨x⟩; RTS option - single: -maxN(x); RTS option +.. rts-flag:: -N <x> + -maxN <x> Use ⟨x⟩ simultaneous threads when running the program. @@ -155,7 +149,8 @@ RTS ``-N`` options. The following options affect the way the runtime schedules threads on CPUs: -``-qa`` +.. rts-flag:: -qa + Use the OS's affinity facilities to try to pin OS threads to CPU cores. @@ -168,7 +163,8 @@ CPUs: this may or may not result in a performance improvement. We recommend trying it out and measuring the difference. -``-qm`` +.. rts-flag:: -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 @@ -182,11 +178,11 @@ CPUs: Hints for using SMP parallelism ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -Add the ``-s`` RTS option when running the program to see timing stats, +Add the :rts-flag:`-s` 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`` for comparison. +without :rts-flag:`-N` for comparison. The output of ``+RTS -s`` tells you how many "sparks" were created and executed during the run of the program (see :ref:`rts-options-gc`), diff --git a/docs/users_guide/using-optimisation.rst b/docs/users_guide/using-optimisation.rst index 84bf27b4d4..bc8e70036e 100644 --- a/docs/users_guide/using-optimisation.rst +++ b/docs/users_guide/using-optimisation.rst @@ -45,39 +45,35 @@ 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. -``-O*`` - .. index:: - single: -O\* not specified +.. ghc-flag:: -O* This is taken to mean: “Please compile quickly; I'm not over-bothered about compiled-code quality.” So, for example: ``ghc -c Foo.hs`` -``-O0`` - .. index:: - single: -O0 +.. ghc-flag:: -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 eg. ``make`` has inserted a ``-O`` on the command line + useful if e.g. ``make`` has inserted a ``-O`` on the command line already. -``-O``, ``-O1`` +.. ghc-flag:: -O + -O1 + .. index:: - single: -O option - single: -O1 option single: optimise; normally Means: "Generate good-quality code without taking too long about it." Thus, for example: ``ghc -c -O Main.lhs`` -``-O2`` +.. ghc-flag:: -O2 + .. index:: - single: -O2 option single: optimise; aggressively Means: "Apply every non-dangerous optimisation, even if it means - significantly longer compile times." + 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 @@ -86,9 +82,9 @@ one reason to stick to no-optimisation when developing code. At the moment, ``-O2`` is *unlikely* to produce better code than ``-O``. -``-Odph`` +.. ghc-flag:: -Odph + .. index:: - single: -Odph single: optimise; DPH Enables all ``-O2`` optimisation, sets @@ -101,7 +97,7 @@ 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``, then stand back in amazement. +:ghc-flag:`-v`, then stand back in amazement. .. _options-f: @@ -113,19 +109,17 @@ The easiest way to see what ``-O`` (etc.) “really mean” is to run with single: -fno-\* options (GHC) These flags turn on and off individual optimisations. Flags marked as -*Enabled by default* are enabled by ``-O``, and as such you shouldn't +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``. See :ref:`options-f-compact` for a compact list. -``-fcase-merge`` - .. index:: - single: -fcase-merge +.. ghc-flag:: -fcase-merge - *On by default.* Merge immediately-nested case expressions that - scrutinse the same variable. For example, + :default: on - :: + Merge immediately-nested case expressions that scrutinse the same variable. + For example, :: case x of Red -> e1 @@ -133,98 +127,85 @@ list. Blue -> e2 Green -> e3 - Is transformed to, + Is transformed to, :: - :: case x of Red -> e1 Blue -> e2 Green -> e2 -``-fcall-arity`` - .. index:: - single: -fcall-arity +.. ghc-flag:: -fcall-arity - *On by default.*. + :default: on -``-fcmm-elim-common-blocks`` - .. index:: - single: -felim-common-blocks + Enable call-arity analysis. + +.. ghc-flag:: -fcmm-elim-common-blocks + + :default: on - *On by default.*. Enables the common block elimination optimisation + Enables the common block elimination optimisation in the code generator. This optimisation attempts to find identical Cmm blocks and eliminate the duplicates. -``-fcmm-sink`` - .. index:: - single: -fcmm-sink +.. ghc-flag:: -fcmm-sink + + :default: on - *On by default.*. Enables the sinking pass in the code generator. + Enables the sinking pass in the code generator. This optimisation attempts to find identical 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. -``-fcpr-off`` - .. index:: - single: -fcpr-Off +.. ghc-flag:: -fcpr-off Switch off CPR analysis in the demand analyser. -``-fcse`` - .. index:: - single: -fcse +.. ghc-flag:: -fcse + + :default: on - *On by default.*. Enables the common-sub-expression elimination + 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. -``-fdicts-cheap`` - .. index:: - single: -fdicts-cheap +.. ghc-flag:: -fdicts-cheap A very experimental flag that makes dictionary-valued expressions seem cheap to the optimiser. -``-fdicts-strict`` - .. index:: - single: -fdicts-strict +.. ghc-flag:: -fdicts-strict Make dictionaries strict. -``-fdmd-tx-dict-sel`` - .. index:: - single: -fdmd-tx-dict-sel +.. ghc-flag:: -fdmd-tx-dict-sel *On by default for ``-O0``, ``-O``, ``-O2``.* Use a special demand transformer for dictionary selectors. -``-fdo-eta-reduction`` - .. index:: - single: -fdo-eta-reduction +.. ghc-flag:: -fdo-eta-reduction - *On by default.* Eta-reduce lambda expressions, if doing so gets rid - of a whole group of lambdas. + :default: on -``-fdo-lambda-eta-expansion`` - .. index:: - single: -fdo-lambda-eta-expansion + Eta-reduce lambda expressions, if doing so gets rid of a whole group of + lambdas. - *On by default.* Eta-expand let-bindings to increase their arity. +.. ghc-flag:: -fdo-lambda-eta-expansion -``-feager-blackholing`` - .. index:: - single: -feager-blackholing + :default: on + + Eta-expand let-bindings to increase their arity. + +.. ghc-flag:: -feager-blackholing 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 <http://research.microsoft.com/en-us/um/people/simonpj/papers/parallel/>`__. -``-fexcess-precision`` - .. index:: - single: -fexcess-precision +.. ghc-flag:: -fexcess-precision When this option is given, intermediate floating point values can have a *greater* precision/range than the final type. Generally this @@ -237,19 +218,17 @@ list. ``-fno-excess-precision`` has any effect. This is a known bug, see :ref:`bugs-ghc`. -``-fexpose-all-unfoldings`` - .. index:: - single: -fexpose-all-unfoldings +.. ghc-flag:: -fexpose-all-unfoldings 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`` - .. index:: - single: -ffloat-in +.. ghc-flag:: -ffloat-in + + :default: on - *On by default.* Float let-bindings inwards, nearer their binding + Float let-bindings inwards, nearer their binding site. See `Let-floating: moving bindings to give faster programs (ICFP'96) <http://research.microsoft.com/en-us/um/people/simonpj/papers/float.ps.gz>`__. @@ -266,11 +245,11 @@ list. grouped into a larger single let binding, effectively batching their allocation and helping the garbage collector and allocator. -``-ffull-laziness`` - .. index:: - single: -ffull-laziness +.. ghc-flag:: -ffull-laziness + + :default: on - *On by default.* Run the full laziness optimisation (also known as + 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 @@ -287,143 +266,124 @@ list. difference is that GHC doesn't consistently apply full-laziness, so don't rely on it. -``-ffun-to-thunk`` - .. index:: - single: -ffun-to-thunk +.. ghc-flag:: -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. Off - by default. + This flag allows worker/wrapper to remove *all* value lambdas. -``-fignore-asserts`` - .. index:: - single: -fignore-asserts +.. ghc-flag:: -fignore-asserts - *On by default.*. Causes GHC to ignore uses of the function - ``Exception.assert`` in source code (in other words, rewriting - ``Exception.assert p e`` to ``e`` (see :ref:`assertions`). + :default: on -``-fignore-interface-pragmas`` - .. index:: - single: -fignore-interface-pragmas + Causes GHC to ignore uses of the function ``Exception.assert`` in source + code (in other words, rewriting ``Exception.assert p e`` to ``e`` (see + :ref:`assertions`). + +.. ghc-flag:: -fignore-interface-pragmas Tells GHC to ignore all inessential information when reading - interface files. That is, even if ``M.hi`` contains unfolding or + interface files. That is, even if :file:`M.hi` contains unfolding or strictness information for a function, GHC will ignore that information. -``-flate-dmd-anal`` - .. index:: - single: -flate-dmd-anal +.. ghc-flag:: -flate-dmd-anal 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`` can create functions with unused arguments which + :ghc-flag:`-fspec-constr` 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 :ghc-wiki:`Trac wiki page <LateDmd>`. -``-fliberate-case`` - .. index:: - single: -fliberate-case +.. ghc-flag:: -fliberate-case *Off by default, but enabled by -O2.* 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``) but for free + the call-pattern specialiser (:ghc-flag:`-fspec-constr`) but for free variables rather than arguments. -``-fliberate-case-threshold=n`` - .. index:: - single: -fliberate-case-threshold +.. ghc-flag:: -fliberate-case-threshold=<n> - *default: 2000.* Set the size threshold for the liberate-case - transformation. + :default: 2000 -``-floopification`` - .. index:: - single: -floopification + Set the size threshold for the liberate-case transformation. - *On by default.* +.. ghc-flag:: -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. -``-fmax-inline-alloc-size=n`` - .. index:: - single: -fmax-inline-alloc-size +.. ghc-flag:: -fmax-inline-alloc-size=<n> + + :default: 128 - *default: 128.* Set the maximum size of inline array allocations to n bytes. + 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-insn=n`` - .. index:: - single: -fmax-inline-memcpy-insn +.. ghc-flag:: -fmax-inline-memcpy-insn=<n> - *default: 32.* Inline ``memcpy`` calls if they would generate no more than n pseudo - instructions. + :default: 32 -``-fmax-inline-memset-insns=n`` - .. index:: - single: -fmax-inline-memset-insns + Inline ``memcpy`` calls if they would generate no more than ⟨n⟩ pseudo-instructions. - *default: 32.* Inline ``memset`` calls if they would generate no more than n pseudo +.. ghc-flag:: -fmax-inline-memset-insns=<n> + + :default: 32 + + Inline ``memset`` calls if they would generate no more than n pseudo instructions. -``-fmax-relevant-binds=n`` - .. index:: - single: -fmax-relevant-bindings +.. ghc-flag:: -fmax-relevant-binds=<n> + -fno-max-relevant-bindings + + :default: 6 The type checker sometimes displays a fragment of the type environment in error messages, but only up to some maximum number, - set by this flag. The default is 6. Turning it off with + set by this flag. Turning it off with ``-fno-max-relevant-bindings`` gives an unlimited number. Syntactically top-level bindings are also usually excluded (since they may be numerous), but ``-fno-max-relevant-bindings`` includes them too. -``-fmax-simplifier-iterations=n`` - .. index:: - single: -fmax-simplifier-iterations +.. ghc-flag:: -fmax-simplifier-iterations=<n> - *default: 4.* Sets the maximal number of iterations for the simplifier. + :default: 4 -``-fmax-worker-args=n`` - .. index:: - single: -fmax-worker-args + Sets the maximal number of iterations for the simplifier. - *default: 10.* If a worker has that many arguments, none will be unpacked - anymore. +.. ghc-flag:: -fmax-worker-args=<n> -``-fno-opt-coercion`` - .. index:: - single: -fno-opt-coercion + :default: 10 + + If a worker has that many arguments, none will be unpacked anymore. + +.. ghc-flag:: -fno-opt-coercion Turn off the coercion optimiser. -``-fno-pre-inlining`` - .. index:: - single: -fno-pre-inlining +.. ghc-flag:: -fno-pre-inlining Turn off pre-inlining. -``-fno-state-hack`` - .. index:: - single: -fno-state-hack +.. ghc-flag:: -fno-state-hack Turn off the "state hack" whereby any lambda with a ``State#`` token as argument is considered to be single-entry, hence it is considered - OK to inline things inside it. This can improve performance of IO + 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`` - .. index:: - single: -fomit-interface-pragmas +.. ghc-flag:: -fomit-interface-pragmas Tells GHC to omit all inessential information from the interface file generated for the module being compiled (say M). This means @@ -434,11 +394,11 @@ list. need to be recompiled less often (only when M's exports change their type, not when they change their implementation). -``-fomit-yields`` - .. index:: - single: -fomit-yields +.. ghc-flag:: -fomit-yields - *On by default.* Tells GHC to omit heap checks when no allocation is + :default: on + + Tells GHC to omit heap checks when no allocation is being performed. While this improves 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 @@ -446,18 +406,14 @@ list. off. Consider also recompiling all libraries with this optimization turned off, if you need to guarantee interruptibility. -``-fpedantic-bottoms`` - .. index:: - single: -fpedantic-bottoms +.. ghc-flag:: -fpedantic-bottoms Make GHC be more precise about its treatment of bottom (but see also - ``-fno-state-hack``). In particular, stop GHC eta-expanding through + :ghc-flag:`-fno-state-hack`). 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`` - .. index:: - single: -fregs-graph +.. ghc-flag:: -fregs-graph *Off by default due to a performance regression bug. Only applies in combination with the native code generator.* Use the graph colouring @@ -466,9 +422,7 @@ list. allocator. The downside being that the linear register allocator usually generates worse code. -``-fregs-iterative`` - .. index:: - single: -fregs-iterative +.. ghc-flag:: -fregs-iterative *Off by default, only applies in combination with the native code generator.* Use the iterative coalescing graph colouring register @@ -476,18 +430,17 @@ list. is the same register allocator as the ``-fregs-graph`` one but also enables iterative coalescing during register allocation. -``-fsimplifier-phases=n`` - .. index:: - single: -fsimplifier-phases +.. ghc-flag:: -fsimplifier-phases=<n> - *default: 2.* Set the number of phases for the simplifier. Ignored - with -O0. + :default: 2 -``-fsimpl-tick-factor=n`` - .. index:: - single: -fsimpl-tick-factor + Set the number of phases for the simplifier. Ignored with ``-O0``. - *default: 100.* GHC's optimiser can diverge if you write rewrite rules +.. ghc-flag:: -fsimpl-tick-factor=<n> + + :default: 100 + + GHC's optimiser can diverge if you write rewrite rules (:ref:`rewrite-rules`) that don't terminate, or (less satisfactorily) if you code up recursion through data types (:ref:`bugs-ghc`). To avoid making the compiler fall into an infinite loop, the optimiser @@ -503,18 +456,14 @@ list. more detailed list. Usually that identifies the loop quite accurately, because some numbers are very large. -``-fspec-constr`` - .. index:: - single: -fspec-constr +.. ghc-flag:: -fspec-constr *Off by default, but enabled by -O2.* Turn on call-pattern specialisation; see `Call-pattern specialisation for Haskell programs <http://research.microsoft.com/en-us/um/people/simonpj/papers/spec-constr/index.htm>`__. This optimisation specializes recursive functions according to their - argument "shapes". This is best explained by example so consider: - - :: + argument "shapes". This is best explained by example so consider: :: last :: [a] -> a last [] = error "last" @@ -523,9 +472,7 @@ list. 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: - - :: + such ``-fspec-constr`` will transform the above code to: :: last :: [a] -> a last [] = error "last" @@ -545,9 +492,7 @@ list. 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: - - :: + ``vector`` library: :: import GHC.Types (SPEC(..)) @@ -573,52 +518,50 @@ list. body directly, allowing heavy specialisation over the recursive cases. -``-fspec-constr-count=n`` - .. index:: - single: -fspec-constr-count +.. ghc-flag:: -fspec-constr-count=<n> + + :default: 3 - *default: 3.* Set the maximum number of specialisations that will be created for + Set the maximum number of specialisations that will be created for any one function by the SpecConstr transformation. -``-fspec-constr-threshold=n`` - .. index:: - single: -fspec-constr-threshold +.. ghc-flag:: -fspec-constr-threshold=<n> - *default: 2000.* Set the size threshold for the SpecConstr transformation. + :default: 2000 -``-fspecialise`` - .. index:: - single: -fspecialise + Set the size threshold for the SpecConstr transformation. + +.. ghc-flag:: -fspecialise + + :default: on - *On by default.* Specialise each type-class-overloaded function + 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`` is set imported functions + module. If :ghc-flag:`-fcross-module-specialise` is set imported functions that have an INLINABLE pragma (:ref:`inlinable-pragma`) will be specialised as well. -``-fcross-module-specialise`` - .. index:: - single: -fcross-module-specialise +.. ghc-flag:: -fcross-module-specialise + + :default: on - *On by default.* Specialise ``INLINABLE`` (:ref:`inlinable-pragma`) + Specialise ``INLINABLE`` (:ref:`inlinable-pragma`) 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. -``-fstatic-argument-transformation`` - .. index:: - single: -fstatic-argument-transformation +.. ghc-flag:: -fstatic-argument-transformation 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 <http://research.microsoft.com/en-us/um/people/simonpj/papers/santos-thesis.ps.gz>`__ -``-fstrictness`` - .. index:: - single: -fstrictness +.. ghc-flag:: -fstrictness - *On by default.*. Switch on the strictness analyser. There is a very + :default: on + + Switch on the strictness analyser. There is a very old paper about GHC's strictness analyser, `Measuring the effectiveness of a simple strictness analyser <http://research.microsoft.com/en-us/um/people/simonpj/papers/simple-strictnes-analyser.ps.gz>`__, @@ -631,27 +574,25 @@ list. they change the semantics of the program when applied to lazy arguments. -``-fstrictness-before=⟨n⟩`` - .. index:: - single: -fstrictness-before +.. ghc-flag:: -fstrictness-before=⟨n⟩ Run an additional strictness analysis before simplifier phase ⟨n⟩. -``-funbox-small-strict-fields`` +.. ghc-flag:: -funbox-small-strict-fields + + :default: on + .. index:: - single: -funbox-small-strict-fields single: strict constructor fields single: constructor fields, strict - *On by default.*. This option causes all constructor fields which + 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 :ref:`unpack-pragma`) to every strict constructor field that fulfils the size restriction. - For example, the constructor fields in the following data types - - :: + For example, the constructor fields in the following data types :: data A = A !Int data B = B !A @@ -672,14 +613,14 @@ list. constructor fields are unpacked on 32-bit platforms, even though they are technically larger than a pointer on those platforms. -``-funbox-strict-fields`` +.. ghc-flag:: -funbox-strict-fields + .. index:: - single: -funbox-strict-fields single: strict constructor fields single: constructor fields, strict This option causes all constructor fields which are marked strict - (i.e. “!”) to be unpacked if possible. It is equivalent to adding an + (i.e. ``!``) to be unpacked if possible. It is equivalent to adding an ``UNPACK`` pragma to every strict constructor field (see :ref:`unpack-pragma`). @@ -690,75 +631,89 @@ list. it for certain constructor fields using the ``NOUNPACK`` pragma (see :ref:`nounpack-pragma`). -``-funfolding-creation-threshold=n`` +.. ghc-flag:: -funfolding-creation-threshold=<n> + + :default: 750 + .. index:: - single: -funfolding-creation-threshold single: inlining, controlling single: unfolding, controlling - *default: 750.* Governs the maximum size that GHC will allow a + 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: (a) nothing larger than this will be inlined (unless - it has an INLINE pragma); (b) nothing larger than this will be - spewed into an interface file. + Consequences: + + a. nothing larger than this will be inlined (unless it has an ``INLINE`` pragma) + b. nothing 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`` is more + times than faster code. The :ghc-flag:`-funfolding-use-threshold` is more useful. -``-funfolding-dict-discount=n`` +.. ghc-flag:: -funfolding-dict-discount=<n> + + :default: 30 + .. index:: - single: -funfolding-dict-discount single: inlining, controlling single: unfolding, controlling - Default: 30 + How eager should the compiler be to inline dictionaries? + +.. ghc-flag:: -funfolding-fun-discount=<n> + + :default: 60 -``-funfolding-fun-discount=n`` .. index:: - single: -funfolding-fun-discount single: inlining, controlling single: unfolding, controlling - Default: 60 + How eager should the compiler be to inline functions? + +.. ghc-flag:: -funfolding-keeness-factor=<n> + + :default: 1.5 -``-funfolding-keeness-factor=n`` .. index:: - single: -funfolding-keeness-factor single: inlining, controlling single: unfolding, controlling - Default: 1.5 + How eager should the compiler be to inline functions? + +.. ghc-flag:: -funfolding-use-threshold=<n> + + :default: 60 -``-funfolding-use-threshold=n`` .. index:: - single: -funfolding-use-threshold single: inlining, controlling single: unfolding, controlling - *default: 60.* This is the magic cut-off figure for unfolding (aka + 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`` + The difference between this and :ghc-flag:`-funfolding-creation-threshold` 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. -``-fvectorisation-avoidance`` +.. ghc-flag:: -fvectorisation-avoidance + + :default: on + .. index:: single: -fvectorisation-avoidance Part of :ref:`Data Parallel Haskell (DPH) <dph>`. - *On by default.* Enable the *vectorisation* avoidance optimisation. + Enable the *vectorisation* avoidance optimisation. This optimisation only works when used in combination with the ``-fvectorise`` transformation. @@ -767,13 +722,13 @@ list. modifies the vectorisation transformation to try to determine if a function would be better of unvectorised and if so, do just that. -``-fvectorise`` - .. index:: - single: -fvectorise +.. ghc-flag:: -fvectorise + + :default: off Part of :ref:`Data Parallel Haskell (DPH) <dph>`. - *Off by default.* Enable the *vectorisation* optimisation + Enable the *vectorisation* optimisation transformation. This optimisation transforms the nested data parallelism code of programs using DPH into flat data parallelism. Flat data parallel programs should have better load balancing, diff --git a/docs/users_guide/using-warnings.rst b/docs/users_guide/using-warnings.rst index bc126887fc..7c9c944a4a 100644 --- a/docs/users_guide/using-warnings.rst +++ b/docs/users_guide/using-warnings.rst @@ -11,77 +11,76 @@ GHC has a number of options that select which types of non-fatal error messages, otherwise known as warnings, can be generated during compilation. By default, you get a standard set of warnings which are generally likely to indicate bugs in your program. These are: -``-Woverlapping-patterns``, ``-Wwarnings-deprecations``, -``-Wdeprecated-flags``, ``-Wunrecognised-pragmas``, -``-Wmissed-specialisations``, ``-Wduplicate-constraints``, -``-Wduplicate-exports``, ``-Woverflowed-literals``, -``-Wempty-enumerations``, ``-Wmissing-fields``, -``-Wmissing-methods``, ``-Wwrong-do-bind``, -``-Wunsupported-calling-conventions``, -``-Wdodgy-foreign-imports``, ``-Winline-rule-shadowing``, -``-Wunsupported-llvm-version`` and ``-Wtabs``. The following flags are -simple ways to select standard “packages” of warnings: -``-W`` - .. index:: - single: -W option - - Provides the standard warnings plus ``-Wunused-binds``, - ``-Wunused-matches``, ``-Wunused-imports``, - ``-Wincomplete-patterns``, ``-Wdodgy-exports``, and - ``-Wdodgy-imports``. - -``-Wall`` - .. index:: - single: -Wall +.. hlist:: + :columns: 3 + + * :ghc-flag:`-Woverlapping-patterns` + * :ghc-flag:`-Wwarnings-deprecations` + * :ghc-flag:`-Wdeprecated-flags` + * :ghc-flag:`-Wunrecognised-pragmas` + * :ghc-flag:`-Wmissed-specialisations` + * :ghc-flag:`-Wduplicate-constraints` + * :ghc-flag:`-Wduplicate-exports` + * :ghc-flag:`-Woverflowed-literals` + * :ghc-flag:`-Wempty-enumerations` + * :ghc-flag:`-Wmissing-fields` + * :ghc-flag:`-Wmissing-methods` + * :ghc-flag:`-Wwrong-do-bind` + * :ghc-flag:`-Wunsupported-calling-conventions` + * :ghc-flag:`-Wdodgy-foreign-imports` + * :ghc-flag:`-Winline-rule-shadowing` + * :ghc-flag:`-Wunsupported-llvm-version` + * :ghc-flag:`-Wtabs` + +The following flags are simple ways to select standard "packages" of warnings: + +.. ghc-flag:: -W + + Provides the standard warnings plus :ghc-flag:`-Wunused-binds`, + :ghc-flag:`-Wunused-matches`, :ghc-flag:`-Wunused-imports`, + :ghc-flag:`-Wincomplete-patterns`, :ghc-flag:`-Wdodgy-exports`, and + :ghc-flag:`-Wdodgy-imports`. + +.. ghc-flag:: -Wall Turns on all warning options that indicate potentially suspicious - code. The warnings that are *not* enabled by ``-Wall`` are - ``-Wincomplete-uni-patterns``, - ``-Wincomplete-record-updates``, - ``-Wmonomorphism-restriction``, - ``-Wimplicit-prelude``, ``-Wmissing-local-sigs``, - ``-Wmissing-exported-sigs``, ``-Wmissing-import-lists`` - and ``-Widentities``. + code. The warnings that are *not* enabled by :ghc-flag:`-Wall` are + :ghc-flag:`-Wincomplete-uni-patterns`, + :ghc-flag:`-Wincomplete-record-updates`, + :ghc-flag:`-Wmonomorphism-restriction`, + :ghc-flag:`-Wimplicit-prelude`, :ghc-flag:`-Wmissing-local-sigs`, + :ghc-flag:`-Wmissing-exported-sigs`, :ghc-flag:`-Wmissing-import-lists` + and :ghc-flag:`-Widentities`. -``-Wcompat`` - .. index:: - single: -Wcompat +.. ghc-flag:: -Wcompat Turns on warnings that will be enabled by default in the future, but remain off in normal compilations for the time being. This allows library authors eager to make their code future compatible to adapt to new features before they even generate warnings. - This currently enables ``-Wmissing-monadfail-instance``, - ``-Wsemigroup``, and ``-Wnoncanonical-monoid-instances``. + This currently enables :ghc-flag:`-Wmissing-monadfail-instance`, + :ghc-flag:`-Wsemigroup`, and :ghc-flag:`-Wnoncanonical-monoid-instances`. -``-Wno-compat`` - .. index:: - single: -Wno-compat +.. ghc-flag:: -Wno-compat - Disables all warnings enabled by ``-Wcompat``. + Disables all warnings enabled by :ghc-flag:`-Wcompat`. -``-w`` - .. index:: - single: -w +.. ghc-flag:: -w Turns off all warnings, including the standard ones and those that - ``-Wall`` doesn't enable. + :ghc-flag:`-Wall` doesn't enable. -``-Werror`` - .. index:: - single: -Werror +.. ghc-flag:: -Werror Makes any warning into a fatal error. Useful so that you don't miss warnings when doing batch compilation. -``-Wwarn`` - .. index:: - single: -Wwarn +.. ghc-flag:: -Wwarn Warnings are treated only as warnings, not as errors. This is the - default, but can be useful to negate a ``-Werror`` flag. + default, but can be useful to negate a :ghc-flag:`-Werror` flag. The full set of warning options is described below. To turn off any warning, simply give the corresponding ``-Wno-...`` option on the @@ -89,10 +88,7 @@ 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-)*``. -``-Wtyped-holes`` - .. index:: - single: -Wtyped-holes - single: warnings +.. ghc-flag:: -Wtyped-holes Determines whether the compiler reports typed holes warnings. Has no effect unless typed holes errors are deferred until runtime. See @@ -100,20 +96,14 @@ of ``-W(no-)*``. This warning is on by default. -``-Wtype-errors`` - .. index:: - single: -Wtype-errors - single: warnings +.. ghc-flag:: -Wtype-errors Causes a warning to be reported when a type error is deferred until runtime. See :ref:`defer-type-errors` This warning is on by default. -``-fdefer-type-errors`` - .. index:: - single: -fdefer-type-errors - single: warnings +.. ghc-flag:: -fdefer-type-errors 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 @@ -121,47 +111,34 @@ of ``-W(no-)*``. can run any type-correct parts of your code just fine. See :ref:`defer-type-errors` -``-fdefer-typed-holes`` - .. index:: - single: -fdefer-typed-holes - single: warnings +.. ghc-flag:: -fdefer-typed-holes Defer typed holes errors until runtime. This will turn the errors produced by :ref:`typed holes <typed-holes>` into warnings. Using a value that depends on a typed hole produces a runtime error, the same as - ``-fdefer-type-errors`` (which implies this option). See :ref:`typed-holes` + :ghc-flag:`-fdefer-type-errors` (which implies this option). See :ref:`typed-holes` and :ref:`defer-type-errors`. - Implied by ``-fdefer-type-errors``. See also ``-Wtyped-holes``. + Implied by :ghc-flag:`-fdefer-type-errors`. See also :ghc-flag:`-Wtyped-holes`. -``-Wpartial-type-signatures`` - .. index:: - single: -Wpartial-type-signatures - single: warnings +.. ghc-flag:: -Wpartial-type-signatures Determines whether the compiler reports holes in partial type signatures as warnings. Has no effect unless - ``-XPartialTypeSignatures`` is enabled, which controls whether + :ghc-flag:`-XPartialTypeSignatures` is enabled, which controls whether errors should be generated for holes in types or not. See :ref:`partial-type-signatures`. This warning is on by default. -``-fhelpful-errors`` - .. index:: - single: -fhelpful-errors - single: warnings +.. ghc-flag:: -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`` - .. index:: - single: -Wunrecognised-pragmas - single: warnings - single: pragmas +.. ghc-flag:: -Wunrecognised-pragmas 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 @@ -170,12 +147,8 @@ of ``-W(no-)*``. This option is on by default. -``-Wmissed-specialisations``, ``-Wall-missed-specialisations`` - .. index:: - single: -Wmissed-specialisations - single: -Wall-missed-specialisations - single: warnings - single: pragmas +.. ghc-flag:: -Wmissed-specialisations + -Wall-missed-specialisations Emits a warning if GHC cannot specialise an overloaded function, usually because the function needs an ``INLINEABLE`` pragma. The "all" form reports @@ -188,11 +161,10 @@ of ``-W(no-)*``. These options are both off by default. -``-Wwarnings-deprecations`` +.. ghc-flag:: -Wwarnings-deprecations + .. index:: - single: -Wwarnings-deprecations - single: warnings - single: deprecations + pair: deprecations; warnings Causes a warning to be emitted when a module, function or type with a ``WARNING`` or ``DEPRECATED pragma`` is used. See @@ -200,9 +172,9 @@ of ``-W(no-)*``. This option is on by default. -``-Wamp`` +.. ghc-flag:: -Wamp + .. index:: - single: -Wamp single: AMP single: Applicative-Monad Proposal @@ -211,9 +183,7 @@ of ``-W(no-)*``. Caused a warning to be emitted when a definition was in conflict with the AMP (Applicative-Monad proosal). -``-Wnoncanonical-monad-instances`` - .. index:: - single: -Wnoncanonical-monad-instances +.. ghc-flag:: -Wnoncanonical-monad-instances Warn if noncanonical ``Applicative`` or ``Monad`` instances declarations are detected. @@ -233,9 +203,7 @@ of ``-W(no-)*``. This option is off by default. -``-Wnoncanonical-monoid-instances`` - .. index:: - single: -Wnoncanonical-monoid-instances +.. ghc-flag:: -Wnoncanonical-monoid-instances Warn if noncanonical ``Semigroup`` or ``Monoid`` instances declarations are detected. @@ -253,70 +221,62 @@ of ``-W(no-)*``. * Warn if ``(<>)`` is defined backwards (i.e. ``(<>) = mappend``). This warning is off by default. However, it is part of the - ``-Wcompat`` option group. + :ghc-flag:`-Wcompat` option group. + +.. ghc-flag:: -Wmissing-monadfail-instance -``-Wmissing-monadfail-instance`` .. index:: - single: -Wmissing-monadfail-instance single: MFP single: MonadFail Proposal Warn when a failable pattern is used in a do-block that does not have a ``MonadFail`` instance. - Being part of the ``-Wcompat`` option group, this warning is off by + Being part of the :ghc-flag:`-Wcompat` option group, this warning is off by default, but will be switched on in a future GHC release, as part of the `MonadFail Proposal (MFP) <https://prime.haskell.org/wiki/Libraries/Proposals/MonadFail>`__. -``-Wsemigroup`` +.. ghc-flag:: -Wsemigroup + .. index:: - single: -Wsemigroup - single: semigroup + single: semigroup; warning Warn when definitions are in conflict with the future inclusion of ``Semigroup`` into the standard typeclasses. - 1. Instances of ``Monoid`` should also be instances of ``Semigroup`` - 2. The ``Semigroup`` operator ``(<>)`` will be in ``Prelude``, which - clashes with custom local definitions of such an operator + 1. Instances of ``Monoid`` should also be instances of ``Semigroup`` + 2. The ``Semigroup`` operator ``(<>)`` will be in ``Prelude``, which + clashes with custom local definitions of such an operator - Being part of the ``-Wcompat`` option group, this warning is off by + Being part of the :ghc-flag:`-Wcompat` option group, this warning is off by default, but will be switched on in a future GHC release. -``-Wdeprecated-flags`` +.. ghc-flag:: -Wdeprecated-flags + .. index:: - single: -Wdeprecated-flags - single: deprecated-flags + single: deprecated flags Causes a warning to be emitted when a deprecated command-line flag is used. This option is on by default. -``-Wunsupported-calling-conventions`` - .. index:: - single: -Wunsupported-calling-conventions +.. ghc-flag:: -Wunsupported-calling-conventions 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`` - .. index:: - single: -Wdodgy-foreign-imports +.. ghc-flag:: -Wdodgy-foreign-imports Causes a warning to be emitted for foreign imports of the following - form: - - :: + form: :: foreign import "f" f :: FunPtr t - on the grounds that it probably should be - - :: + on the grounds that it probably should be :: foreign import "&f" f :: FunPtr t @@ -327,9 +287,7 @@ of ``-W(no-)*``. that is hard to debug because it results in a crash, hence this warning. -``-Wdodgy-exports`` - .. index:: - single: -Wdodgy-exports +.. ghc-flag:: -Wdodgy-exports Causes a warning to be emitted when a datatype ``T`` is exported with all constructors, i.e. ``T(..)``, but is it just a type @@ -338,9 +296,7 @@ of ``-W(no-)*``. Also causes a warning to be emitted when a module is re-exported, but that module exports nothing. -``-Wdodgy-imports`` - .. index:: - single: -Wdodgy-imports +.. ghc-flag:: -Wdodgy-imports Causes a warning to be emitted in the following cases: @@ -350,54 +306,44 @@ of ``-W(no-)*``. - When an ``import`` statement hides an entity that is not exported. -``-Woverflowed-literals`` - .. index:: - single: -Woverflowed-literals +.. ghc-flag:: -Woverflowed-literals Causes a warning to be emitted if a literal will overflow, e.g. ``300 :: Word8``. -``-Wempty-enumerations`` - .. index:: - single: -Wempty-enumerations +.. ghc-flag:: -Wempty-enumerations Causes a warning to be emitted if an enumeration is empty, e.g. ``[5 .. 3]``. -``-Wlazy-unlifted-bindings`` - .. index:: - single: -Wlazy-unlifted-bindings +.. ghc-flag:: -Wlazy-unlifted-bindings This flag is a no-op, and will be removed in GHC 7.10. -``-Wduplicate-constraints`` +.. ghc-flag:: -Wduplicate-constraints + .. index:: - single: -Wduplicate-constraints single: duplicate constraints, warning Have the compiler warn about duplicate constraints in a type - signature. For example - - :: + signature. For example :: f :: (Eq a, Show a, Eq a) => a -> a The warning will indicate the duplicated ``Eq a`` constraint. This option is now deprecated in favour of - ``-Wredundant-constraints``. + :ghc-flag:`-Wredundant-constraints`. + +.. ghc-flag:: -Wredundant-constraints -``-Wredundant-constraints`` .. index:: - single: -Wredundant-constraints single: redundant constraints, warning Have the compiler warn about redundant constraints in a type signature. In particular: - - A redundant constraint within the type signature itself: - - :: + - A redundant constraint within the type signature itself: :: f :: (Eq a, Ord a) => a -> a @@ -405,9 +351,7 @@ of ``-W(no-)*``. is subsumed by the ``Ord a`` constraint. - A constraint in the type signature is not used in the code it - covers: - - :: + covers: :: f :: Eq a => a -> a -> Bool f x y = True @@ -419,14 +363,12 @@ of ``-W(no-)*``. declaration. This option is on by default. As usual you can suppress it on a - per-module basis with ``-Wno-redundant-constraints``. + per-module basis with :ghc-flag:`-Wno-redundant-constraints`. 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: - - :: + basis, using a call in a dead binding. For example: :: f :: Eq a => a -> a -> Bool f x y = True @@ -436,9 +378,9 @@ of ``-W(no-)*``. Here the call to ``(==)`` makes GHC think that the ``(Eq a)`` constraint is needed, so no warning is issued. -``-Wduplicate-exports`` +.. ghc-flag:: -Wduplicate-exports + .. index:: - single: -Wduplicate-exports single: duplicate exports, warning single: export lists, duplicates @@ -449,37 +391,35 @@ of ``-W(no-)*``. This option is on by default. -``-Whi-shadowing`` +.. ghc-flag:: -Whi-shadowing + .. index:: - single: -Whi-shadowing single: shadowing; interface files 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. -``-Widentities`` - .. index:: - single: -Widentities +.. ghc-flag:: -Widentities Causes the compiler to emit a warning when a Prelude numeric - conversion converts a type T to the same type T; such calls are + 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-prelude`` +.. ghc-flag:: -Wimplicit-prelude + .. index:: - single: -Wimplicit-prelude single: implicit prelude, warning 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 ``-XNoImplicitPrelude`` or a + disabled (either by :ghc-flag:`-XNoImplicitPrelude` or a ``LANGUAGE NoImplicitPrelude`` pragma). Note that no warning is given for syntax that implicitly refers to - the Prelude, even if ``-XNoImplicitPrelude`` would change whether it + the Prelude, even if :ghc-flag:`-XNoImplicitPrelude` would change whether it refers to the Prelude. For example, no warning is given when ``368`` means ``Prelude.fromInteger (368::Prelude.Integer)`` (where ``Prelude`` refers to the actual Prelude module, regardless of the @@ -487,47 +427,41 @@ of ``-W(no-)*``. This warning is off by default. -``-Wincomplete-patterns``, ``-Wincomplete-uni-patterns`` +.. ghc-flag:: -Wincomplete-patterns + -Wincomplete-uni-patterns + .. index:: - single: -Wincomplete-patterns - single: -Wincomplete-uni-patterns single: incomplete patterns, warning single: patterns, incomplete - The option ``-Wincomplete-patterns`` warns about places where a + The option :ghc-flag:`-Wincomplete-patterns` 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`` is enabled. - - :: + warning about this when :ghc-flag:`-Wincomplete-patterns` 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``. + functions, and it is switched on by :ghc-flag:`-W`. - The flag ``-Wincomplete-uni-patterns`` is similar, except that + The flag :ghc-flag:`-Wincomplete-uni-patterns` is similar, except that it applies only to lambda-expressions and pattern bindings, - constructs that only allow a single pattern: - - :: + constructs that only allow a single pattern: :: h = \[] -> 2 Just k = f y -``-Wincomplete-record-updates`` +.. ghc-flag:: -Wincomplete-record-updates + .. index:: - single: -Wincomplete-record-updates single: incomplete record updates, warning single: record updates, incomplete The function ``f`` below will fail when applied to ``Bar``, so the compiler will emit a warning about this when - ``-Wincomplete-record-updates`` is enabled. - - :: + :ghc-flag:`-Wincomplete-record-updates` is enabled. :: data Foo = Foo { x :: Int } | Bar @@ -538,40 +472,41 @@ of ``-W(no-)*``. This option isn't enabled by default because it can be very noisy, and it often doesn't indicate a bug in the program. -``-Wtoo-many-guards`` +.. ghc-flag:: -Wtoo-many-guards + -Wno-too-many-guards + .. index:: - single: -Wtoo-many-guards single: too many guards, warning - The option ``-Wtoo-many-guards`` warns about places where a + The option :ghc-flag:`-Wtoo-many-guards` warns about places where a pattern match contains too many guards (over 20 at the moment). It has an effect only if any form of exhaustivness/overlapping checking is enabled (one of - ``-Wincomplete-patterns``, - ``-Wincomplete-uni-patterns``, - ``-Wincomplete-record-updates``, - ``-Woverlapping-patterns``). When enabled, the warning can be - suppressed by enabling either ``-Wno-too-many-guards``, which just - hides the warning, or ``-ffull-guard-reasoning`` which runs the + :ghc-flag:`-Wincomplete-patterns`, + :ghc-flag:`-Wincomplete-uni-patterns`, + :ghc-flag:`-Wincomplete-record-updates`, + :ghc-flag:`-Woverlapping-patterns`). When enabled, the warning can be + suppressed by enabling either :ghc-flag:`-Wno-too-many-guards`, which just + hides the warning, or :ghc-flag:`-ffull-guard-reasoning` which runs the full check, independently of the number of guards. -``-ffull-guard-reasoning`` +.. ghc-flag:: -ffull-guard-reasoning + .. index:: - single: -ffull-guard-reasoning single: guard reasoning, warning - The option ``-ffull-guard-reasoning`` forces pattern match checking + The option :ghc-flag:`-ffull-guard-reasoning` forces pattern match checking to run in full. This gives more precise warnings concerning pattern guards but in most cases increases memory consumption and compilation time. Hence, it is off by default. Enabling - ``-ffull-guard-reasoning`` also implies ``-Wno-too-many-guards``. - Note that (like ``-Wtoo-many-guards``) ``-ffull-guard-reasoning`` + :ghc-flag:`-ffull-guard-reasoning` also implies :ghc-flag:`-Wno-too-many-guards`. + Note that (like :ghc-flag:`-Wtoo-many-guards`) :ghc-flag:`-ffull-guard-reasoning` makes a difference only if pattern match checking is already enabled. -``-Wmissing-fields`` +.. ghc-flag:: -Wmissing-fields + .. index:: - single: -Wmissing-fields single: missing fields, warning single: fields, missing @@ -581,17 +516,15 @@ of ``-W(no-)*``. fields are initialised with bottoms), it is often an indication of a programmer error. -``-Wmissing-import-lists`` +.. ghc-flag:: -Wmissing-import-lists + .. index:: - single: -Wimport-lists single: missing import lists, warning single: import lists, missing This flag warns if you use an unqualified ``import`` declaration that does not explicitly list the entities brought into scope. For - example - - :: + example :: module M where import X( f ) @@ -599,15 +532,15 @@ of ``-W(no-)*``. import qualified Z p x = f x x - The ``-Wimport-lists`` 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``. + The :ghc-flag:`-Wmissing-import-lists` 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``. + +.. ghc-flag:: -Wmissing-methods -``-Wmissing-methods`` .. index:: - single: -Wmissing-methods single: missing methods, warning single: methods, missing @@ -616,9 +549,7 @@ of ``-W(no-)*``. class declaration has no default declaration for them. The warning is suppressed if the method name begins with an - underscore. Here's an example where this is useful: - - :: + underscore. Here's an example where this is useful: :: class C a where _simpleFn :: a -> String @@ -633,51 +564,51 @@ of ``-W(no-)*``. methods will be required for instances of a particular class. See :ref:`minimal-pragma`. -``-Wmissing-signatures`` +.. ghc-flag:: -Wmissing-signatures + .. index:: - single: -Wmissing-signatures single: type signatures, missing If you would like GHC to check that every top-level function/value - has a type signature, use the ``-Wmissing-signatures`` option. + has a type signature, use the :ghc-flag:`-Wmissing-signatures` option. As part of the warning GHC also reports the inferred type. The option is off by default. -``-Wmissing-exported-sigs`` +.. ghc-flag:: -Wmissing-exported-sigs + .. index:: - single: -Wmissing-exported-sigs single: type signatures, missing 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-sigs`` option. This option - takes precedence over ``-Wmissing-signatures``. As part of the + values, use the :ghc-flag:`-Wmissing-exported-sigs` option. This option + takes precedence over :ghc-flag:`-Wmissing-signatures`. As part of the warning GHC also reports the inferred type. The option is off by default. -``-Wmissing-local-sigs`` +.. ghc-flag:: -Wmissing-local-sigs + .. index:: - single: -Wmissing-local-sigs single: type signatures, missing - If you use the ``-Wmissing-local-sigs`` flag GHC will warn you + If you use the :ghc-flag:`-Wmissing-local-sigs` 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-pat-syn-sigs`` - .. index :: - single: -Wmissing-pat-syn-sigs - single: type signatures, missing, pattern synonyms +.. ghc-flag:: -Wmissing-pat-syn-sigs + + .. index:: + single: type signatures, missing, pattern synonyms + + If you would like GHC to check that every pattern synonym has a type + signature, use the :ghc-flag:`-Wmissing-pat-syn-sigs` option. If this option is + used in conjunction with :ghc-flag:`-Wmissing-exported-sigs` then only + exported pattern synonyms must have a type signature. GHC also reports the + inferred type. This option is off by default. - If you would like GHC to check that every pattern synonym has a type - signature, use the ``-Wmissing-pat-syn-sigs`` option. If this option is - used in conjunction with ``-Wmissing-exported-sigs`` then only - exported pattern synonyms must have a type signature. GHC also reports the - inferred type. This option is off by default. +.. ghc-flag:: -Wname-shadowing -``-Wname-shadowing`` .. index:: - single: -Wname-shadowing single: shadowing, warning This option causes a warning to be emitted whenever an inner-scope @@ -688,15 +619,13 @@ of ``-W(no-)*``. ``f = ... let f = id in ... f ...``. The warning is suppressed for names beginning with an underscore. - For example - - :: + For example :: f x = do { _ignore <- this; _ignore <- that; return (the other) } -``-Worphans`` +.. ghc-flag:: -Worphans + .. index:: - single: -Worphans single: orphan instances, warning single: orphan rules, warning @@ -713,19 +642,17 @@ of ``-W(no-)*``. or rules play a role, whether or not the module's interface would otherwise be of any use. See :ref:`orphan-modules` for details. - The flag ``-Worphans`` warns about user-written orphan rules or + The flag :ghc-flag:`-Worphans` warns about user-written orphan rules or instances. -``-Woverlapping-patterns`` +.. ghc-flag:: -Woverlapping-patterns + .. index:: - single: -Woverlapping-patterns single: overlapping patterns, warning single: patterns, overlapping By default, the compiler will warn you if a set of patterns are - overlapping, e.g., - - :: + overlapping, e.g., :: f :: String -> Int f [] = 0 @@ -736,16 +663,16 @@ of ``-W(no-)*``. second pattern overlaps it. More often than not, redundant patterns is a programmer mistake/error, so this option is enabled by default. -``-Wtabs`` +.. ghc-flag:: -Wtabs + .. index:: - single: -Wtabs single: tabs, warning Have the compiler warn if there are tabs in your source file. -``-Wtype-defaults`` +.. ghc-flag:: -Wtype-defaults + .. index:: - single: -Wtype-defaults single: defaulting mechanism, warning Have the compiler warn/inform you where in your source the Haskell @@ -759,9 +686,9 @@ of ``-W(no-)*``. This warning is off by default. -``-Wmonomorphism-restriction`` +.. ghc-flag:: -Wmonomorphism-restriction + .. index:: - single: -Wmonomorphism-restriction single: monomorphism restriction, warning Have the compiler warn/inform you where in your source the Haskell @@ -771,17 +698,19 @@ of ``-W(no-)*``. This warning is off by default. -``-Wunticked-promoted-constructors`` +.. ghc-flag:: -Wunsupported-llvm-version + + Warn when using :ghc-flag:`-fllvm` with an unsupported version of LLVM. + +.. ghc-flag:: -Wunticked-promoted-constructors + .. index:: - single: -Wunticked-promoted-constructors single: promoted constructor, warning Warn if a promoted data constructor is used without a tick preceding its name. - For example: - - :: + For example: :: data Nat = Succ Nat | Zero @@ -792,24 +721,24 @@ of ``-W(no-)*``. Will raise two warnings because ``Zero`` and ``Succ`` are not written as ``'Zero`` and ``'Succ``. - This warning is is enabled by default in ``-Wall`` mode. + This warning is is enabled by default in :ghc-flag:`-Wall` mode. + +.. ghc-flag:: -Wunused-binds -``-Wunused-binds`` .. index:: - single: -Wunused-binds single: unused binds, warning single: binds, unused Report any function definitions (and local bindings) which are unused. An alias for - - ``-Wunused-top-binds`` - - ``-Wunused-local-binds`` - - ``-Wunused-pattern-binds`` + - :ghc-flag:`-Wunused-top-binds` + - :ghc-flag:`-Wunused-local-binds` + - :ghc-flag:`-Wunused-pattern-binds` + +.. ghc-flag:: -Wunused-top-binds -``-Wunused-top-binds`` .. index:: - single: -Wunused-top-binds single: unused binds, warning single: binds, unused @@ -827,9 +756,7 @@ of ``-W(no-)*``. - It appears in the right hand side of a binding that binds at least one used variable that is used - For example - - :: + For example: :: module A (f) where f = let (p,q) = rhs1 in t p -- No warning: q is unused, but is locally bound @@ -839,30 +766,26 @@ of ``-W(no-)*``. -- right-hand side of another unused binding _w = True -- No warning: _w starts with an underscore -``-Wunused-local-binds`` +.. ghc-flag:: -Wunused-local-binds + .. index:: - single: -Wunused-local-binds single: unused binds, warning single: binds, unused - Report any local definitions which are unused. For example - - :: + Report any local definitions which are unused. For example: :: module A (f) where f = let (p,q) = rhs1 in t p -- Warning: q is unused g = h x -- No warning: g is unused, but is a top-level binding -``-Wunused-pattern-binds`` +.. ghc-flag:: -Wunused-pattern-binds + .. index:: - single: -Wunused-pattern-binds single: unused binds, warning single: binds, unused Warn if a pattern binding binds no variables at all, unless it is a - lone, possibly-banged, wild-card pattern. For example: - - :: + lone, possibly-banged, wild-card pattern. For example: :: Just _ = rhs3 -- Warning: unused pattern binding (_, _) = rhs4 -- Warning: unused pattern binding @@ -875,9 +798,9 @@ of ``-W(no-)*``. lone banged wild-card pattern is useful as an alternative (to ``seq``) way to force evaluation. -``-Wunused-imports`` +.. ghc-flag:: -Wunused-imports + .. index:: - single: -Wunused-imports single: unused imports, warning single: imports, unused @@ -886,9 +809,9 @@ of ``-W(no-)*``. import, because it is a useful idiom for importing instance declarations, which are anonymous in Haskell. -``-Wunused-matches`` +.. ghc-flag:: -Wunused-matches + .. index:: - single: -Wunused-matches single: unused matches, warning single: matches, unused @@ -896,15 +819,13 @@ of ``-W(no-)*``. including patterns consisting of a single variable. This includes unused type variables in type family instances. 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: - - :: + is suppressed if the variable name begins with an underscore, thus: :: f _x = True -``-Wunused-do-bind`` +.. ghc-flag:: -Wunused-do-bind + .. index:: - single: -Wunused-do-bind single: unused do binding, warning single: do binding, unused @@ -915,21 +836,17 @@ of ``-W(no-)*``. ``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: - - :: + something away: :: do { _ <- mapM popInt xs ; return 10 } - Of course, in this particular situation you can do even better: - - :: + Of course, in this particular situation you can do even better: :: do { mapM_ popInt xs ; return 10 } -``-Wwrong-do-bind`` +.. ghc-flag:: -Wwrong-do-bind + .. index:: - single: -Wwrong-do-bind single: apparently erroneous do binding, warning single: do binding, apparently erroneous @@ -941,28 +858,22 @@ of ``-W(no-)*``. 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: - - :: + something away: :: do { _ <- return (popInt 10) ; return 10 } For almost all sensible programs this will indicate a bug, and you - probably intended to write: - - :: + probably intended to write: :: do { popInt 10 ; return 10 } -``-Winline-rule-shadowing`` - .. index:: - single: -Winline-rule-shadowing +.. ghc-flag:: -Winline-rule-shadowing Warn if a rewrite RULE might fail to fire because the function might be inlined before the rule has a chance to fire. See :ref:`rules-inline`. -If you're feeling really paranoid, the ``-dcore-lint`` option is a good choice. +If you're feeling really paranoid, the :ghc-flag:`-dcore-lint` option is a good choice. It turns on heavyweight intra-pass sanity-checking within GHC. (It checks GHC's sanity, not yours.) diff --git a/docs/users_guide/using.rst b/docs/users_guide/using.rst index b936ea4de7..a600a133d9 100644 --- a/docs/users_guide/using.rst +++ b/docs/users_guide/using.rst @@ -18,25 +18,29 @@ 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 ``hello.hs`` containing the Haskell code: :: +create a file :file:`hello.hs` containing the Haskell code: :: main = putStrLn "Hello, World!" -To compile the program, use GHC like this: :: +To compile the program, use GHC like this: + +.. code-block:: sh $ ghc hello.hs (where ``$`` represents the prompt: don't type it). GHC will compile the -source file ``hello.hs``, producing an object file ``hello.o`` and an -interface file ``hello.hi``, and then it will link the object file to +source file :file:`hello.hs`, producing an object file :file:`hello.o` and an +interface file :file:`hello.hi`, 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 ``hello.exe`` on Windows. +:file:`hello` on Unix/Linux/Mac, or :file:`hello.exe` 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`` to the command line. +the scenes, add :ghc-flag:`-v` to the command line. + +Then we can run the program like this: -Then we can run the program like this: :: +.. code-block:: sh $ ./hello Hello World! @@ -66,7 +70,9 @@ Command-line arguments single: command-line; arguments single: arguments; command-line -An invocation of GHC takes the following form: :: +An invocation of GHC takes the following form: + +.. code-block:: none ghc [argument...] @@ -116,14 +122,14 @@ if you try to glob etc. inside ``OPTIONS_GHC``. 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`` and have ``OPTION`` flags in +is the Right Thing. (If you use :ghc-flag:`-keep-hc-file` and have ``OPTION`` flags in your module, the ``OPTIONS_GHC`` will get put into the generated ``.hc`` file). Setting options in GHCi ~~~~~~~~~~~~~~~~~~~~~~~ -Options may also be modified from within GHCi, using the ``:set`` -command. See :ref:`ghci-set` for more details. +Options may also be modified from within GHCi, using the :ghci-cmd:`:set` +command. .. _static-dynamic-flags: @@ -138,13 +144,13 @@ Static, Dynamic, and Mode options Each of GHC's command line options is classified as static, dynamic or mode: - For example, ``--make`` or ``-E``. There may only be a single mode + For example, :ghc-flag:`--make` or :ghc-flag:`-E`. There may only be a single mode flag on the command line. The available modes are listed in :ref:`modes`. Most non-mode flags fall into this category. A dynamic flag may be used on the command line, in a ``OPTIONS_GHC`` pragma in a source - file, or set using ``:set`` in GHCi. + file, or set using :ghci-cmd:`:set` in GHCi. A few flags are "static", which means they can only be used on the command-line, and remain in force over the entire GHC/GHCi run. @@ -153,7 +159,7 @@ The flag reference tables (:ref:`flag-reference`) lists the status of each flag. There are a few flags that are static except that they can also be used -with GHCi's ``:set`` command; these are listed as “static/\ ``:set``\ ” +with GHCi's :ghci-cmd:`:set` command; these are listed as “static/\ ``:set``\ ” in the table. .. _file-suffixes: @@ -216,39 +222,45 @@ Modes of operation 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. +option on the command-line. For instance, + +.. code-block:: none -If no mode flag is present, then GHC will enter make mode + $ ghc Main.hs --make -o my-application + +If no mode flag is present, then GHC will enter :ghc-flag:`--make` mode (:ref:`make-mode`) 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: -``ghc --interactive`` +.. ghc-flag:: --interactive + .. index:: single: interactive mode single: GHCi - Interactive mode, which is also available as ``ghci``. Interactive + Interactive mode, which is also available as :program:`ghci`. Interactive mode is described in more detail in :ref:`ghci`. -``ghc --make`` +.. ghc-flag:: --make + .. index:: single: make mode; of GHC - single: --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 + and faster, than using :command:`make`. Make mode is described in :ref:`make-mode`. This mode is the default if there are any Haskell source files - mentioned on the command line, and in this case the ``--make`` + mentioned on the command line, and in this case the :ghc-flag:`--make` option can be omitted. -``ghc -e`` ⟨expr⟩ +.. ghc-flag:: -e ⟨expr⟩ + .. index:: single: eval mode; of GHC @@ -257,18 +269,17 @@ The available mode flags are: which is given on the command line. See :ref:`eval-mode` for more details. -``ghc -E`` ``ghc -C`` ``ghc -S`` ``ghc -c`` - .. index:: - single: -E; GHC option - single: -C; GHC option - single: -S; GHC option - single: -c; GHC option +.. ghc-flag:: -E + -C + -S + -c 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 :ref:`options-order`. -``ghc -M`` +.. ghc-flag:: -M + .. index:: single: dependency-generation mode; of GHC @@ -276,62 +287,50 @@ The available mode flags are: generate dependency information suitable for use in a ``Makefile``. See :ref:`makefile-dependencies`. -``ghc --mk-dll`` +.. ghc-flag:: --mk-dll + .. index:: single: DLL-creation mode DLL-creation mode (Windows only). See :ref:`win32-dlls-create`. -``ghc --help``, ``ghc -?`` - .. index:: - single: --help; GHC option +.. ghc-flag:: --help + -? Cause GHC to spew a long usage message to standard output and then exit. -``ghc --show-iface ⟨file⟩`` - .. index:: - single: --show-iface; GHC option +.. ghc-flag:: --show-iface ⟨file⟩ Read the interface in ⟨file⟩ and dump it as text to ``stdout``. For example ``ghc --show-iface M.hi``. -``ghc --supported-extensions``, ``ghc --supported-languages`` - .. index:: - single: --supported-extensions; GHC option - single: --supported-languages; GHC option +.. ghc-flag:: --supported-extensions + --supported-languages Print the supported language extensions. -``ghc --show-options`` - .. index:: - single: --show-options; GHC option +.. ghc-flag:: --show-options Print the supported command line options. This flag can be used for autocompletion in a shell. -``ghc --info`` - .. index:: - single: --info +.. ghc-flag:: --info Print information about the compiler. -``ghc --version``, ``ghc -V`` - .. index:: - single: -V - single: --version +.. ghc-flag:: --version + -V Print a one-line string including GHC's version number. -``ghc --numeric-version`` - .. index:: - single: --numeric-version +.. ghc-flag:: --numeric-version Print GHC's numeric version number only. -``ghc --print-libdir`` +.. ghc-flag:: --print-libdir + .. index:: - single: --print-libdir single: libdir Print the path to GHC's library directory. This is the top of the @@ -351,14 +350,18 @@ Using ``ghc`` ``--make`` 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 ``Main.hs``, you -could compile and link the program like this: :: +example, if your ``Main`` module is in a file called :file:`Main.hs`, you +could compile and link the program like this: + +.. code-block:: none ghc --make Main.hs 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 :: +this case we could just type + +.. code-block:: none ghc Main.hs @@ -384,7 +387,7 @@ The main advantages to using ``ghc --make`` over traditional - GHC re-calculates the dependencies each time it is invoked, so the dependencies never get out of sync with the source. -- Using the ``-j`` flag, you can compile modules in parallel. Specify +- Using the :ghc-flag:`-j` flag, you can compile modules in parallel. Specify ``-j⟨N⟩`` to compile ⟨N⟩ jobs in parallel. Any of the command-line options described in the rest of this chapter @@ -398,7 +401,7 @@ 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``, the linking phase is omitted (same as +combination with :ghc-flag:`-c`, the linking phase is omitted (same as ``--make -no-link``). Note that GHC can only follow dependencies if it has the source file @@ -408,9 +411,15 @@ 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`` option can be used to add directories to the +directory; the :ghc-flag:`-i` option can be used to add directories to the search path (see :ref:`search-path`). +.. ghc-flag:: -j <N> + + Perform compilation in parallel when possible. GHC will use up to ⟨N⟩ + threads during compilation. Note that compilation of a module may not + begin until its dependencies have been built. + .. _eval-mode: Expression evaluation mode @@ -418,7 +427,9 @@ Expression evaluation mode 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: :: +an argument to the ``-e`` option: + +.. code-block:: none ghc -e expr @@ -427,12 +438,16 @@ 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 :: +``Main``, we might say: + +.. code-block:: none ghc -e Main.main Main.hs or we can just use this mode to evaluate expressions in the context of -the ``Prelude``: :: +the ``Prelude``: + +.. code-block:: none $ ghc -e "interact (unlines.map reverse.lines)" hello @@ -474,7 +489,7 @@ go all the way through to linking. This table summarises: Thus, a common invocation would be: -:: +.. code-block:: none ghc -c Foo.hs @@ -486,15 +501,15 @@ to compile the Haskell source file ``Foo.hs`` to an object file code generator is used. See :ref:`code-generators` for more details. .. note:: - Pre-processing is optional, the ``-cpp``\ ``-cpp`` flag turns it + Pre-processing is optional, the :ghc-flag:`-cpp` flag turns it on. See :ref:`c-pre-processor` for more details. .. note:: - The option ``-E`` runs just the pre-processing passes of + The option :ghc-flag:`-E` runs just the pre-processing passes of the compiler, dumping the result in a file. .. note:: - The option ``-C`` is only available when GHC is built in + The option :ghc-flag:`-C` is only available when GHC is built in unregisterised mode. See :ref:`unreg` for more details. .. _overriding-suffixes: @@ -503,11 +518,9 @@ Overriding the default behaviour for a file ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 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`` option: +on its suffix. This behaviour can be overridden using the :ghc-flag:`-x` option: -``-x``\ ⟨suffix⟩ - .. index:: - single: -x +.. ghc-flag:: -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 @@ -525,11 +538,9 @@ Verbosity options See also the ``--help``, ``--version``, ``--numeric-version``, and ``--print-libdir`` modes in :ref:`modes`. -``-v`` - .. index:: - single: -v +.. ghc-flag:: -v - The ``-v`` option makes GHC *verbose*: it reports its version number + The :ghc-flag:`-v` 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 @@ -539,9 +550,8 @@ See also the ``--help``, ``--version``, ``--numeric-version``, and Knowing that you ran the right bits in the right order is always the first thing we want to verify. -``-v⟨n⟩`` - .. index:: - single: -v +.. ghc-flag:: -v ⟨n⟩ + :noindex: To provide more control over the compiler's verbosity, the ``-v`` flag takes an optional numeric argument. Specifying ``-v`` on its @@ -569,26 +579,24 @@ See also the ``--help``, ``--version``, ``--numeric-version``, and representation after each compilation phase is also printed (excluding preprocessed and C/assembly files). -``--fprint-potential-instances`` - .. index:: - single: -fprint-potential-instances +.. ghc-flag:: --fprint-potential-instances When GHC can't find an instance for a class, it displays a short list of some in the instances it knows about. With this flag it prints *all* the instances it knows about. -``-fprint-explicit-foralls, -fprint-explicit-kinds, -fprint-unicode-syntax, -fprint-explicit-coercions, -fprint-equality-relations`` - .. index:: - single: -fprint-explicit-foralls - single: -fprint-explicit-kinds - single: -fprint-unicode-syntax - single: -fprint-explicit-coercions - single: -fprint-equality-relations - - These three flags control the way in which GHC displays types, in - error messages and in GHCi. Using ``-fprint-explicit-foralls`` makes +.. ghc-flag:: -fprint-explicit-foralls + -fprint-explicit-kinds + -fprint-unicode-syntax + -fprint-explicit-coercions + -fprint-equality-relations + + These flags control the way in which GHC displays types, in + error messages and in GHCi. Using :ghc-flag:`-fprint-explicit-foralls` makes GHC print explicit ``forall`` quantification at the top level of a - type; normally this is suppressed. For example, in GHCi: :: + type; normally this is suppressed. For example, in GHCi: + + .. code-block:: none ghci> let f x = x ghci> :t f @@ -600,13 +608,17 @@ See also the ``--help``, ``--version``, ``--numeric-version``, and However, regardless of the flag setting, the quantifiers are printed under these circumstances: - - For nested ``foralls``, e.g. :: + - For nested ``foralls``, e.g. + + .. code-block:: none ghci> :t GHC.ST.runST GHC.ST.runST :: (forall s. GHC.ST.ST s a) -> a - If any of the quantified type variables has a kind that mentions - a kind variable, e.g. :: + a kind variable, e.g. + + .. code-block:: none ghci> :i Data.Type.Equality.sym Data.Type.Equality.sym :: @@ -614,9 +626,11 @@ See also the ``--help``, ``--version``, ``--numeric-version``, and (a Data.Type.Equality.:~: b) -> b Data.Type.Equality.:~: a -- Defined in Data.Type.Equality - Using ``-fprint-explicit-kinds`` makes GHC print kind arguments in + Using :ghc-flag:`-fprint-explicit-kinds` makes GHC print kind arguments in types, which are normally suppressed. This can be important when you - are using kind polymorphism. For example: :: + are using kind polymorphism. For example: + + .. code-block:: none ghci> :set -XPolyKinds ghci> data T a = MkT @@ -626,32 +640,32 @@ See also the ``--help``, ``--version``, ``--numeric-version``, and ghci> :t MkT MkT :: forall (k :: BOX) (a :: k). T k a - When ``-fprint-unicode-syntax`` is enabled, GHC prints type + When :ghc-flag:`-fprint-unicode-syntax` is enabled, GHC prints type signatures using the unicode symbols from the ``-XUnicodeSyntax`` - extension. :: + extension. + + .. code-block:: none ghci> :set -fprint-unicode-syntax ghci> :t (>>) (>>) :: ∀ (m :: * → *) a b. Monad m ⇒ m a → m b → m b - Using ``-fprint-explicit-coercions`` makes GHC print coercions in + Using :ghc-flag:`-fprint-explicit-coercions` 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. - Using ``-fprint-equality-relations`` tells GHC to distinguish between + Using :ghc-flag:`-fprint-equality-relations` 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``, GHC + probably what you want. Without :ghc-flag:`-fprint-equality-relations`, GHC prints all of these as ``~``. -``-fprint-expanded-synonyms`` - .. index:: - single: -fprint-expanded-synonyms +.. ghc-flag:: -fprint-expanded-synonyms When enabled, GHC also prints type-synonym-expanded types in type errors. For example, with this type synonyms: :: @@ -660,13 +674,17 @@ See also the ``--help``, ``--version``, ``--numeric-version``, and type Bar = Bool type MyBarST s = ST s Bar - This error message: :: + This error message: + + .. code-block:: none Couldn't match type 'Int' with 'Bool' Expected type: ST s Foo Actual type: MyBarST s - Becomes this: :: + Becomes this: + + .. code-block:: none Couldn't match type 'Int' with 'Bool' Expected type: ST s Foo @@ -675,9 +693,7 @@ See also the ``--help``, ``--version``, ``--numeric-version``, and Expected type: ST s Int Actual type: ST s Bool -``-fprint-typechecker-elaboration`` - .. index:: - single: -fprint-typechecker-elaboration +.. ghc-flag:: -fprint-typechecker-elaboration When enabled, GHC also prints extra information from the typechecker in warnings. For example: :: @@ -687,14 +703,18 @@ See also the ``--help``, ``--version``, ``--numeric-version``, and return $ let a = "hello" in a return () - This warning message: :: + This warning message: + + .. code-block:: none A do-notation statement discarded a result of type ‘[Char]’ Suppress this warning by saying ‘_ <- ($) return let a = "hello" in a’ or by using the flag -fno-warn-unused-do-bind - Becomes this: :: + Becomes this: + + .. code-block:: none A do-notation statement discarded a result of type ‘[Char]’ Suppress this warning by saying @@ -710,23 +730,27 @@ See also the ``--help``, ``--version``, ``--numeric-version``, and in a’ or by using the flag -fno-warn-unused-do-bind -``-ferror-spans`` - .. index:: - single: -ferror-spans +.. ghc-flag:: -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: :: + For example: + + .. code-block:: none test.hs:3:6: parse error on input `where' - becomes: :: + becomes: + + .. code-block:: none test296.hs:3:6-10: parse error on input `where' - And multi-line spans are possible too: :: + And multi-line spans are possible too: + + .. code-block:: none test.hs:(5,4)-(6,7): Conflicting definitions for `a' @@ -738,16 +762,12 @@ See also the ``--help``, ``--version``, ``--numeric-version``, and start at zero. This choice was made to follow existing convention (i.e. this is how Emacs does it). -``-H⟨size⟩`` - .. index:: - single: -H +.. ghc-flag:: -H <size> Set the minimum size of the heap to ⟨size⟩. This option is equivalent to ``+RTS -Hsize``, see :ref:`rts-options-gc`. -``-Rghc-timing`` - .. index:: - single: -Rghc-timing +.. ghc-flag:: -Rghc-timing Prints a one-line summary of timing statistics for the GHC run. This option is equivalent to ``+RTS -tstderr``, see @@ -765,7 +785,8 @@ Platform-specific Flags Some flags only make sense for particular target platforms. -``-msse2`` +.. ghc-flag:: -msse2 + (x86 only, added in GHC 7.0.1) Use the SSE2 registers and instruction set to implement floating point operations when using the :ref:`native code generator <native-code-gen>`. This gives a @@ -778,7 +799,9 @@ Some flags only make sense for particular target platforms. SSE2 is unconditionally used on x86-64 platforms. -``-msse4.2`` +.. ghc-flag:: -msse4.2 + :noindex: + (x86 only, added in GHC 7.4.1) Use the SSE4.2 instruction set to implement some floating point and bit operations when using the :ref:`native code generator <native-code-gen>`. The resulting compiled diff --git a/docs/users_guide/win32-dlls.rst b/docs/users_guide/win32-dlls.rst index b1495d9503..59c66683fa 100644 --- a/docs/users_guide/win32-dlls.rst +++ b/docs/users_guide/win32-dlls.rst @@ -15,7 +15,7 @@ starts ``ghci``. Be aware of that ``ghc`` and ``ghci`` do require filenames containing spaces to be escaped using quotes: -:: +.. code-block:: none c:\ghc\bin\ghci "c:\\Program Files\\Haskell\\Project.hs" @@ -70,7 +70,7 @@ window, use the flag ``-optl-mwindows`` in the link step. using the ordinary Haskell input/output functions will cause your program to fail with an IO exception, such as: - :: + .. code-block:: none Fail: <stdout>: hPutChar: failed (Bad file descriptor) @@ -166,7 +166,7 @@ Things to do escaping ``\\`` in paths. Apart from the banner and the startup time, something like this would also do: - :: + .. code-block:: none $ echo "Directory.getCurrentDirectory >>= putStrLn . init . tail . show " | ghci @@ -204,7 +204,7 @@ 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: -:: +.. code-block:: none ghc -shared -o foo.dll bar.o baz.o wibble.a -lfooble @@ -219,7 +219,7 @@ A couple of things to notice: this, you can specify the *module definition file* to use on the command line as follows: - :: + .. code-block:: none ghc -shared -o .... MyDef.def @@ -227,7 +227,7 @@ A couple of things to notice: simply lists what entry points you want to export. Here's one that's suitable when building a Haskell COM server DLL: - :: + .. code-block:: none EXPORTS DllCanUnloadNow = DllCanUnloadNow@0 @@ -239,7 +239,7 @@ A couple of things to notice: import library. The import library name is derived from the name of the DLL, as follows: - :: + .. code-block:: none DLL: HScool.dll ==> import lib: libHScool.dll.a @@ -278,7 +278,7 @@ to call from the outside. For example: Add some helper code that starts up and shuts down the Haskell RTS: -:: +.. code-block:: c // StartEnd.c #include <Rts.h> @@ -302,7 +302,7 @@ 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: -:: +.. code-block:: none ghc -c Adder.hs ghc -c StartEnd.c @@ -327,7 +327,7 @@ Using from VBA An example of using ``Adder.dll`` from VBA is: -:: +.. code-block:: none Private Declare Function Adder Lib "Adder.dll" Alias "adder@8" _ (ByVal x As Long, ByVal y As Long) As Long @@ -347,7 +347,7 @@ An example of using ``Adder.dll`` from VBA is: MsgBox "12 + 5 = " & Adder(12, 5) End Sub -This example uses the ``Document_Open``/``Close`` functions of Microsoft +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. @@ -358,7 +358,7 @@ Using from C++ An example of using ``Adder.dll`` from C++ is: -:: +.. code-block:: c // Tester.cpp #include "HsFFI.h" @@ -381,7 +381,7 @@ An example of using ``Adder.dll`` from C++ is: This can be compiled and run with: -:: +.. code-block:: none $ ghc -o tester Tester.cpp Adder.dll.a $ tester |