diff options
Diffstat (limited to 'docs/users_guide')
38 files changed, 7584 insertions, 1747 deletions
diff --git a/docs/users_guide/8.2.1-notes.rst b/docs/users_guide/8.2.1-notes.rst index 76fcc49f9d..d46f08dd94 100644 --- a/docs/users_guide/8.2.1-notes.rst +++ b/docs/users_guide/8.2.1-notes.rst @@ -54,6 +54,10 @@ Language - Support for overloaded record fields via a new ``HasField`` class and associated compiler logic (see :ref:`record-field-selector-polymorphism`) +- GHC now recognizes the ``COMPLETE`` language pragma, allowing the user to + specify sets of patterns (including pattern synonyms) which constitute a + complete pattern match. See :ref:`complete-pragma` for details. + Compiler ~~~~~~~~ @@ -150,7 +154,7 @@ Compiler directive on undefined identifiers. - GHC will no longer automatically infer the kind of higher-rank type synonyms; - you must explicitly explicitly annotate the synonym with a kind signature. + you must explicitly annotate the synonym with a kind signature. For example, given:: data T :: (forall k. k -> Type) -> Type @@ -247,6 +251,8 @@ GHCi - Added support for :ghc-flag:`-XStaticPointers` in interpreted modules. Note, however, that ``static`` expressions are still not allowed in expressions evaluated in the REPL. +- Added support for :ghci-cmd:`:type +d` and :ghci-cmd:`:type +v`. (:ghc-ticket:`11975`) + Template Haskell ~~~~~~~~~~~~~~~~ diff --git a/docs/users_guide/8.4.1-notes.rst b/docs/users_guide/8.4.1-notes.rst deleted file mode 100644 index 9b9d79ffd4..0000000000 --- a/docs/users_guide/8.4.1-notes.rst +++ /dev/null @@ -1,142 +0,0 @@ -.. _release-8-4-1: - -Release notes for version 8.4.1 -=============================== - -The significant changes to the various parts of the compiler are listed in the -following sections. There have also been numerous bug fixes and performance -improvements over the 8.2.1 release. - - -Highlights ----------- - -The highlights, since the 8.2.1 release, are: - -- Many, many bug fixes. - -Full details ------------- - -Language -~~~~~~~~ - -Compiler -~~~~~~~~ - -- The ``configure`` script now no longer accepts ``--with-TOOL`` flags (e.g. - ``--with-nm``, ``--with-ld``, etc.). Instead, these are taken from environment - variables, as is typical in ``autoconf`` scripts. For instance, - ``./configure --with-nm=/usr/local/bin/nm`` turns into - ``./configure NM=/usr/local/bin/nm``. - -- Derived ``Functor``, ``Foldable``, and ``Traversable`` instances are now - optimized when their last type parameters have phantom roles. - Specifically, :: - - fmap _ = coerce - traverse _ x = pure (coerce x) - foldMap _ _ = mempty - - These definitions of ``foldMap`` and ``traverse`` are lazier than the ones we - would otherwise derive, as they may produce results without inspecting their - arguments at all. - - See also :ref:`deriving-functor`, :ref:`deriving-foldable`, and - :ref:`deriving-traversable`. - -- Derived ``Functor``, ``Foldable``, ``Traversable``, ``Generic``, and - ``Generic1`` instances now have better, and generally better-documented, - behaviors for types with no constructors. In particular, :: - - fmap _ x = case x of - foldMap _ _ = mempty - traverse _ x = pure (case x of) - to x = case x of - to1 x = case x of - from x = case x of - from1 x = case x of - - The new behavior generally leads to more useful error messages than the - old did, and lazier semantics for ``foldMap`` and ``traverse``. - -- Derived ``Foldable`` instances now derive custom definitions for ``null`` - instead of using the default one. This leads to asymptotically better - performance for recursive types not shaped like cons-lists, and allows ``null`` - to terminate for more (but not all) infinitely large structures. - -- Derived instances for types with no constructors now have appropriate - arities: they take all their arguments before producing errors. This may not - be terribly important in practice, but it seems like the right thing to do. - Previously, we generated :: - - (==) = error ... - -Now we generate :: - - _ == _ = error ... - -- `-fsplit-sections` is now supported on x86_64 Windows and is on by default. - See :ghc-ticket:`12913`. - -- Configure on Windows now supports ``--enable-distro-toolchain`` which can be - used to build a GHC using compilers on your ``PATH`` instead of using the - bundled bindist. See :ghc-ticket:`13792` - -- The optional ``instance`` keyword is now usable in type family instance - declarations. See :ghc-ticket:`13747` - -- Lots of other bugs. See `Trac <https://ghc.haskell.org/trac/ghc/query?status=closed&milestone=8.4.1&col=id&col=summary&col=status&col=type&col=priority&col=milestone&col=component&order=priority>`_ - for a complete list. - -Runtime system -~~~~~~~~~~~~~~ - -- Function ``hs_add_root()`` was removed. It was a no-op since GHC-7.2.1 - where module initialisation stopped requiring a call to ``hs_add_root()``. - -- Proper import library support added to GHC which can handle all of the libraries produced - by dlltool. The limitation of them needing to be named with the suffix .dll.a is also removed. - See :ghc-ticket:`13606`, :ghc-ticket:`12499`, :ghc-ticket:`12498` - -- The GHCi runtime linker on Windows now supports the `big-obj` file format. - -Template Haskell -~~~~~~~~~~~~~~~~ - -``ghc`` library -~~~~~~~~~~~~~~~ - -- hsSyn Abstract Syntax Tree (AST) is now extensible via the mechanism described in `Trees that Grow <http://www.jucs.org/jucs_23_1/trees_that_grow/jucs_23_01_0042_0062_najd.pdf>`_ - - The main change for users of the GHC API is that the AST is no longer indexed - by the type used as the identifier, but by a specific index type, :: - - type GhcPs = GhcPass 'Parsed -- Old 'RdrName' type param - type GhcRn = GhcPass 'Renamed -- Old 'Name' type param - type GhcTc = GhcPass 'Typechecked -- Old 'Id' type para, - type GhcTcId = GhcTc -- Old 'TcId' type param - - The simplest way to support the current GHC as well as earlier ones is to define :: - - #if MIN_VERSION_ghc(8,3,0) - type ParseI = GhcPs - type RenameI = GhcRn - type TypecheckI = GhcTc - #else - type ParseI = RdrName - type RenameI = Name - type TypecheckI = Var - #endif - - and then replace all hardcoded index types accordingly. For polymorphic types, - the constraint :: - - #if MIN_VERSION_ghc(8,3,0) - -- |bundle up the constraints required for a trees that grow pass - type IsPass pass = (DataId pass, OutputableBndrId pass, SourceTextX pass) - else - type IsPass pass = (DataId pass, OutputableBndrId pass) - #endif - - can be used. diff --git a/docs/users_guide/8.6.1-notes.rst b/docs/users_guide/8.6.1-notes.rst new file mode 100644 index 0000000000..cfa28806eb --- /dev/null +++ b/docs/users_guide/8.6.1-notes.rst @@ -0,0 +1,292 @@ +.. _release-8-6-1: + +Release notes for version 8.6.1 +=============================== + +The significant changes to the various parts of the compiler are listed in the +following sections. There have also been numerous bug fixes and performance +improvements over the 8.4.1 release. + + +Highlights +---------- + +The highlights, since the 8.4.1 release, are: + +- Programs are no longer constrained by the Windows ``MAX_PATH`` file path + length limit. The file path limit is now approximately 32,767 characters. Note + that GHC itself is still somewhat limited due to GCC not supporting file + namespaced paths. Paths that are passed directly to the compiler, linker or + other GNU tools are currently still constrained. See :ref:`windows-file-paths` + for details. + +- Many, many bug fixes. + + +Full details +------------ + +Language +~~~~~~~~ + +- Use of quantified type variables in constraints is now allowed via the + :extension:`QuantifiedConstraints` language extension. This long-awaited feature + enables users to encode significantly more precision in their types. For instance, + the common ``MonadTrans`` typeclass could now make the expectation that an + applied transformer is must be a ``Monad`` :: + + class (forall m. Monad m => Monad (t m)) => MonadTrans t where {- ... -} + + Additionally, quantification can enable terminating instance resolution + where this previously was not possible. See :ref:`quantified-constraints` for + details. + +- A new :extension:`DerivingVia` language extension has been added which allows + the use of the ``via`` deriving strategy. For instance: :: + + newtype T = MkT Int + deriving Monoid via (Sum Int) + + See :ref:`deriving-via` for more information. + +- A new :extension:`StarIsType` language extension has been added which controls + whether ``*`` is parsed as ``Data.Kind.Type`` or a regular type operator. + :extension:`StarIsType` is enabled by default. + +- GHC now permits the use of a wildcard type as the context of a standalone + ``deriving`` declaration with the use of the + :extension:`PartialTypeSignatures` language extension. For instance, this + declaration: :: + + deriving instance _ => Eq (Foo a) + + Denotes a derived ``Eq (Foo a)`` instance, where the context is inferred in + much the same way as ordinary ``deriving`` clauses do. + See :ref:`partial-type-signatures`. + +- Data declarations with empty ``where`` clauses are no longer valid without the + extension :extension:`GADTSyntax` enabled. For instance, consider the + following, :: + + data T where + + The grammar is invalid in Haskell2010. Previously it could be compiled successfully + without ``GADTs``. As of GHC 8.6.1, this is a parse error. + +- Incomplete patterns warning :ghc-flag:`-Wincomplete-patterns` is extended to + guards in pattern bindings and ``if`` alternatives of :extension:`MultiWayIf`. + For instance, consider the following, :: + + foo :: Bool -> Int + foo b = if | b -> 1 + + In GHC 8.6.1, it will raise the warning: :: + + <interactive>:2:12: warning: [-Wincomplete-patterns] + Pattern match(es) are non-exhaustive + In a multi-way if alternative: + Guards do not cover entire pattern space + + See :ghc-ticket:`14773`. + +- Scoped type variables now work in default methods of class declarations + and in pattern synonyms in Template Haskell. See :ghc-ticket:`14885`. + +- ``do`` expressions, lambda expressions, etc. to be directly used as + a function argument, enabled with :extension:`BlockArguments`. + See :ref:`More liberal syntax for function arguments <block-arguments>` + for the full details. + +- Underscores in numeric literals (e.g. ``1_000_000``), enabled with + :extension:`NumericUnderscores`. + See :ref:`Numeric underscores <numeric-underscores>` + for the full details. + +- CUSKs now require all kind variables to be explicitly quantified. This was + already the case with :extension:`TypeInType`, but now :extension:`PolyKinds` + also exhibits this behavior. This means that the following example is no + longer considered to have a CUSK:: + + data T1 :: k -> Type -- No CUSK: `k` is not explicitly quantified + +- Functionality of :extension:`TypeInType` has been subsumed by + :extension:`PolyKinds`, and it is now merely a shorthand for + :extension:`PolyKinds`, :extension:`DataKinds`, and :extension:`NoStarIsType`. + The users are advised to avoid :extension:`TypeInType` due to its misleading + name: the ``Type :: Type`` axiom holds regardless of whether it is enabled. + +- GHC has become more diligent about catching illegal uses of kind polymorphism. + For instance, GHC 8.4 would accept the following without the use of + :extension:`PolyKinds`:: + + f :: forall k (a :: k). Proxy a + f = Proxy + + This is now an error unless :extension:`PolyKinds` is enabled. + +- The plugin mechanism has been extended to allow plugins to run between frontend + phases. Of particular note are the parser and typechecker plugins which run + after parsing and typechecking have completed. Collectively, these new extension + points are called :ref:`source plugins <source-plugins>`. + +- Type literals now could be used in type class instances without the extension + :extension:`FlexibleInstances`. + + See :ghc-ticket:`13833`. + +- :extension:`MonadFailDesugaring` is now enabled by default. See + `MonadFail Proposal (MFP) + <https://prime.haskell.org/wiki/Libraries/Proposals/MonadFail>`__ + for more details. + +Compiler +~~~~~~~~ + +- GHC now no longer adds the current file's directory as a general include path + calling the C compiler. Instead we use :ghc-flag:`-iquote` to only add it as + an include path for `#include ""`. See :ghc-ticket:`14312`. + +- GHC now supports British spelling of :extension:`GeneralizedNewtypeDeriving`. + +- GHC now does significantly more constant folding in its core-to-core optimiser. + This will result in significantly better code being generated for some + programs. See :ghc-ticket:`9136`. + +- GHC now offers significantly more information about typed holes such as valid + hole fits and refinement hole fits. See :ref:`Valid Hole Fits <typed-hole-valid-hole-fits>` + for more information. + +- The code-generation effects of :ghc-flag:`-dynamic` can now be + enabled independently by the flag + :ghc-flag:`-fexternal-dynamic-refs`. If you don't know why you might + need this, you don't need it. + +- :ghc-flag:`-Wcompat` now includes :ghc-flag:`-Wimplicit-kind-vars` to + provide early detection of breakage that will be caused by implementation of + `GHC proposal #24 + <https://github.com/ghc-proposals/ghc-proposals/blob/master/proposals/0024-no-kind-vars.rst>`__ + in a future release. + +Plugins +~~~~~~~ + +- GHC's plugin mechanism now offers plugin authors control over their plugin's + effect on recompilation checking. Specifically the ``Plugin`` record name has + a new field :: + + data Plugin = Plugin { + pluginRecompile :: [CommandLineOption] -> IO PluginRecompile + , {- ... -} + } + + data PluginRecompile = ForceRecompile | NoForceRecompile | MaybeRecompile Fingerprint + + Plugin based on ``defaultPlugin`` will have their previous recompilation + behavior (``ForceRecompile``) preserved. However, plugins that are "pure" are + encouraged to override this to either ``NoForceRecompile`` or ``MaybeRecompile``. + See :ref:`plugin_recompilation` for details. + +- GHC now provides a class of new plugins: source plugins. These plugins can + inspect and modify a variety of intermediate representations used by the + compiler's frontend. These include: + + * The ability to modify the parser output + * The ability to inspect the renamer output + * The ability to modify the typechecked AST + * The ability to modify Template Haskell splices + * The ability to modify interface files as they are loaded + + See :ref:`source-plugins` for details. + +GHCi +~~~~ + +- Added an experimental :ghci-cmd:`:doc` command that displays the + documentation for a declaration. + +Runtime system +~~~~~~~~~~~~~~ + +- The GHC runtime linker now prefers user shared libraries above system ones. + When extra search directories are specified these are searched before anything + else. This fixes ``iuuc`` on Windows given the proper search directories (e.g + ``-L/mingw64/lib``). + +- The GHC runtime linker now uses ``LIBRARY_PATH`` and the runtime loader now also + searches ``LD_LIBRARY_PATH``. + +- The GHC runtime on Windows is no longer constrained by the ``MAX_PATH`` file path + length limitation. See :ref:`windows-file-paths`. + +- The runtime now allows use of the :rts-flag:`-hT` profiling variety on + programs built with :ghc-flag:`-prof`. + +- The STM assertions mechanism (namely the ``always`` and ``alwaysSucceeds`` + functions) has been removed. This happened a bit earlier than proposed in the + deprecation pragma included in GHC 8.4, but due to community feedback we + decided to move ahead with the early removal. + +Template Haskell +~~~~~~~~~~~~~~~~ + +``ghc`` library +~~~~~~~~~~~~~~~ + + +``base`` library +~~~~~~~~~~~~~~~~ + +- ``($!)`` is now representation-polymorphic like ``($)``. + +- The module ``Data.Functor.Contravariant`` has been moved from the + ``contravariant`` package into ``base``. All the other modules in + ``contravariant`` (``Data.Functor.Contravariant.Divisible``, etc.) + have not been moved to ``base``, and they still reside in ``contravariant``. + +``ghc-prim`` library +~~~~~~~~~~~~~~~~~~~~ + +- Version number 0.5.2.1 (was 0.5.2.0) + +- Added new ``addWordC#`` operation for unsigned addition with carry. + +Build system +~~~~~~~~~~~~ + + +Included libraries +------------------ + +The package database provided with this distribution also contains a number of +packages other than GHC itself. See the changelogs provided with these packages +for further change information. + +.. ghc-package-list:: + + libraries/array/array.cabal: Dependency of ``ghc`` library + libraries/base/base.cabal: Core library + libraries/binary/binary.cabal: Dependency of ``ghc`` library + libraries/bytestring/bytestring.cabal: Deppendency of ``ghc`` library + libraries/Cabal/Cabal/Cabal.cabal: Dependency of ``ghc-pkg`` utility + libraries/containers/containers.cabal: Dependency of ``ghc`` library + libraries/deepseq/deepseq.cabal: Dependency of ``ghc`` library + libraries/directory/directory.cabal: Dependency of ``ghc`` library + libraries/filepath/filepath.cabal: Dependency of ``ghc`` library + compiler/ghc.cabal: The compiler itself + libraries/ghci/ghci.cabal: The REPL interface + libraries/ghc-boot/ghc-boot.cabal: Internal compiler library + libraries/ghc-compact/ghc-compact.cabal: Core library + libraries/ghc-prim/ghc-prim.cabal: Core library + libraries/haskeline/haskeline.cabal: Dependency of ``ghci`` executable + libraries/hpc/hpc.cabal: Dependency of ``hpc`` executable + libraries/integer-gmp/integer-gmp.cabal: Core library + libraries/mtl/mtl.cabal: Dependency of ``Cabal`` library + libraries/parsec/parsec.cabal: Dependency of ``Cabal`` library + libraries/process/process.cabal: Dependency of ``ghc`` library + libraries/template-haskell/template-haskell.cabal: Core library + libraries/text/text.cabal: Dependency of ``Cabal`` library + libraries/time/time.cabal: Dependency of ``ghc`` library + libraries/transformers/transformers.cabal: Dependency of ``ghc`` library + libraries/unix/unix.cabal: Dependency of ``ghc`` library + libraries/Win32/Win32.cabal: Dependency of ``ghc`` library + libraries/xhtml/xhtml.cabal: Dependency of ``haddock`` executable diff --git a/docs/users_guide/8.8.1-notes.rst b/docs/users_guide/8.8.1-notes.rst new file mode 100644 index 0000000000..e3a8d3ea22 --- /dev/null +++ b/docs/users_guide/8.8.1-notes.rst @@ -0,0 +1,146 @@ +.. _release-8-8-1: + +Release notes for version 8.8.1 +=============================== + +The significant changes to the various parts of the compiler are listed in the +following sections. There have also been numerous bug fixes and performance +improvements over the 8.6.1 release. + + +Highlights +---------- + +The highlights, since the 8.6.1 release, are: + +- Many, many bug fixes. + + +Full details +------------ + +Language +~~~~~~~~ + +- :extension:`ScopedTypeVariables`: The type variable that a type signature on + a pattern can bring into scope can now stand for arbitrary types. Previously, + they could only stand in for other type variables, but this restriction was deemed + unnecessary in `GHC proposal #29 <https://github.com/ghc-proposals/ghc-proposals/blob/master/proposals/0029-scoped-type-variables-types.rst>`__. Also see :ghc-ticket:`15050`. + +- The pattern-match coverage checker now checks for cases that are unreachable + due to constructors have strict argument types. For instance, in the + following example: :: + + data K = K1 | K2 !Void + + f :: K -> () + f K1 = () + + ``K2`` cannot be matched on in ``f``, since it is impossible to construct a + terminating value of type ``Void``. Accordingly, GHC will not warn about + ``K2`` (whereas previous versions of GHC would). + +Compiler +~~~~~~~~ + +- New :ghc-flag:`-keep-hscpp-files` to keep the output of the CPP pre-processor. + +Runtime system +~~~~~~~~~~~~~~ + +- Add and document new FFI functions ``hs_lock_stable_ptr_table`` + and ``hs_unlock_stable_ptr_table``. These replace the undocumented + functions ``hs_lock_stable_tables`` and ``hs_unlock_stable_tables``, + respectively. The latter should now be considered deprecated. + +- Document the heretofore undocumented FFI function + ``hs_free_stable_ptr_unsafe``, used in conjunction with manual + locking and unlocking. + +- The runtime linker on Windows has been overhauled to properly handle section + alignment, lower the amount of wasted memory and lower the amount of in use memory. + See :ghc-ticket:`13617`. Note that committed memory may be slightly higher. + + +Template Haskell +~~~~~~~~~~~~~~~~ + +- Reifying type classes no longer shows redundant class type variables and + contexts in the type signature of each class method. For instance, + reifying the following class: :: + + class C a where + method :: a + + Used to produce the following: :: + + class C a where + method :: forall a. C a => a + + Where the ``forall a. C a =>`` part is entirely redundant. This part is no + longer included when reifying ``C``. It's possible that this may break some + code which assumes the existence of ``forall a. C a =>``. + +- Template Haskell now supports implicit parameters and recursive do. + +``ghc-prim`` library +~~~~~~~~~~~~~~~~~~~~ + +- GHC now exposes a new primop, ``traceBinaryEvent#``. This primop writes + eventlog events similar to ``traceBinaryEvent#`` but allows the user to pass + the event payload as a binary blob instead of a ``String``. + +``ghc`` library +~~~~~~~~~~~~~~~ + + +``base`` library +~~~~~~~~~~~~~~~~ + +- Support the characters from recent versions of Unicode (up to v. 12) in literals + (see :ghc-ticket:`5518`). + +Build system +~~~~~~~~~~~~ + + +Included libraries +------------------ + +The package database provided with this distribution also contains a number of +packages other than GHC itself. See the changelogs provided with these packages +for further change information. + +.. ghc-package-list:: + + libraries/array/array.cabal: Dependency of ``ghc`` library + libraries/base/base.cabal: Core library + libraries/binary/binary.cabal: Dependency of ``ghc`` library + libraries/bytestring/bytestring.cabal: Deppendency of ``ghc`` library + libraries/Cabal/Cabal/Cabal.cabal: Dependency of ``ghc-pkg`` utility + libraries/containers/containers.cabal: Dependency of ``ghc`` library + libraries/deepseq/deepseq.cabal: Dependency of ``ghc`` library + libraries/directory/directory.cabal: Dependency of ``ghc`` library + libraries/filepath/filepath.cabal: Dependency of ``ghc`` library + compiler/ghc.cabal: The compiler itself + libraries/ghci/ghci.cabal: The REPL interface + libraries/ghc-boot/ghc-boot.cabal: Internal compiler library + libraries/ghc-boot-th/ghc-boot-th.cabal: Internal compiler library + libraries/ghc-compact/ghc-compact.cabal: Core library + libraries/ghc-heap/ghc-heap.cabal: GHC heap-walking library + libraries/ghc-prim/ghc-prim.cabal: Core library + libraries/haskeline/haskeline.cabal: Dependency of ``ghci`` executable + libraries/hpc/hpc.cabal: Dependency of ``hpc`` executable + libraries/integer-gmp/integer-gmp.cabal: Core library + libraries/mtl/mtl.cabal: Dependency of ``Cabal`` library + libraries/parsec/parsec.cabal: Dependency of ``Cabal`` library + libraries/process/process.cabal: Dependency of ``ghc`` library + libraries/stm/stm.cabal: Dependency of ``haskeline`` library + libraries/template-haskell/template-haskell.cabal: Core library + libraries/terminfo/terminfo.cabal: Dependency of ``haskeline`` library + libraries/text/text.cabal: Dependency of ``Cabal`` library + libraries/time/time.cabal: Dependency of ``ghc`` library + libraries/transformers/transformers.cabal: Dependency of ``ghc`` library + libraries/unix/unix.cabal: Dependency of ``ghc`` library + libraries/Win32/Win32.cabal: Dependency of ``ghc`` library + libraries/xhtml/xhtml.cabal: Dependency of ``haddock`` executable diff --git a/docs/users_guide/Makefile b/docs/users_guide/Makefile index 27f3a117dd..4e820eb19f 100644 --- a/docs/users_guide/Makefile +++ b/docs/users_guide/Makefile @@ -2,6 +2,3 @@ dir = docs/users_guide TOP = ../.. include $(TOP)/mk/sub-makefile.mk - -# This makes 'make fast' work: assume that mkUserGuidePart exists -FAST_MAKE_OPTS += utils/mkUserGuidePart_dist_NOT_NEEDED=YES diff --git a/docs/users_guide/bugs.rst b/docs/users_guide/bugs.rst index 7ccb215d23..aee8dc5842 100644 --- a/docs/users_guide/bugs.rst +++ b/docs/users_guide/bugs.rst @@ -83,12 +83,6 @@ Context-free syntax (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 - before only expressions that could potentially be applied as a function. - - .. _infelicities-exprs-pats: Expressions and patterns @@ -143,7 +137,7 @@ group is generalised (`Haskell Report, Section 4.5.2 <http://www.haskell.org/onlinereport/decls.html#sect4.5.2>`__). Following a suggestion of Mark Jones, in his paper `Typing Haskell in -Haskell <http://citeseer.ist.psu.edu/424440.html>`__, GHC implements a +Haskell <https://web.cecs.pdx.edu/~mpj/thih/>`__, GHC implements a more general scheme. In GHC *the dependency analysis ignores references to variables that have an explicit type signature*. As a result of this refined dependency analysis, the dependency groups are smaller, and more bindings will @@ -348,6 +342,31 @@ The Foreign Function Interface single: hs_init single: hs_exit +.. _infelicities-operator-sections: + +Operator sections +^^^^^^^^^^^^^^^^^ + +The Haskell Report demands that, for infix operators ``%``, the following +identities hold: + +:: + + (% expr) = \x -> x % expr + (expr %) = \x -> expr % x + +However, the second law is violated in the presence of undefined operators, + +:: + + (%) = error "urk" + (() %) `seq` () -- urk + (\x -> () % x) `seq` () -- OK, result () + +The operator section is treated like function application of an undefined +function, while the lambda form is in WHNF that contains an application of an +undefined function. + .. _haskell-98-2010-undefined: GHC's interpretation of undefined behaviour in Haskell 98 and Haskell 2010 diff --git a/docs/users_guide/codegens.rst b/docs/users_guide/codegens.rst index 6db549958b..936d7251dd 100644 --- a/docs/users_guide/codegens.rst +++ b/docs/users_guide/codegens.rst @@ -15,7 +15,7 @@ described below. .. _native-code-gen: -Native code Generator (``-fasm``) +Native Code Generator (``-fasm``) --------------------------------- .. index:: @@ -40,20 +40,25 @@ performance as good as the native code generator but for some cases can produce much faster code. This is especially true for numeric, array heavy code using packages like vector. The penalty is a significant increase in compilation times. Select the LLVM backend with the -``-fllvm`` flag. Currently *LLVM 2.8* and later are supported. +:ghc-flag:`-fllvm` flag. You must install and have LLVM available on your ``PATH`` for the LLVM code generator to work. Specifically GHC needs to be able to call the ``opt`` and ``llc`` tools. Secondly, if you are running Mac OS X with LLVM 3.0 -or greater then you also need the `Clang c +or greater then you also need the `Clang C compiler <http://clang.llvm.org>`__ compiler available on your ``PATH``. +.. note:: + + Note that this GHC release expects an LLVM version in the |llvm-version| + release series. + To install LLVM and Clang: - *Linux*: Use your package management tool. - *Mac OS X*: Clang is included by default on recent OS X machines when - XCode is installed (from ``10.6`` and later). LLVM is not included. + XCode is installed (from 10.6 and later). LLVM is not included. In order to use the LLVM based code generator, you should install the `Homebrew <http://mxcl.github.com/homebrew/>`__ package manager for OS X. Alternatively you can download binaries for LLVM and Clang from @@ -73,7 +78,7 @@ C Code Generator (``-fvia-C``) This is the oldest code generator in GHC and is generally not included any more having been deprecated around GHC 7.0. Select it with the -``-fvia-C`` flag. +:ghc-flag:`-fvia-C` flag. The C code generator is only supported when GHC is built in unregisterised mode, a mode where GHC produces "portable" C code as @@ -81,7 +86,7 @@ output to facilitate porting GHC itself to a new platform. This mode produces much slower code though so it's unlikely your version of GHC was built this way. If it has then the native code generator probably won't be available. You can check this information by calling -``ghc --info`` (see :ref:`ghc-info`). +``ghc --info`` (see :ghc-flag:`--info`). .. _unreg: @@ -112,4 +117,4 @@ to build GHC with the appropriate options set. Consult the GHC Building Guide for details. You can check if your GHC is unregisterised by calling -``ghc --info`` (see :ref:`ghc-info`). +``ghc --info`` (see :ghc-flag:`--info`). diff --git a/docs/users_guide/conf.py b/docs/users_guide/conf.py index 9c75d5bf97..0732c5ccd4 100644 --- a/docs/users_guide/conf.py +++ b/docs/users_guide/conf.py @@ -13,13 +13,21 @@ sys.path.insert(0, os.path.abspath('.')) from ghc_config import extlinks, version import ghc_config -extensions = ['sphinx.ext.extlinks', 'sphinx.ext.mathjax'] +extensions = ['sphinx.ext.extlinks', + 'sphinx.ext.mathjax', + # GHC-specific extensions + 'flags', + 'ghc_packages'] templates_path = ['.templates'] source_suffix = '.rst' source_encoding = 'utf-8-sig' master_doc = 'index' +rst_prolog = """ +.. |llvm-version| replace:: {llvm_version} +""".format(llvm_version=ghc_config.llvm_version) + # General information about the project. project = u'Glasgow Haskell Compiler' copyright = u'2015, GHC Team' @@ -32,7 +40,7 @@ pygments_style = 'tango' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. -exclude_patterns = ['.build', "*.gen.rst"] +exclude_patterns = ['.build'] # -- Options for HTML output --------------------------------------------- @@ -49,6 +57,9 @@ html_use_smartypants = True html_use_opensearch = 'https://downloads.haskell.org/~ghc/master/users-guide' html_show_copyright = True +# See GHC #15006 +mathjax_path = 'https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.0/MathJax.js' + # If true, an OpenSearch description file will be output, and all pages will # contain a <link> tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. @@ -72,6 +83,7 @@ latex_elements = { \setsansfont{DejaVu Sans} \setromanfont{DejaVu Serif} \setmonofont{DejaVu Sans Mono} +\setlength{\\tymin}{45pt} ''', } @@ -193,16 +205,6 @@ def setup(app): 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') - ]) - # Haddock references app.add_role('th-ref', haddock_role('template-haskell')) app.add_role('base-ref', haddock_role('base')) diff --git a/docs/users_guide/debug-info.rst b/docs/users_guide/debug-info.rst index 6a34431c84..ecda4afc6c 100644 --- a/docs/users_guide/debug-info.rst +++ b/docs/users_guide/debug-info.rst @@ -7,13 +7,19 @@ useable by most UNIX debugging tools. .. ghc-flag:: -g -g⟨n⟩ + :shortdesc: Produce DWARF debug information in compiled object files. + ⟨n⟩ can be 0, 1, or 2, with higher numbers producing richer + output. If ⟨n⟩ is omitted, level 2 is assumed. + :type: dynamic + :category: debugging :since: 7.10, numeric levels since 8.0 Emit debug information in object code. Currently only DWARF debug information is supported on x86-64 and i386. Currently debug levels 0 - through 3 are accepted, with 0 disabling debug information production. - Levels 1 through 3 are functionally equivalent. + through 3 are accepted, with 0 disabling debug information production + and higher numbers producing richer output. If ⟨n⟩ is omitted, level 2 + is assumed. Tutorial @@ -180,16 +186,21 @@ Stack trace functionality is exposed for use by Haskell programs in the :base-ref:`GHC.ExecutionStack.` module. See the Haddock documentation in this module for details regarding usage. -Requesting a stack trace with ``SIGUSR2`` +.. _backtrace-signal: + +Requesting a stack trace with ``SIGQUIT`` ----------------------------------------- On POSIX-compatible platforms GHC's runtime system (when built with ``libdw`` -support) will produce a stack trace on ``stderr`` when a ``SIGUSR2`` signal is -received. For instance (using the same ``fib.hs`` as above), +support) will produce a stack trace on ``stderr`` when a ``SIGQUIT`` signal is +received (on many systems this signal can be sent using :kbd:`Ctrl-\\`). For +instance (using the same ``fib.hs`` as above), .. code-block:: sh - $ ./fib & killall -SIGUSR2 fib + $ ./fib & killall -SIGQUIT fib + + Caught SIGQUIT; Backtrace: 0x7f3176b15dd8 dwfl_thread_getframes (/usr/lib/x86_64-linux-gnu/libdw-0.163.so) 0x7f3176b1582f (null) (/usr/lib/x86_64-linux-gnu/libdw-0.163.so) 0x7f3176b15b57 dwfl_getthreads (/usr/lib/x86_64-linux-gnu/libdw-0.163.so) @@ -258,10 +269,10 @@ GHC may produce the following standard DIEs in the ``.debug_info`` section, Represents a compilation unit (e.g. a Haskell module). ``DW_TAG_subprogram`` - Represents a C-- top-level basic block. + Represents a C-\\- top-level basic block. ``DW_TAG_lexical_block`` - Represents a C-- basic block. Note that this is a slight departure from the + Represents a C-\\- basic block. Note that this is a slight departure from the intended meaning of this DIE type as it does not necessarily reflect lexical scope in the source program. diff --git a/docs/users_guide/debugging.rst b/docs/users_guide/debugging.rst index bc155884c8..6a4c7fe1a7 100644 --- a/docs/users_guide/debugging.rst +++ b/docs/users_guide/debugging.rst @@ -6,8 +6,14 @@ Debugging the compiler .. index:: single: debugging options (for GHC) +.. + It is not necessary to provide :category: tags for ``ghc-flag:``s defined in + this file; a default is specified in ``flags.py``. + HACKER TERRITORY. HACKER TERRITORY. (You were warned.) +.. contents:: Dump flags + .. _dumping-output: Dumping out compiler intermediate structures @@ -17,255 +23,552 @@ Dumping out compiler intermediate structures single: dumping GHC intermediates single: intermediate passes, output -``-ddump-`` ⟨pass⟩ - .. index:: - single: -ddump options +.. ghc-flag:: -ddump-to-file + :shortdesc: Dump to files instead of stdout + :type: dynamic - Make a debugging dump after pass ``<pass>`` (may be common enough to - 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 - :ghc-flag:`-ddump-to-file`. Some of the most useful ones are: + 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-to-file +.. ghc-flag:: -ddump-json + :shortdesc: Dump error messages as JSON documents + :type: dynamic - 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`. + Dump error messages as JSON documents. This is intended to be consumed + by external tooling. A good way to use it is in conjunction with + :ghc-flag:`-ddump-to-file`. - .. ghc-flag:: -ddump-parsed +.. ghc-flag:: -dshow-passes + :shortdesc: Print out each pass name as it happens + :type: dynamic - Dump parser output + Print out each pass name, its runtime and heap allocations as it happens. + Note that this may come at a slight performance cost as the compiler will + be a bit more eager in forcing pass results to more accurately account for + their costs. - .. ghc-flag:: -ddump-parsed-ast + Two types of messages are produced: Those beginning with ``***`` do + denote the beginning of a compilation phase whereas those starting with + ``!!!`` mark the end of a pass and are accompanied by allocation and + runtime statistics. - Dump parser output as a syntax tree +.. ghc-flag:: -dfaststring-stats + :shortdesc: Show statistics for fast string usage when finished + :type: dynamic - .. ghc-flag:: -ddump-rn + Show statistics on the usage of fast strings by the compiler. - Dump renamer output +.. ghc-flag:: -dppr-debug + :shortdesc: Turn on debug printing (more verbose) + :type: dynamic - .. ghc-flag:: -ddump-rn-ast + Debugging output is in one of several "styles." Take the printing of + types, for example. In the "user" style (the default), the + compiler's internal ideas about types are presented in Haskell + source-level syntax, insofar as possible. In the "debug" style + (which is the default for debugging output), the types are printed + in with explicit foralls, and variables have their unique-id + attached (so you can check for things that look the same but + aren't). This flag makes debugging output appear in the more verbose + debug style. - Dump renamer output as a syntax tree +.. ghc-flag:: -ddump-timings + :shortdesc: Dump per-pass timing and allocation statistics + :type: dynamic - .. ghc-flag:: -ddump-tc + Show allocation and runtime statistics for various stages of compilation. - Dump typechecker output +GHC is a large program consisting of a number of stages. You can tell GHC to +dump information from various stages of compilation using the ``-ddump-⟨pass⟩`` +flags listed below. Note that some of these tend to produce a lot of output. +You can prevent them from clogging up your standard output by passing +:ghc-flag:`-ddump-to-file`. - .. ghc-flag:: -ddump-tc-ast +Front-end +~~~~~~~~~ - Dump typechecker output as a syntax tree +These flags dump various information from GHC's frontend. This includes the +parser and interface file reader. - .. ghc-flag:: -ddump-splices +.. ghc-flag:: -ddump-parsed + :shortdesc: Dump parse tree + :type: dynamic - Dump Template Haskell expressions that we splice in, and what - Haskell code the expression evaluates to. + Dump parser output - .. ghc-flag:: -dth-dec-file=⟨file⟩ +.. ghc-flag:: -ddump-parsed-ast + :shortdesc: Dump parser output as a syntax tree + :type: dynamic - Dump expansions of all top-level Template Haskell splices into ⟨file⟩. + Dump parser output as a syntax tree - .. ghc-flag:: -ddump-types +.. ghc-flag:: -ddump-if-trace + :shortdesc: Trace interface files + :type: dynamic - Dump a type signature for each value defined at the top level of - the module. The list is sorted alphabetically. Using - :ghc-flag:`-dppr-debug` dumps a type signature for all the imported and - system-defined things as well; useful for debugging the - compiler. + Make the interface loader be *real* chatty about what it is up to. - .. ghc-flag:: -ddump-deriv - Dump derived instances +Type-checking and renaming +~~~~~~~~~~~~~~~~~~~~~~~~~~ - .. ghc-flag:: -ddump-ds +These flags dump various information from GHC's typechecker and renamer. - Dump desugarer output +.. ghc-flag:: -ddump-tc-trace + :shortdesc: Trace typechecker + :type: dynamic - .. ghc-flag:: -ddump-spec + Make the type checker be *real* chatty about what it is up to. - Dump output of specialisation pass +.. ghc-flag:: -ddump-rn-trace + :shortdesc: Trace renamer + :type: dynamic - .. ghc-flag:: -ddump-rules + Make the renamer be *real* chatty about what it is up to. - Dumps all rewrite rules specified in this module; see - :ref:`controlling-rules`. +.. ghc-flag:: -ddump-ec-trace + :shortdesc: Trace exhaustiveness checker + :type: dynamic - .. ghc-flag:: -ddump-rule-firings + Make the pattern match exhaustiveness checker be *real* chatty about + what it is up to. - Dumps the names of all rules that fired in this module +.. ghc-flag:: -ddump-rn-stats + :shortdesc: Renamer stats + :type: dynamic - .. ghc-flag:: -ddump-rule-rewrites + Print out summary of what kind of information the renamer had to + bring in. - Dumps detailed information about all rules that fired in this - module +.. ghc-flag:: -ddump-rn + :shortdesc: Dump renamer output + :type: dynamic - .. ghc-flag:: -ddump-vect + Dump renamer output - Dumps the output of the vectoriser. +.. ghc-flag:: -ddump-rn-ast + :shortdesc: Dump renamer output as a syntax tree + :type: dynamic - .. ghc-flag:: -ddump-simpl + Dump renamer output as a syntax tree - Dump simplifier output (Core-to-Core passes) +.. ghc-flag:: -ddump-tc + :shortdesc: Dump typechecker output + :type: dynamic - .. ghc-flag:: -ddump-inlinings + Dump typechecker output. Note that this hides a great deal of detail by + default; you might consider using this with + :ghc-flag:`-fprint-typechecker-elaboration`. - Dumps inlining info from the simplifier. Note that if used in conjunction with - :ghc-flag:`-dverbose-core2core` the compiler will also dump the inlinings that - it considers but passes up, along with its rationale. +.. ghc-flag:: -ddump-tc-ast + :shortdesc: Dump typechecker output as a syntax tree + :type: dynamic - .. ghc-flag:: -ddump-stranal + Dump typechecker output as a syntax tree - Dump strictness analyser output +.. ghc-flag:: -ddump-splices + :shortdesc: Dump TH spliced expressions, and what they evaluate to + :type: dynamic - .. ghc-flag:: -ddump-str-signatures + Dump Template Haskell expressions that we splice in, and what + Haskell code the expression evaluates to. - Dump strictness signatures +.. ghc-flag:: -dth-dec-file + :shortdesc: Dump evaluated TH declarations into `*.th.hs` files + :type: dynamic - .. ghc-flag:: -ddump-cse + Dump expansions of all top-level Template Haskell splices into + :file:`{module}.th.hs` for each file :file:`{module}.hs`. - Dump common subexpression elimination (CSE) pass output +.. ghc-flag:: -ddump-types + :shortdesc: Dump type signatures + :type: dynamic - .. ghc-flag:: -ddump-worker-wrapper + Dump a type signature for each value defined at the top level of + the module. The list is sorted alphabetically. Using + :ghc-flag:`-dppr-debug` dumps a type signature for all the imported and + system-defined things as well; useful for debugging the + compiler. - Dump worker/wrapper split output +.. ghc-flag:: -ddump-deriv + :shortdesc: Dump deriving output + :type: dynamic - .. ghc-flag:: -ddump-occur-anal + Dump derived instances - Dump "occurrence analysis" output - .. ghc-flag:: -ddump-prep +Core representation and simplification +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - Dump output of Core preparation pass +These flags dump various phases of GHC's Core-to-Core pipeline. This begins with +the desugarer and includes the simplifier, worker-wrapper transformation, the +rule engine, the specialiser, the strictness/occurrence analyser, and a common +subexpression elimination pass. - .. ghc-flag:: -ddump-stg +.. ghc-flag:: -ddump-core-stats + :shortdesc: Print a one-line summary of the size of the Core program at the + end of the optimisation pipeline + :type: dynamic - Dump output of STG-to-STG passes + Print a one-line summary of the size of the Core program at the end + of the optimisation pipeline. - .. ghc-flag:: -ddump-cmm +.. ghc-flag:: -ddump-ds + -ddump-ds-preopt + :shortdesc: Dump desugarer output. + :type: dynamic - Dump the result of the C-- pipeline processing + Dump desugarer output. :ghc-flag:`-ddump-ds` dumps the output after the very + simple optimiser has run (which discards a lot of clutter and hence is a + sensible default. :ghc-flag:`-ddump-ds-preopt` shows the output after + desugaring but before the very simple optimiser. - .. ghc-flag:: -ddump-cmm-from-stg - Dump the result of STG-to-C-- conversion +.. ghc-flag:: -ddump-simpl-iterations + :shortdesc: Dump output from each simplifier iteration + :type: dynamic - .. ghc-flag:: -ddump-cmm-verbose + Show the output of each *iteration* of the simplifier (each run of + the simplifier has a maximum number of iterations, normally 4). - Dump output from all C-- pipeline stages. In case of - ``.cmm`` compilation this also dumps the result of - file parsing. +.. ghc-flag:: -ddump-simpl-stats + :shortdesc: Dump simplifier stats + :type: dynamic - .. ghc-flag:: -ddump-opt-cmm + Dump statistics about how many of each kind of transformation took + place. If you add :ghc-flag:`-dppr-debug` you get more detailed information. - Dump the results of C-- to C-- optimising passes. +.. ghc-flag:: -dverbose-core2core + :shortdesc: Show output from each core-to-core pass + :type: dynamic - .. ghc-flag:: -ddump-asm + Show the output of the intermediate Core-to-Core pass. (*lots* of output!) + So: when we're really desperate: - Dump assembly language produced by the :ref:`native code - generator <native-code-gen>` + .. code-block:: sh - .. ghc-flag:: -ddump-llvm + % ghc -noC -O -ddump-simpl -dverbose-core2core -dcore-lint Foo.hs - :implies: :ghc-flag:`-fllvm` +.. ghc-flag:: -ddump-spec + :shortdesc: Dump specialiser output + :type: dynamic - LLVM code from the :ref:`LLVM code generator <llvm-code-gen>` + Dump output of specialisation pass - .. ghc-flag:: -ddump-bcos +.. ghc-flag:: -ddump-rules + :shortdesc: Dump rewrite rules + :type: dynamic - Dump byte-code compiler output + Dumps all rewrite rules specified in this module; see + :ref:`controlling-rules`. - .. ghc-flag:: -ddump-foreign +.. ghc-flag:: -ddump-rule-firings + :shortdesc: Dump rule firing info + :type: dynamic - dump foreign export stubs + Dumps the names of all rules that fired in this module - .. ghc-flag:: -ddump-json +.. ghc-flag:: -ddump-rule-rewrites + :shortdesc: Dump detailed rule firing info + :type: dynamic - Dump error messages as JSON documents. This is intended to be consumed - by external tooling. A good way to use it is in conjunction with - :ghc-flag:`-ddump-to-file`. + Dumps detailed information about all rules that fired in this + module -.. ghc-flag:: -ddump-simpl-iterations +.. ghc-flag:: -drule-check=⟨str⟩ + :shortdesc: Dump information about potential rule application + :type: dynamic - 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``. + This flag is useful for debugging why a rule you expect to be firing isn't. -.. ghc-flag:: -ddump-simpl-stats + Rules are filtered by the user provided string, a rule is kept if a prefix + of its name matches the string. + The pass then checks whether any of these rules could apply to + the program but which didn't file for some reason. For example, specifying + ``-drule-check=SPEC`` will check whether there are any applications which + might be subject to a rule created by specialisation. - Dump statistics about how many of each kind of transformation too - place. If you add ``-dppr-debug`` you get more detailed information. +.. ghc-flag:: -dinline-check=⟨str⟩ + :shortdesc: Dump information about inlining decisions + :type: dynamic -.. ghc-flag:: -ddump-if-trace + This flag is useful for debugging why a definition is not inlined. - Make the interface loader be *real* chatty about what it is up to. + When a string is passed to this flag we report information + about all functions whose name shares a prefix with the string. -.. ghc-flag:: -ddump-tc-trace + For example, if you are inspecting the core of your program and you observe + that ``foo`` is not being inlined. You can pass ``-dinline-check foo`` and + you will see a report about why ``foo`` is not inlined. - Make the type checker be *real* chatty about what it is up to. +.. ghc-flag:: -ddump-simpl + :shortdesc: Dump final simplifier output + :type: dynamic -.. ghc-flag:: -ddump-vt-trace + Dump simplifier output (Core-to-Core passes) - Make the vectoriser be *real* chatty about what it is up to. +.. ghc-flag:: -ddump-inlinings + :shortdesc: Dump inlining info + :type: dynamic -.. ghc-flag:: -ddump-rn-trace + Dumps inlining info from the simplifier. Note that if used in + conjunction with :ghc-flag:`-dverbose-core2core` the compiler will + also dump the inlinings that it considers but passes up, along with + its rationale. - Make the renamer be *real* chatty about what it is up to. +.. ghc-flag:: -ddump-stranal + :shortdesc: Dump strictness analyser output + :type: dynamic -.. ghc-flag:: -ddump-ec-trace + Dump strictness analyser output - Make the pattern match exhaustiveness checker be *real* chatty about - what it is up to. +.. ghc-flag:: -ddump-str-signatures + :shortdesc: Dump strictness signatures + :type: dynamic -.. ghc-flag:: -ddump-rn-stats + Dump strictness signatures - Print out summary of what kind of information the renamer had to - bring in. +.. ghc-flag:: -ddump-cse + :shortdesc: Dump CSE output + :type: dynamic -.. ghc-flag:: -dverbose-core2core - -dverbose-stg2stg + Dump common subexpression elimination (CSE) pass output - Show the output of the intermediate Core-to-Core and STG-to-STG - passes, respectively. (*lots* of output!) So: when we're really - desperate: +.. ghc-flag:: -ddump-worker-wrapper + :shortdesc: Dump worker-wrapper output + :type: dynamic - .. code-block:: sh + Dump worker/wrapper split output - % ghc -noC -O -ddump-simpl -dverbose-core2core -dcore-lint Foo.hs +.. ghc-flag:: -ddump-occur-anal + :shortdesc: Dump occurrence analysis output + :type: dynamic -.. ghc-flag:: -dshow-passes + Dump "occurrence analysis" output - Print out each pass name, its runtime and heap allocations as it happens. - Note that this may come at a slight performance cost as the compiler will - be a bit more eager in forcing pass results to more accurately account for - their costs. +.. ghc-flag:: -ddump-prep + :shortdesc: Dump prepared core + :type: dynamic - Two types of messages are produced: Those beginning with ``***`` are - denote the beginning of a compilation phase whereas those starting with - ``!!!`` mark the end of a pass and are accompanied by allocation and - runtime statistics. + Dump output of Core preparation pass -.. ghc-flag:: -ddump-core-stats - Print a one-line summary of the size of the Core program at the end - of the optimisation pipeline. +STG representation +~~~~~~~~~~~~~~~~~~ -.. ghc-flag:: -dfaststring-stats +These flags dump various phases of GHC's STG pipeline. - Show statistics on the usage of fast strings by the compiler. +.. ghc-flag:: -ddump-stg + :shortdesc: Dump final STG + :type: dynamic -.. ghc-flag:: -dppr-debug + Dump output of STG-to-STG passes + +.. ghc-flag:: -dverbose-stg2stg + :shortdesc: Show output from each STG-to-STG pass + :type: dynamic + + Show the output of the intermediate STG-to-STG pass. (*lots* of output!) + + +C-\\- representation +~~~~~~~~~~~~~~~~~~~~ + +These flags dump various phases of GHC's C-\\- pipeline. + +.. ghc-flag:: -ddump-cmm-verbose + :shortdesc: Show output from main C-\\- pipeline passes + :type: dynamic + + Dump output from main C-\\- pipeline stages. In case of + ``.cmm`` compilation this also dumps the result of + file parsing. Not included are passes run by + the chosen backend. Currently only the NCG backends runs + additional passes ( :ghc-flag:`-ddump-opt-cmm` ). + + Cmm dumps don't include unreachable blocks since we print + blocks in reverse post-order. + +.. ghc-flag:: -ddump-cmm-from-stg + :shortdesc: Dump STG-to-C-\\- output + :type: dynamic + + Dump the result of STG-to-C-\\- conversion + +.. ghc-flag:: -ddump-cmm-raw + :shortdesc: Dump raw C-\\- + :type: dynamic + + Dump the “raw” C-\\-. + +.. ghc-flag:: -ddump-cmm-cfg + :shortdesc: Dump the results of the C-\\- control flow optimisation pass. + :type: dynamic + + Dump the results of the C-\\- control flow optimisation pass. + +.. ghc-flag:: -ddump-cmm-cbe + :shortdesc: Dump the results of common block elimination + :type: dynamic + + Dump the results of the C-\\- Common Block Elimination (CBE) pass. + +.. ghc-flag:: -ddump-cmm-switch + :shortdesc: Dump the results of switch lowering passes + :type: dynamic + + Dump the results of the C-\\- switch lowering pass. + +.. ghc-flag:: -ddump-cmm-proc + :shortdesc: Dump the results of proc-point analysis + :type: dynamic + + Dump the results of the C-\\- proc-point analysis pass. + +.. ghc-flag:: -ddump-cmm-sp + :shortdesc: Dump the results of the C-\\- stack layout pass. + :type: dynamic + + Dump the results of the C-\\- stack layout pass. + +.. ghc-flag:: -ddump-cmm-sink + :shortdesc: Dump the results of the C-\\- sinking pass. + :type: dynamic + + Dump the results of the C-\\- sinking pass. + +.. ghc-flag:: -ddump-cmm-caf + :shortdesc: Dump the results of the C-\\- CAF analysis pass. + :type: dynamic + + Dump the results of the C-\\- CAF analysis pass. + +.. ghc-flag:: -ddump-cmm-procmap + :shortdesc: Dump the results of the C-\\- proc-point map pass. + :type: dynamic + + Dump the results of the C-\\- proc-point map pass. + +.. ghc-flag:: -ddump-cmm-split + :shortdesc: Dump the results of the C-\\- proc-point splitting pass. + :type: dynamic + + Dump the results of the C-\\- proc-point splitting pass. + +.. ghc-flag:: -ddump-cmm-info + :shortdesc: Dump the results of the C-\\- info table augmentation pass. + :type: dynamic + + Dump the results of the C-\\- info table augmentation pass. + +.. ghc-flag:: -ddump-cmm-cps + :shortdesc: Dump the results of the CPS pass + :type: dynamic + + Dump the results of the CPS pass. + +.. ghc-flag:: -ddump-cmm + :shortdesc: Dump the final C-\\- output + :type: dynamic + + Dump the result of the C-\\- pipeline processing + + + +LLVM code generator +~~~~~~~~~~~~~~~~~~~~~~ + +.. ghc-flag:: -ddump-llvm + :shortdesc: Dump LLVM intermediate code. + :type: dynamic + + :implies: :ghc-flag:`-fllvm` + + LLVM code from the :ref:`LLVM code generator <llvm-code-gen>` + +Native code generator +~~~~~~~~~~~~~~~~~~~~~ + +These flags dump various stages of the :ref:`native code generator's +<native-code-gen>` pipeline, which starts with C-\\- and produces native +assembler. + +.. ghc-flag:: -ddump-opt-cmm + :shortdesc: Dump the results of C-\\- to C-\\- optimising passes + :type: dynamic + + Dump the results of C-\\- to C-\\- optimising passes performed by the NCG. + +.. ghc-flag:: -ddump-asm-native + :shortdesc: Dump initial assembly + :type: dynamic + + Dump the initial assembler output produced from C-\\-. + +.. ghc-flag:: -ddump-asm-liveness + :shortdesc: Dump assembly augmented with register liveness + :type: dynamic + + Dump the result of the register liveness pass. + +.. ghc-flag:: -ddump-asm-regalloc + :shortdesc: Dump the result of register allocation + :type: dynamic + + Dump the result of the register allocation pass. + +.. ghc-flag:: -ddump-asm-regalloc-stages + :shortdesc: Dump the build/spill stages of the :ghc-flag:`-fregs-graph` + register allocator. + :type: dynamic + + Dump the build/spill stages of the :ghc-flag:`-fregs-graph` register + allocator. + +.. ghc-flag:: -ddump-asm-stats + :shortdesc: Dump statistics from the register allocator. + :type: dynamic + + Dump statistics from the register allocator. + +.. ghc-flag:: -ddump-asm-expanded + :shortdesc: Dump the result of the synthetic instruction expansion pass. + :type: dynamic + + Dump the result of the synthetic instruction expansion pass. + +.. ghc-flag:: -ddump-asm + :shortdesc: Dump final assembly + :type: dynamic + + Dump the final assembly produced by the native code generator. + + +Miscellaneous backend dumps +~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +These flags dump various bits of information from other backends. + +.. ghc-flag:: -ddump-bcos + :shortdesc: Dump interpreter byte code + :type: dynamic + + Dump byte-code objects (BCOs) produced for the GHC's byte-code interpreter. + +.. ghc-flag:: -ddump-rtti + :shortdesc: Trace runtime type inference + :type: dynamic + + Trace runtime type inference done by various interpreter commands. + +.. ghc-flag:: -ddump-foreign + :shortdesc: Dump ``foreign export`` stubs + :type: dynamic + + Dump foreign export stubs. - Debugging output is in one of several "styles." Take the printing of - types, for example. In the "user" style (the default), the - compiler's internal ideas about types are presented in Haskell - source-level syntax, insofar as possible. In the "debug" style - (which is the default for debugging output), the types are printed - in with explicit foralls, and variables have their unique-id - attached (so you can check for things that look the same but - aren't). This flag makes debugging output appear in the more verbose - debug style. .. _formatting dumps: @@ -277,23 +580,46 @@ Formatting dumps single: formatting dumps .. ghc-flag:: -dppr-user-length + :shortdesc: Set the depth for printing expressions in error msgs + :type: dynamic In error messages, expressions are printed to a certain "depth", with subexpressions beyond the depth replaced by ellipses. This flag sets the depth. Its default value is 5. .. ghc-flag:: -dppr-cols=⟨n⟩ + :shortdesc: Set the width of debugging output. For example ``-dppr-cols200`` + :type: dynamic Set the width of debugging output. Use this if your code is wrapping too much. For example: ``-dppr-cols=200``. .. ghc-flag:: -dppr-case-as-let + :shortdesc: Print single alternative case expressions as strict lets. + :type: dynamic Print single alternative case expressions as though they were strict let expressions. This is helpful when your code does a lot of unboxing. +.. ghc-flag:: -dhex-word-literals + :shortdesc: Print values of type `Word#` in hexadecimal. + :type: dynamic + + Print values of type `Word#` and `Word64#` (but not values of + type `Int#` and `Int64#`) in hexadecimal instead of decimal. + The hexadecimal is zero-padded to make the length of the + representation a power of two. For example: `0x0A0A##`, + `0x000FFFFF##`, `0xC##`. This flag may be helpful when you + are producing a bit pattern that to expect to work correctly on a 32-bit + or a 64-bit architecture. Dumping hexadecimal literals after + optimizations and constant folding makes it easier to confirm + that the generated bit pattern is correct. + .. ghc-flag:: -dno-debug-output + :shortdesc: Suppress unsolicited debugging output + :type: dynamic + :reverse: -ddebug-output Suppress any unsolicited debugging output. When GHC has been built with the ``DEBUG`` option it occasionally emits debug output of @@ -314,16 +640,24 @@ are doing, not all of it will be useful. Use these flags to suppress the parts that you are not interested in. .. ghc-flag:: -dsuppress-all + :shortdesc: In dumps, suppress everything (except for uniques) that is + suppressible. + :type: dynamic 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. .. ghc-flag:: -dsuppress-ticks + :shortdesc: Suppress "ticks" in the pretty-printer output. + :type: dynamic Suppress "ticks" in the pretty-printer output. .. ghc-flag:: -dsuppress-uniques + :shortdesc: Suppress the printing of uniques in debug output (easier to use + ``diff``) + :type: dynamic Suppress the printing of uniques. This may make the printout ambiguous (e.g. unclear where an occurrence of 'x' is bound), but it @@ -333,6 +667,9 @@ parts that you are not interested in. :ghc-flag:`-dsuppress-uniques` .. ghc-flag:: -dsuppress-idinfo + :shortdesc: Suppress extended information about identifiers where they + are bound + :type: dynamic Suppress extended information about identifiers where they are bound. This includes strictness information and inliner templates. @@ -340,27 +677,59 @@ parts that you are not interested in. the lack of inliner templates .. ghc-flag:: -dsuppress-unfoldings + :shortdesc: Suppress the printing of the stable unfolding of a variable at + its binding site + :type: dynamic Suppress the printing of the stable unfolding of a variable at its binding site. .. ghc-flag:: -dsuppress-module-prefixes + :shortdesc: Suppress the printing of module qualification prefixes + :type: dynamic Suppress the printing of module qualification prefixes. This is the ``Data.List`` in ``Data.List.length``. +.. ghc-flag:: -dsuppress-timestamps + :shortdesc: Suppress timestamps in dumps + :type: dynamic + + Suppress the printing of timestamps. + This makes it easier to diff dumps. + .. ghc-flag:: -dsuppress-type-signatures + :shortdesc: Suppress type signatures + :type: dynamic Suppress the printing of type signatures. .. ghc-flag:: -dsuppress-type-applications + :shortdesc: Suppress type applications + :type: dynamic Suppress the printing of type applications. .. ghc-flag:: -dsuppress-coercions + :shortdesc: Suppress the printing of coercions in Core dumps to make them + shorter + :type: dynamic Suppress the printing of type coercions. +.. ghc-flag:: -dsuppress-var-kinds + :shortdesc: Suppress the printing of variable kinds + :type: dynamic + + Suppress the printing of variable kinds + +.. ghc-flag:: -dsuppress-stg-free-vars + :shortdesc: Suppress the printing of closure free variable lists in STG output + :type: dynamic + + Suppress the printing of closure free variable lists in STG output + + .. _checking-consistency: Checking for consistency @@ -371,25 +740,54 @@ Checking for consistency single: lint .. ghc-flag:: -dcore-lint + :shortdesc: Turn on internal sanity checking + :type: dynamic Turn on heavyweight intra-pass sanity-checking within GHC, at Core level. (It checks GHC's sanity, not yours.) .. ghc-flag:: -dstg-lint + :shortdesc: STG pass sanity checking + :type: dynamic - Ditto for STG level. (note: currently doesn't work). + Ditto for STG level. .. ghc-flag:: -dcmm-lint + :shortdesc: C-\\- pass sanity checking + :type: dynamic - Ditto for C-- level. + Ditto for C-\\- level. .. ghc-flag:: -fllvm-fill-undef-with-garbage + :shortdesc: Intruct LLVM to fill dead STG registers with garbage + :type: dynamic Instructs the LLVM code generator to fill dead STG registers with garbage instead of ``undef`` in calls. This makes it easier to catch subtle code generator and runtime system bugs (e.g. see :ghc-ticket:`11487`). +.. ghc-flag:: -falignment-sanitisation + :shortdesc: Compile with alignment checks for all info table dereferences. + :type: dynamic + + Compile with alignment checks for all info table dereferences. This can be + useful when finding pointer tagging issues. + +.. ghc-flag:: -fproc-alignment + :shortdesc: Align functions at given boundary. + :type: dynamic + + Align functions to multiples of the given value. Only valid values are powers + of two. + + ``-fproc-alignment=64`` can be used to limit alignment impact on performance + as each function will start at a cache line. + However forcing larger alignments in general reduces performance. + .. ghc-flag:: -fcatch-bottoms + :shortdesc: Insert ``error`` expressions after bottoming expressions; useful + when debugging the compiler. + :type: dynamic Instructs the simplifier to emit ``error`` expressions in the continuation of empty case analyses (which should bottom and consequently not return). @@ -405,10 +803,14 @@ Checking for determinism single: deterministic builds .. ghc-flag:: -dinitial-unique=⟨s⟩ + :shortdesc: Start ``UniqSupply`` allocation from ⟨s⟩. + :type: dynamic Start ``UniqSupply`` allocation from ⟨s⟩. .. ghc-flag:: -dunique-increment=⟨i⟩ + :shortdesc: Set the increment for the generated ``Unique``'s to ⟨i⟩. + :type: dynamic Set the increment for the generated ``Unique``'s to ⟨i⟩. diff --git a/docs/users_guide/editing-guide.rst b/docs/users_guide/editing-guide.rst index b57a5d12b9..8dd3701371 100644 --- a/docs/users_guide/editing-guide.rst +++ b/docs/users_guide/editing-guide.rst @@ -347,11 +347,29 @@ Will be rendered as, Sets the context switch interval to ⟨s⟩ seconds. -and will have an associated index entry generated automatically. Note that, as -in Style Conventions below, we use ``⟨⟩`` instead of less-than/greater-than -signs. To reference a ``ghc-flag`` or ``rts-flag``, you must match the -definition exactly, including the arguments. A quick way to find the exact -names and special characters is, +and will have an associated index entry generated automatically. + +The ``ghc-flag`` directive requires a few extra parameters to be passed. +This extra information is used to generate the :ref:`flag-reference` and the +man page. A ``ghc-flag`` directive looks like this, + +.. code-block:: rest + + .. ghc-flag:: -fasm + :shortdesc: Use the native code generator + :type: dynamic + :reverse: -fllvm + :category: codegen + + Regular description... + +When rendered, the extra parameters will be hidden, and the data stored for +later use. For more details, see the Sphinx extension ``flags.py``. + +Note that, as in Style Conventions below, we use ``⟨⟩`` instead of +less-than/greater-than signs. To reference a ``ghc-flag`` or ``rts-flag``, you +must match the definition exactly, including the arguments. A quick way to find +the exact names and special characters is, .. code-block:: sh @@ -401,17 +419,6 @@ user-substitutable tokens. In this document we use the convention, ``⟨subst⟩ less-than/greater-than signs). -.. _references: - -GHC command-line options reference ----------------------------------- - -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 -: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/eventlog-formats.rst b/docs/users_guide/eventlog-formats.rst index 8b1427d7d5..9910d4dbb0 100644 --- a/docs/users_guide/eventlog-formats.rst +++ b/docs/users_guide/eventlog-formats.rst @@ -33,12 +33,13 @@ A single fixed-width event emitted during program start-up describing the sample * ``Word64``: Sampling period in nanoseconds * ``Word32``: Sample break-down type. One of, - * ``SAMPLE_TYPE_COST_CENTER`` (output from ``-hc``) - * ``SAMPLE_TYPE_CLOSURE_DESCR`` (output from ``-hd``) - * ``SAMPLE_TYPE_RETAINER`` (output from ``-hr``) - * ``SAMPLE_TYPE_MODULE`` (output from ``-hm``) - * ``SAMPLE_TYPE_TYPE_DESCR`` (output from ``-hy``) - * ``SAMPLE_TYPE_BIOGRAPHY`` (output from ``-hb``) + * ``HEAP_PROF_BREAKDOWN_COST_CENTER`` (output from :rts-flag:`-hc`) + * ``HEAP_PROF_BREAKDOWN_CLOSURE_DESCR`` (output from :rts-flag:`-hd`) + * ``HEAP_PROF_BREAKDOWN_RETAINER`` (output from :rts-flag:`-hr`) + * ``HEAP_PROF_BREAKDOWN_MODULE`` (output from :rts-flag:`-hm`) + * ``HEAP_PROF_BREAKDOWN_TYPE_DESCR`` (output from :rts-flag:`-hy`) + * ``HEAP_PROF_BREAKDOWN_BIOGRAPHY`` (output from :rts-flag:`-hb`) + * ``HEAP_PROF_BREAKDOWN_CLOSURE_TYPE`` (output from :rts-flag:`-hT`) * ``String``: Module filter * ``String``: Closure description filter diff --git a/docs/users_guide/extending_ghc.rst b/docs/users_guide/extending_ghc.rst index 4a3e02e83e..ef07f61f2d 100644 --- a/docs/users_guide/extending_ghc.rst +++ b/docs/users_guide/extending_ghc.rst @@ -130,10 +130,10 @@ when invoked: import GHC import GHC.Paths ( libdir ) - import DynFlags ( defaultLogAction ) - - main = - defaultErrorHandler defaultLogAction $ do + import DynFlags ( defaultFatalMessager, defaultFlushOut ) + + main = + defaultErrorHandler defaultFatalMessager defaultFlushOut $ do runGhc (Just libdir) $ do dflags <- getSessionDynFlags setSessionDynFlags dflags @@ -157,7 +157,7 @@ Compiling it results in: [1 of 1] Compiling Main ( simple_ghc_api.hs, simple_ghc_api.o ) Linking simple_ghc_api ... $ ./simple_ghc_api - $ ./test_main + $ ./test_main hi $ @@ -179,12 +179,15 @@ GHC's intermediate language, Core. Plugins are suitable for experimental analysis or optimization, and require no changes to GHC's source code to use. -Plugins cannot optimize/inspect C--, nor can they implement things like +Plugins cannot optimize/inspect C-\\-, nor can they implement things like parser/front-end modifications like GCC, apart from limited changes to the constraint solver. If you feel strongly that any of these restrictions are too onerous, :ghc-wiki:`please give the GHC team a shout <MailingListsAndIRC>`. +Plugins do not work with ``-fexternal-interpreter``. If you need to run plugins +with ``-fexternal-interpreter`` let GHC developers know in :ghc-ticket:`14335`. + .. _using-compiler-plugins: Using compiler plugins @@ -196,13 +199,22 @@ module in a registered package that exports a plugin. Arguments can be given to plugins with the :ghc-flag:`-fplugin-opt=⟨module⟩:⟨args⟩` option. .. ghc-flag:: -fplugin=⟨module⟩ + :shortdesc: Load a plugin exported by a given module + :type: dynamic + :category: plugins 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⟩ + :shortdesc: Give arguments to a plugin module; module must be specified with + :ghc-flag:`-fplugin=⟨module⟩` + :type: dynamic + :category: plugins + + Give arguments to a plugin module; module must be specified with + :ghc-flag:`-fplugin=⟨module⟩`. - 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 @@ -221,12 +233,27 @@ would invoke GHC like this: Linking Test ... $ +Alternatively, core plugins can be specified with Template Haskell. + +:: + + addCorePlugin "Foo.Plugin" + +This inserts the plugin as a core-to-core pass. Unlike `-fplugin=(module)`, +the plugin module can't reside in the same package as the module calling +:th-ref:`Language.Haskell.TH.Syntax.addCorePlugin`. This way, the +implementation can expect the plugin to be built by the time +it is needed. + Plugin modules live in a separate namespace from 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: .. ghc-flag:: -plugin-package ⟨pkg⟩ + :shortdesc: Expose ⟨pkg⟩ for plugins + :type: dynamic + :category: plugins This option causes the installed package ⟨pkg⟩ to be exposed for plugins, such as :ghc-flag:`-fplugin=⟨module⟩`. The package ⟨pkg⟩ can be specified @@ -241,6 +268,9 @@ control specifically plugin packages: to be linked into the resulting executable or shared object. .. ghc-flag:: -plugin-package-id ⟨pkg-id⟩ + :shortdesc: Expose ⟨pkg-id⟩ for plugins + :type: dynamic + :category: plugins Exposes a package in the plugin namespace like :ghc-flag:`-plugin-package ⟨pkg⟩`, but the package is named by its installed package ID rather than by @@ -251,6 +281,9 @@ control specifically plugin packages: described in :ref:`package-thinning-and-renaming`. .. ghc-flag:: -hide-all-plugin-packages + :shortdesc: Hide all packages for plugins by default + :type: dynamic + :category: plugins By default, all exposed packages in the normal, source import namespace are also available for plugins. This causes those packages to be hidden by @@ -319,7 +352,7 @@ Core plugins in more detail ``CoreToDo`` is effectively a data type that describes all the kinds of optimization passes GHC does on Core. There are passes for -simplification, CSE, vectorisation, etc. There is a specific case for +simplification, CSE, etc. There is a specific case for plugins, ``CoreDoPluginPass :: String -> PluginPass -> CoreToDo`` which should be what you always use when inserting your own pass into the pipeline. The first parameter is the name of the plugin, and the second @@ -392,7 +425,7 @@ in a module it compiles: where printBind :: DynFlags -> CoreBind -> CoreM CoreBind printBind dflags bndr@(NonRec b _) = do putMsgS $ "Non-recursive binding named " ++ showSDoc dflags (ppr b) - return bndr + return bndr printBind _ bndr = return bndr .. _getting-annotations: @@ -567,6 +600,276 @@ the plugin to create equality axioms for use in evidence terms, but GHC does not check their consistency, and inconsistent axiom sets may lead to segfaults or other runtime misbehaviour. +.. _source-plugins: + +Source plugins +~~~~~~~~~~~~~~ + +In addition to core and type checker plugins, you can install plugins that can +access different representations of the source code. The main purpose of these +plugins is to make it easier to implement development tools. + +There are several different access points that you can use for defining plugins +that access the representations. All these fields receive the list of +``CommandLineOption`` strings that are passed to the compiler using the +:ghc-flag:`-fplugin-opt` flags. + +:: + + plugin :: Plugin + plugin = defaultPlugin { + parsedResultAction = parsed + , typeCheckResultAction = typechecked + , spliceRunAction = spliceRun + , interfaceLoadAction = interfaceLoad + , renamedResultAction = renamed + } + +Parsed representation +^^^^^^^^^^^^^^^^^^^^^ + +When you want to define a plugin that uses the syntax tree of the source code, +you would like to override the ``parsedResultAction`` field. This access point +enables you to get access to information about the lexical tokens and comments +in the source code as well as the original syntax tree of the compiled module. + +:: + + parsed :: [CommandLineOption] -> ModSummary -> HsParsedModule + -> Hsc HsParsedModule + +The ``ModSummary`` contains useful +meta-information about the compiled module. The ``HsParsedModule`` contains the +lexical and syntactical information we mentioned before. The result that you +return will change the result of the parsing. If you don't want to change the +result, just return the ``HsParsedModule`` that you received as the argument. + +Type checked representation +^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +When you want to define a plugin that needs semantic information about the +source code, use the ``typeCheckResultAction`` field. For example, if your +plugin have to decide if two names are referencing the same definition or it has +to check the type of a function it is using semantic information. In this case +you need to access the renamed or type checked version of the syntax tree with +``typeCheckResultAction`` or ``renamedResultAction``. + +:: + + typechecked :: [CommandLineOption] -> ModSummary -> TcGblEnv -> TcM TcGblEnv + renamed :: [CommandLineOption] -> TcGblEnv -> HsGroup GhcRn -> TcM (TcGblEnv, HsGroup GhcRn) + +By overriding the ``renamedResultAction`` field we can modify each ``HsGroup`` +after it has been renamed. A source file is seperated into groups depending on +the location of template haskell splices so the contents of these groups may +not be intuitive. In order to save the entire renamed AST for inspection +at the end of typechecking you can set ``renamedResultAction`` to ``keepRenamedSource`` +which is provided by the ``Plugins`` module. +This is important because some parts of the renamed +syntax tree (for example, imports) are not found in the typechecked one. + + + +Evaluated code +^^^^^^^^^^^^^^ + +When the compiler type checks the source code, :ref:`template-haskell` Splices +and :ref:`th-quasiquotation` will be replaced by the syntax tree fragments +generated from them. However for tools that operate on the source code the +code generator is usually more interesting than the generated code. For this +reason we included ``spliceRunAction``. This field is invoked on each expression +before they are evaluated. The input is type checked, so semantic information is +available for these syntax tree fragments. If you return a different expression +you can change the code that is generated. + + +:: + + spliceRun :: [CommandLineOption] -> LHsExpr GhcTc -> TcM (LHsExpr GhcTc) + + +However take care that the generated definitions are still in the input of +``typeCheckResultAction``. If your don't take care to filter the typechecked +input, the behavior of your tool might be inconsistent. + +Interface files +^^^^^^^^^^^^^^^ + +Sometimes when you are writing a tool, knowing the source code is not enough, +you also have to know details about the modules that you import. In this case we +suggest using the ``interfaceLoadAction``. This will be called each time when +the code of an already compiled module is loaded. It will be invoked for modules +from installed packages and even modules that are installed with GHC. It will +NOT be invoked with your own modules. + +:: + + interfaceLoad :: forall lcl . [CommandLineOption] -> ModIface + -> IfM lcl ModIface + +In the ``ModIface`` datatype you can find lots of useful information, including +the exported definitions and type class instances. + + +Source plugin example +^^^^^^^^^^^^^^^^^^^^^ + +In this example, we inspect all available details of the compiled source code. +We don't change any of the representation, but write out the details to the +standard output. The pretty printed representation of the parsed, renamed and +type checked syntax tree will be in the output as well as the evaluated splices +and quasi quotes. The name of the interfaces that are loaded will also be +displayed. + +:: + + module SourcePlugin where + + import Control.Monad.IO.Class + import DynFlags (getDynFlags) + import Plugins + import HscTypes + import TcRnTypes + import HsExtension + import HsDecls + import HsExpr + import HsImpExp + import Avail + import Outputable + import HsDoc + + plugin :: Plugin + plugin = defaultPlugin { parsedResultAction = parsedPlugin + , renamedResultAction = Just renamedAction + , typeCheckResultAction = typecheckPlugin + , spliceRunAction = metaPlugin + , interfaceLoadAction = interfaceLoadPlugin + } + + parsedPlugin :: [CommandLineOption] -> ModSummary -> HsParsedModule -> Hsc HsParsedModule + parsedPlugin _ _ pm + = do dflags <- getDynFlags + liftIO $ putStrLn $ "parsePlugin: \n" ++ (showSDoc dflags $ ppr $ hpm_module pm) + return pm + + renamedAction :: [CommandLineOption] -> ModSummary + -> ( HsGroup GhcRn, [LImportDecl GhcRn] + , Maybe [(LIE GhcRn, Avails)], Maybe LHsDocString ) + -> TcM () + renamedAction _ _ ( gr, _, _, _ ) + = do dflags <- getDynFlags + liftIO $ putStrLn $ "typeCheckPlugin (rn): " ++ (showSDoc dflags $ ppr gr) + + typecheckPlugin :: [CommandLineOption] -> ModSummary -> TcGblEnv -> TcM TcGblEnv + typecheckPlugin _ _ tc + = do dflags <- getDynFlags + liftIO $ putStrLn $ "typeCheckPlugin (rn): \n" ++ (showSDoc dflags $ ppr $ tcg_rn_decls tc) + liftIO $ putStrLn $ "typeCheckPlugin (tc): \n" ++ (showSDoc dflags $ ppr $ tcg_binds tc) + return tc + + metaPlugin :: [CommandLineOption] -> LHsExpr GhcTc -> TcM (LHsExpr GhcTc) + metaPlugin _ meta + = do dflags <- getDynFlags + liftIO $ putStrLn $ "meta: " ++ (showSDoc dflags $ ppr meta) + return meta + + interfaceLoadPlugin :: [CommandLineOption] -> ModIface -> IfM lcl ModIface + interfaceLoadPlugin _ iface + = do dflags <- getDynFlags + liftIO $ putStrLn $ "interface loaded: " ++ (showSDoc dflags $ ppr $ mi_module iface) + return iface + +When you compile a simple module that contains Template Haskell splice + +:: + + {-# LANGUAGE TemplateHaskell #-} + module A where + + a = () + + $(return []) + +with the compiler flags ``-fplugin SourcePlugin`` it will give the following +output: + +.. code-block:: none + + parsePlugin: + module A where + a = () + $(return []) + interface loaded: Prelude + interface loaded: GHC.Float + interface loaded: GHC.Base + interface loaded: Language.Haskell.TH.Lib.Internal + interface loaded: Language.Haskell.TH.Syntax + interface loaded: GHC.Types + meta: return [] + interface loaded: GHC.Integer.Type + typeCheckPlugin (rn): + Just a = () + typeCheckPlugin (tc): + {$trModule = Module (TrNameS "main"#) (TrNameS "A"#), a = ()} + + +.. _plugin_recompilation: + +Controlling Recompilation +~~~~~~~~~~~~~~~~~~~~~~~~~ + +By default, modules compiled with plugins are always recompiled even if the source file is +unchanged. This most conservative option is taken due to the ability of plugins +to perform arbitrary IO actions. In order to control the recompilation behaviour +you can modify the ``pluginRecompile`` field in ``Plugin``. :: + + plugin :: Plugin + plugin = defaultPlugin { + installCoreToDos = install, + pluginRecompile = purePlugin + } + +By inspecting the example ``plugin`` defined above, we can see that it is pure. This +means that if the two modules have the same fingerprint then the plugin +will always return the same result. Declaring a plugin as pure means that +the plugin will never cause a module to be recompiled. + +In general, the ``pluginRecompile`` field has the following type:: + + pluginRecompile :: [CommandLineOption] -> IO PluginRecompile + +The ``PluginRecompile`` data type is an enumeration determining how the plugin +should affect recompilation. :: + data PluginRecompile = ForceRecompile | NoForceRecompile | MaybeRecompile Fingerprint + +A plugin which declares itself impure using ``ForceRecompile`` will always +trigger a recompilation of the current module. ``NoForceRecompile`` is used +for "pure" plugins which don't need to be rerun unless a module would ordinarily +be recompiled. ``MaybeRecompile`` computes a ``Fingerprint`` and if this ``Fingerprint`` +is different to a previously computed ``Fingerprint`` for the plugin, then +we recompile the module. + +As such, ``purePlugin`` is defined as a function which always returns ``NoForceRecompile``. :: + + purePlugin :: [CommandLineOption] -> IO PluginRecompile + purePlugin _ = return NoForceRecompile + +Users can use the same functions that GHC uses internally to compute fingerprints. +The `GHC.Fingerprint +<https://hackage.haskell.org/package/base-4.10.1.0/docs/GHC-Fingerprint.html>`_ module provides useful functions for constructing fingerprints. For example, combining +together ``fingerprintFingerprints`` and ``fingerprintString`` provides an easy to +to naively fingerprint the arguments to a plugin. :: + + pluginFlagRecompile :: [CommandLineOption] -> IO PluginRecompile + pluginFlagRecompile = + return . MaybeRecompile . fingerprintFingerprints . map fingerprintString . sort + +``defaultPlugin`` defines ``pluginRecompile`` to be ``impurePlugin`` which +is the most conservative and backwards compatible option. :: + + impurePlugin :: [CommandLineOption] -> IO PluginRecompile + impurePlugin _ = return ForceRecompile + .. _frontend_plugins: Frontend plugins diff --git a/docs/users_guide/ffi-chap.rst b/docs/users_guide/ffi-chap.rst index 311146c4d9..62bad46781 100644 --- a/docs/users_guide/ffi-chap.rst +++ b/docs/users_guide/ffi-chap.rst @@ -7,7 +7,10 @@ Foreign function interface (FFI) single: Foreign function interface single: interfacing with native code -.. ghc-flag:: -XForeignFunctionInterface +.. extension:: ForeignFunctionInterface + :shortdesc: Enable foreign function interface. + + :since: 6.8.1 Allow use of the Haskell foreign function interface. @@ -16,7 +19,7 @@ definition is part of the Haskell Report on `http://www.haskell.org/ <http://www.haskell.org/>`__. FFI support is enabled by default, but can be enabled or disabled -explicitly with the :ghc-flag:`-XForeignFunctionInterface` flag. +explicitly with the :extension:`ForeignFunctionInterface` flag. GHC implements a number of GHC-specific extensions to the FFI Chapter of the Haskell 2010 Report. These extensions are described in :ref:`ffi-ghcexts`, but @@ -32,17 +35,22 @@ GHC differences to the FFI Chapter Guaranteed call safety ~~~~~~~~~~~~~~~~~~~~~~ -The FFI addendum stipulates that an implementation is free to implement an -``unsafe`` call by performing a ``safe`` call (and therefore may run in an -arbitrary thread and may be subject to concurrent garbage collection). This -greatly constrains library authors since it implies that it is never safe to -pass any heap object reference to a foreign function, even if invoked with an -``unsafe`` call. For instance, it is often desirable to pass an unpinned -``ByteArray#``\s directly to native code to avoid making an -otherwise-unnecessary copy. However, this can only be done safely under -``unsafe`` call semantics as otherwise the array may be moved by the garbage +The Haskell 2010 Report specifies that ``safe`` FFI calls must allow foreign +calls to safely call into Haskell code. In practice, this means that the +garbage collector must be able to run while these calls are in progress, +moving heap-allocated Haskell values around arbitrarily. + +This greatly constrains library authors since it implies that it is not safe to +pass any heap object reference to a ``safe`` foreign function call. For +instance, it is often desirable to pass an unpinned ``ByteArray#``\s directly +to native code to avoid making an otherwise-unnecessary copy. However, this can +only be done safely if the array is guaranteed not to be moved by the garbage collector in the middle of the call. +The Chapter does *not* require implementations to refrain from doing the +same for ``unsafe`` calls, so strictly Haskell 2010-conforming programs +cannot pass heap-allocated references to ``unsafe`` FFI calls either. + In previous releases, GHC would take advantage of the freedom afforded by the Chapter by performing ``safe`` foreign calls in place of ``unsafe`` calls in the bytecode interpreter. This meant that some packages which worked when @@ -50,7 +58,8 @@ compiled would fail under GHCi (e.g. :ghc-ticket:`13730`). However, since version 8.4 this is no longer the case: GHC **guarantees** that garbage collection will never occur during an ``unsafe`` call, even in the -bytecode interpreter. +bytecode interpreter, and further guarantees that ``unsafe`` calls will be +performed in the calling thread. .. _ffi-ghcexts: @@ -118,6 +127,11 @@ come with GHC. For more details see the Interruptible foreign calls ~~~~~~~~~~~~~~~~~~~~~~~~~~~ +.. extension:: InterruptibleFFI + :shortdesc: Enable interruptible FFI. + + :since: 7.2.1 + This concerns the interaction of foreign calls with ``Control.Concurrent.throwTo``. Normally when the target of a ``throwTo`` is involved in a foreign call, the exception is not raised @@ -152,7 +166,7 @@ Unix systems Windows systems [Vista and later only] The RTS calls the Win32 function - ``CancelSynchronousIO``, which will cause a blocking I/O operation + ``CancelSynchronousIo``, which will cause a blocking I/O operation to return with the error ``ERROR_OPERATION_ABORTED``. If the system call is successfully interrupted, it will return to @@ -167,6 +181,11 @@ it is not typically necessary to handle ``ERROR_OPERATION_ABORTED``. The CAPI calling convention ~~~~~~~~~~~~~~~~~~~~~~~~~~~ +.. extension:: CApiFFI + :shortdesc: Enable the CAPI calling convention. + + :since: 7.10.1 + The ``CApiFFI`` extension allows a calling convention of ``capi`` to be used in foreign declarations, e.g. :: @@ -226,6 +245,46 @@ allocated until ``hs_exit()`` is called. If you call it too often, the worst that can happen is that the next call to a Haskell function incurs some extra overhead. +.. _ffi-stable-ptr-extras: + +Freeing many stable pointers efficiently +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +The standard function ``hs_free_stable_ptr`` locks the stable pointer +table, frees the given stable pointer, and then unlocks the stable pointer +table again. When freeing many stable pointers at once, it is usually +more efficient to lock and unlock the table only once. + +.. code-block:: c + + extern void hs_lock_stable_ptr_table (void); + + extern void hs_unlock_stable_ptr_table (void); + + extern void hs_free_stable_ptr_unsafe (HsStablePtr sp); + +``hs_free_stable_ptr_unsafe`` must be used *only* when the table has been +locked using ``hs_lock_stable_ptr_table``. It must be unlocked afterwards +using ``hs_unlock_stable_ptr_table``. The Haskell garbage collector cannot +run while the table is locked, so it should be unlocked promptly. The +following operations are forbidden while the stable pointer table is locked: + +* Calling any Haskell function, whether or not that function + manipulates stable pointers. + +* Calling any FFI function that deals with the stable pointer table + except for arbitrarily many calls to ``hs_free_stable_ptr_unsafe`` + and the final call to ``hs_unlock_stable_ptr_table``. + +* Calling ``hs_free_fun_ptr``. + +.. note:: + + GHC versions before 8.8 defined undocumented functions + ``hs_lock_stable_tables`` and ``hs_unlock_stable_tables`` instead + of ``hs_lock_stable_ptr_table`` and ``hs_unlock_stable_ptr_table``. + Those names are now deprecated. + .. _ffi-ghc: Using the FFI with GHC @@ -337,6 +396,12 @@ reliably re-initialise after this has happened; see :ref:`infelicities-ffi`. don't forget the flag :ghc-flag:`-no-hs-main`, otherwise GHC will try to link to the ``Main`` Haskell module. +.. note:: + On Windows hs_init treats argv as UTF8-encoded. Passing other encodings + might lead to unexpected results. Passing NULL as argv is valid but can + lead to <unknown> showing up in error messages instead of the name of the + executable. + To use ``+RTS`` flags with ``hs_init()``, we have to modify the example slightly. By default, GHC's RTS will only accept "safe" ``+RTS`` flags (see :ref:`options-linker`), and the :ghc-flag:`-rtsopts[=⟨none|some|all⟩]` diff --git a/docs/users_guide/flags.py b/docs/users_guide/flags.py new file mode 100644 index 0000000000..c95b9aa96c --- /dev/null +++ b/docs/users_guide/flags.py @@ -0,0 +1,631 @@ +# GHC User's Guide flag extension +# +# This file defines a Sphinx extension to document GHC flags. +# It introduces a directive: +# +# .. ghc-flag:: +# :shortdesc: A short description (REQUIRED) +# :type: dynamic or mode (REQUIRED) +# :reverse: The reverse of the flag +# :category: The category to list the flag under (default: 'misc') +# :noindex: Do not list the flag anywhere (good for duplicates) +# +# That can be referenced using: +# +# :ghc-flag:`flag` +# +# As well as a directive to generate a display of flags: +# +# .. flag-print:: +# :type: table/list/summary (REQUIRED) +# :category: Limit the output to a single category +# +# It also provides a directive to list language extensions: +# +# .. extension:: +# :shortdesc: A short description (REQUIRED) +# :noindex: Do not list the extension anywhere (good for duplicates) +# +# This has the side-effect of an appropriate ghc-flag directive for the `-X` +# flag. +# +# Extensions can be referenced with +# +# :extension:`extension` +# +# Language exensions can be listed: +# +# .. extension-print:: +# :type: table/list/summary (REQUIRED) +# +# The two main functions in this extension are Flag.after_content() which adds +# flag metadata into the environment, and flagprint.generate_output(), which +# reads the metadata back out and formats it as desired. +# +# + +from docutils import nodes +from docutils.parsers.rst import Directive, directives +import sphinx +from sphinx import addnodes +from sphinx.domains.std import GenericObject +from sphinx.errors import SphinxError +from distutils.version import LooseVersion +from utils import build_table_from_list + +### Settings + +# Categories to titles as well as a canonical list of categories +categories = { + '': 'All flags', + 'codegen': 'Code generation', + 'coverage': 'Program coverage', + 'cpp': 'C pre-processor', + 'debugging': 'Debugging the compiler', + 'interactive': 'Interactive mode', + 'interface-files': 'Interface files', + 'keep-intermediates': 'Keeping intermediate files', + 'language': 'Language options', + 'linking': 'Linking options', + 'misc': 'Miscellaneous options', + 'modes': 'Modes of operation', + 'optimization': 'Individual optimizations', + 'optimization-levels': 'Optimization levels', + 'packages': 'Package options', + 'phases': 'Phases of compilation', + 'phase-programs': 'Overriding external programs', + 'phase-options': 'Phase-specific options', + 'platform-options': 'Platform-specific options', + 'plugins': 'Compiler plugins', + 'profiling': 'Profiling', + 'recompilation': 'Recompilation checking', + 'redirect-output': 'Redirecting output', + 'search-path': 'Finding imports', + 'temp-files': 'Temporary files', + 'verbosity': 'Verbosity options', + 'warnings': 'Warnings', +} + +# Map file names to default flag categories +file_defaults = { + 'debugging': 'debugging', + 'ghci': 'interactive', + 'glasgow_exts': 'language', + 'packages': 'packages', + 'profiling': 'profiling', + 'safe_haskell': 'language', + 'separate_compilation': 'redirect-output', + 'using-warnings': 'warnings', + 'using-optimisation': 'optimization' +} + + +### Flag declaration + +# Functionality to add a flag to the tables, used by both Flag and LanguageExtension +class GenericFlag(GenericObject): + def register_flag(self, names, category, name_string, shortdesc, flag_type, reverse_string): + # Create nodes for each cell of the table + name_node = nodes.paragraph() + shortdesc_node = nodes.paragraph() + type_node = nodes.paragraph() + reverse_node = nodes.paragraph() + + assert flag_type in ('dynamic', 'mode'), ('Unknown flag type for %s: %s' % + (name_string, flag_type)) + + # Nodes expect an internal ViewList type for the content, + # we are just spoofing it here + from docutils.statemachine import ViewList + name_vl = ViewList(initlist=[name_string], + source=self.env.docname, parent=[]) + shortdesc_vl = ViewList(initlist=[shortdesc], + source=self.env.docname, parent=[]) + type_vl = ViewList(initlist=[flag_type], + source=self.env.docname, parent=[]) + reverse_vl = ViewList(initlist=[reverse_string], + source=self.env.docname, parent=[]) + + + # Parse the content into the nodes + self.state.nested_parse(name_vl, 0, name_node) + self.state.nested_parse(shortdesc_vl, 0, shortdesc_node) + self.state.nested_parse(type_vl, 0, type_node) + self.state.nested_parse(reverse_vl, 0, reverse_node) + + + # The parsing adds extra layers that we don't need + name_node = name_node[0] + shortdesc_node = shortdesc_node[0] + + # Append this flag to the environment, initializing if necessary + if not hasattr(self.env, 'all_flags'): + self.env.all_flags = [] + self.env.all_flags.append({ + 'names': names, + 'docname': self.env.docname, + 'category': category, + 'cells': [name_node, shortdesc_node, type_node, reverse_node], + }) + +# This class inherits from Sphinx's internal GenericObject, which drives +# the add_object_type() utility function. We want to keep that tooling, +# but need to override some of the functionality. +class Flag(GenericFlag): + + # The options that can be passed to our directive and their validators + option_spec = { + 'shortdesc': directives.unchanged_required, + 'type': directives.unchanged_required, + 'reverse': directives.unchanged, + 'category': directives.unchanged, + 'noindex': directives.flag + } + + # The index directive generated unless :noindex: is specified + indextemplate = 'pair: %s; GHC option' + + + # Generate docutils node from directive arguments + @staticmethod + def _parse_flag(env, sig, signode): + + # Break flag into name and args + import re + parts = re.split(r'( |=|\[)', sig, 1) + flag = parts[0] + # Bold printed name + signode += addnodes.desc_name(flag, flag) + if len(parts) > 1: + args = ''.join(parts[1:]) + # Smaller arguments + signode += addnodes.desc_addname(args, args) + + # Reference name left unchanged + return sig + + # Used in the GenericObject class + parse_node = _parse_flag + + # Override the (empty) function that is called at the end of run() + # to append metadata about this flag into the environment + def after_content(self): + + # If noindex, then do not include this flag in the table + if 'noindex' in self.options: + return + + # Validity checking + if 'shortdesc' not in self.options: + raise SphinxError('ghc-flag (%s) directive missing :shortdesc: key' % self.names) + if 'type' not in self.options: + raise SphinxError('ghc-flag (%s) directive missing :type: key' % self.names) + + # Set the flag category (default: misc) + self.category = 'misc' + if not 'category' in self.options or self.options['category'] == '': + if self.env.docname in file_defaults: + self.category = file_defaults[self.env.docname] + else: + self.category = self.options['category'] + + # Manually create references + name_string = ", ".join([':ghc-flag:`'+n+'`' for n in self.names]) + reverse_string = '' + if 'reverse' in self.options and self.options['reverse'] != '': + reverse_string = ':ghc-flag:`' + self.options['reverse'] + '`' + + self.register_flag( + self.names, + self.category, + name_string, + self.options['shortdesc'], + self.options['type'], + reverse_string) + +# This class inherits from Sphinx's internal GenericObject, which drives +# the add_object_type() utility function. We want to keep that tooling, +# but need to override some of the functionality. +class LanguageExtension(GenericFlag): + + # The options that can be passed to our directive and their validators + option_spec = { + 'shortdesc': directives.unchanged_required, + 'noindex': directives.flag + } + + # The index directive generated unless :noindex: is specified + indextemplate = 'pair: %s; Language Extension' + + # Invert the flag + @staticmethod + def _noname(name): + if name[:2] == "No": + return name[2:] + else: + return "No%s" % name + + @staticmethod + def _onname(name): + if name[:2] == "No": + return name[2:] + else: + return name + + # Add additional targets + def add_target_and_index(self, name, sig, signode): + + GenericFlag.add_target_and_index(self, name, sig, signode) + + # Mostly for consistency in URL anchors + signode['ids'].append('ghc-flag--X%s' % name) + # So that anchors stay valid even if an extension turns to on-by-default + signode['ids'].append('extension-%s' % self._noname(name)) + + targetname = '%s-%s' % (self.objtype, name) + + # FIXME: This causes some Sphinx versions to fail + # Add index entries for the -XFoo flag + #self.indexnode['entries'].append(('pair', '-X%s; GHC option' % name, + # targetname, '', None)) + + # Make this also addressable using :ghc-flag:-XFoo + self.env.domaindata['std']['objects']['ghc-flag', '-X%s' % name] = \ + self.env.docname, 'extension-%s' % name + # Make this also addressable using :extension:-XNoFoo + self.env.domaindata['std']['objects']['extension', self._noname(name)] = \ + self.env.docname, 'extension-%s' % name + + + # Override the (empty) function that is called at the end of run() + # to append metadata about this flag into the environment + def after_content(self): + + # If noindex, then do not include this extension in the table + if 'noindex' in self.options: + return + + # Validity checking + if len(self.names) < 1: + raise SphinxError('extension needs at least one name') + primary_name = self.names[0] + if 'shortdesc' not in self.options: + raise SphinxError('extension (%s) directive missing :shortdesc: key' % primary_name) + + # Register the corresponding flags + for name in self.names: + self.register_flag( + ['-X%s' % name], + 'language', + ':extension:`-X%s <%s>`' % (name, primary_name), + self.options['shortdesc'], + 'dynamic', + ':extension:`-X%s <%s>`' % (self._noname(name), primary_name)) + + # Register the extension for the table, under the "on name" (no No...) + onname = self._onname(primary_name) + + name_node = nodes.paragraph() + shortdesc_node = nodes.paragraph() + # Nodes expect an internal ViewList type for the content, + # we are just spoofing it here + from docutils.statemachine import ViewList + name_vl = ViewList(initlist=[':extension:`%s`' % onname], + source=self.env.docname, parent=[]) + shortdesc_vl = ViewList(initlist=[self.options['shortdesc']], + source=self.env.docname, parent=[]) + # Parse the content into the nodes + self.state.nested_parse(name_vl, 0, name_node) + self.state.nested_parse(shortdesc_vl, 0, shortdesc_node) + # The parsing adds extra layers that we don't need + name_node = name_node[0] + shortdesc_node = shortdesc_node[0] + + if not hasattr(self.env, 'all_extensions'): + self.env.all_extensions = [] + self.env.all_extensions.append({ + 'name': onname, + 'docname': self.env.docname, + 'cells': [name_node, shortdesc_node] + }) + +### Flag Printing + + +# Generate a table of flags +def generate_flag_table(flags, category): + + # Create column headers for table + header = [] + for h in ["Flag", "Description", "Type", "Reverse"]: + inline = nodes.inline(text=h) + header.append(inline) + + flags_list = [header] + + for flag_info in flags: + + flags_list.append(flag_info['cells']) + + # The column width hints only apply to html, + # latex widths are set in file (see flags.rst) + table = build_table_from_list(flags_list, [28, 34, 10, 28]) + + # Flag tables have lots of content, so we need to set 'longtable' + # to allow for pagebreaks. (latex specific) + table['classes'].append('longtable') + + return table + + +# Generate a list of flags and their short descriptions +def generate_flag_list(flags, category): + + list_node = nodes.definition_list() + + for flag_info in flags: + + dl_item_node = nodes.definition_list_item() + term_node = nodes.term() + # The man writer is picky, so we have to remove the outer + # paragraph node to get just the flag name + term_node += flag_info['cells'][0][0] + dl_item_node += term_node + def_node = nodes.definition() + def_node += flag_info['cells'][1] + dl_item_node += def_node + + list_node += dl_item_node + + return list_node + + +# Generate a block of flag names under a category +def generate_flag_summary(flags, category): + + summary_node = nodes.definition_list_item() + term_node = nodes.term(text=categories[category]) + summary_node += term_node + block = nodes.definition() + summary_node += block + + # Fill block with flags + for flag_info in flags: + + for name in flag_info['names']: + block += nodes.literal(text=name) + block += nodes.inline(text=' ') + + block += nodes.inline(text='\n') + + return summary_node + +# Output dispatch table +flag_handlers = { + 'table': generate_flag_table, + 'list': generate_flag_list, + 'summary': generate_flag_summary +} + + +# Generic node for printing flag output +class flagprint(nodes.General, nodes.Element): + + def __init__(self, output_type='', category='', **kwargs): + + nodes.Element.__init__(self, rawsource='', **kwargs) + + # Verify options + if category not in categories: + error = "flagprint: Unknown category: " + category + raise ValueError(error) + if output_type not in flag_handlers: + error = "flagprint: Unknown output type: " + output_type + raise ValueError(error) + + # Store the options + self.options = { + 'type': output_type, + 'category': category + } + + + # The man writer has a copy issue, so we explicitly override it here + def copy(self): + newnode = flagprint(output_type=self.options['type'], + category=self.options['category'], **self.attributes) + newnode.source = self.source + newnode.line = self.line + return newnode + + + def generate_output(self, app, fromdocname): + env = app.builder.env + + # Filter flags before passing to flag_handlers + flags = [] + + for flag_info in sorted(env.all_flags, + key=lambda fi: fi['names'][0].lower()): + + if not (self.options['category'] == '' or + self.options['category'] == flag_info['category']): + continue + + # Resolve all references as if they were originated from this node. + # This fixes the relative uri. + for cell in flag_info['cells']: + for ref in cell.traverse(addnodes.pending_xref): + ref['refdoc'] = fromdocname + env.resolve_references(cell, flag_info['docname'], app.builder) + + flags.append(flag_info) + + handler = flag_handlers[self.options['type']] + self.replace_self(handler(flags, self.options['category'])) + +# A directive to create flagprint nodes +class FlagPrintDirective(Directive): + + option_spec = { + 'type': directives.unchanged_required, + 'category': directives.unchanged + } + + def run(self): + + # Process options + category = '' + if 'category' in self.options: + category = self.options['category'] + + # Create a flagprint node + node = flagprint(output_type=self.options['type'], category=category) + return [node] + +### Extension Printing + + +# Generate a table of flags +def generate_extension_table(extensions): + + # Create column headers for table + header = [] + for h in ["Extension", "Description"]: + inline = nodes.inline(text=h) + header.append(inline) + + extension_list = [header] + + for extension_info in extensions: + extension_list.append(extension_info['cells']) + + # The column width hints only apply to html, + # latex widths are set in file (see flags.rst) + table = build_table_from_list(extension_list, [28, 72]) + + # Flag tables have lots of content, so we need to set 'longtable' + # to allow for pagebreaks. (latex specific) + table['classes'].append('longtable') + + return table + + +# Output dispatch table +extension_handlers = { + 'table': generate_extension_table, +} + +# Generic node for printing extension output +class extensionprint(nodes.General, nodes.Element): + + def __init__(self, output_type='', **kwargs): + + nodes.Element.__init__(self, rawsource='', **kwargs) + + # Verify options + if output_type not in extension_handlers: + error = "extensionprint: Unknown output type: " + output_type + raise ValueError(error) + + # Store the options + self.options = { + 'type': output_type, + } + + + # The man writer has a copy issue, so we explicitly override it here + def copy(self): + newnode = extensionprint(output_type=self.options['type'], **self.attributes) + newnode.source = self.source + newnode.line = self.line + return newnode + + + def generate_output(self, app, fromdocname): + env = app.builder.env + + extensions = [] + + for extension_info in sorted(env.all_extensions, + key=lambda fi: fi['name'].lower()): + + # Resolve all references as if they were originated from this node. + # This fixes the relative uri. + for cell in extension_info['cells']: + for ref in cell.traverse(addnodes.pending_xref): + ref['refdoc'] = fromdocname + env.resolve_references(cell, extension_info['docname'], app.builder) + + extensions.append(extension_info) + + handler = extension_handlers[self.options['type']] + self.replace_self(handler(extensions)) + +# A directive to create extensionprint nodes +class ExtensionPrintDirective(Directive): + + option_spec = { + 'type': directives.unchanged_required + } + + def run(self): + # Create a extensionprint node + node = extensionprint(output_type=self.options['type']) + return [node] + + +### Additional processing + +# Convert every flagprint node into its output format +def process_print_nodes(app, doctree, fromdocname): + + for node in doctree.traverse(flagprint): + node.generate_output(app, fromdocname) + + for node in doctree.traverse(extensionprint): + node.generate_output(app, fromdocname) + + +# To avoid creating duplicates in the serialized environment, clear all +# flags originating from a file before re-reading it. +def purge_flags(app, env, docname): + + if hasattr(env, 'all_flags'): + env.all_flags = [flag for flag in env.all_flags + if flag['docname'] != docname] + if hasattr(env, 'all_extensions'): + env.all_extensions = [ext for ext in env.all_extensions + if ext['docname'] != docname] + +### Initialization + +def setup(app): + # The override argument to add_directive_to_domain is only supported by >= 1.8 + sphinx_version = LooseVersion(sphinx.__version__) + override_arg = {'override': True} if sphinx_version >= LooseVersion('1.8') else {} + + # Add ghc-flag directive, and override the class with our own + app.add_object_type('ghc-flag', 'ghc-flag') + app.add_directive_to_domain('std', 'ghc-flag', Flag, **override_arg) + + # Add extension directive, and override the class with our own + app.add_object_type('extension', 'extension') + app.add_directive_to_domain('std', 'extension', LanguageExtension, + **override_arg) + # NB: language-extension would be misinterpreted by sphinx, and produce + # lang="extensions" XML attributes + + # Add new node and directive + app.add_node(flagprint) + app.add_directive('flag-print', FlagPrintDirective) + + # Add new node and directive + app.add_node(extensionprint) + app.add_directive('extension-print', ExtensionPrintDirective) + + # Add our generator and cleanup functions as callbacks + app.connect('doctree-resolved', process_print_nodes) + app.connect('env-purge-doc', purge_flags) + + return {'version': '1.0'} diff --git a/docs/users_guide/flags.rst b/docs/users_guide/flags.rst index 4064f46bdf..5c2e7ae072 100644 --- a/docs/users_guide/flags.rst +++ b/docs/users_guide/flags.rst @@ -4,71 +4,143 @@ Flag reference ============== This section is a quick-reference for GHC's command-line flags. For each -flag, we also list its static/dynamic status (see -:ref:`static-dynamic-flags`), and the flag's opposite (if available). +flag, we also list its mode/dynamic status (see +:ref:`mode-dynamic-flags`), and the flag's opposite (if available). Verbosity options ----------------- More details in :ref:`options-help` -.. include:: flags-verbosity.gen.rst +.. tabularcolumns:: + | p{\dimexpr 0.33\textwidth-2\tabcolsep} | + p{\dimexpr 0.31\textwidth-2\tabcolsep} | + p{\dimexpr 0.11\textwidth-2\tabcolsep} | + p{\dimexpr 0.26\textwidth-2\tabcolsep} | + +.. flag-print:: + :type: table + :category: verbosity Alternative modes of operation ------------------------------ More details in :ref:`modes` -.. include:: flags-modes.gen.rst +.. tabularcolumns:: + | p{\dimexpr 0.30\textwidth-2\tabcolsep} | + p{\dimexpr 0.31\textwidth-2\tabcolsep} | + p{\dimexpr 0.11\textwidth-2\tabcolsep} | + p{\dimexpr 0.29\textwidth-2\tabcolsep} | + +.. flag-print:: + :type: table + :category: modes Which phases to run ------------------- More details in :ref:`options-order` -.. include:: flags-phases.gen.rst +.. tabularcolumns:: + | p{\dimexpr 0.30\textwidth-2\tabcolsep} | + p{\dimexpr 0.31\textwidth-2\tabcolsep} | + p{\dimexpr 0.11\textwidth-2\tabcolsep} | + p{\dimexpr 0.29\textwidth-2\tabcolsep} | + +.. flag-print:: + :type: table + :category: phases Redirecting output ------------------ More details in :ref:`options-output` -.. include:: flags-redirecting-output.gen.rst +.. tabularcolumns:: + | p{\dimexpr 0.30\textwidth-2\tabcolsep} | + p{\dimexpr 0.31\textwidth-2\tabcolsep} | + p{\dimexpr 0.11\textwidth-2\tabcolsep} | + p{\dimexpr 0.29\textwidth-2\tabcolsep} | + +.. flag-print:: + :type: table + :category: redirect-output Keeping intermediate files -------------------------- More details in :ref:`keeping-intermediates` -.. include:: flags-keeping-intermediates.gen.rst +.. tabularcolumns:: + | p{\dimexpr 0.30\textwidth-2\tabcolsep} | + p{\dimexpr 0.31\textwidth-2\tabcolsep} | + p{\dimexpr 0.11\textwidth-2\tabcolsep} | + p{\dimexpr 0.29\textwidth-2\tabcolsep} | + +.. flag-print:: + :type: table + :category: keep-intermediates Temporary files --------------- More details in :ref:`temp-files` -.. include:: flags-temporary-files.gen.rst +.. tabularcolumns:: + | p{\dimexpr 0.30\textwidth-2\tabcolsep} | + p{\dimexpr 0.31\textwidth-2\tabcolsep} | + p{\dimexpr 0.11\textwidth-2\tabcolsep} | + p{\dimexpr 0.29\textwidth-2\tabcolsep} | + +.. flag-print:: + :type: table + :category: temp-files Finding imports --------------- More details in :ref:`search-path` -.. include:: flags-finding-imports.gen.rst +.. tabularcolumns:: + | p{\dimexpr 0.30\textwidth-2\tabcolsep} | + p{\dimexpr 0.31\textwidth-2\tabcolsep} | + p{\dimexpr 0.11\textwidth-2\tabcolsep} | + p{\dimexpr 0.29\textwidth-2\tabcolsep} | + +.. flag-print:: + :type: table + :category: search-path Interface file options ---------------------- More details in :ref:`hi-options` -.. include:: flags-interface-files.gen.rst +.. tabularcolumns:: + | p{\dimexpr 0.30\textwidth-2\tabcolsep} | + p{\dimexpr 0.31\textwidth-2\tabcolsep} | + p{\dimexpr 0.11\textwidth-2\tabcolsep} | + p{\dimexpr 0.29\textwidth-2\tabcolsep} | + +.. flag-print:: + :type: table + :category: interface-files Recompilation checking ---------------------- More details in :ref:`recomp` -.. include:: flags-recompilation-checking.gen.rst +.. tabularcolumns:: + | p{\dimexpr 0.30\textwidth-2\tabcolsep} | + p{\dimexpr 0.31\textwidth-2\tabcolsep} | + p{\dimexpr 0.11\textwidth-2\tabcolsep} | + p{\dimexpr 0.29\textwidth-2\tabcolsep} | + +.. flag-print:: + :type: table + :category: recompilation .. _interactive-mode-options: @@ -77,31 +149,54 @@ Interactive-mode options More details in :ref:`ghci-dot-files` -.. include:: flags-interactive.gen.rst +.. tabularcolumns:: + | p{\dimexpr 0.30\textwidth-2\tabcolsep} | + p{\dimexpr 0.31\textwidth-2\tabcolsep} | + p{\dimexpr 0.11\textwidth-2\tabcolsep} | + p{\dimexpr 0.29\textwidth-2\tabcolsep} | + +.. flag-print:: + :type: table + :category: interactive Packages -------- More details in :ref:`packages` -.. include:: flags-packages.gen.rst +.. tabularcolumns:: + | p{\dimexpr 0.30\textwidth-2\tabcolsep} | + p{\dimexpr 0.31\textwidth-2\tabcolsep} | + p{\dimexpr 0.11\textwidth-2\tabcolsep} | + p{\dimexpr 0.29\textwidth-2\tabcolsep} | + +.. flag-print:: + :type: table + :category: packages + Language options ---------------- Language options can be enabled either by a command-line option ``-Xblah``, or by a ``{-# LANGUAGE blah #-}`` pragma in the file itself. -See :ref:`options-language`. Some options are enabled using ``-f*`` -flags. +See :ref:`options-language`. -.. include:: flags-language.gen.rst Warnings -------- More details in :ref:`options-sanity` -.. include:: flags-warnings.gen.rst +.. tabularcolumns:: + | p{\dimexpr 0.30\textwidth-2\tabcolsep} | + p{\dimexpr 0.31\textwidth-2\tabcolsep} | + p{\dimexpr 0.11\textwidth-2\tabcolsep} | + p{\dimexpr 0.29\textwidth-2\tabcolsep} | + +.. flag-print:: + :type: table + :category: warnings Optimisation levels ------------------- @@ -111,7 +206,15 @@ These options are described in more detail in :ref:`options-optimise`. See :ref:`options-f-compact` for a list of optimisations enabled on level 1 and level 2. -.. include:: flags-optimization-levels.gen.rst +.. tabularcolumns:: + | p{\dimexpr 0.30\textwidth-2\tabcolsep} | + p{\dimexpr 0.31\textwidth-2\tabcolsep} | + p{\dimexpr 0.11\textwidth-2\tabcolsep} | + p{\dimexpr 0.29\textwidth-2\tabcolsep} | + +.. flag-print:: + :type: table + :category: optimization-levels .. _options-f-compact: @@ -123,90 +226,175 @@ flag is implied by ``-O`` then it is also implied by ``-O2`` (unless flag description explicitly says otherwise). If a flag is implied by ``-O0`` only then the flag is not implied by ``-O`` and ``-O2``. -.. include:: flags-optimization.gen.rst +.. tabularcolumns:: + | p{\dimexpr 0.30\textwidth-2\tabcolsep} | + p{\dimexpr 0.31\textwidth-2\tabcolsep} | + p{\dimexpr 0.11\textwidth-2\tabcolsep} | + p{\dimexpr 0.29\textwidth-2\tabcolsep} | + +.. flag-print:: + :type: table + :category: optimization Profiling options ----------------- More details in :ref:`profiling` -.. include:: flags-profiling.gen.rst +.. tabularcolumns:: + | p{\dimexpr 0.30\textwidth-2\tabcolsep} | + p{\dimexpr 0.31\textwidth-2\tabcolsep} | + p{\dimexpr 0.11\textwidth-2\tabcolsep} | + p{\dimexpr 0.29\textwidth-2\tabcolsep} | + +.. flag-print:: + :type: table + :category: profiling Program coverage options ------------------------ More details in :ref:`hpc` -.. include:: flags-program-coverage.gen.rst +.. tabularcolumns:: + | p{\dimexpr 0.30\textwidth-2\tabcolsep} | + p{\dimexpr 0.31\textwidth-2\tabcolsep} | + p{\dimexpr 0.11\textwidth-2\tabcolsep} | + p{\dimexpr 0.29\textwidth-2\tabcolsep} | + +.. flag-print:: + :type: table + :category: coverage C pre-processor options ----------------------- More details in :ref:`c-pre-processor` -.. include:: flags-cpp.gen.rst +.. tabularcolumns:: + | p{\dimexpr 0.30\textwidth-2\tabcolsep} | + p{\dimexpr 0.31\textwidth-2\tabcolsep} | + p{\dimexpr 0.11\textwidth-2\tabcolsep} | + p{\dimexpr 0.29\textwidth-2\tabcolsep} | + +.. flag-print:: + :type: table + :category: cpp Code generation options ----------------------- More details in :ref:`options-codegen` -.. include:: flags-codegen.gen.rst +.. tabularcolumns:: + | p{\dimexpr 0.30\textwidth-2\tabcolsep} | + p{\dimexpr 0.31\textwidth-2\tabcolsep} | + p{\dimexpr 0.11\textwidth-2\tabcolsep} | + p{\dimexpr 0.29\textwidth-2\tabcolsep} | + +.. flag-print:: + :type: table + :category: codegen Linking options --------------- More details in :ref:`options-linker` -.. include:: flags-linking.gen.rst +.. tabularcolumns:: + | p{\dimexpr 0.35\textwidth-2\tabcolsep} | + p{\dimexpr 0.44\textwidth-2\tabcolsep} | + p{\dimexpr 0.11\textwidth-2\tabcolsep} | + p{\dimexpr 0.10\textwidth-2\tabcolsep} | + +.. flag-print:: + :type: table + :category: linking Plugin options -------------- More details in :ref:`compiler-plugins` -.. include:: flags-plugin.gen.rst +.. tabularcolumns:: + | p{\dimexpr 0.30\textwidth-2\tabcolsep} | + p{\dimexpr 0.31\textwidth-2\tabcolsep} | + p{\dimexpr 0.11\textwidth-2\tabcolsep} | + p{\dimexpr 0.29\textwidth-2\tabcolsep} | + +.. flag-print:: + :type: table + :category: plugins Replacing phases ---------------- More details in :ref:`replacing-phases` -.. include:: flags-phase-programs.gen.rst +.. tabularcolumns:: + | p{\dimexpr 0.30\textwidth-2\tabcolsep} | + p{\dimexpr 0.31\textwidth-2\tabcolsep} | + p{\dimexpr 0.11\textwidth-2\tabcolsep} | + p{\dimexpr 0.29\textwidth-2\tabcolsep} | -.. index:: - single: -pgmL - single: -pgmP - single: -pgmc - single: -pgmlo - single: -pgmlc - single: -pgma - single: -pgml - single: -pgmdll - single: -pgmF +.. flag-print:: + :type: table + :category: phase-programs Forcing options to particular phases ------------------------------------ More details in :ref:`forcing-options-through` -.. include:: flags-phase-specific.gen.rst +.. tabularcolumns:: + | p{\dimexpr 0.30\textwidth-2\tabcolsep} | + p{\dimexpr 0.31\textwidth-2\tabcolsep} | + p{\dimexpr 0.11\textwidth-2\tabcolsep} | + p{\dimexpr 0.29\textwidth-2\tabcolsep} | + +.. flag-print:: + :type: table + :category: phase-options Platform-specific options ------------------------- More details in :ref:`options-platform` -.. include:: flags-platform-specific.gen.rst +.. tabularcolumns:: + | p{\dimexpr 0.30\textwidth-2\tabcolsep} | + p{\dimexpr 0.31\textwidth-2\tabcolsep} | + p{\dimexpr 0.11\textwidth-2\tabcolsep} | + p{\dimexpr 0.29\textwidth-2\tabcolsep} | + +.. flag-print:: + :type: table + :category: platform-options Compiler debugging options -------------------------- More details in :ref:`options-debugging` -.. include:: flags-compiler-debugging.gen.rst +.. tabularcolumns:: + | p{\dimexpr 0.35\textwidth-2\tabcolsep} | + p{\dimexpr 0.44\textwidth-2\tabcolsep} | + p{\dimexpr 0.11\textwidth-2\tabcolsep} | + p{\dimexpr 0.10\textwidth-2\tabcolsep} | + +.. flag-print:: + :type: table + :category: debugging Miscellaneous compiler options ------------------------------ -.. include:: flags-misc.gen.rst +.. tabularcolumns:: + | p{\dimexpr 0.35\textwidth-2\tabcolsep} | + p{\dimexpr 0.44\textwidth-2\tabcolsep} | + p{\dimexpr 0.11\textwidth-2\tabcolsep} | + p{\dimexpr 0.10\textwidth-2\tabcolsep} | + +.. flag-print:: + :type: table + :category: misc diff --git a/docs/users_guide/ghc.mk b/docs/users_guide/ghc.mk index 9144a0728e..c2e20ebc03 100644 --- a/docs/users_guide/ghc.mk +++ b/docs/users_guide/ghc.mk @@ -11,9 +11,7 @@ # ----------------------------------------------------------------------------- -docs/users_guide_RST_SOURCES := \ - $(utils/mkUserGuidePart_GENERATED_RST_SOURCES) \ - $(wildcard docs/users_guide/*.rst) +docs/users_guide_RST_SOURCES := $(wildcard docs/users_guide/*.rst) $(eval $(call sphinx,docs/users_guide,users_guide)) @@ -26,7 +24,7 @@ MAN_SECTION := 1 MAN_PAGES := docs/users_guide/build-man/ghc.1 ifneq "$(BINDIST)" "YES" -$(MAN_PAGES): $(docs/users_guide_MAN_RST_SOURCES) $(utils/mkUserGuidePart_GENERATED_RST_SOURCES) +$(MAN_PAGES): $(docs/users_guide_MAN_RST_SOURCES) $(SPHINXBUILD) -b man -d docs/users_guide/.doctrees-man docs/users_guide docs/users_guide/build-man endif diff --git a/docs/users_guide/ghc.rst b/docs/users_guide/ghc.rst index a44c9d94f6..7e20069396 100644 --- a/docs/users_guide/ghc.rst +++ b/docs/users_guide/ghc.rst @@ -62,7 +62,317 @@ Common suffixes of file names for Haskell are: Options ------- -.. include:: all-flags.gen.rst +.. flag-print:: + :type: summary + :category: codegen + + +.. flag-print:: + :type: summary + :category: debugging + + +.. flag-print:: + :type: summary + :category: cpp + + +.. flag-print:: + :type: summary + :category: search-path + + +.. flag-print:: + :type: summary + :category: interactive + + +.. flag-print:: + :type: summary + :category: interface-files + + +.. flag-print:: + :type: summary + :category: keep-intermediates + + +.. flag-print:: + :type: summary + :category: language + + +.. flag-print:: + :type: summary + :category: linking + + +.. flag-print:: + :type: summary + :category: misc + + +.. flag-print:: + :type: summary + :category: modes + + +.. flag-print:: + :type: summary + :category: optimization + + +.. flag-print:: + :type: summary + :category: optimization-levels + + +.. flag-print:: + :type: summary + :category: packages + + +.. flag-print:: + :type: summary + :category: phases + + +.. flag-print:: + :type: summary + :category: phase-programs + + +.. flag-print:: + :type: summary + :category: phase-options + + +.. flag-print:: + :type: summary + :category: platform-options + + +.. flag-print:: + :type: summary + :category: plugins + + +.. flag-print:: + :type: summary + :category: profiling + + +.. flag-print:: + :type: summary + :category: coverage + + +.. flag-print:: + :type: summary + :category: recompilation + + +.. flag-print:: + :type: summary + :category: redirect-output + + +.. flag-print:: + :type: summary + :category: temp-files + + +.. flag-print:: + :type: summary + :category: verbosity + + +.. flag-print:: + :type: summary + :category: warnings + + +Code generation +~~~~~~~~~~~~~~~ + +.. flag-print:: + :type: list + :category: codegen + +Debugging the compiler +~~~~~~~~~~~~~~~~~~~~~~ + +.. flag-print:: + :type: list + :category: debugging + +C pre-processor +~~~~~~~~~~~~~~~ + +.. flag-print:: + :type: list + :category: cpp + +Finding imports +~~~~~~~~~~~~~~~ + +.. flag-print:: + :type: list + :category: search-path + +Interactive mode +~~~~~~~~~~~~~~~~ + +.. flag-print:: + :type: list + :category: interactive + +Interface files +~~~~~~~~~~~~~~~ + +.. flag-print:: + :type: list + :category: interface-files + +Keeping intermediate files +~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. flag-print:: + :type: list + :category: keep-intermediates + +Language options +~~~~~~~~~~~~~~~~ + +.. flag-print:: + :type: list + :category: language + +Linking options +~~~~~~~~~~~~~~~ + +.. flag-print:: + :type: list + :category: linking + +Miscellaneous options +~~~~~~~~~~~~~~~~~~~~~ + +.. flag-print:: + :type: list + :category: misc + +Modes of operation +~~~~~~~~~~~~~~~~~~ + +.. flag-print:: + :type: list + :category: modes + +Individual optimizations +~~~~~~~~~~~~~~~~~~~~~~~~ + +.. flag-print:: + :type: list + :category: optimization + +Optimization levels +~~~~~~~~~~~~~~~~~~~ + +.. flag-print:: + :type: list + :category: optimization-levels + +Package options +~~~~~~~~~~~~~~~ + +.. flag-print:: + :type: list + :category: packages + +Phases of compilation +~~~~~~~~~~~~~~~~~~~~~ + +.. flag-print:: + :type: list + :category: phases + +Overriding external programs +~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. flag-print:: + :type: list + :category: phase-programs + +Phase-specific options +~~~~~~~~~~~~~~~~~~~~~~ + +.. flag-print:: + :type: list + :category: phase-options + +Platform-specific options +~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. flag-print:: + :type: list + :category: platform-options + +Compiler plugins +~~~~~~~~~~~~~~~~ + +.. flag-print:: + :type: list + :category: plugins + +Profiling +~~~~~~~~~ + +.. flag-print:: + :type: list + :category: profiling + +Program coverage +~~~~~~~~~~~~~~~~ + +.. flag-print:: + :type: list + :category: coverage + +Recompilation checking +~~~~~~~~~~~~~~~~~~~~~~ + +.. flag-print:: + :type: list + :category: recompilation + +Redirecting output +~~~~~~~~~~~~~~~~~~ + +.. flag-print:: + :type: list + :category: redirect-output + +Temporary files +~~~~~~~~~~~~~~~ + +.. flag-print:: + :type: list + :category: temp-files + +Verbosity options +~~~~~~~~~~~~~~~~~ + +.. flag-print:: + :type: list + :category: verbosity + +Warnings +~~~~~~~~ + +.. flag-print:: + :type: list + :category: warnings Copyright --------- diff --git a/docs/users_guide/ghc_config.py.in b/docs/users_guide/ghc_config.py.in index 113d1b022f..4ff77adc9d 100644 --- a/docs/users_guide/ghc_config.py.in +++ b/docs/users_guide/ghc_config.py.in @@ -16,3 +16,5 @@ lib_versions = { } version = '@ProjectVersion@' + +llvm_version = '@LlvmVersion@' diff --git a/docs/users_guide/ghc_packages.py b/docs/users_guide/ghc_packages.py new file mode 100644 index 0000000000..6419834e1e --- /dev/null +++ b/docs/users_guide/ghc_packages.py @@ -0,0 +1,65 @@ +from docutils import nodes +from docutils.parsers.rst import Directive, directives +from sphinx import addnodes +from sphinx.domains.std import GenericObject +from sphinx.errors import SphinxError +from utils import build_table_from_list + +def read_cabal_file(pkg_path): + import re + cabal_file = open(pkg_path, 'r').read() + pkg_name = re.search(r'^[nN]ame\s*:\s*([-a-zA-Z0-9]+)', cabal_file, re.MULTILINE) + if pkg_name is not None: + pkg_name = pkg_name.group(1) + else: + raise RuntimeError("Failed to parse `Name:` field from %s" % pkg_path) + + pkg_version = re.search(r'^[vV]ersion\s*:\s*(\d+(\.\d+)*)', cabal_file, re.MULTILINE) + if pkg_version is not None: + pkg_version = pkg_version.group(1) + else: + raise RuntimeError("Failed to parse `Version:` field from %s" % pkg_path) + + return (pkg_name, pkg_version) + + +class PackageListDirective(Directive): + has_content = True + def run(self): + self.assert_has_content() + + packages = [] + for line in self.content: + (pkg_path, _, reason) = line.partition(':') + if len(reason) == 0: + raise RuntimeError("Missing reason for inclusion of package %s" + % pkg_path) + + # Parse reason + from docutils.statemachine import ViewList + reason_vl = ViewList(initlist=[reason.strip()]) + reason_node = nodes.paragraph() + self.state.nested_parse(reason_vl, 0, reason_node) + packages.append((pkg_path, reason_node)) + + # Create column headers for table + header = [ nodes.inline(text=h) + for h in ["Package", "Version", "Reason for inclusion"] ] + package_list = [header] + + for (pkg_path, reason) in sorted(packages): + (pkg_name, pkg_version) = read_cabal_file(pkg_path) + cells = [ nodes.paragraph(text=pkg_name), + nodes.inline(text=pkg_version), + reason ] + package_list.append(cells) + + table = build_table_from_list(package_list, [20, 20, 40]) + table['classes'].append('longtable') + return [table] + +### Initialization +def setup(app): + app.add_directive('ghc-package-list', PackageListDirective) + + return {'version': '1.0'} diff --git a/docs/users_guide/ghci.rst b/docs/users_guide/ghci.rst index fe481ae799..49a96caa0b 100644 --- a/docs/users_guide/ghci.rst +++ b/docs/users_guide/ghci.rst @@ -37,7 +37,7 @@ command ``ghci``: .. code-block:: none $ ghci - GHCi, version 8.0.1: http://www.haskell.org/ghc/ :? for help + GHCi, version 8.y.z: http://www.haskell.org/ghc/ :? for help Prelude> There may be a short pause while GHCi loads the prelude and standard @@ -69,6 +69,15 @@ GHCi, since the expression can also be interpreted in the ``IO`` monad, a ``let`` binding with no accompanying ``in`` statement can be signalled by an empty line, as in the above example. +Since GHC 8.0.1, you can bind values and functions to names without ``let`` statement: + +.. code-block:: none + + Prelude> x = 42 + Prelude> x + 42 + Prelude> + .. _loading-source-files: Loading source files @@ -129,6 +138,19 @@ them all in dependency order. Windows, then the current directory is probably something like ``C:\Documents and Settings\user name``. +.. ghc-flag:: -fshow-loaded-modules + :shortdesc: Show the names of modules that GHCi loaded after a + :ghci-cmd:`:load` command. + :type: dynamic + + :default: off + :since: 8.2.2 + + Typically GHCi will show only the number of modules that it loaded after a + :ghci-cmd:`:load` command. With this flag, GHC will also list the loaded + modules' names. This was the default behavior prior to GHC 8.2.1 and can be + useful for some tooling users. + .. _ghci-modules-filenames: @@ -425,6 +447,10 @@ The statement ``x <- return 42`` means “execute ``return 42`` in the future statements, for example to print it as we did above. .. ghc-flag:: -fprint-bind-result + :shortdesc: :ref:`Turn on printing of binding results in GHCi <ghci-stmts>` + :type: dynamic + :reverse: -fno-print-bind-result + :category: If :ghc-flag:`-fprint-bind-result` is set then GHCi will print the result of a statement if and only if: @@ -987,10 +1013,10 @@ of type ``a``. eg.: .. code-block:: none - Prelude> Time.getClockTime - Wed Mar 14 12:23:13 GMT 2001 + Prelude> Data.Time.getZonedTime + 2017-04-10 12:34:56.93213581 UTC Prelude> print it - Wed Mar 14 12:23:13 GMT 2001 + 2017-04-10 12:34:56.93213581 UTC The corresponding translation for an IO-typed ``e`` is @@ -1001,6 +1027,20 @@ The corresponding translation for an IO-typed ``e`` is Note that ``it`` is shadowed by the new value each time you evaluate a new expression, and the old value of ``it`` is lost. +In order to stop the value ``it`` being bound on each command, the flag +:ghc-flag:`-fno-it` can be set. The ``it`` variable can be the source +of space leaks due to how shadowed declarations are handled by +GHCi (see :ref:`ghci-decls`). + +.. ghc-flag:: -fno-it + :shortdesc: No longer set the special variable ``it``. + :type: dynamic + :reverse: -fno-no-it + :category: + + When this flag is set, the variable ``it`` will no longer be set + to the result of the previously evaluated expression. + .. _extended-default-rules: Type defaulting in GHCi @@ -1010,7 +1050,10 @@ Type defaulting in GHCi single: Type defaulting; in GHCi single: Show class -.. ghc-flag:: -XExtendedDefaultRules +.. extension:: ExtendedDefaultRules + :shortdesc: Use GHCi's extended default rules in a normal module. + + :since: 6.8.1 Allow defaulting to take place for more than just numeric classes. @@ -1044,7 +1087,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 :ghc-flag:`-XExtendedDefaultRules` flag +At the GHCi prompt, or with GHC if the :extension:`ExtendedDefaultRules` flag is given, the types are instead resolved with the following method: Find all the unsolved constraints. Then: @@ -1097,7 +1140,7 @@ Interactive classes .. index:: single: Interactive classes -The interactive classes (only relevant when :ghc-flag:`-XExtendedDefaultRules` +The interactive classes (only relevant when :extension:`ExtendedDefaultRules` is in effect) are: any numeric class, ``Show``, ``Eq``, ``Ord``, ``Foldable`` or ``Traversable``. @@ -1111,7 +1154,7 @@ Extended rules around ``default`` declarations single: default declarations Since the rules for defaulting are relaxed under -:ghc-flag:`-XExtendedDefaultRules`, the rules for ``default`` declarations +:extension:`ExtendedDefaultRules`, the rules for ``default`` declarations are also relaxed. According to Section 4.3.4 of the Haskell 2010 Report, a ``default`` declaration looks like ``default (t1, ..., tn)`` where, for each ``ti``, ``Num ti`` must hold. This is relaxed to say that for each @@ -1146,6 +1189,10 @@ it survive a :ghci-cmd:`:cd`, :ghci-cmd:`:add`, :ghci-cmd:`:load`, :ghci-cmd:`:reload` or, :ghci-cmd:`:set`. .. ghc-flag:: -interactive-print ⟨expr⟩ + :shortdesc: :ref:`Select the function to use for printing evaluated + expressions in GHCi <ghci-interactive-print>` + :type: dynamic + :category: Set the function used by GHCi to print evaluation results. Expression must be of type ``C a => a -> IO ()``. @@ -1162,7 +1209,7 @@ printed value. Running GHCi with the command: .. code-block:: none - ghci -interactive-print=SpecPrinter.sprinter SpecPrinter + ghci -interactive-print=SpecPrinter.sprint SpecPrinter will start an interactive session where values with be printed using ``sprint``: @@ -1735,6 +1782,10 @@ is we found that logging each breakpoint in the history cuts performance by a factor of 2 or more. .. ghc-flag:: -fghci-hist-size=⟨n⟩ + :shortdesc: Set the number of entries GHCi keeps for ``:history``. + See :ref:`ghci-debugger`. + :type: dynamic + :category: :default: 50 @@ -1799,12 +1850,26 @@ 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 + :shortdesc: :ref:`Break on any exception thrown <ghci-debugger-exceptions>` + :type: dynamic + :reverse: -fno-break-on-exception + :category: 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. + in the event of an exception. :ghc-flag:`-fbreak-on-exception` breaks + on all exceptions. + +.. ghc-flag:: -fbreak-on-error + :shortdesc: :ref:`Break on uncaught exceptions and errors + <ghci-debugger-exceptions>` + :type: dynamic + :reverse: -fno-break-on-error + :category: + + Causes GHCi to halt evaluation and return to the interactive prompt in the + event of an exception. :ghc-flag:`-fbreak-on-error` breaks on only those + exceptions which would otherwise be uncaught. + Example: inspecting functions ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ @@ -1945,15 +2010,31 @@ also make sense in interactive mode. The ones that don't make sense are mostly obvious. .. ghc-flag:: -flocal-ghci-history + :shortdesc: Use current directory for the GHCi command history + file ``.ghci-history``. + :type: dynamic + :reverse: -fno-local-ghci-history + :category: + + By default, GHCi keeps global history in ``~/.ghc/ghci_history`` or + ``%APPDATA%/<app>/ghci_history``, but you can use current directory, e.g.: - By default, GHCi keeps global history in ``~/.ghc/ghci_history`` or - ``%APPDATA%/<app>/ghci_history``, but you can use current directory, e.g.: + .. code-block:: none + + $ ghci -flocal-ghci-history - .. code-block:: none + It will create ``.ghci-history`` in current folder where GHCi is launched. - $ ghci -flocal-ghci-history +.. ghc-flag:: -fghci-leak-check + :shortdesc: (Debugging only) check for space leaks when loading + new modules in GHCi. + :type: dynamic + :reverse: -fno-ghci-leak-check + :category: - It will create ``.ghci-history`` in current folder where GHCi is launched. + (Debugging only) When loading new modules with ``:load``, check + that any previously loaded modules have been correctly garbage + collected. Emits messages if a leak is detected. Packages ~~~~~~~~ @@ -1971,7 +2052,7 @@ by using the :ghc-flag:`-package ⟨pkg⟩` flag: .. code-block:: none $ ghci -package readline - GHCi, version 6.8.1: http://www.haskell.org/ghc/ :? for help + GHCi, version 8.y.z: http://www.haskell.org/ghc/ :? for help Loading package base ... linking ... done. Loading package readline-1.0 ... linking ... done. Prelude> @@ -2006,17 +2087,28 @@ libraries, in this order: - Paths specified using the :ghc-flag:`-L ⟨dir⟩` command-line option, -- the standard library search path for your system, which on some +- The standard library search path for your system loader, which on some systems may be overridden by setting the :envvar:`LD_LIBRARY_PATH` environment variable. +- The linker standard library search can also be overriden on some systems using + the :envvar:`LIBRARY_PATH` environment variable. Because of some + implementation detail on Windows, setting ``LIBRARY_PATH`` will also extend + the system loader path for any library it finds. So often setting + :envvar:`LIBRARY_PATH` is enough. + On systems with ``.dll``-style shared libraries, the actual library -loaded will be ``lib.dll``. Again, GHCi will signal an error if it can't -find the library. +loaded will be ``lib.dll``, ``liblib.dll``. GHCi also has full support for +import libraries, either Microsoft style ``.lib``, or GNU GCC style ``.a`` and +``.dll.a`` libraries. If you have an import library it is advisable to always +specify the import libary instead of the ``.dll``. e.g. use ``-lgcc` instead of +``-llibgcc_s_seh-1``. Again, GHCi will signal an error if it can't find the +library. GHCi can also load plain object files (``.o`` or ``.obj`` depending on -your platform) from the command-line. Just add the name the object file -to the command line. +your platform) or static archives (``.a``) from the command-line. Just add the +name the object file or library to the command line. +On Windows GHCi also supports the ``big-obj`` format. Ordering of ``-l`` options matters: a library should be mentioned *before* the libraries it depends on (see :ref:`options-linker`). @@ -2238,17 +2330,17 @@ commonly used commands. .. code-block:: none - Prelude> let date _ = Time.getClockTime >>= print >> return "" + Prelude> let date _ = Data.Time.getZonedTime >>= print >> return "" Prelude> :def date date Prelude> :date - Fri Mar 23 15:16:40 GMT 2001 + 2017-04-10 12:34:56.93213581 UTC Here's an example of a command that takes an argument. It's a re-implementation of :ghci-cmd:`:cd`: .. code-block:: none - Prelude> let mycd d = Directory.setCurrentDirectory d >> return "" + Prelude> let mycd d = System.Directory.setCurrentDirectory d >> return "" Prelude> :def mycd mycd Prelude> :mycd .. @@ -2282,6 +2374,14 @@ commonly used commands. see the number of each breakpoint). The ``*`` form deletes all the breakpoints. +.. ghci-cmd:: :doc; ⟨name⟩ + + (Experimental: This command will likely change significantly in GHC 8.8.) + + Displays the documentation for the given name. Currently the command is + restricted to displaying the documentation directly on the declaration + in question, ignoring documentation for arguments, constructors etc. + .. ghci-cmd:: :edit; ⟨file⟩ Opens an editor to edit the file ⟨file⟩, or the most recently loaded @@ -2733,7 +2833,7 @@ commonly used commands. Infers and prints the type of ⟨expression⟩, but without fiddling with type variables or class constraints. This is useful when you - are using :ghc-flag:`-XTypeApplications` and care about the distinction + are using :extension:`TypeApplications` and care about the distinction between specified type variables (available for type application) and inferred type variables (not available). This mode sometimes prints constraints (such as ``Show Int``) that could readily be solved, but @@ -2745,13 +2845,13 @@ commonly used commands. *X> :type +v length length :: forall (t :: * -> *). Foldable t => forall a. t a -> Int -.. ghci-cmd:: :type +d ⟨expression⟩ +.. ghci-cmd:: :type +d; ⟨expression⟩ Infers and prints the type of ⟨expression⟩, defaulting type variables if possible. In this mode, if the inferred type is constrained by any interactive class (``Num``, ``Show``, ``Eq``, ``Ord``, ``Foldable``, or ``Traversable``), the constrained type variable(s) are defaulted - according to the rules described under :ghc-flag:`-XExtendedDefaultRules`. + according to the rules described under :extension:`ExtendedDefaultRules`. This mode is quite useful when the inferred type is quite general (such as for ``foldr``) and it may be helpful to see a more concrete instantiation. @@ -2946,7 +3046,7 @@ that option apply to loaded modules too. For example :seti -XMonoLocalBinds -It would be undesirable if :ghc-flag:`-XMonoLocalBinds` were to apply to loaded +It would be undesirable if :extension:`MonoLocalBinds` 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. @@ -3054,11 +3154,17 @@ Two command-line options control whether the startup files files are read: .. ghc-flag:: -ignore-dot-ghci + :shortdesc: Disable reading of ``.ghci`` files + :type: dynamic + :category: Don't read either :file:`./.ghci` or the other startup files when starting up. .. ghc-flag:: -ghci-script + :shortdesc: Read additional ``.ghci`` files + :type: dynamic + :category: Read a specific file after the usual startup files. Maybe be specified repeatedly for multiple inputs. @@ -3109,7 +3215,7 @@ The ``.haskeline`` file GHCi uses `Haskeline <https://hackage.haskell.org/package/haskeline>`__ under the hood. You can configure it to, among other things, prune duplicates from GHCi history. See: -`Haskeline user preferences <http://trac.haskell.org/haskeline/wiki/UserPrefs>`__. +`Haskeline user preferences <https://github.com/judah/haskeline/wiki/UserPreferences>`__. .. _ghci-obj: @@ -3147,6 +3253,9 @@ separate process for running interpreted code, and communicate with it using messages over a pipe. .. ghc-flag:: -fexternal-interpreter + :shortdesc: Run interpreted code in a separate process + :type: dynamic + :category: misc :since: 8.0.1 diff --git a/docs/users_guide/glasgow_exts.rst b/docs/users_guide/glasgow_exts.rst index a2cc0ba269..4fd6f1b2af 100644 --- a/docs/users_guide/glasgow_exts.rst +++ b/docs/users_guide/glasgow_exts.rst @@ -31,7 +31,7 @@ Language options single: options; language single: extensions; options controlling -The language option flags control what variation of the language are +The language extensions control what variation of the language are permitted. Language options can be controlled in two ways: @@ -44,15 +44,24 @@ Language options can be controlled in two ways: ``LANGUAGE`` pragma, thus ``{-# LANGUAGE TemplateHaskell #-}`` (see :ref:`language-pragma`). +GHC supports these language options: + +.. extension-print:: + :type: table Although not recommended, the deprecated :ghc-flag:`-fglasgow-exts` flag enables a large swath of the extensions supported by GHC at once. .. ghc-flag:: -fglasgow-exts + :shortdesc: Deprecated. Enable most language extensions; + see :ref:`options-language` for exactly which ones. + :type: dynamic + :reverse: -fno-glasgow-exts + :category: misc The flag ``-fglasgow-exts`` is equivalent to enabling the following extensions: - .. include:: what_glasgow_exts_does.gen.rst + .. include:: what_glasgow_exts_does.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 @@ -79,7 +88,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 :ghc-flag:`-XMagicHash` extension (:ref:`magic-hash`). +you need the :extension:`MagicHash` extension. The primops make extensive use of `unboxed types <#glasgow-unboxed>`__ and `unboxed tuples <#unboxed-tuples>`__, which we briefly summarise @@ -139,24 +148,25 @@ stores a pointer. GHC currently does not support this variety of ``Just`` nodes (nor for any other datatype). Accordingly, the *kind* of an unboxed type is different from the kind of a boxed type. -The Haskell Report describes that ``*`` is the kind of ordinary datatypes, -such as ``Int``. Furthermore, type constructors can have kinds with arrows; -for example, ``Maybe`` has kind ``* -> *``. Unboxed types have a kind that -specifies their runtime representation. For example, the type ``Int#`` has -kind ``TYPE 'IntRep`` and ``Double#`` has kind ``TYPE 'DoubleRep``. These -kinds say that the runtime representation of an ``Int#`` is a machine integer, -and the runtime representation of a ``Double#`` is a machine double-precision -floating point. In contrast, the kind ``*`` is actually just a synonym -for ``TYPE 'PtrRepLifted``. More details of the ``TYPE`` mechanisms appear in -the `section on runtime representation polymorphism <#runtime-rep>`__. - -Given that ``Int#``'s kind is not ``*``, it then it follows that -``Maybe Int#`` is disallowed. Similarly, because type variables tend -to be of kind ``*`` (for example, in ``(.) :: (b -> c) -> (a -> b) -> a -> c``, -all the type variables have kind ``*``), polymorphism tends not to work -over primitive types. Stepping back, this makes some sense, because -a polymorphic function needs to manipulate the pointers to its data, -and most primitive types are unboxed. +The Haskell Report describes that ``*`` (spelled ``Type`` and imported from +``Data.Kind`` in the GHC dialect of Haskell) is the kind of ordinary datatypes, +such as ``Int``. Furthermore, type constructors can have kinds with arrows; for +example, ``Maybe`` has kind ``Type -> Type``. Unboxed types have a kind that +specifies their runtime representation. For example, the type ``Int#`` has kind +``TYPE 'IntRep`` and ``Double#`` has kind ``TYPE 'DoubleRep``. These kinds say +that the runtime representation of an ``Int#`` is a machine integer, and the +runtime representation of a ``Double#`` is a machine double-precision floating +point. In contrast, the kind ``Type`` is actually just a synonym for ``TYPE +'LiftedRep``. More details of the ``TYPE`` mechanisms appear in the `section +on runtime representation polymorphism <#runtime-rep>`__. + +Given that ``Int#``'s kind is not ``Type``, it then it follows that ``Maybe +Int#`` is disallowed. Similarly, because type variables tend to be of kind +``Type`` (for example, in ``(.) :: (b -> c) -> (a -> b) -> a -> c``, all the +type variables have kind ``Type``), polymorphism tends not to work over +primitive types. Stepping back, this makes some sense, because a polymorphic +function needs to manipulate the pointers to its data, and most primitive types +are unboxed. There are some restrictions on the use of primitive types: @@ -200,12 +210,14 @@ There are some restrictions on the use of primitive types: Unboxed tuples -------------- -.. ghc-flag:: -XUnboxedTuples +.. extension:: UnboxedTuples + :shortdesc: Enable the use of unboxed tuple syntax. + + :since: 6.8.1 - 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 +syntactic extension (:extension:`UnboxedTuples`). An unboxed tuple looks like this: :: (# e_1, ..., e_n #) @@ -261,7 +273,10 @@ There are some restrictions on the use of unboxed tuples: Unboxed sums ------------ -.. ghc-flag:: -XUnboxedSums +.. extension:: UnboxedSums + :shortdesc: Enable unboxed sums. + + :since: 8.2.1 Enable the use of unboxed sum syntax. @@ -270,21 +285,21 @@ for an unboxed sum type with N alternatives is :: (# t_1 | t_2 | ... | t_N #) -where `t_1` ... `t_N` are types (which can be unlifted, including unboxed tuple -and sums). +where ``t_1`` ... ``t_N`` are types (which can be unlifted, including unboxed +tuples and sums). Unboxed tuples can be used for multi-arity alternatives. For example: :: (# (# Int, String #) | Bool #) -Term level syntax is similar. Leading and preceding bars (`|`) indicate which -alternative it is. Here is two terms of the type shown above: :: +The term level syntax is similar. Leading and preceding bars (`|`) indicate which +alternative it is. Here are two terms of the type shown above: :: (# (# 1, "foo" #) | #) -- first alternative (# | True #) -- second alternative -Pattern syntax reflects the term syntax: :: +The pattern syntax reflects the term syntax: :: case x of (# (# i, str #) | #) -> ... @@ -293,45 +308,56 @@ Pattern syntax reflects the term syntax: :: Unboxed sums are "unboxed" in the sense that, instead of allocating sums in the heap and representing values as pointers, unboxed sums are represented as their components, just like unboxed tuples. These "components" depend on alternatives -of a sum type. Code generator tries to generate as compact layout as possible. -In the best case, size of an unboxed sum is size of its biggest alternative + -one word (for tag). The algorithm for generating memory layout for a sum type -works like this: +of a sum type. Like unboxed tuples, unboxed sums are lazy in their lifted +components. + +The code generator tries to generate as compact layout as possible for each +unboxed sum. In the best case, size of an unboxed sum is size of its biggest +alternative plus one word (for a tag). The algorithm for generating the memory +layout for a sum type works like this: - All types are classified as one of these classes: 32bit word, 64bit word, 32bit float, 64bit float, pointer. - For each alternative of the sum type, a layout that consists of these fields - is generated. For example, if an alternative has `Int`, `Float#` and `String` - fields, the layout will have an 32bit word, 32bit float and pointer fields. + is generated. For example, if an alternative has ``Int``, ``Float#`` and + ``String`` fields, the layout will have an 32bit word, 32bit float and + pointer fields. - Layout fields are then overlapped so that the final layout will be as compact - as possible. E.g. say two alternatives have these fields: :: + as possible. For example, suppose we have the unboxed sum: :: - Word32, String, Float# - Float#, Float#, Maybe Int + (# (# Word32#, String, Float# #) + | (# Float#, Float#, Maybe Int #) #) - Final layout will be something like :: + The final layout will be something like :: Int32, Float32, Float32, Word32, Pointer - First `Int32` is for the tag. It has two `Float32` fields because floating - point types can't overlap with other types, because of limitations of the code - generator that we're hoping to overcome in the future, and second alternative - needs two `Float32` fields. `Word32` field is for the `Word32` in the first - alternative. `Pointer` field is shared between `String` and `Maybe Int` values - of the alternatives. - - In the case of enumeration types (like `Bool`), the unboxed sum layout only - has an `Int32` field (i.e. the whole thing is represented by an integer). + The first ``Int32`` is for the tag. There are two ``Float32`` fields because + floating point types can't overlap with other types, because of limitations of + the code generator that we're hoping to overcome in the future. The second + alternative needs two ``Float32`` fields: The ``Word32`` field is for the + ``Word32#`` in the first alternative. The ``Pointer`` field is shared between + ``String`` and ``Maybe Int`` values of the alternatives. -In the example above, a value of this type is thus represented as 5 values. As -an another example, this is the layout for unboxed version of `Maybe a` type: :: + As another example, this is the layout for the unboxed version of ``Maybe a`` + type, ``(# (# #) | a #)``: :: Int32, Pointer -The `Pointer` field is not used when tag says that it's `Nothing`. Otherwise -`Pointer` points to the value in `Just`. + The ``Pointer`` field is not used when tag says that it's ``Nothing``. + Otherwise ``Pointer`` points to the value in ``Just``. As mentioned + above, this type is lazy in its lifted field. Therefore, the type :: + + data Maybe' a = Maybe' (# (# #) | a #) + + is *precisely* isomorphic to the type ``Maybe a``, although its memory + representation is different. + + In the degenerate case where all the alternatives have zero width, such + as the ``Bool``-like ``(# (# #) | (# #) #)``, the unboxed sum layout only + has an ``Int32`` tag field (i.e., the whole thing is represented by an integer). .. _syntax-extns: @@ -343,12 +369,15 @@ Syntactic extensions Unicode syntax -------------- -.. ghc-flag:: -XUnicodeSyntax +.. extension:: UnicodeSyntax + :shortdesc: Enable unicode syntax. + + :since: 6.8.1 Enable the use of Unicode characters in place of their equivalent ASCII sequences. -The language extension :ghc-flag:`-XUnicodeSyntax` enables +The language extension :extension:`UnicodeSyntax` enables Unicode characters to be used to stand for certain ASCII character sequences. The following alternatives are provided: @@ -390,26 +419,29 @@ sequences. The following alternatives are provided: The magic hash -------------- -.. ghc-flag:: -XMagicHash +.. extension:: MagicHash + :shortdesc: Allow ``#`` as a postfix modifier on identifiers. - Enable the use of the hash character (``#``) as an identifier suffix. + :since: 6.8.1 + + Enables the use of the hash character (``#``) as an identifier suffix. -The language extension :ghc-flag:`-XMagicHash` allows ``#`` as a postfix modifier +The language extension :extension:`MagicHash` 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 :ghc-flag:`-XMagicHash` extension bring anything into +variables. Nor does the :extension:`MagicHash` extension bring anything into scope. For example, to bring ``Int#`` into scope you must import -``GHC.Prim`` (see :ref:`primitives`); the :ghc-flag:`-XMagicHash` extension then +``GHC.Prim`` (see :ref:`primitives`); the :extension:`MagicHash` 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 :ghc-flag:`-XMagicHash` also enables some new forms of literals (see +The :extension:`MagicHash` also enables some new forms of literals (see :ref:`glasgow-unboxed`): - ``'x'#`` has type ``Char#`` @@ -432,7 +464,8 @@ The :ghc-flag:`-XMagicHash` also enables some new forms of literals (see Negative literals ----------------- -.. ghc-flag:: -XNegativeLiterals +.. extension:: NegativeLiterals + :shortdesc: Enable support for negative literals. :since: 7.8.1 @@ -440,7 +473,7 @@ Negative literals The literal ``-123`` is, according to Haskell98 and Haskell 2010, desugared as ``negate (fromInteger 123)``. The language extension -:ghc-flag:`-XNegativeLiterals` means that it is instead desugared as +:extension:`NegativeLiterals` means that it is instead desugared as ``fromInteger (-123)``. This can make a difference when the positive and negative range of a @@ -453,7 +486,8 @@ elicit an unexpected integer-literal-overflow message. Fractional looking integer literals ----------------------------------- -.. ghc-flag:: -XNumDecimals +.. extension:: NumDecimals + :shortdesc: Enable support for 'fractional' integer literals. :since: 7.8.1 @@ -462,7 +496,7 @@ Fractional looking integer literals Haskell 2010 and Haskell 98 define floating literals with the syntax ``1.2e6``. These literals have the type ``Fractional a => a``. -The language extension :ghc-flag:`-XNumDecimals` allows you to also use the +The language extension :extension:`NumDecimals` allows you to also use the floating literal syntax for instances of ``Integral``, and have values like ``(1.2e6 :: Num a => a)`` @@ -471,7 +505,8 @@ like ``(1.2e6 :: Num a => a)`` Binary integer literals ----------------------- -.. ghc-flag:: -XBinaryLiterals +.. extension:: BinaryLiterals + :shortdesc: Enable support for binary literals. :since: 7.10.1 @@ -481,19 +516,150 @@ 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 :ghc-flag:`-XBinaryLiterals` adds support for expressing +The language extension :extension:`BinaryLiterals` 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. +``fromInteger 201`` when :extension:`BinaryLiterals` is enabled. + +.. _hex-float-literals: + +Hexadecimal floating point literals +----------------------------------- + +.. extension:: HexFloatLiterals + :shortdesc: Enable support for :ref:`hexadecimal floating point literals <hex-float-literals>`. + + :since: 8.4.1 + + Allow writing floating point literals using hexadecimal notation. + +The hexadecimal notation for floating point literals is useful when you +need to specify floating point constants precisely, as the literal notation +corresponds closely to the underlying bit-encoding of the number. + +In this notation floating point numbers are written using hexadecimal digits, +and so the digits are interpreted using base 16, rather then the usual 10. +This means that digits left of the decimal point correspond to positive +powers of 16, while the ones to the right correspond to negative ones. + +You may also write an explicit exponent, which is similar to the exponent +in decimal notation with the following differences: +- the exponent begins with ``p`` instead of ``e`` +- the exponent is written in base ``10`` (**not** 16) +- the base of the exponent is ``2`` (**not** 16). + +In terms of the underlying bit encoding, each hexadecimal digit corresponds +to 4 bits, and you may think of the exponent as "moving" the floating point +by one bit left (negative) or right (positive). Here are some examples: + +- ``0x0.1`` is the same as ``1/16`` +- ``0x0.01`` is the same as ``1/256`` +- ``0xF.FF`` is the same as ``15 + 15/16 + 15/256`` +- ``0x0.1p4`` is the same as ``1`` +- ``0x0.1p-4`` is the same as ``1/256`` +- ``0x0.1p12`` is the same as ``256`` + + + + +.. _numeric-underscores: + +Numeric underscores +------------------- + +.. extension:: NumericUnderscores + :shortdesc: Enable support for :ref:`numeric underscores <numeric-underscores>`. + + :since: 8.6.1 + + Allow the use of underscores in numeric literals. + +GHC allows for numeric literals to be given in decimal, octal, hexadecimal, +binary, or float notation. + +The language extension :extension:`NumericUnderscores` adds support for expressing +underscores in numeric literals. +For instance, the numeric literal ``1_000_000`` will be parsed into +``1000000`` when :extension:`NumericUnderscores` is enabled. +That is, underscores in numeric literals are ignored when +:extension:`NumericUnderscores` is enabled. +See also :ghc-ticket:`14473`. + +For example: + +.. code-block:: none + + -- decimal + million = 1_000_000 + billion = 1_000_000_000 + lightspeed = 299_792_458 + version = 8_04_1 + date = 2017_12_31 + + -- hexadecimal + red_mask = 0xff_00_00 + size1G = 0x3fff_ffff + + -- binary + bit8th = 0b01_0000_0000 + packbits = 0b1_11_01_0000_0_111 + bigbits = 0b1100_1011__1110_1111__0101_0011 + + -- float + pi = 3.141_592_653_589_793 + faraday = 96_485.332_89 + avogadro = 6.022_140_857e+23 + + -- function + isUnderMillion = (< 1_000_000) + + clip64M x + | x > 0x3ff_ffff = 0x3ff_ffff + | otherwise = x + + test8bit x = (0b01_0000_0000 .&. x) /= 0 + +About validity: + +.. code-block:: none + + x0 = 1_000_000 -- valid + x1 = 1__000000 -- valid + x2 = 1000000_ -- invalid + x3 = _1000000 -- invalid + + e0 = 0.0001 -- valid + e1 = 0.000_1 -- valid + e2 = 0_.0001 -- invalid + e3 = _0.0001 -- invalid + e4 = 0._0001 -- invalid + e5 = 0.0001_ -- invalid + + f0 = 1e+23 -- valid + f1 = 1_e+23 -- valid + f2 = 1__e+23 -- valid + f3 = 1e_+23 -- invalid + + g0 = 1e+23 -- valid + g1 = 1e+_23 -- invalid + g2 = 1e+23_ -- invalid + + h0 = 0xffff -- valid + h1 = 0xff_ff -- valid + h2 = 0x_ffff -- valid + h3 = 0x__ffff -- valid + h4 = _0xffff -- invalid .. _pattern-guards: Pattern guards -------------- -.. ghc-flag:: -XNoPatternGuards +.. extension:: NoPatternGuards + :shortdesc: Disable pattern guards. + Implied by :extension:`Haskell98`. - :implied by: :ghc-flag:`-XHaskell98` + :implied by: :extension:`Haskell98` :since: 6.8.1 Disable `pattern guards @@ -504,11 +670,14 @@ Disable `pattern guards View patterns ------------- -.. ghc-flag:: -XViewPatterns +.. extension:: ViewPatterns + :shortdesc: Enable view patterns. + + :since: 6.10.1 Allow use of view pattern syntax. -View patterns are enabled by the flag :ghc-flag:`-XViewPatterns`. More +View patterns are enabled by the language extension :extension:`ViewPatterns`. More information and examples of view patterns can be found on the :ghc-wiki:`Wiki page <ViewPatterns>`. @@ -642,10 +811,12 @@ follows: n+k patterns ------------ -.. ghc-flag:: -XNPlusKPatterns +.. extension:: NPlusKPatterns + :shortdesc: Enable support for ``n+k`` patterns. + Implied by :extension:`Haskell98`. - :implied by: :ghc-flag:`-XHaskell98` - :since: 6.12 + :implied by: :extension:`Haskell98` + :since: 6.12.1 Enable use of ``n+k`` patterns. @@ -654,7 +825,10 @@ n+k patterns The recursive do-notation ------------------------- -.. ghc-flag:: -XRecursiveDo +.. extension:: RecursiveDo + :shortdesc: Enable recursive do (mdo) notation. + + :since: 6.8.1 Allow the use of recursive ``do`` notation. @@ -679,7 +853,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 -:ghc-flag:`-XRecursiveDo` (language pragma: ``RecursiveDo``) provides the +:extension:`RecursiveDo` (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`` @@ -715,7 +889,7 @@ lower level syntax flagged by the ``rec`` keyword, as we describe next. Recursive binding groups ~~~~~~~~~~~~~~~~~~~~~~~~ -The flag :ghc-flag:`-XRecursiveDo` also introduces a new keyword ``rec``, which +The extension :extension:`RecursiveDo` 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 @@ -834,8 +1008,8 @@ version would do so. Here are some other important points in using the recursive-do notation: -- It is enabled with the flag :ghc-flag:`-XRecursiveDo`, or the - ``LANGUAGE RecursiveDo`` pragma. (The same flag enables both +- It is enabled with the extension :extension:`RecursiveDo`, or the + ``LANGUAGE RecursiveDo`` pragma. (The same extension enables both ``mdo``-notation, and the use of ``rec`` blocks inside ``do`` expressions.) @@ -866,13 +1040,14 @@ Applicative do-notation single: Applicative do-notation single: do-notation; Applicative -.. ghc-flag:: -XApplicativeDo +.. extension:: ApplicativeDo + :shortdesc: Enable Applicative do-notation desugaring :since: 8.0.1 Allow use of ``Applicative`` ``do`` notation. -The language option :ghc-flag:`-XApplicativeDo` enables an alternative translation for +The language option :extension:`ApplicativeDo` 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: @@ -884,10 +1059,10 @@ 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 -:ghc-flag:`-XApplicativeDo` without fear of breaking your program. There is one pitfall +:extension:`ApplicativeDo` 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 :ghc-flag:`-XApplicativeDo`. The only way it shows +There are no syntactic changes with :extension:`ApplicativeDo`. 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: :: @@ -957,6 +1132,10 @@ cases it might miss an opportunity. There is an algorithm that finds the optimal solution, provided as an option: .. ghc-flag:: -foptimal-applicative-do + :shortdesc: Use a slower but better algorithm for ApplicativeDo + :type: dynamic + :reverse: -fno-optimal-applicative-do + :category: optimization :since: 8.0.1 @@ -1003,52 +1182,12 @@ will always be connected with ``>>=``, to retain the same strictness semantics as the standard do-notation. If you don't want this, simply put a ``~`` on the pattern match to make it lazy. -.. _applicative-do-existential: - -Existential patterns and GADTs -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -When the pattern in a statement matches a constructor with -existential type variables and/or constraints, the transformation that -``ApplicativeDo`` performs may mean that the pattern does not scope -over the statements that follow it. This is because the rearrangement -happens before the expression is typechecked. For example, this -program does not typecheck:: - - {-# LANGUAGE RankNTypes, GADTs, ApplicativeDo #-} - - data T where A :: forall a . Eq a => a -> T - - test = do - A x <- undefined - _ <- return 'a' - _ <- return 'b' - return (x == x) - -The reason is that the ``Eq`` constraint that would be brought into -scope from the pattern match ``A x`` is not available when -typechecking the expression ``x == x``, because ``ApplicativeDo`` has -rearranged the expression to look like this:: - - test = - (\x _ -> x == x) - <$> do A x <- undefined; _ <- return 'a'; return x - <*> return 'b' - -(Note that the ``return 'a'`` and ``return 'b'`` statements are needed -to make ``ApplicativeDo`` apply despite the restriction noted in -:ref:`applicative-do-strict`, because ``A x`` is a strict pattern match.) - -Turning off ``ApplicativeDo`` lets the program typecheck. This is -something to bear in mind when using ``ApplicativeDo`` in combination -with :ref:`existential-quantification` or :ref:`gadt`. - .. _applicative-do-pitfall: Things to watch out for ~~~~~~~~~~~~~~~~~~~~~~~ -Your code should just work as before when :ghc-flag:`-XApplicativeDo` is enabled, +Your code should just work as before when :extension:`ApplicativeDo` 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: :: @@ -1092,7 +1231,10 @@ Parallel List Comprehensions single: list comprehensions; parallel single: parallel list comprehensions -.. ghc-flag:: -XParallelListComp +.. extension:: ParallelListComp + :shortdesc: Enable parallel list comprehensions. + + :since: 6.8.1 Allow parallel list comprehension syntax. @@ -1141,7 +1283,10 @@ Generalised (SQL-like) List Comprehensions single: group single: SQL -.. ghc-flag:: -XTransformListComp +.. extension:: TransformListComp + :shortdesc: Enable generalised list comprehensions. + + :since: 6.10.1 Allow use of generalised list (SQL-like) comprehension syntax. This introduces the ``group``, ``by``, and ``using`` keywords. @@ -1153,7 +1298,7 @@ paper `Comprehensive comprehensions: comprehensions with "order by" and "group by" <https://www.microsoft.com/en-us/research/wp-content/uploads/2007/09/list-comp.pdf>`__, except that the syntax we use differs slightly from the paper. -The extension is enabled with the flag :ghc-flag:`-XTransformListComp`. +The extension is enabled with the extension :extension:`TransformListComp`. Here is an example: @@ -1279,9 +1424,10 @@ Monad comprehensions .. index:: single: monad comprehensions -.. ghc-flag:: -XMonadComprehensions +.. extension:: MonadComprehensions + :shortdesc: Enable monad comprehensions. - :since: 7.2 + :since: 7.2.1 Enable list comprehension syntax for arbitrary monads. @@ -1314,7 +1460,7 @@ Monad comprehensions support: guard (x <= 5) return x -- Transform statements (as with :ghc-flag:`-XTransformListComp`): :: +- Transform statements (as with :extension:`TransformListComp`): :: [ x+y | x <- [1..10], y <- [1..x], then take 2 ] @@ -1325,14 +1471,14 @@ Monad comprehensions support: return (x,y)) return (x+y) -- Group statements (as with :ghc-flag:`-XTransformListComp`): +- Group statements (as with :extension:`TransformListComp`): :: [ 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 :ghc-flag:`-XParallelListComp`): +- Parallel statements (as with :extension:`ParallelListComp`): :: @@ -1352,7 +1498,7 @@ Monad comprehensions support: return y) return (x+y) -All these features are enabled by default if the :ghc-flag:`-XMonadComprehensions` +All these features are enabled by default if the :extension:`MonadComprehensions` extension is enabled. The types and more detailed examples on how to use comprehensions are explained in the previous chapters :ref:`generalised-list-comprehensions` and @@ -1363,7 +1509,7 @@ comprehensions. .. note:: Even though most of these examples are using the list monad, monad comprehensions work for any monad. The ``base`` package offers all - necessary instances for lists, which make :ghc-flag:`-XMonadComprehensions` + necessary instances for lists, which make :extension:`MonadComprehensions` backward compatible to built-in, transform and parallel list comprehensions. @@ -1441,7 +1587,8 @@ parameterised over some arbitrary type ``n`` (provided it has an New monadic failure desugaring mechanism ---------------------------------------- -.. ghc-flag:: -XMonadFailDesugaring +.. extension:: MonadFailDesugaring + :shortdesc: Enable monadfail desugaring. :since: 8.0.1 @@ -1449,21 +1596,24 @@ New monadic failure desugaring mechanism 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 -eventually be the default behaviour in a future GHC release, under the +``do``-blocks to use ``MonadFail.fail`` instead of ``Monad.fail``. + +This extension is enabled by default since GHC 8.6.1, under the `MonadFail Proposal (MFP) <https://prime.haskell.org/wiki/Libraries/Proposals/MonadFail>`__. -This extension is temporary, and will be deprecated in a future release. It is -included so that library authors have a hard check for whether their code -will work with future GHC versions. +This extension is temporary, and will be deprecated in a future release. .. _rebindable-syntax: Rebindable syntax and the implicit Prelude import ------------------------------------------------- -.. ghc-flag:: -XNoImplicitPrelude +.. extension:: NoImplicitPrelude + :shortdesc: Don't implicitly ``import Prelude``. + Implied by :extension:`RebindableSyntax`. + + :since: 6.8.1 Don't import ``Prelude`` by default. @@ -1473,9 +1623,11 @@ 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 +.. extension:: RebindableSyntax + :shortdesc: Employ rebindable syntax. + Implies :extension:`NoImplicitPrelude`. - :implies: :ghc-flag:`-XNoImplicitPrelude` + :implies: :extension:`NoImplicitPrelude` :since: 7.0.1 Enable rebinding of a variety of usually-built-in operations. @@ -1483,7 +1635,7 @@ must not conflict with any Prelude module.) 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 :ghc-flag:`-XRebindableSyntax` flag causes the +Report specifies. So the :extension:`RebindableSyntax` extension causes the following pieces of built-in syntax to refer to *whatever is in scope*, not the Prelude versions: @@ -1524,7 +1676,7 @@ not the Prelude versions: - An overloaded label "``#foo``" means "``fromLabel @"foo"``", rather than "``GHC.OverloadedLabels.fromLabel @"foo"``" (see :ref:`overloaded-labels`). -:ghc-flag:`-XRebindableSyntax` implies :ghc-flag:`-XNoImplicitPrelude`. +:extension:`RebindableSyntax` implies :extension:`NoImplicitPrelude`. 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 @@ -1541,10 +1693,10 @@ Be warned: this is an experimental facility, with fewer checks than usual. Use ``-dcore-lint`` to typecheck the desugared program. If Core Lint is happy you should be all right. -Things unaffected by :ghc-flag:`-XRebindableSyntax` +Things unaffected by :extension:`RebindableSyntax` ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -:ghc-flag:`-XRebindableSyntax` does not apply to any code generated from a +:extension:`RebindableSyntax` does not apply to any code generated from a ``deriving`` clause or declaration. To see why, consider the following code: :: {-# LANGUAGE RebindableSyntax, OverloadedStrings #-} @@ -1560,12 +1712,12 @@ This will generate code to the effect of: :: instance Show Foo where showsPrec _ Foo = showString "Foo" -But because :ghc-flag:`-XRebindableSyntax` and :ghc-flag:`-XOverloadedStrings` +But because :extension:`RebindableSyntax` and :extension:`OverloadedStrings` are enabled, the ``"Foo"`` string literal would now be of type ``Text``, not ``String``, which ``showString`` doesn't accept! This causes the generated ``Show`` instance to fail to typecheck. It's hard to imagine any scenario where -it would be desirable have :ghc-flag:`-XRebindableSyntax` behavior within -derived code, so GHC simply ignores :ghc-flag:`-XRebindableSyntax` entirely +it would be desirable have :extension:`RebindableSyntax` behavior within +derived code, so GHC simply ignores :extension:`RebindableSyntax` entirely when checking derived code. .. _postfix-operators: @@ -1573,11 +1725,14 @@ when checking derived code. Postfix operators ----------------- -.. ghc-flag:: -XPostfixOperators +.. extension:: PostfixOperators + :shortdesc: Enable postfix operators. + + :since: 7.10.1 Allow the use of post-fix operators -The :ghc-flag:`-XPostfixOperators` flag enables a small extension to the syntax +The :extension:`PostfixOperators` extension enables a small extension to the syntax of left operator sections, which allows you to define postfix operators. The extension is this: the left section :: @@ -1605,13 +1760,14 @@ definitions; you must define such a function in prefix form. Tuple sections -------------- -.. ghc-flag:: -XTupleSections +.. extension:: TupleSections + :shortdesc: Enable tuple sections. :since: 6.12 Allow the use of tuple section syntax -The :ghc-flag:`-XTupleSections` flag enables partially applied +The :extension:`TupleSections` extension enables partially applied tuple constructors. For example, the following program :: (, True) @@ -1646,13 +1802,14 @@ continues to stand for the unboxed singleton tuple data constructor. Lambda-case ----------- -.. ghc-flag:: -XLambdaCase +.. extension:: LambdaCase + :shortdesc: Enable lambda-case expressions. :since: 7.6.1 Allow the use of lambda-case syntax. -The :ghc-flag:`-XLambdaCase` flag enables expressions of the form :: +The :extension:`LambdaCase` extension enables expressions of the form :: \case { p1 -> e1; ...; pN -> eN } @@ -1672,13 +1829,14 @@ Note that ``\case`` starts a layout, so you can write :: Empty case alternatives ----------------------- -.. ghc-flag:: -XEmptyCase +.. extension:: EmptyCase + :shortdesc: Allow empty case alternatives. :since: 7.8.1 Allow empty case expressions. -The :ghc-flag:`-XEmptyCase` flag enables case expressions, or lambda-case +The :extension:`EmptyCase` extension enables case expressions, or lambda-case expressions, that have no alternatives, thus: :: case e of { } -- No alternatives @@ -1701,8 +1859,8 @@ example, consider these two candidate definitions of ``absurd``: :: - data a :==: b where - Refl :: a :==: a + data a :~: b where + Refl :: a :~: a absurd :: True :~: False -> a absurd x = error "absurd" -- (A) @@ -1710,23 +1868,23 @@ 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 :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. +is able to compile with :ghc-flag:`-Wincomplete-patterns` and +:ghc-flag:`-Werror`. On the other hand (A) looks dangerous, and GHC doesn't +check to make sure that, in fact, the function can never get called. .. _multi-way-if: Multi-way if-expressions ------------------------ -.. ghc-flag:: -XMultiWayIf +.. extension:: MultiWayIf + :shortdesc: Enable multi-way if-expressions. :since: 7.6.1 Allow the use of multi-way-``if`` syntax. -With :ghc-flag:`-XMultiWayIf` flag GHC accepts conditional expressions with +With :extension:`MultiWayIf` extension GHC accepts conditional expressions with multiple branches: :: if | guard1 -> expr1 @@ -1799,7 +1957,7 @@ elsewhere, as in :: let infixr 9 $ in ... -Because local fixity declarations are technically Haskell 98, no flag is +Because local fixity declarations are technically Haskell 98, no extension is necessary to enable them. .. _package-imports: @@ -1836,11 +1994,14 @@ not export. Package-qualified imports ~~~~~~~~~~~~~~~~~~~~~~~~~ -.. ghc-flag:: -XPackageImports +.. extension:: PackageImports + :shortdesc: Enable package-qualified imports. + + :since: 6.10.1 Allow the use of package-qualified ``import`` syntax. -With the :ghc-flag:`-XPackageImports` flag, GHC allows import declarations to be +With the :extension:`PackageImports` extension, GHC allows import declarations to be qualified by the package name that the module is intended to be imported from. For example: :: @@ -1867,16 +2028,31 @@ package being built. Safe imports ~~~~~~~~~~~~ -.. ghc-flag:: -XSafe - -XTrustworthy - -XUnsafe +.. extension:: Safe + :shortdesc: Enable the :ref:`Safe Haskell <safe-haskell>` Safe mode. :noindex: - :since: 7.2 + :since: 7.2.1 Declare the Safe Haskell state of the current module. -With the :ghc-flag:`-XSafe`, :ghc-flag:`-XTrustworthy` and :ghc-flag:`-XUnsafe` +.. extension:: Trustworthy + :shortdesc: Enable the :ref:`Safe Haskell <safe-haskell>` Trustworthy mode. + :noindex: + + :since: 7.2.1 + + Declare the Safe Haskell state of the current module. + +.. extension:: Unsafe + :shortdesc: Enable Safe Haskell Unsafe mode. + :noindex: + + :since: 7.4.1 + + Declare the Safe Haskell state of the current module. + +With the :extension:`Safe`, :extension:`Trustworthy` and :extension:`Unsafe` 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: :: @@ -1892,7 +2068,10 @@ when a import is considered safe see :ref:`safe-haskell`. Explicit namespaces in import/export ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.. ghc-flag:: -XExplicitNamespaces +.. extension:: ExplicitNamespaces + :shortdesc: Enable using the keyword ``type`` to specify the namespace of + entries in imports and exports (:ref:`explicit-namespaces`). + Implied by :extension:`TypeOperators` and :extension:`TypeFamilies`. :since: 7.6.1 @@ -1909,7 +2088,7 @@ operators (:ref:`type-operators`) it becomes possible to declare ``(++)`` as a *type constructor*. In that case, how would you export or import it? -The :ghc-flag:`-XExplicitNamespaces` extension allows you to prefix the name of +The :extension:`ExplicitNamespaces` extension allows you to prefix the name of a type constructor in an import or export list with "``type``" to disambiguate this case, thus: :: @@ -1919,14 +2098,112 @@ disambiguate this case, thus: :: module N( f, type (++) ) where data family a ++ b = L a | R b -The extension :ghc-flag:`-XExplicitNamespaces` is implied by -:ghc-flag:`-XTypeOperators` and (for some reason) by :ghc-flag:`-XTypeFamilies`. +The extension :extension:`ExplicitNamespaces` is implied by +:extension:`TypeOperators` and (for some reason) by :extension:`TypeFamilies`. -In addition, with :ghc-flag:`-XPatternSynonyms` you can prefix the name of a +In addition, with :extension:`PatternSynonyms` 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`). +.. _block-arguments: + +More liberal syntax for function arguments +------------------------------------------ + +.. extension:: BlockArguments + :shortdesc: Allow ``do`` blocks and other constructs as function arguments. + + :since: 8.6.1 + + Allow ``do`` expressions, lambda expressions, etc. to be directly used as + a function argument. + +In Haskell 2010, certain kinds of expressions can be used without parentheses +as an argument to an operator, but not as an argument to a function. +They include ``do``, lambda, ``if``, ``case``, and ``let`` +expressions. Some GHC extensions also define language constructs of this type: +``mdo`` (:ref:`recursive-do-notation`), ``\case`` (:ref:`lambda-case`), and +``proc`` (:ref:`arrow-notation`). + +The :extension:`BlockArguments` extension allows these constructs to be directly +used as a function argument. For example:: + + when (x > 0) do + print x + exitFailure + +will be parsed as:: + + when (x > 0) (do + print x + exitFailure) + +and + +:: + + withForeignPtr fptr \ptr -> c_memcpy buf ptr size + +will be parsed as:: + + withForeignPtr fptr (\ptr -> c_memcpy buf ptr size) + +Changes to the grammar +~~~~~~~~~~~~~~~~~~~~~~ + +The Haskell report `defines +<https://www.haskell.org/onlinereport/haskell2010/haskellch3.html#x8-220003>`_ +the ``lexp`` nonterminal thus (``*`` indicates a rule of interest):: + + lexp → \ apat1 … apatn -> exp (lambda abstraction, n ≥ 1) * + | let decls in exp (let expression) * + | if exp [;] then exp [;] else exp (conditional) * + | case exp of { alts } (case expression) * + | do { stmts } (do expression) * + | fexp + + fexp → [fexp] aexp (function application) + + aexp → qvar (variable) + | gcon (general constructor) + | literal + | ( exp ) (parenthesized expression) + | qcon { fbind1 … fbindn } (labeled construction) + | aexp { fbind1 … fbindn } (labelled update) + | … + +The :extension:`BlockArguments` extension moves these production rules under +``aexp``:: + + lexp → fexp + + fexp → [fexp] aexp (function application) + + aexp → qvar (variable) + | gcon (general constructor) + | literal + | ( exp ) (parenthesized expression) + | qcon { fbind1 … fbindn } (labeled construction) + | aexp { fbind1 … fbindn } (labelled update) + | \ apat1 … apatn -> exp (lambda abstraction, n ≥ 1) * + | let decls in exp (let expression) * + | if exp [;] then exp [;] else exp (conditional) * + | case exp of { alts } (case expression) * + | do { stmts } (do expression) * + | … + +Now the ``lexp`` nonterminal is redundant and can be dropped from the grammar. + +Note that this change relies on an existing meta-rule to resolve ambiguities: + + The grammar is ambiguous regarding the extent of lambda abstractions, let + expressions, and conditionals. The ambiguity is resolved by the meta-rule + that each of these constructs extends as far to the right as possible. + +For example, ``f \a -> a b`` will be parsed as ``f (\a -> a b)``, not as ``f +(\a -> a) b``. + .. _syntax-stolen: Summary of stolen syntax @@ -1956,39 +2233,39 @@ The following syntax is stolen: .. index:: single: forall - Stolen (in types) by: :ghc-flag:`-XExplicitForAll`, and hence by - :ghc-flag:`-XScopedTypeVariables`, :ghc-flag:`-XLiberalTypeSynonyms`, - :ghc-flag:`-XRankNTypes`, :ghc-flag:`-XExistentialQuantification` + Stolen (in types) by: :extension:`ExplicitForAll`, and hence by + :extension:`ScopedTypeVariables`, :extension:`LiberalTypeSynonyms`, + :extension:`RankNTypes`, :extension:`ExistentialQuantification` ``mdo`` .. index:: single: mdo - Stolen by: :ghc-flag:`-XRecursiveDo` + Stolen by: :extension:`RecursiveDo` ``foreign`` .. index:: single: foreign - Stolen by: :ghc-flag:`-XForeignFunctionInterface` + Stolen by: :extension:`ForeignFunctionInterface` ``rec``, ``proc``, ``-<``, ``>-``, ``-<<``, ``>>-``, ``(|``, ``|)`` .. index:: single: proc - Stolen by: :ghc-flag:`-XArrows` + Stolen by: :extension:`Arrows` ``?varid`` .. index:: single: implicit parameters - Stolen by: :ghc-flag:`-XImplicitParams` + Stolen by: :extension:`ImplicitParams` ``[|``, ``[e|``, ``[p|``, ``[d|``, ``[t|``, ``[||``, ``[e||`` .. index:: single: Quasi-quotes - Stolen by: :ghc-flag:`-XQuasiQuotes`. Moreover, this introduces an ambiguity + Stolen by: :extension:`QuasiQuotes`. Moreover, this introduces an ambiguity with list comprehension syntax. See the :ref:`discussion on quasi-quoting <quasi-quotes-list-comprehension-ambiguity>` for details. @@ -1997,25 +2274,28 @@ The following syntax is stolen: .. index:: single: Template Haskell - Stolen by: :ghc-flag:`-XTemplateHaskell` + Stolen by: :extension:`TemplateHaskell` ``[varid|`` .. index:: single: quasi-quotation - Stolen by: :ghc-flag:`-XQuasiQuotes` + Stolen by: :extension:`QuasiQuotes` ⟨varid⟩, ``#``\ ⟨char⟩, ``#``, ⟨string⟩, ``#``, ⟨integer⟩, ``#``, ⟨float⟩, ``#``, ⟨float⟩, ``##`` - Stolen by: :ghc-flag:`-XMagicHash` + Stolen by: :extension:`MagicHash` ``(#``, ``#)`` - Stolen by: :ghc-flag:`-XUnboxedTuples` + Stolen by: :extension:`UnboxedTuples` ⟨varid⟩, ``!``, ⟨varid⟩ - Stolen by: :ghc-flag:`-XBangPatterns` + Stolen by: :extension:`BangPatterns` ``pattern`` - Stolen by: :ghc-flag:`-XPatternSynonyms` + Stolen by: :extension:`PatternSynonyms` + +``static`` + Stolen by: :extension:`StaticPointers` .. _data-type-extensions: @@ -2027,29 +2307,45 @@ Extensions to data types and type synonyms Data types with no constructors ------------------------------- -.. ghc-flag:: -XEmptyDataDecls +.. extension:: EmptyDataDecls + :shortdesc: Allow definition of empty ``data`` types. + + :since: 6.8.1 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: :: +With the :extension:`EmptyDataDecls` extension, GHC lets you declare a +data type with no constructors. + +You only need to enable this extension if the language you're using +is Haskell 98, in which a data type must have at least one constructor. +Haskell 2010 relaxed this rule to allow data types with no constructors, +and thus :extension:`EmptyDataDecls` is enabled by default when the +language is Haskell 2010. + +For example: :: - data S -- S :: * - data T a -- T :: * -> * + data S -- S :: Type + data T a -- T :: Type -> Type -Syntactically, the declaration lacks the "= constrs" part. The type can -be parameterised over types of any kind, but if the kind is not ``*`` -then an explicit kind annotation must be used (see :ref:`kinding`). +Syntactically, the declaration lacks the "= constrs" part. The type can be +parameterised over types of any kind, but if the kind is not ``Type`` then an +explicit kind annotation must be used (see :ref:`kinding`). Such data types have only one value, namely bottom. Nevertheless, they can be useful when defining "phantom types". +In conjunction with the :ghc-flag:`-XEmptyDataDeriving` extension, empty data +declarations can also derive instances of standard type classes +(see :ref:`empty-data-deriving`). + .. _datatype-contexts: Data type contexts ------------------ -.. ghc-flag:: -XDatatypeContexts +.. extension:: DatatypeContexts + :shortdesc: Allow contexts on ``data`` types. :since: 7.0.1 @@ -2121,9 +2417,12 @@ specifically: Type operators -------------- -.. ghc-flag:: -XTypeOperators +.. extension:: TypeOperators + :shortdesc: Enable type operators. + Implies :extension:`ExplicitNamespaces`. - :implies: :ghc-flag:`-XExplicitNamespaces` + :implies: :extension:`ExplicitNamespaces` + :since: 6.8.1 Allow the use and definition of types with operator names. @@ -2141,7 +2440,7 @@ 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 :ghc-flag:`-XTypeOperators` changes this behaviour: +The language :extension:`TypeOperators` changes this behaviour: - Operator symbols become type *constructors* rather than type *variables*. @@ -2155,8 +2454,8 @@ The language :ghc-flag:`-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 :ghc-flag:`-XExplicitNamespaces` (which is implied by - :ghc-flag:`-XTypeOperators`) GHC allows you to specify the latter by + but with :extension:`ExplicitNamespaces` (which is implied by + :extension:`TypeOperators`) GHC allows you to specify the latter by preceding it with the keyword ``type``, thus: :: import M( type (+) ) @@ -2172,15 +2471,17 @@ The language :ghc-flag:`-XTypeOperators` changes this behaviour: Liberalised type synonyms ------------------------- -.. ghc-flag:: -XLiberalTypeSynonyms +.. extension:: LiberalTypeSynonyms + :shortdesc: Enable liberalised type synonyms. - :implies: :ghc-flag:`-XExplicitForAll` + :implies: :extension:`ExplicitForAll` + :since: 6.8.1 Relax many of the Haskell 98 rules on type synonym definitions. Type synonyms are like macros at the type level, but Haskell 98 imposes many rules on individual synonym declarations. With the -:ghc-flag:`-XLiberalTypeSynonyms` extension, GHC does validity checking on types +:extension:`LiberalTypeSynonyms` 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. @@ -2195,7 +2496,7 @@ 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 :ghc-flag:`-XUnboxedTuples`, you can write an unboxed tuple +- If you also use :extension:`UnboxedTuples`, you can write an unboxed tuple in a type synonym: :: type Pr = (# Int, Int #) @@ -2232,7 +2533,7 @@ looking for the following malformedness which isn't detected simply by kind checking: - Type constructor applied to a type involving for-alls (if - :ghc-flag:`-XImpredicativeTypes` is off) + :extension:`ImpredicativeTypes` is off) - Partially-applied type synonym. @@ -2250,9 +2551,11 @@ because GHC does not allow type constructors applied to for-all types. Existentially quantified data constructors ------------------------------------------ -.. ghc-flag:: -XExistentialQuantification +.. extension:: ExistentialQuantification + :shortdesc: Enable liberalised type synonyms. - :implies: :ghc-flag:`-XExplicitForAll` + :implies: :extension:`ExplicitForAll` + :since: 6.8.1 Allow existentially quantified type variables in types. @@ -2506,12 +2809,13 @@ constructors can be used. Declaring data types with explicit constructor signatures --------------------------------------------------------- -.. ghc-flag:: -XGADTSyntax +.. extension:: GADTSyntax + :shortdesc: Enable generalised algebraic data type syntax. - :since: 7.2 + :since: 7.2.1 Allow the use of GADT syntax in data type definitions (but not GADTs - themselves; for this see :ghc-flag:`-XGADTs`) + themselves; for this see :extension:`GADTs`) When the ``GADTSyntax`` extension is enabled, GHC allows you to declare an algebraic data type by giving the type signatures of constructors @@ -2655,16 +2959,16 @@ type declarations. in the "``data Set a where``" header have no scope. Indeed, one can write a kind signature instead: :: - data Set :: * -> * where ... + data Set :: Type -> Type where ... or even a mixture of the two: :: - data Bar a :: (* -> *) -> * where ... + data Bar a :: (Type -> Type) -> Type where ... The type variables (if given) may be explicitly kinded, so we could also write the header for ``Foo`` like this: :: - data Bar a (b :: * -> *) where ... + data Bar a (b :: Type -> Type) where ... - You can use strictness annotations, in the obvious places in the constructor type: :: @@ -2758,9 +3062,12 @@ type declarations. Generalised Algebraic Data Types (GADTs) ---------------------------------------- -.. ghc-flag:: -XGADTs +.. extension:: GADTs + :shortdesc: Enable generalised algebraic data types. + Implies :extension:`GADTSyntax` and :extension:`MonoLocalBinds`. - :implies: :ghc-flag:`-XMonoLocalBinds`, :ghc-flag:`-XGADTSyntax` + :implies: :extension:`MonoLocalBinds`, :extension:`GADTSyntax` + :since: 6.8.1 Allow use of Generalised Algebraic Data Types (GADTs). @@ -2820,8 +3127,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 :ghc-flag:`-XGADTs`. The :ghc-flag:`-XGADTs` flag -also sets :ghc-flag:`-XGADTSyntax` and :ghc-flag:`-XMonoLocalBinds`. +GADTs. The extension is enabled with :extension:`GADTs`. The :extension:`GADTs` extension +also sets :extension:`GADTSyntax` and :extension:`MonoLocalBinds`. - A GADT can only be declared using GADT-style syntax (:ref:`gadt-style`); the old Haskell 98 syntax for data declarations @@ -2897,21 +3204,27 @@ Extensions to the record system Traditional record syntax ------------------------- -.. ghc-flag:: -XNoTraditionalRecordSyntax +.. extension:: NoTraditionalRecordSyntax + :shortdesc: Disable support for traditional record syntax + (as supported by Haskell 98) ``C {f = x}`` :since: 7.4.1 Disallow use of record syntax. Traditional record syntax, such as ``C {f = x}``, is enabled by default. -To disable it, you can use the :ghc-flag:`-XNoTraditionalRecordSyntax` flag. +To disable it, you can use the :extension:`NoTraditionalRecordSyntax` extension. .. _disambiguate-fields: Record field disambiguation --------------------------- -.. ghc-flag:: -XDisambiguateRecordFields +.. extension:: DisambiguateRecordFields + :shortdesc: Enable record field disambiguation. + Implied by :extension:`RecordWildCards`. + + :since: 6.8.1 Allow the compiler to automatically choose between identically-named record selectors based on type (if the choice is unambiguous). @@ -2943,7 +3256,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 -:ghc-flag:`-XDisambiguateRecordFields` flag, GHC will accept the former two. The +:extension:`DisambiguateRecordFields` extension, GHC will accept the former two. The rules are precisely the same as those for instance declarations in Haskell 98, where the method names on the left-hand side of the method bindings in an instance declaration refer unambiguously to the method of @@ -2962,7 +3275,7 @@ Some details: x=True ok3 (MkS { x }) = x+1 -- Uses both disambiguation and punning -- With :ghc-flag:`-XDisambiguateRecordFields` you can use *unqualified* field +- With :extension:`DisambiguateRecordFields` 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: :: @@ -2982,15 +3295,16 @@ Some details: Duplicate record fields ----------------------- -.. ghc-flag:: -XDuplicateRecordFields +.. extension:: DuplicateRecordFields + :shortdesc: Allow definition of record types with identically-named fields. - :implies: :ghc-flag:`-XDisambiguateRecordFields` + :implies: :extension:`DisambiguateRecordFields` :since: 8.0.1 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 +Going beyond :extension:`DisambiguateRecordFields` (see :ref:`disambiguate-fields`), +the :extension:`DuplicateRecordFields` extension allows multiple datatypes to be declared using the same field names in a single module. For example, it allows this: :: @@ -3001,7 +3315,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 -:ghc-flag:`-XDisambiguateRecordFields`): :: +:extension:`DisambiguateRecordFields`): :: s = MkS { x = 3 } @@ -3058,7 +3372,7 @@ definitions: :: data T = MkT { foo :: Int, bar :: Int } data U = MkU { bar :: Int, baz :: Int } -Without :ghc-flag:`-XDuplicateRecordFields`, an update mentioning ``foo`` will always be +Without :extension:`DuplicateRecordFields`, 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: @@ -3097,7 +3411,7 @@ ambiguous: :: Import and export of record fields ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -When :ghc-flag:`-XDuplicateRecordFields` is enabled, an ambiguous field must be exported +When :extension:`DuplicateRecordFields` 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: :: @@ -3116,11 +3430,14 @@ Similar restrictions apply on import. Record puns ----------- -.. ghc-flag:: -XNamedFieldPuns +.. extension:: NamedFieldPuns + :shortdesc: Enable record puns. + + :since: 6.10.1 Allow use of record puns. -Record puns are enabled by the flag :ghc-flag:`-XNamedFieldPuns`. +Record puns are enabled by the language extension :extension:`NamedFieldPuns`. When using records, it is common to write a pattern that binds a variable with the same name as a record field, such as: :: @@ -3177,14 +3494,17 @@ Note that: Record wildcards ---------------- -.. ghc-flag:: -XRecordWildCards +.. extension:: RecordWildCards + :shortdesc: Enable record wildcards. + Implies :extension:`DisambiguateRecordFields`. - :implies: :ghc-flag:`-XDisambiguateRecordFields`. + :implies: :extension:`DisambiguateRecordFields`. + :since: 6.8.1 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`. +Record wildcards are enabled by the language extension :extension:`RecordWildCards`. This +exension implies :extension:`DisambiguateRecordFields`. For records with many fields, it can be tiresome to write out each field individually in a record pattern, as in :: @@ -3223,11 +3543,6 @@ More details: refers to the nearest enclosing variables that are spelled the same as the omitted field names. -- Record wildcards may *not* be used in record *updates*. For example - this is illegal: :: - - f r = r { x = 3, .. } - - For both pattern and expression wildcards, the "``..``" expands to the missing *in-scope* record fields. Specifically the expansion of "``C {..}``" includes ``f`` if and only if: @@ -3237,26 +3552,42 @@ More details: - The record field ``f`` is in scope somehow (either qualified or unqualified). - - In the case of expressions (but not patterns), the variable ``f`` - is in scope unqualified, and is not imported or bound at top level. - For example, ``f`` can be bound by an enclosing pattern match or - let/where-binding. (The motivation here is that it should be - easy for the reader to figure out what the "``..``" expands to.) - These rules restrict record wildcards to the situations in which the user could have written the expanded version. For example :: module M where data R = R { a,b,c :: Int } module X where - import M( R(a,c) ) - f b = R { .. } + import M( R(R,a,c) ) + f a b = R { .. } - The ``R{..}`` expands to ``R{M.a=a}``, omitting ``b`` since the + The ``R{..}`` expands to ``R{a=a}``, omitting ``b`` since the record field is not in scope, and omitting ``c`` since the variable ``c`` is not in scope (apart from the binding of the record selector ``c``, of course). +- When record wildcards are use in record construction, a field ``f`` + is initialised only if ``f`` is in scope, + and is not imported or bound at top level. + For example, ``f`` can be bound by an enclosing pattern match or + let/where-binding. For example :: + + module M where + import A( a ) + + data R = R { a,b,c,d :: Int } + + c = 3 :: Int + + f b = R { .. } -- Expands to R { b = b, d = d } + where + d = b+1 + + Here, ``a`` is imported, and ``c`` is bound at top level, so neither + contribute to the expansion of the "``..``". + The motivation here is that it should be + easy for the reader to figure out what the "``..``" expands to. + - Record wildcards cannot be used (a) in a record update construct, and (b) for data constructors that are not declared with record fields. For example: :: @@ -3449,6 +3780,79 @@ prohibited, to avoid conflicts in downstream modules. Extensions to the "deriving" mechanism ====================================== +Haskell 98 allows the programmer to add a deriving clause to a data type +declaration, to generate a standard instance declaration for specified class. +GHC extends this mechanism along several axes: + +* The derivation mechanism can be used separtely from the data type + declaration, using the `standalone deriving mechanism + <#stand-alone-deriving>`__. + +* In Haskell 98, the only derivable classes are ``Eq``, + ``Ord``, ``Enum``, ``Ix``, ``Bounded``, ``Read``, and ``Show``. `Various + language extensions <#deriving-extra>`__ extend this list. + +* Besides the stock approach to deriving instances by generating all method + definitions, GHC supports two additional deriving strategies, which can + derive arbitrary classes: + + * `Generalised newtype deriving <#newtype-deriving>`__ for newtypes and + * `deriving any class <#derive-any-class>`__ using an empty instance + declaration. + + The user can optionally declare the desired `deriving strategy + <#deriving-stragies>`__, especially if the compiler chooses the wrong + one `by default <#default-deriving-strategy>`__. + +.. _empty-data-deriving: + +Deriving instances for empty data types +--------------------------------------- + +.. ghc-flag:: -XEmptyDataDeriving + :shortdesc: Allow deriving instances of standard type classes for + empty data types. + :type: dynamic + :reverse: -XNoEmptyDataDeriving + :category: + + :since: 8.4.1 + + Allow deriving instances of standard type classes for empty data types. + +One can write data types with no constructors using the +:ghc-flag:`-XEmptyDataDecls` flag (see :ref:`nullary-types`), which is on by +default in Haskell 2010. What is not on by default is the ability to derive +type class instances for these types. This ability is enabled through use of +the :ghc-flag:`-XEmptyDataDeriving` flag. For instance, this lets one write: :: + + data Empty deriving (Eq, Ord, Read, Show) + +This would generate the following instances: :: + + instance Eq Empty where + _ == _ = True + + instance Ord Empty where + compare _ _ = EQ + + instance Read Empty where + readPrec = pfail + + instance Show Empty where + showsPrec _ x = case x of {} + +The :ghc-flag:`-XEmptyDataDeriving` flag is only required to enable deriving +of these four "standard" type classes (which are mentioned in the Haskell +Report). Other extensions to the ``deriving`` mechanism, which are explained +below in greater detail, do not require :ghc-flag:`-XEmptyDataDeriving` to be +used in conjunction with empty data types. These include: + +* :ghc-flag:`-XStandaloneDeriving` (see :ref:`stand-alone-deriving`) +* Type classes which require their own extensions to be enabled to be derived, + such as :ghc-flag:`-XDeriveFunctor` (see :ref:`deriving-extra`) +* :ghc-flag:`-XDeriveAnyClass` (see :ref:`derive-any-class`) + .. _deriving-inferred: Inferred context for deriving clauses @@ -3485,12 +3889,15 @@ mechanism <#stand-alone-deriving>`__. Stand-alone deriving declarations --------------------------------- -.. ghc-flag:: -XStandaloneDeriving +.. extension:: StandaloneDeriving + :shortdesc: Enable standalone deriving. + + :since: 6.8.1 Allow the use of stand-alone ``deriving`` declarations. GHC allows stand-alone ``deriving`` declarations, enabled by -:ghc-flag:`-XStandaloneDeriving`: :: +:extension:`StandaloneDeriving`: :: data Foo a = Bar a | Baz String @@ -3507,14 +3914,24 @@ number of important ways: module as the data type declaration. (But be aware of the dangers of orphan instances (:ref:`orphan-modules`). -- You must supply an explicit context (in the example the context is - ``(Eq a)``), exactly as you would in an ordinary instance +- In most cases, you must supply an explicit context (in the example the + context is ``(Eq a)``), exactly as you would in an ordinary instance declaration. (In contrast, in a ``deriving`` clause attached to a data type declaration, the context is inferred.) + The exception to this rule is that the context of a standalone deriving + declaration can infer its context when a single, extra-wildcards constraint + is used as the context, such as in: :: + + deriving instance _ => Eq (Foo a) + + This is essentially the same as if you had written ``deriving Foo`` after + the declaration for ``data Foo a``. Using this feature requires the use of + :extension:`PartialTypeSignatures` (:ref:`partial-type-signatures`). + - Unlike a ``deriving`` declaration attached to a ``data`` declaration, the instance can be more specific than the data type (assuming you - also use :ghc-flag:`-XFlexibleInstances`, :ref:`instance-rules`). Consider + also use :extension:`FlexibleInstances`, :ref:`instance-rules`). Consider for example :: data Foo a = Bar a | Baz String @@ -3557,8 +3974,8 @@ number of important ways: because the derived instance would generate code that uses the constructors behind the scenes, which would break abstraction. - The one exception to this rule is :ghc-flag:`-XDeriveAnyClass`, since - deriving an instance via :ghc-flag:`-XDeriveAnyClass` simply generates + The one exception to this rule is :extension:`DeriveAnyClass`, since + deriving an instance via :extension:`DeriveAnyClass` simply generates an empty instance declaration, which does not require the use of any constructors. See the `deriving any class <#derive-any-class>`__ section for more details. @@ -3586,32 +4003,6 @@ ordinary deriving: Deriving instances of extra classes (``Data``, etc.) ---------------------------------------------------- -.. ghc-flag:: -XDeriveGeneric - - :since: 7.2 - - Allow automatic deriving of instances for the ``Generic`` typeclass. - -.. ghc-flag:: -XDeriveFunctor - - :since: 6.12 - - Allow automatic deriving of instances for the ``Functor`` typeclass. - -.. ghc-flag:: -XDeriveFoldable - - :since: 6.12 - - Allow automatic deriving of instances for the ``Foldable`` typeclass. - -.. ghc-flag:: -XDeriveTraversable - - :since: 6.12 - - :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 @@ -3622,31 +4013,30 @@ classes ``Eq``, ``Ord``, ``Enum``, ``Ix``, ``Bounded``, ``Read``, and GHC extends this list with several more classes that may be automatically derived: -- With :ghc-flag:`-XDeriveGeneric`, you can derive instances of the classes +- With :extension:`DeriveGeneric`, 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 :ghc-flag:`-XDeriveFunctor`, you can derive instances of the class - ``Functor``, defined in ``GHC.Base``. See :ref:`deriving-functor`. +- With :extension:`DeriveFunctor`, you can derive instances of the class + ``Functor``, defined in ``GHC.Base``. -- With :ghc-flag:`-XDeriveDataTypeable`, you can derive instances of the class - ``Data``, defined in ``Data.Data``. See :ref:`deriving-data`. +- With :extension:`DeriveDataTypeable`, you can derive instances of the class + ``Data``, defined in ``Data.Data``. -- With :ghc-flag:`-XDeriveFoldable`, you can derive instances of the class - ``Foldable``, defined in ``Data.Foldable``. See - :ref:`deriving-foldable`. +- With :extension:`DeriveFoldable`, you can derive instances of the class + ``Foldable``, defined in ``Data.Foldable``. -- With :ghc-flag:`-XDeriveTraversable`, you can derive instances of the class +- With :extension:`DeriveTraversable`, 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 - :ghc-flag:`-XDeriveTraversable` implies :ghc-flag:`-XDeriveFunctor` and - :ghc-flag:`-XDeriveFoldable`. See :ref:`deriving-traversable`. + :extension:`DeriveTraversable` implies :extension:`DeriveFunctor` and + :extension:`DeriveFoldable`. -- With :ghc-flag:`-XDeriveLift`, you can derive instances of the class ``Lift``, +- With :extension:`DeriveLift`, 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`. + ``template-haskell`` package. You can also use a standalone deriving declaration instead (see :ref:`stand-alone-deriving`). @@ -3657,10 +4047,19 @@ mentioned in the ``deriving`` clause. .. _deriving-functor: Deriving ``Functor`` instances ------------------------------- +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. extension:: DeriveFunctor + :shortdesc: Enable deriving for the Functor class. + Implied by :extension:`DeriveTraversable`. + + :since: 7.10.1 + + Allow automatic deriving of instances for the ``Functor`` typeclass. -With :ghc-flag:`-XDeriveFunctor`, one can derive ``Functor`` instances for data types -of kind ``* -> *``. For example, this declaration:: + +With :extension:`DeriveFunctor`, one can derive ``Functor`` instances for data types +of kind ``Type -> Type``. For example, this declaration:: data Example a = Ex a Char (Example a) (Example Char) deriving Functor @@ -3670,7 +4069,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 :ghc-flag:`-XDeriveFunctor` walks the arguments of each +The basic algorithm for :extension:`DeriveFunctor` 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 @@ -3695,7 +4094,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 :ghc-flag:`-XDeriveFunctor` works. The +This distinction is important because of the way :extension:`DeriveFunctor` works. The derived ``Functor Right`` instance would be:: instance Functor Right where @@ -3716,13 +4115,13 @@ causes the generated code to be ill-typed. As a general rule, if a data type has a derived ``Functor`` instance and its last type parameter occurs on the right-hand side of the data declaration, then -either it must (1) occur bare (e.g., ``newtype Id a = a``), or (2) occur as the +either it must (1) occur bare (e.g., ``newtype Id a = Id a``), or (2) occur as the last argument of a type constructor (as in ``Right`` above). There are two exceptions to this rule: #. Tuple types. When a non-unit tuple is used on the right-hand side of a data - declaration, :ghc-flag:`-XDeriveFunctor` treats it as a product of distinct types. + declaration, :extension:`DeriveFunctor` treats it as a product of distinct types. In other words, the following code:: newtype Triple a = Triple (a, Int, [a]) deriving Functor @@ -3734,9 +4133,9 @@ There are two exceptions to this rule: Triple (case a of (a1, a2, a3) -> (f a1, a2, fmap f a3)) - That is, :ghc-flag:`-XDeriveFunctor` pattern-matches its way into tuples and maps + That is, :extension:`DeriveFunctor` 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 + reminiscent of what would be generated from ``data Triple a = Triple a Int [a]``, except with extra machinery to handle the tuple. @@ -3800,11 +4199,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 :ghc-flag:`-XDatatypeContexts` +#. A data type's last type variable is used in a :extension:`DatatypeContexts` constraint (e.g., ``data Ord a => O a = O a``). #. A data type's last type variable is used in an - :ghc-flag:`-XExistentialQuantification` constraint, or is refined in a GADT. For + :extension:`ExistentialQuantification` constraint, or is refined in a GADT. For example, :: data T a b where @@ -3829,7 +4228,7 @@ will produce the following instance: :: When a type has no constructors, the derived ``Functor`` instance will simply force the (bottom) value of the argument using -:ghc-flag:`-XEmptyCase`. :: +:extension:`EmptyCase`. :: data V a deriving Functor type role V nominal @@ -3842,10 +4241,18 @@ will produce .. _deriving-foldable: Deriving ``Foldable`` instances -------------------------------- +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -With :ghc-flag:`-XDeriveFoldable`, one can derive ``Foldable`` instances for data types -of kind ``* -> *``. For example, this declaration:: +.. extension:: DeriveFoldable + :shortdesc: Enable deriving for the Foldable class. + Implied by :extension:`DeriveTraversable`. + + :since: 7.10.1 + + Allow automatic deriving of instances for the ``Foldable`` typeclass. + +With :extension:`DeriveFoldable`, one can derive ``Foldable`` instances for data types +of kind ``Type -> Type``. For example, this declaration:: data Example a = Ex a Char (Example a) (Example Char) deriving Foldable @@ -3856,15 +4263,15 @@ 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 :ghc-flag:`-XDeriveFoldable` is adapted from the -:ghc-flag:`-XDeriveFunctor` algorithm, but it generates definitions for +The algorithm for :extension:`DeriveFoldable` is adapted from the +:extension:`DeriveFunctor` algorithm, but it generates definitions for ``foldMap``, ``foldr``, and ``null`` instead of ``fmap``. In addition, -:ghc-flag:`-XDeriveFoldable` filters out all constructor arguments on the RHS +:extension:`DeriveFoldable` filters out all constructor arguments on the RHS expression whose types do not mention the last type parameter, since those arguments do not need to be folded over. When the type parameter has a phantom role (see :ref:`roles`), -:ghc-flag:`-XDeriveFoldable` derives a trivial instance. For example, this +:extension:`DeriveFoldable` derives a trivial instance. For example, this declaration: :: data Phantom a = Z | S (Phantom a) @@ -3874,7 +4281,7 @@ will generate the following instance. :: instance Foldable Phantom where foldMap _ _ = mempty -Similarly, when the type has no constructors, :ghc-flag:`-XDeriveFoldable` will +Similarly, when the type has no constructors, :extension:`DeriveFoldable` will derive a trivial instance: :: data V a deriving Foldable @@ -3888,14 +4295,14 @@ will generate the following. :: Here are the differences between the generated code for ``Functor`` and ``Foldable``: -#. When a bare type variable ``a`` is encountered, :ghc-flag:`-XDeriveFunctor` -would generate ``f a`` for an ``fmap`` definition. :ghc-flag:`-XDeriveFoldable` +#. When a bare type variable ``a`` is encountered, :extension:`DeriveFunctor` +would generate ``f a`` for an ``fmap`` definition. :extension:`DeriveFoldable` would generate ``f a z`` for ``foldr``, ``f a`` for ``foldMap``, and ``False`` for ``null``. #. When a type that is not syntactically equivalent to ``a``, but which does - contain ``a``, is encountered, :ghc-flag:`-XDeriveFunctor` recursively calls - ``fmap`` on it. Similarly, :ghc-flag:`-XDeriveFoldable` would recursively call + contain ``a``, is encountered, :extension:`DeriveFunctor` recursively calls + ``fmap`` on it. Similarly, :extension:`DeriveFoldable` would recursively call ``foldr`` and ``foldMap``. Depending on the context, ``null`` may recursively call ``null`` or ``all null``. For example, given :: @@ -3909,8 +4316,8 @@ for ``null``. null (G x) = null x null (H x) = all null x -#. :ghc-flag:`-XDeriveFunctor` puts everything back together again at the end by - invoking the constructor. :ghc-flag:`-XDeriveFoldable`, however, builds up a value +#. :extension:`DeriveFunctor` puts everything back together again at the end by + invoking the constructor. :extension:`DeriveFoldable`, however, builds up a value of some type. For ``foldr``, this is accomplished by chaining applications of ``f`` and recursive ``foldr`` calls on the state value ``z``. For ``foldMap``, this happens by combining all values with ``mappend``. For ``null``, @@ -3964,7 +4371,7 @@ There are some other differences regarding what data types can have derived polymorphic types that are syntactically equivalent to the last type parameter. In particular: - - We don't fold over the arguments of ``E1`` or ``E4`` beacause even though + - We don't fold over the arguments of ``E1`` or ``E4`` because even though ``(a ~ Int)``, ``Int`` is not syntactically equivalent to ``a``. - We don't fold over the argument of ``E3`` because ``a`` is not universally @@ -3974,10 +4381,20 @@ There are some other differences regarding what data types can have derived .. _deriving-traversable: Deriving ``Traversable`` instances ----------------------------------- +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + + +.. extension:: DeriveTraversable + :shortdesc: Enable deriving for the Traversable class. + Implies :extension:`DeriveFunctor` and :extension:`DeriveFoldable`. + + :implies: :extension:`DeriveFoldable`, :extension:`DeriveFunctor` + :since: 7.10.1 + + Allow automatic deriving of instances for the ``Traversable`` typeclass. -With :ghc-flag:`-XDeriveTraversable`, one can derive ``Traversable`` instances for data -types of kind ``* -> *``. For example, this declaration:: +With :extension:`DeriveTraversable`, one can derive ``Traversable`` instances for data +types of kind ``Type -> Type``. For example, this declaration:: data Example a = Ex a Char (Example a) (Example Char) deriving (Functor, Foldable, Traversable) @@ -3988,15 +4405,15 @@ would generate the following ``Traversable`` instance:: traverse f (Ex a1 a2 a3 a4) = fmap (\b1 b3 -> Ex b1 a2 b3 a4) (f a1) <*> traverse f a3 -The algorithm for :ghc-flag:`-XDeriveTraversable` is adapted from the -:ghc-flag:`-XDeriveFunctor` algorithm, but it generates a definition for ``traverse`` -instead of ``fmap``. In addition, :ghc-flag:`-XDeriveTraversable` filters out +The algorithm for :extension:`DeriveTraversable` is adapted from the +:extension:`DeriveFunctor` algorithm, but it generates a definition for ``traverse`` +instead of ``fmap``. In addition, :extension:`DeriveTraversable` filters out all constructor arguments on the RHS expression whose types do not mention the last type parameter, since those arguments do not produce any effects in a traversal. When the type parameter has a phantom role (see :ref:`roles`), -:ghc-flag:`-XDeriveTraversable` coerces its argument. For example, this +:extension:`DeriveTraversable` coerces its argument. For example, this declaration:: data Phantom a = Z | S (Phantom a) deriving Traversable @@ -4006,13 +4423,13 @@ will generate the following instance:: instance Traversable Phantom where traverse _ z = pure (coerce z) -When the type has no constructors, :ghc-flag:`-XDeriveTraversable` will +When the type has no constructors, :extension:`DeriveTraversable` will derive the laziest instance it can. :: data V a deriving Traversable type role V nominal -will generate the following, using :ghc-flag:`-XEmptyCase`: :: +will generate the following, using :extension:`EmptyCase`: :: instance Traversable V where traverse _ z = pure (case z of) @@ -4020,40 +4437,44 @@ will generate the following, using :ghc-flag:`-XEmptyCase`: :: Here are the differences between the generated code in each extension: -#. When a bare type variable ``a`` is encountered, both :ghc-flag:`-XDeriveFunctor` and - :ghc-flag:`-XDeriveTraversable` would generate ``f a`` for an ``fmap`` and +#. When a bare type variable ``a`` is encountered, both :extension:`DeriveFunctor` and + :extension:`DeriveTraversable` 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, :ghc-flag:`-XDeriveFunctor` recursively calls - ``fmap`` on it. Similarly, :ghc-flag:`-XDeriveTraversable` would recursively call + contain ``a``, is encountered, :extension:`DeriveFunctor` recursively calls + ``fmap`` on it. Similarly, :extension:`DeriveTraversable` would recursively call ``traverse``. -#. :ghc-flag:`-XDeriveFunctor` puts everything back together again at the end by - invoking the constructor. :ghc-flag:`-XDeriveTraversable` does something similar, +#. :extension:`DeriveFunctor` puts everything back together again at the end by + invoking the constructor. :extension:`DeriveTraversable` does something similar, but it works in an ``Applicative`` context by chaining everything together with ``(<*>)``. -Unlike :ghc-flag:`-XDeriveFunctor`, :ghc-flag:`-XDeriveTraversable` cannot be used on data +Unlike :extension:`DeriveFunctor`, :extension:`DeriveTraversable` cannot be used on data types containing a function type on the right-hand side. -For a full specification of the algorithms used in :ghc-flag:`-XDeriveFunctor`, -:ghc-flag:`-XDeriveFoldable`, and :ghc-flag:`-XDeriveTraversable`, see +For a full specification of the algorithms used in :extension:`DeriveFunctor`, +:extension:`DeriveFoldable`, and :extension:`DeriveTraversable`, see :ghc-wiki:`this wiki page <Commentary/Compiler/DeriveFunctor>`. .. _deriving-data: Deriving ``Data`` instances -------------------------------- +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. extension:: DeriveDataTypeable + :shortdesc: Enable deriving for the Data class. + Implied by (deprecated) :extension:`AutoDeriveTypeable`. -.. ghc-flag:: -XDeriveDataTypeable + :since: 6.8.1 Enable automatic deriving of instances for the ``Data`` typeclass .. _deriving-typeable: Deriving ``Typeable`` instances -------------------------------- +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The class ``Typeable`` is very special: @@ -4065,7 +4486,7 @@ The class ``Typeable`` is very special: bogus instances. - Derived instances of ``Typeable`` may be declared if the - :ghc-flag:`-XDeriveDataTypeable` extension is enabled, but they are ignored, + :extension:`DeriveDataTypeable` extension is enabled, but they are ignored, and they may be reported as an error in a later version of the compiler. - The rules for solving \`Typeable\` constraints are as follows: @@ -4081,24 +4502,23 @@ The class ``Typeable`` is very special: applied to all of its kinds parameters, and these kinds need to be concrete (i.e., they cannot mention kind variables). - - :: + - A type variable applied to some types:: - A type variable applied to some types. instance (Typeable f, Typeable t1, .., Typeable t_n) => Typeable (f t1 .. t_n) - - :: + - A concrete type literal.:: - A concrete type literal. instance Typeable 0 -- Type natural literals instance Typeable "Hello" -- Type-level symbols .. _deriving-lift: Deriving ``Lift`` instances ---------------------------- +~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.. ghc-flag:: -XDeriveLift +.. extension:: DeriveLift + :shortdesc: Enable deriving for the Lift class :since: 8.0.1 @@ -4149,7 +4569,7 @@ Here is an example of how one can derive ``Lift``: fooExp :: Lift a => Foo a -> Q Exp fooExp f = [| f |] -:ghc-flag:`-XDeriveLift` also works for certain unboxed types (``Addr#``, ``Char#``, +:extension:`DeriveLift` also works for certain unboxed types (``Addr#``, ``Char#``, ``Double#``, ``Float#``, ``Int#``, and ``Word#``): :: @@ -4178,8 +4598,11 @@ Here is an example of how one can derive ``Lift``: Generalised derived instances for newtypes ------------------------------------------ -.. ghc-flag:: -XGeneralisedNewtypeDeriving - -XGeneralizedNewtypeDeriving +.. extension:: GeneralisedNewtypeDeriving + GeneralizedNewtypeDeriving + :shortdesc: Enable newtype deriving. + + :since: 6.8.1. British spelling since 8.6.1. Enable GHC's cunning generalised deriving mechanism for ``newtype``\s @@ -4203,13 +4626,16 @@ It is particularly galling that, since the constructor doesn't appear at run-time, this instance declaration defines a dictionary which is *wholly equivalent* to the ``Int`` dictionary, only slower! +:extension:`DerivingVia` (see :ref:`deriving-via`) is a generalization of +this idea. + .. _generalized-newtype-deriving: Generalising the deriving clause ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -GHC now permits such instances to be derived instead, using the flag -:ghc-flag:`-XGeneralizedNewtypeDeriving`, so one can write :: +GHC now permits such instances to be derived instead, using the extension +:extension:`GeneralizedNewtypeDeriving`, so one can write :: newtype Dollars = Dollars { getDollars :: Int } deriving (Eq,Show,Num) @@ -4255,7 +4681,7 @@ In this case the derived instance declaration is of the form :: instance Monad (State [tok] (Failure m)) => Monad (Parser tok m) Notice that, since ``Monad`` is a constructor class, the instance is a -*partial application* of the new type, not the entire left hand side. We +*partial application* of the newtype, not the entire left hand side. We can imagine that the type declaration is "eta-converted" to generate the context of the instance declaration. @@ -4283,6 +4709,43 @@ declarations are treated uniformly (and implemented just by reusing the dictionary for the representation type), *except* ``Show`` and ``Read``, which really behave differently for the newtype and its representation. +.. note:: + + It is sometimes necessary to enable additional language extensions when + deriving instances via :extension:`GeneralizedNewtypeDeriving`. For instance, + consider a simple class and instance using :extension:`UnboxedTuples` + syntax: :: + + {-# LANGUAGE UnboxedTuples #-} + + module Lib where + + class AClass a where + aMethod :: a -> (# Int, a #) + + instance AClass Int where + aMethod x = (# x, x #) + + The following will fail with an "Illegal unboxed tuple" error, since the + derived instance produced by the compiler makes use of unboxed tuple syntax, + :: + + {-# LANGUAGE GeneralizedNewtypeDeriving #-} + + import Lib + + newtype Int' = Int' Int + deriving (AClass) + + However, enabling the :extension:`UnboxedTuples` extension allows the module + to compile. Similar errors may occur with a variety of extensions, + including: + + * :extension:`UnboxedTuples` + * :extension:`PolyKinds` + * :extension:`MultiParamTypeClasses` + * :extension:`FlexibleContexts` + .. _precise-gnd-specification: A more precise specification @@ -4315,7 +4778,8 @@ where - ``C`` is not ``Read``, ``Show``, ``Typeable``, or ``Data``. These classes should not "look through" the type or its constructor. You can still derive these classes for a newtype, but it happens in the - usual way, not via this new mechanism. + usual way, not via this new mechanism. Confer with + :ref:`default-deriving-strategy`. - It is safe to coerce each of the methods of ``C``. That is, the missing last argument to ``C`` is not used at a nominal role in any @@ -4370,7 +4834,7 @@ whether the stock method is used or the one described here.) Associated type families ~~~~~~~~~~~~~~~~~~~~~~~~ -:ghc-flag:`-XGeneralizedNewtypeDeriving` also works for some type classes with +:extension:`GeneralizedNewtypeDeriving` also works for some type classes with associated type families. Here is an example: :: class HasRing a where @@ -4419,7 +4883,7 @@ then you can derive a ``C c_1 c_2 ... c_(m-1)`` instance for Now we're stuck, since we have no way to refer to ``a`` on the right-hand side of the ``B`` family instance, so this instance doesn't really make sense - in a :ghc-flag:`-XGeneralizedNewtypeDeriving` setting. + in a :extension:`GeneralizedNewtypeDeriving` setting. - ``C`` does not have any associated data families (only type families). To see why data families are forbidden, imagine the following scenario: :: @@ -4456,7 +4920,7 @@ redundant, so GHC will instead generate ``instance C c_1 c_2 ... c_(m-1) (N n_1 n_2 ... n_q)``. Beware that in some cases, you may need to enable the -:ghc-flag:`-XUndecidableInstances` extension in order to use this feature. +:extension:`UndecidableInstances` extension in order to use this feature. Here's a pathological case that illustrates why this might happen: :: class C a where @@ -4472,7 +4936,7 @@ This will generate the derived instance: :: Here, it is evident that attempting to use the type ``T Loop`` will throw the typechecker into an infinite loop, as its definition recurses endlessly. In -other cases, you might need to enable :ghc-flag:`-XUndecidableInstances` even +other cases, you might need to enable :extension:`UndecidableInstances` even if the generated code won't put the typechecker into a loop. For example: :: instance C Int where @@ -4488,22 +4952,28 @@ This will generate the derived instance: :: Although typechecking ``T MyInt`` will terminate, GHC's termination checker isn't sophisticated enough to determine this, so you'll need to enable -:ghc-flag:`-XUndecidableInstances` in order to use this derived instance. If +:extension:`UndecidableInstances` in order to use this derived instance. If you do go down this route, make sure you can convince yourself that all of the type family instances you're deriving will eventually terminate if used! +Note that :extension:`DerivingVia` (see :ref:`deriving-via`) uses essentially +the same specification to derive instances of associated type families as well +(except that it uses the ``via`` type instead of the underlying ``rep-type`` +of a newtype). + .. _derive-any-class: Deriving any other class ------------------------ -.. ghc-flag:: -XDeriveAnyClass +.. extension:: DeriveAnyClass + :shortdesc: Enable deriving for any class. :since: 7.10.1 Allow use of any typeclass in ``deriving`` clauses. -With :ghc-flag:`-XDeriveAnyClass` you can derive any other class. The compiler +With :extension:`DeriveAnyClass` you can derive any other class. The compiler will simply generate an instance declaration with no explicitly-defined methods. This is @@ -4522,7 +4992,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 :ghc-flag:`-XDeriveAnyClass` extension to +default to ``show``. Now we can leverage the :extension:`DeriveAnyClass` extension to easily implement a ``SPretty`` instance for a new data type: :: data Foo = Foo deriving (Show, SPretty) @@ -4533,14 +5003,14 @@ 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 :ghc-flag:`-XDefaultSignatures` in this example, a +for all methods. Since we are using :extension:`DefaultSignatures` 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 :ghc-flag:`-XGeneralizedNewtypeDeriving` is also on, - :ghc-flag:`-XDeriveAnyClass` takes precedence. + class on a newtype, and :extension:`GeneralizedNewtypeDeriving` is also on, + :extension:`DeriveAnyClass` takes precedence. - The instance context is determined by the type signatures of the derived class's methods. For instance, if the class is: :: @@ -4554,7 +5024,7 @@ Note the following details default baz :: Ord a => a -> a -> Bool baz x y = compare x y == EQ - And you attempt to derive it using :ghc-flag:`-XDeriveAnyClass`: :: + And you attempt to derive it using :extension:`DeriveAnyClass`: :: instance Eq a => Eq (Option a) where ... instance Ord a => Ord (Option a) where ... @@ -4608,7 +5078,7 @@ Note the following details instance HigherEq Option -- :ghc-flag:`-XDeriveAnyClass` can be used with partially applied classes, +- :extension:`DeriveAnyClass` can be used with partially applied classes, such as :: data T a = MKT a deriving( D Int ) @@ -4617,7 +5087,7 @@ Note the following details instance D Int a => D Int (T a) where {} -- :ghc-flag:`-XDeriveAnyClass` can be used to fill in default instances for +- :extension:`DeriveAnyClass` can be used to fill in default instances for associated type families: :: {-# LANGUAGE DeriveAnyClass, TypeFamilies #-} @@ -4643,14 +5113,17 @@ Note the following details Deriving strategies ------------------- -.. ghc-flag:: -XDerivingStrategies +.. extension:: DerivingStrategies + :shortdesc: Enables deriving strategies. + + :since: 8.2.1 Allow multiple ``deriving``, each optionally qualified with a *strategy*. In most scenarios, every ``deriving`` statement generates a typeclass instance in an unambiguous fashion. There is a corner case, however, where -simultaneously enabling both the :ghc-flag:`-XGeneralizedNewtypeDeriving` and -:ghc-flag:`-XDeriveAnyClass` extensions can make deriving become ambiguous. +simultaneously enabling both the :extension:`GeneralizedNewtypeDeriving` and +:extension:`DeriveAnyClass` extensions can make deriving become ambiguous. Consider the following example :: {-# LANGUAGE DeriveAnyClass, GeneralizedNewtypeDeriving #-} @@ -4664,7 +5137,7 @@ to use both language extensions in a single module. To make this more robust, GHC has a notion of deriving strategies, which allow the user to explicitly request which approach to use when deriving an instance. -To enable this feature, one must enable the :ghc-flag:`-XDerivingStrategies` +To enable this feature, one must enable the :extension:`DerivingStrategies` language extension. A deriving strategy can be specified in a deriving clause :: @@ -4675,7 +5148,7 @@ Or in a standalone deriving declaration :: deriving anyclass instance C Foo -:ghc-flag:`-XDerivingStrategies` also allows the use of multiple deriving +:extension:`DerivingStrategies` also allows the use of multiple deriving clauses per data declaration so that a user can derive some instance with one deriving strategy and other instances with another deriving strategy. For example :: @@ -4691,29 +5164,173 @@ Currently, the deriving strategies are: - ``stock``: Have GHC implement a "standard" instance for a data type, if possible (e.g., ``Eq``, ``Ord``, ``Generic``, ``Data``, ``Functor``, etc.) -- ``anyclass``: Use :ghc-flag:`-XDeriveAnyClass` +- ``anyclass``: Use :extension:`DeriveAnyClass` (see :ref:`derive-any-class`) + +- ``newtype``: Use :extension:`GeneralizedNewtypeDeriving` + (see :ref:`newtype-deriving`) + +- ``via``: Use :extension:`DerivingVia` (see :ref:`deriving-via`) + +.. _default-deriving-strategy: + +Default deriving strategy +~~~~~~~~~~~~~~~~~~~~~~~~~ + +If an explicit deriving strategy is not given, multiple strategies may apply. +In that case, GHC chooses the strategy as follows: + +1. Stock type classes, i.e. those specified in the report and those enabled by + `language extensions <#deriving-extra>`__, are derived using the ``stock`` + strategy, with the following exception: + + * For newtypes, ``Eq``, ``Ord``, ``Ix`` and ``Bounded`` are always derived + using the ``newtype`` strategy, even without + ``GeneralizedNewtypeDeriving`` enabled. (There should be no observable + difference to instances derived using the stock strategy.) + + * Also for newtypes, ``Functor``, ``Foldable`` and ``Enum`` are derived + using the ``newtype`` strategy if ``GeneralizedNewtypeDeriving`` is + enabled and the derivation succeeds. + +2. For other any type class: + + 1. When ``DeriveAnyClass`` is enabled, use ``anyclass``. + + 2. When ``GeneralizedNewtypeDeriving`` is enabled and we are deriving for a + newtype, then use ``newytype``. + + If both rules apply to a deriving clause, then ``anyclass`` is used and the + user is warned about the ambiguity. The warning can be avoided by explicitly + stating the desired deriving strategy. + +.. _deriving-via: + +Deriving via +------------ + +.. extension:: DerivingVia + :shortdesc: Enable deriving instances ``via`` types of the same runtime + representation. + Implies :extension:`DerivingStrategies`. + + :implies: :extension:`DerivingStrategies` -- ``newtype``: Use :ghc-flag:`-XGeneralizedNewtypeDeriving` + :since: 8.6.1 -If an explicit deriving strategy is not given, GHC has an algorithm for -determining how it will actually derive an instance. For brevity, the algorithm -is omitted here. You can read the full algorithm on the -:ghc-wiki:`GHC Wiki <Commentary/Compiler/DerivingStrategies>`. +This allows ``deriving`` a class instance for a type by specifying +another type of equal runtime representation (such that there exists a +``Coercible`` instance between the two: see :ref:`coercible`) that is +already an instance of the that class. + +:extension:`DerivingVia` is indicated by the use of the ``via`` +deriving strategy. ``via`` requires specifying another type (the ``via`` type) +to ``coerce`` through. For example, this code: :: + + {-# LANGUAGE DerivingVia #-} + + import Numeric + + newtype Hex a = Hex a + + instance (Integral a, Show a) => Show (Hex a) where + show (Hex a) = "0x" ++ showHex a "" + + newtype Unicode = U Int + deriving Show + via (Hex Int) + + -- >>> euroSign + -- 0x20ac + euroSign :: Unicode + euroSign = U 0x20ac + +Generates the following instance :: + + instance Show Unicode where + show :: Unicode -> String + show = Data.Coerce.coerce + @(Hex Int -> String) + @(Unicode -> String) + show + +This extension generalizes :extension:`GeneralizedNewtypeDeriving`. To +derive ``Num Unicode`` with GND (``deriving newtype Num``) it must +reuse the ``Num Int`` instance. With ``DerivingVia``, we can explicitly +specify the representation type ``Int``: :: + + newtype Unicode = U Int + deriving Num + via Int + + deriving Show + via (Hex Int) + + euroSign :: Unicode + euroSign = 0x20ac + +Code duplication is common in instance declarations. A familiar +pattern is lifting operations over an ``Applicative`` functor. +Instead of having catch-all instances for ``f a`` which overlap +with all other such instances, like so: :: + + instance (Applicative f, Semigroup a) => Semigroup (f a) .. + instance (Applicative f, Monoid a) => Monoid (f a) .. + +We can instead create a newtype ``App`` +(where ``App f a`` and ``f a`` are represented the same in memory) +and use :extension:`DerivingVia` to explicitly enable uses of this +pattern: :: + + {-# LANGUAGE DerivingVia, DeriveFunctor, GeneralizedNewtypeDeriving #-} + + import Control.Applicative + + newtype App f a = App (f a) deriving newtype (Functor, Applicative) + + instance (Applicative f, Semigroup a) => Semigroup (App f a) where + (<>) = liftA2 (<>) + + instance (Applicative f, Monoid a) => Monoid (App f a) where + mempty = pure mempty + + data Pair a = MkPair a a + deriving stock + Functor + + deriving (Semigroup, Monoid) + via (App Pair a) + + instance Applicative Pair where + pure a = MkPair a a + + MkPair f g <*> MkPair a b = MkPair (f a) (g b) + +Note that the ``via`` type does not have to be a ``newtype``. +The only restriction is that it is coercible with the +original data type. This means there can be arbitrary nesting of newtypes, +as in the following example: :: + + newtype Kleisli m a b = (a -> m b) + deriving (Semigroup, Monoid) + via (a -> App m b) + +Here we make use of the ``Monoid ((->) a)`` instance. .. _pattern-synonyms: Pattern synonyms ================ -.. ghc-flag:: -XPatternSynonyms +.. extension:: PatternSynonyms + :shortdesc: Enable pattern synonyms. :since: 7.8.1 Allow the definition of pattern synonyms. -Pattern synonyms are enabled by the flag :ghc-flag:`-XPatternSynonyms`, which is +Pattern synonyms are enabled by the language extension :extension:`PatternSynonyms`, 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>`. +examples of pattern synonyms can be found on the :ghc-wiki:`Wiki page <PatternSynonyms>`. Pattern synonyms enable giving names to parametrized pattern schemes. They can also be thought of as abstract constructors that don't have a @@ -4815,6 +5432,52 @@ We can then use ``HeadC`` in both expression and pattern contexts. In a pattern context it will match the head of any list with length at least one. In an expression context it will construct a singleton list. +Explicitly bidirectional pattern synonyms offer greater flexibility than +implicitly bidirectional ones in terms of the syntax that is permitted. For +instance, the following is not a legal implicitly bidirectional pattern +synonym: :: + + pattern StrictJust a = Just !a + +This is illegal because the use of :extension:`BangPatterns` on the right-hand +sides prevents it from being a well formed expression. However, constructing a +strict pattern synonym is quite possible with an explicitly bidirectional +pattern synonym: :: + + pattern StrictJust a <- Just !a where + StrictJust !a = Just a + +Constructing an explicitly bidirectional pattern synonym also: + +- can create different data constructors from the underlying data type, + not just the one appearing in the pattern match; + +- can call any functions or conditional logic, especially validation, + of course providing it constructs a result of the right type; + +- can use guards on the lhs of the ``=``; + +- can have multiple equations. + +For example: :: + + data PosNeg = Pos Int | Neg Int + pattern Smarter{ nonneg } <- Pos nonneg where + Smarter x = if x >= 0 then (Pos x) else (Neg x) + +Or using guards: :: + + pattern Smarter{ nonneg } <- Pos nonneg where + Smarter x | x >= 0 = (Pos x) + | otherwise = (Neg x) + +There is an extensive Haskell folk art of `smart constructors +<https://wiki.haskell.org/Smart_constructor>`_, +essentially functions that wrap validation around a constructor, +and avoid exposing its representation. +The downside is that the underlying constructor can't be used as a matcher. +Pattern synonyms can be used as genuinely smart constructors, for both validation and matching. + The table below summarises where each kind of pattern synonym can be used. +---------------+----------------+---------------+---------------------------+ @@ -4888,7 +5551,7 @@ the syntax for bidirectional pattern synonyms is: :: and the syntax for explicitly bidirectional pattern synonyms is: :: pattern pat_lhs <- pat where - pat_lhs = expr + pat_lhs = expr -- lhs restricted, see below We can define either prefix, infix or record pattern synonyms by modifying the form of `pat_lhs`. The syntax for these is as follows: @@ -4902,6 +5565,9 @@ Infix ``arg1 `Name` arg2`` Record ``Name{arg1,arg2,...,argn}`` ======= ============================ +The `pat_lhs` for explicitly bidirectional construction cannot use Record syntax. +(Because the rhs *expr* might be constructing different data constructors.) +It can use guards with multiple equations. Pattern synonym declarations can only occur in the top level of a module. In particular, they are not allowed as local definitions. @@ -5036,6 +5702,8 @@ Note also the following points P :: () => CProv => t1 -> t2 -> .. -> tN -> t +- The GHCi :ghci-cmd:`:info` command shows pattern types in this format. + - You may specify an explicit *pattern signature*, as we did for ``ExNumPat`` above, to specify the type of a pattern, just as you can for a function. As usual, the type signature can be less polymorphic @@ -5052,7 +5720,21 @@ Note also the following points pattern Left' x = Left x pattern Right' x = Right x -- The GHCi :ghci-cmd:`:info` command shows pattern types in this format. +- The rules for lexically-scoped type variables (see + :ref:`scoped-type-variables`) apply to pattern-synonym signatures. + As those rules specify, only the type variables from an explicit, + syntactically-visible outer `forall` (the universals) scope over + the definition of the pattern synonym; the existentials, bound by + the inner forall, do not. For example :: + + data T a where + MkT :: Bool -> b -> (b->Int) -> a -> T a + + pattern P :: forall a. forall b. b -> (b->Int) -> a -> T a + pattern P x y v <- MkT True x y (v::a) + + Here the universal type variable `a` scopes over the definition of `P`, + but the existential `b` does not. (c.f. discussion on Trac #14998.) - For a bidirectional pattern synonym, a use of the pattern synonym as an expression has the type @@ -5113,6 +5795,24 @@ 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. + +More precisely, the semantics of pattern matching is given in +`Section 3.17 of the Haskell 2010 report <https://www.haskell.org/onlinereport/haskell2010/haskellch3.html#x8-580003.17>`__. To the informal semantics in Section 3.17.2 we add this extra rule: + +* If the pattern is a constructor pattern ``(P p1 ... pn)``, where ``P`` is + a pattern synonym defined by ``P x1 ... xn = p`` or ``P x1 ... xn <- p``, then: + + (a) Match the value ``v`` against ``p``. If this match fails or diverges, + so does the whole (pattern synonym) match. Otherwise the match + against ``p`` must bind the variables ``x1 ... xn``; let them be bound to values ``v1 ... vn``. + + (b) Match ``v1`` against ``p1``, ``v2`` against ``p2`` and so on. + If any of these matches fail or diverge, so does the whole match. + + (c) If all the matches against the ``pi`` succeed, the match succeeds, + binding the variables bound by the ``pi`` . (The ``xi`` are not + bound; they remain local to the pattern synonym declaration.) + For example, in the following program, ``f`` and ``f'`` are equivalent: :: pattern Pair x y <- [x, y] @@ -5155,14 +5855,17 @@ space <http://research.microsoft.com/~simonpj/Papers/type-class-design-space/>`_ Multi-parameter type classes ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.. ghc-flag:: -XMultiParamTypeClasses +.. extension:: MultiParamTypeClasses + :shortdesc: Enable multi parameter type classes. + Implied by :extension:`FunctionalDependencies`. - :implies: :ghc-flag:`-XConstrainedClassMethods` + :implies: :extension:`ConstrainedClassMethods` + :since: 6.8.1 Allow the definition of typeclasses with more than one parameter. -Multi-parameter type classes are permitted, with flag -:ghc-flag:`-XMultiParamTypeClasses`. For example: :: +Multi-parameter type classes are permitted, with extension +:extension:`MultiParamTypeClasses`. For example: :: class Collection c a where union :: c a -> c a -> c a @@ -5173,13 +5876,17 @@ Multi-parameter type classes are permitted, with flag The superclasses of a class declaration ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.. ghc-flag:: -XFlexibleContexts +.. extension:: FlexibleContexts + :shortdesc: Enable flexible contexts. Implied by + :extension:`ImplicitParams`. + + :since: 6.8.1 Allow the use of complex constraints in class declaration contexts. In Haskell 98 the context of a class declaration (which introduces superclasses) must be simple; that is, each predicate must consist of a -class applied to type variables. The flag :ghc-flag:`-XFlexibleContexts` +class applied to type variables. The extension :extension:`FlexibleContexts` (: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: :: @@ -5223,7 +5930,10 @@ context. Constrained class method types ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.. ghc-flag:: -XConstrainedClassMethods +.. extension:: ConstrainedClassMethods + :shortdesc: Enable constrained class methods. + + :since: 6.8.1 Allows the definition of further constraints on individual class methods. @@ -5254,18 +5964,19 @@ this case ``a``). More precisely, a constraint in a class method signature is r GHC lifts this restriction with language extension -:ghc-flag:`-XConstrainedClassMethods`. The restriction is a pretty stupid one in -the first place, so :ghc-flag:`-XConstrainedClassMethods` is implied by -:ghc-flag:`-XMultiParamTypeClasses`. +:extension:`ConstrainedClassMethods`. The restriction is a pretty stupid one in +the first place, so :extension:`ConstrainedClassMethods` is implied by +:extension:`MultiParamTypeClasses`. .. _class-default-signatures: Default method signatures ~~~~~~~~~~~~~~~~~~~~~~~~~ -.. ghc-flag:: -XDefaultSignatures +.. extension:: DefaultSignatures + :shortdesc: Enable default signatures. - :since: 7.2 + :since: 7.2.1 Allows the definition of default method signatures in class definitions. @@ -5278,7 +5989,7 @@ 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 :ghc-flag:`-XDefaultSignatures`. For +to the default method using the extension :extension:`DefaultSignatures`. 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: :: @@ -5310,7 +6021,7 @@ Then a default method for ``bar`` must take on the form: :: ``C`` is allowed to be different from ``C'``, but the right-hand sides of the type signatures must coincide. We require this because when you declare an -empty instance for a class that uses :ghc-flag:`-XDefaultSignatures`, GHC +empty instance for a class that uses :extension:`DefaultSignatures`, GHC implicitly fills in the default implementation like this: :: instance Foo Int where @@ -5356,17 +6067,19 @@ We use default signatures to simplify generic programming in GHC Nullary type classes ~~~~~~~~~~~~~~~~~~~~ -.. ghc-flag:: -XNullaryTypeClasses +.. extension:: NullaryTypeClasses + :shortdesc: Deprecated, does nothing. nullary (no parameter) type + classes are now enabled using :extension:`MultiParamTypeClasses`. :since: 7.8.1 - Allows the use definition of type classes with no parameters. This flag - has been replaced by :ghc-flag:`-XMultiParamTypeClasses`. + Allows the use definition of type classes with no parameters. This extension + has been replaced by :extension:`MultiParamTypeClasses`. 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 +:extension:`MultiParamTypeClasses`; historically, they were enabled with the +(now deprecated) :extension:`NullaryTypeClasses`. 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 @@ -5392,9 +6105,12 @@ dependence with: :: Functional dependencies ----------------------- -.. ghc-flag:: -XFunctionalDependencies +.. extension:: FunctionalDependencies + :shortdesc: Enable functional dependencies. + Implies :extension:`MultiParamTypeClasses`. - :implies: :ghc-flag:`-XMultiParamTypeClasses` + :implies: :extension:`MultiParamTypeClasses` + :since: 6.8.1 Allow use of functional dependencies in class declarations. @@ -5408,12 +6124,12 @@ of a class declaration; e.g. :: class Foo a b c | a b -> c where ... -There should be more documentation, but there isn't (yet). Yell if you -need it. +More documentation can be found in the `Haskell Wiki +<https://wiki.haskell.org/Functional_dependencies>`_. .. [Jones2000] "`Type Classes with Functional - Dependencies <http://citeseer.ist.psu.edu/jones00type.html>`__", + Dependencies <https://web.cecs.pdx.edu/~mpj/pubs/fundeps.html>`__", Mark P. Jones, In *Proceedings of the 9th European Symposium on Programming*, ESOP 2000, Berlin, Germany, March 2000, Springer-Verlag LNCS 1782, . @@ -5561,12 +6277,17 @@ information can be seen both as a generalisation of the proposal for Odersky, or as a special case of Mark Jones's later framework for "improvement" of qualified types. The underlying ideas are also discussed in a more theoretical and abstract setting in a manuscript -[implparam], where they are identified as one point in a general design +[Jones1999]_, 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: :: class C a b where ... +.. [Jones1999] + "`Exploring the Design Space for Type-based Implicit Parameterization + <https://web.cecs.pdx.edu/~mpj/pubs/fdtr.html>`__", Mark P. Jones, Oregon + Graduate Institute of Science & Technology, Technical Report, July 1999. + 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 @@ -5576,7 +6297,7 @@ about dependencies between parameters, as in the following examples: :: class E a b | a -> b, b -> a where ... The notation ``a -> b`` used here between the ``|`` and ``where`` symbols — -not to be confused with a function type — indicates that the a +not to be confused with a function type — indicates that the ``a`` parameter uniquely determines the ``b`` parameter, and might be read as "``a`` determines ``b``." Thus ``D`` is not just a relation, but actually a (partial) function. Similarly, from the two dependencies that are included in the @@ -5641,9 +6362,9 @@ original definition of ``Collects`` with a simple dependency: :: The dependency ``ce -> e`` here specifies that the type ``e`` of elements is uniquely determined by the type of the collection ``ce``. Note that both -parameters of Collects are of kind ``*``; there are no constructor classes -here. Note too that all of the instances of ``Collects`` that we gave -earlier can be used together with this new definition. +parameters of Collects are of kind ``Type``; there are no constructor classes +here. Note too that all of the instances of ``Collects`` that we gave earlier +can be used together with this new definition. What about the ambiguity problems that we encountered with the original definition? The empty function still has type ``Collects e ce => ce``, but @@ -5730,13 +6451,21 @@ resolution rules. Relaxed rules for the instance head ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.. ghc-flag:: -XTypeSynonymInstances +.. extension:: TypeSynonymInstances + :shortdesc: Enable type synonyms in instance heads. + Implied by :extension:`FlexibleInstances`. + + :since: 6.8.1 Allow definition of type class instances for type synonyms. -.. ghc-flag:: -XFlexibleInstances +.. extension:: FlexibleInstances + :shortdesc: Enable flexible instances. + Implies :extension:`TypeSynonymInstances`. + Implied by :extension:`ImplicitParams`. - :implies: :ghc-flag:`-XTypeSynonymInstances` + :implies: :extension:`TypeSynonymInstances` + :since: 6.8.1 Allow definition of type class instances with arbitrary nested types in the instance head. @@ -5751,7 +6480,7 @@ the moment). GHC relaxes this rule in two ways: -- With the :ghc-flag:`-XTypeSynonymInstances` flag, instance heads may use type +- With the :extension:`TypeSynonymInstances` extension, instance heads may use type synonyms. As always, using a type synonym is just shorthand for writing the RHS of the type synonym definition. For example: :: @@ -5767,7 +6496,7 @@ GHC relaxes this rule in two ways: instance Monad Point where ... -- The :ghc-flag:`-XFlexibleInstances` flag allows the head of the instance +- The :extension:`FlexibleInstances` extension allows the head of the instance declaration to mention arbitrary nested types. For example, this becomes a legal instance declaration :: @@ -5775,8 +6504,8 @@ GHC relaxes this rule in two ways: See also the `rules on overlap <#instance-overlap>`__. - The :ghc-flag:`-XFlexibleInstances` flag implies - :ghc-flag:`-XTypeSynonymInstances`. + The :extension:`FlexibleInstances` extension implies + :extension:`TypeSynonymInstances`. However, the instance declaration must still conform to the rules for instance termination: see :ref:`instance-termination`. @@ -5790,14 +6519,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 :ghc-flag:`-XFlexibleContexts` flag relaxes this rule, as well as relaxing +The :extension:`FlexibleContexts` extension relaxes this rule, as well as relaxing the corresponding rule for type signatures (see -:ref:`flexible-contexts`). Specifically, :ghc-flag:`-XFlexibleContexts`, allows +:ref:`flexible-contexts`). Specifically, :extension:`FlexibleContexts`, 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 :ghc-flag:`-XTypeFamilies` or :ghc-flag:`-XGADTs`. +Notice that the extension does not affect equality constraints in an instance +context; they are permitted by :extension:`TypeFamilies` or :extension:`GADTs`. However, the instance declaration must still conform to the rules for instance termination: see :ref:`instance-termination`. @@ -5807,14 +6536,17 @@ instance termination: see :ref:`instance-termination`. Instance termination rules ~~~~~~~~~~~~~~~~~~~~~~~~~~ -.. ghc-flag:: -XUndecidableInstances +.. extension:: UndecidableInstances + :shortdesc: Enable undecidable instances. + + :since: 6.8.1 Permit definition of instances which may lead to type-checker non-termination. -Regardless of :ghc-flag:`-XFlexibleInstances` and :ghc-flag:`-XFlexibleContexts`, +Regardless of :extension:`FlexibleInstances` and :extension:`FlexibleContexts`, instance declarations must conform to some rules that ensure that instance resolution will terminate. The restrictions can be lifted with -:ghc-flag:`-XUndecidableInstances` (see :ref:`undecidable-instances`). +:extension:`UndecidableInstances` (see :ref:`undecidable-instances`). The rules are these: @@ -5910,7 +6642,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 :ghc-flag:`-XUndecidableInstances`, both the Paterson +you use the experimental extension :extension:`UndecidableInstances`, 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 @@ -5991,7 +6723,7 @@ indeed the (somewhat strange) definition: makes instance inference go into a loop, because it requires the constraint ``(Mul a [b] b)``. -The :ghc-flag:`-XUndecidableInstances` flag is also used to lift some of the +The :extension:`UndecidableInstances` extension is also used to lift some of the restrictions imposed on type family instances. See :ref:`type-family-decidability`. @@ -6000,15 +6732,24 @@ restrictions imposed on type family instances. See Overlapping instances ~~~~~~~~~~~~~~~~~~~~~ -.. ghc-flag:: -XOverlappingInstances - -XIncoherentInstances +.. extension:: OverlappingInstances + :shortdesc: Enable overlapping instances. + + Deprecated extension to weaken checks intended to ensure instance resolution + termination. + +.. extension:: IncoherentInstances + :shortdesc: Enable incoherent instances. + Implies :extension:`OverlappingInstances`. + + :since: 6.8.1 - Deprecated flags to weaken checks intended to ensure instance resolution + Deprecated extension 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 +resolve a type-class constraint*. GHC also provides a way to loosen the instance resolution, by allowing more than one instance to match, *provided there is a most specific one*. Moreover, it can be loosened further, by allowing more than one instance to match irrespective of @@ -6021,8 +6762,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: :ghc-flag:`-XOverlappingInstances` and -:ghc-flag:`-XIncoherentInstances`. These flags are now +extension flags: :extension:`OverlappingInstances` and +:extension:`IncoherentInstances`. These extensions are now deprecated (since GHC 7.10) in favour of the fine-grained per-instance pragmas. @@ -6032,16 +6773,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 :ghc-flag:`-XIncoherentInstances`. + with :extension:`IncoherentInstances`. - 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 :ghc-flag:`-XOverlappingInstances`; or if the + in a module compiled with :extension:`OverlappingInstances`; 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 :ghc-flag:`-XOverlappingInstances`; or if the + in a module compiled with :extension:`OverlappingInstances`; or if the instance is incoherent. Now suppose that, in some client module, we are searching for an @@ -6108,7 +6849,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 :ghc-flag:`-XIncoherentInstances` is enabled, in which case it would be +unless :extension:`IncoherentInstances` 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 @@ -6127,7 +6868,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 :ghc-flag:`-XIncoherentInstances` when compiling +If, however, you enable the extension :extension:`IncoherentInstances` when compiling the module that contains (D), GHC will instead pick (C), without complaining about the problem of subsequent instantiations. @@ -6143,7 +6884,7 @@ the type :: That postpones the question of which instance to pick to the call site for ``f`` by which time more is known about the type ``b``. You can write this type signature yourself if you use the -:ghc-flag:`-XFlexibleContexts` flag. +:extension:`FlexibleContexts` extension. Exactly the same situation can arise in instance declarations themselves. Suppose we have :: @@ -6163,12 +6904,12 @@ declaration, thus: :: instance C Int [b] => Foo [b] where f x = ... -(You need :ghc-flag:`-XFlexibleInstances` to do this.) +(You need :extension:`FlexibleInstances` 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 :ghc-flag:`-XIncoherentInstances`. + different parts of the program) even without :extension:`IncoherentInstances`. Consider: :: {-# LANGUAGE OverlappingInstances #-} @@ -6217,7 +6958,8 @@ declaration, thus: :: Instance signatures: type signatures in instance declarations ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.. ghc-flag:: -XInstanceSigs +.. extension:: InstanceSigs + :shortdesc: Enable instance signatures. :since: 7.6.1 @@ -6225,7 +6967,7 @@ Instance signatures: type signatures in instance declarations 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 -:ghc-flag:`-XInstanceSigs` allows you to do so. For example: :: +:extension:`InstanceSigs` allows you to do so. For example: :: data T a = MkT a a instance Eq a => Eq (T a) where @@ -6264,7 +7006,7 @@ Some details xs :: [b] xs = [x,x,x] - Provided that you also specify :ghc-flag:`-XScopedTypeVariables` + Provided that you also specify :extension:`ScopedTypeVariables` (:ref:`scoped-type-variables`), the ``forall b`` scopes over the definition of ``foo``, and in particular over the type signature for ``xs``. @@ -6274,14 +7016,17 @@ Some details Overloaded string literals -------------------------- -.. ghc-flag:: -XOverloadedStrings +.. extension:: OverloadedStrings + :shortdesc: Enable overloaded string literals. + + :since: 6.8.1 Enable overloaded string literals (e.g. string literals desugared via the ``IsString`` class). GHC supports *overloaded string literals*. Normally a string literal has type ``String``, but with overloaded string literals enabled (with -:ghc-flag:`-XOverloadedStrings`) a string literal has type +:extension:`OverloadedStrings`) a string literal has type ``(IsString a) => a``. This means that the usual string syntax can be used, e.g., for @@ -6304,11 +7049,11 @@ usual: :: The class ``IsString`` is not in scope by default. If you want to mention it explicitly (for example, to give an instance declaration for -it), you can import it from module ``GHC.Exts``. +it), you can import it from module ``Data.String``. 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 :ghc-flag:`-XOverloadedStrings` is +extended to cover string literals, when :extension:`OverloadedStrings` is specified. Specifically: - Each type in a ``default`` declaration must be an instance of ``Num`` @@ -6332,7 +7077,7 @@ A small example: module Main where - import GHC.Exts( IsString(..) ) + import Data.String( IsString(..) ) newtype MyString = MyString String deriving (Eq, Show) instance IsString MyString where @@ -6354,7 +7099,8 @@ since it gets translated into an equality comparison. Overloaded labels ----------------- -.. ghc-flag:: -XOverloadedLabels +.. extension:: OverloadedLabels + :shortdesc: Enable overloaded labels. :since: 8.0.1 @@ -6362,7 +7108,7 @@ Overloaded labels GHC supports *overloaded labels*, a form of identifier whose interpretation may depend both on its type and on its literal text. When the -:ghc-flag:`-XOverloadedLabels` extension is enabled, an overloaded label can written +:extension:`OverloadedLabels` extension is enabled, an overloaded label can be written with a prefix hash, for example ``#foo``. The type of this expression is ``IsLabel "foo" a => a``. @@ -6393,22 +7139,22 @@ The intention is for ``IsLabel`` to be used to support overloaded record fields and perhaps anonymous records. Thus, it may be given instances for base datatypes (in particular ``(->)``) in the future. -If :ghc-flag:`-XRebindableSyntax` is enabled, overloaded +If :extension:`RebindableSyntax` is enabled, overloaded labels will be desugared using whatever ``fromLabel`` function is in scope, rather than always using ``GHC.OverloadedLabels.fromLabel``. When writing an overloaded label, there must be no space between the hash sign -and the following identifier. The :ghc-flag:`-XMagicHash` extension makes use -of postfix hash signs; if :ghc-flag:`-XOverloadedLabels` and -:ghc-flag:`-XMagicHash` are both enabled then ``x#y`` means ``x# y``, but if -only :ghc-flag:`-XOverloadedLabels` is enabled then it means ``x #y``. The -:ghc-flag:`-XUnboxedTuples` extension makes ``(#`` a single lexeme, so when -:ghc-flag:`-XUnboxedTuples` is enabled you must write a space between an opening +and the following identifier. The :extension:`MagicHash` extension makes use +of postfix hash signs; if :extension:`OverloadedLabels` and +:extension:`MagicHash` are both enabled then ``x#y`` means ``x# y``, but if +only :extension:`OverloadedLabels` is enabled then it means ``x #y``. The +:extension:`UnboxedTuples` extension makes ``(#`` a single lexeme, so when +:extension:`UnboxedTuples` is enabled you must write a space between an opening parenthesis and an overloaded label. To avoid confusion, you are strongly encouraged to put a space before the hash when using -:ghc-flag:`-XOverloadedLabels`. +:extension:`OverloadedLabels`. -When using :ghc-flag:`-XOverloadedLabels` (or other extensions that make use of +When using :extension:`OverloadedLabels` (or other extensions that make use of hash signs) in a ``.hsc`` file (see :ref:`hsc2hs`), the hash signs must be doubled (write ``##foo`` instead of ``#foo``) to avoid them being treated as ``hsc2hs`` directives. @@ -6446,7 +7192,8 @@ showing how an overloaded label can be used as a record selector: Overloaded lists ---------------- -.. ghc-flag:: -XOverloadedLists +.. extension:: OverloadedLists + :shortdesc: Enable overloaded lists. :since: 7.8.1 @@ -6579,11 +7326,11 @@ several example instances: Rebindable syntax ~~~~~~~~~~~~~~~~~ -When desugaring list notation with :ghc-flag:`-XOverloadedLists` GHC uses the +When desugaring list notation with :extension:`OverloadedLists` 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 :ghc-flag:`-XRebindableSyntax`, then GHC instead uses +However if you use :extension:`RebindableSyntax`, 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`. @@ -6613,14 +7360,16 @@ representation). Undecidable (or recursive) superclasses --------------------------------------- -.. ghc-flag:: -XUndecidableSuperClasses +.. extension:: UndecidableSuperClasses + :shortdesc: Allow all superclass constraints, including those that may + result in non-termination of the typechecker. :since: 8.0.1 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 +The language extension :extension:`UndecidableSuperClasses` allows much more flexible constraints in superclasses. A class cannot generally have itself as a superclass. So this is illegal :: @@ -6656,12 +7405,12 @@ example (Trac #10318) :: Fractional (Frac a), IntegralDomain (Frac a)) => IntegralDomain a where - type Frac a :: * + type Frac a :: Type Here the superclass cycle does terminate but it's not entirely straightforward to see that it does. -With the language extension :ghc-flag:`-XUndecidableSuperClasses` GHC lifts all restrictions +With the language extension :extension:`UndecidableSuperClasses` GHC lifts all restrictions on superclass constraints. If there really *is* a loop, GHC will only expand it to finite depth. @@ -6671,10 +7420,14 @@ expand it to finite depth. Type families ============= -.. ghc-flag:: -XTypeFamilies +.. extension:: TypeFamilies + :shortdesc: Enable type families. + Implies :extension:`ExplicitNamespaces`, :extension:`KindSignatures`, + and :extension:`MonoLocalBinds`. - :implies: :ghc-flag:`-XMonoLocalBinds`, :ghc-flag:`-XKindSignatures`, - :ghc-flag:`-XExplicitNamespaces` + :implies: :extension:`MonoLocalBinds`, :extension:`KindSignatures`, + :extension:`ExplicitNamespaces` + :since: 6.8.1 Allow use and definition of indexed type and data families. @@ -6707,7 +7460,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 :ghc-flag:`-XTypeFamilies`. Additional +Type families are enabled by the language extension :extension:`TypeFamilies`. 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>`__. @@ -6719,14 +7472,14 @@ families <http://www.haskell.org/haskellwiki/GHC/Indexed_types>`__. and S. Marlow. In Proceedings of “The 32nd Annual ACM SIGPLAN-SIGACT Symposium on Principles of Programming Languages (POPL'05)”, pages 1-13, ACM - Press, 2005) + Press, 2005. .. [AssocTypeSyn2005] “`Type Associated Type Synonyms <http://www.cse.unsw.edu.au/~chak/papers/CKP05.html>`__\ ”. M. Chakravarty, G. Keller, and S. Peyton Jones. In Proceedings of “The Tenth ACM SIGPLAN International Conference on Functional Programming”, - ACM Press, pages 241-253, 2005). + ACM Press, pages 241-253, 2005. .. [TypeFamilies2008] “\ `Type Checking with Open Type @@ -6758,11 +7511,11 @@ Data family declarations Indexed data families are introduced by a signature, such as :: - data family GMap k :: * -> * + data family GMap k :: Type -> Type 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 ``Type`` if omitted. An example is :: data family Array e @@ -6770,7 +7523,12 @@ 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 :: - data family Array :: * -> * + data family Array :: Type -> Type + +Unlike with ordinary data definitions, the result kind of a data family +does not need to be ``Type``: it can alternatively be a kind variable +(with :extension:`PolyKinds`). Data instances' kinds must end in +``Type``, however. .. _data-instance-declarations: @@ -6804,7 +7562,7 @@ 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 :ghc-flag:`-XPartialTypeSignatures` have any effect. +the extension :extension:`PartialTypeSignatures` have any effect. Data and newtype instance declarations are only permitted when an appropriate family declaration is in scope - just as a class instance @@ -6897,35 +7655,36 @@ Type family declarations Open indexed type families are introduced by a signature, such as :: - type family Elem c :: * + type family Elem c :: Type 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 ``Type`` if omitted. An example is :: type family Elem c Parameters can also be given explicit kind signatures if needed. We call the number of parameters in a type family declaration, the family's arity, and all applications of a type family must be fully saturated -with respect to to that arity. This requirement is unlike ordinary type synonyms +with respect to that arity. This requirement is unlike ordinary type synonyms and it implies that the kind of a type family is not sufficient to determine a family's arity, and hence in general, also insufficient to determine whether a type family application is well formed. As an example, consider the following declaration: :: - type family F a b :: * -> * -- F's arity is 2, - -- although its overall kind is * -> * -> * -> * + type family F a b :: Type -> Type + -- F's arity is 2, + -- although its overall kind is Type -> Type -> Type -> Type Given this declaration the following are examples of well-formed and malformed types: :: - F Char [Int] -- OK! Kind: * -> * - F Char [Int] Bool -- OK! Kind: * + F Char [Int] -- OK! Kind: Type -> Type + F Char [Int] Bool -- OK! Kind: Type F IO Bool -- WRONG: kind mismatch in the first argument F Bool -- WRONG: unsaturated application -The result kind annotation is optional and defaults to ``*`` (like +The result kind annotation is optional and defaults to ``Type`` (like argument kinds) if omitted. Polykinded type families can be declared using a parameter in the kind annotation: :: @@ -7009,7 +7768,7 @@ Type family examples Here are some examples of admissible and illegal type instances: :: - type family F a :: * + type family F a :: Type type instance F [Int] = Int -- OK! type instance F String = Char -- OK! type instance F (F a) = a -- WRONG: type parameter mentions a type family @@ -7024,7 +7783,7 @@ Here are some examples of admissible and illegal type instances: :: type instance H Char = Char -- WRONG: cannot have instances of closed family type family K a where -- OK! - type family G a b :: * -> * + type family G a b :: Type -> Type type instance G Int = (,) -- WRONG: must be two type parameters type instance G Int Char Float = Double -- WRONG: must be two type parameters @@ -7075,8 +7834,8 @@ like types. For example, the following is accepted: :: type instance J Int = Bool type instance J Int = Maybe -These instances are compatible because they differ in their implicit -kind parameter; the first uses ``*`` while the second uses ``* -> *``. +These instances are compatible because they differ in their implicit kind +parameter; the first uses ``Type`` while the second uses ``Type -> Type``. The definition for "compatible" uses a notion of "apart", whose definition in turn relies on type family reduction. This condition of @@ -7122,7 +7881,7 @@ However see :ref:`ghci-decls` for the overlap rules in GHCi. Decidability of type synonym instances ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.. ghc-flag:: -XUndecidableInstances +.. extension:: UndecidableInstances :noindex: Relax restrictions on the decidability of type synonym family instances. @@ -7155,7 +7914,7 @@ 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 :ghc-flag:`-XUndecidableInstances` is passed to the compiler, the +If the option :extension:`UndecidableInstances` 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. @@ -7168,11 +7927,11 @@ When the name of a type argument of a data or type instance declaration doesn't matter, it can be replaced with an underscore (``_``). This is the same as writing a type variable with a unique name. :: - data family F a b :: * + data family F a b :: Type data instance F Int _ = Int -- Equivalent to data instance F Int b = Int - type family T a :: * + type family T a :: Type type instance T (a,_) = a -- Equivalent to type instance T (a,b) = a @@ -7199,11 +7958,11 @@ A data or type synonym family can be declared as part of a type class, thus: :: class GMapKey k where - data GMap k :: * -> * + data GMap k :: Type -> Type ... class Collects ce where - type Elem ce :: * + type Elem ce :: Type ... When doing so, we (optionally) may drop the "``family``" keyword. @@ -7215,7 +7974,7 @@ may be omitted and they may be in an order other than in the class head. Hence, the following contrived example is admissible: :: class C a b c where - type T c a x :: * + type T c a x :: Type Here ``c`` and ``a`` are class parameters, but the type is also indexed on a third parameter ``x``. @@ -7237,12 +7996,12 @@ keyword in the family instance: :: type Elem [e] = e ... -The data or type family instance for an assocated type must follow +The data or type family instance for an associated type must follow the rule that the type indexes corresponding to class parameters must have precisely the same as type given in the instance head. For example: :: class Collects ce where - type Elem ce :: * + type Elem ce :: Type instance Eq (Elem [e]) => Collects [e] where -- Choose one of the following alternatives: @@ -7257,8 +8016,23 @@ Note the following points: instance declarations of the class in which the family was declared, just as with the equations of the methods of a class. -- The variables on the right hand side of the type family equation - must, as usual, be bound on the left hand side. +- The type variables on the right hand side of the type family equation + must, as usual, be explicitly bound by the left hand side. This restriction + is relaxed for *kind* variables, however, as the right hand side is allowed + to mention kind variables that are implicitly bound. For example, these are + legitimate: :: + + data family Nat :: k -> k -> Type + -- k is implicitly bound by an invisible kind pattern + newtype instance Nat :: (k -> Type) -> (k -> Type) -> Type where + Nat :: (forall xx. f xx -> g xx) -> Nat f g + + class Funct f where + type Codomain f :: Type + instance Funct ('KProxy :: KProxy o) where + -- o is implicitly bound by the kind signature + -- of the LHS type pattern ('KProxy) + type Codomain 'KProxy = NatTr (Proxy :: o -> Type) - The instance for an associated type can be omitted in class instances. In that case, unless there is a default instance (see @@ -7279,7 +8053,7 @@ Note the following points: parameter is ``[v]``, and one for which it is ``Int``. Since you cannot give any *subsequent* instances for ``(GMap Flob ...)``, this facility is most useful when the free indexed parameter is of a kind - with a finite number of alternatives (unlike ``*``). + with a finite number of alternatives (unlike ``Type``). .. _assoc-decl-defs: @@ -7313,16 +8087,19 @@ Note the following points: - The default declaration must mention only type *variables* on the left hand side, and the right hand side must mention only type - variables bound on the left hand side. However, unlike the associated - type family declaration itself, the type variables of the default - instance are independent of those of the parent class. + variables that are explicitly bound on the left hand side. This restriction + is relaxed for *kind* variables, however, as the right hand side is allowed + to mention kind variables that are implicitly bound on the left hand side. + +- Unlike the associated type family declaration itself, the type variables of + the default instance are independent of those of the parent class. Here are some examples: :: - class C a where - type F1 a :: * + class C (a :: Type) where + type F1 a :: Type type instance F1 a = [a] -- OK type instance F1 a = a->a -- BAD; only one default instance is allowed @@ -7336,6 +8113,21 @@ Here are some examples: type F4 a type F4 b = a -- BAD; 'a' is not in scope in the RHS + type F5 a :: [k] + type F5 a = ('[] :: [x]) -- OK; the kind variable x is implicitly + bound by an invisible kind pattern + on the LHS + + type F6 a + type F6 a = + Proxy ('[] :: [x]) -- BAD; the kind variable x is not bound, + even by an invisible kind pattern + + type F7 (x :: a) :: [a] + type F7 x = ('[] :: [a]) -- OK; the kind variable a is implicitly + bound by the kind signature of the + LHS type pattern + .. _scoping-class-params: Scoping of class parameters @@ -7358,6 +8150,33 @@ Here, the right-hand side of the data instance mentions the type variable ``d`` that does not occur in its left-hand side. We cannot admit such data instances as they would compromise type safety. +Bear in mind that it is also possible for the *right*-hand side of an +associated family instance to contain *kind* parameters (by using the +:extension:`PolyKinds` extension). For instance, this class and instance are +perfectly admissible: :: + + class C k where + type T :: k + + instance C (Maybe a) where + type T = (Nothing :: Maybe a) + +Here, although the right-hand side ``(Nothing :: Maybe a)`` mentions a kind +variable ``a`` which does not occur on the left-hand side, this is acceptable, +because ``a`` is *implicitly* bound by ``T``'s kind pattern. + +A kind variable can also be bound implicitly in a LHS type pattern, as in this +example: :: + + class C a where + type T (x :: a) :: [a] + + instance C (Maybe a) where + type T x = ('[] :: [Maybe a]) + +In ``('[] :: [Maybe a])``, the kind variable ``a`` is implicitly bound by the +kind signature of the LHS type pattern ``x``. + Instance contexts and associated type and data instances ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ @@ -7415,7 +8234,7 @@ Recall our running ``GMapKey`` class example: :: class GMapKey k where - data GMap k :: * -> * + data GMap k :: Type -> Type insert :: GMap k v -> k -> v -> GMap k v lookup :: GMap k v -> k -> Maybe v empty :: GMap k v @@ -7562,9 +8381,11 @@ which implicitly defines an instance of the form :: Injective type families ----------------------- -.. ghc-flag:: -XTypeFamilyDependencies +.. extension:: TypeFamilyDependencies + :shortdesc: Enable injective type families. + Implies :extension:`TypeFamilies`. - :implies: :ghc-flag:`-XTypeFamilies` + :implies: :extension:`TypeFamilies` :since: 8.0.1 Allow functional dependency annotations on type families. This allows one to @@ -7690,7 +8511,8 @@ family applications as possibly unifying with anything. Datatype promotion ================== -.. ghc-flag:: -XDataKinds +.. extension:: DataKinds + :shortdesc: Enable datatype promotion. :since: 7.4.1 @@ -7698,7 +8520,7 @@ Datatype promotion This section describes *data type promotion*, an extension to the kind system that complements kind polymorphism. It is enabled by -:ghc-flag:`-XDataKinds`, and described in more detail in the paper `Giving +:extension:`DataKinds`, and described in more detail in the paper `Giving Haskell a Promotion <http://dreixel.net/research/pdf/ghp.pdf>`__, which appeared at TLDI 2012. @@ -7708,7 +8530,7 @@ Motivation Standard Haskell has a rich type language. Types classify terms and serve to avoid many common programming mistakes. The kind language, however, is relatively simple, distinguishing only regular types (kind -``*``) and type constructors (e.g. kind ``* -> * -> *``). +``Type``) and type constructors (e.g. kind ``Type -> Type -> Type``). 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 @@ -7718,19 +8540,19 @@ numbers, and length-indexed vectors: :: data Ze data Su n - data Vec :: * -> * -> * where + data Vec :: Type -> Type -> Type where Nil :: Vec a Ze Cons :: a -> Vec a n -> Vec a (Su n) -The kind of ``Vec`` is ``* -> * -> *``. This means that, e.g., +The kind of ``Vec`` is ``Type -> Type -> Type``. This means that, e.g., ``Vec Int Char`` is a well-kinded type, even though this is not what we intend when defining length-indexed vectors. -With :ghc-flag:`-XDataKinds`, the example above can then be rewritten to: :: +With :extension:`DataKinds`, the example above can then be rewritten to: :: data Nat = Ze | Su Nat - data Vec :: * -> Nat -> * where + data Vec :: Type -> Nat -> Type where Nil :: Vec a 'Ze Cons :: a -> Vec a n -> Vec a ('Su n) @@ -7740,7 +8562,7 @@ ill-kinded, and GHC will report an error. Overview -------- -With :ghc-flag:`-XDataKinds`, GHC automatically promotes every datatype +With :extension:`DataKinds`, GHC automatically promotes every datatype to be a kind and its (value) constructors to be type constructors. The following types :: @@ -7755,48 +8577,39 @@ following types :: give rise to the following kinds and type constructors (where promoted constructors are prefixed by a tick ``'``): :: - Nat :: * + Nat :: Type 'Zero :: Nat 'Succ :: Nat -> Nat - List :: * -> * + List :: Type -> Type 'Nil :: forall k. List k 'Cons :: forall k. k -> List k -> List k - Pair :: * -> * -> * + Pair :: Type -> Type -> Type 'Pair :: forall k1 k2. k1 -> k2 -> Pair k1 k2 - Sum :: * -> * -> * + Sum :: Type -> Type -> Type 'L :: k1 -> Sum k1 k2 'R :: k2 -> Sum k1 k2 -The following restrictions apply to promotion: - -- We promote ``data`` types and ``newtypes``; type synonyms and - type/data families are not promoted (:ref:`type-families`). - -- We only promote types whose kinds are of the form - ``* -> ... -> * -> *``. In particular, we do not promote - higher-kinded datatypes such as ``data Fix f = In (f (Fix f))``, or - datatypes whose kinds involve promoted types such as - ``Vec :: * -> Nat -> *``. +Virtually all data constructors, even those with rich kinds, can be promoted. +There are only a couple of exceptions to this rule: -- We do not promote data constructors that are kind polymorphic, - involve constraints, mention type or data families, or involve types - that are not promotable. +- Data family instance constructors cannot be promoted at the moment. GHC's + type theory just isn’t up to the task of promoting data families, which + requires full dependent types. -The flag :ghc-flag:`-XTypeInType` (which implies :ghc-flag:`-XDataKinds`) -relaxes some of these restrictions, allowing: +- Data constructors with contexts that contain non-equality constraints cannot + be promoted. For example: :: -- Promotion of type synonyms and type families, but not data families. - GHC's type theory just isn't up to the task of promoting data families, - which requires full dependent types. + data Foo :: Type -> Type where + MkFoo1 :: a ~ Int => Foo a -- promotable + MkFoo2 :: a ~~ Int => Foo a -- promotable + MkFoo3 :: Show a => Foo a -- not promotable -- All datatypes, even those with rich kinds, get promoted. For example: :: - - data Proxy a = Proxy - data App f a = MkApp (f a) -- App :: forall k. (k -> *) -> k -> * - x = Proxy :: Proxy ('MkApp ('Just 'True)) + ``MkFoo1`` and ``MkFoo2`` can be promoted, since their contexts + only involve equality-oriented constraints. However, ``MkFoo3``'s context + contains a non-equality constraint ``Show a``, and thus cannot be promoted. .. _promotion-syntax: @@ -7834,15 +8647,15 @@ promotion quote and the data constructor: :: Promoted list and tuple types ----------------------------- -With :ghc-flag:`-XDataKinds`, Haskell's list and tuple types are natively +With :extension:`DataKinds`, 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: :: - data HList :: [*] -> * where + data HList :: [Type] -> Type where HNil :: HList '[] HCons :: a -> HList t -> HList (a ': t) - data Tuple :: (*,*) -> * where + data Tuple :: (Type,Type) -> Type where Tuple :: a -> b -> Tuple '(a,b) foo0 :: HList '[] @@ -7861,8 +8674,8 @@ 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 ``(:')`` + The declaration for ``HCons`` also requires :extension:`TypeOperators` + because of infix type operator ``(':)`` .. _promotion-existentials: @@ -7873,7 +8686,7 @@ Promoting existential data constructors Note that we do promote existential data constructors that are otherwise suitable. For example, consider the following: :: - data Ex :: * where + data Ex :: Type where MkEx :: forall a. a -> Ex Both the type ``Ex`` and the data constructor ``MkEx`` get promoted, @@ -7892,7 +8705,7 @@ The return kind ``k`` is an implicit parameter to ``UnEx``. The elaborated definitions are as follows (where implicit parameters are denoted by braces): :: - type family UnEx {k :: *} (ex :: Ex) :: k + type family UnEx {k :: Type} (ex :: Ex) :: k type instance UnEx {k} (MkEx @k x) = x Thus, the instance triggers only when the implicit parameter to ``UnEx`` @@ -7905,21 +8718,23 @@ See also :ghc-ticket:`7347`. .. _type-in-type: .. _kind-polymorphism: -Kind polymorphism and Type-in-Type +Kind polymorphism ================================== -.. ghc-flag:: -XTypeInType +.. extension:: TypeInType + :shortdesc: Deprecated. Enable kind polymorphism and datatype promotion. - :implies: :ghc-flag:`-XPolyKinds`, :ghc-flag:`-XDataKinds`, :ghc-flag:`-XKindSignatures` + :implies: :extension:`PolyKinds`, :extension:`DataKinds`, :extension:`KindSignatures` :since: 8.0.1 - Allow kinds to be as intricate as types, allowing explicit quantification - over kind variables, higher-rank kinds, and the use of type synonyms and - families in kinds, among other features. + In the past this extension used to enable advanced type-level programming + techniques. Now it's a shorthand for a couple of other extensions. -.. ghc-flag:: -XPolyKinds +.. extension:: PolyKinds + :shortdesc: Enable kind polymorphism. + Implies :extension:`KindSignatures`. - :implies: :ghc-flag:`-XKindSignatures` + :implies: :extension:`KindSignatures` :since: 7.4.1 Allow kind polymorphic types. @@ -7930,31 +8745,6 @@ although it is a conservative extension beyond standard Haskell. The extensions above simply enable syntax and tweak the inference algorithm to allow users to take advantage of the extra expressiveness of GHC's kind system. -The difference between :ghc-flag:`-XTypeInType` and :ghc-flag:`-XPolyKinds` ---------------------------------------------------------------------------- - -It is natural to consider :ghc-flag:`-XTypeInType` as an extension of -:ghc-flag:`-XPolyKinds`. The latter simply enables fewer features of GHC's -rich kind system than does the former. The need for two separate extensions -stems from their history: :ghc-flag:`-XPolyKinds` was introduced for GHC 7.4, -when it was experimental and temperamental. The wrinkles were smoothed out for -GHC 7.6. :ghc-flag:`-XTypeInType` was introduced for GHC 8.0, and is currently -experimental and temperamental, with the wrinkles to be smoothed out in due -course. The intent of having the two extensions is that users can rely on -:ghc-flag:`-XPolyKinds` to work properly while being duly sceptical of -:ghc-flag:`-XTypeInType`. In particular, we recommend enabling -:ghc-flag:`-dcore-lint` whenever using :ghc-flag:`-XTypeInType`; that flag -turns on a set of internal checks within GHC that will discover bugs in the -implementation of :ghc-flag:`-XTypeInType`. Please report bugs at `our bug -tracker <https://ghc.haskell.org/trac/ghc/wiki/ReportABug>`__. - -Although we have tried to allow the new behavior only when -:ghc-flag:`-XTypeInType` is enabled, some particularly thorny cases may have -slipped through. It is thus possible that some construct is available in GHC -8.0 with :ghc-flag:`-XPolyKinds` that was not possible in GHC 7.x. If you spot -such a case, you are welcome to submit that as a bug as well. We flag -newly-available capabilities below. - Overview of kind polymorphism ----------------------------- @@ -7962,22 +8752,22 @@ Consider inferring the kind for :: data App f a = MkApp (f a) -In Haskell 98, the inferred kind for ``App`` is ``(* -> *) -> * -> *``. -But this is overly specific, because another suitable Haskell 98 kind for -``App`` is ``((* -> *) -> *) -> (* -> *) -> *``, where the kind assigned -to ``a`` is ``* -> *``. Indeed, without kind signatures -(:ghc-flag:`-XKindSignatures`), it is necessary to use a dummy constructor -to get a Haskell compiler to infer the second kind. With kind polymorphism -(:ghc-flag:`-XPolyKinds`), GHC infers the kind ``forall k. (k -> *) -> k -> *`` -for ``App``, which is its most general kind. +In Haskell 98, the inferred kind for ``App`` is ``(Type -> Type) -> Type -> +Type``. But this is overly specific, because another suitable Haskell 98 kind +for ``App`` is ``((Type -> Type) -> Type) -> (Type -> Type) -> Type``, where the +kind assigned to ``a`` is ``Type -> Type``. Indeed, without kind signatures +(:extension:`KindSignatures`), it is necessary to use a dummy constructor to get +a Haskell compiler to infer the second kind. With kind polymorphism +(:extension:`PolyKinds`), GHC infers the kind ``forall k. (k -> Type) -> k -> +Type`` for ``App``, which is its most general kind. Thus, the chief benefit of kind polymorphism is that we can now infer these most general kinds and use ``App`` at a variety of kinds: :: - App Maybe Int -- `k` is instantiated to * + App Maybe Int -- `k` is instantiated to Type - data T a = MkT (a Int) -- `a` is inferred to have kind (* -> *) - App T Maybe -- `k` is instantiated to (* -> *) + data T a = MkT (a Int) -- `a` is inferred to have kind (Type -> Type) + App T Maybe -- `k` is instantiated to (Type -> Type) Overview of Type-in-Type ------------------------ @@ -7992,16 +8782,15 @@ between types and kinds is a hallmark of dependently typed languages. Full dependently typed languages also remove the difference between expressions and types, but doing that in GHC is a story for another day. -One simplification allowed by combining types and kinds is that the type -of ``*`` is just ``*``. It is true that the ``* :: *`` axiom can lead to -non-termination, but this is not a problem in GHC, as we already have other -means of non-terminating programs in both types and expressions. This -decision (among many, many others) *does* mean that despite the expressiveness -of GHC's type system, a "proof" you write in Haskell is not an irrefutable -mathematical proof. GHC promises only partial correctness, that if your -programs compile and run to completion, their results indeed have the types -assigned. It makes no claim about programs that do not finish in a finite -amount of time. +One simplification allowed by combining types and kinds is that the type of +``Type`` is just ``Type``. It is true that the ``Type :: Type`` axiom can lead +to non-termination, but this is not a problem in GHC, as we already have other +means of non-terminating programs in both types and expressions. This decision +(among many, many others) *does* mean that despite the expressiveness of GHC's +type system, a "proof" you write in Haskell is not an irrefutable mathematical +proof. GHC promises only partial correctness, that if your programs compile and +run to completion, their results indeed have the types assigned. It makes no +claim about programs that do not finish in a finite amount of time. To learn more about this decision and the design of GHC under the hood please see the `paper <http://www.seas.upenn.edu/~sweirich/papers/fckinds.pdf>`__ @@ -8010,9 +8799,10 @@ introducing this kind system to GHC/Haskell. Principles of kind inference ---------------------------- -Generally speaking, when :ghc-flag:`-XPolyKinds` is on, GHC tries to infer the +Generally speaking, when :extension:`PolyKinds` is on, GHC tries to infer the most general kind for a declaration. -In this case the definition has a right-hand side to inform kind +In many cases (for example, in a datatype declaration) +the definition has a right-hand side to inform kind inference. But that is not always the case. Consider :: type family F a @@ -8020,13 +8810,13 @@ inference. But that is not always the case. Consider :: Type family declarations have no right-hand side, but GHC must still infer a kind for ``F``. Since there are no constraints, it could infer ``F :: forall k1 k2. k1 -> k2``, but that seems *too* polymorphic. So -GHC defaults those entirely-unconstrained kind variables to ``*`` and we -get ``F :: * -> *``. You can still declare ``F`` to be kind-polymorphic +GHC defaults those entirely-unconstrained kind variables to ``Type`` and we +get ``F :: Type -> Type``. You can still declare ``F`` to be kind-polymorphic using kind signatures: :: - type family F1 a -- F1 :: * -> * - type family F2 (a :: k) -- F2 :: forall k. k -> * - type family F3 a :: k -- F3 :: forall k. * -> k + type family F1 a -- F1 :: Type -> Type + type family F2 (a :: k) -- F2 :: forall k. k -> Type + type family F3 a :: k -- F3 :: forall k. Type -> k type family F4 (a :: k1) :: k2 -- F4 :: forall k1 k2. k1 -> k2 The general principle is this: @@ -8038,7 +8828,7 @@ The general principle is this: class method signatures. - *When there is no right hand side, GHC defaults argument and result - kinds to ``*``, except when directed otherwise by a kind signature*. + kinds to ``Type``, except when directed otherwise by a kind signature*. Examples: data and open type family declarations. This rule has occasionally-surprising consequences (see @@ -8048,10 +8838,10 @@ This rule has occasionally-surprising consequences (see -- so C :: forall k. k -> Constraint data D1 a -- No right hand side for these two family type F1 a -- declarations, but the class forces (a :: k) - -- so D1, F1 :: forall k. k -> * + -- so D1, F1 :: forall k. k -> Type - data D2 a -- No right-hand side so D2 :: * -> * - type F2 a -- No right-hand side so F2 :: * -> * + data D2 a -- No right-hand side so D2 :: Type -> Type + type F2 a -- No right-hand side so F2 :: Type -> Type The kind-polymorphism from the class declaration makes ``D1`` kind-polymorphic, but not so ``D2``; and similarly ``F1``, ``F1``. @@ -8069,21 +8859,21 @@ Just as in type inference, kind inference for recursive types can only use *monomorphic* recursion. Consider this (contrived) example: :: data T m a = MkT (m a) (T Maybe (m a)) - -- GHC infers kind T :: (* -> *) -> * -> * + -- GHC infers kind T :: (Type -> Type) -> Type -> Type The recursive use of ``T`` forced the second argument to have kind -``*``. However, just as in type inference, you can achieve polymorphic +``Type``. However, just as in type inference, you can achieve polymorphic recursion by giving a *complete user-supplied kind signature* (or CUSK) for ``T``. A CUSK is present when all argument kinds and the result kind are known, without any need for inference. For example: :: - data T (m :: k -> *) :: k -> * where + data T (m :: k -> Type) :: k -> Type where MkT :: m a -> T Maybe (m a) -> T m a The complete user-supplied kind signature specifies the polymorphic kind for ``T``, and this signature is used for all the calls to ``T`` including the recursive ones. In particular, the recursive use of ``T`` -is at kind ``*``. +is at kind ``Type``. What exactly is considered to be a "complete user-supplied kind signature" for a type constructor? These are the forms: @@ -8094,35 +8884,30 @@ signature" for a type constructor? These are the forms: annotation does not affect whether or not the declaration has a complete signature. :: - data T1 :: (k -> *) -> k -> * where ... - -- Yes; T1 :: forall k. (k->*) -> k -> * + data T1 :: (k -> Type) -> k -> Type where ... + -- Yes; T1 :: forall k. (k->Type) -> k -> Type - data T2 (a :: k -> *) :: k -> * where ... - -- Yes; T2 :: forall k. (k->*) -> k -> * + data T2 (a :: k -> Type) :: k -> Type where ... + -- Yes; T2 :: forall k. (k->Type) -> k -> Type - data T3 (a :: k -> *) (b :: k) :: * where ... - -- Yes; T3 :: forall k. (k->*) -> k -> * + data T3 (a :: k -> Type) (b :: k) :: Type where ... + -- Yes; T3 :: forall k. (k->Type) -> k -> Type - data T4 (a :: k -> *) (b :: k) where ... - -- Yes; T4 :: forall k. (k->*) -> k -> * + data T4 (a :: k -> Type) (b :: k) where ... + -- Yes; T4 :: forall k. (k->Type) -> k -> Type - data T5 a (b :: k) :: * where ... + data T5 a (b :: k) :: Type where ... -- No; kind is inferred data T6 a b where ... -- No; kind is inferred -- For a datatype with a top-level ``::`` when :ghc-flag:`-XTypeInType` - is in effect: all kind variables introduced after the ``::`` must - be explicitly quantified. :: - - -- -XTypeInType is on - data T1 :: k -> * -- No CUSK: `k` is not explicitly quantified - data T2 :: forall k. k -> * -- CUSK: `k` is bound explicitly - data T3 :: forall (k :: *). k -> * -- still a CUSK +- For a datatype with a top-level ``::``: all kind variables introduced after + the ``::`` must be explicitly quantified. :: - Note that the first example would indeed have a CUSK without - :ghc-flag:`-XTypeInType`. + data T1 :: k -> Type -- No CUSK: `k` is not explicitly quantified + data T2 :: forall k. k -> Type -- CUSK: `k` is bound explicitly + data T3 :: forall (k :: Type). k -> Type -- still a CUSK - For a class, every type variable must be annotated with a kind. @@ -8138,13 +8923,12 @@ signature" for a type constructor? These are the forms: signature -- no inference can be done before detecting the signature. - An un-associated open type or data family declaration *always* has a CUSK; - un-annotated type variables default to - kind ``*``: :: + un-annotated type variables default to kind ``Type``: :: - data family D1 a -- D1 :: * -> * - data family D2 (a :: k) -- D2 :: forall k. k -> * - data family D3 (a :: k) :: * -- D3 :: forall k. k -> * - type family S1 a :: k -> * -- S1 :: forall k. * -> k -> * + data family D1 a -- D1 :: Type -> Type + data family D2 (a :: k) -- D2 :: forall k. k -> Type + data family D3 (a :: k) :: Type -- D3 :: forall k. k -> Type + type family S1 a :: k -> Type -- S1 :: forall k. Type -> k -> Type - An associated type or data family declaration has a CUSK precisely if its enclosing class has a CUSK. :: @@ -8159,21 +8943,15 @@ signature" for a type constructor? These are the forms: variables are annotated and a return kind (with a top-level ``::``) is supplied. -With :ghc-flag:`-XTypeInType` enabled, it is possible to write a datatype -that syntactically has a CUSK (according to the rules above) -but actually requires some inference. As a very contrived example, consider :: +It is possible to write a datatype that syntactically has a CUSK (according to +the rules above) but actually requires some inference. As a very contrived +example, consider :: - data Proxy a -- Proxy :: forall k. k -> * + data Proxy a -- Proxy :: forall k. k -> Type data X (a :: Proxy k) -According to the rules above ``X`` has a CUSK. Yet, what is the kind of ``k``? -It is impossible to know. This code is thus rejected as masquerading as having -a CUSK, but not really. If you wish ``k`` to be polykinded, it is straightforward -to specify this: :: - - data X (a :: Proxy (k1 :: k2)) - -The above definition is indeed fully fixed, with no masquerade. +According to the rules above ``X`` has a CUSK. Yet, the kind of ``k`` is undetermined. +It is thus quantified over, giving ``X`` the kind ``forall k1 (k :: k1). Proxy k -> Type``. Kind inference in closed type families -------------------------------------- @@ -8226,9 +9004,9 @@ for it: :: In the class declaration, nothing constrains the kind of the type ``a``, so it becomes a poly-kinded type variable ``(a :: k)``. Yet, in the instance declaration, the right-hand side of the associated type -instance ``b -> b`` says that ``b`` must be of kind ``*``. GHC could +instance ``b -> b`` says that ``b`` must be of kind ``Type``. GHC could theoretically propagate this information back into the instance head, -and make that instance declaration apply only to type of kind ``*``, as +and make that instance declaration apply only to type of kind ``Type``, as opposed to types of any kind. However, GHC does *not* do this. In short: GHC does *not* propagate kind information from the members of @@ -8247,25 +9025,25 @@ When kind-checking a type, GHC considers only what is written in that type when figuring out how to generalise the type's kind. For example, -consider these definitions (with :ghc-flag:`-XScopedTypeVariables`): :: +consider these definitions (with :extension:`ScopedTypeVariables`): :: - data Proxy a -- Proxy :: forall k. k -> * + data Proxy a -- Proxy :: forall k. k -> Type p :: forall a. Proxy a - p = Proxy :: Proxy (a :: *) + p = Proxy :: Proxy (a :: Type) GHC reports an error, saying that the kind of ``a`` should be a kind variable -``k``, not ``*``. This is because, by looking at the type signature +``k``, not ``Type``. This is because, by looking at the type signature ``forall a. Proxy a``, GHC assumes ``a``'s kind should be generalised, not -restricted to be ``*``. The function definition is then rejected for being +restricted to be ``Type``. The function definition is then rejected for being more specific than its type signature. Explicit kind quantification ---------------------------- -Enabled by :ghc-flag:`-XTypeInType`, GHC now supports explicit kind quantification, +Enabled by :extension:`PolyKinds`, GHC supports explicit kind quantification, as in these examples: :: - data Proxy :: forall k. k -> * + data Proxy :: forall k. k -> Type f :: (forall k (a :: k). Proxy a -> ()) -> Int Note that the second example has a ``forall`` that binds both a kind ``k`` and @@ -8296,10 +9074,10 @@ Consider the type :: This datatype ``G`` is GADT-like in both its kind and its type. Suppose you have ``g :: G a``, where ``a :: k``. Then pattern matching to discover that -``g`` is in fact ```GMaybe`` tells you both that ``k ~ (* -> *)`` and -``a ~ Maybe``. The definition for ``G`` requires that :ghc-flag:`-XTypeInType` +``g`` is in fact ``GMaybe`` tells you both that ``k ~ (Type -> Type)`` and +``a ~ Maybe``. The definition for ``G`` requires that :extension:`PolyKinds` be in effect, but pattern-matching on ``G`` requires no extension beyond -:ghc-flag:`-XGADTs`. That this works is actually a straightforward extension +:extension:`GADTs`. That this works is actually a straightforward extension of regular GADTs and a consequence of the fact that kinds and types are the same. @@ -8309,10 +9087,67 @@ It is thus only possible to use this feature if you have provided a complete user-supplied kind signature for the datatype (:ref:`complete-kind-signatures`). +Higher-rank kinds +----------------- + +In concert with :extension:`RankNTypes`, GHC supports higher-rank kinds. +Here is an example:: + + -- Heterogeneous propositional equality + data (a :: k1) :~~: (b :: k2) where + HRefl :: a :~~: a + + class HTestEquality (t :: forall k. k -> Type) where + hTestEquality :: forall k1 k2 (a :: k1) (b :: k2). t a -> t b -> Maybe (a :~~: b) + +Note that ``hTestEquality`` takes two arguments where the type variable ``t`` is applied +to types of different kinds. That type variable must then be polykinded. Accordingly, +the kind of ``HTestEquality`` (the class) is ``(forall k. k -> Type) -> Constraint``, +a higher-rank kind. + +A big difference with higher-rank kinds as compared with higher-rank types is that +``forall``\s in kinds *cannot* be moved. This is best illustrated by example. +Suppose we want to have an instance of ``HTestEquality`` for ``(:~~:)``. :: + + instance HTestEquality ((:~~:) a) where + hTestEquality HRefl HRefl = Just HRefl + +With the declaration of ``(:~~:)`` above, it gets kind ``forall k1 k2. k1 -> k2 -> Type``. +Thus, the type ``(:~~:) a`` has kind ``k2 -> Type`` for some ``k2``. GHC cannot +then *regeneralize* this kind to become ``forall k2. k2 -> Type`` as desired. Thus, the +instance is rejected as ill-kinded. + +To allow for such an instance, we would have to define ``(:~~:)`` as follows:: + + data (:~~:) :: forall k1. k1 -> forall k2. k2 -> Type where + HRefl :: a :~~: a + +In this redefinition, we give an explicit kind for ``(:~~:)``, deferring the choice +of ``k2`` until after the first argument (``a``) has been given. With this declaration +for ``(:~~:)``, the instance for ``HTestEquality`` is accepted. + +Another difference between higher-rank kinds and types can be found in their +treatment of inferred and user-specified type variables. Consider the following +program: :: + + newtype Foo (f :: forall k. k -> Type) = MkFoo (f Int) + data Proxy a = Proxy + + foo :: Foo Proxy + foo = MkFoo Proxy + +The kind of ``Foo``'s parameter is ``forall k. k -> Type``, but the kind of +``Proxy`` is ``forall {k}. k -> Type``, where ``{k}`` denotes that the kind +variable ``k`` is to be inferred, not specified by the user. (See +:ref:`visible-type-application` for more discussion on the inferred-specified +distinction). GHC does not consider ``forall k. k -> Type`` and +``forall {k}. k -> Type`` to be equal at the kind level, and thus rejects +``Foo Proxy`` as ill-kinded. + Constraints in kinds -------------------- -As kinds and types are the same, kinds can now (with :ghc-flag:`-XTypeInType`) +As kinds and types are the same, kinds can (with :extension:`PolyKinds`) contain type constraints. Only equality constraints are currently supported, however. We expect this to extend to other constraints in the future. @@ -8323,7 +9158,7 @@ Here is an example of a constrained kind: :: IsTypeLit Symbol = 'True IsTypeLit a = 'False - data T :: forall a. (IsTypeLit a ~ 'True) => a -> * where + data T :: forall a. (IsTypeLit a ~ 'True) => a -> Type where MkNat :: T 42 MkSymbol :: T "Don't panic!" @@ -8332,46 +9167,22 @@ we get an error that the equality constraint is not satisfied; ``Int`` is not a type literal. Note that explicitly quantifying with ``forall a`` is not necessary here. -The kind ``*`` --------------- - -The kind ``*`` classifies ordinary types. Without :ghc-flag:`-XTypeInType`, -this identifier is always in scope when writing a kind. However, with -:ghc-flag:`-XTypeInType`, a user may wish to use ``*`` in a type or a -type operator ``*`` in a kind. To make this all more manageable, ``*`` -becomes an (almost) ordinary name with :ghc-flag:`-XTypeInType` enabled. -So as not to cause naming collisions, it is not imported by default; -you must ``import Data.Kind`` to get ``*`` (but only with :ghc-flag:`-XTypeInType` -enabled). - -The only way ``*`` is unordinary is in its parsing. In order to be backward -compatible, ``*`` is parsed as if it were an alphanumeric idenfifier; note -that we do not write ``Int :: (*)`` but just plain ``Int :: *``. Due to the -bizarreness with which ``*`` is parsed-and the fact that it is the only such -operator in GHC-there are some corner cases that are -not handled. We are aware of two: - -- In a Haskell-98-style data constructor, you must put parentheses around - ``*``, like this: :: - - data Universe = Ty (*) | Num Int | ... - -- In an import/export list, you must put parentheses around ``*``, like this: :: - - import Data.Kind ( type (*) ) +The kind ``Type`` +----------------- - Note that the keyword ``type`` there is just to disambiguate the import - from a term-level ``(*)``. (:ref:`explicit-namespaces`) +.. extension:: StarIsType + :shortdesc: Treat ``*`` as ``Data.Kind.Type``. -The ``Data.Kind`` module also exports ``Type`` as a synonym for ``*``. -Now that type synonyms work in kinds, it is conceivable that we will deprecate -``*`` when there is a good migration story for everyone to use ``Type``. -If you like neither of these names, feel free to write your own synonym: :: + :since: 8.6.1 - type Set = * -- silly Agda programmers... + Treat the unqualified uses of the ``*`` type operator as nullary and desugar + to ``Data.Kind.Type``. -All the affordances for ``*`` also apply to ``★``, the Unicode variant -of ``*``. +The kind ``Type`` (imported from ``Data.Kind``) classifies ordinary types. With +:extension:`StarIsType` (currently enabled by default), ``*`` is desugared to +``Type``, but using this legacy syntax is not recommended due to conflicts with +:extension:`TypeOperators`. This also applies to ``★``, the Unicode variant of +``*``. Inferring dependency in datatype declarations --------------------------------------------- @@ -8404,19 +9215,44 @@ system does not have principal types) or merely practical (inferring this dependency is hard, given GHC's implementation). So, GHC takes the easy way out and requires a little help from the user. -Kind defaulting without :ghc-flag:`-XPolyKinds` +Inferring dependency in user-written ``forall``\s +------------------------------------------------- + +A programmer may use ``forall`` in a type to introduce new quantified type +variables. These variables may depend on each other, even in the same +``forall``. However, GHC requires that the dependency be inferrable from +the body of the ``forall``. Here are some examples:: + + data Proxy k (a :: k) = MkProxy -- just to use below + + f :: forall k a. Proxy k a -- This is just fine. We see that (a :: k). + f = undefined + + g :: Proxy k a -> () -- This is to use below. + g = undefined + + data Sing a + h :: forall k a. Sing k -> Sing a -> () -- No obvious relationship between k and a + h _ _ = g (MkProxy :: Proxy k a) -- This fails. We didn't know that a should have kind k. + +Note that in the last example, it's impossible to learn that ``a`` depends on ``k`` in the +body of the ``forall`` (that is, the ``Sing k -> Sing a -> ()``). And so GHC rejects +the program. + +Kind defaulting without :extension:`PolyKinds` ----------------------------------------------- -Without :ghc-flag:`-XPolyKinds` or :ghc-flag:`-XTypeInType` enabled, GHC -refuses to generalise over kind variables. It thus defaults kind variables -to ``*`` when possible; when this is not possible, an error is issued. +Without :extension:`PolyKinds`, GHC refuses to generalise over kind variables. +It thus defaults kind variables to ``Type`` when possible; when this is not +possible, an error is issued. Here is an example of this in action: :: - {-# LANGUAGE TypeInType #-} - data Proxy a = P -- inferred kind: Proxy :: k -> * + {-# LANGUAGE PolyKinds #-} + import Data.Kind (Type) + data Proxy a = P -- inferred kind: Proxy :: k -> Type data Compose f g x = MkCompose (f (g x)) - -- inferred kind: Compose :: (b -> *) -> (a -> b) -> a -> * + -- inferred kind: Compose :: (b -> Type) -> (a -> b) -> a -> Type -- separate module having imported the first {-# LANGUAGE NoPolyKinds, DataKinds #-} @@ -8425,13 +9261,13 @@ Here is an example of this in action: :: In the last line, we use the promoted constructor ``'MkCompose``, which has kind :: - forall (a :: *) (b :: *) (f :: b -> *) (g :: a -> b) (x :: a). + forall (a :: Type) (b :: Type) (f :: b -> Type) (g :: a -> b) (x :: a). f (g x) -> Compose f g x Now we must infer a type for ``z``. To do so without generalising over kind -variables, we must default the kind variables of ``'MkCompose``. We can -easily default ``a`` and ``b`` to ``*``, but ``f`` and ``g`` would be ill-kinded -if defaulted. The definition for ``z`` is thus an error. +variables, we must default the kind variables of ``'MkCompose``. We can easily +default ``a`` and ``b`` to ``Type``, but ``f`` and ``g`` would be ill-kinded if +defaulted. The definition for ``z`` is thus an error. Pretty-printing in the presence of kind polymorphism ---------------------------------------------------- @@ -8461,7 +9297,7 @@ polymorphism. Here are the key definitions, all available from ``GHC.Exts``: :: - TYPE :: RuntimeRep -> * -- highly magical, built into GHC + TYPE :: RuntimeRep -> Type -- highly magical, built into GHC data RuntimeRep = LiftedRep -- for things like `Int` | UnliftedRep -- for things like `Array#` @@ -8470,7 +9306,7 @@ Here are the key definitions, all available from ``GHC.Exts``: :: | SumRep [RuntimeRep] -- unboxed sums, indexed by the representations of the disjuncts | ... - type * = TYPE LiftedRep -- * is just an ordinary type synonym + type Type = TYPE LiftedRep -- Type is just an ordinary type synonym The idea is that we have a new fundamental type constant ``TYPE``, which is parameterised by a ``RuntimeRep``. We thus get ``Int# :: TYPE 'IntRep`` @@ -8508,7 +9344,7 @@ representation-polymorphic type. However, not all is lost. We can still do this: :: - ($) :: forall r (a :: *) (b :: TYPE r). + ($) :: forall r (a :: Type) (b :: TYPE r). (a -> b) -> a -> b f $ x = f x @@ -8540,16 +9376,22 @@ stub out functions that return unboxed types. Printing levity-polymorphic types --------------------------------- -.. ghc-flag:: -Wprint-explicit-runtime-rep +.. ghc-flag:: -fprint-explicit-runtime-reps + :shortdesc: Print ``RuntimeRep`` variables in types which are + runtime-representation polymorphic. + :type: dynamic + :reverse: -fno-print-explicit-runtime-reps + :category: verbosity - Print ``RuntimeRep`` parameters as they appear; otherwise, they are - defaulted to ``'LiftedRep``. + Print ``RuntimeRep`` parameters as they appear; otherwise, they are + defaulted to ``'LiftedRep``. Most GHC users will not need to worry about levity polymorphism or unboxed types. For these users, seeing the levity polymorphism in the type of ``$`` is unhelpful. And thus, by default, it is suppressed, by supposing all type variables of type ``RuntimeRep`` to be ``'LiftedRep`` -when printing, and printing ``TYPE 'LiftedRep`` as ``*``. +when printing, and printing ``TYPE 'LiftedRep`` as ``Type`` (or ``*`` when +:extension:`StarIsType` is on). Should you wish to see levity polymorphism in your types, enable the flag :ghc-flag:`-fprint-explicit-runtime-reps`. @@ -8562,7 +9404,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 :ghc-flag:`-XDataKinds` language +``Symbol``. This feature is enabled by the :extension:`DataKinds` language extension. The kinds of the literals and all other low-level operations for this @@ -8675,8 +9517,8 @@ the type level: GHC.TypeLits> natVal (lg (Proxy :: Proxy 2) (Proxy :: Proxy 8)) 3 -Constraints in types -==================== +Equality constraints, Coercible, and the kind Constraint +======================================================== .. _equality-constraints: @@ -8760,7 +9602,8 @@ paper The ``Constraint`` kind ----------------------- -.. ghc-flag:: -XConstraintKinds +.. extension:: ConstraintKinds + :shortdesc: Enable a kind of constraints. :since: 7.4.1 @@ -8772,12 +9615,12 @@ arrow) have a very restricted syntax. They can only be: - Class constraints, e.g. ``Show a`` - :ghc-flag:`Implicit parameter <-XImplicitParams>` constraints, e.g. - ``?x::Int`` (with the :ghc-flag:`-XImplicitParams` flag) + ``?x::Int`` (with the :extension:`ImplicitParams` extension) - :ref:`Equality constraints <equality-constraints>`, e.g. ``a ~ Int`` - (with the :ghc-flag:`-XTypeFamilies` or :ghc-flag:`-XGADTs` flag) + (with the :extension:`TypeFamilies` or :extension:`GADTs` extensions) -With the :ghc-flag:`-XConstraintKinds` flag, GHC becomes more liberal in what it +With the :extension:`ConstraintKinds` extension, 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``: @@ -8791,8 +9634,8 @@ The following things have kind ``Constraint``: - Anything whose form is not yet known, but the user has declared to have kind ``Constraint`` (for which they need to import it from - ``GHC.Exts``). So for example - ``type Foo (f :: \* -> Constraint) = forall b. f b => b -> b`` + ``Data.Kind``). So for example + ``type Foo (f :: Type -> Constraint) = forall b. f b => b -> b`` is allowed, as well as examples involving type families: :: type family Typ a b :: Constraint @@ -8831,9 +9674,267 @@ 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 -:ghc-flag:`-XUndecidableInstances` to signal that you don't mind if the type +:extension:`UndecidableInstances` to signal that you don't mind if the type checker fails to terminate. +.. _quantified-constraints: + +Quantified constraints +====================== + +.. extension:: QuantifiedConstraints + :shortdesc: Allow ``forall`` quantifiers in constraints. + + :since: 8.6.1 + + Allow constraints to quantify over types. + +The extension :extension:`QuantifiedConstraints` introduces **quantified constraints**, +which give a new level of expressiveness in constraints. For example, consider :: + + data Rose f a = Branch a (f (Rose f a)) + + instance (Eq a, ???) => Eq (Rose f a) + where + (Branch x1 c1) == (Branch x2 c2) + = x1==x1 && c1==c2 + +From the ``x1==x2`` we need ``Eq a``, which is fine. From ``c1==c2`` we need ``Eq (f (Rose f a))`` which +is *not* fine in Haskell today; we have no way to solve such a constraint. + +:extension:`QuantifiedConstraints` lets us write this :: + + instance (Eq a, forall b. (Eq b) => Eq (f b)) + => Eq (Rose f a) + where + (Branch x1 c1) == (Branch x2 c2) + = x1==x1 && c1==c2 + +Here, the quantified constraint ``forall b. (Eq b) => Eq (f b)`` behaves +a bit like a local instance declaration, and makes the instance typeable. + +The paper `Quantified class constraints <http://i.cs.hku.hk/~bruno//papers/hs2017.pdf>`_ (by Bottu, Karachalias, Schrijvers, Oliveira, Wadler, Haskell Symposium 2017) describes this feature in technical detail, with examples, and so is a primary reference source for this proposal. + +Motivation +---------------- +Introducing quantified constraints offers two main benefits: + +- Firstly, they enable terminating resolution where this was not possible before. Consider for instance the following instance declaration for the general rose datatype :: + + data Rose f x = Rose x (f (Rose f x)) + + instance (Eq a, forall b. Eq b => Eq (f b)) => Eq (Rose f a) where + (Rose x1 rs1) == (Rose x2 rs2) = x1 == x2 && rs1 == rs2 + + This extension allows us to write constraints of the form ``forall b. Eq b => + Eq (f b)``, which is needed to solve the ``Eq (f (Rose f x))`` constraint + arising from the second usage of the ``(==)`` method. + +- Secondly, quantified constraints allow for more concise and precise specifications. As an example, consider the MTL type class for monad transformers:: + + class Trans t where + lift :: Monad m => m a -> (t m) a + + The developer knows that a monad transformer takes a monad ``m`` into a new monad ``t m``. + But this property is not formally specified in the above declaration. + This omission becomes an issue when defining monad transformer composition:: + + newtype (t1 * t2) m a = C { runC :: t1 (t2 m) a } + + instance (Trans t1, Trans t2) => Trans (t1 * t2) where + lift = C . lift . lift + + The goal here is to ``lift`` from monad ``m`` to ``t2 m`` and + then ``lift`` this again into ``t1 (t2 m)``. + However, this second ``lift`` can only be accepted when ``(t2 m)`` is a monad + and there is no way of establishing that this fact universally holds. + + Quantified constraints enable this property to be made explicit in the ``Trans`` + class declaration:: + + class (forall m. Monad m => Monad (t m)) => Trans t where + lift :: Monad m => m a -> (t m) a + +This idea is very old; see Seciton 7 of `Derivable type classes <https://www.microsoft.com/en-us/research/publication/derivable-type-classes/>`_. + +Syntax changes +---------------- + +`Haskell 2010 <https://www.haskell.org/onlinereport/haskell2010/haskellch10.html#x17-18000010.5>`_ defines a ``context`` (the bit to the left of ``=>`` in a type) like this + +.. code-block:: none + + context ::= class + | ( class1, ..., classn ) + + class ::= qtycls tyvar + | qtycls (tyvar atype1 ... atypen) + +We to extend ``class`` (warning: this is a rather confusingly named non-terminal symbol) with two extra forms, namely precisely what can appear in an instance declaration + +.. code-block:: none + + class ::= ... + | [context =>] qtycls inst + | [context =>] tyvar inst + +The definition of ``inst`` is unchanged from the Haskell Report (roughly, just a type). +The ``context =>`` part is optional. That is the only syntactic change to the language. + +Notes: + +- Where GHC allows extensions instance declarations we allow exactly the same extensions to this new form of ``class``. Specifically, with :extension:`ExplicitForAll` and :extension:`MultiParameterTypeClasses` the syntax becomes + + .. code-block:: none + + class ::= ... + | [forall tyavrs .] [context =>] qtycls inst1 ... instn + | [forall tyavrs .] [context =>] tyvar inst1 ... instn + + Note that an explicit ``forall`` is often absolutely essential. Consider the rose-tree example :: + + instance (Eq a, forall b. Eq b => Eq (f b)) => Eq (Rose f a) where ... + + Without the ``forall b``, the type variable ``b`` would be quantified over the whole instance declaration, which is not what is intended. + +- One of these new quantified constraints can appear anywhere that any other constraint can, not just in instance declarations. Notably, it can appear in a type signature for a value binding, data constructor, or expression. For example :: + + f :: (Eq a, forall b. Eq b => Eq (f b)) => Rose f a -> Rose f a -> Bool + f t1 t2 = not (t1 == t2) + +- The form with a type variable at the head allows this:: + + instance (forall xx. c (Free c xx)) => Monad (Free c) where + Free f >>= g = f g + + See `Iceland Jack's summary <https://ghc.haskell.org/trac/ghc/ticket/14733#comment:6>`_. The key point is that the bit to the right of the ``=>`` may be headed by a type *variable* (``c`` in this case), rather than a class. It should not be one of the forall'd variables, though. + + (NB: this goes beyond what is described in `the paper <http://i.cs.hku.hk/~bruno//papers/hs2017.pdf>`_, but does not seem to introduce any new technical difficulties.) + + +Typing changes +---------------- + +See `the paper <http://i.cs.hku.hk/~bruno//papers/hs2017.pdf>`_. + +Superclasses +---------------- + +Suppose we have:: + + f :: forall m. (forall a. Ord a => Ord (m a)) => m Int -> Bool + f x = x == x + +From the ``x==x`` we need an ``Eq (m Int)`` constraint, but the context only gives us a way to figure out ``Ord (m a)`` constraints. But from the given constraint ``forall a. Ord a => Ord (m a)`` we derive a second given constraint ``forall a. Ord a => Eq (m a)``, and from that we can readily solve ``Eq (m Int)``. This process is very similar to the way that superclasses already work: given an ``Ord a`` constraint we derive a second given ``Eq a`` constraint. + +NB: This treatment of superclasses goes beyond `the paper <http://i.cs.hku.hk/~bruno//papers/hs2017.pdf>`_, but is specifically desired by users. + +Overlap +------------- + +Quantified constraints can potentially lead to overlapping local axioms. +Consider for instance the following example:: + + class A a where {} + class B a where {} + class C a where {} + class (A a => C a) => D a where {} + class (B a => C a) => E a where {} + + class C a => F a where {} + instance (B a, D a, E a) => F a where {} + +When type checking the instance declaration for ``F a``, +we need to check that the superclass ``C`` of ``F`` holds. +We thus try to entail the constraint ``C a`` under the theory containing: + +- The instance axioms : ``(B a, D a, E a) => F a`` +- The local axioms from the instance context : ``B a``, ``D a`` and ``E a`` +- The closure of the superclass relation over these local axioms : ``A a => C a`` and ``B a => C a`` + +However, the ``A a => C a`` and ``B a => C a`` axioms both match the wanted constraint ``C a``. +There are several possible approaches for handling these overlapping local axioms: + +- **Pick first**. We can simply select the **first matching axiom** we encounter. + In the above example, this would be ``A a => C a``. + We'd then need to entail ``A a``, for which we have no matching axioms available, causing the above program to be rejected. + + But suppose we made a slight adjustment to the order of the instance context, putting ``E a`` before ``D a``:: + + instance (B a, E a, D a) => F a where {} + + The first matching axiom we encounter while entailing ``C a``, is ``B a => C a``. + We have a local axiom ``B a`` available, so now the program is suddenly accepted. + This behaviour, where the ordering of an instance context determines + whether or not the program is accepted, seems rather confusing for the developer. + +- **Reject if in doubt**. An alternative approach would be to check for overlapping axioms, + when solving a constraint. + When multiple matching axioms are discovered, we **reject the program**. + This approach is a bit conservative, in that it may reject working programs. + But it seem much more transparent towards the developer, who + can be presented with a clear message, explaining why the program is rejected. + +- **Backtracking**. Lastly, a simple form of **backtracking** could be introduced. + We simply select the first matching axiom we encounter and when the entailment fails, + we backtrack and look for other axioms that might match the wanted constraint. + + This seems the most intuitive and transparent approach towards the developer, + who no longer needs to concern himself with the fact that his code might contain + overlapping axioms or with the ordering of his instance contexts. But backtracking + would apply equally to ordinary instance selection (in the presence of overlapping + instances), so it is a much more pervasive change, with substantial consequences + for the type inference engine. + +GHC adopts **Reject if in doubt** for now. We can see how painful it +is in practice, and try something more ambitious if necessary. + +Instance lookup +------------------- + +In the light of the overlap decision, instance lookup works like this when +trying to solve a class constraint ``C t`` + +1. First see if there is a given un-quantified constraint ``C t``. If so, use it to solve the constraint. + +2. If not, look at all the available given quantified constraints; if exactly one one matches ``C t``, choose it; if more than one matches, report an error. + +3. If no quantified constraints match, look up in the global instances, as described in :ref:`instance-resolution` and :ref:`instance-overlap`. + +Termination +--------------- + +GHC uses the :ref:`Paterson Conditions <instance-termination>` to ensure +that instance resolution terminates. How are those rules modified for quantified +constraints? In two ways. + +- Each quantified constraint, taken by itself, must satisfy the termination rules for an instance declaration. + +- After "for each class constraint ``(C t1 ... tn)``", add "or each quantified constraint ``(forall as. context => C t1 .. tn)``" + +Note that the second item only at the *head* of the quantified constraint, not its context. Reason: the head is the new goal that has to be solved if we use the instance declaration. + +Of course, ``UndecidableInstances`` lifts the Paterson Conditions, as now. + +Coherence +----------- + +Although quantified constraints are a little like local instance declarations, they differ +in one big way: the local instances are written by the compiler, not the user, and hence +cannot introduce incoherence. Consider :: + + f :: (forall a. Eq a => Eq (f a)) => f b -> f Bool + f x = ...rhs... + +In ``...rhs...`` there is, in effect a local instance for ``Eq (f a)`` for any ``a``. But +at a call site for ``f`` the compiler itself produces evidence to pass to ``f``. For example, +if we called ``f Nothing``, then ``f`` is ``Maybe`` and the compiler must prove (at the +call site) that ``forall a. Eq a => Eq (Maybe a)`` holds. It can do this easily, by +appealing to the existing instance declaration for ``Eq (Maybe a)``. + +In short, quantifed constraints do not introduce incoherence. + + .. _extensions-to-type-signatures: Extensions to type signatures @@ -8844,15 +9945,18 @@ Extensions to type signatures Explicit universal quantification (forall) ------------------------------------------ -.. ghc-flag:: -XExplicitForAll +.. extension:: ExplicitForAll + :shortdesc: Enable explicit universal quantification. + Implied by :extension:`ScopedTypeVariables`, :extension:`LiberalTypeSynonyms`, + :extension:`RankNTypes` and :extension:`ExistentialQuantification`. - :since: 6.12 + :since: 6.12.1 Allow use of the ``forall`` keyword in places where universal quantification is implicit. Haskell type signatures are implicitly quantified. When the language -option :ghc-flag:`-XExplicitForAll` is used, the keyword ``forall`` allows us to +option :extension:`ExplicitForAll` is used, the keyword ``forall`` allows us to say exactly what this means. For example: :: g :: b -> b @@ -8866,7 +9970,7 @@ into scope (see :ref:`scoped-type-variables`). Notes: -- With :ghc-flag:`-XExplicitForAll`, ``forall`` becomes a keyword; you can't use ``forall`` as a +- With :extension:`ExplicitForAll`, ``forall`` becomes a keyword; you can't use ``forall`` as a type variable any more! - As well in type signatures, you can also use an explicit ``forall`` @@ -8887,16 +9991,16 @@ Notes: The context of a type signature ------------------------------- -The :ghc-flag:`-XFlexibleContexts` flag lifts the Haskell 98 restriction that +The :extension:`FlexibleContexts` extension lifts the Haskell 98 restriction that the type-class constraints in a type signature must have the form *(class type-variable)* or *(class (type-variable type1 type2 ... typen))*. With -:ghc-flag:`-XFlexibleContexts` these type signatures are perfectly okay +:extension:`FlexibleContexts` these type signatures are perfectly okay :: g :: Eq [a] => ... g :: Ord (T a ()) => ... -The flag :ghc-flag:`-XFlexibleContexts` also lifts the corresponding restriction +The flag :extension:`FlexibleContexts` also lifts the corresponding restriction on class declarations (:ref:`superclass-rules`) and instance declarations (:ref:`instance-rules`). @@ -8905,7 +10009,9 @@ declarations (:ref:`instance-rules`). Ambiguous types and the ambiguity check --------------------------------------- -.. ghc-flag:: -XAllowAmbiguousTypes +.. extension:: AllowAmbiguousTypes + :shortdesc: Allow the user to write ambiguous types, and + the type inference engine to infer them. :since: 7.8.1 @@ -8923,7 +10029,7 @@ 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 :ghc-flag:`-XAllowAmbiguousTypes` switches off the ambiguity +language extension :extension:`AllowAmbiguousTypes` switches off the ambiguity check. Ambiguity can be subtle. Consider this example which uses functional @@ -8996,7 +10102,7 @@ because it gives rise to a constraint ``(D Bool beta)``, which is soluble by the ``(D Bool b)`` instance. Another way of getting rid of the ambiguity at the call site is to use -the :ghc-flag:`-XTypeApplications` flag to specify the types. For example: :: +the :extension:`TypeApplications` extension to specify the types. For example: :: class D a b where h :: b @@ -9007,7 +10113,7 @@ the :ghc-flag:`-XTypeApplications` flag to specify the types. For example: :: Here ``a`` is ambiguous in the definition of ``D`` but later specified to be `Int` using type applications. -:ghc-flag:`-XAllowAmbiguousTypes` allows you to switch off the ambiguity check. +:extension:`AllowAmbiguousTypes` allows you to switch off the ambiguity check. However, even with ambiguity checking switched off, GHC will complain about a function that can *never* be called, such as this one: :: @@ -9030,7 +10136,11 @@ function that can *never* be called, such as this one: :: Explicitly-kinded quantification -------------------------------- -.. ghc-flag:: -XKindSignatures +.. extension:: KindSignatures + :shortdesc: Enable kind signatures. + Implied by :extension:`TypeFamilies` and :extension:`PolyKinds`. + + :since: 6.8.1 Allow explicit kind signatures on type variables. @@ -9048,36 +10158,34 @@ 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 -:ghc-flag:`-XKindSignatures`. +directly, wherever a type variable is explicitly bound, with the extension +:extension:`KindSignatures`. -This flag enables kind signatures in the following places: +This extension enables kind signatures in the following places: - ``data`` declarations: :: - data Set (cxt :: * -> *) a = Set [a] + data Set (cxt :: Type -> Type) a = Set [a] - ``type`` declarations: :: - type T (f :: * -> *) = f Int + type T (f :: Type -> Type) = f Int - ``class`` declarations: :: - class (Eq a) => C (f :: * -> *) a where ... + class (Eq a) => C (f :: Type -> Type) a where ... - ``forall``\'s in type signatures: :: - f :: forall (cxt :: * -> *). Set cxt Int + f :: forall (cxt :: Type -> Type). 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. +The parentheses are required. As part of the same extension, you can put kind annotations in types as well. Thus: :: - f :: (Int :: *) -> Int - g :: forall a. a -> (a :: *) + f :: (Int :: Type) -> Int + g :: forall a. a -> (a :: Type) The syntax is @@ -9094,13 +10202,26 @@ The parentheses are required. Lexically scoped type variables =============================== -.. ghc-flag:: -XScopedTypeVariables +.. extension:: ScopedTypeVariables + :shortdesc: Enable lexically-scoped type variables. - :implies: :ghc-flag:`-XExplicitForAll` + :implies: :extension:`ExplicitForAll` + :since: 6.8.1 Enable lexical scoping of type variables explicitly introduced with ``forall``. +.. tip:: + + ``ScopedTypeVariables`` breaks GHC's usual rule that explicit ``forall`` is optional and doesn't affect semantics. + For the :ref:`decl-type-sigs` (or :ref:`exp-type-sigs`) examples in this section, + the explicit ``forall`` is required. + (If omitted, usually the program will not compile; in a few cases it will compile but the functions get a different signature.) + To trigger those forms of ``ScopedTypeVariables``, the ``forall`` must appear against the top-level signature (or outer expression) + but *not* against nested signatures referring to the same type variables. + + Explicit ``forall`` is not always required -- see :ref:`pattern signature equivalent <pattern-equiv-form>` for the example in this section, or :ref:`pattern-type-sigs`. + GHC supports *lexically scoped type variables*, without which some type signatures are simply impossible to write. For example: :: @@ -9119,6 +10240,21 @@ signature for ``ys``. In Haskell 98 it is not possible to declare a type for ``ys``; a major benefit of scoped type variables is that it becomes possible to do so. +.. _pattern-equiv-form: + +An equivalent form for that example, avoiding explicit ``forall`` uses :ref:`pattern-type-sigs`: :: + + f :: [a] -> [a] + f (xs :: [aa]) = xs ++ ys + where + ys :: [aa] + ys = reverse xs + +Unlike the ``forall`` form, type variable ``a`` from ``f``'s signature is not scoped over ``f``'s equation(s). +Type variable ``aa`` bound by the pattern signature is scoped over the right-hand side of ``f``'s equation. +(Therefore there is no need to use a distinct type variable; using ``a`` would be equivalent.) + + Overview -------- @@ -9185,6 +10321,26 @@ This only happens if: the definition of "``g``", so "``x::a``" means "``x::forall a. a``" by Haskell's usual implicit quantification rules. +- The type variable is quantified by the single, syntactically visible, + outermost ``forall`` of the type signature. For example, GHC will reject + all of the following examples: :: + + f1 :: forall a. forall b. a -> [b] -> [b] + f1 _ (x:xs) = xs ++ [ x :: b ] + + f2 :: forall a. a -> forall b. [b] -> [b] + f2 _ (x:xs) = xs ++ [ x :: b ] + + type Foo = forall b. [b] -> [b] + + f3 :: Foo + f3 (x:xs) = xs ++ [ x :: b ] + + In ``f1`` and ``f2``, the type variable ``b`` is not quantified by the + outermost ``forall``, so it is not in scope over the bodies of the + functions. Neither is ``b`` in scope over the body of ``f3``, as the + ``forall`` is tucked underneath the ``Foo`` type synonym. + - The signature gives a type for a function binding or a bare variable binding, not a pattern binding. For example: :: @@ -9197,10 +10353,12 @@ This only happens if: f3 :: forall a. [a] -> [a] Just f3 = Just (\(x:xs) -> xs ++ [ x :: a ]) -- Not OK! - The binding for ``f3`` is a pattern binding, and so its type - signature does not bring ``a`` into scope. However ``f1`` is a - function binding, and ``f2`` binds a bare variable; in both cases the - type signature brings ``a`` into scope. + ``f1`` is a function binding, and ``f2`` binds a bare variable; + in both cases the type signature brings ``a`` into scope. + However the binding for ``f3`` is a pattern binding, + and so ``f3`` is a fresh variable brought into scope by the pattern, + not connected with top level ``f3``. + Then type variable ``a`` is not in scope of the right-hand side of ``Just f3 = ...``. .. _exp-type-sigs: @@ -9246,17 +10404,28 @@ example: :: f xs = (n, zs) where (ys::[a], n) = (reverse xs, length xs) -- OK - zs::[a] = xs ++ ys -- 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. 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: :: +case, *the signature brings that type variable into scope*. For example: :: + + -- same f and g as above, now assuming that 'a' is not already in scope + f = \(x::Int, y::a) -> x -- 'a' is in scope on RHS of -> + + g (x::a) = x :: a + + hh (Just (v :: b)) = v :: b + +The pattern type signature makes the type variable available on the right-hand side of the equation. + +Bringing type variables into scope is particularly important +for existential data constructors. For example: :: data T = forall a. MkT [a] @@ -9264,28 +10433,25 @@ particularly important for existential data constructors. For example: :: 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 -scope, because it is bound by the pattern match. GHC's rule is that in -this situation (and only then), a pattern type signature can mention a -type variable that is not already in scope; the effect is to bring it -into scope, standing for the existentially-bound type variable. - -When a pattern type signature binds a type variable in this way, GHC -insists that the type variable is bound to a *rigid*, or fully-known, -type variable. This means that any user-written type signature always -stands for a completely known type. - -If all this seems a little odd, we think so too. But we must have *some* -way to bring such type variables into scope, else we could not name -existentially-bound type variables in subsequent type signatures. - -This is (now) the *only* situation in which a pattern type signature is -allowed to mention a lexical variable that is not already in scope. For -example, both ``f`` and ``g`` would be illegal if ``a`` was not already -in scope. + (t3::[a]) = [t,t,t] + +Here, the pattern type signature ``[t::a]`` mentions a lexical type +variable that is not already in scope. Indeed, it *must not* already be in +scope, because it is bound by the pattern match. +The effect is to bring it into scope, +standing for the existentially-bound type variable. + +It does seem odd that the existentially-bound type variable *must not* +be already in scope. Contrast that usually name-bindings merely shadow +(make a 'hole') in a same-named outer variable's scope. +But we must have *some* way to bring such type variables into scope, +else we could not name existentially-bound type variables +in subsequent type signatures. + +Compare the two (identical) definitions for examples ``f``, ``g``; +they are both legal whether or not ``a`` is already in scope. +They differ in that *if* ``a`` is already in scope, the signature constrains +the pattern, rather than the pattern binding the variable. .. _cls-inst-scoped-tyvars: @@ -9317,9 +10483,11 @@ Bindings and generalisation Switching off the dreaded Monomorphism Restriction -------------------------------------------------- -.. ghc-flag:: -XNoMonomorphismRestriction +.. extension:: NoMonomorphismRestriction + :shortdesc: Disable the monomorphism restriction. :default: on + :since: 6.8.1 Prevents the compiler from applying the monomorphism restriction to bindings lacking explicit type signatures. @@ -9327,7 +10495,7 @@ Switching off the dreaded Monomorphism Restriction 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 -:ghc-flag:`-XNoMonomorphismRestriction`. Since GHC 7.8.1, the monomorphism +:extension:`NoMonomorphismRestriction`. Since GHC 7.8.1, the monomorphism restriction is switched off by default in GHCi's interactive options (see :ref:`ghci-interactive-options`). @@ -9336,15 +10504,17 @@ restriction is switched off by default in GHCi's interactive options Let-generalisation ------------------ -.. ghc-flag:: -XMonoLocalBinds +.. extension:: MonoLocalBinds + :shortdesc: Enable do not generalise local bindings. + Implied by :extension:`TypeFamilies` and :extension:`GADTs`. - :since: 6.12 + :since: 6.12.1 Infer less polymorphic types for local bindings by default. An ML-style language usually generalises the type of any ``let``\-bound or ``where``\-bound variable, so that it is as polymorphic as possible. With the -flag :ghc-flag:`-XMonoLocalBinds` GHC implements a slightly more conservative +extension :extension:`MonoLocalBinds` GHC implements a slightly more conservative policy, using the following rules: - A variable is *closed* if and only if @@ -9390,66 +10560,24 @@ papers <https://www.microsoft.com/en-us/research/wp-content/uploads/2016/02/jfp- "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 :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!) - -.. _kind-generalisation: - -Kind generalisation -------------------- - -Just as :ghc-flag:`-XMonoLocalBinds` places limitations on when the *type* of a -*term* is generalised (see :ref:`mono-local-binds`), it also limits when the -*kind* of a *type signature* is generalised. Here is an example involving -:ref:`type signatures on instance declarations <instance-sigs>`: :: - - data Proxy a = Proxy - newtype Tagged s b = Tagged b - - class C b where - c :: forall (s :: k). Tagged s b - - instance C (Proxy a) where - c :: forall s. Tagged s (Proxy a) - c = Tagged Proxy - -With :ghc-flag:`-XMonoLocalBinds` enabled, this ``C (Proxy a)`` instance will -fail to typecheck. The reason is that the type signature for ``c`` captures -``a``, an outer-scoped type variable, which means the type signature is not -closed. Therefore, the inferred kind for ``s`` will *not* be generalised, and -as a result, it will fail to unify with the kind variable ``k`` which is -specified in the declaration of ``c``. This can be worked around by specifying -an explicit kind variable for ``s``, e.g., :: - - instance C (Proxy a) where - c :: forall (s :: k). Tagged s (Proxy a) - c = Tagged Proxy - -or, alternatively: :: - - instance C (Proxy a) where - c :: forall k (s :: k). Tagged s (Proxy a) - c = Tagged Proxy - -This declarations are equivalent using Haskell's implicit "add implicit -foralls" rules (see :ref:`implicit-quantification`). The implicit foralls rules -are purely syntactic and are quite separate from the kind generalisation -described here. +The extension :extension:`MonoLocalBinds` is implied by :extension:`TypeFamilies` +and :extension:`GADTs`. You can switch it off again with +:extension:`NoMonoLocalBinds <-XMonoLocalBinds>` but type inference becomes +less predictable if you do so. (Read the papers!) .. _visible-type-application: Visible type application ======================== -.. ghc-flag:: -XTypeApplications +.. extension:: TypeApplications + :shortdesc: Enable type application syntax. :since: 8.0.1 Allow the use of type application syntax. -The :ghc-flag:`-XTypeApplications` extension allows you to use +The :extension:`TypeApplications` 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 @@ -9473,14 +10601,35 @@ Here are the details: will have its type variables ordered as ``m, a, b, c``. +- If the type signature includes any kind annotations (either on variable + binders or as annotations on types), any variables used in kind + annotations come before any variables never used in kind annotations. + This rule is not recursive: if there is an annotation within an annotation, + then the variables used therein are on equal footing. Examples:: + + f :: Proxy (a :: k) -> Proxy (b :: j) -> () + -- as if f :: forall k j a b. ... + + g :: Proxy (b :: j) -> Proxy (a :: (Proxy :: (k -> Type) -> Type) Proxy) -> () + -- as if g :: forall j k b a. ... + -- NB: k is in a kind annotation within a kind annotation + - If any of the variables depend on other variables (that is, if some of the variables are *kind* variables), the variables are reordered so that kind variables come before type variables, preserving the left-to-right order as much as possible. That is, GHC performs a - stable topological sort on the variables. + stable topological sort on the variables. Examples:: + + h :: Proxy (a :: (j, k)) -> Proxy (b :: Proxy a) -> () + -- as if h :: forall j k a b. ... - For example: if we have ``bar :: Proxy (a :: (j, k)) -> b``, then - the variables are ordered ``j``, ``k``, ``a``, ``b``. + In this example, all of ``a``, ``j``, and ``k`` are considered kind + variables and will always be placed before ``b``, a lowly type variable. + (Note that ``a`` is used in ``b``\'s kind.) Yet, even though ``a`` appears + lexically before ``j`` and ``k``, ``j`` and ``k`` are quantified first, + because ``a`` depends on ``j`` and ``k``. Note further that ``j`` and ``k`` + are not reordered with respect to each other, even though doing so would + not violate dependency conditions. - Visible type application is available to instantiate only user-specified type variables. This means that in ``data Proxy a = Proxy``, the unmentioned @@ -9492,7 +10641,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 :ghc-flag:`-XRankNTypes` extension +- With the :extension:`RankNTypes` 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)`` @@ -9505,7 +10654,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 :ghc-flag:`-XPartialTypeSignatures` and your + necessary to specify :extension:`PartialTypeSignatures` and your code will not generate a warning informing you of the omitted type. - When printing types with :ghc-flag:`-fprint-explicit-foralls` enabled, @@ -9551,33 +10700,32 @@ Here are the details: if you want the most accurate information with respect to visible type application properties. -- Data constructors declared with GADT syntax follow different rules - for the time being; it is expected that these will be brought in line - with other declarations in the future. The rules for GADT - data constructors are as follows: +- Although GHC supports visible *type* applications, it does not yet support + visible *kind* applications. However, GHC does follow similar rules for + quantifying variables in kind signatures as it does for quantifying type + signatures. For instance: :: - * All kind and type variables are considered specified and available for - visible type application. + type family F (a :: j) (b :: k) :: l + -- F :: forall j k l. j -> k -> l - * Universal variables always come first, in precisely the order they - appear in the type declaration. Universal variables that are - constrained by a GADT return type are not included in the data constructor. - - * Existential variables come next. Their order is determined by a user- - written `forall`; or, if there is none, by taking the left-to-right order - in the data constructor's type and doing a stable topological sort. + In the kind of ``F``, the left-to-right ordering of ``j``, ``k``, and ``l`` + is preserved. .. _implicit-parameters: Implicit parameters =================== -.. ghc-flag:: -XImplicitParams +.. extension:: ImplicitParams + :shortdesc: Enable Implicit Parameters. + Implies :extension:`FlexibleContexts` and :extension:`FlexibleInstances`. + + :since: 6.8.1 Allow definition of functions expecting implicit parameters. Implicit parameters are implemented as described in [Lewis2000]_ and enabled -with the option :ghc-flag:`-XImplicitParams`. (Most of the following, still rather +with the option :extension:`ImplicitParams`. (Most of the following, still rather incomplete, documentation is due to Jeff Lewis.) .. [Lewis2000] @@ -9769,15 +10917,22 @@ a type signature for ``y``, then ``y`` will get type Arbitrary-rank polymorphism =========================== -.. ghc-flag:: -XRankNTypes +.. extension:: RankNTypes + :shortdesc: Enable rank-N types. + Implied by :extension:`ImpredicativeTypes`. - :implies: :ghc-flag:`-XExplicitForAll` + :implies: :extension:`ExplicitForAll` + :since: 6.8.1 Allow types of arbitrary rank. -.. ghc-flag:: -XRank2Types +.. extension:: Rank2Types + :shortdesc: Enable rank-2 types. + Synonym for :extension:`RankNTypes`. - A deprecated alias of :ghc-flag:`-XRankNTypes`. + :since: 6.8.1 + + A deprecated alias of :extension:`RankNTypes`. GHC's type system supports *arbitrary-rank* explicit universal quantification in types. For example, all the following types are legal: :: @@ -9803,8 +10958,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 :ghc-flag:`-XRankNTypes` (which implies -:ghc-flag:`-XExplicitForAll`) enables higher-rank +The language option :extension:`RankNTypes` (which implies +:extension:`ExplicitForAll`) 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: @@ -9819,11 +10974,11 @@ including a type-class context, is legal: - In a pattern type signature (see :ref:`scoped-type-variables`) -The :ghc-flag:`-XRankNTypes` option is also required for any type with a +The :extension:`RankNTypes` option is also required for any type with a ``forall`` or context to the right of an arrow (e.g. ``f :: Int -> forall a. a->a``, or ``g :: Int -> Ord a => a -> a``). Such types are technically rank 1, but are clearly not Haskell-98, and -an extra flag did not seem worth the bother. +an extra extension did not seem worth the bother. In particular, in ``data`` and ``newtype`` declarations the constructor arguments may be polymorphic types of any rank; see examples in @@ -9832,8 +10987,8 @@ monomorphic. This is important because by default GHC will not instantiate type variables to a polymorphic type (:ref:`impredicative-polymorphism`). -The obsolete language options :ghc-flag:`-XPolymorphicComponents` and -:ghc-flag:`-XRank2Types` are synonyms for :ghc-flag:`-XRankNTypes`. They used to +The obsolete language options :extension:`PolymorphicComponents` and +:extension:`Rank2Types` are synonyms for :extension:`RankNTypes`. 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.) @@ -9996,7 +11151,7 @@ the following pairs are equivalent: :: h x y = y in ... -Notice that GHC always adds implicit quantfiers *at the outermost level* +Notice that GHC always adds implicit quantifiers *at the outermost level* of a user-written type; it does *not* find the inner-most possible quantification point. For example: :: @@ -10035,9 +11190,12 @@ so no implicit quantification happens, and the declaration is rejected Impredicative polymorphism ========================== -.. ghc-flag:: -XImpredicativeTypes +.. extension:: ImpredicativeTypes + :shortdesc: Enable impredicative types. + Implies :extension:`RankNTypes`. - :implies: :ghc-flag:`-XRankNTypes` + :implies: :extension:`RankNTypes` + :since: 6.10.1 Allow impredicative polymorphic types. @@ -10055,7 +11213,7 @@ 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 :ghc-flag:`-XImpredicativeTypes`. If it worked, this would mean +enabled with :extension:`ImpredicativeTypes`. 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: :: @@ -10071,13 +11229,13 @@ consistently, or working the same in subsequent releases. See :ghc-wiki:`this wiki page <ImpredicativePolymorphism>` for more details. If you want impredicative polymorphism, the main workaround is to use a -newtype wrapper. The ``id runST`` example can be written using theis +newtype wrapper. The ``id runST`` example can be written using this workaround like this: :: runST :: (forall s. ST s a) -> a id :: forall b. b -> b - nwetype Wrap a = Wrap { unWrap :: (forall s. ST s a) -> a } + newtype Wrap a = Wrap { unWrap :: (forall s. ST s a) -> a } foo :: (forall s. ST s a) -> a foo = unWrap (id (Wrap runST)) @@ -10094,7 +11252,8 @@ written with a leading underscore (e.g., "``_``", "``_foo``", will generate an error message that describes which type is expected at the hole's location, information about the origin of any free type variables, and a list of local bindings that might help fill the hole -with actual code. Typed holes are always enabled in GHC. +and bindings in scope that fit the type of the hole that might help fill +the hole with actual code. Typed holes are always enabled in GHC. The goal of typed holes is to help with writing Haskell code rather than to change the type system. Typed holes can be used to obtain extra @@ -10116,11 +11275,12 @@ will fail with the following error: :: Found hole `_' with type: a Where: `a' is a rigid type variable bound by the type signature for f :: a -> a at hole.hs:1:6 - Relevant bindings include - f :: a -> a (bound at hole.hs:2:1) - x :: a (bound at hole.hs:2:3) In the expression: _ In an equation for `f': f x = _ + Relevant bindings include + x :: a (bound at hole.hs:2:3) + f :: a -> a (bound at hole.hs:2:1) + Valid hole fits include x :: a (bound at hole.hs:2:3) Here are some more details: @@ -10157,13 +11317,36 @@ Here are some more details: .. code-block:: none - Foo.hs:5:15: error: - Found hole: _x :: Bool - Relevant bindings include - p :: Bool (bound at Foo.hs:3:6) - cons :: Bool -> [Bool] (bound at Foo.hs:3:1) - - Foo.hs:5:20: error: + Foo.hs:3:21: error: + Found hole: _x :: Bool + Or perhaps ‘_x’ is mis-spelled, or not in scope + In the first argument of ‘(:)’, namely ‘_x’ + In the second argument of ‘(:)’, namely ‘_x : y’ + In the second argument of ‘(:)’, namely ‘True : _x : y’ + Relevant bindings include + z :: Bool (bound at Foo.hs:3:6) + cons :: Bool -> [Bool] (bound at Foo.hs:3:1) + Valid hole fits include + z :: Bool (bound at mpt.hs:2:6) + otherwise :: Bool + (imported from ‘Prelude’ at mpt.hs:1:8-10 + (and originally defined in ‘GHC.Base’)) + False :: Bool + (imported from ‘Prelude’ at mpt.hs:1:8-10 + (and originally defined in ‘GHC.Types’)) + True :: Bool + (imported from ‘Prelude’ at mpt.hs:1:8-10 + (and originally defined in ‘GHC.Types’)) + maxBound :: forall a. Bounded a => a + with maxBound @Bool + (imported from ‘Prelude’ at mpt.hs:1:8-10 + (and originally defined in ‘GHC.Enum’)) + minBound :: forall a. Bounded a => a + with minBound @Bool + (imported from ‘Prelude’ at mpt.hs:1:8-10 + (and originally defined in ‘GHC.Enum’)) + + Foo.hs:3:26: error: Variable not in scope: y :: [Bool] More information is given for explicit holes (i.e. ones that start @@ -10181,24 +11364,33 @@ Here are some more details: .. code-block:: none - unbound.hs:1:8: - Found hole '_x' with type: a - Where: `a' is a rigid type variable bound by - the inferred type of cons :: [a] at unbound.hs:1:1 - Relevant bindings include cons :: [a] (bound at unbound.hs:1:1) - In the first argument of `(:)', namely `_x' - In the expression: _x : _x - In an equation for `cons': cons = _x : _x - - unbound.hs:1:13: - Found hole '_x' with type: [a] - Arising from: an undeclared identifier `_x' at unbound.hs:1:13-14 - Where: `a' is a rigid type variable bound by - the inferred type of cons :: [a] at unbound.hs:1:1 - Relevant bindings include cons :: [a] (bound at unbound.hs:1:1) - In the second argument of `(:)', namely `_x' - In the expression: _x : _x - In an equation for `cons': cons = _x : _x + unbound.hs:1:8: + Found hole '_x' with type: a + Where: `a' is a rigid type variable bound by + the inferred type of cons :: [a] at unbound.hs:1:1 + In the first argument of `(:)', namely `_x' + In the expression: _x : _x + In an equation for `cons': cons = _x : _x + Relevant bindings include cons :: [a] (bound at unbound.hs:1:1) + + unbound.hs:1:13: + Found hole: _x :: [a] + Where: ‘a’ is a rigid type variable bound by + the inferred type of cons :: [a] + at unbound.hs:3:1-12 + Or perhaps ‘_x’ is mis-spelled, or not in scope + In the second argument of ‘(:)’, namely ‘_x’ + In the expression: _x : _x + In an equation for ‘cons’: cons = _x : _x + Relevant bindings include cons :: [a] (bound at unbound.hs:3:1) + Valid hole fits include + cons :: forall a. [a] + with cons @a + (defined at mpt.hs:3:1) + mempty :: forall a. Monoid a => a + with mempty @[a] + (imported from ‘Prelude’ at mpt.hs:1:8-10 + (and originally defined in ‘GHC.Base’)) Notice the two different types reported for the two different occurrences of ``_x``. @@ -10222,10 +11414,69 @@ Here are some more details: implementation terms, they are reported by the renamer rather than the type checker.) -There's a flag for controlling the amount of context information shown for -typed holes: +- The list of valid hole fits is found by checking which bindings in scope + would fit into the hole. As an example, compiling the following module with + GHC: :: + + import Data.List (inits) + + g :: [String] + g = _ "hello, world" + + yields the errors: + + + .. code-block:: none + + + • Found hole: _ :: [Char] -> [String] + • In the expression: _ + In the expression: _ "hello, world" + In an equation for ‘g’: g = _ "hello, world" + • Relevant bindings include g :: [String] (bound at mpt.hs:6:1) + Valid hole fits include + lines :: String -> [String] + (imported from ‘Prelude’ at mpt.hs:3:8-9 + (and originally defined in ‘base-4.11.0.0:Data.OldList’)) + words :: String -> [String] + (imported from ‘Prelude’ at mpt.hs:3:8-9 + (and originally defined in ‘base-4.11.0.0:Data.OldList’)) + inits :: forall a. [a] -> [[a]] + with inits @Char + (imported from ‘Data.List’ at mpt.hs:4:19-23 + (and originally defined in ‘base-4.11.0.0:Data.OldList’)) + repeat :: forall a. a -> [a] + with repeat @String + (imported from ‘Prelude’ at mpt.hs:3:8-9 + (and originally defined in ‘GHC.List’)) + fail :: forall (m :: * -> *). Monad m => forall a. String -> m a + with fail @[] @String + (imported from ‘Prelude’ at mpt.hs:3:8-9 + (and originally defined in ‘GHC.Base’)) + return :: forall (m :: * -> *). Monad m => forall a. a -> m a + with return @[] @String + (imported from ‘Prelude’ at mpt.hs:3:8-9 + (and originally defined in ‘GHC.Base’)) + pure :: forall (f :: * -> *). Applicative f => forall a. a -> f a + with pure @[] @String + (imported from ‘Prelude’ at mpt.hs:3:8-9 + (and originally defined in ‘GHC.Base’)) + read :: forall a. Read a => String -> a + with read @[String] + (imported from ‘Prelude’ at mpt.hs:3:8-9 + (and originally defined in ‘Text.Read’)) + mempty :: forall a. Monoid a => a + with mempty @([Char] -> [String]) + (imported from ‘Prelude’ at mpt.hs:3:8-9 + (and originally defined in ‘GHC.Base’)) + +There are a few flags for controlling the amount of context information shown +for typed holes: .. ghc-flag:: -fshow-hole-constraints + :shortdesc: Show constraints when reporting typed holes. + :type: dynamic + :category: verbosity When reporting typed holes, also print constraints that are in scope. Example: :: @@ -10237,25 +11488,333 @@ typed holes: .. code-block:: none - show_constraints.hs:4:7: error: - • Found hole: _ :: Bool - • In the expression: _ - In an equation for ‘f’: f x = _ - • Relevant bindings include - x :: a (bound at show_constraints.hs:4:3) - f :: a -> Bool (bound at show_constraints.hs:4:1) - Constraints include - Eq a (from the type signature for: - f :: Eq a => a -> Bool - at show_constraints.hs:3:1-22) + show_constraints.hs:4:7: error: + • Found hole: _ :: Bool + • In the expression: _ + In an equation for ‘f’: f x = _ + • Relevant bindings include + x :: a (bound at show_constraints.hs:4:3) + f :: a -> Bool (bound at show_constraints.hs:4:1) + Constraints include Eq a (from show_constraints.hs:3:1-22) + Valid hole fits include + otherwise :: Bool + False :: Bool + True :: Bool + maxBound :: forall a. Bounded a => a + with maxBound @Bool + minBound :: forall a. Bounded a => a + with minBound @Bool + +.. _typed-hole-valid-hole-fits: + +Valid Hole Fits +------------------- +GHC sometimes suggests valid hole fits for typed holes, which is +configurable by a few flags. + +.. ghc-flag:: -fno-show-valid-hole-fits + :shortdesc: Disables showing a list of valid hole fits for typed holes + in type error messages. + :type: dynamic + :category: verbosity + + :default: off + + This flag can be toggled to turn off the display of valid hole fits + entirely. + +.. ghc-flag:: -fmax-valid-hole-fits=⟨n⟩ + :shortdesc: *default: 6.* Set the maximum number of valid hole fits for + typed holes to display in type error messages. + :type: dynamic + :reverse: -fno-max-valid-hole-fits + :category: verbosity + + :default: 6 + + The list of valid hole fits is limited by displaying up to 6 + hole fits per hole. The number of hole fits shown can be set by this + flag. Turning the limit off with :ghc-flag:`-fno-max-valid-hole-fits` + displays all found hole fits. + + +.. ghc-flag:: -fshow-type-of-hole-fits + :shortdesc: Toggles whether to show the type of the valid hole fits + in the output. + :type: dynamic + :category: verbosity + :reverse: -fno-type-of-hole-fits + + :default: on + + By default, the hole fits show the type of the hole fit. + This can be turned off by the reverse of this flag. + +.. ghc-flag:: -fshow-type-app-of-hole-fits + :shortdesc: Toggles whether to show the type application of the valid + hole fits in the output. + :type: dynamic + :category: verbosity + :reverse: -fno-show-type-app-of-hole-fits + + :default: on + + By default, the hole fits show the type application needed to make + this hole fit fit the type of the hole, e.g. for the hole + ``(_ :: Int -> [Int])``, ``mempty`` is a hole fit with + ``mempty @(Int -> [Int])``. This can be toggled off with + the reverse of this flag. + +.. ghc-flag:: -fshow-docs-of-hole-fits + :shortdesc: Toggles whether to show the documentation of the valid + hole fits in the output. + :type: dynamic + :category: verbosity + :reverse: -fno-show-docs-of-hole-fits + + :default: off + + It can sometime be the case that the name and type of a valid hole + fit is not enough to realize what the fit stands for. This flag + adds the documentation of the fit to the message, if the + documentation is available (and the module from which the function + comes was compiled with the ``-haddock`` flag). + +.. ghc-flag:: -fshow-type-app-vars-of-hole-fits + :shortdesc: Toggles whether to show what type each quantified + variable takes in a valid hole fit. + :type: dynamic + :category: verbosity + :reverse: -fno-show-type-app-vars-of-hole-fits + + :default: on + + By default, the hole fits show the type application needed to make + this hole fit fit the type of the hole, e.g. for the hole + ``(_ :: Int -> [Int])``, ``mempty :: Monoid a => a`` is a hole fit + with ``mempty @(Int -> [Int])``. This flag toggles whether to show + ``a ~ (Int -> [Int])`` instead of ``mempty @(Int -> [Int])`` in the where + clause of the valid hole fit message. + +.. ghc-flag:: -fshow-provenance-of-hole-fits + :shortdesc: Toggles whether to show the provenance of the valid hole fits + in the output. + :type: dynamic + :category: verbosity + :reverse: -fno-show-provenance-of-hole-fits + + :default: on + + By default, each hole fit shows the provenance information of its + hole fit, i.e. where it was bound or defined, and what module + it was originally defined in if it was imported. This can be toggled + off using the reverse of this flag. + + +.. ghc-flag:: -funclutter-valid-hole-fits + :shortdesc: Unclutter the list of valid hole fits by not showing + provenance nor type applications of suggestions. + :type: dynamic + :category: verbosity + + :default: off + + This flag can be toggled to decrease the verbosity of the valid hole fit + suggestions by not showing the provenance nor type application of the + suggestions. + + + +.. _typed-holes-refinement-hole-fits: + +Refinement Hole Fits +~~~~~~~~~~~~~~~~~~~~~~~~ + +When the flag :ghc-flag:`-frefinement-level-hole-fits=⟨n⟩` is set to an +``n`` larger than ``0``, GHC will offer up a list of valid refinement +hole fits, which are valid hole fits that need up to ``n`` levels of +additional refinement to be complete, where each level represents an additional +hole in the hole fit that requires filling in. As an example, consider the +hole in :: + + f :: [Integer] -> Integer + f = _ + +When the refinement level is not set, it will only offer valid hole fits +suggestions: :: + + Valid hole fits include + f :: [Integer] -> Integer + head :: forall a. [a] -> a + with head @Integer + last :: forall a. [a] -> a + with last @Integer + maximum :: forall (t :: * -> *). + Foldable t => + forall a. Ord a => t a -> a + with maximum @[] @Integer + minimum :: forall (t :: * -> *). + Foldable t => + forall a. Ord a => t a -> a + with minimum @[] @Integer + product :: forall (t :: * -> *). + Foldable t => + forall a. Num a => t a -> a + with product @[] @Integer + sum :: forall (t :: * -> *). + Foldable t => + forall a. Num a => t a -> a + with sum @[] @Integer + +However, with :ghc-flag:`-frefinement-level-hole-fits=⟨n⟩` set to e.g. `1`, +it will additionally offer up a list of refinement hole fits, in this case: :: + + Valid refinement hole fits include + foldl1 (_ :: Integer -> Integer -> Integer) + with foldl1 @[] @Integer + where foldl1 :: forall (t :: * -> *). + Foldable t => + forall a. (a -> a -> a) -> t a -> a + foldr1 (_ :: Integer -> Integer -> Integer) + with foldr1 @[] @Integer + where foldr1 :: forall (t :: * -> *). + Foldable t => + forall a. (a -> a -> a) -> t a -> a + const (_ :: Integer) + with const @Integer @[Integer] + where const :: forall a b. a -> b -> a + ($) (_ :: [Integer] -> Integer) + with ($) @'GHC.Types.LiftedRep @[Integer] @Integer + where ($) :: forall a b. (a -> b) -> a -> b + fail (_ :: String) + with fail @((->) [Integer]) @Integer + where fail :: forall (m :: * -> *). + Monad m => + forall a. String -> m a + return (_ :: Integer) + with return @((->) [Integer]) @Integer + where return :: forall (m :: * -> *). Monad m => forall a. a -> m a + (Some refinement hole fits suppressed; + use -fmax-refinement-hole-fits=N or -fno-max-refinement-hole-fits) + +Which shows that the hole could be replaced with e.g. ``foldl1 _``. While not +fixing the hole, this can help users understand what options they have. + +.. ghc-flag:: -frefinement-level-hole-fits=⟨n⟩ + :shortdesc: *default: off.* Sets the level of refinement of the + refinement hole fits, where level ``n`` means that hole fits + of up to ``n`` holes will be considered. + :type: dynamic + :reverse: -fno-refinement-level-hole-fits + :category: verbosity + + :default: off + + The list of valid refinement hole fits is generated by considering + hole fits with a varying amount of additional holes. The amount of + holes in a refinement can be set by this flag. If the flag is set to 0 + or not set at all, no valid refinement hole fits will be suggested. + +.. ghc-flag:: -fabstract-refinement-hole-fits + :shortdesc: *default: off.* Toggles whether refinements where one or more + or more of the holes are abstract are reported. + :type: dynamic + :reverse: -fno-abstract-refinement-hole-fits + :category: verbosity + + :default: off + + Valid list of valid refinement hole fits can often grow large when + the refinement level is ``>= 2``, with holes like ``head _ _`` or + ``fst _ _``, which are valid refinements, but which are unlikely to be + relevant since one or more of the holes are still completely open, in that + neither the type nor kind of those holes are constrained by the proposed + identifier at all. By default, such holes are not reported. By turning this + flag on, such holes are included in the list of valid refinement hole fits. + +.. ghc-flag:: -fmax-refinement-hole-fits=⟨n⟩ + :shortdesc: *default: 6.* Set the maximum number of refinement hole fits + for typed holes to display in type error messages. + :type: dynamic + :reverse: -fno-max-refinement-hole-fits + :category: verbosity + + :default: 6 + + The list of valid refinement hole fits is limited by displaying up to 6 + hole fits per hole. The number of hole fits shown can be set by this + flag. Turning the limit off with :ghc-flag:`-fno-max-refinement-hole-fits` + displays all found hole fits. + +.. ghc-flag:: -fshow-hole-matches-of-hole-fits + :shortdesc: Toggles whether to show the type of the additional holes + in refinement hole fits. + :type: dynamic + :category: verbosity + :reverse: -fno-show-hole-matches-of-hole-fits + + :default: on + + The types of the additional holes in refinement hole fits are displayed + in the output, e.g. ``foldl1 (_ :: a -> a -> a)`` is a refinement + for the hole ``_ :: [a] -> a``. If this flag is toggled off, the output + will display only ``foldl1 _``, which can be used as a direct replacement + for the hole, without requiring ``-XScopedTypeVariables``. + + + + +Sorting Valid Hole Fits +~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +There are currently two ways to sort valid hole fits. +Sorting can be toggled with :ghc-flag:`-fsort-valid-hole-fits` + +.. ghc-flag:: -fno-sort-valid-hole-fits + :shortdesc: Disables the sorting of the list of valid hole fits for typed holes + in type error messages. + :type: dynamic + :category: verbosity + + :default: off + + By default the valid hole fits are sorted to show the most relevant + hole fits at the top of the list of valid hole fits. This can be + toggled off with this flag. + +.. ghc-flag:: -fsort-by-size-hole-fits + :shortdesc: Sort valid hole fits by size. + :type: dynamic + :reverse: -fno-sort-by-size-hole-fits + + :default: on + + Sorts by how big the types the quantified type variables in the type of the + function would have to be in order to match the type of the hole. + + +.. ghc-flag:: -fsort-by-subsumption-hole-fits + :shortdesc: Sort valid hole fits by subsumption. + :type: dynamic + :reverse: -fno-sort-by-subsumption-hole-fits + + :default: off + + An alternative sort. Sorts by checking which hole fits subsume other + hole fits, such that if hole fit a could be used as hole fits for + hole fit b, then b appears before a in the output. It is more precise than + the default sort, but also a lot slower, since a subsumption check has to be + run for each pair of valid hole fits. + .. _partial-type-signatures: Partial Type Signatures ======================= -.. ghc-flag:: -XPartialTypeSignatures +.. extension:: PartialTypeSignatures + :shortdesc: Enable partial type signatures. :since: 7.10.1 @@ -10280,12 +11839,16 @@ 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 :ghc-flag:`-XPartialTypeSignatures` flag is enabled, the +type. When the :extension:`PartialTypeSignatures` extension is enabled, the type-checker will accept the inferred type for each hole, generating warnings instead of errors. Additionally, these warnings can be silenced with the :ghc-flag:`-Wno-partial-type-signatures <-Wpartial-type-signatures>` flag. +However, because GHC must *infer* the type when part of a type is left +out, it is unable to use polymorphic recursion. The same restriction +takes place when the type signature is omitted completely. + .. _pts-syntax: Syntax @@ -10364,7 +11927,8 @@ generalised over, i.e. replaced by a fresh type variable, e.g. Named Wildcards ~~~~~~~~~~~~~~~ -.. ghc-flag:: -XNamedWildCards +.. extension:: NamedWildCards + :shortdesc: Enable named wildcards. :since: 7.10.1 @@ -10409,13 +11973,13 @@ 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 :ghc-flag:`-XNamedWildCards` flag should be +treat them as named wildcards, the :extension:`NamedWildCards` extension should be enabled. The example below demonstrated the effect. :: foo :: _a -> _a foo _ = False -Compiling this program without enabling :ghc-flag:`-XNamedWildCards` produces +Compiling this program without enabling :extension:`NamedWildCards` produces the following error message complaining about the type variable ``_a`` no matching the actual type ``Bool``. @@ -10431,8 +11995,8 @@ no matching the actual type ``Bool``. In an equation for ‘foo’: foo _ = False • Relevant bindings include foo :: _a -> _a (bound at Test.hs:5:1) -Compiling this program with :ghc-flag:`-XNamedWildCards` (as well as -:ghc-flag:`-XPartialTypeSignatures`) enabled produces the following error +Compiling this program with :extension:`NamedWildCards` (as well as +:extension:`PartialTypeSignatures`) enabled produces the following error message reporting the inferred type of the named wildcard ``_a``. .. code-block:: none @@ -10532,6 +12096,15 @@ Anonymous wildcards are also allowed in visible type applications argument to ``wurble``, then you can say ``wurble @_ @Int`` where the first argument is a wildcard. +Standalone ``deriving`` declarations permit the use of a single, +extra-constraints wildcard, like so: :: + + deriving instance _ => Eq (Foo a) + +This denotes a derived ``Eq (Foo a)`` instance where the context is inferred, +in much the same way that ordinary ``deriving`` clauses do. Any other use of +wildcards in a standalone ``deriving`` declaration is prohibited. + In all other contexts, type wildcards are disallowed, and a named wildcard is treated as an ordinary type variable. For example: :: @@ -10561,7 +12134,7 @@ splices. expression splices are supported. - Pattern splices: anonymous and named wildcards can be used in pattern - signatures. Note that :ghc-flag:`-XScopedTypeVariables` has to be enabled + signatures. Note that :extension:`ScopedTypeVariables` has to be enabled to allow pattern signatures. Extra-constraints wildcards are not supported, just like in regular pattern signatures. :: @@ -10599,7 +12172,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 :ghc-flag:`-XDataKinds`) +along with a small type-level language (via :extension:`DataKinds`) for constructing pretty-printed error messages, :: -- ErrorMessage is intended to be used as a kind @@ -10734,6 +12307,29 @@ demonstrates: Prelude> fst x True +Limitations of deferred type errors +----------------------------------- +The errors that can be deferred are: + +- Out of scope term variables +- Equality constraints; e.g. `ord True` gives rise to an insoluble equality constraint `Char ~ Bool`, which can be deferred. +- Type-class and implicit-parameter constraints + +All other type errors are reported immediately, and cannot be deferred; for +example, an ill-kinded type signature, an instance declaration that is +non-terminating or ill-formed, a type-family instance that does not +obey the declared injectivity constraints, etc etc. + +In a few cases, even equality constraints cannot be deferred. Specifically: + +- Kind-equalities cannot be deferred, e.g. :: + + f :: Int Bool -> Char + + This type signature contains a kind error which cannot be deferred. + +- Type equalities under a forall cannot be deferred (c.f. Trac #14605). + .. _template-haskell: Template Haskell @@ -10750,7 +12346,7 @@ page on the GHC Wiki has a wealth of information. You may also consult the :th-ref:`Haddock reference documentation <Language.Haskell.TH.>`. Many changes to the original design are described in `Notes on Template Haskell version -2 <http://research.microsoft.com/~simonpj/papers/meta-haskell/notes2.ps>`__. +2 <https://www.haskell.org/ghc/docs/papers/th2.ps>`__. Not all of these changes are in GHC, however. The first example from that paper is set out below (:ref:`th-example`) @@ -10765,25 +12361,28 @@ GHC. It is not detailed enough to understand Template Haskell; see the Syntax ------ -.. ghc-flag:: -XTemplateHaskell +.. extension:: TemplateHaskell + :shortdesc: Enable Template Haskell. + :implies: :extension:`TemplateHaskellQuotes` :since: 6.0. Typed splices introduced in GHC 7.8.1. - :implies: :ghc-flag:`-XTemplateHaskellQuotes` Enable Template Haskell's splice and quotation syntax. -.. ghc-flag:: -XTemplateHaskellQuotes +.. extension:: TemplateHaskellQuotes + :shortdesc: Enable quotation subset of + :ref:`Template Haskell <template-haskell>`. :since: 8.0.1 Enable only Template Haskell's quotation syntax. 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 +the extension :extension:`TemplateHaskell` to switch these syntactic extensions on. +Alternatively, the :extension:`TemplateHaskellQuotes` extension 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. +The :extension:`TemplateHaskellQuotes` extension is considered safe under +:ref:`safe-haskell` while :extension:`TemplateHaskell` is not. - A splice is written ``$x``, where ``x`` is an identifier, or ``$(...)``, where the "..." is an arbitrary expression. There must be @@ -10911,7 +12510,7 @@ The :ghc-flag:`-XTemplateHaskellQuotes` extension is considered safe under The ``template-haskell`` library provides ``Lift`` instances for many common data types. Furthermore, it is possible to derive ``Lift`` - instances automatically by using the :ghc-flag:`-XDeriveLift` language extension. + instances automatically by using the :extension:`DeriveLift` language extension. See :ref:`deriving-lift` for more information. - You may omit the ``$(...)`` in a top-level declaration splice. Simply @@ -11130,9 +12729,9 @@ non-trivial program, you may be interested in combining this with the :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 :ghc-flag:`-dth-dec-file=⟨file⟩` shows the expansions of all top-level +The flag :ghc-flag:`-dth-dec-file` dumps 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 +for each module `M` being compiled. Note that other types of splices (expressions, types, and patterns) are not shown. Application developers can check this into their repository so that they can grep for identifiers that were defined in Template Haskell. This is similar to using @@ -11151,7 +12750,7 @@ Below is a sample output of :ghc-flag:`-ddump-splices` :: foo :: Int -> Int foo x = (x + 1) -Below is the output of the same sample using :ghc-flag:`-dth-dec-file=⟨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 @@ -11279,7 +12878,10 @@ releases). Template Haskell Quasi-quotation -------------------------------- -.. ghc-flag:: -XQuasiQuotes +.. extension:: QuasiQuotes + :shortdesc: Enable quasiquotation. + + :since: 6.10.1 Enable Template Haskell Quasi-quotation syntax. @@ -11354,13 +12956,13 @@ Here are the salient features single: quasi-quotes; ambiguity with list comprehensions single: list comprehensions; ambiguity with quasi-quotes - :ghc-flag:`-XQuasiQuotes` introduces an unfortunate ambiguity with list + :extension:`QuasiQuotes` introduces an unfortunate ambiguity with list comprehension syntax. Consider the following, :: let x = [v| v <- [0..10]] - Without :ghc-flag:`-XQuasiQuotes` this is parsed as a list comprehension. - With :ghc-flag:`-XQuasiQuotes` this is parsed as a quasi-quote; however, + Without :extension:`QuasiQuotes` this is parsed as a list comprehension. + With :extension:`QuasiQuotes` this is parsed as a quasi-quote; however, this parse will fail due to the lack of a closing ``|]``. See :ghc-ticket:`11679`. @@ -11456,7 +13058,10 @@ Run "main" and here is your output: Arrow notation ============== -.. ghc-flag:: -XArrows +.. extension:: Arrows + :shortdesc: Enable arrow notation extension + + :since: 6.8.1 Enable arrow notation. @@ -11492,7 +13097,7 @@ more details, see - The arrows web page at ``http://www.haskell.org/arrows/`` <http://www.haskell.org/arrows/>`__. -With the :ghc-flag:`-XArrows` flag, GHC supports the arrow notation described in +With the :extension:`Arrows` extension, GHC supports the arrow notation described in the second of these papers, translating it using combinators from the :base-ref:`Control.Arrow.` module. What follows is a brief introduction to the notation; it won't make much @@ -11553,7 +13158,7 @@ A simple example of the new notation is the expression :: We call this a procedure or arrow abstraction. As with a lambda expression, the variable ``x`` is a new variable bound within the ``proc``-expression. It refers to the input to the arrow. In the above -example, ``-<`` is not an identifier but an new reserved symbol used for +example, ``-<`` is not an identifier but a new reserved symbol used for building commands from an expression of arrow type and an expression to be fed as input to that arrow. (The weird look will make more sense later.) It may be read as analogue of application for arrows. The above @@ -11875,16 +13480,16 @@ Bang patterns and Strict Haskell In high-performance Haskell code (e.g. numeric code) eliminating thunks from an inner loop can be a huge win. GHC supports three extensions to allow the programmer to specify -use of strict (call-by-value) evalution rather than lazy (call-by-need) +use of strict (call-by-value) evaluation rather than lazy (call-by-need) evaluation. -- Bang patterns (:ghc-flag:`-XBangPatterns`) makes pattern matching and +- Bang patterns (:extension:`BangPatterns`) makes pattern matching and let bindings stricter. -- Strict data types (:ghc-flag:`-XStrictData`) makes constructor fields +- Strict data types (:extension:`StrictData`) makes constructor fields strict by default, on a per-module basis. -- Strict pattern (:ghc-flag:`-XStrict`) makes all patterns and let bindings +- Strict pattern (:extension:`Strict`) makes all patterns and let bindings strict by default, on a per-module basis. The latter two extensions are simply a way to avoid littering high-performance @@ -11897,7 +13502,10 @@ Bang patterns and strict matching do not affect the type system in any way. Bang patterns ------------- -.. ghc-flag:: -XBangPatterns +.. extension:: BangPatterns + :shortdesc: Enable bang patterns. + + :since: 6.8.1 Allow use of bang pattern syntax. @@ -11993,7 +13601,8 @@ Note the following points: Strict-by-default data types ---------------------------- -.. ghc-flag:: -XStrictData +.. extension:: StrictData + :shortdesc: Enable default strict datatype fields. :since: 8.0.1 @@ -12021,9 +13630,10 @@ The extension only affects definitions in this module. Strict-by-default pattern bindings ---------------------------------- -.. ghc-flag:: -XStrict +.. extension:: Strict + :shortdesc: Make bindings in the current module strict by default. - :implies: :ghc-flag:`-XStrictData` + :implies: :extension:`StrictData` :since: 8.0.1 Make bindings in the current module strict by default. @@ -12048,6 +13658,10 @@ optionally had by adding ``!`` in front of a variable. Adding ``~`` in front of ``x`` gives the regular lazy behavior. + Turning patterns into irrefutable ones requires ``~(~p)`` or ``(~ ~p)`` when ``Strict`` is enabled. + + + - **Let/where bindings** When the user writes :: @@ -12363,7 +13977,7 @@ GHC offers a helping hand here, doing all of this for you. For every use of ``assert`` in the user's source: :: kelvinToC :: Double -> Double - kelvinToC k = assert (k >= 0.0) (k+273.15) + kelvinToC k = assert (k >= 0.0) (k-273.15) GHC will rewrite this to also include the source location where the assertion was made, :: @@ -12396,13 +14010,14 @@ Static pointers .. index:: single: Static pointers -.. ghc-flag:: -XStaticPointers +.. extension:: StaticPointers + :shortdesc: Enable static pointers. :since: 7.10.1 Allow use of static pointer syntax. -The language extension :ghc-flag:`-XStaticPointers` adds a new syntactic form +The language extension :extension:`StaticPointers` 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 @@ -12457,10 +14072,17 @@ While the following definitions are rejected: :: .. note:: While modules loaded in GHCi with the :ghci-cmd:`:load` command may use - :ghc-flag:`-XStaticPointers` and ``static`` expressions, statements + :extension:`StaticPointers` and ``static`` expressions, statements entered on the REPL may not. This is a limitation of GHCi; see :ghc-ticket:`12356` for details. +.. note:: + + The set of keys used for locating static pointers in the Static Pointer + Table is not guaranteed to remain stable for different program binaries. + Or in other words, only processes launched from the same program binary + are guaranteed to use the same set of keys. + .. _typechecking-static-pointers: Static semantics of static pointers @@ -12711,9 +14333,8 @@ Conjunction binds stronger than disjunction. If no ``MINIMAL`` pragma is given in the class declaration, it is just as if a pragma ``{-# MINIMAL op1, op2, ..., opn #-}`` was given, where the -``opi`` are the methods (a) that lack a default method in the class -declaration, and (b) whose name that does not start with an underscore -(c.f. :ghc-flag:`-Wmissing-methods`, :ref:`options-sanity`). +``opi`` are the methods that lack a default method in the class +declaration (c.f. :ghc-flag:`-Wmissing-methods`, :ref:`options-sanity`). This warning can be turned off with the flag :ghc-flag:`-Wno-missing-methods <-Wmissing-methods>`. @@ -13203,19 +14824,6 @@ to be called at type ``T``: However, sometimes there are no such calls, in which case the pragma can be useful. -Obsolete ``SPECIALIZE`` syntax -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -In earlier versions of GHC, it was possible to provide your own -specialised function for a given type: - -:: - - {-# SPECIALIZE hammeredLookup :: [(Int, value)] -> Int -> value = intLookup #-} - -This feature has been removed, as it is now subsumed by the ``RULES`` -pragma (see :ref:`rule-spec`). - .. _specialize-instance-pragma: ``SPECIALIZE`` instance pragma @@ -13284,11 +14892,8 @@ See also the :ghc-flag:`-funbox-strict-fields` flag, which essentially has the effect of adding ``{-# UNPACK #-}`` to every strict constructor field. .. [1] - in fact, UNPACK has no effect without - -O - , for technical reasons (see - tick 5252 - ) + In fact, ``UNPACK`` has no effect without :ghc-flag:`-O`, for technical + reasons (see :ghc-ticket:`5252`). .. _nounpack-pragma: @@ -13370,7 +14975,7 @@ modules. ``COMPLETE`` pragmas should be thought of as asserting a universal truth about a set of patterns and as a result, should not be used to silence context specific incomplete match warnings. -When specifing a ``COMPLETE`` pragma, the result types of all patterns must +When specifying a ``COMPLETE`` pragma, the result types of all patterns must be consistent with each other. This is a sanity check as it would be impossible to match on all the patterns if the types were inconsistent. @@ -13393,6 +14998,49 @@ the user must provide a type signature. :: foo :: [a] -> Int foo T = 5 +.. _multiple-complete-pragmas: + +Disambiguating between multiple ``COMPLETE`` pragmas +---------------------------------------------------- + +What should happen if there are multiple ``COMPLETE`` sets that apply to a +single set of patterns? Consider this example: :: + + data T = MkT1 | MkT2 | MkT2Internal + {-# COMPLETE MkT1, MkT2 #-} + {-# COMPLETE MkT1, MkT2Internal #-} + + f :: T -> Bool + f MkT1 = True + f MkT2 = False + +Which ``COMPLETE`` pragma should be used when checking the coverage of the +patterns in ``f``? If we pick the ``COMPLETE`` set that covers ``MkT1`` and +``MkT2``, then ``f`` is exhaustive, but if we pick the other ``COMPLETE`` set +that covers ``MkT1`` and ``MkT2Internal``, then ``f`` is *not* exhaustive, +since it fails to match ``MkT2Internal``. An intuitive way to solve this +dilemma is to recognize that picking the former ``COMPLETE`` set produces the +fewest number of uncovered pattern clauses, and thus is the better choice. + +GHC disambiguates between multiple ``COMPLETE`` sets based on this rationale. +To make things more formal, when the pattern-match checker requests a set of +constructors for some data type constructor ``T``, the checker returns: + +* The original set of data constructors for ``T`` +* Any ``COMPLETE`` sets of type ``T`` + +GHC then checks for pattern coverage using each of these sets. If any of these +sets passes the pattern coverage checker with no warnings, then we are done. If +each set produces at least one warning, then GHC must pick one of the sets of +warnings depending on how good the results are. The results are prioritized in +this order: + +1. Fewest uncovered clauses +2. Fewest redundant clauses +3. Fewest inaccessible clauses +4. Whether the match comes from the original set of data constructors or from a + ``COMPLETE`` pragma (prioritizing the former over the latter) + .. _overlap-pragma: ``OVERLAPPING``, ``OVERLAPPABLE``, ``OVERLAPS``, and ``INCOHERENT`` pragmas @@ -13440,6 +15088,12 @@ 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 + :shortdesc: Switch on all rewrite rules (including rules generated by + automatic specialisation of overloaded functions). Implied by + :ghc-flag:`-O`. + :type: dynamic + :reverse: -fno-enable-rewrite-rules + :category: optimization Allow the compiler to apply rewrite rules to the source program. @@ -13521,7 +15175,7 @@ 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 :ghc-flag:`-XScopedTypeVariables` is automatically enabled; see + extension :extension:`ScopedTypeVariables` is automatically enabled; see :ref:`scoped-type-variables`. - Like other pragmas, ``RULE`` pragmas are always checked for scope errors, @@ -13686,7 +15340,7 @@ 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: :: instance C Bool where - op x y = opBool + op = opBool opBool :: Bool -> Bool -> Bool {-# NOINLINE [1] opBool #-} @@ -13889,8 +15543,8 @@ programming <#generic-programming>`__. Generic programming =================== -Using a combination of :ghc-flag:`-XDeriveGeneric`, -:ghc-flag:`-XDefaultSignatures`, and :ghc-flag:`-XDeriveAnyClass`, you can +Using a combination of :extension:`DeriveGeneric`, +:extension:`DefaultSignatures`, and :extension:`DeriveAnyClass`, you can easily do datatype-generic programming using the :base-ref:`GHC.Generics.` framework. This section gives a very brief overview of how to do it. @@ -13910,7 +15564,7 @@ Haskell datatypes: :: -- | Unit: used for constructors without arguments data U1 p = U1 - -- | Constants, additional parameters and recursion of kind * + -- | Constants, additional parameters and recursion of kind Type newtype K1 i c p = K1 { unK1 :: c } -- | Meta-information (constructor names, etc.) @@ -13929,25 +15583,33 @@ datatypes and their internal representation as a sum-of-products: :: class Generic a where -- Encode the representation of a user datatype - type Rep a :: * -> * + type Rep a :: Type -> Type -- Convert from the datatype to its representation from :: a -> (Rep a) x -- Convert from the representation to the datatype to :: (Rep a) x -> a - class Generic1 (f :: k -> *) where - type Rep1 f :: k -> * + class Generic1 (f :: k -> Type) where + type Rep1 f :: k -> Type from1 :: f a -> Rep1 f a to1 :: Rep1 f a -> f a ``Generic1`` is used for functions that can only be defined over type containers, such as ``map``. Note that ``Generic1`` ranges over types of kind -``* -> *`` by default, but if the :ghc-flag:`-XPolyKinds` extension is enabled, -then it can range of types of kind ``k -> *``, for any kind ``k``. +``Type -> Type`` by default, but if the :extension:`PolyKinds` extension is +enabled, then it can range of types of kind ``k -> Type``, for any kind ``k``. + +.. extension:: DeriveGeneric + :shortdesc: Enable deriving for the Generic class. + + :since: 7.2.1 + + Allow automatic deriving of instances for the ``Generic`` typeclass. + Instances of these classes can be derived by GHC with the -:ghc-flag:`-XDeriveGeneric` extension, and are necessary to be able to define +:extension:`DeriveGeneric` extension, and are necessary to be able to define generic instances automatically. For example, a user-defined datatype of trees :: @@ -14099,7 +15761,7 @@ write: :: The default method for ``put`` is then used, corresponding to the generic implementation of serialization. If you are using -:ghc-flag:`-XDeriveAnyClass`, the same instance is generated by simply attaching +:extension:`DeriveAnyClass`, 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>`__ @@ -14126,8 +15788,8 @@ Roles .. index:: single: roles -Using :ghc-flag:`-XGeneralizedNewtypeDeriving` -(:ref:`generalized-newtype-deriving`), a programmer can take existing +Using :extension:`GeneralizedNewtypeDeriving` +(:ref:`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 following: @@ -14213,8 +15875,8 @@ Here are some examples: :: The type ``Simple`` has its parameter at role representational, which is generally the most common case. ``Simple Age`` would have the same representation as ``Simple Int``. The type ``Complex``, on the other -hand, has its parameter at role nominal, because ``Simple Age`` and -``Simple Int`` are *not* the same. Lastly, ``Phant Age`` and +hand, has its parameter at role nominal, because ``Complex Age`` and +``Complex Int`` are *not* the same. Lastly, ``Phant Age`` and ``Phant Bool`` have the same representation, even though ``Age`` and ``Bool`` are unrelated. @@ -14267,7 +15929,8 @@ role nominal for ``b``. Role annotations ---------------- -.. ghc-flag:: -XRoleAnnotations +.. extension:: RoleAnnotations + :shortdesc: Enable role annotations. :since: 7.8.1 @@ -14287,7 +15950,7 @@ a pointer to a ``Bool``. But, that's not at all how we want to use type role Ptr representational data Ptr a = Ptr Addr# -The ``type role`` (enabled with :ghc-flag:`-XRoleAnnotations`) declaration +The ``type role`` (enabled with :extension:`RoleAnnotations`) 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 @@ -14307,7 +15970,7 @@ This would be done with a declaration :: 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 :ghc-flag:`-XIncoherentInstances` to allow +it is necessary to also specify :extension:`IncoherentInstances` to allow non-nominal roles for classes. The other place where role annotations may be necessary are in @@ -14354,28 +16017,67 @@ HasCallStack ``GHC.Stack.HasCallStack`` is a lightweight method of obtaining a partial call-stack at any point in the program. -A function can request its call-site with the ``HasCallStack`` constraint. -For example, we can define :: +A function can request its call-site with the ``HasCallStack`` constraint +and access it as a Haskell value by using ``callStack``. + +One can then use functions from ``GHC.Stack`` to inspect or pretty +print (as is done in ``f`` below) the call stack. + + f :: HasCallStack => IO () + f = putStrLn (prettyCallStack callStack) + + g :: HasCallStack => IO () + g = f + +Evaluating ``f`` directly shows a call stack with a single entry, +while evaluating ``g``, which also requests its call-site, shows +two entries, one for each computation "annotated" with +``HasCallStack``. + +.. code-block:: none + + ghci> f + CallStack (from HasCallStack): + f, called at <interactive>:19:1 in interactive:Ghci1 + ghci> g + CallStack (from HasCallStack): + f, called at <interactive>:17:5 in main:Main + g, called at <interactive>:20:1 in interactive:Ghci2 + +The ``error`` function from the Prelude supports printing the call stack that +led to the error in addition to the usual error message: + +.. code-block:: none + + ghci> error "bad" + *** Exception: bad + CallStack (from HasCallStack): + error, called at <interactive>:25:1 in interactive:Ghci5 - errorWithCallStack :: HasCallStack => String -> a +The call stack here consists of a single entry, pinpointing the source +of the call to ``error``. However, by annotating several computations +with ``HasCallStack``, figuring out the exact circumstances and sequences +of calls that lead to a call to ``error`` becomes a lot easier, as demonstrated +with the simple example below. :: -as a variant of ``error`` that will get its call-site (as of GHC 8.0, -``error`` already gets its call-site, but let's assume for the sake of -demonstration that it does not). We can access the call-stack inside -``errorWithCallStack`` with ``GHC.Stack.callStack``. :: + f :: HasCallStack => IO () + f = error "bad bad bad" - errorWithCallStack :: HasCallStack => String -> a - errorWithCallStack msg = error (msg ++ "\n" ++ prettyCallStack callStack) + g :: HasCallStack => IO () + g = f -Thus, if we call ``errorWithCallStack`` we will get a formatted call-stack -alongside our error message. + h :: HasCallStack => IO () + h = g .. code-block:: none - ghci> errorWithCallStack "die" - *** Exception: die + ghci> h + *** Exception: bad bad bad CallStack (from HasCallStack): - errorWithCallStack, called at <interactive>:2:1 in interactive:Ghci1 + error, called at call-stack.hs:4:5 in main:Main + f, called at call-stack.hs:7:5 in main:Main + g, called at call-stack.hs:10:5 in main:Main + h, called at <interactive>:28:1 in interactive:Ghci1 The ``CallStack`` will only extend as far as the types allow it, for example :: diff --git a/docs/users_guide/index.rst b/docs/users_guide/index.rst index b57e37b018..c20aec7e56 100644 --- a/docs/users_guide/index.rst +++ b/docs/users_guide/index.rst @@ -12,8 +12,8 @@ Contents: license intro - 8.2.1-notes - 8.4.1-notes + 8.6.1-notes + 8.8.1-notes ghci runghc usage diff --git a/docs/users_guide/packages.rst b/docs/users_guide/packages.rst index c728acbd08..632162f6c8 100644 --- a/docs/users_guide/packages.rst +++ b/docs/users_guide/packages.rst @@ -128,6 +128,9 @@ command (see :ref:`package-management`): The GHC command line options that control packages are: .. ghc-flag:: -package ⟨pkg⟩ + :shortdesc: Expose package ⟨pkg⟩ + :type: dynamic + :category: This option causes the installed package ⟨pkg⟩ to be exposed. The package ⟨pkg⟩ can be specified in full with its version number (e.g. @@ -177,6 +180,9 @@ The GHC command line options that control packages are: $ ghc -o myprog Foo.hs Main.hs -package network .. ghc-flag:: -package-id ⟨unit-id⟩ + :shortdesc: Expose package by id ⟨unit-id⟩ + :type: dynamic + :category: Exposes a package like :ghc-flag:`-package ⟨pkg⟩`, but the package is named by its unit ID (i.e. the value of ``id`` in its entry in the installed @@ -187,6 +193,9 @@ The GHC command line options that control packages are: renaming described in :ref:`package-thinning-and-renaming`. .. ghc-flag:: -hide-all-packages + :shortdesc: Hide all packages by default + :type: dynamic + :category: Ignore the exposed flag on installed packages, and hide them all by default. If you use this flag, then any packages you require @@ -199,6 +208,9 @@ The GHC command line options that control packages are: ``-hide-all-packages`` flag to GHC, for exactly this reason. .. ghc-flag:: -hide-package ⟨pkg⟩ + :shortdesc: Hide package ⟨pkg⟩ + :type: dynamic + :category: This option does the opposite of :ghc-flag:`-package ⟨pkg⟩`: it causes the specified package to be hidden, which means that none of its modules @@ -209,6 +221,9 @@ The GHC command line options that control packages are: exposed package. .. ghc-flag:: -ignore-package ⟨pkg⟩ + :shortdesc: Ignore package ⟨pkg⟩ + :type: dynamic + :category: Causes the compiler to behave as if package ⟨pkg⟩, and any packages that depend on ⟨pkg⟩, are not installed at all. @@ -220,11 +235,18 @@ The GHC command line options that control packages are: :ghc-flag:`-ignore-package ⟨pkg⟩` flag can be useful. .. ghc-flag:: -no-auto-link-packages + :shortdesc: Don't automatically link in the base and rts packages. + :type: dynamic + :category: By default, GHC will automatically link in the ``base`` and ``rts`` packages. This flag disables that behaviour. .. ghc-flag:: -this-unit-id ⟨unit-id⟩ + :shortdesc: Compile to be part of unit (i.e. package) + ⟨unit-id⟩ + :type: dynamic + :category: Tells GHC that the module being compiled forms part of unit ID ⟨unit-id⟩; internally, these keys are used to determine type equality @@ -234,6 +256,10 @@ The GHC command line options that control packages are: way in later releases. .. ghc-flag:: -trust ⟨pkg⟩ + :shortdesc: Expose package ⟨pkg⟩ and set it to be trusted + :type: dynamic + :category: + :noindex: This option causes the install package ⟨pkg⟩ to be both exposed and trusted by GHC. This command functions in a very similar way @@ -242,6 +268,10 @@ The GHC command line options that control packages are: package database. (see :ref:`safe-haskell`). .. ghc-flag:: -distrust ⟨pkg⟩ + :shortdesc: Expose package ⟨pkg⟩ and set it to be distrusted + :type: dynamic + :category: + :noindex: This option causes the install package ⟨pkg⟩ to be both exposed and distrusted by GHC. This command functions in a very similar way to the @@ -249,7 +279,11 @@ The GHC command line options that control packages are: packages to be distrusted by GHC, regardless of the contents of the package database. (see :ref:`safe-haskell`). -.. ghc-flag:: -distrust-all +.. ghc-flag:: -distrust-all-packages + :shortdesc: Distrust all packages by default + :type: dynamic + :category: + :noindex: Ignore the trusted flag on installed packages, and distrust them by default. If you use this flag and Safe Haskell then any packages you @@ -397,19 +431,31 @@ You can control GHC's package database stack using the following options: .. ghc-flag:: -package-db ⟨file⟩ + :shortdesc: Add ⟨file⟩ to the package db stack. + :type: dynamic + :category: Add the package database ⟨file⟩ on top of the current stack. .. ghc-flag:: -no-global-package-db + :shortdesc: Remove the global package db from the stack. + :type: dynamic + :category: Remove the global package database from the package database stack. .. ghc-flag:: -no-user-package-db + :shortdesc: Remove the user's package db from the stack. + :type: dynamic + :category: Prevent loading of the user's local package database in the initial stack. .. ghc-flag:: -clear-package-db + :shortdesc: Clear the package db stack. + :type: dynamic + :category: Reset the current package database stack. This option removes every previously specified package database (including those read from the @@ -417,6 +463,9 @@ options: stack. .. ghc-flag:: -global-package-db + :shortdesc: Add the global package db to the stack. + :type: dynamic + :category: Add the global package database on top of the current stack. This option can be used after :ghc-flag:`-no-global-package-db` to specify the @@ -424,6 +473,9 @@ options: loaded. .. ghc-flag:: -user-package-db + :shortdesc: Add the user's package db to the stack. + :type: dynamic + :category: Add the user's package database on top of the current stack. This option can be used after :ghc-flag:`-no-user-package-db` to specify the @@ -521,6 +573,9 @@ 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. .. ghc-flag:: -package-env ⟨file⟩|⟨name⟩ + :shortdesc: Use the specified package environment. + :type: dynamic + :category: Use the package environment in ⟨file⟩, or in ``$HOME/.ghc/arch-os-version/environments/⟨name⟩`` @@ -1001,7 +1056,7 @@ extra indirection). .. code-block:: sh - ghc -shared libHSfoo-1.0-ghcGHCVersion.so A.o B.o C.o + ghc -shared -dynamic -o libHSfoo-1.0-ghcGHCVersion.so A.o B.o C.o Using GHC's version number in the shared object name allows different library versions compiled by different GHC versions to be installed diff --git a/docs/users_guide/parallel.rst b/docs/users_guide/parallel.rst index f334e1be38..fea8fa4a57 100644 --- a/docs/users_guide/parallel.rst +++ b/docs/users_guide/parallel.rst @@ -156,13 +156,3 @@ from the ``Control.Parallel.Strategies`` module in the `parallel package <http://hackage.haskell.org/package/parallel>`__. This module builds functionality around ``par``, expressing more elaborate patterns of parallel computation, such as parallel ``map``. - -.. _dph: - -Data Parallel Haskell ---------------------- - -GHC includes experimental support for Data Parallel Haskell (DPH). This -code is highly unstable and is only provided as a technology preview. -More information can be found on the corresponding -`DPH wiki page <http://www.haskell.org/haskellwiki/GHC/Data_Parallel_Haskell>`__. diff --git a/docs/users_guide/phases.rst b/docs/users_guide/phases.rst index cefaa8a6d1..531f8c0bf6 100644 --- a/docs/users_guide/phases.rst +++ b/docs/users_guide/phases.rst @@ -18,46 +18,79 @@ following options allow you to change the external program used for a given compilation phase: .. ghc-flag:: -pgmL ⟨cmd⟩ + :shortdesc: Use ⟨cmd⟩ as the literate pre-processor + :type: dynamic + :category: phase-programs Use ⟨cmd⟩ as the literate pre-processor. .. ghc-flag:: -pgmP ⟨cmd⟩ + :shortdesc: Use ⟨cmd⟩ as the C pre-processor (with ``-cpp`` only) + :type: dynamic + :category: phase-programs Use ⟨cmd⟩ as the C pre-processor (with ``-cpp`` only). .. ghc-flag:: -pgmc ⟨cmd⟩ + :shortdesc: Use ⟨cmd⟩ as the C compiler + :type: dynamic + :category: phase-programs Use ⟨cmd⟩ as the C compiler. .. ghc-flag:: -pgmlo ⟨cmd⟩ + :shortdesc: Use ⟨cmd⟩ as the LLVM optimiser + :type: dynamic + :category: phase-programs Use ⟨cmd⟩ as the LLVM optimiser. .. ghc-flag:: -pgmlc ⟨cmd⟩ + :shortdesc: Use ⟨cmd⟩ as the LLVM compiler + :type: dynamic + :category: phase-programs Use ⟨cmd⟩ as the LLVM compiler. .. ghc-flag:: -pgms ⟨cmd⟩ + :shortdesc: Use ⟨cmd⟩ as the splitter + :type: dynamic + :category: phase-programs Use ⟨cmd⟩ as the splitter. .. ghc-flag:: -pgma ⟨cmd⟩ + :shortdesc: Use ⟨cmd⟩ as the assembler + :type: dynamic + :category: phase-programs Use ⟨cmd⟩ as the assembler. .. ghc-flag:: -pgml ⟨cmd⟩ + :shortdesc: Use ⟨cmd⟩ as the linker + :type: dynamic + :category: phase-programs Use ⟨cmd⟩ as the linker. .. ghc-flag:: -pgmdll ⟨cmd⟩ + :shortdesc: Use ⟨cmd⟩ as the DLL generator + :type: dynamic + :category: phase-programs Use ⟨cmd⟩ as the DLL generator. .. ghc-flag:: -pgmF ⟨cmd⟩ + :shortdesc: Use ⟨cmd⟩ as the pre-processor (with ``-F`` only) + :type: dynamic + :category: phase-programs Use ⟨cmd⟩ as the pre-processor (with ``-F`` only). .. ghc-flag:: -pgmwindres ⟨cmd⟩ + :shortdesc: Use ⟨cmd⟩ as the program for embedding manifests on Windows. + :type: dynamic + :category: phase-programs Use ⟨cmd⟩ as the program to use for embedding manifests on Windows. Normally this is the program ``windres``, which is supplied with a @@ -65,10 +98,16 @@ given compilation phase: :ref:`options-linker`. .. ghc-flag:: -pgmlibtool ⟨cmd⟩ + :shortdesc: Use ⟨cmd⟩ as the command for libtool (with ``-staticlib`` only). + :type: dynamic + :category: phase-programs Use ⟨cmd⟩ as the libtool command (when using ``-staticlib`` only). .. ghc-flag:: -pgmi ⟨cmd⟩ + :shortdesc: Use ⟨cmd⟩ as the external interpreter command. + :type: dynamic + :category: phase-programs Use ⟨cmd⟩ as the external interpreter command (see: :ref:`external-interpreter`). Default: ``ghc-iserv-prof`` if @@ -87,48 +126,81 @@ Options can be forced through to a particular compilation phase, using the following flags: .. ghc-flag:: -optL ⟨option⟩ + :shortdesc: pass ⟨option⟩ to the literate pre-processor + :type: dynamic + :category: phase-options Pass ⟨option⟩ to the literate pre-processor .. ghc-flag:: -optP ⟨option⟩ + :shortdesc: pass ⟨option⟩ to cpp (with ``-cpp`` only) + :type: dynamic + :category: phase-options Pass ⟨option⟩ to CPP (makes sense only if ``-cpp`` is also on). .. ghc-flag:: -optF ⟨option⟩ + :shortdesc: pass ⟨option⟩ to the custom pre-processor + :type: dynamic + :category: phase-options Pass ⟨option⟩ to the custom pre-processor (see :ref:`pre-processor`). .. ghc-flag:: -optc ⟨option⟩ + :shortdesc: pass ⟨option⟩ to the C compiler + :type: dynamic + :category: phase-options Pass ⟨option⟩ to the C compiler. .. ghc-flag:: -optlo ⟨option⟩ + :shortdesc: pass ⟨option⟩ to the LLVM optimiser + :type: dynamic + :category: phase-options Pass ⟨option⟩ to the LLVM optimiser. .. ghc-flag:: -optlc ⟨option⟩ + :shortdesc: pass ⟨option⟩ to the LLVM compiler + :type: dynamic + :category: phase-options Pass ⟨option⟩ to the LLVM compiler. .. ghc-flag:: -opta ⟨option⟩ + :shortdesc: pass ⟨option⟩ to the assembler + :type: dynamic + :category: phase-options Pass ⟨option⟩ to the assembler. .. ghc-flag:: -optl ⟨option⟩ + :shortdesc: pass ⟨option⟩ to the linker + :type: dynamic + :category: phase-options Pass ⟨option⟩ to the linker. .. ghc-flag:: -optdll ⟨option⟩ + :shortdesc: pass ⟨option⟩ to the DLL generator + :type: dynamic + :category: phase-options Pass ⟨option⟩ to the DLL generator. .. ghc-flag:: -optwindres ⟨option⟩ + :shortdesc: pass ⟨option⟩ to ``windres``. + :type: dynamic + :category: phase-options Pass ⟨option⟩ to ``windres`` when embedding manifests on Windows. See ``-fno-embed-manifest`` in :ref:`options-linker`. .. ghc-flag:: -opti ⟨option⟩ + :shortdesc: pass ⟨option⟩ to the interpreter sub-process. + :type: dynamic + :category: phase-options Pass ⟨option⟩ to the interpreter sub-process (see :ref:`external-interpreter`). A common use for this is to pass @@ -149,12 +221,20 @@ to GHC's runtime system you can enclose them in ``+RTS ... -RTS`` (see Options affecting the C pre-processor ------------------------------------- +.. extension:: CPP + :shortdesc: Enable the C preprocessor. + + :since: 6.8.1 + .. index:: single: pre-processing: cpp single: C pre-processor options single: cpp, pre-processing with .. ghc-flag:: -cpp + :shortdesc: Run the C pre-processor on Haskell source files + :type: dynamic + :category: cpp 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 @@ -162,6 +242,10 @@ Options affecting the C pre-processor really shouldn't need it. .. ghc-flag:: -D⟨symbol⟩[=⟨value⟩] + :shortdesc: Define a symbol in the C pre-processor + :type: dynamic + :reverse: -U⟨symbol⟩ + :category: cpp Define macro ⟨symbol⟩ in the usual way. When no value is given, the value is taken to be ``1``. For instance, ``-DUSE_MYLIB`` is equivalent to @@ -174,10 +258,16 @@ Options affecting the C pre-processor this case use the ``-optc-Dfoo`` hack… (see :ref:`forcing-options-through`). .. ghc-flag:: -U⟨symbol⟩ + :shortdesc: Undefine a symbol in the C pre-processor + :type: dynamic + :category: cpp Undefine macro ⟨symbol⟩ in the usual way. .. ghc-flag:: -I⟨dir⟩ + :shortdesc: Add ⟨dir⟩ to the directory search list for ``#include`` files + :type: dynamic + :category: cpp Specify a directory in which to look for ``#include`` files, in the usual C way. @@ -363,6 +453,10 @@ Options affecting a Haskell pre-processor single: pre-processor options .. ghc-flag:: -F + :shortdesc: Enable the use of a :ref:`pre-processor <pre-processor>` + (set with :ghc-flag:`-pgmF ⟨cmd⟩`) + :type: dynamic + :category: phases A custom pre-processor is run over your Haskell source file only if the ``-F`` option is given. @@ -412,11 +506,19 @@ Options affecting code generation --------------------------------- .. ghc-flag:: -fasm + :shortdesc: Use the :ref:`native code generator <native-code-gen>` + :type: dynamic + :reverse: -fllvm + :category: codegen Use GHC's :ref:`native code generator <native-code-gen>` rather than compiling via LLVM. ``-fasm`` is the default. .. ghc-flag:: -fllvm + :shortdesc: Compile using the :ref:`LLVM code generator <llvm-code-gen>` + :type: dynamic + :reverse: -fasm + :category: codegen Compile via :ref:`LLVM <llvm-code-gen>` instead of using the native code generator. This will generally take slightly longer than the @@ -425,12 +527,23 @@ Options affecting code generation via LLVM requires LLVM's :command:`opt` and :command:`llc` executables to be in :envvar:`PATH`. + .. note:: + + Note that this GHC release expects an LLVM version in the |llvm-version| + release series. + .. ghc-flag:: -fno-code + :shortdesc: Omit code generation + :type: dynamic + :category: codegen Omit code generation (and all later phases) altogether. This is useful if you're only interested in type checking code. .. ghc-flag:: -fwrite-interface + :shortdesc: Always write interface files + :type: dynamic + :category: codegen Always write interface files. GHC will normally write interface files automatically, but this flag is useful with :ghc-flag:`-fno-code`, @@ -439,12 +552,18 @@ Options affecting code generation compiling dependencies. .. ghc-flag:: -fobject-code + :shortdesc: Generate object code + :type: dynamic + :category: codegen 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. .. ghc-flag:: -fbyte-code + :shortdesc: Generate byte-code + :type: dynamic + :category: codegen Generate byte-code instead of object-code. This is the default in GHCi. Byte-code can currently only be used in the interactive @@ -452,26 +571,54 @@ Options affecting code generation reversing the effect of :ghc-flag:`-fobject-code`. .. ghc-flag:: -fPIC + :shortdesc: Generate position-independent code (where available) + :type: dynamic + :category: codegen 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. +.. ghc-flag:: -fexternal-dynamic-refs + :shortdesc: Generate code for linking against dynamic libraries + :type: dynamic + :category: codegen + + When generating code, assume that entities imported from a + different module might be dynamically linked. This flag is enabled + automatically by :ghc-flag:`-dynamic`. + +.. ghc-flag:: -fPIE + :shortdesc: Generate code for a position-independent executable (where available) + :type: dynamic + :category: codegen + + Generate code in such a way to be linkable into a position-independent + executable This currently works on Linux x86 and x86-64. On Windows, + position-independent code is never used so the flag is a no-op on that + platform. To link the final executable use :ghc-flag:`-pie`. + .. ghc-flag:: -dynamic + :shortdesc: Build dynamically-linked object files and executables + :type: dynamic + :category: codegen :noindex: - When generating code, assume that entities imported from a different - package will be dynamically linked. This can reduce code size - tremendously, but may slow-down cross-package calls of non-inlined - functions. There can be some complications combining :ghc-flag:`-shared` - with this flag relating to linking in the RTS under Linux. See - :ghc-ticket:`10352`. + Build code for dynamic linking. This can reduce code size + tremendously, but may slow-down cross-module calls of non-inlined + functions. There can be some complications combining + :ghc-flag:`-shared` with this flag relating to linking in the RTS + under Linux. See :ghc-ticket:`10352`. Note that using this option when linking causes GHC to link against shared libraries. .. ghc-flag:: -dynamic-too + :shortdesc: Build dynamic object files *as well as* static object files + during compilation + :type: dynamic + :category: codegen Generates both dynamic and static object files in a single run of GHC. This option is functionally equivalent to running GHC twice, @@ -499,6 +646,9 @@ user-supplied, GHC-supplied, and system-supplied (``-lm`` math library, for example). .. ghc-flag:: -l ⟨lib⟩ + :shortdesc: Link in library ⟨lib⟩ + :type: dynamic + :category: linking Link in the ⟨lib⟩ library. On Unix systems, this will be in a file called :file:`lib{lib}.a` or :file:`lib{lib}.so` which resides somewhere on the @@ -518,12 +668,18 @@ for example). and pass ``-no-hs-main``. See also :ref:`using-own-main`. .. ghc-flag:: -c + :shortdesc: Stop after generating object (``.o``) file + :type: mode + :category: linking 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. .. ghc-flag:: -package ⟨name⟩ + :shortdesc: Expose package ⟨pkg⟩ + :type: dynamic + :category: linking If you are using a Haskell "package" (see :ref:`packages`), don't forget to add the relevant ``-package`` option when linking the @@ -532,6 +688,10 @@ for example). result in several pages of link errors. .. ghc-flag:: -framework ⟨name⟩ + :shortdesc: On Darwin/OS X/iOS only, link in the framework ⟨name⟩. This + option corresponds to the ``-framework`` option for Apple's Linker. + :type: dynamic + :category: linking On Darwin/OS X/iOS only, link in the framework ⟨name⟩. This option corresponds to the ``-framework`` option for Apple's Linker. Please @@ -541,17 +701,31 @@ for example). for example, you'd use ``-framework Carbon``. .. ghc-flag:: -staticlib + :shortdesc: Generate a standalone static library (as opposed to an + executable). This is useful when cross compiling. The + library together with all its dependencies ends up in in a + single static library that can be linked against. + :type: dynamic + :category: linking Link all passed files into a static library suitable for linking. To control the name, use the :ghc-flag:`-o ⟨file⟩` option as usual. The default name is ``liba.a``. .. ghc-flag:: -L ⟨dir⟩ + :shortdesc: Add ⟨dir⟩ to the list of directories searched for libraries + :type: dynamic + :category: linking Where to find user-supplied libraries… Prepend the directory ⟨dir⟩ to the library directories path. .. ghc-flag:: -framework-path ⟨dir⟩ + :shortdesc: On Darwin/OS X/iOS only, add ⟨dir⟩ to the list of directories + searched for frameworks. This option corresponds to the ``-F`` + option for Apple's Linker. + :type: dynamic + :category: linking On Darwin/OS X/iOS only, prepend the directory ⟨dir⟩ to the framework directories path. This option corresponds to the ``-F`` @@ -559,6 +733,9 @@ for example). GHC). .. ghc-flag:: -split-objs + :shortdesc: Split objects (for libraries) + :type: dynamic + :category: linking Tell the linker to split the single object file that would normally be generated into multiple object files, one per top-level Haskell @@ -571,6 +748,9 @@ for example). larger. We use this feature for building GHC's libraries. .. ghc-flag:: -split-sections + :shortdesc: Split sections for link-time dead-code stripping + :type: dynamic + :category: linking 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 @@ -583,11 +763,17 @@ for example). files are about 30% smaller than with :ghc-flag:`-split-objs`. .. ghc-flag:: -static + :shortdesc: Use static Haskell libraries + :type: dynamic + :category: linking Tell the linker to avoid shared Haskell libraries, if possible. This is the default. .. ghc-flag:: -dynamic + :shortdesc: Build dynamically-linked object files and executables + :type: dynamic + :category: linking This flag tells GHC to link against shared Haskell libraries. This flag only affects the selection of dependent libraries, not the form @@ -598,6 +784,9 @@ for example). above). .. ghc-flag:: -shared + :shortdesc: Generate a shared library (as opposed to an executable) + :type: dynamic + :category: linking Instead of creating an executable, GHC produces a shared object with this linker flag. Depending on the operating system target, this @@ -618,12 +807,18 @@ for example). when linked against this package. See shared object name mangling. .. ghc-flag:: -dynload + :shortdesc: Selects one of a number of modes for finding shared libraries at runtime. + :type: dynamic + :category: linking 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. .. ghc-flag:: -main-is ⟨thing⟩ + :shortdesc: Set main module and function + :type: dynamic + :category: linking .. index:: single: specifying your own main function @@ -655,6 +850,9 @@ for example). :ghc-flag:`-fforce-recomp` flag. .. ghc-flag:: -no-hs-main + :shortdesc: Don't assume this program contains ``main`` + :type: dynamic + :category: linking .. index:: single: linking Haskell libraries with foreign code @@ -676,14 +874,18 @@ for example). ``Main`` module present (normally the compiler will not attempt linking when there is no ``Main``). - The flags :ghc-flag:`-rtsopts[=⟨none|some|all⟩]` and + The flags :ghc-flag:`-rtsopts[=⟨none|some|all|ignore|ignoreAll⟩]` and :ghc-flag:`-with-rtsopts=⟨opts⟩` 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 :ghc-flag:`-rtsopts[=⟨none|some|all⟩]` and + how to get the effect of + :ghc-flag:`-rtsopts[=⟨none|some|all|ignore|ignoreAll⟩]` and :ghc-flag:`-with-rtsopts=⟨opts⟩` when using your own ``main``. .. ghc-flag:: -debug + :shortdesc: Use the debugging runtime + :type: dynamic + :category: linking Link the program with a debugging version of the runtime system. The debugging runtime turns on numerous assertions and sanity checks, @@ -691,6 +893,9 @@ for example). (run the program with ``+RTS -?`` to see a list). .. ghc-flag:: -threaded + :shortdesc: Use the threaded runtime + :type: dynamic + :category: linking Link the program with the "threaded" version of the runtime system. The threaded runtime system is so-called because it manages multiple @@ -704,9 +909,8 @@ for example). The threaded runtime system provides the following benefits: - It enables the :rts-flag:`-N ⟨x⟩` RTS option to be used, - which allows threads to run in parallelparallelism on a - multiprocessormultiprocessorSMP or multicoremulticore machine. - See :ref:`using-smp`. + which allows threads to run in parallel on a multiprocessor + or multicore 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 @@ -716,6 +920,9 @@ for example). :ref:`ffi-threads`. .. ghc-flag:: -eventlog + :shortdesc: Enable runtime event tracing + :type: dynamic + :category: linking Link the program with the "eventlog" version of the runtime system. A program linked in this way can generate a runtime trace of events @@ -726,7 +933,19 @@ for example). :ghc-flag:`-eventlog` can be used with :ghc-flag:`-threaded`. It is implied by :ghc-flag:`-debug`. -.. ghc-flag:: -rtsopts[=⟨none|some|all⟩] +.. ghc-flag:: -rtsopts[=⟨none|some|all|ignore|ignoreAll⟩] + :shortdesc: Control whether the RTS behaviour can be tweaked via command-line + flags and the ``GHCRTS`` environment variable. Using ``none`` + means no RTS flags can be given; ``some`` means only a minimum + of safe options can be given (the default); ``all`` (or no + argument at all) means that all RTS flags are permitted; ``ignore`` + means RTS flags can be given, but are treated as regular arguments and + passed to the Haskell program as arguments; ``ignoreAll`` is the same as + ``ignore``, but ``GHCRTS`` is also ignored. ``-rtsopts`` does not + affect ``-with-rtsopts`` behavior; flags passed via ``-with-rtsopts`` + are used regardless of ``-rtsopts``. + :type: dynamic + :category: linking :default: all @@ -741,6 +960,15 @@ for example). then the program will emit a warning message, ``GHCRTS`` will be ignored, and the program will run as normal. + ``-rtsopts=ignore`` + Disables all processing of RTS options. Unlike ``none`` this treats + all RTS flags appearing on the command line the same way as regular + arguments. (Passing them on to your program as arguments). + ``GHCRTS`` options will be processed normally. + + ``-rtsopts=ignoreAll`` + Same as ``ignore`` but also ignores ``GHCRTS``. + ``-rtsopts=some`` [this is the default setting] Enable only the "safe" RTS options: (Currently only ``-?`` and ``--info``.) Any other RTS @@ -760,7 +988,13 @@ for example). Note that ``-rtsopts`` has no effect when used with :ghc-flag:`-no-hs-main`; see :ref:`using-own-main` for details. + ``-rtsopts`` does not affect RTS options passed via ``-with-rtsopts``; + those are used regardless of ``-rtsopts``. + .. ghc-flag:: -with-rtsopts=⟨opts⟩ + :shortdesc: Set the default RTS options to ⟨opts⟩. + :type: dynamic + :category: linking This option allows you to set the default RTS options at link-time. For example, ``-with-rtsopts="-H128m"`` sets the default heap size @@ -770,19 +1004,30 @@ for example). change RTS options at run-time, in which case ``-with-rtsopts`` would be the *only* way to set them.) + Use the runtime flag :rts-flag:`--info` on the executable program + to see the options set with ``-with-rtsopts``. + Note that ``-with-rtsopts`` has no effect when used with ``-no-hs-main``; see :ref:`using-own-main` for details. .. ghc-flag:: -no-rtsopts-suggestions + :shortdesc: Don't print RTS suggestions about linking with + :ghc-flag:`-rtsopts[=⟨none|some|all|ignore|ignoreAll⟩]`. + :type: dynamic + :category: linking This option disables RTS suggestions about linking with - :ghc-flag:`-rtsopts[=⟨none|some|all⟩]` 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``. + :ghc-flag:`-rtsopts[=⟨none|some|all|ignore|ignoreAll⟩]` 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``. .. ghc-flag:: -fno-gen-manifest + :shortdesc: Do not generate a manifest file (Windows only) + :type: dynamic + :category: linking On Windows, GHC normally generates a manifestmanifest file when linking a binary. The manifest is placed in the file @@ -814,6 +1059,9 @@ for example). below. .. ghc-flag:: -fno-embed-manifest + :shortdesc: Do not embed the manifest in the executable (Windows only) + :type: dynamic + :category: linking .. index:: single: windres @@ -829,6 +1077,9 @@ for example). :ghc-flag:`-optwindres ⟨option⟩` (:ref:`forcing-options-through`). .. ghc-flag:: -fno-shared-implib + :shortdesc: Don't generate an import library for a DLL (Windows only) + :type: dynamic + :category: linking DLLs on Windows are typically linked to by linking to a corresponding ``.lib`` or ``.dll.a`` — the so-called import library. @@ -844,6 +1095,13 @@ for example). library entirely. .. ghc-flag:: -dylib-install-name ⟨path⟩ + :shortdesc: Set the install name (via ``-install_name`` passed to Apple's + linker), specifying the full install path of the library file. + Any libraries or executables that link with it later will pick + up that path as their runtime search location for it. + (Darwin/OS X only) + :type: dynamic + :category: linking On Darwin/OS X, dynamic libraries are stamped at build time with an "install name", which is the ultimate install path of the library @@ -855,6 +1113,13 @@ for example). on other platforms. .. ghc-flag:: -rdynamic + :shortdesc: This instructs the linker to add all symbols, not only used + ones, to the dynamic symbol table. Currently Linux and + Windows/MinGW32 only. This is equivalent to using + ``-optl -rdynamic`` on Linux, and ``-optl -export-all-symbols`` + on Windows. + :type: dynamic + :category: linking This instructs the linker to add all symbols, not only used ones, to the dynamic symbol table. Currently Linux and Windows/MinGW32 only. @@ -862,6 +1127,11 @@ for example). ``-optl -export-all-symbols`` on Windows. .. ghc-flag:: -fwhole-archive-hs-libs + :shortdesc: When linking a binary executable, this inserts the flag + ``-Wl,--whole-archive`` before any ``-l`` flags for Haskell + libraries, and ``-Wl,--no-whole-archive`` afterwards + :type: dynamic + :category: linking When linking a binary executable, this inserts the flag ``-Wl,--whole-archive`` before any ``-l`` flags for Haskell @@ -875,3 +1145,27 @@ for example). aren't referenced by any other code linked into the executable. If you're using ``-fwhole-archive-hs-libs``, you probably also want ``-rdynamic``. + +.. ghc-flag:: -pie + :shortdesc: Instruct the linker to produce a position-independent executable. + :type: dynamic + :category: linking + + :since: 8.2.2 + + This instructs the linker to produce a position-independent executable. + This flag is only valid while producing executables and all object code + being linked must have been produced with :ghc-flag:`-fPIE`. + + Position independent executables are required by some platforms as they + enable address-space layout randomization (ASLR), a common security measure. + They can also be useful as they can be dynamically loaded and used as shared + libraries by other executables. + + Position independent executables should be dynamically-linked (e.g. built + with :ghc-flag:`-dynamic` and only loaded into other dynamically-linked + executables to ensure that only one ``libHSrts`` is present if + loaded into the address space of another Haskell process. + + Also, you may need to use the :ghc-flag:`-rdynamic` flag to ensure that + that symbols are not dropped from your PIE objects. diff --git a/docs/users_guide/profiling.rst b/docs/users_guide/profiling.rst index 3f2e592944..def3596393 100644 --- a/docs/users_guide/profiling.rst +++ b/docs/users_guide/profiling.rst @@ -309,6 +309,9 @@ Compiler options for profiling single: options; for profiling .. ghc-flag:: -prof + :shortdesc: Turn on profiling + :type: dynamic + :category: To make use of the profiling system *all* modules must be compiled and linked with the :ghc-flag:`-prof` option. Any ``SCC`` annotations you've @@ -322,12 +325,20 @@ There are a few other profiling-related compilation options. Use them for all modules in a program. .. ghc-flag:: -fprof-auto + :shortdesc: Auto-add ``SCC``\\ s to all bindings not marked INLINE + :type: dynamic + :reverse: -fno-prof-auto + :category: *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. .. ghc-flag:: -fprof-auto-top + :shortdesc: Auto-add ``SCC``\\ s to all top-level bindings not marked INLINE + :type: dynamic + :reverse: -fno-prof-auto + :category: .. index:: single: cost centres; automatically inserting @@ -337,6 +348,10 @@ for all modules in a program. function, you have to add it manually. .. ghc-flag:: -fprof-auto-exported + :shortdesc: Auto-add ``SCC``\\ s to all exported bindings not marked INLINE + :type: dynamic + :reverse: -fno-prof-auto + :category: .. index:: single: cost centres; automatically inserting @@ -346,6 +361,10 @@ for all modules in a program. function, you have to add it manually. .. ghc-flag:: -fprof-auto-calls + :shortdesc: Auto-add ``SCC``\\ s to all call sites + :type: dynamic + :reverse: -fno-prof-auto-calls + :category: Adds an automatic ``SCC`` annotation to all *call sites*. This is particularly useful when using profiling for the purposes of @@ -354,21 +373,38 @@ for all modules in a program. details. .. ghc-flag:: -fprof-cafs + :shortdesc: Auto-add ``SCC``\\ s to all CAFs + :type: dynamic + :reverse: -fno-prof-cafs + :category: The costs of all CAFs in a module are usually attributed to one "big" CAF cost-centre. With this option, all CAFs get their own cost-centre. An “if all else fails” option… .. ghc-flag:: -fno-prof-auto + :shortdesc: Disables any previous :ghc-flag:`-fprof-auto`, + :ghc-flag:`-fprof-auto-top`, or :ghc-flag:`-fprof-auto-exported` options. + :type: dynamic + :reverse: -fprof-auto + :category: Disables any previous :ghc-flag:`-fprof-auto`, :ghc-flag:`-fprof-auto-top`, or :ghc-flag:`-fprof-auto-exported` options. .. ghc-flag:: -fno-prof-cafs + :shortdesc: Disables any previous :ghc-flag:`-fprof-cafs` option. + :type: dynamic + :reverse: -fprof-cafs + :category: Disables any previous :ghc-flag:`-fprof-cafs` option. .. ghc-flag:: -fno-prof-count-entries + :shortdesc: Do not collect entry counts + :type: dynamic + :reverse: -fprof-count-entries + :category: Tells GHC not to collect information about how often functions are entered at runtime (the "entries" column of the time profile), for @@ -651,38 +687,43 @@ 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: +.. rts-flag:: -hT + + Breaks down the graph by heap closure type. + .. rts-flag:: -hc -h - (can be shortened to :rts-flag:`-h`). Breaks down the graph by the - cost-centre stack which produced the data. + *Requires :ghc-flag:`-prof`.* Breaks down the graph by the cost-centre stack + which produced the data. .. rts-flag:: -hm - Break down the live heap by the module containing the code which - produced the data. + *Requires :ghc-flag:`-prof`.* Break down the live heap by the module + containing the code which produced the data. .. 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. + *Requires :ghc-flag:`-prof`.* 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. .. 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. + *Requires :ghc-flag:`-prof`.* 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. .. rts-flag:: -hr - Break down the graph by retainer set. Retainer profiling is - described in more detail below (:ref:`retainer-prof`). + *Requires :ghc-flag:`-prof`.* Break down the graph by retainer set. Retainer + profiling is described in more detail below (:ref:`retainer-prof`). .. rts-flag:: -hb - Break down the graph by biography. Biographical profiling is - described in more detail below (:ref:`biography-prof`). + *Requires :ghc-flag:`-prof`.* Break down the graph by biography. + Biographical profiling is described in more detail below + (:ref:`biography-prof`). .. rts-flag:: -l @@ -1345,6 +1386,9 @@ Options for instrumenting code for coverage .. program:: hpc .. ghc-flag:: -fhpc + :shortdesc: Turn on Haskell program coverage instrumentation + :type: dynamic + :category: coverage Enable code coverage for the current module or modules being compiled. @@ -1564,8 +1608,11 @@ Using “ticky-ticky” profiling (for implementors) single: ticky-ticky profiling .. ghc-flag:: -ticky + :shortdesc: :ref:`Turn on ticky-ticky profiling <ticky-ticky>` + :type: dynamic + :category: - Enable ticky-ticky profiling. + Enable ticky-ticky profiling. Because ticky-ticky profiling requires a certain familiarity with GHC internals, we have moved the documentation to the GHC developers wiki. diff --git a/docs/users_guide/runtime_control.rst b/docs/users_guide/runtime_control.rst index 422eaa2ceb..0c38ac5919 100644 --- a/docs/users_guide/runtime_control.rst +++ b/docs/users_guide/runtime_control.rst @@ -117,8 +117,8 @@ Setting RTS options with the ``GHCRTS`` environment variable .. envvar:: GHCRTS - If the ``-rtsopts`` flag is set to something other than ``none`` when - linking, RTS options are also taken from the environment variable + If the ``-rtsopts`` flag is set to something other than ``none`` or ``ignoreAll`` + 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): @@ -218,7 +218,28 @@ Miscellaneous RTS options interval timer signal is still enabled. The timer signal is either SIGVTALRM or SIGALRM, depending on the RTS configuration and OS capabilities. To disable the timer signal, use the ``-V0`` RTS - option (see above). + option (see :rts-flag:`-V ⟨secs⟩`). + +.. rts-flag:: --install-seh-handlers=⟨yes|no⟩ + + If yes (the default), the RTS on Windows installs exception handlers to + catch unhandled exceptions using the Windows exception handling mechanism. + This option is primarily useful for when you are using the Haskell code as a + DLL, and don't want the RTS to ungracefully terminate your application on + erros such as segfaults. + +.. rts-flag:: --generate-crash-dumps + + If yes (the default), the RTS on Windows will generate a core dump on + any crash. These dumps can be inspected using debuggers such as WinDBG. + The dumps record all code, registers and threading information at the time + of the crash. Note that this implies `--install-seh-handlers=yes`. + +.. rts-flag:: --generate-stack-traces=<yes|no> + + If yes (the default), the RTS on Windows will generate a stack trace on + crashes if exception handling are enabled. In order to get more information + in compiled executables, C code or DLLs symbols need to be available. .. rts-flag:: -xm ⟨address⟩ @@ -514,7 +535,7 @@ performance. .. rts-flag:: -I ⟨seconds⟩ - :default: 0.3 seconds + :default: 0.3 seconds in the threaded runtime, 0 in the non-threaded runtime .. index:: single: idle GC @@ -664,7 +685,7 @@ performance. single: NUMA, enabling in the runtime Enable NUMA-aware memory allocation in the runtime (only available - with ``-threaded``, and only on Linux currently). + with ``-threaded``, and only on Linux and Windows currently). Background: some systems have a Non-Uniform Memory Architecture, whereby main memory is split into banks which are "local" to @@ -707,6 +728,44 @@ performance. that indicates the NUMA nodes on which to run the program. For example, ``--numa=3`` would run the program on NUMA nodes 0 and 1. +.. rts-flag:: --long-gc-sync + --long-gc-sync=<seconds> + + .. index:: + single: GC sync time, measuring + + When a GC starts, all the running mutator threads have to stop and + synchronise. The period between when the GC is initiated and all + the mutator threads are stopped is called the GC synchronisation + phase. If this phase is taking a long time (longer than 1ms is + considered long), then it can have a severe impact on overall + throughput. + + A long GC sync can be caused by a mutator thread that is inside an + ``unsafe`` FFI call, or running in a loop that doesn't allocate + memory and so doesn't yield. To fix the former, make the call + ``safe``, and to fix the latter, either avoid calling the code in + question or compile it with :ghc-flag:`-fomit-yields`. + + By default, the flag will cause a warning to be emitted to stderr + when the sync time exceeds the specified time. This behaviour can + be overriden, however: the ``longGCSync()`` hook is called when + the sync time is exceeded during the sync period, and the + ``longGCSyncEnd()`` hook at the end. Both of these hooks can be + overriden in the ``RtsConfig`` when the runtime is started with + ``hs_init_ghc()``. The default implementations of these hooks + (``LongGcSync()`` and ``LongGCSyncEnd()`` respectively) print + warnings to stderr. + + One way to use this flag is to set a breakpoint on + ``LongGCSync()`` in the debugger, and find the thread that is + delaying the sync. You probably want to use :ghc-flag:`-g` to + provide more info to the debugger. + + The GC sync time, along with other GC stats, are available by + calling the ``getRTSStats()`` function from C, or + ``GHC.Stats.getRTSStats`` from Haskell. + .. _rts-options-statistics: RTS options to produce runtime statistics @@ -717,6 +776,7 @@ RTS options to produce runtime statistics -s [⟨file⟩] -S [⟨file⟩] --machine-readable + --internal-counters These options produce runtime-system statistics, such as the amount of time spent executing the program and in the garbage collector, @@ -726,7 +786,10 @@ RTS options to produce runtime statistics line of output in the same format as GHC's ``-Rghc-timing`` option, ``-s`` produces a more detailed summary at the end of the program, and ``-S`` additionally produces information about each and every - garbage collection. + garbage collection. Passing ``--internal-counters`` to a threaded + runtime will cause a detailed summary to include various internal + counts accumulated during the run; note that these are unspecified + and may change between releases. The output is placed in ⟨file⟩. If ⟨file⟩ is omitted, then the output is sent to ``stderr``. @@ -1156,6 +1219,7 @@ Getting information about the RTS ,("Word size", "64") ,("Compiler unregisterised", "NO") ,("Tables next to code", "YES") + ,("Flag -with-rtsopts", "") ] The information is formatted such that it can be read as a of type @@ -1206,3 +1270,6 @@ Getting information about the RTS 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.) + + ``Flag -with-rtsopts`` + The value of the GHC flag :ghc-flag:`-with-rtsopts=⟨opts⟩` at compile/link time. diff --git a/docs/users_guide/safe_haskell.rst b/docs/users_guide/safe_haskell.rst index e1238a8e2c..adf70d2a90 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 :ghc-flag:`-XSafe` or :ghc-flag:`-XTrustworthy` flag and compiling -``Danger`` with the :ghc-flag:`-XSafe` flag. We explain each below. +RIO module with the :extension:`Safe` or :extension:`Trustworthy` flag and compiling +``Danger`` with the :extension:`Safe` flag. We explain each below. -The use of :ghc-flag:`-XSafe` to compile ``Danger`` restricts the features of +The use of :extension:`Safe` 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 :ghc-flag:`-XSafe` flag also restricts the modules can be imported by +The :extension:`Safe` flag also restricts the modules can be imported by ``Danger`` to only those that are considered trusted. Trusted modules -are those compiled with :ghc-flag:`-XSafe`, where GHC provides a mechanical +are those compiled with :extension:`Safe`, where GHC provides a mechanical guarantee that the code is safe. Or those modules compiled with -:ghc-flag:`-XTrustworthy`, where the module author claims that the module is +:extension:`Trustworthy`, where the module author claims that the module is 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 +This is why the RIO module is compiled with :extension:`Safe` or +:extension:`Trustworthy`>, to allow the ``Danger`` module to import it. The +:extension:`Trustworthy` flag doesn't place any restrictions on the module like +:extension:`Safe` 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 :ghc-flag:`-XTrustworthy` is a problem as an +However, the unrestricted use of :extension:`Trustworthy` is a problem as an arbitrary module can use it to mark themselves as trusted, yet -: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 +:extension:`Trustworthy` doesn't offer any guarantees about the module, unlike +:extension:`Safe`. 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 -:ghc-flag:`-XSafe` compiled code, the client C compiling the code must tell GHC +:extension:`Safe` 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 -:ghc-flag:`-XSafe`, I trust the author(s) of this package and trust the modules +:extension:`Safe`, 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 :ghc-flag:`-XSafe`. Thus, ``Danger`` can make use of the +compiled with :extension:`Safe`. 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 :ghc-flag:`-XSafe` are +- ``RULES`` — Rewrite rules defined in a module M compiled with :extension:`Safe` are dropped. Rules defined in Trustworthy modules that ``M`` imports are still valid and will fire as usual. @@ -278,7 +278,7 @@ Furthermore, we restrict the following features: there is an important invariant that a ``Generic`` instance should adhere to the structure of the data type for which the instance is defined, and allowing manually implemented ``Generic`` instances would break that - invariant. Derived instances (through the :ghc-flag:`-XDeriveGeneric` + invariant. Derived instances (through the :extension:`DeriveGeneric` extension) are still allowed. Note that the only allowed :ref:`deriving strategy <deriving-strategies>` for deriving ``Generic`` under Safe Haskell is ``stock``, as another strategy (e.g., ``anyclass``) would @@ -327,12 +327,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 :ghc-flag:`-XSafe` +Both module ``Class`` and module ``Dangerous`` will compile under :extension:`Safe` 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 -:ghc-flag:`-XSafe` shouldn't change the meaning of code that compiles fine +:extension:`Safe` shouldn't change the meaning of code that compiles fine without importing the module. This is the Safe Haskell property known as *semantic consistency*. @@ -358,9 +358,9 @@ imported module ``N`` changing the behaviour of existing code. For example, if the second condition isn't violated, then the module author ``M`` must depend either on a type-class or type defined in ``N``. -When an particular type-class method call is considered unsafe due to -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 +When a particular type-class method call is considered unsafe due to +overlapping instances, and the module being compiled is using :extension:`Safe` +or :extension:`Trustworthy`, then compilation will fail. For :extension:`Unsafe`, no restriction is applied, and for modules using safe inference, they will be inferred unsafe. @@ -396,13 +396,13 @@ Trust and Safe Haskell Modes Safe Haskell introduces the following three language flags: -- :ghc-flag:`-XSafe` — Enables the safe language dialect, asking GHC to guarantee trust. +- :extension:`Safe` — 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. -- :ghc-flag:`-XTrustworthy` — Means that while this module may invoke unsafe functions +- :extension:`Trustworthy` — 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 @@ -412,8 +412,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. -- :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 +- :extension:`Unsafe` — Marks the module being compiled as unsafe so that modules + compiled using :extension:`Safe` 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. @@ -439,16 +439,16 @@ 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 :ghc-flag:`-XSafe` + - The module was compiled with :extension:`Safe` - All of M's direct imports are trusted by C - *or* all of these hold: - - The module was compiled with :ghc-flag:`-XTrustworthy` + - The module was compiled with :extension:`Trustworthy` - 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 :ghc-flag:`-XTrustworthy` and it will be trusted. To control this, there is +with :extension:`Trustworthy` and it will be trusted. To control this, there is an additional definition of package trust (enabled with the :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 @@ -481,12 +481,12 @@ trusted by a client C* if and only if: - Both of these hold: - - The module was compiled with :ghc-flag:`-XSafe` + - The module was compiled with :extension:`Safe` - All of ``M``\'s direct imports are trusted by C - *or* all of these hold: - - The module was compiled with :ghc-flag:`-XTrustworthy` + - The module was compiled with :extension:`Trustworthy` - All of ``M``\'s direct safe imports are trusted by C - Package ``P`` is trusted by C @@ -495,7 +495,7 @@ 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 :ghc-flag:`-XTrustworthy` +chain is required as GHC provides no guarantee for :extension:`Trustworthy` compiled modules. The reason there are two modes of checking trust is that the extra @@ -528,11 +528,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 :ghc-flag:`-XTrustworthy`, so we don't +does C trust module ``M``? Well ``M`` is marked :extension:`Trustworthy`, 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 :ghc-flag:`-XTrustworthy` , so ``P``\'s author takes + ``M`` was compiled with :extension:`Trustworthy` , so ``P``\'s author takes responsibility for that import. ``C`` trusts ``P``\'s author, so this import is fine. @@ -544,14 +544,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 :ghc-flag:`-XTrustworthy`. +- Buggle only imports ``Prelude``, which is compiled with :extension:`Trustworthy`. ``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 :ghc-flag:`-XTrustworthy` +is enough. C only needs to trust packages that contain :extension:`Trustworthy` modules. .. _trustworthy-guarantees: @@ -562,10 +562,10 @@ Trustworthy Requirements .. index:: single: trustworthy -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. +Module authors using the :extension:`Trustworthy` 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. .. _safe-package-trust: @@ -580,19 +580,30 @@ Several new options are available at the GHC command-line to specify the trust property of packages: .. ghc-flag:: -trust ⟨pkg⟩ + :shortdesc: Expose package ⟨pkg⟩ and set it to be trusted. See + :ref:`safe-haskell`. + :type: dynamic + :category: packages - Exposes package ⟨pkg⟩ if it was hidden and considers it a - trusted package regardless of the package database. + Exposes package ⟨pkg⟩ if it was hidden and considers it a + trusted package regardless of the package database. .. ghc-flag:: -distrust ⟨pkg⟩ + :shortdesc: Expose package ⟨pkg⟩ and set it to be distrusted. See + :ref:`safe-haskell`. + :type: dynamic + :category: packages - 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 + an untrusted package regardless of the package database. .. ghc-flag:: -distrust-all-packages + :shortdesc: Distrust all packages by default. See :ref:`safe-haskell`. + :type: dynamic + :category: packages - Considers all packages distrusted unless they are - explicitly set to be trusted by subsequent command-line options. + 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`. @@ -605,16 +616,16 @@ Safe Haskell Inference .. index:: single: safe inference -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 +In the case where a module is compiled without one of :extension:`Safe`, +:extension:`Trustworthy` or :extension:`Unsafe` 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 :ghc-flag:`-XSafe` flag, then M is marked as +compile without error under the :extension:`Safe` 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 :ghc-flag:`-XSafe` flag? The later case should be used when you have a +explicit :extension:`Safe` 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 @@ -646,7 +657,8 @@ Safe Haskell Flag Summary In summary, Safe Haskell consists of the following three language flags: -.. ghc-flag:: -XSafe +.. extension:: Safe + :shortdesc: Enable the :ref:`Safe Haskell <safe-haskell>` Safe mode. :since: 7.2.1 @@ -661,14 +673,15 @@ 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. -.. ghc-flag:: -XTrustworthy +.. extension:: Trustworthy + :shortdesc: Enable the :ref:`Safe Haskell <safe-haskell>` Trustworthy mode. :since: 7.2.1 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. :ghc-flag:`-XTrustworthy` doesn't restrict the + the package containing the module. :extension:`Trustworthy` 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 @@ -682,12 +695,13 @@ In summary, Safe Haskell consists of the following three language flags: - *Imported Modules* — Under control of module author which ones must be trusted. -.. ghc-flag:: -XUnsafe +.. extension:: Unsafe + :shortdesc: Enable :ref:`Safe Haskell <safe-haskell>` Unsafe mode. :since: 7.4.1 Mark a module as unsafe so that it can't be imported by code - compiled with :ghc-flag:`-XSafe`. Also enable the Safe Import extension so that a + compiled with :extension:`Safe`. Also enable the Safe Import extension so that a module can require a dependency to be trusted. @@ -699,6 +713,11 @@ In summary, Safe Haskell consists of the following three language flags: And one general flag: .. ghc-flag:: -fpackage-trust + :shortdesc: Enable :ref:`Safe Haskell <safe-haskell>` trusted package + requirement for trustworthy modules. + :type: dynamic + :category: packages + 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. @@ -706,18 +725,33 @@ And one general flag: And three warning flags: .. ghc-flag:: -Wunsafe + :shortdesc: warn if the module being compiled is regarded to be unsafe. + See :ref:`safe-haskell` + :type: dynamic + :reverse: -Wno-unsafe + :category: warnings 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. .. ghc-flag:: -Wsafe + :shortdesc: warn if the module being compiled is regarded to be safe. + :type: dynamic + :reverse: -Wno-safe + :category: warnings 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. .. ghc-flag:: -Wtrustworthy-safe + :shortdesc: warn if the module being compiled is marked as + :extension:`Trustworthy` but it could instead be marked as + :extension:`Safe`, a more informative bound. + :type: dynamic + :reverse: -Wno-safe + :category: warnings Issue a warning if the module being compiled is marked as -XTrustworthy but it could instead be marked as diff --git a/docs/users_guide/separate_compilation.rst b/docs/users_guide/separate_compilation.rst index 06af6f0ddf..d17ed2111c 100644 --- a/docs/users_guide/separate_compilation.rst +++ b/docs/users_guide/separate_compilation.rst @@ -158,6 +158,9 @@ current directory). The following options can be used to add to or change the contents of the search path: .. ghc-flag:: -i⟨dir⟩[:⟨dir⟩]* + :shortdesc: add ⟨dir⟩, ⟨dir2⟩, etc. to import path + :type: dynamic + :category: search-path .. index:: single: search path; source code @@ -166,6 +169,10 @@ contents of the search path: the search path. .. ghc-flag:: -i + :shortdesc: Empty the import directory list + :type: dynamic + :category: search-path + resets the search path back to nothing. This isn't the whole story: GHC also looks for modules in pre-compiled @@ -182,6 +189,9 @@ Redirecting the compilation output(s) single: redirecting compilation output .. ghc-flag:: -o ⟨file⟩ + :shortdesc: set output filename + :type: dynamic + :category: GHC's compiled output normally goes into a ``.hc``, ``.o``, etc., file, depending on the last-run compilation phase. The option @@ -231,6 +241,9 @@ Redirecting the compilation output(s) will produce ``Prog`` (or ``Prog.exe`` if you are on Windows). .. ghc-flag:: -odir ⟨dir⟩ + :shortdesc: set directory for object files + :type: dynamic + :category: Redirects object files to directory ⟨dir⟩. For example: @@ -248,6 +261,9 @@ Redirecting the compilation output(s) ``parse/Bar.hi``, and ``gurgle/Bumble.hi``. .. ghc-flag:: -ohi ⟨file⟩ + :shortdesc: set the filename in which to put the interface + :type: dynamic + :category: The interface output may be directed to another file ``bar2/Wurble.iface`` with the option ``-ohi bar2/Wurble.iface`` @@ -265,11 +281,17 @@ Redirecting the compilation output(s) for example. .. ghc-flag:: -hidir ⟨dir⟩ + :shortdesc: set directory for interface files + :type: dynamic + :category: Redirects all generated interface files into ⟨dir⟩, instead of the default. .. ghc-flag:: -stubdir ⟨dir⟩ + :shortdesc: redirect FFI stub files + :type: dynamic + :category: Redirects all generated FFI stub files into ⟨dir⟩. Stub files are generated when the Haskell source contains a ``foreign export`` or @@ -279,31 +301,40 @@ Redirecting the compilation output(s) hierarchical modules. .. ghc-flag:: -dumpdir ⟨dir⟩ + :shortdesc: redirect dump files + :type: dynamic + :category: Redirects all dump files into ⟨dir⟩. Dump files are generated when ``-ddump-to-file`` is used with other ``-ddump-*`` flags. .. ghc-flag:: -outputdir ⟨dir⟩ + :shortdesc: set output directory + :type: dynamic + :category: The ``-outputdir`` option is shorthand for the combination of :ghc-flag:`-odir ⟨dir⟩`, :ghc-flag:`-hidir ⟨dir⟩`, :ghc-flag:`-stubdir ⟨dir⟩` and :ghc-flag:`-dumpdir ⟨dir⟩`. .. ghc-flag:: -osuf ⟨suffix⟩ - -hisuf ⟨suffix⟩ - -hcsuf ⟨suffix⟩ + :shortdesc: set the output file suffix + :type: dynamic + :category: The ``-osuf`` ⟨suffix⟩ will change the ``.o`` file suffix for object files to whatever you specify. We use this when compiling libraries, so that objects for the profiling versions of the libraries don't clobber the normal ones. +.. ghc-flag:: -hisuf ⟨suffix⟩ + :shortdesc: set the suffix to use for interface files + :type: dynamic + :category: + Similarly, the ``-hisuf`` ⟨suffix⟩ will change the ``.hi`` file suffix for non-system interface files (see :ref:`hi-options`). - Finally, the option ``-hcsuf`` ⟨suffix⟩ will change the ``.hc`` file - suffix for compiler-generated intermediate C files. - The ``-hisuf``/``-osuf`` game is particularly useful if you want to compile a program both with and without profiling, in the same directory. You can say: @@ -320,6 +351,15 @@ Redirecting the compilation output(s) to get the profiled version. + +.. ghc-flag:: -hcsuf ⟨suffix⟩ + :shortdesc: set the suffix to use for intermediate C files + :type: dynamic + :category: + + Finally, the option ``-hcsuf`` ⟨suffix⟩ will change the ``.hc`` file + suffix for compiler-generated intermediate C files. + .. _keeping-intermediates: Keeping Intermediate Files @@ -337,21 +377,45 @@ compilation: .. ghc-flag:: -keep-hc-file -keep-hc-files + :shortdesc: Retain intermediate ``.hc`` files. + :type: dynamic + :category: keep-intermediates 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). .. ghc-flag:: -keep-hi-files + :shortdesc: Retain intermediate ``.hi`` files (the default). + :type: dynamic + :reverse: -no-keep-hi-files + :category: keep-intermediates .. index:: single: temporary files; keeping - Keep intermediate ``.hi`` files. This is the default. You may use - ``-no-keep-hi-files`` if you are not interested in the ``.hi`` files. + Keep intermediate ``.hi`` files. This is the default. You may use + ``-no-keep-hi-files`` if you are not interested in the ``.hi`` files. + +.. ghc-flag:: -keep-hscpp-file + -keep-hscpp-files + :shortdesc: Retain intermediate ``.hscpp`` files. + :type: dynamic + :category: keep-intermediates + + .. index:: + single: temporary files; keeping + + Keep the output of the ``CPP`` pre-processor phase as ``.hscpp`` files. + A ``.hscpp`` file is only created, if a module gets compiled and uses the + C pre-processor. .. ghc-flag:: -keep-llvm-file -keep-llvm-files + :shortdesc: Retain intermediate LLVM ``.ll`` files. + Implies :ghc-flag:`-fllvm`. + :type: dynamic + :category: keep-intermediates :implies: :ghc-flag:`-fllvm` @@ -361,19 +425,29 @@ compilation: to use :ghc-flag:`-fllvm` to force them to be produced). .. ghc-flag:: -keep-o-files + :shortdesc: Retain intermediate ``.o`` files (the default). + :type: dynamic + :reverse: -no-keep-o-files + :category: keep-intermediates .. index:: single: temporary files; keeping - Keep intermediate ``.o`` files. This is the default. You may use - ``-no-keep-o-files`` if you are not interested in the ``.o`` files. + Keep intermediate ``.o`` files. This is the default. You may use + ``-no-keep-o-files`` if you are not interested in the ``.o`` files. .. ghc-flag:: -keep-s-file -keep-s-files + :shortdesc: Retain intermediate ``.s`` files. + :type: dynamic + :category: keep-intermediates Keep intermediate ``.s`` files. .. ghc-flag:: -keep-tmp-files + :shortdesc: Retain all intermediate temporary files. + :type: dynamic + :category: keep-intermediates .. index:: single: temporary files; keeping @@ -392,6 +466,9 @@ Redirecting temporary files single: temporary files; redirecting .. ghc-flag:: -tmpdir ⟨dir⟩ + :shortdesc: set the directory for temporary files + :type: dynamic + :category: temp-files If you have trouble because of running out of space in ``/tmp`` (or wherever your installation thinks temporary files should go), you @@ -415,10 +492,16 @@ Other options related to interface files single: interface files, options .. ghc-flag:: -ddump-hi + :shortdesc: Dump the new interface to stdout + :type: dynamic + :category: interface-files Dumps the new interface to standard output. .. ghc-flag:: -ddump-hi-diffs + :shortdesc: Show the differences vs. the old interface + :type: dynamic + :category: interface-files 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 @@ -427,6 +510,9 @@ Other options related to interface files differences between the old and new ``.hi`` files. .. ghc-flag:: -ddump-minimal-imports + :shortdesc: Dump a minimal set of imports + :type: dynamic + :category: interface-files Dump to the file :file:`{M}.imports` (where ⟨M⟩ is the name of the module being compiled) a "minimal" set of import declarations. The @@ -441,6 +527,9 @@ Other options related to interface files is intended to reduce the labour. .. ghc-flag:: --show-iface ⟨file⟩ + :shortdesc: See :ref:`modes`. + :type: mode + :category: interface-files where ⟨file⟩ is the name of an interface file, dumps the contents of that interface in a human-readable format. See :ref:`modes`. @@ -454,12 +543,35 @@ The recompilation checker single: recompilation checker .. ghc-flag:: -fforce-recomp + :shortdesc: Turn off recompilation checking. This is implied by any + ``-ddump-X`` option when compiling a single file + (i.e. when using :ghc-flag:`-c`). + :type: dynamic + :reverse: -fno-force-recomp + :category: recompilation Turn off recompilation checking (which is on by default). Recompilation checking normally stops compilation early, leaving an existing ``.o`` file in place, if it can be determined that the module does not need to be recompiled. +.. ghc-flag:: -fignore-optim-changes + :shortdesc: Do not recompile modules just to match changes to + optimisation flags. This is especially useful for avoiding + recompilation when using GHCi, and is enabled by default for + GHCi. + :type: dynamic + :reverse: -fno-ignore-optim-changes + :category: recompilation + +.. ghc-flag:: -fignore-hpc-changes + :shortdesc: Do not recompile modules just to match changes to + HPC flags. This is especially useful for avoiding recompilation + when using GHCi, and is enabled by default for GHCi. + :type: dynamic + :reverse: -fno-ignore-hpc-changes + :category: recompilation + In the olden days, GHC compared the newly-generated ``.hi`` file with the previous version; if they were identical, it left the old one alone and didn't change its modification date. In consequence, importers of a @@ -522,11 +634,15 @@ files, thus: :: g :: TA -> TB g (MkTA x) = MkTB x -``hs-boot`` files importing, ``hi-boot`` files Here ``A`` imports ``B``, -but ``B`` imports ``A`` with a ``{-# SOURCE #-}`` pragma, which breaks -the circular dependency. Every loop in the module import graph must be -broken by a ``{-# SOURCE #-}`` import; or, equivalently, the module -import graph must be acyclic if ``{-# SOURCE #-}`` imports are ignored. +.. index:: + single: ``hs-boot`` files + single: importing, ``hi-boot`` files + +Here ``A`` imports ``B``, but ``B`` imports ``A`` with a +``{-# SOURCE #-}`` pragma, which breaks the circular dependency. Every +loop in the module import graph must be broken by a ``{-# SOURCE #-}`` +import; or, equivalently, the module import graph must be acyclic if +``{-# SOURCE #-}`` imports are ignored. For every module ``A.hs`` that is ``{-# SOURCE #-}``-imported in this way there must exist a source file ``A.hs-boot``. This file contains an @@ -564,7 +680,7 @@ There are several points to note here: - Just as compiling ``A.hs`` produces an interface file ``A.hi``, and an object file ``A.o``, so compiling ``A.hs-boot`` produces an - interface file ``A.hi-boot``, and an pseudo-object file ``A.o-boot``: + interface file ``A.hi-boot``, and a pseudo-object file ``A.o-boot``: - The pseudo-object file ``A.o-boot`` is empty (don't link it!), but it is very useful when using a Makefile, to record when the @@ -687,7 +803,7 @@ be able to pick a particular implementation of strings:: toString s = s module A where - import Text + import Str z = toString empty By replacing ``Str.hs`` with a signature ``Str.hsig``, ``A`` (and @@ -912,7 +1028,18 @@ to ``hs-boot`` files, but with some slight changes: If you do not write out the constructors, you may need to give a kind to tell GHC what the kinds of the type variables are, if they are not the default - ``*``. + ``*``. Unlike regular data type declarations, the return kind of an + abstract data declaration can be anything (in which case it probably + will be implemented using a type synonym.) This can be used + to allow compile-time representation polymorphism (as opposed to + `run-time representation polymorphism <#runtime-rep>`__), + as in this example:: + + signature Number where + import GHC.Types + data Rep :: RuntimeRep + data Number :: TYPE Rep + plus :: Number -> Number -> Number Roles of type parameters are subject to the subtyping relation ``phantom < representational < nominal``: for example, @@ -1168,6 +1295,9 @@ which you may find useful. The options which affect dependency generation are: .. ghc-flag:: -ddump-mod-cycles + :shortdesc: Dump module cycles + :type: dynamic + :category: Display a list of the cycles in the module graph. This is useful when trying to eliminate such cycles. @@ -1180,6 +1310,9 @@ generation are: ``-v3`` and ``-v4``; see :ref:`options-help`.) .. ghc-flag:: -dep-makefile ⟨file⟩ + :shortdesc: Use ⟨file⟩ as the makefile + :type: dynamic + :category: Use ⟨file⟩ as the makefile, rather than ``makefile`` or ``Makefile``. If ⟨file⟩ doesn't exist, ``mkdependHS`` creates it. We @@ -1188,6 +1321,10 @@ generation are: ``Makefile``. .. ghc-flag:: -dep-suffix ⟨suffix⟩ + :shortdesc: Make dependencies that declare that files with suffix + ``.⟨suf⟩⟨osuf⟩`` depend on interface files with suffix ``.⟨suf⟩hi`` + :type: dynamic + :category: Make dependencies that declare that files with suffix ``.⟨suf⟩⟨osuf⟩`` depend on interface files with suffix @@ -1199,11 +1336,18 @@ generation are: then pass ``-dep-suffix ''``. .. ghc-flag:: --exclude-module=⟨file⟩ + :shortdesc: Regard ``⟨file⟩`` as "stable"; i.e., exclude it from having + dependencies on it. + :type: dynamic + :category: Regard ``⟨file⟩`` as "stable"; i.e., exclude it from having dependencies on it. .. ghc-flag:: -include-pkg-deps + :shortdesc: Regard modules imported from packages as unstable + :type: dynamic + :category: Regard modules imported from packages as unstable, i.e., generate dependencies on any imported package modules (including ``Prelude``, diff --git a/docs/users_guide/shared_libs.rst b/docs/users_guide/shared_libs.rst index 486df51ad9..7e525019ca 100644 --- a/docs/users_guide/shared_libs.rst +++ b/docs/users_guide/shared_libs.rst @@ -207,6 +207,10 @@ library directories of all the packages that the program depends on paths. The unix tool ``readelf --dynamic`` is handy for inspecting the ``RPATH``/``RUNPATH`` entries in ELF shared libraries and executables. +On most UNIX platforms it is also possible to build executables that can be +``dlopen``\'d like shared libraries using the :ghc-flag:`-pie` flag during +linking. + .. _finding-shared-libs-mac: Mac OS X diff --git a/docs/users_guide/using-concurrent.rst b/docs/users_guide/using-concurrent.rst index 32e24256c3..da27708b5d 100644 --- a/docs/users_guide/using-concurrent.rst +++ b/docs/users_guide/using-concurrent.rst @@ -76,6 +76,10 @@ the :ghc-flag:`-threaded` option (see :ref:`options-linker`). Additionally, the following compiler options affect parallelism: .. ghc-flag:: -feager-blackholing + :shortdesc: Turn on :ref:`eager blackholing <parallel-compile-options>` + :type: dynamic + :category: + :noindex: Blackholing is the act of marking a thunk (lazy computation) as being under evaluation. It is useful for three reasons: firstly it @@ -129,6 +133,8 @@ use the RTS :rts-flag:`-N ⟨x⟩` options. value of ⟨x⟩ itself based on how many processors are in your machine. + Omitting ``-N⟨x⟩`` entirely means ``-N1``. + With ``-maxN⟨x⟩``, i.e. ``+RTS -maxN3 -RTS``, the runtime will choose at most (x), also limited by the number of processors on the system. Omitting (x) is an error, if you need a default use option ``-N``. diff --git a/docs/users_guide/using-optimisation.rst b/docs/users_guide/using-optimisation.rst index 15916b2690..da066e158c 100644 --- a/docs/users_guide/using-optimisation.rst +++ b/docs/users_guide/using-optimisation.rst @@ -50,6 +50,9 @@ compile quickly; I'm not over-bothered about compiled-code quality.” So, for example, ``ghc -c Foo.hs`` .. ghc-flag:: -O0 + :shortdesc: Disable optimisations (default) + :type: dynamic + :category: optimization-levels Means "turn off all optimisation", reverting to the same settings as if no ``-O`` options had been specified. Saying ``-O0`` can be @@ -58,6 +61,10 @@ So, for example, ``ghc -c Foo.hs`` .. ghc-flag:: -O -O1 + :shortdesc: Enable level 1 optimisations + :type: dynamic + :reverse: -O0 + :category: optimization-levels .. index:: single: optimise; normally @@ -66,6 +73,10 @@ So, for example, ``ghc -c Foo.hs`` it." Thus, for example: ``ghc -c -O Main.lhs`` .. ghc-flag:: -O2 + :shortdesc: Enable level 2 optimisations + :type: dynamic + :reverse: -O0 + :category: optimization-levels .. index:: single: optimise; aggressively @@ -77,15 +88,6 @@ So, for example, ``ghc -c Foo.hs`` runtime or space *worse* if you're unlucky. They are normally turned on or off individually. -.. ghc-flag:: -Odph - - .. index:: - single: optimise; DPH - - Enables all ``-O2`` optimisation, sets - ``-fmax-simplifier-iterations=20`` and ``-fsimplifier-phases=3``. - Designed for use with :ref:`Data Parallel Haskell (DPH) <dph>`. - We don't use a ``-O*`` flag for day-to-day work. We use ``-O`` to get respectable speed; e.g., when we want to measure something. When we want to go for broke, we tend to use ``-O2`` (and we go for lots of coffee @@ -109,6 +111,10 @@ need to set any of them explicitly. A flag ``-fwombat`` can be negated by saying ``-fno-wombat``. .. ghc-flag:: -fcase-merge + :shortdesc: Enable case-merging. Implied by :ghc-flag:`-O`. + :type: dynamic + :reverse: -fno-case-merge + :category: :default: on @@ -129,6 +135,10 @@ by saying ``-fno-wombat``. Green -> e2 .. ghc-flag:: -fcase-folding + :shortdesc: Enable constant folding in case expressions. Implied by :ghc-flag:`-O`. + :type: dynamic + :reverse: -fno-case-folding + :category: :default: on @@ -148,12 +158,30 @@ by saying ``-fno-wombat``. _ -> let v = x `minusWord#` 10## in e3 .. ghc-flag:: -fcall-arity + :shortdesc: Enable call-arity optimisation. Implied by :ghc-flag:`-O`. + :type: dynamic + :reverse: -fno-call-arity + :category: :default: on Enable call-arity analysis. +.. ghc-flag:: -fexitification + :shortdesc: Enables exitification optimisation. Implied by :ghc-flag:`-O`. + :type: dynamic + :reverse: -fno-exitification + :category: + + :default: on + + Enables the floating of exit paths out of recursive functions. + .. ghc-flag:: -fcmm-elim-common-blocks + :shortdesc: Enable Cmm common block elimination. Implied by :ghc-flag:`-O`. + :type: dynamic + :reverse: -fno-cmm-elim-common-blocks + :category: :default: on @@ -162,6 +190,10 @@ by saying ``-fno-wombat``. Cmm blocks and eliminate the duplicates. .. ghc-flag:: -fcmm-sink + :shortdesc: Enable Cmm sinking. Implied by :ghc-flag:`-O`. + :type: dynamic + :reverse: -fno-cmm-sink + :category: :default: on @@ -171,13 +203,38 @@ by saying ``-fno-wombat``. to their usage sites. It also inlines simple expressions like literals or registers. +.. ghc-flag:: -fasm-shortcutting + :shortdesc: Enable shortcutting on assembly. Implied by :ghc-flag:`-O2`. + :type: dynamic + :reverse: -fno-asm-shortcutting + :category: + + :default: off + + This enables shortcutting at the assembly stage of the code generator. + In simpler terms shortcutting means if a block of instructions A only consists + of a unconditionally jump, we replace all jumps to A by jumps to the successor + of A. + + This is mostly done during Cmm passes. However this can miss corner cases. So at -O2 + we run the pass again at the asm stage to catch these. + + .. ghc-flag:: -fcpr-anal + :shortdesc: Turn on CPR analysis in the demand analyser. Implied by :ghc-flag:`-O`. + :type: dynamic + :reverse: -fno-cpr-anal + :category: :default: on Turn on CPR analysis in the demand analyser. .. ghc-flag:: -fcse + :shortdesc: Enable common sub-expression elimination. Implied by :ghc-flag:`-O`. + :type: dynamic + :reverse: -fno-cse + :category: :default: on @@ -186,6 +243,11 @@ by saying ``-fno-wombat``. ``unsafePerformIO`` expressions that you don't want commoned-up. .. ghc-flag:: -fstg-cse + :shortdesc: Enable common sub-expression elimination on the STG + intermediate language + :type: dynamic + :reverse: -fno-stg-cse + :category: :default: on @@ -194,6 +256,10 @@ by saying ``-fno-wombat``. that differ in their types, but not their represetation. .. ghc-flag:: -fdicts-cheap + :shortdesc: Make dictionary-valued expressions seem cheap to the optimiser. + :type: dynamic + :reverse: -fno-dicts-cheap + :category: :default: off @@ -201,18 +267,31 @@ by saying ``-fno-wombat``. seem cheap to the optimiser. .. ghc-flag:: -fdicts-strict + :shortdesc: Make dictionaries strict + :type: dynamic + :reverse: -fno-dicts-strict + :category: :default: off Make dictionaries strict. .. ghc-flag:: -fdmd-tx-dict-sel + :shortdesc: Use a special demand transformer for dictionary selectors. + Always enabled by default. + :type: dynamic + :reverse: -fno-dmd-tx-dict-sel + :category: :default: on Use a special demand transformer for dictionary selectors. .. ghc-flag:: -fdo-eta-reduction + :shortdesc: Enable eta-reduction. Implied by :ghc-flag:`-O`. + :type: dynamic + :reverse: -fno-do-eta-reduction + :category: :default: on @@ -220,12 +299,19 @@ by saying ``-fno-wombat``. lambdas. .. ghc-flag:: -fdo-lambda-eta-expansion + :shortdesc: Enable lambda eta-expansion. Always enabled by default. + :type: dynamic + :reverse: -fno-do-lambda-eta-expansion + :category: :default: on Eta-expand let-bindings to increase their arity. .. ghc-flag:: -feager-blackholing + :shortdesc: Turn on :ref:`eager blackholing <parallel-compile-options>` + :type: dynamic + :category: :default: off @@ -234,7 +320,13 @@ by saying ``-fno-wombat``. a shared-memory multiprocessor <http://community.haskell.org/~simonmar/papers/multiproc.pdf>`__. + See :ref:`parallel-compile-options` for a dicussion on its use. + .. ghc-flag:: -fexcess-precision + :shortdesc: Enable excess intermediate precision + :type: dynamic + :reverse: -fno-excess-precision + :category: :default: off @@ -250,6 +342,10 @@ by saying ``-fno-wombat``. :ref:`bugs-ghc`. .. ghc-flag:: -fexpose-all-unfoldings + :shortdesc: Expose all unfoldings, even for very large or recursive functions. + :type: dynamic + :reverse: -fno-expose-all-unfoldings + :category: :default: off @@ -258,6 +354,10 @@ by saying ``-fno-wombat``. while usually GHC would avoid inlining larger functions. .. ghc-flag:: -ffloat-in + :shortdesc: Turn on the float-in transformation. Implied by :ghc-flag:`-O`. + :type: dynamic + :reverse: -fno-float-in + :category: :default: on @@ -279,6 +379,11 @@ by saying ``-fno-wombat``. allocation and helping the garbage collector and allocator. .. ghc-flag:: -ffull-laziness + :shortdesc: Turn on full laziness (floating bindings outwards). + Implied by :ghc-flag:`-O`. + :type: dynamic + :reverse: -fno-full-laziness + :category: :default: on @@ -300,6 +405,11 @@ by saying ``-fno-wombat``. don't rely on it. .. ghc-flag:: -ffun-to-thunk + :shortdesc: Allow worker-wrapper to convert a function closure into a thunk + if the function does not use any of its arguments. Off by default. + :type: dynamic + :reverse: -fno-fun-to-thunk + :category: :default: off @@ -309,6 +419,10 @@ by saying ``-fno-wombat``. This flag allows worker/wrapper to remove *all* value lambdas. .. ghc-flag:: -fignore-asserts + :shortdesc: Ignore assertions in the source. Implied by :ghc-flag:`-O`. + :type: dynamic + :reverse: -fno-ignore-asserts + :category: :default: on @@ -317,6 +431,10 @@ by saying ``-fno-wombat``. :ref:`assertions`). .. ghc-flag:: -fignore-interface-pragmas + :shortdesc: Ignore pragmas in interface files. Implied by :ghc-flag:`-O0` only. + :type: dynamic + :reverse: -fno-ignore-interface-pragmas + :category: :default: off @@ -326,6 +444,11 @@ by saying ``-fno-wombat``. information. .. ghc-flag:: -flate-dmd-anal + :shortdesc: Run demand analysis again, at the end of the + simplification pipeline + :type: dynamic + :reverse: -fno-late-dmd-anal + :category: :default: off @@ -337,6 +460,10 @@ by saying ``-fno-wombat``. so is the cost. See notes on the :ghc-wiki:`Trac wiki page <LateDmd>`. .. ghc-flag:: -fliberate-case + :shortdesc: Turn on the liberate-case transformation. Implied by :ghc-flag:`-O2`. + :type: dynamic + :reverse: -fno-liberate-case + :category: :default: off but enabled with :ghc-flag:`-O2`. @@ -346,12 +473,22 @@ by saying ``-fno-wombat``. free variables rather than arguments. .. ghc-flag:: -fliberate-case-threshold=⟨n⟩ + :shortdesc: *default: 2000.* Set the size threshold for the liberate-case + transformation to ⟨n⟩ + :type: dynamic + :reverse: -fno-liberate-case-threshold + :category: :default: 2000 Set the size threshold for the liberate-case transformation. .. ghc-flag:: -floopification + :shortdesc: Turn saturated self-recursive tail-calls into local jumps in the + generated assembly. Implied by :ghc-flag:`-O`. + :type: dynamic + :reverse: -fno-loopification + :category: :default: on @@ -359,7 +496,23 @@ by saying ``-fno-wombat``. self-recursive saturated tail calls into local jumps rather than function calls. +.. ghc-flag:: -fllvm-pass-vectors-in-regs + :shortdesc: Pass vector value in vector registers for function calls + :type: dynamic + :reverse: -fno-llvm-pass-vectors-in-regs + :category: + + :default: on + + Instructs GHC to use the platform's native vector registers to pass vector + arguments during function calls. As with all vector support, this requires + :ghc-flag:`-fllvm`. + .. ghc-flag:: -fmax-inline-alloc-size=⟨n⟩ + :shortdesc: *default: 128.* Set the maximum size of inline array allocations + to ⟨n⟩ bytes (default: 128). + :type: dynamic + :category: :default: 128 @@ -369,12 +522,20 @@ by saying ``-fno-wombat``. value should be quite a bit smaller than the block size (typically: 4096). .. ghc-flag:: -fmax-inline-memcpy-insns=⟨n⟩ + :shortdesc: *default: 32.* Inline ``memcpy`` calls if they would generate no + more than ⟨n⟩ pseudo instructions. + :type: dynamic + :category: :default: 32 Inline ``memcpy`` calls if they would generate no more than ⟨n⟩ pseudo-instructions. .. ghc-flag:: -fmax-inline-memset-insns=⟨n⟩ + :shortdesc: *default: 32.* Inline ``memset`` calls if they would generate no + more than ⟨n⟩ pseudo instructions + :type: dynamic + :category: :default: 32 @@ -382,7 +543,11 @@ by saying ``-fno-wombat``. instructions. .. ghc-flag:: -fmax-relevant-binds=⟨n⟩ - -fno-max-relevant-bindings + :shortdesc: *default: 6.* Set the maximum number of bindings to display in + type error messages. + :type: dynamic + :reverse: -fno-max-relevant-bindings + :category: verbosity :default: 6 @@ -394,17 +559,11 @@ by saying ``-fno-wombat``. they may be numerous), but ``-fno-max-relevant-bindings`` includes them too. -.. ghc-flag:: -fmax-valid-substitutions=⟨n⟩ - -fno-max-valid-substitutions - - :default: 6 - - The type checker sometimes displays a list of valid substitutions - for typed holes in error messages, but only up to some maximum number, - set by this flag. Turning it off with - ``-fno-max-valid-substitutions`` gives an unlimited number. - .. ghc-flag:: -fmax-uncovered-patterns=⟨n⟩ + :shortdesc: *default: 4.* Set the maximum number of patterns to display in + warnings about non-exhaustive ones. + :type: dynamic + :category: :default: 4 @@ -412,32 +571,50 @@ by saying ``-fno-wombat``. :ghc-flag:`-Wincomplete-patterns` and :ghc-flag:`-Wincomplete-uni-patterns`. .. ghc-flag:: -fmax-simplifier-iterations=⟨n⟩ + :shortdesc: *default: 4.* Set the max iterations for the simplifier. + :type: dynamic + :category: :default: 4 Sets the maximal number of iterations for the simplifier. .. ghc-flag:: -fmax-worker-args=⟨n⟩ + :shortdesc: *default: 10.* If a worker has that many arguments, none will + be unpacked anymore. + :type: dynamic + :category: :default: 10 If a worker has that many arguments, none will be unpacked anymore. .. ghc-flag:: -fno-opt-coercion + :shortdesc: Turn off the coercion optimiser + :type: dynamic + :category: - :default: off + :default: coercion optimisation enabled. Turn off the coercion optimiser. .. ghc-flag:: -fno-pre-inlining + :shortdesc: Turn off pre-inlining + :type: dynamic + :category: - :default: off + :default: pre-inlining enabled Turn off pre-inlining. .. ghc-flag:: -fno-state-hack + :shortdesc: Turn off the \state hack\ whereby any lambda with a real-world + state token as argument is considered to be single-entry. Hence + OK to inline things inside it. + :type: dynamic + :category: - :default: off + :default: state hack is enabled Turn off the "state hack" whereby any lambda with a ``State#`` token as argument is considered to be single-entry, hence it is considered @@ -445,8 +622,12 @@ by saying ``-fno-wombat``. and ST monad code, but it runs the risk of reducing sharing. .. ghc-flag:: -fomit-interface-pragmas + :shortdesc: Don't generate interface pragmas. Implied by :ghc-flag:`-O0` only. + :type: dynamic + :reverse: -fno-omit-interface-pragmas + :category: - :default: off + :default: Implied by :ghc-flag:`-O0`, otherwise off. Tells GHC to omit all inessential information from the interface file generated for the module being compiled (say M). This means @@ -458,8 +639,12 @@ by saying ``-fno-wombat``. type, not when they change their implementation). .. ghc-flag:: -fomit-yields + :shortdesc: Omit heap checks when no allocation is being performed. + :type: dynamic + :reverse: -fno-omit-yields + :category: - :default: on + :default: yield points enabled Tells GHC to omit heap checks when no allocation is being performed. While this improves binary sizes by about 5%, it @@ -470,6 +655,14 @@ by saying ``-fno-wombat``. turned off, if you need to guarantee interruptibility. .. ghc-flag:: -fpedantic-bottoms + :shortdesc: Make GHC be more precise about its treatment of bottom (but see + also :ghc-flag:`-fno-state-hack`). In particular, GHC will not + eta-expand through a case expression. + :type: dynamic + :reverse: -fno-pedantic-bottoms + :category: + + :default: off Make GHC be more precise about its treatment of bottom (but see also :ghc-flag:`-fno-state-hack`). In particular, stop GHC eta-expanding through @@ -477,6 +670,11 @@ by saying ``-fno-wombat``. using ``seq`` on partial applications. .. ghc-flag:: -fregs-graph + :shortdesc: Use the graph colouring register allocator for register + allocation in the native code generator. Implied by :ghc-flag:`-O2`. + :type: dynamic + :reverse: -fno-regs-graph + :category: :default: off due to a performance regression bug (:ghc-ticket:`7679`) @@ -490,6 +688,11 @@ by saying ``-fno-wombat``. when faced with code with high register pressure :ghc-ticket:`8657`. .. ghc-flag:: -fregs-iterative + :shortdesc: Use the iterative coalescing graph colouring register allocator + in the native code generator. + :type: dynamic + :reverse: -fno-regs-iterative + :category: :default: off @@ -500,12 +703,19 @@ by saying ``-fno-wombat``. during register allocation. .. ghc-flag:: -fsimplifier-phases=⟨n⟩ + :shortdesc: *default: 2.* Set the number of phases for the simplifier. + Ignored with :ghc-flag:`-O0`. + :type: dynamic + :category: :default: 2 Set the number of phases for the simplifier. Ignored with ``-O0``. .. ghc-flag:: -fsimpl-tick-factor=⟨n⟩ + :shortdesc: *default: 100.* Set the percentage factor for simplifier ticks. + :type: dynamic + :category: :default: 100 @@ -526,6 +736,10 @@ by saying ``-fno-wombat``. accurately, because some numbers are very large. .. ghc-flag:: -fspec-constr + :shortdesc: Turn on the SpecConstr transformation. Implied by :ghc-flag:`-O2`. + :type: dynamic + :reverse: -fno-spec-constr + :category: :default: off but enabled by :ghc-flag:`-O2`. @@ -590,6 +804,11 @@ by saying ``-fno-wombat``. cases. .. ghc-flag:: -fspec-constr-keen + :shortdesc: Specialize a call with an explicit constructor argument, + even if the argument is not scrutinised in the body of the function + :type: dynamic + :reverse: -fno-spec-constr-keen + :category: :default: off @@ -600,6 +819,12 @@ by saying ``-fno-wombat``. that can itself be specialised. .. ghc-flag:: -fspec-constr-count=⟨n⟩ + :shortdesc: default: 3.* Set to ⟨n⟩ the maximum number of specialisations that + will be created for any one function by the SpecConstr + transformation. + :type: dynamic + :reverse: -fno-spec-constr-count + :category: :default: 3 @@ -607,12 +832,21 @@ by saying ``-fno-wombat``. any one function by the SpecConstr transformation. .. ghc-flag:: -fspec-constr-threshold=⟨n⟩ + :shortdesc: *default: 2000.* Set the size threshold for the SpecConstr + transformation to ⟨n⟩. + :type: dynamic + :reverse: -fno-spec-constr-threshold + :category: :default: 2000 Set the size threshold for the SpecConstr transformation. .. ghc-flag:: -fspecialise + :shortdesc: Turn on specialisation of overloaded functions. Implied by :ghc-flag:`-O`. + :type: dynamic + :reverse: -fno-specialise + :category: :default: on @@ -623,6 +857,11 @@ by saying ``-fno-wombat``. specialised as well. .. ghc-flag:: -fspecialise-aggressively + :shortdesc: Turn on specialisation of overloaded functions regardless of + size, if unfolding is available + :type: dynamic + :reverse: -fno-specialise-aggressively + :category: :default: off @@ -635,6 +874,11 @@ by saying ``-fno-wombat``. .. ghc-flag:: -fcross-module-specialise + :shortdesc: Turn on specialisation of overloaded functions imported from + other modules. + :type: dynamic + :reverse: -fno-cross-module-specialise + :category: :default: on @@ -643,7 +887,28 @@ by saying ``-fno-wombat``. which they are called in this module. Note that specialisation must be enabled (by ``-fspecialise``) for this to have any effect. +.. ghc-flag:: -flate-specialise + :shortdesc: Run a late specialisation pass + :type: dynamic + :reverse: -fno-late-specialise + :category: + + :default: off + + Runs another specialisation pass towards the end of the optimisation + pipeline. This can catch specialisation opportunities which arose from + the previous specialisation pass or other inlining. + + You might want to use this if you are you have a type class method + which returns a constrained type. For example, a type class where one + of the methods implements a traversal. + .. ghc-flag:: -fsolve-constant-dicts + :shortdesc: When solving constraints, try to eagerly solve + super classes using available dictionaries. + :type: dynamic + :reverse: -fno-solve-constant-dicts + :category: :default: on @@ -675,6 +940,10 @@ by saying ``-fno-wombat``. .. ghc-flag:: -fstatic-argument-transformation + :shortdesc: Turn on the static argument transformation. + :type: dynamic + :reverse: -fno-static-argument-transformation + :category: :default: off @@ -684,6 +953,11 @@ by saying ``-fno-wombat``. thesis <http://research.microsoft.com/en-us/um/people/simonpj/papers/santos-thesis.ps.gz>`__ .. ghc-flag:: -fstrictness + :shortdesc: Turn on strictness analysis. + Implied by :ghc-flag:`-O`. Implies :ghc-flag:`-fworker-wrapper` + :type: dynamic + :reverse: -fno-strictness + :category: :default: on @@ -698,10 +972,18 @@ by saying ``-fno-wombat``. arguments. .. ghc-flag:: -fstrictness-before=⟨n⟩ + :shortdesc: Run an additional strictness analysis before simplifier phase ⟨n⟩ + :type: dynamic + :category: Run an additional strictness analysis before simplifier phase ⟨n⟩. .. ghc-flag:: -funbox-small-strict-fields + :shortdesc: Flatten strict constructor fields with a pointer-sized + representation. Implied by :ghc-flag:`-O`. + :type: dynamic + :reverse: -fno-unbox-small-strict-fields + :category: :default: on @@ -737,6 +1019,10 @@ by saying ``-fno-wombat``. they are technically larger than a pointer on those platforms. .. ghc-flag:: -funbox-strict-fields + :shortdesc: Flatten strict constructor fields + :type: dynamic + :reverse: -fno-unbox-strict-fields + :category: :default: off @@ -760,6 +1046,9 @@ by saying ``-fno-wombat``. unbox strict fields which are "small". .. ghc-flag:: -funfolding-creation-threshold=⟨n⟩ + :shortdesc: *default: 750.* Tweak unfolding settings. + :type: dynamic + :category: :default: 750 @@ -783,6 +1072,9 @@ by saying ``-fno-wombat``. useful. .. ghc-flag:: -funfolding-dict-discount=⟨n⟩ + :shortdesc: *default: 30.* Tweak unfolding settings. + :type: dynamic + :category: :default: 30 @@ -793,6 +1085,9 @@ by saying ``-fno-wombat``. How eager should the compiler be to inline dictionaries? .. ghc-flag:: -funfolding-fun-discount=⟨n⟩ + :shortdesc: *default: 60.* Tweak unfolding settings. + :type: dynamic + :category: :default: 60 @@ -803,6 +1098,9 @@ by saying ``-fno-wombat``. How eager should the compiler be to inline functions? .. ghc-flag:: -funfolding-keeness-factor=⟨n⟩ + :shortdesc: *default: 1.5.* Tweak unfolding settings. + :type: dynamic + :category: :default: 1.5 @@ -813,6 +1111,9 @@ by saying ``-fno-wombat``. How eager should the compiler be to inline functions? .. ghc-flag:: -funfolding-use-threshold=⟨n⟩ + :shortdesc: *default: 60.* Tweak unfolding settings. + :type: dynamic + :category: :default: 60 @@ -832,33 +1133,3 @@ by saying ``-fno-wombat``. 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. - -.. ghc-flag:: -fvectorisation-avoidance - - :default: on - - .. index:: - single: -fvectorisation-avoidance - - Part of :ref:`Data Parallel Haskell (DPH) <dph>`. - - Enable the *vectorisation* avoidance optimisation. - This optimisation only works when used in combination with the - ``-fvectorise`` transformation. - - While vectorisation of code using DPH is often a big win, it can - also produce worse results for some kinds of code. This optimisation - modifies the vectorisation transformation to try to determine if a - function would be better of unvectorised and if so, do just that. - -.. ghc-flag:: -fvectorise - - :default: off - - Part of :ref:`Data Parallel Haskell (DPH) <dph>`. - - 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, - enable SIMD parallelism and friendlier cache behaviour. diff --git a/docs/users_guide/using-warnings.rst b/docs/users_guide/using-warnings.rst index 48a9296b1a..d93064b464 100644 --- a/docs/users_guide/using-warnings.rst +++ b/docs/users_guide/using-warnings.rst @@ -20,23 +20,32 @@ generally likely to indicate bugs in your program. These are: * :ghc-flag:`-Wdeprecations` * :ghc-flag:`-Wdeprecated-flags` * :ghc-flag:`-Wunrecognised-pragmas` - * :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:`-Wsimplifiable-class-constraints` + * :ghc-flag:`-Wtyped-holes` + * :ghc-flag:`-Wdeferred-type-errors` + * :ghc-flag:`-Wpartial-type-signatures` * :ghc-flag:`-Wunsupported-calling-conventions` * :ghc-flag:`-Wdodgy-foreign-imports` * :ghc-flag:`-Winline-rule-shadowing` * :ghc-flag:`-Wunsupported-llvm-version` * :ghc-flag:`-Wtabs` * :ghc-flag:`-Wunrecognised-warning-flags` + * :ghc-flag:`-Winaccessible-code` + * :ghc-flag:`-Wstar-binder` The following flags are simple ways to select standard "packages" of warnings: .. ghc-flag:: -W + :shortdesc: enable normal warnings + :type: dynamic + :reverse: -w + :category: Provides the standard warnings plus @@ -53,6 +62,10 @@ The following flags are simple ways to select standard "packages" of warnings: * :ghc-flag:`-Wunbanged-strict-patterns` .. ghc-flag:: -Wall + :shortdesc: enable almost all warnings (details in :ref:`options-sanity`) + :type: dynamic + :reverse: -w + :category: Turns on all warning options that indicate potentially suspicious code. The warnings that are *not* enabled by :ghc-flag:`-Wall` are @@ -66,12 +79,28 @@ The following flags are simple ways to select standard "packages" of warnings: * :ghc-flag:`-Wimplicit-prelude` * :ghc-flag:`-Wmissing-local-signatures` * :ghc-flag:`-Wmissing-exported-signatures` + * :ghc-flag:`-Wmissing-export-lists` * :ghc-flag:`-Wmissing-import-lists` * :ghc-flag:`-Wmissing-home-modules` * :ghc-flag:`-Widentities` * :ghc-flag:`-Wredundant-constraints` + * :ghc-flag:`-Wpartial-fields` + * :ghc-flag:`-Wmissed-specialisations` + * :ghc-flag:`-Wall-missed-specialisations` + +.. ghc-flag:: -Weverything + :shortdesc: enable all warnings supported by GHC + :type: dynamic + :category: + + Turns on every single warning supported by the compiler. .. ghc-flag:: -Wcompat + :shortdesc: enable future compatibility warnings + (details in :ref:`options-sanity`) + :type: dynamic + :reverse: -Wno-compat + :category: 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 @@ -86,12 +115,20 @@ The following flags are simple ways to select standard "packages" of warnings: * :ghc-flag:`-Wmissing-monadfail-instances` * :ghc-flag:`-Wsemigroup` * :ghc-flag:`-Wnoncanonical-monoid-instances` + * :ghc-flag:`-Wimplicit-kind-vars` .. ghc-flag:: -Wno-compat + :shortdesc: Disables all warnings enabled by :ghc-flag:`-Wcompat`. + :type: dynamic + :reverse: -Wcompat + :category: Disables all warnings enabled by :ghc-flag:`-Wcompat`. .. ghc-flag:: -w + :shortdesc: disable all warnings + :type: dynamic + :category: Turns off all warnings, including the standard ones and those that :ghc-flag:`-Wall` doesn't enable. @@ -100,11 +137,19 @@ These options control which warnings are considered fatal and cause compilation to abort. .. ghc-flag:: -Werror + :shortdesc: make warnings fatal + :type: dynamic + :reverse: -Wwarn + :category: Makes any warning into a fatal error. Useful so that you don't miss warnings when doing batch compilation. .. ghc-flag:: -Werror=⟨wflag⟩ + :shortdesc: make a specific warning fatal + :type: dynamic + :reverse: -Wwarn=⟨wflag⟩ + :category: :noindex: :implies: ``-W<wflag>`` @@ -112,12 +157,23 @@ to abort. Makes a specific warning into a fatal error. The warning will be enabled if it hasn't been enabled yet. + ``-Werror=compat`` has the same effect as ``-Werror=...`` for each warning + flag in the :ghc-flag:`-Wcompat` option group. + .. ghc-flag:: -Wwarn + :shortdesc: make warnings non-fatal + :type: dynamic + :reverse: -Werror + :category: Warnings are treated only as warnings, not as errors. This is the default, but can be useful to negate a :ghc-flag:`-Werror` flag. .. ghc-flag:: -Wwarn=⟨wflag⟩ + :shortdesc: make a specific warning non-fatal + :type: dynamic + :reverse: -Werror=⟨wflag⟩ + :category: :noindex: Causes a specific warning to be treated as normal warning, not fatal error. @@ -125,10 +181,17 @@ to abort. Note that it doesn't fully negate the effects of ``-Werror=<wflag>`` - the warning will still be enabled. + ``-Wwarn=compat`` has the same effect as ``-Wwarn=...`` for each warning + flag in the :ghc-flag:`-Wcompat` option group. + When a warning is emitted, the specific warning flag which controls it is shown. .. ghc-flag:: -fshow-warning-groups + :shortdesc: show which group an emitted warning belongs to. + :type: dynamic + :reverse: -fno-show-warning-groups + :category: When showing which flag controls a warning, also show the respective warning group flag(s) that warning is contained in. @@ -142,6 +205,11 @@ all these warnings can still be controlled with ``-f(no-)warn-*`` instead of ``-W(no-)*``. .. ghc-flag:: -Wunrecognised-warning-flags + :shortdesc: throw a warning when an unreconised ``-W...`` flag is + encountered on the command line. + :type: dynamic + :reverse: -Wno-unrecognised-warning-flags + :category: Enables warnings when the compiler encounters a ``-W...`` flag that is not recognised. @@ -149,6 +217,12 @@ of ``-W(no-)*``. This warning is on by default. .. ghc-flag:: -Wtyped-holes + :shortdesc: Report warnings when :ref:`typed hole <typed-holes>` errors are + :ref:`deferred until runtime <defer-type-errors>`. See + :ghc-flag:`-fdefer-typed-holes`. + :type: dynamic + :reverse: -Wno-typed-holes + :category: Determines whether the compiler reports typed holes warnings. Has no effect unless typed holes errors are deferred until runtime. See @@ -156,7 +230,13 @@ of ``-W(no-)*``. This warning is on by default. -.. ghc-flag:: -Wtype-errors +.. ghc-flag:: -Wdeferred-type-errors + :shortdesc: Report warnings when :ref:`deferred type errors + <defer-type-errors>` are enabled. This option is enabled by + default. See :ghc-flag:`-fdefer-type-errors`. + :type: dynamic + :reverse: -Wno-deferred-type-errors + :category: Causes a warning to be reported when a type error is deferred until runtime. See :ref:`defer-type-errors` @@ -164,8 +244,16 @@ of ``-W(no-)*``. This warning is on by default. .. ghc-flag:: -fdefer-type-errors + :shortdesc: Turn type errors into warnings, :ref:`deferring the error until + runtime <defer-type-errors>`. Implies + :ghc-flag:`-fdefer-typed-holes` and + :ghc-flag:`-fdefer-out-of-scope-variables`. + See also :ghc-flag:`-Wdeferred-type-errors` + :type: dynamic + :reverse: -fno-defer-type-errors + :category: - :implies: :ghc-flag:`-fdefer-typed-holes` + :implies: :ghc-flag:`-fdefer-typed-holes`, :ghc-flag:`-fdefer-out-of-scope-variables` 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 @@ -174,6 +262,13 @@ of ``-W(no-)*``. :ref:`defer-type-errors` .. ghc-flag:: -fdefer-typed-holes + :shortdesc: Convert :ref:`typed hole <typed-holes>` errors into warnings, + :ref:`deferring the error until runtime <defer-type-errors>`. + Implied by :ghc-flag:`-fdefer-type-errors`. + See also :ghc-flag:`-Wtyped-holes`. + :type: dynamic + :reverse: -fno-defer-typed-holes + :category: Defer typed holes errors (errors about names with a leading underscore (e.g., “_”, “_foo”, “_bar”)) until runtime. This will turn the errors @@ -185,20 +280,40 @@ of ``-W(no-)*``. Implied by :ghc-flag:`-fdefer-type-errors`. See also :ghc-flag:`-Wtyped-holes`. .. ghc-flag:: -fdefer-out-of-scope-variables + :shortdesc: Convert variable out of scope variables errors into warnings. + Implied by :ghc-flag:`-fdefer-type-errors`. + See also :ghc-flag:`-Wdeferred-out-of-scope-variables`. + :type: dynamic + :reverse: -fno-defer-out-of-scope-variables + :category: Defer variable out-of-scope errors (errors about names without a leading underscore) until runtime. This will turn variable-out-of-scope errors into warnings. - Using a value that depends on a typed hole produces a runtime error, + Using a value that depends on an out-of-scope variable produces a runtime error, the same as :ghc-flag:`-fdefer-type-errors` (which implies this option). See :ref:`typed-holes` and :ref:`defer-type-errors`. Implied by :ghc-flag:`-fdefer-type-errors`. See also :ghc-flag:`-Wdeferred-out-of-scope-variables`. .. ghc-flag:: -Wdeferred-out-of-scope-variables + :shortdesc: Report warnings when variable out-of-scope errors are + :ref:`deferred until runtime <defer-type-errors>`. + See :ghc-flag:`-fdefer-out-of-scope-variables`. + :type: dynamic + :reverse: -Wno-deferred-out-of-scope-variables + :category: Warn when a deferred out-of-scope variable is encountered. .. ghc-flag:: -Wpartial-type-signatures + :shortdesc: warn about holes in partial type signatures when + :ghc-flag:`-XPartialTypeSignatures` is enabled. Not applicable when + :ghc-flag:`-XPartialTypesignatures` is not enabled, in which case + errors are generated for such holes. See + :ref:`partial-type-signatures`. + :type: dynamic + :reverse: -Wno-partial-type-signatures + :category: Determines whether the compiler reports holes in partial type signatures as warnings. Has no effect unless @@ -209,6 +324,10 @@ of ``-W(no-)*``. This warning is on by default. .. ghc-flag:: -fhelpful-errors + :shortdesc: Make suggestions for mis-spelled names. + :type: dynamic + :reverse: -fno-helpful-errors + :category: When a name or package is not found in scope, make suggestions for the name or package you might have meant instead. @@ -216,6 +335,10 @@ of ``-W(no-)*``. This option is on by default. .. ghc-flag:: -Wunrecognised-pragmas + :shortdesc: warn about uses of pragmas that GHC doesn't recognise + :type: dynamic + :reverse: -Wno-unrecognised-pragmas + :category: 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 @@ -225,22 +348,47 @@ of ``-W(no-)*``. This option is on by default. .. ghc-flag:: -Wmissed-specialisations - -Wall-missed-specialisations + :shortdesc: warn when specialisation of an imported, overloaded function + fails. + :type: dynamic + :reverse: -Wno-missed-specialisations + :category: Emits a warning if GHC cannot specialise an overloaded function, usually - because the function needs an ``INLINABLE`` pragma. The "all" form reports - all such situations whereas the "non-all" form only reports when the + because the function needs an ``INLINABLE`` pragma. Reports when the situation arises during specialisation of an imported function. - The "non-all" form is intended to catch cases where an imported function - that is marked as ``INLINABLE`` (presumably to enable specialisation) cannot - be specialised as it calls other functions that are themselves not specialised. + This form is intended to catch cases where an imported function + that is marked as ``INLINABLE`` (presumably to enable specialisation) + cannot be specialised as it calls other functions that are themselves not + specialised. + + Note that this warning will not throw errors if used with + :ghc-flag:`-Werror`. + + This option is off by default. + +.. ghc-flag:: -Wall-missed-specialisations + :shortdesc: warn when specialisation of any overloaded function fails. + :type: dynamic + :reverse: -Wno-all-missed-specialisations + :category: + + Emits a warning if GHC cannot specialise an overloaded function, usually + because the function needs an ``INLINABLE`` pragma. Reports + all such situations. - Note that these warnings will not throw errors if used with :ghc-flag:`-Werror`. + Note that this warning will not throw errors if used with + :ghc-flag:`-Werror`. - These options are both off by default. + This option is off by default. .. ghc-flag:: -Wwarnings-deprecations + :shortdesc: warn about uses of functions & types that have warnings or + deprecated pragmas + :type: dynamic + :reverse: -Wno-warnings-deprecations + :category: .. index:: pair: deprecations; warnings @@ -252,6 +400,11 @@ of ``-W(no-)*``. This option is on by default. .. ghc-flag:: -Wdeprecations + :shortdesc: warn about uses of functions & types that have warnings or + deprecated pragmas. Alias for :ghc-flag:`-Wwarnings-deprecations` + :type: dynamic + :reverse: -Wno-deprecations + :category: .. index:: single: deprecations @@ -263,18 +416,14 @@ of ``-W(no-)*``. This option is on by default. -.. ghc-flag:: -Wamp - - .. index:: - single: AMP - single: Applicative-Monad Proposal - - This option is deprecated. - - Caused a warning to be emitted when a definition was in conflict with - the AMP (Applicative-Monad proosal). - .. ghc-flag:: -Wnoncanonical-monad-instances + :shortdesc: warn when ``Applicative`` or ``Monad`` instances have + noncanonical definitions of ``return``, ``pure``, ``(>>)``, + or ``(*>)``. + See flag description in :ref:`options-sanity` for more details. + :type: dynamic + :reverse: -Wno-noncanonical-monad-instances + :category: Warn if noncanonical ``Applicative`` or ``Monad`` instances declarations are detected. @@ -295,6 +444,12 @@ of ``-W(no-)*``. This option is off by default. .. ghc-flag:: -Wnoncanonical-monadfail-instances + :shortdesc: warn when ``Monad`` or ``MonadFail`` instances have + noncanonical definitions of ``fail``. + See flag description in :ref:`options-sanity` for more details. + :type: dynamic + :reverse: -Wno-noncanonical-monadfail-instances + :category: Warn if noncanonical ``Monad`` or ``MonadFail`` instances declarations are detected. @@ -317,6 +472,12 @@ of ``-W(no-)*``. This option is off by default. .. ghc-flag:: -Wnoncanonical-monoid-instances + :shortdesc: warn when ``Semigroup`` or ``Monoid`` instances have + noncanonical definitions of ``(<>)`` or ``mappend``. + See flag description in :ref:`options-sanity` for more details. + :type: dynamic + :reverse: -Wno-noncanonical-monoid-instances + :category: Warn if noncanonical ``Semigroup`` or ``Monoid`` instances declarations are detected. @@ -337,6 +498,11 @@ of ``-W(no-)*``. :ghc-flag:`-Wcompat` option group. .. ghc-flag:: -Wmissing-monadfail-instances + :shortdesc: Warn when a failable pattern is used in a do-block that does + not have a ``MonadFail`` instance. + :type: dynamic + :reverse: -Wno-missing-monadfail-instances + :category: .. index:: single: MFP @@ -353,6 +519,11 @@ of ``-W(no-)*``. <https://prime.haskell.org/wiki/Libraries/Proposals/MonadFail>`__. .. ghc-flag:: -Wsemigroup + :shortdesc: warn when a ``Monoid`` is not ``Semigroup``, and on non- + ``Semigroup`` definitions of ``(<>)``? + :type: dynamic + :reverse: -Wno-semigroup + :category: .. index:: single: semigroup; warning @@ -368,6 +539,10 @@ of ``-W(no-)*``. default, but will be switched on in a future GHC release. .. ghc-flag:: -Wdeprecated-flags + :shortdesc: warn about uses of commandline flags that are deprecated + :type: dynamic + :reverse: -Wno-deprecated-flags + :category: .. index:: single: deprecated flags @@ -378,6 +553,10 @@ of ``-W(no-)*``. This option is on by default. .. ghc-flag:: -Wunsupported-calling-conventions + :shortdesc: warn about use of an unsupported calling convention + :type: dynamic + :reverse: -Wno-unsupported-calling-conventions + :category: Causes a warning to be emitted for foreign declarations that use unsupported calling conventions. In particular, if the ``stdcall`` @@ -385,6 +564,10 @@ of ``-W(no-)*``. it will be treated as ``ccall``. .. ghc-flag:: -Wdodgy-foreign-imports + :shortdesc: warn about dodgy foreign imports + :type: dynamic + :reverse: -Wno-dodgy-foreign-import + :category: Causes a warning to be emitted for foreign imports of the following form: :: @@ -395,14 +578,18 @@ of ``-W(no-)*``. foreign import "&f" f :: FunPtr t - The first form declares that \`f\` is a (pure) C function that takes - no arguments and returns a pointer to a C function with type \`t\`, - whereas the second form declares that \`f\` itself is a C function - with type \`t\`. The first declaration is usually a mistake, and one + The first form declares that ``f`` is a (pure) C function that takes + no arguments and returns a pointer to a C function with type ``t``, + whereas the second form declares that ``f`` itself is a C function + with type ``t``. The first declaration is usually a mistake, and one that is hard to debug because it results in a crash, hence this warning. .. ghc-flag:: -Wdodgy-exports + :shortdesc: warn about dodgy exports + :type: dynamic + :reverse: -Wno-dodgy-exports + :category: Causes a warning to be emitted when a datatype ``T`` is exported with all constructors, i.e. ``T(..)``, but is it just a type @@ -412,6 +599,10 @@ of ``-W(no-)*``. but that module exports nothing. .. ghc-flag:: -Wdodgy-imports + :shortdesc: warn about dodgy imports + :type: dynamic + :reverse: -Wno-dodgy-imports + :category: Causes a warning to be emitted in the following cases: @@ -422,16 +613,28 @@ of ``-W(no-)*``. exported. .. ghc-flag:: -Woverflowed-literals + :shortdesc: warn about literals that will overflow their type + :type: dynamic + :reverse: -Wno-overflowed-literals + :category: Causes a warning to be emitted if a literal will overflow, e.g. ``300 :: Word8``. .. ghc-flag:: -Wempty-enumerations + :shortdesc: warn about enumerations that are empty + :type: dynamic + :reverse: -Wno-empty-enumerations + :category: Causes a warning to be emitted if an enumeration is empty, e.g. ``[5 .. 3]``. .. ghc-flag:: -Wduplicate-constraints + :shortdesc: warn when a constraint appears duplicated in a type signature + :type: dynamic + :reverse: -Wno-duplicate-constraints + :category: .. index:: single: duplicate constraints, warning @@ -447,6 +650,11 @@ of ``-W(no-)*``. :ghc-flag:`-Wredundant-constraints`. .. ghc-flag:: -Wredundant-constraints + :shortdesc: Have the compiler warn about redundant constraints in type + signatures. + :type: dynamic + :reverse: -Wno-redundant-constraints + :category: :since: 8.0 @@ -475,8 +683,8 @@ of ``-W(no-)*``. Similar warnings are given for a redundant constraint in an instance declaration. - This option is on by default. As usual you can suppress it on a - per-module basis with :ghc-flag:`-Wno-redundant-constraints <-Wredundant-constraints>`. + When turning on, you can suppress it on a per-module basis with + :ghc-flag:`-Wno-redundant-constraints <-Wredundant-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 @@ -492,6 +700,10 @@ of ``-W(no-)*``. constraint is needed, so no warning is issued. .. ghc-flag:: -Wduplicate-exports + :shortdesc: warn when an entity is exported multiple times + :type: dynamic + :reverse: -Wno-duplicate-exports + :category: .. index:: single: duplicate exports, warning @@ -505,6 +717,10 @@ of ``-W(no-)*``. This option is on by default. .. ghc-flag:: -Whi-shadowing + :shortdesc: warn when a ``.hi`` file in the current directory shadows a library + :type: dynamic + :reverse: -Wno-hi-shadowing + :category: .. index:: single: shadowing; interface files @@ -514,6 +730,11 @@ of ``-W(no-)*``. name in a library or other directory. .. ghc-flag:: -Widentities + :shortdesc: warn about uses of Prelude numeric conversions that are probably + the identity (and hence could be omitted) + :type: dynamic + :reverse: -Wno-identities + :category: Causes the compiler to emit a warning when a Prelude numeric conversion converts a type ``T`` to the same type ``T``; such calls are @@ -521,27 +742,86 @@ of ``-W(no-)*``. ``toInteger``, ``toRational``, ``fromIntegral``, and ``realToFrac``. .. ghc-flag:: -Wimplicit-prelude + :shortdesc: warn when the Prelude is implicitly imported + :type: dynamic + :reverse: -Wno-implicit-prelude + :category: .. index:: 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 :ghc-flag:`-XNoImplicitPrelude` or a - ``LANGUAGE NoImplicitPrelude`` pragma). + 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 + :ghc-flag:`-XNoImplicitPrelude` or a ``LANGUAGE NoImplicitPrelude`` + pragma). - Note that no warning is given for syntax that implicitly refers to - 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 - imports of the module being compiled). + Note that no warning is given for syntax that implicitly refers to 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 imports of the module + being compiled). This warning is off by default. +.. ghc-flag:: -Wimplicit-kind-vars + :shortdesc: warn when kind variables are brought into scope implicitly despite + the "forall-or-nothing" rule + :type: dynamic + :reverse: -Wno-implicit-kind-vars + :category: + + :since: 8.6 + + `GHC proposal #24 + <https://github.com/ghc-proposals/ghc-proposals/blob/master/proposals/0024-no-kind-vars.rst>`__ + prescribes to treat kind variables and type variables identically in + ``forall``, removing the legacy distinction between them. + + Consider the following examples: :: + + f :: Proxy a -> Proxy b -> () + g :: forall a b. Proxy a -> Proxy b -> () + + ``f`` does not use an explicit ``forall``, so type variables ``a`` and ``b`` + are brought into scope implicitly. ``g`` quantifies both ``a`` and ``b`` + explicitly. Both ``f`` and ``g`` work today and will continue to work in the + future because they adhere to the "forall-or-nothing" rule: either all type + variables in a function definition are introduced explicitly or implicitly, + there is no middle ground. + + A violation of the "forall-or-nothing" rule looks like this: :: + + m :: forall a. Proxy a -> Proxy b -> () + + ``m`` does not introduce one of the variables, ``b``, and thus is rejected. + + However, consider the following example: :: + + n :: forall a. Proxy (a :: k) -> () + + While ``n`` uses ``k`` without introducing it and thus violates the rule, it + is currently accepted. This is because ``k`` in ``n`` is considered a kind + variable, as it occurs in a kind signature. In reality, the line between + type variables and kind variables is blurry, as the following example + demonstrates: :: + + kindOf :: forall a. Proxy (a :: k) -> Proxy k + + In ``kindOf``, the ``k`` variable is used both in a kind position and a type + position. Currently, ``kindOf`` happens to be accepted as well. + + In a future release of GHC, both ``n`` and ``kindOf`` will be rejected per + the "forall-or-nothing" rule. This warning, being part of the + :ghc-flag:`-Wcompat` option group, allows to detect this before the actual + breaking change takes place. + .. ghc-flag:: -Wincomplete-patterns - -Wincomplete-uni-patterns + :shortdesc: warn when a pattern match could fail + :type: dynamic + :reverse: -Wno-incomplete-patterns + :category: .. index:: single: incomplete patterns, warning @@ -559,14 +839,26 @@ of ``-W(no-)*``. generally considered good practice to cover all the cases in your functions, and it is switched on by :ghc-flag:`-W`. - 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: :: + +.. ghc-flag:: -Wincomplete-uni-patterns + :shortdesc: warn when a pattern match in a lambda expression or + pattern binding could fail + :type: dynamic + :reverse: -Wno-incomplete-uni-patterns + :category: + + The flag :ghc-flag:`-Wincomplete-uni-patterns` is similar to + :ghc-flag:`-Wincomplete-patterns`, except that it applies only to + lambda-expressions and pattern bindings, constructs that only allow a + single pattern: :: h = \[] -> 2 Just k = f y .. ghc-flag:: -fmax-pmcheck-iterations=⟨n⟩ + :shortdesc: the iteration limit for the pattern match checker + :type: dynamic + :category: :default: 2000000 @@ -579,6 +871,10 @@ of ``-W(no-)*``. pattern match, for the sake of future readers of your code. .. ghc-flag:: -Wincomplete-record-updates + :shortdesc: warn when a record update could fail + :type: dynamic + :reverse: -Wno-incomplete-record-updates + :category: .. index:: single: incomplete record updates, warning @@ -598,6 +894,10 @@ of ``-W(no-)*``. and it often doesn't indicate a bug in the program. .. ghc-flag:: -Wmissing-fields + :shortdesc: warn when fields of a record are uninitialised + :type: dynamic + :reverse: -Wno-missing-fields + :category: .. index:: single: missing fields, warning @@ -609,7 +909,37 @@ of ``-W(no-)*``. fields are initialised with bottoms), it is often an indication of a programmer error. +.. ghc-flag:: -Wmissing-export-lists + :shortdesc: warn when a module declaration does not explicitly list all + exports + :type: dynamic + :reverse: -fnowarn-missing-export-lists + :category: + + :since: 8.4.1 + + .. index:: + single: missing export lists, warning + single: export lists, missing + + This flag warns if you declare a module without declaring an explicit + export list. For example :: + + module M where + + p x = x + + The :ghc-flag:`-Wmissing-export-lists` flag will warn that ``M`` does not + declare an export list. Declaring an explicit export list for ``M`` enables + GHC dead code analysis, prevents accidental export of names and can ease + optimizations like inlining. + .. ghc-flag:: -Wmissing-import-lists + :shortdesc: warn when an import declaration does not explicitly list all the + names brought into scope + :type: dynamic + :reverse: -fnowarn-missing-import-lists + :category: .. index:: single: missing import lists, warning @@ -632,6 +962,10 @@ of ``-W(no-)*``. unlikely to produce ambiguity in ``M``. .. ghc-flag:: -Wmissing-methods + :shortdesc: warn when class methods are undefined + :type: dynamic + :reverse: -Wno-missing-methods + :category: .. index:: single: missing methods, warning @@ -641,23 +975,15 @@ of ``-W(no-)*``. declaration is missing one or more methods, and the corresponding 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: :: - - class C a where - _simpleFn :: a -> String - complexFn :: a -> a -> String - complexFn x y = ... _simpleFn ... - - The idea is that: (a) users of the class will only call - ``complexFn``; never ``_simpleFn``; and (b) instance declarations - can define either ``complexFn`` or ``_simpleFn``. - The ``MINIMAL`` pragma can be used to change which combination of methods will be required for instances of a particular class. See :ref:`minimal-pragma`. .. ghc-flag:: -Wmissing-signatures + :shortdesc: warn about top-level functions without signatures + :type: dynamic + :reverse: -Wno-missing-signatures + :category: .. index:: single: type signatures, missing @@ -668,6 +994,12 @@ of ``-W(no-)*``. option is off by default. .. ghc-flag:: -Wmissing-exported-sigs + :shortdesc: *(deprecated)* + warn about top-level functions without signatures, only if they + are exported. takes precedence over -Wmissing-signatures + :type: dynamic + :reverse: -Wno-missing-exported-sigs + :category: .. index:: single: type signatures, missing @@ -676,6 +1008,11 @@ of ``-W(no-)*``. :ghc-flag:`-Wmissing-exported-signatures`. .. ghc-flag:: -Wmissing-exported-signatures + :shortdesc: warn about top-level functions without signatures, only if they + are exported. takes precedence over -Wmissing-signatures + :type: dynamic + :reverse: -Wno-missing-exported-signatures + :category: .. index:: single: type signatures, missing @@ -688,6 +1025,11 @@ of ``-W(no-)*``. reports the inferred type. The option is off by default. .. ghc-flag:: -Wmissing-local-sigs + :shortdesc: *(deprecated)* + warn about polymorphic local bindings without signatures + :type: dynamic + :reverse: -Wno-missing-local-sigs + :category: .. index:: single: type signatures, missing @@ -696,6 +1038,10 @@ of ``-W(no-)*``. :ghc-flag:`-Wmissing-local-signatures`. .. ghc-flag:: -Wmissing-local-signatures + :shortdesc: warn about polymorphic local bindings without signatures + :type: dynamic + :reverse: -Wno-missing-local-signatures + :category: .. index:: single: type signatures, missing @@ -706,6 +1052,10 @@ of ``-W(no-)*``. default. .. ghc-flag:: -Wmissing-pattern-synonym-signatures + :shortdesc: warn when pattern synonyms do not have type signatures + :type: dynamic + :reverse: -Wno-missing-pattern-synonym-signatures + :category: .. index:: single: type signatures, missing, pattern synonyms @@ -719,6 +1069,10 @@ of ``-W(no-)*``. type. This option is off by default. .. ghc-flag:: -Wname-shadowing + :shortdesc: warn when names are shadowed + :type: dynamic + :reverse: -Wno-name-shadowing + :category: .. index:: single: shadowing, warning @@ -736,6 +1090,11 @@ of ``-W(no-)*``. f x = do { _ignore <- this; _ignore <- that; return (the other) } .. ghc-flag:: -Worphans + :shortdesc: warn when the module contains :ref:`orphan instance declarations + or rewrite rules <orphan-modules>` + :type: dynamic + :reverse: -Wno-orphans + :category: .. index:: single: orphan instances, warning @@ -758,6 +1117,10 @@ of ``-W(no-)*``. instances. .. ghc-flag:: -Woverlapping-patterns + :shortdesc: warn about overlapping patterns + :type: dynamic + :reverse: -Wno-overlapping-patterns + :category: .. index:: single: overlapping patterns, warning @@ -775,7 +1138,79 @@ 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. +.. ghc-flag:: -Winaccessible-code + :shortdesc: warn about inaccessible code + :type: dynamic + :reverse: -Wno-inaccessible-code + :category: + + .. index:: + single: inaccessible code, warning + single: inaccessible + + By default, the compiler will warn you if types make a branch inaccessible. + This generally requires GADTs or similar extensions. + + Take, for example, the following program :: + + {-# LANGUAGE GADTs #-} + + data Foo a where + Foo1 :: Foo Char + Foo2 :: Foo Int + + data TyEquality a b where + Refl :: TyEquality a a + + checkTEQ :: Foo t -> Foo u -> Maybe (TyEquality t u) + checkTEQ x y = error "unimportant" + + step2 :: Bool + step2 = case checkTEQ Foo1 Foo2 of + Just Refl -> True -- Inaccessible code + Nothing -> False + + The ``Just Refl`` case in ``step2`` is inaccessible, because in order for + ``checkTEQ`` to be able to produce a ``Just``, ``t ~ u`` must hold, but + since we're passing ``Foo1`` and ``Foo2`` here, it follows that ``t ~ + Char``, and ``u ~ Int``, and thus ``t ~ u`` cannot hold. + +.. ghc-flag:: -Wstar-binder + :shortdesc: warn about binding the ``(*)`` type operator despite + :ghc-flag:`-XStarIsType` + :type: dynamic + :reverse: -Wno-star-binder + + Under :ghc-flag:`-XStarIsType`, a ``*`` in types is not an operator nor + even a name, it is special syntax that stands for ``Data.Kind.Type``. This + means that an expression like ``Either * Char`` is parsed as ``Either (*) + Char`` and not ``(*) Either Char``. + + In binding positions, we have similar parsing rules. Consider the following + example :: + + {-# LANGUAGE TypeOperators, TypeFamilies, StarIsType #-} + + type family a + b + type family a * b + + While ``a + b`` is parsed as ``(+) a b`` and becomes a binding position for + the ``(+)`` type operator, ``a * b`` is parsed as ``a (*) b`` and is rejected. + + As a workaround, we allow to bind ``(*)`` in prefix form:: + + type family (*) a b + + This is a rather fragile arrangement, as generally a programmer expects + ``(*) a b`` to be equivalent to ``a * b``. With :ghc-flag:`-Wstar-binder` + we warn when this special treatment of ``(*)`` takes place. + .. ghc-flag:: -Wsimplifiable-class-constraints + :shortdesc: Warn about class constraints in a type signature that can + be simplified using a top-level instance declaration. + :type: dynamic + :reverse: -Wno-simplifiable-class-constraints + :category: :since: 8.2 @@ -799,6 +1234,10 @@ of ``-W(no-)*``. <-Wsimplifiable-class-constraints>`. .. ghc-flag:: -Wtabs + :shortdesc: warn if there are tabs in the source file + :type: dynamic + :reverse: -Wno-tabs + :category: .. index:: single: tabs, warning @@ -806,6 +1245,10 @@ of ``-W(no-)*``. Have the compiler warn if there are tabs in your source file. .. ghc-flag:: -Wtype-defaults + :shortdesc: warn when defaulting happens + :type: dynamic + :reverse: -Wno-type-defaults + :category: .. index:: single: defaulting mechanism, warning @@ -822,6 +1265,10 @@ of ``-W(no-)*``. This warning is off by default. .. ghc-flag:: -Wmonomorphism-restriction + :shortdesc: warn when the Monomorphism Restriction is applied + :type: dynamic + :reverse: -Wno-monomorphism-restriction + :category: .. index:: single: monomorphism restriction, warning @@ -834,10 +1281,19 @@ of ``-W(no-)*``. This warning is off by default. .. ghc-flag:: -Wunsupported-llvm-version + :shortdesc: Warn when using :ghc-flag:`-fllvm` with an unsupported + version of LLVM. + :type: dynamic + :reverse: -Wno-monomorphism-restriction + :category: Warn when using :ghc-flag:`-fllvm` with an unsupported version of LLVM. .. ghc-flag:: -Wunticked-promoted-constructors + :shortdesc: warn if promoted constructors are not ticked + :type: dynamic + :reverse: -Wno-unticked-promoted-constructors + :category: .. index:: single: promoted constructor, warning @@ -859,6 +1315,12 @@ of ``-W(no-)*``. This warning is enabled by default in :ghc-flag:`-Wall` mode. .. ghc-flag:: -Wunused-binds + :shortdesc: warn about bindings that are unused. Alias for + :ghc-flag:`-Wunused-top-binds`, :ghc-flag:`-Wunused-local-binds` and + :ghc-flag:`-Wunused-pattern-binds` + :type: dynamic + :reverse: -Wno-unused-binds + :category: .. index:: single: unused binds, warning @@ -872,6 +1334,10 @@ of ``-W(no-)*``. - :ghc-flag:`-Wunused-pattern-binds` .. ghc-flag:: -Wunused-top-binds + :shortdesc: warn about top-level bindings that are unused + :type: dynamic + :reverse: -Wno-unused-top-binds + :category: .. index:: single: unused binds, warning @@ -902,6 +1368,10 @@ of ``-W(no-)*``. _w = True -- No warning: _w starts with an underscore .. ghc-flag:: -Wunused-local-binds + :shortdesc: warn about local bindings that are unused + :type: dynamic + :reverse: -Wno-unused-local-binds + :category: .. index:: single: unused binds, warning @@ -914,6 +1384,10 @@ of ``-W(no-)*``. g = h x -- No warning: g is unused, but is a top-level binding .. ghc-flag:: -Wunused-pattern-binds + :shortdesc: warn about pattern match bindings that are unused + :type: dynamic + :reverse: -Wno-unused-pattern-binds + :category: .. index:: single: unused binds, warning @@ -936,6 +1410,10 @@ of ``-W(no-)*``. it forces evaluation, and is useful as an alternative to ``seq``. .. ghc-flag:: -Wunused-imports + :shortdesc: warn about unnecessary imports + :type: dynamic + :reverse: -Wno-unused-imports + :category: .. index:: single: unused imports, warning @@ -947,6 +1425,10 @@ of ``-W(no-)*``. declarations, which are anonymous in Haskell. .. ghc-flag:: -Wunused-matches + :shortdesc: warn about variables in patterns that aren't used + :type: dynamic + :reverse: -Wno-unused-matches + :category: .. index:: single: unused matches, warning @@ -965,6 +1447,11 @@ of ``-W(no-)*``. :ghc-flag:`-Wunused-type-patterns` flag. .. ghc-flag:: -Wunused-do-bind + :shortdesc: warn about do bindings that appear to throw away values of types + other than ``()`` + :type: dynamic + :reverse: -Wno-unused-do-bind + :category: .. index:: single: unused do binding, warning @@ -986,6 +1473,11 @@ of ``-W(no-)*``. do { mapM_ popInt xs ; return 10 } .. ghc-flag:: -Wunused-type-patterns + :shortdesc: warn about unused type variables which arise from patterns + in type family and data family instances + :type: dynamic + :reverse: -Wno-unused-type-patterns + :category: .. index:: single: unused type patterns, warning @@ -1008,6 +1500,11 @@ of ``-W(no-)*``. documentation harder to read. .. ghc-flag:: -Wunused-foralls + :shortdesc: warn about type variables in user-written + ``forall``\\s that are unused + :type: dynamic + :reverse: -Wno-unused-foralls + :category: .. index:: single: unused foralls, warning @@ -1021,6 +1518,11 @@ of ``-W(no-)*``. would report ``a`` and ``c`` as unused. .. ghc-flag:: -Wwrong-do-bind + :shortdesc: warn about do bindings that appear to throw away monadic values + that you should have bound instead + :type: dynamic + :reverse: -Wno-wrong-do-bind + :category: .. index:: single: apparently erroneous do binding, warning @@ -1044,12 +1546,21 @@ of ``-W(no-)*``. do { popInt 10 ; return 10 } .. ghc-flag:: -Winline-rule-shadowing + :shortdesc: 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`. + :type: dynamic + :reverse: -Wno-inline-rule-shadowing + :category: 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`. .. ghc-flag:: -Wcpp-undef + :shortdesc: warn on uses of the `#if` directive on undefined identifiers + :type: dynamic + :category: :since: 8.2 @@ -1058,12 +1569,24 @@ of ``-W(no-)*``. undefined identifiers. .. ghc-flag:: -Wunbanged-strict-patterns + :shortdesc: warn on pattern bind of unlifted variable that is neither bare + nor banged + :type: dynamic + :reverse: -Wno-unbanged-strict-patterns + :category: This flag warns whenever you write a pattern that binds a variable whose type is unlifted, and yet the pattern is not a bang pattern nor a bare variable. See :ref:`glasgow-unboxed` for information about unlifted types. .. ghc-flag:: -Wmissing-home-modules + :shortdesc: warn when encountering a home module imported, but not listed + on the command line. Useful for cabal to ensure GHC won't pick + up modules, not listed neither in ``exposed-modules``, nor in + ``other-modules``. + :type: dynamic + :reverse: -Wno-missing-home-modules + :category: :since: 8.2 @@ -1073,7 +1596,23 @@ of ``-W(no-)*``. pick up modules, not listed neither in ``exposed-modules``, nor in ``other-modules``. +.. ghc-flag:: -Wpartial-fields + :shortdesc: warn when defining a partial record field. + :type: dynamic + :reverse: -Wno-partial-fields + :category: + + :since: 8.4 + + The option :ghc-flag:`-Wpartial-fields` warns about record fields that could + fail when accessed via a lacking constructor. The function ``f`` below will + fail when applied to ``Bar``, so the compiler will emit a warning at its + definition when :ghc-flag:`-Wpartial-fields` is enabled. + + The warning is suppressed if the field name begins with an underscore. :: + + data Foo = Foo { f :: Int } | Bar + 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 dff9603b66..9ec26f2bb2 100644 --- a/docs/users_guide/using.rst +++ b/docs/users_guide/using.rst @@ -130,7 +130,7 @@ possible to do this directly in the source file using the ``OPTIONS_GHC`` is a *file-header pragma* (see :ref:`options-pragma`). Only *dynamic* flags can be used in an ``OPTIONS_GHC`` pragma (see -:ref:`static-dynamic-flags`). +:ref:`mode-dynamic-flags`). Note that your command shell does not get to the source file options, they are just included literally in the array of command-line arguments @@ -153,37 +153,29 @@ Setting options in GHCi Options may also be modified from within GHCi, using the :ghci-cmd:`:set` command. -.. _static-dynamic-flags: +.. _mode-dynamic-flags: -Static, Dynamic, and Mode options ---------------------------------- +Dynamic and Mode options +------------------------ .. index:: - single: static; options single: dynamic; options single: mode; options -Each of GHC's command line options is classified as static, dynamic or -mode: +Each of GHC's command line options is classified as dynamic or 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`. + Mode: A mode may be used on the command line only. + You can pass only one mode flag. + For example, :ghc-flag:`--make` or :ghc-flag:`-E`. + 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 + Dynamic: A dynamic flag may be used on the command line, + in a ``OPTIONS_GHC`` pragma in a source 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. - 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 :ghci-cmd:`:set` command; these are listed as “static/\ ``:set``\ ” -in the table. - .. _file-suffixes: Meaningful file suffixes @@ -258,6 +250,10 @@ to produce an executable. The available mode flags are: .. ghc-flag:: --interactive + :shortdesc: Interactive mode - normally used by just running ``ghci``; + see :ref:`ghci` for details. + :type: mode + :category: modes .. index:: single: interactive mode @@ -267,6 +263,11 @@ The available mode flags are: mode is described in more detail in :ref:`ghci`. .. ghc-flag:: --make + :shortdesc: Build a multi-module Haskell program, automatically figuring out + dependencies. Likely to be much easier, and faster, than using + ``make``; see :ref:`make-mode` for details. + :type: mode + :category: modes .. index:: single: make mode; of GHC @@ -282,6 +283,9 @@ The available mode flags are: option can be omitted. .. ghc-flag:: -e ⟨expr⟩ + :shortdesc: Evaluate ``expr``; see :ref:`eval-mode` for details. + :type: mode + :category: modes .. index:: single: eval mode; of GHC @@ -292,15 +296,42 @@ The available mode flags are: details. .. ghc-flag:: -E - -C - -S - -c + :shortdesc: Stop after preprocessing (``.hspp`` file) + :type: mode + :category: phases + + Stop after preprocessing (``.hspp`` file) + +.. ghc-flag:: -C + :shortdesc: Stop after generating C (``.hc`` file) + :type: mode + :category: phases + + Stop after generating C (``.hc`` file) + +.. ghc-flag:: -S + :shortdesc: Stop after generating assembly (``.s`` file) + :type: mode + :category: phases + + Stop after generating assembly (``.s`` file) + +.. ghc-flag:: -c + :shortdesc: Stop after generating object (``.o``) file + :type: mode + :category: phases + + Stop after generating object (``.o``) file This is the traditional batch-compiler mode, in which GHC can compile source files one at a time, or link objects together into an executable. See :ref:`options-order`. .. ghc-flag:: -M + :shortdesc: generate dependency information suitable for use in a + ``Makefile``; see :ref:`makefile-dependencies` for details. + :type: mode + :category: modes .. index:: single: dependency-generation mode; of GHC @@ -310,6 +341,10 @@ The available mode flags are: See :ref:`makefile-dependencies`. .. ghc-flag:: --frontend ⟨module⟩ + :shortdesc: run GHC with the given frontend plugin; see + :ref:`frontend_plugins` for details. + :type: mode + :category: modes .. index:: single: frontend plugins; using @@ -318,6 +353,9 @@ The available mode flags are: details. .. ghc-flag:: --mk-dll + :shortdesc: DLL-creation mode (Windows only) + :type: mode + :category: modes .. index:: single: DLL-creation mode @@ -326,39 +364,63 @@ The available mode flags are: .. ghc-flag:: --help -? + :shortdesc: Display help + :type: mode + :category: modes Cause GHC to spew a long usage message to standard output and then exit. .. ghc-flag:: --show-iface ⟨file⟩ + :shortdesc: display the contents of an interface file. + :type: mode + :category: modes Read the interface in ⟨file⟩ and dump it as text to ``stdout``. For example ``ghc --show-iface M.hi``. .. ghc-flag:: --supported-extensions --supported-languages + :shortdesc: display the supported language extensions + :type: mode + :category: modes Print the supported language extensions. .. ghc-flag:: --show-options + :shortdesc: display the supported command line options + :type: mode + :category: modes Print the supported command line options. This flag can be used for autocompletion in a shell. .. ghc-flag:: --info + :shortdesc: display information about the compiler + :type: mode + :category: modes Print information about the compiler. .. ghc-flag:: --version -V + :shortdesc: display GHC version + :type: mode + :category: modes Print a one-line string including GHC's version number. .. ghc-flag:: --numeric-version + :shortdesc: display GHC version (numeric only) + :type: mode + :category: modes Print GHC's numeric version number only. .. ghc-flag:: --print-libdir + :shortdesc: display GHC library directory + :type: mode + :category: modes .. index:: single: libdir @@ -446,6 +508,10 @@ directory; the :ghc-flag:`-i` option can be used to add directories to the search path (see :ref:`search-path`). .. ghc-flag:: -j[⟨n⟩] + :shortdesc: When compiling with :ghc-flag:`--make`, compile ⟨n⟩ modules + in parallel. + :type: dynamic + :category: misc Perform compilation in parallel when possible. GHC will use up to ⟨N⟩ threads during compilation. If N is omitted, then it defaults to the @@ -554,6 +620,9 @@ suffix. This behaviour can be overridden using the :ghc-flag:`-x ⟨suffix⟩` option: .. ghc-flag:: -x ⟨suffix⟩ + :shortdesc: Override default behaviour for source files + :type: dynamic + :category: phases Causes all files following this option on the command line to be processed as if they had the suffix ⟨suffix⟩. For example, to @@ -572,6 +641,9 @@ See also the ``--help``, ``--version``, ``--numeric-version``, and ``--print-libdir`` modes in :ref:`modes`. .. ghc-flag:: -v + :shortdesc: verbose mode (equivalent to ``-v3``) + :type: dynamic + :category: verbosity 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 @@ -583,8 +655,10 @@ 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. -.. ghc-flag:: -v ⟨n⟩ - :noindex: +.. ghc-flag:: -v⟨n⟩ + :shortdesc: set verbosity level + :type: dynamic + :category: verbosity To provide more control over the compiler's verbosity, the ``-v`` flag takes an optional numeric argument. Specifying ``-v`` on its @@ -613,12 +687,19 @@ See also the ``--help``, ``--version``, ``--numeric-version``, and (excluding preprocessed and C/assembly files). .. ghc-flag:: -fprint-potential-instances + :shortdesc: display all available instances in type error messages + :type: dynamic + :reverse: -fno-print-potential-instances + :category: verbosity 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. .. ghc-flag:: -fhide-source-paths + :shortdesc: hide module source and object paths + :type: dynamic + :category: verbosity Starting with minimal verbosity (``-v1``, see :ghc-flag:`-v`), GHC displays the name, the source path and the target path of each compiled @@ -629,6 +710,11 @@ The following flags control the way in which GHC displays types in error messages and in GHCi: .. ghc-flag:: -fprint-unicode-syntax + :shortdesc: Use unicode syntax when printing expressions, types and kinds. + See also :ghc-flag:`-XUnicodeSyntax` + :type: dynamic + :reverse: -fno-print-unicode-syntax + :category: verbosity When enabled GHC prints type signatures using the unicode symbols from the :ghc-flag:`-XUnicodeSyntax` extension. For instance, @@ -636,12 +722,17 @@ messages and in GHCi: .. code-block:: none ghci> :set -fprint-unicode-syntax - ghci> :t (>>) - (>>) :: ∀ (m :: * → *) a b. Monad m ⇒ m a → m b → m b + ghci> :t +v (>>) + (>>) ∷ Monad m ⇒ ∀ a b. m a → m b → m b .. _pretty-printing-types: .. ghc-flag:: -fprint-explicit-foralls + :shortdesc: Print explicit ``forall`` quantification in types. + See also :ghc-flag:`-XExplicitForAll` + :type: dynamic + :reverse: -fno-print-explicit-foralls + :category: verbosity Using :ghc-flag:`-fprint-explicit-foralls` makes GHC print explicit ``forall`` quantification at the top level of a @@ -678,6 +769,11 @@ messages and in GHCi: -- Defined in Data.Type.Equality .. ghc-flag:: -fprint-explicit-kinds + :shortdesc: Print explicit kind foralls and kind arguments in types. + See also :ghc-flag:`-XKindSignatures` + :type: dynamic + :reverse: -fno-print-explicit-kinds + :category: verbosity Using :ghc-flag:`-fprint-explicit-kinds` makes GHC print kind arguments in types, which are normally suppressed. This can be important when you @@ -694,10 +790,15 @@ messages and in GHCi: MkT :: forall (k :: BOX) (a :: k). T k a .. ghc-flag:: -fprint-explicit-runtime-reps + :shortdesc: Print ``RuntimeRep`` variables in types which are + runtime-representation polymorphic. + :type: dynamic + :reverse: -fno-print-explicit-runtime-reps + :category: verbosity When :ghc-flag:`-fprint-explicit-runtime-reps` is enabled, GHC prints ``RuntimeRep`` type variables for levity-polymorphic types. - Otherwise GHC will default these to ``PtrRepLifted``. For example, + Otherwise GHC will default these to ``LiftedRep``. For example, .. code-block:: none @@ -710,6 +811,10 @@ messages and in GHCi: (a -> b) -> a -> b .. ghc-flag:: -fprint-explicit-coercions + :shortdesc: Print coercions in types + :type: dynamic + :reverse: -fno-print-explicit-coercions + :category: verbosity Using :ghc-flag:`-fprint-explicit-coercions` makes GHC print coercions in types. When trying to prove the equality between types of different @@ -717,6 +822,10 @@ messages and in GHCi: see these, as they are meant to be internal. .. ghc-flag:: -fprint-equality-relations + :shortdesc: Distinguish between equality relations when printing + :type: dynamic + :reverse: -fno-print-equality-relations + :category: verbosity Using :ghc-flag:`-fprint-equality-relations` tells GHC to distinguish between its equality relations when printing. For example, ``~`` is homogeneous @@ -729,6 +838,10 @@ messages and in GHCi: prints all of these as ``~``. See also :ref:`equality-constraints`. .. ghc-flag:: -fprint-expanded-synonyms + :shortdesc: In type errors, also print type-synonym-expanded types. + :type: dynamic + :reverse: -fno-print-expanded-synonyms + :category: verbosity When enabled, GHC also prints type-synonym-expanded types in type errors. For example, with this type synonyms: :: @@ -757,6 +870,10 @@ messages and in GHCi: Actual type: ST s Bool .. ghc-flag:: -fprint-typechecker-elaboration + :shortdesc: Print extra information from typechecker. + :type: dynamic + :reverse: -fno-print-typechecker-elaboration + :category: verbosity When enabled, GHC also prints extra information from the typechecker in warnings. For example: :: @@ -794,6 +911,9 @@ messages and in GHCi: or by using the flag -fno-warn-unused-do-bind .. ghc-flag:: -fdiagnostics-color=⟨always|auto|never⟩ + :shortdesc: Use colors in error messages + :type: dynamic + :category: verbosity Causes GHC to display error messages with colors. To do this, the terminal must have support for ANSI color codes, or else garbled text will @@ -833,13 +953,20 @@ messages and in GHCi: or ``always``, which is equivalent to setting the corresponding ``-fdiagnostics-color`` flag but with lower precedence. -.. ghc-flag:: -f[no-]diagnostics-show-caret +.. ghc-flag:: -fdiagnostics-show-caret + :shortdesc: Whether to show snippets of original source code + :type: dynamic + :reverse: -fno-diagnostics-show-caret + :category: verbosity Controls whether GHC displays a line of the original source code where the error was detected. This also affects the associated caret symbol that points at the region of code at fault. The flag is on by default. .. ghc-flag:: -ferror-spans + :shortdesc: Output full span in error messages + :type: dynamic + :category: verbosity Causes GHC to emit the full source span of the syntactic entity relating to an error message. Normally, GHC emits the source @@ -872,11 +999,17 @@ messages and in GHCi: (i.e. this is how Emacs does it). .. ghc-flag:: -H ⟨size⟩ + :shortdesc: Set the minimum size of the heap to ⟨size⟩ + :type: dynamic + :category: misc Set the minimum size of the heap to ⟨size⟩. This option is equivalent to ``+RTS -Hsize``, see :ref:`rts-options-gc`. .. ghc-flag:: -Rghc-timing + :shortdesc: Summarise timing stats for GHC (same as ``+RTS -tstderr``). + :type: dynamic + :category: verbosity Prints a one-line summary of timing statistics for the GHC run. This option is equivalent to ``+RTS -tstderr``, see @@ -895,6 +1028,9 @@ Platform-specific Flags Some flags only make sense for particular target platforms. .. ghc-flag:: -msse2 + :shortdesc: (x86 only) Use SSE2 for floating-point operations + :type: dynamic + :category: platform-options (x86 only, added in GHC 7.0.1) Use the SSE2 registers and instruction set to implement floating point operations when using @@ -909,6 +1045,9 @@ Some flags only make sense for particular target platforms. SSE2 is unconditionally used on x86-64 platforms. .. ghc-flag:: -msse4.2 + :shortdesc: (x86 only) Use SSE4.2 for floating-point operations + :type: dynamic + :category: platform-options (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 @@ -917,3 +1056,26 @@ Some flags only make sense for particular target platforms. and later). The :ref:`LLVM backend <llvm-code-gen>` will also use SSE4.2 if your processor supports it but detects this automatically so no flag is required. + +Miscellaneous flags +------------------- + +.. index:: + single: miscellaneous flags + +Some flags only make sense for a particular use case. + +.. ghc-flag:: -ghcversion-file ⟨path to ghcversion.h⟩ + :shortdesc: (GHC as a C compiler only) Use this ``ghcversion.h`` file + :type: dynamic + :category: misc + + When GHC is used to compile C files, GHC adds package include paths and + includes ``ghcversion.h`` directly. The compiler will lookup the path for + the ``ghcversion.h`` file from the ``rts`` package in the package database. + In some cases, the compiler's package database does not contain the ``rts`` + package, or one wants to specify a specific ``ghcversions.h`` to be + included. This option can be used to specify the path to the + ``ghcversions.h`` file to be included. This is primarily intended to be + used by GHC's build system. + diff --git a/docs/users_guide/utils.py b/docs/users_guide/utils.py new file mode 100644 index 0000000000..128ae51ba5 --- /dev/null +++ b/docs/users_guide/utils.py @@ -0,0 +1,26 @@ +from docutils import nodes + +# Taken from Docutils source inside the ListTable class. We must bypass +# using the class itself, but this function comes in handy. +def build_table_from_list(table_data, col_widths): + table = nodes.table() + tgroup = nodes.tgroup(cols=len(col_widths)) + table += tgroup + for col_width in col_widths: + colspec = nodes.colspec(colwidth=col_width) + tgroup += colspec + rows = [] + for row in table_data: + row_node = nodes.row() + for cell in row: + entry = nodes.entry() + entry += cell + row_node += entry + rows.append(row_node) + thead = nodes.thead() + thead.extend(rows[:1]) + tgroup += thead + tbody = nodes.tbody() + tbody.extend(rows[1:]) + tgroup += tbody + return table diff --git a/docs/users_guide/what_glasgow_exts_does.rst b/docs/users_guide/what_glasgow_exts_does.rst new file mode 100644 index 0000000000..1c1d3a2a7b --- /dev/null +++ b/docs/users_guide/what_glasgow_exts_does.rst @@ -0,0 +1,33 @@ +.. hlist:: + + * :extension:`ConstrainedClassMethods` + * :extension:`DeriveDataTypeable` + * :extension:`DeriveFoldable` + * :extension:`DeriveFunctor` + * :extension:`DeriveGeneric` + * :extension:`DeriveTraversable` + * :extension:`EmptyDataDecls` + * :extension:`ExistentialQuantification` + * :extension:`ExplicitNamespaces` + * :extension:`FlexibleContexts` + * :extension:`FlexibleInstances` + * :extension:`ForeignFunctionInterface` + * :extension:`FunctionalDependencies` + * :extension:`GeneralizedNewtypeDeriving` + * :extension:`ImplicitParams` + * :extension:`KindSignatures` + * :extension:`LiberalTypeSynonyms` + * :extension:`MagicHash` + * :extension:`MultiParamTypeClasses` + * :extension:`ParallelListComp` + * :extension:`PatternGuards` + * :extension:`PostfixOperators` + * :extension:`RankNTypes` + * :extension:`RecursiveDo` + * :extension:`ScopedTypeVariables` + * :extension:`StandaloneDeriving` + * :extension:`TypeOperators` + * :extension:`TypeSynonymInstances` + * :extension:`UnboxedTuples` + * :extension:`UnicodeSyntax` + * :extension:`UnliftedFFITypes` diff --git a/docs/users_guide/win32-dlls.rst b/docs/users_guide/win32-dlls.rst index 26c3ffe3b0..4ecdd10f72 100644 --- a/docs/users_guide/win32-dlls.rst +++ b/docs/users_guide/win32-dlls.rst @@ -97,6 +97,52 @@ Windows. ``IOExts.hSetBinaryMode``. The ``IOExts`` module is part of the ``lang`` package. +.. _windows-file-paths: + +File paths under Windows +------------------------ + +Windows paths are not all the same. The different kinds of paths each have +different meanings. The ``MAX_PATH`` limitation is not a limitation of the operating +system nor the file system. It is a limitation of the default namespace enforced +by the Win32 API for backwards compatibility. + +The NT kernel however allows you ways to opt out of this path preprocessing by +the Win32 APIs. This is done by explicitly using the desired namespace in the +path. + +The namespaces are: + + - file namespace: ``\\?\`` + - device namespace: ``\\.\`` + - NT namespace: ``\`` + +Each of these turn off path processing completely by the Win32 API and the paths +are passed untouched to the filesystem. + +Paths with a drive letter are *legacy* paths. The drive letters are actually +meaningless to the kernel. Just like Unix operating systems, drive letters are +just a mount point. You can view your mount points by using the :command:`mountvol` +command. + +Since GHC 8.6.1, the Haskell I/O manager automatically promotes paths in the legacy +format to Win32 file namespace. By default the I/O manager will do two things to +your paths: + + - replace ``\`` with ``\\`` + - expand relative paths to absolute paths + +If you want to opt out of all preprocessing just expliticly use namespaces in +your paths. Due to this change, if you need to open raw devices (e.g. COM ports) +you need to use the device namespace explicitly. (e.g. ``\\.\COM1``). GHC and +Haskell programs in general no longer support opening devices in the legacy +format. + +See the +`Windows documentation <https://msdn.microsoft.com/en-us/library/windows/desktop/aa365247.aspx>`_ +for more details. + + .. _ghci-cygwin: Using GHC (and other GHC-compiled executables) with Cygwin |