diff options
author | Simon Marlow <simonmar@microsoft.com> | 2006-04-07 02:05:11 +0000 |
---|---|---|
committer | Simon Marlow <simonmar@microsoft.com> | 2006-04-07 02:05:11 +0000 |
commit | 0065d5ab628975892cea1ec7303f968c3338cbe1 (patch) | |
tree | 8e2afe0ab48ee33cf95009809d67c9649573ef92 /docs/users_guide | |
parent | 28a464a75e14cece5db40f2765a29348273ff2d2 (diff) | |
download | haskell-0065d5ab628975892cea1ec7303f968c3338cbe1.tar.gz |
Reorganisation of the source tree
Most of the other users of the fptools build system have migrated to
Cabal, and with the move to darcs we can now flatten the source tree
without losing history, so here goes.
The main change is that the ghc/ subdir is gone, and most of what it
contained is now at the top level. The build system now makes no
pretense at being multi-project, it is just the GHC build system.
No doubt this will break many things, and there will be a period of
instability while we fix the dependencies. A straightforward build
should work, but I haven't yet fixed binary/source distributions.
Changes to the Building Guide will follow, too.
Diffstat (limited to 'docs/users_guide')
30 files changed, 23990 insertions, 0 deletions
diff --git a/docs/users_guide/5-00-notes.xml b/docs/users_guide/5-00-notes.xml new file mode 100644 index 0000000000..28712472c6 --- /dev/null +++ b/docs/users_guide/5-00-notes.xml @@ -0,0 +1,207 @@ +<?xml version="1.0" encoding="iso-8859-1"?> +<sect1 id="release-5-00"> + <title>Release notes for version 5.00 (April 2001)</title> + + <sect2> + <title>User-visible compiler changes</title> + <itemizedlist> + <listitem> + <para>GHCi, the new interactive environment on top of GHC, has + been added (<xref linkend="ghci">).</para> + </listitem> + <listitem> + <para>New <option>––make</option> flag added (<xref + linkend="make-mode">).</para> + </listitem> + <listitem> + <para>The native code generator now supports Sparc in addition + to x86.</para> + </listitem> + <listitem> + <para>We now make it clear which options can be placed in an + OPTIONS pragma. See <xref + linkend="static-dynamic-flags">.</para> + </listitem> + <listitem> + <para><option>-fglasgow-exts</option> no longer implies + <option>-package lang</option>.</para> + </listitem> + <listitem> + <para><option>-noC</option> is no more.</para> + </listitem> + <listitem> + <para><option>-hi</option> and <option>-nohi</option> are no more.</para> + </listitem> + <listitem> + <para>The concept of “packages” has been + generalised and extended. Packages may be installed or + removed from an existing GHC installation using the new + <command>ghc-pkg</command> tool. See <xref + linkend="packages">.</para> + </listitem> + <listitem> + <para>Initial unicode support: the <literal>Char</literal> + type is now 31 bits. We don't yet have support for unicode + I/O.</para> + </listitem> + <listitem> + <para><option>-v</option> now takes an optional numeric + argument indicating the level of verbosity (<xref + linkend="options-help">). <option>-dshow-passes</option> has + been removed.</para> + </listitem> + <listitem> + <para>Parallel list comprehensions added. See <xref + linkend="parallel-list-comprehensions">.</para> + </listitem> + <listitem> + <para>Functional dependencies are now fully implemented. + </para> + </listitem> + <listitem> + <para>Profiling: please use + <literal>{-# SCC ".." #-}</literal> + rather than <literal>_scc_ "..."</literal>. The latter + will be phased out in due course.</para> + </listitem> + <listitem> + <para>A new experimental optimisation, SpecConstr, is turned + on with <literal>-O2</literal>.</para> + </listitem> + <listitem> + <para>Please report bugs using the <ulink + url="http://sourceforge.net/projects/ghc/">SourceForge bug + tracker</ulink> instead of + <email>glasgow-haskell-bugs@haskell.org</email> if + possible.</para> + </listitem> + <listitem> + <para>Documentation changes: there's now a useful Flag + Reference section, see <xref linkend="flag-reference">.</para> + </listitem> + <listitem> + <para>Many, many, bugfixes.</para> + </listitem> + </itemizedlist> + </sect2> + + <sect2> + <title>New experimental features</title> + + <itemizedlist> + <listitem> + <para>A “front panel” for GHC-compiled programs + displays real-time graphs of memory behaviour in a GTK+ + window. You need to recompile the RTS with front panel + support to use this.</para> + </listitem> + </itemizedlist> + </sect2> + + <sect2> + <title>FFI changes</title> + <itemizedlist> + <listitem> + <para><command>hsc2hs</command> added (<xref linkend="hsc2hs">).</para> + </listitem> + <listitem> + <para>FFI libraries have been updated to the latest proposal + from the FFI task force. Too many changes to list here, see + the docs: <xref linkend="sec-Foreign">.</para> + </listitem> + </itemizedlist> + </sect2> + + <sect2> + <title>User-visible library changes</title> + <itemizedlist> + <listitem> + <para><function>putMVar</function> now blocks if the + <literal>MVar</literal> is already full. The + <literal>PutFullMVar</literal> exception no longer exists. + A non-blocking version of <function>putMVar</function>, + <function>tryPutMVar</function>, has been added (<xref + linkend="sec-MVars">).</para> + </listitem> + <listitem> + <para>The <literal>Int</literal> and + <literal>Integer</literal> types now have instances of + <literal>Bits</literal> (<xref linkend="sec-Bits">).</para> + </listitem> + <listitem> + <para>Package <literal>hssource</literal> has been added. It + contains a Haskell 98 abstract syntax, parser, lexer and pretty + printer. No documentation yet.</para> + </listitem> + <listitem> + <para>The methods <literal>fromInt</literal> and + <literal>toInt</literal>, which used to be in class + <literal>Num</literal> but exported from module + <literal>Int</literal>, are no longer in class + <literal>Num</literal>. They're still available from module + <literal>Int</literal>, however.</para> + + <para>In most cases, there should be no benefit from using + <literal>fromInt</literal> instead of + <literal>fromIntegral</literal>, which is specialised for all + integral types.</para> + </listitem> + <listitem> + <para>New modules: DiffArray (<xref linkend="sec-DiffArray">), + StorableArray (<xref linkend="sec-StorableArray">), + MonadList, MonadCont (no documentation yet).</para> + </listitem> + </itemizedlist> + </sect2> + + <sect2> + <title>Build system changes</title> + + <itemizedlist> + <listitem> + <para>The <literal>WithGhcHc</literal> setting in + <literal>build.mk</literal> has been replaced by the + <literal>––with-ghc=<replaceable>ghc</replaceable></literal> + option to <literal>configure</literal>. The new option + <emphasis>must</emphasis> be used if you intend to use + anything except “<literal>ghc</literal>” to + bootstrap GHC, in order that the build system can figure out + what version of GHC you're using.</para> + </listitem> + <listitem> + <para>Source distributions are now made by doing <literal>make + distclean</literal> in a build tree, instead of requiring a + linked build tree.</para> + </listitem> + </itemizedlist> + </sect2> + + <sect2> + <title>Internal changes</title> + <itemizedlist> + <listitem> + <para>Many internal compiler changes: too many to list + here.</para> + </listitem> + <listitem> + <para>The old perl driver has been removed and replaced by a + driver in the compiler proper.</para> + </listitem> + <listitem> + <para>We now use GMP 3 instead of GMP 2 for + arbitrary-precision integer support.</para> + </listitem> + <listitem> + <para>Several libraries rewritten to use the FFI.</para> + </listitem> + </itemizedlist> + </sect2> + +</sect1> + +<!-- Emacs stuff: + ;;; Local Variables: *** + ;;; mode: xml *** + ;;; sgml-parent-document: ("users_guide.xml" "book" "chapter" "sect1") *** + ;;; End: *** + --> diff --git a/docs/users_guide/5-02-notes.xml b/docs/users_guide/5-02-notes.xml new file mode 100644 index 0000000000..a8bc83a4ba --- /dev/null +++ b/docs/users_guide/5-02-notes.xml @@ -0,0 +1,57 @@ +<?xml version="1.0" encoding="iso-8859-1"?> +<sect1 id="release-5-04"> + <title>Release notes for version 5.04</title> + + <sect2> + <title>User-visible compiler changes</title> + <itemizedlist> + <listitem> + <para></para> + </listitem> + </itemizedlist> + </sect2> + + <sect2> + <title>User-visible interpreter (GHCi) changes</title> + <itemizedlist> + <listitem> + <para></para> + </listitem> + </itemizedlist> + </sect2> + + <sect2> + <title>User-visible library changes</title> + <itemizedlist> + <listitem> + <para></para> + </listitem> + </itemizedlist> + </sect2> + + <sect2> + <title>New experimental features</title> + <itemizedlist> + <listitem> + <para></para> + </listitem> + </itemizedlist> + </sect2> + + <sect2> + <title>Internal changes</title> + <itemizedlist> + <listitem> + <para></para> + </listitem> + </itemizedlist> + </sect2> + +</sect1> + +<!-- Emacs stuff: + ;;; Local Variables: *** + ;;; mode: xml *** + ;;; sgml-parent-document: ("users_guide.xml" "book" "chapter" "sect1") *** + ;;; End: *** + --> diff --git a/docs/users_guide/5-04-notes.xml b/docs/users_guide/5-04-notes.xml new file mode 100644 index 0000000000..91b8dcf606 --- /dev/null +++ b/docs/users_guide/5-04-notes.xml @@ -0,0 +1,288 @@ +<?xml version="1.0" encoding="iso-8859-1"?> +<sect1 id="release-5-04"> + <title>Release notes for version 5.04</title> + + <sect2> + <title>User-visible compiler changes</title> + <itemizedlist> + <listitem> + <para>Full support for MacOS X, including fully optimized compilation, has been added. Only a native + code generator and support for <option>-split-objs</option> is still missing. + Everything else needs more testing, but should work.</para> + </listitem> + <listitem> + <para><literal>ghc-pkg</literal>: new options + <option>--auto-ghci-libs</option>, + <option>-u</option>/<option>--update-package</option>, + <option>--force</option>, and + <option>-i</option>/<option>--input-file</option>, and + suppport for expanding environment variables in package + descriptions. See <xref linkend="packages">).</para> + </listitem> + <listitem> + <para>The latest version of the FFI spec is fully supported. + The syntax of FFI declarations has changed accordingly. The + old syntax is still accepted for the time being, but will + elicit a warning from the compiler.</para> + </listitem> + <listitem> + <para>New option: <option>-F</option> specifies a user-defined + preprocessing phase (see <xref linkend="pre-processor">).</para> + </listitem> + <listitem> + <para>Major overhaul of the heap profiling subsystem, with new + facilities for retainer profiling and biographical profiling + (ala nhc98, albeit with a couple of omissions). The syntax of + the runtime heap-profiling options has changed. See <xref + linkend="prof-heap">.</para> + </listitem> + <listitem> + <para>The type system now supports full rank-N types + (previously only limited rank-2 types were supported). See + <xref linkend="universal-quantification">.</para> + </listitem> + <listitem> + <para>Explicit kind annotations can now be given on any + binding occurrence of a type variable. See <xref + linkend="sec-kinding">.</para> + </listitem> + <listitem> + <para>The handling of type synonyms has been rationalised. + See <xref linkend="type-synonyms">.</para> + </listitem> + <listitem> + <para>Fixes for several space leaks in the compiler itself + (these fixes were also merged into 5.02.3).</para> + </listitem> + <listitem> + <para>It is now possible to derive arbitrary classes for + newtypes. See <xref linkend="newtype-deriving">.</para> + </listitem> + <listitem> + <para>Deadlock is now an exception, rather than a return + status from the scheduler. See the module + <literal>Control.Exception</literal> in the library + documentation for more details.</para> + </listitem> + <listitem> + <para>The syntax and behaviour of <literal>RULE</literal> + pragmas has changed slightly. See <xref + linkend="rewrite-rules">.</para> + </listitem> + <listitem> + <para>Interface files are now in a binary format to reduce + compilation times. To view an interface file in plain text, + use the <option>--show-iface</option> flag.</para> + </listitem> + <listitem> + <para>A restriction on the form of class declarations has been + lifted. In Haskell 98, it is illegal for class method types + to mention constraints on the class type variable. eg.</para> + +<programlisting> + class Seq s a where + elem :: Eq a => a -> s a -> Bool +</programlisting> + + <para>This restriction has now been lifted in GHC.</para> + </listitem> + <listitem> + <para>Main threads can now receive the + <literal>BlockedOnDeadMVar</literal> exception in the same way + as other threads.</para> + </listitem> + <listitem> + <para>The <option>-fall-strict</option> flag never really + worked, and has been removed.</para> + </listitem> + <listitem> + <para>The syntax of <literal>.hi-boot</literal> files is now + much clearer and Haskell-like. See <xref + linkend="mutual-recursion">.</para> + </listitem> + <listitem> + <para>There is a new flag <option>-fffi</option> which enables + FFI support without turning on the rest of the GHC + extensions.</para> + </listitem> + <listitem> + <para>The syntax for implicit parameter bindings has changed. + Previously the keyword <literal>with</literal> was used to + introduce implicit bindings, but now implicit bindings may be + introduced using <literal>let</literal> (see <xref + linkend="implicit-parameters">). As a result of this, + <literal>with</literal> is no longer a keyword when + <option>-fglasgow-exts</option> is turned on.</para> + + <para>The option <literal>-fwith</literal> may be used to + restore the old behaviour.</para> + </listitem> + <listitem> + <para>Infix type constructors are now allowed, and must begin + with a colon (as with data constructors). See <xref + linkend="infix-tycons">.</para> + </listitem> + <listitem> + <para>The <literal>do</literal>-notation syntax is now + rebindable in the same way as other built-in syntax. See + <xref linkend="rebindable-syntax">.</para> + </listitem> + <listitem> + <para>Support for using “frameworks” on + Darwin/MacOS X has been added. See the + <option>-framework</option> option in <xref + linkend="options-linker">, and the + <literal>framework_dirs</literal> field of a package spec in + <xref linkend="package-management">.</para> + </listitem> + </itemizedlist> + </sect2> + + <sect2> + <title>User-visible interpreter (GHCi) changes</title> + <itemizedlist> + <listitem> + <para>New commands: <literal>:browse</literal>, <literal>:set + args</literal>, <literal>:set prog</literal>, <literal>:show + bindings</literal>, and <literal>:show modules</literal> (see + <xref linkend="ghci-commands">).</para> + </listitem> + <listitem> + <para>There is a much more flexible mechanism for manipulating + the scope for expressions typed at the prompt. For example, + one can now have both the <literal>Prelude</literal> and the + exports of several compiled modules in scope at the same + time. See <xref linkend="ghci-scope">.</para> + </listitem> + <listitem> + <para>GHCi now supports <literal>foreign import + "wrapper"</literal> FFI declarations.</para> + </listitem> + </itemizedlist> + </sect2> + + <sect2> + <title>User-visible library changes</title> + <itemizedlist> + <listitem> + <para>GHC is in the process of moving to a new hierarchical + set of libraries. At the moment, we have two sets of + libraries, both described in accompanying documents:</para> + <itemizedlist> + <listitem> + <para>The “new libraries” which are + hierarchical and consist of the following packages: + <literal>base</literal>, <literal>haskell98</literal>, + <literal>haskell-src</literal>, and + <literal>network</literal>. Broadly speaking, + <literal>base</literal> contains the + <literal>Prelude</literal>, standard libraries and most of + the contents of the old <literal>lang</literal> + package. By default, the <literal>base</literal> and + <literal>haskell98</literal> packages are enabled.</para> + </listitem> + + <listitem> + <para>The <literal>hslibs</literal>, most of which are now + deprecated. Where possible, new code should be written to + use the new libraries instead. </para> + + <para>The following libraries in <literal>hslibs</literal> + have not moved yet:</para> + <itemizedlist> + <listitem> + <para>The packages <literal>win32</literal>, + <literal>xlib</literal>, <literal>graphics</literal>, + and <literal>posix</literal>.</para> + </listitem> + <listitem> + <para>The Edison libraries in the + <literal>data</literal> package.</para> + </listitem> + <listitem> + <para>In the <literal>lang</literal> package, the + modules <literal>TimeExts</literal>, + <literal>DirectoryExts</literal>, + <literal>SystemExts</literal>, and + <literal>NumExts</literal>.</para> + </listitem> + <listitem> + <para>The HaXml libraries in the + <literal>text</literal> package.</para> + </listitem> + <listitem> + <para>In the <literal>util</literal> package, the + modules <literal>MD5</literal>, + <literal>Select</literal>, <literal>Memo</literal>, + <literal>Observe</literal>, and + <literal>Readline</literal>.</para> + </listitem> + </itemizedlist> + + <para>All other libraries from <literal>hslibs</literal> + either have equivalents in the new libraries (see the + <literal>hslibs</literal> docs for details), or were + already deprecated and hence were not moved into the new + hierarchy.</para> + </listitem> + </itemizedlist> + </listitem> + + <listitem> + <para>The <literal>Read</literal> class is now based on a + parsing combinator library which is vastly more efficient than + the previous one. See the modules + <literal>Text.Read</literal>. + <literal>Text.ParserCombinators.ReadP</literal>, and + <literal>Text.ParserCombinators.ReadPrec</literal> in the + library documentation.</para> + + <para>The code generated by the compiler for derived + <literal>Read</literal> instances should be much shorter than + before.</para> + </listitem> + </itemizedlist> + </sect2> + + <sect2> + <title>New experimental features</title> + <itemizedlist> + <listitem> + <para>Linear implicit parameters. See <xref + linkend="linear-implicit-parameters">.</para> + </listitem> + <listitem> + <para>The RTS has support for running in a multi-threaded + environment and making non-blocking (from Haskell's point of + view) calls to foreign C functions which would normally block. + To enable this behaviour, configure with the + <option>--enable-threaded-rts</option> option.</para> + </listitem> + <listitem> + <para>The compiler can now read in files containing Core + syntax (such as those produced by the + <option>-fext-core</option> option) and compile them. Input + files with the <literal>.hcr</literal> file extension are + assumed to contain Core syntax.</para> + </listitem> + </itemizedlist> + </sect2> + + <sect2> + <title>Internal changes</title> + <itemizedlist> + <listitem> + <para>Happy 1.13 is now required to build GHC, because of the + change in names of certain libraries.</para> + </listitem> + </itemizedlist> + </sect2> + +</sect1> + +<!-- Emacs stuff: + ;;; Local Variables: *** + ;;; mode: xml *** + ;;; sgml-parent-document: ("users_guide.xml" "book" "chapter" "sect1") *** + ;;; End: *** + --> diff --git a/docs/users_guide/6.0-notes.xml b/docs/users_guide/6.0-notes.xml new file mode 100644 index 0000000000..e07bc890f2 --- /dev/null +++ b/docs/users_guide/6.0-notes.xml @@ -0,0 +1,319 @@ +<?xml version="1.0" encoding="iso-8859-1"?> +<sect1 id="release-6-0"> + <title>Release notes for version 6.0</title> + + <sect2> + <title>User-visible compiler changes</title> + <itemizedlist> + <listitem> + <para>Template Haskell, a new feature for compile-time + metaprogramming has been introduced. See <xref + linkend="template-haskell"/>.</para> + </listitem> + <listitem> + <para>INLINE pragmas on methods in class or instance + declarations now work properly.</para> + </listitem> + <listitem> + <para>Recursive do-notation (aka <literal>mdo</literal>) is + now supported. See <xref linkend="mdo-notation"/>.</para> + </listitem> + <listitem> + <para>There is now a native code generator for PowerPC + platforms.</para> + </listitem> + <listitem> + <para>Profiling: the <option>-xt</option> RTS option enables + inclusion of thread stacks in a heap profile. See <xref + linkend="rts-options-heap-prof"/>.</para> + </listitem> + <listitem> + <para>Non-blocking I/O is now supported on Windows.</para> + </listitem> + <listitem> + <para>The <ulink url="../libraries/base/Data.Dynamic.html#Typeable"><literal>Typeable</literal></ulink> class can now be + derived, and the implementation of <literal>Typeable</literal> + is now more efficient.</para> + </listitem> + </itemizedlist> + </sect2> + + <sect2> + <title>User-visible interpreter (GHCi) changes</title> + <itemizedlist> + <listitem> + <para>Loading a <literal>Main</literal> module that does not + define <literal>main</literal> is no longer an error, although + GHCi will still emit a warning in this case.</para> + </listitem> + </itemizedlist> + </sect2> + + <sect2> + <title>User-visible library changes</title> + <itemizedlist> + <listitem> + <para>Hierarchical libraries are now available without needing + to specify an explicit <option>-package</option> flag. There + are some exceptions to this rule (see <xref + linkend="using-packages"/>), but if you stick to GHCi and + <option>--make</option> mode then there will normally be no + need to specify <option>-package</option> options at + all.</para> + + <para>Non-hierarchical libraries + (i.e. <literal>hslibs</literal> libraries) still need to be + explicitly requested with <option>-package</option> + options.</para> + </listitem> + + <listitem> + <para>The <literal>Posix</literal> library has been rewritten. + It is now a hierarchical library rooted at + <literal>System.Posix</literal>, and has some additions aimed + at supporting the latest revision of the POSIX standard (IEEE + Std 1003.1-2001). See the <ulink + url="../libraries/unix/index.html"><literal>unix</literal> + package</ulink> for details.</para> + + <para>The old <literal>posix</literal> package is still + available for backwards compatibility, but is deprecated and + will be removed in a future release.</para> + </listitem> + + <listitem> + <para><ulink url="../libraries/base/Data.IORef.html"><literal>Data.IORef</literal></ulink>: Added <literal>atomicModifyIORef</literal>.</para> + </listitem> + + <listitem> + <para><ulink url="../libraries/base/System.Cmd.html"><literal>System.Cmd</literal></ulink>: Added <literal>rawSystem</literal>.</para> + </listitem> + + <listitem> + <para><ulink + url="../libraries/base/System.Environment.html"><literal>System.Environment</literal></ulink>: + Added <literal>withArgs</literal> and <literal>withProgName</literal>.</para> + </listitem> + + <listitem> + <para><ulink + url="../libraries/network/Network.Socket.html"><literal>Network.Socket</literal></ulink>: + Added <literal>sendFd</literal> and <literal>recvFd</literal>.</para> + </listitem> + + <listitem> + <para>The <literal>Readline</literal> library has moved to + <ulink + url="../libraries/readline/System.Console.Readline.html"><literal>System.Console.Readline</literal></ulink>, + and is in a package of its own + (<literal>readline</literal>).</para> + </listitem> + + <listitem> + <para>The non-hierarchical versions of the FFI libraries are + now all available without needing to specify <literal>-package + lang</literal> (they are actually now in the + <literal>haskell98</literal> package, which is available by + default).</para> + </listitem> + + <listitem> + <para><ulink + url="../libraries/network/Network.BSD.html"><literal>Network.BSD</literal></ulink>: + <literal>symlink</literal> and <literal>readline</literal> are + now deprecated; use + <literal>System.Posix.createSymbolicLink</literal> and + <literal>System.Posix.readSymbolicLink</literal> + respectively.</para> + </listitem> + + <listitem> + <para><ulink + url="../libraries/base/Control.Exception.html"><literal>Control.Exception</literal></ulink>: + Added <literal>mapException</literal>.</para> + </listitem> + + <listitem> + <para><ulink + url="../libraries/base/Data.Dynamic.html"><literal>Data.Dynamic</literal></ulink>: + various changes to make the implementation of + <literal>Typeable</literal> more efficient. This entails some + changes to the interface, and affects how instances of + <literal>Typeable</literal> are defined.</para> + </listitem> + + <listitem> + <para><ulink + url="../libraries/base/Data.Tree.html"><literal>Data.Tree</literal></ulink> + is a new library for trees.</para> + </listitem> + + <listitem> + <para><ulink + url="../libraries/base/Data.Graph.html"><literal>Data.Graph</literal></ulink> + is a new library for graphs.</para> + </listitem> + + <listitem> + <para><ulink + url="../libraries/base/System.IO.html"><literal>System.IO</literal></ulink>: + Removed <literal>bracket</literal> and + <literal>bracket_</literal> (use the versions from + <literal>Control.Exception</literal> instead).</para> + </listitem> + + <listitem> + <para><ulink + url="../libraries/base/System.IO.html"><literal>System.IO</literal></ulink>: + The <literal>IOError</literal> type is now a synonym for + <literal>IOException</literal>, whereas previously it was a + synonym for <literal>Exception</literal>. This has various + consequences, one of which is that the types of + <literal>System.IO.catch</literal> and + <literal>Control.Exception.catch</literal> are now different + (useful, because they do different things).</para> + </listitem> + + <listitem> + <para><ulink + url="../libraries/base/System.IO.Error.html"><literal>System.IO.Error</literal></ulink>: + added <literal>annotateIOError</literal>, + <literal>modifyIOError</literal>, and <literal>ioeSet{ErrorType,ErrorString,Handle,FileName}</literal>.</para> + </listitem> + + <listitem> + <para><ulink + url="../libraries/base/Text.ParserCombinators.ReadP.html"><literal>Text.ParserCombinators.ReadP</literal></ulink>: + lots of updates.</para> + </listitem> + + <listitem> + <para><literal>Control.Monad.Monoid</literal> is now <ulink url="../libraries/base/Data.Monoid.html"><literal>Data.Monoid</literal></ulink>.</para> + </listitem> + + <listitem> + <para><ulink + url="../libraries/base/Data.PackedString.html"><literal>Data.PackedString</literal></ulink>: + added <literal>joinPS</literal>, <literal>unwordsPS</literal> + and <literal>unlinesPS</literal>.</para> + </listitem> + + <listitem> + <para><ulink + url="../libraries/base/Data.HashTable.html"><literal>Data.HashTable</literal></ulink> + is a new dynamic hash-table implementation.</para> + </listitem> + + <listitem> + <para>Added <ulink + url="../libraries/unix/System.Sendfile.html"><literal>System.Sendfile</literal></ulink>.</para> + </listitem> + + <listitem> + <para>Added <ulink + url="../libraries/base/Foreign.Marshal.Pool.html"><literal>Foreign.Marshal.Pool</literal></ulink>.</para> + </listitem> + + <listitem> + <para><ulink + url="../libraries/base/Data.Bits.html"><literal>Data.Bits</literal></ulink>: + <literal>shiftL</literal>, <literal>shiftR</literal>, + <literal>rotateL</literal>, and <literal>rotateR</literal> are + now methods of the <literal>Bite</literal> class.</para> + </listitem> + + <listitem> + <para>The FFI libraries now conform to the latest version of + the FFI spec:</para> + <itemizedlist> + <listitem> + <para>Added <ulink + url="../libraries/base/Foreign.ForeignPtr.html#mallocForeignPtr"><literal>Foreign.ForeignPtr.mallocForeignPtr</literal></ulink> + and friends.</para> + </listitem> + <listitem> + <para>Finalizers added to a <literal>ForeignPtr</literal> + with <literal>addForeignPtrFinalizer</literal> are now run + in strict order; namely the reverse of the order they were + added.</para> + </listitem> + <listitem> + <para><literal>Foreign.C.TypesISO</literal> has been + merged into <ulink + url="../libraries/base/Foreign.C.Types.html"><literal>Foreign.C.Types</literal></ulink>.</para> + </listitem> + </itemizedlist> + </listitem> + </itemizedlist> + </sect2> + + <sect2> + <title>Experimental features</title> + <itemizedlist> + <listitem> + <para>The <literal>Data</literal> class provides for generic + data traversals and folds; see <ulink + url="../libraries/base/Data.Generics.html"><literal>Data.Generics</literal></ulink>. + <literal>Data</literal> can be derived for arbitrary + datatypes. The <literal>Data</literal> class is still + experimental, so its contents may change in the future.</para> + </listitem> + <listitem> + <para>Several bugs have been fixed in the threaded RTS, and it + should now be rather more robust (it should still be + considered experimental, however).</para> + </listitem> + </itemizedlist> + </sect2> + + <sect2> + <title>Internal changes</title> + <itemizedlist> + <listitem> + <para>Sweeping changes to the compiler and runtime system to + change the evaluation model from <quote>push/enter</quote> to + <quote>eval/apply</quote>. The bottom line is that the + compiler is now more portable and some of the complexity is + now more centralised, while performance and binary sizes + remain about the same.</para> + + <para>A paper describing these changes can be found <ulink + url="http://research.microsoft.com/~simonpj/papers/eval-apply">here</ulink>.</para> + </listitem> + <listitem> + <para>The test suite is now driven by a Python script and is + rather more flexible and robust. It now supports building + tests several different "ways", and as a result we now run + each test with optimisation, profiling, native code + generation, and GHCi in addition to the vanilla way.</para> + </listitem> + <listitem> + <para>The build system now supports bootstrapping the compiler + in a single build tree. By default, typing + <literal>make</literal> at the top level will bootstrap the + compiler once to create a stage-2 compiler. See the Building + Guide for more details.</para> + </listitem> + <listitem> + <para>The RTS debugging flags are no longer represented by a + bitfield and now have single-character names. For example, to + turn on scheduler debugging output, use <literal>-Ds</literal> + rather than <literal>-D1</literal>.</para> + </listitem> + <listitem> + <para>The compiler no longer requires any packages from + <literal>hslibs</literal> to bootstrap. It is enough to + compile <literal>fptools/libraries</literal> before building + the stage 2 compiler.</para> + </listitem> + </itemizedlist> + </sect2> + +</sect1> + +<!-- Emacs stuff: + ;;; Local Variables: *** + ;;; mode: xml *** + ;;; sgml-parent-document: ("users_guide.xml" "book" "chapter" "sect1") *** + ;;; End: *** + --> diff --git a/docs/users_guide/Makefile b/docs/users_guide/Makefile new file mode 100644 index 0000000000..f0a31fb705 --- /dev/null +++ b/docs/users_guide/Makefile @@ -0,0 +1,7 @@ +TOP = ../.. +include $(TOP)/mk/boilerplate.mk + +XML_DOC = users_guide +INSTALL_XML_DOC = users_guide + +include $(TOP)/mk/target.mk diff --git a/docs/users_guide/bugs.xml b/docs/users_guide/bugs.xml new file mode 100644 index 0000000000..ab0b9be7b9 --- /dev/null +++ b/docs/users_guide/bugs.xml @@ -0,0 +1,400 @@ +<?xml version="1.0" encoding="iso-8859-1"?> +<chapter id="bugs-and-infelicities"> + <title>Known bugs and infelicities</title> + + <sect1 id="vs-Haskell-defn"> + <title>Haskell 98 vs. Glasgow Haskell: language non-compliance +</title> + + <indexterm><primary>GHC vs the Haskell 98 language</primary></indexterm> + <indexterm><primary>Haskell 98 language vs GHC</primary></indexterm> + + <para>This section lists Glasgow Haskell infelicities in its + implementation of Haskell 98. See also the “when things + go wrong” section (<xref linkend="wrong"/>) for information + about crashes, space leaks, and other undesirable phenomena.</para> + + <para>The limitations here are listed in Haskell Report order + (roughly).</para> + + <sect2 id="haskell98-divergence"> + <title>Divergence from Haskell 98</title> + + + <sect3 id="infelicities-lexical"> + <title>Lexical syntax</title> + + <itemizedlist> + <listitem> + <para>The Haskell report specifies that programs may be + written using Unicode. GHC only accepts the ISO-8859-1 + character set at the moment.</para> + </listitem> + + <listitem> + <para>Certain lexical rules regarding qualified identifiers + are slightly different in GHC compared to the Haskell + report. When you have + <replaceable>module</replaceable><literal>.</literal><replaceable>reservedop</replaceable>, + such as <literal>M.\</literal>, GHC will interpret it as a + single qualified operator rather than the two lexemes + <literal>M</literal> and <literal>.\</literal>.</para> + </listitem> + </itemizedlist> + </sect3> + + <sect3 id="infelicities-syntax"> + <title>Context-free syntax</title> + + <itemizedlist> + <listitem> + <para>GHC is a little less strict about the layout rule when used + in <literal>do</literal> expressions. Specifically, the + restriction that "a nested context must be indented further to + the right than the enclosing context" is relaxed to allow the + nested context to be at the same level as the enclosing context, + if the enclosing context is a <literal>do</literal> + expression.</para> + + <para>For example, the following code is accepted by GHC: + +<programlisting> +main = do args <- getArgs + if null args then return [] else do + ps <- mapM process args + mapM print ps</programlisting> + + </para> + </listitem> + + <listitem> + <para>GHC doesn't do fixity resolution in expressions during + parsing. For example, according to the Haskell report, the + following expression is legal Haskell: +<programlisting> + let x = 42 in x == 42 == True</programlisting> + and parses as: +<programlisting> + (let x = 42 in x == 42) == True</programlisting> + + because according to the report, the <literal>let</literal> + expression <quote>extends as far to the right as + possible</quote>. Since it can't extend past the second + equals sign without causing a parse error + (<literal>==</literal> is non-fix), the + <literal>let</literal>-expression must terminate there. GHC + simply gobbles up the whole expression, parsing like this: +<programlisting> + (let x = 42 in x == 42 == True)</programlisting> + + The Haskell report is arguably wrong here, but nevertheless + it's a difference between GHC & Haskell 98.</para> + </listitem> + </itemizedlist> + </sect3> + + <sect3 id="infelicities-exprs-pats"> + <title>Expressions and patterns</title> + + <para>None known.</para> + </sect3> + + <sect3 id="infelicities-decls"> + <title>Declarations and bindings</title> + + <para>None known.</para> + </sect3> + + <sect3 id="infelicities-Modules"> + <title>Module system and interface files</title> + + <para>None known.</para> + </sect3> + + <sect3 id="infelicities-numbers"> + <title>Numbers, basic types, and built-in classes</title> + + <variablelist> + <varlistentry> + <term>Multiply-defined array elements—not checked:</term> + <listitem> + <para>This code fragment should + elicit a fatal error, but it does not: + +<programlisting> +main = print (array (1,1) [(1,2), (1,3)])</programlisting> +GHC's implementation of <literal>array</literal> takes the value of an +array slot from the last (index,value) pair in the list, and does no +checking for duplicates. The reason for this is efficiency, pure and simple. + </para> + </listitem> + </varlistentry> + </variablelist> + + </sect3> + + <sect3 id="infelicities-Prelude"> + <title>In <literal>Prelude</literal> support</title> + + <variablelist> + <varlistentry> + <term>Arbitrary-sized tuples</term> + <listitem> + <para>Tuples are currently limited to size 100. HOWEVER: + standard instances for tuples (<literal>Eq</literal>, + <literal>Ord</literal>, <literal>Bounded</literal>, + <literal>Ix</literal> <literal>Read</literal>, and + <literal>Show</literal>) are available + <emphasis>only</emphasis> up to 16-tuples.</para> + + <para>This limitation is easily subvertible, so please ask + if you get stuck on it.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>Read</literal>ing integers</term> + <listitem> + <para>GHC's implementation of the + <literal>Read</literal> class for integral types accepts + hexadecimal and octal literals (the code in the Haskell + 98 report doesn't). So, for example, +<programlisting>read "0xf00" :: Int</programlisting> + works in GHC.</para> + <para>A possible reason for this is that <literal>readLitChar</literal> accepts hex and + octal escapes, so it seems inconsistent not to do so for integers too.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>isAlpha</literal></term> + <listitem> + <para>The Haskell 98 definition of <literal>isAlpha</literal> + is:</para> + +<programlisting>isAlpha c = isUpper c || isLower c</programlisting> + + <para>GHC's implementation diverges from the Haskell 98 + definition in the sense that Unicode alphabetic characters which + are neither upper nor lower case will still be identified as + alphabetic by <literal>isAlpha</literal>.</para> + </listitem> + </varlistentry> + </variablelist> + </sect3> + </sect2> + + <sect2 id="haskell98-undefined"> + <title>GHC's interpretation of undefined behaviour in + Haskell 98</title> + + <para>This section documents GHC's take on various issues that are + left undefined or implementation specific in Haskell 98.</para> + + <variablelist> + <varlistentry> + <term> + The <literal>Char</literal> type + <indexterm><primary><literal>Char</literal></primary><secondary>size of</secondary></indexterm> + </term> + <listitem> + <para>Following the ISO-10646 standard, + <literal>maxBound :: Char</literal> in GHC is + <literal>0x10FFFF</literal>.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term> + Sized integral types + <indexterm><primary><literal>Int</literal></primary><secondary>size of</secondary></indexterm> + </term> + <listitem> + <para>In GHC the <literal>Int</literal> type follows the + size of an address on the host architecture; in other words + it holds 32 bits on a 32-bit machine, and 64-bits on a + 64-bit machine.</para> + + <para>Arithmetic on <literal>Int</literal> is unchecked for + overflow<indexterm><primary>overflow</primary><secondary><literal>Int</literal></secondary> + </indexterm>, so all operations on <literal>Int</literal> happen + modulo + 2<superscript><replaceable>n</replaceable></superscript> + where <replaceable>n</replaceable> is the size in bits of + the <literal>Int</literal> type.</para> + + <para>The <literal>fromInteger</literal><indexterm><primary><literal>fromInteger</literal></primary> + </indexterm>function (and hence + also <literal>fromIntegral</literal><indexterm><primary><literal>fromIntegral</literal></primary> + </indexterm>) is a special case when + converting to <literal>Int</literal>. The value of + <literal>fromIntegral x :: Int</literal> is given by taking + the lower <replaceable>n</replaceable> bits of <literal>(abs + x)</literal>, multiplied by the sign of <literal>x</literal> + (in 2's complement <replaceable>n</replaceable>-bit + arithmetic). This behaviour was chosen so that for example + writing <literal>0xffffffff :: Int</literal> preserves the + bit-pattern in the resulting <literal>Int</literal>.</para> + + + <para>Negative literals, such as <literal>-3</literal>, are + specified by (a careful reading of) the Haskell Report as + meaning <literal>Prelude.negate (Prelude.fromInteger 3)</literal>. + So <literal>-2147483648</literal> means <literal>negate (fromInteger 2147483648)</literal>. + Since <literal>fromInteger</literal> takes the lower 32 bits of the representation, + <literal>fromInteger (2147483648::Integer)</literal>, computed at type <literal>Int</literal> is + <literal>-2147483648::Int</literal>. The <literal>negate</literal> operation then + overflows, but it is unchecked, so <literal>negate (-2147483648::Int)</literal> is just + <literal>-2147483648</literal>. In short, one can write <literal>minBound::Int</literal> as + a literal with the expected meaning (but that is not in general guaranteed. + </para> + + <para>The <literal>fromIntegral</literal> function also + preserves bit-patterns when converting between the sized + integral types (<literal>Int8</literal>, + <literal>Int16</literal>, <literal>Int32</literal>, + <literal>Int64</literal> and the unsigned + <literal>Word</literal> variants), see the modules + <literal>Data.Int</literal> and <literal>Data.Word</literal> + in the library documentation.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term>Unchecked float arithmetic</term> + <listitem> + <para>Operations on <literal>Float</literal> and + <literal>Double</literal> numbers are + <emphasis>unchecked</emphasis> for overflow, underflow, and + other sad occurrences. (note, however that some + architectures trap floating-point overflow and + loss-of-precision and report a floating-point exception, + probably terminating the + program)<indexterm><primary>floating-point + exceptions</primary></indexterm>.</para> + </listitem> + </varlistentry> + </variablelist> + + </sect2> + </sect1> + + + <sect1 id="bugs"> + <title>Known bugs or infelicities</title> + + <para>The bug tracker lists bugs that have been reported in GHC but not + yet fixed: see the <ulink url="http://sourceforge.net/projects/ghc/">SourceForge GHC + page</ulink>. In addition to those, GHC also has the following known bugs + or infelicities. These bugs are more permanent; it is unlikely that + any of them will be fixed in the short term.</para> + + <sect2 id="bugs-ghc"> + <title>Bugs in GHC</title> + + <itemizedlist> + <listitem> + <para> GHC can warn about non-exhaustive or overlapping + patterns (see <xref linkend="options-sanity"/>), and usually + does so correctly. But not always. It gets confused by + string patterns, and by guards, and can then emit bogus + warnings. The entire overlap-check code needs an overhaul + really.</para> + </listitem> + + <listitem> + <para>GHC does not allow you to have a data type with a context + that mentions type variables that are not data type parameters. + For example: +<programlisting> + data C a b => T a = MkT a +</programlisting> + so that <literal>MkT</literal>'s type is +<programlisting> + MkT :: forall a b. C a b => a -> T a +</programlisting> + In principle, with a suitable class declaration with a functional dependency, + it's possible that this type is not ambiguous; but GHC nevertheless rejects + it. The type variables mentioned in the context of the data type declaration must + be among the type parameters of the data type.</para> + </listitem> + + <listitem> + <para>GHC's inliner can be persuaded into non-termination + using the standard way to encode recursion via a data type:</para> +<programlisting> + data U = MkU (U -> Bool) + + russel :: U -> Bool + russel u@(MkU p) = not $ p u + + x :: Bool + x = russel (MkU russel) +</programlisting> + + <para>We have never found another class of programs, other + than this contrived one, that makes GHC diverge, and fixing + the problem would impose an extra overhead on every + compilation. So the bug remains un-fixed. There is more + background in <ulink + url="http://research.microsoft.com/~simonpj/Papers/inlining"> + Secrets of the GHC inliner</ulink>.</para> + </listitem> + + <listitem> + <para>GHC does not keep careful track of + what instance declarations are 'in scope' if they come from other packages. + Instead, all instance declarations that GHC has seen in other + packages are all in scope everywhere, whether or not the + module from that package is used by the command-line + expression. This bug affects only the <option>--make</option> mode and + GHCi.</para> + </listitem> + + </itemizedlist> + </sect2> + + <sect2 id="bugs-ghci"> + <title>Bugs in GHCi (the interactive GHC)</title> + <itemizedlist> + <listitem> + <para>GHCi does not respect the <literal>default</literal> + declaration in the module whose scope you are in. Instead, + for expressions typed at the command line, you always get the + default default-type behaviour; that is, + <literal>default(Int,Double)</literal>.</para> + + <para>It would be better for GHCi to record what the default + settings in each module are, and use those of the 'current' + module (whatever that is).</para> + </listitem> + + <listitem> + <para>On Windows, there's a GNU ld/BFD bug + whereby it emits bogus PE object files that have more than + 0xffff relocations. When GHCi tries to load a package affected by this + bug, you get an error message of the form +<screen> +Loading package javavm ... linking ... WARNING: Overflown relocation field (# relocs found: 30765) +</screen> + The last time we looked, this bug still + wasn't fixed in the BFD codebase, and there wasn't any + noticeable interest in fixing it when we reported the bug + back in 2001 or so. + </para> + <para>The workaround is to split up the .o files that make up + your package into two or more .o's, along the lines of + how the "base" package does it.</para> + </listitem> + </itemizedlist> + </sect2> + </sect1> + +</chapter> + +<!-- Emacs stuff: + ;;; Local Variables: *** + ;;; mode: xml *** + ;;; sgml-parent-document: ("users_guide.xml" "book" "chapter") *** + ;;; End: *** + --> diff --git a/docs/users_guide/debugging.xml b/docs/users_guide/debugging.xml new file mode 100644 index 0000000000..a325389d46 --- /dev/null +++ b/docs/users_guide/debugging.xml @@ -0,0 +1,599 @@ +<?xml version="1.0" encoding="iso-8859-1"?> +<sect1 id="options-debugging"> + <title>Debugging the compiler</title> + + <indexterm><primary>debugging options (for GHC)</primary></indexterm> + + <para>HACKER TERRITORY. HACKER TERRITORY. (You were warned.)</para> + + <sect2 id="dumping-output"> + <title>Dumping out compiler intermediate structures</title> + + <indexterm><primary>dumping GHC intermediates</primary></indexterm> + <indexterm><primary>intermediate passes, output</primary></indexterm> + + <variablelist> + <varlistentry> + <term> + <option>-ddump-</option><replaceable>pass</replaceable> + <indexterm><primary><option>-ddump</option> options</primary></indexterm> + </term> + <listitem> + <para>Make a debugging dump after pass + <literal><pass></literal> (may be common enough to need + a short form…). You can get all of these at once + (<emphasis>lots</emphasis> of output) by using + <option>-v5</option>, or most of them with + <option>-v4</option>. Some of the most useful ones + are:</para> + + <variablelist> + <varlistentry> + <term> + <option>-ddump-parsed</option>: + <indexterm><primary><option>-ddump-parsed</option></primary></indexterm> + </term> + <listitem> + <para>parser output</para> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <option>-ddump-rn</option>: + <indexterm><primary><option>-ddump-rn</option></primary></indexterm> + </term> + <listitem> + <para>renamer output</para> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <option>-ddump-tc</option>: + <indexterm><primary><option>-ddump-tc</option></primary></indexterm> + </term> + <listitem> + <para>typechecker output</para> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <option>-ddump-types</option>: + <indexterm><primary><option>-ddump-types</option></primary></indexterm> + </term> + <listitem> + <para>Dump a type signature for each value defined at + the top level of the module. The list is sorted + alphabetically. Using <option>-dppr-debug</option> + dumps a type signature for all the imported and + system-defined things as well; useful for debugging the + compiler.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <option>-ddump-deriv</option>: + <indexterm><primary><option>-ddump-deriv</option></primary></indexterm> + </term> + <listitem> + <para>derived instances</para> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <option>-ddump-ds</option>: + <indexterm><primary><option>-ddump-ds</option></primary></indexterm> + </term> + <listitem> + <para>desugarer output</para> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <option>-ddump-spec</option>: + <indexterm><primary><option>-ddump-spec</option></primary></indexterm> + </term> + <listitem> + <para>output of specialisation pass</para> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <option>-ddump-rules</option>: + <indexterm><primary><option>-ddump-rules</option></primary></indexterm> + </term> + <listitem> + <para>dumps all rewrite rules (including those generated + by the specialisation pass)</para> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <option>-ddump-simpl</option>: + <indexterm><primary><option>-ddump-simpl</option></primary></indexterm> + </term> + <listitem> + <para>simplifier output (Core-to-Core passes)</para> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <option>-ddump-inlinings</option>: + <indexterm><primary><option>-ddump-inlinings</option></primary></indexterm> + </term> + <listitem> + <para>inlining info from the simplifier</para> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <option>-ddump-usagesp</option>: + <indexterm><primary><option>-ddump-usagesp</option></primary></indexterm> + </term> + <listitem> + <para>UsageSP inference pre-inf and output</para> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <option>-ddump-cpranal</option>: + <indexterm><primary><option>-ddump-cpranal</option></primary></indexterm> + </term> + <listitem> + <para>CPR analyser output</para> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <option>-ddump-stranal</option>: + <indexterm><primary><option>-ddump-stranal</option></primary></indexterm> + </term> + <listitem> + <para>strictness analyser output</para> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <option>-ddump-cse</option>: + <indexterm><primary><option>-ddump-cse</option></primary></indexterm> + </term> + <listitem> + <para>CSE pass output</para> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <option>-ddump-workwrap</option>: + <indexterm><primary><option>-ddump-workwrap</option></primary></indexterm> + </term> + <listitem> + <para>worker/wrapper split output</para> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <option>-ddump-occur-anal</option>: + <indexterm><primary><option>-ddump-occur-anal</option></primary></indexterm> + </term> + <listitem> + <para>`occurrence analysis' output</para> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <option>-ddump-sat</option>: + <indexterm><primary><option>-ddump-sat</option></primary></indexterm> + </term> + <listitem> + <para>output of “saturate” pass</para> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <option>-ddump-stg</option>: + <indexterm><primary><option>-ddump-stg</option></primary></indexterm> + </term> + <listitem> + <para>output of STG-to-STG passes</para> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <option>-ddump-absC</option>: + <indexterm><primary><option>-ddump-absC</option></primary></indexterm> + </term> + <listitem> + <para><emphasis>un</emphasis>flattened Abstract C</para> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <option>-ddump-flatC</option>: + <indexterm><primary><option>-ddump-flatC</option></primary></indexterm> + </term> + <listitem> + <para><emphasis>flattened</emphasis> Abstract C</para> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <option>-ddump-realC</option>: + <indexterm><primary><option>-ddump-realC</option></primary></indexterm> + </term> + <listitem> + <para>same as what goes to the C compiler</para> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <option>-ddump-stix</option>: + <indexterm><primary><option>-ddump-stix</option></primary></indexterm> + </term> + <listitem> + <para>native-code generator intermediate form</para> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <option>-ddump-asm</option>: + <indexterm><primary><option>-ddump-asm</option></primary></indexterm> + </term> + <listitem> + <para>assembly language from the native-code generator</para> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <option>-ddump-bcos</option>: + <indexterm><primary><option>-ddump-bcos</option></primary></indexterm> + </term> + <listitem> + <para>byte code compiler output</para> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <option>-ddump-foreign</option>: + <indexterm><primary><option>-ddump-foreign</option></primary></indexterm> + </term> + <listitem> + <para>dump foreign export stubs</para> + </listitem> + </varlistentry> + </variablelist> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <option>-dverbose-core2core</option> + <indexterm><primary><option>-dverbose-core2core</option></primary></indexterm> + </term> + <term> + <option>-dverbose-stg2stg</option> + <indexterm><primary><option>-dverbose-stg2stg</option></primary></indexterm> + </term> + <listitem> + <para>Show the output of the intermediate Core-to-Core and + STG-to-STG passes, respectively. (<emphasis>Lots</emphasis> + of output!) So: when we're really desperate:</para> + + <screen> +% ghc -noC -O -ddump-simpl -dverbose-simpl -dcore-lint Foo.hs +</screen> + + </listitem> + </varlistentry> + + <varlistentry> + <term> + <option>-ddump-simpl-iterations</option>: + <indexterm><primary><option>-ddump-simpl-iterations</option></primary></indexterm> + </term> + <listitem> + <para>Show the output of each <emphasis>iteration</emphasis> + of the simplifier (each run of the simplifier has a maximum + number of iterations, normally 4). Used when even + <option>-dverbose-simpl</option> doesn't cut it.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <option>-dppr-debug</option> + <indexterm><primary><option>-dppr-debug</option></primary></indexterm> + </term> + <listitem> + <para>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.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <option>-dppr-user-length</option> + <indexterm><primary><option>-dppr-user-length</option></primary></indexterm> + </term> + <listitem> + <para>In error messages, expressions are printed to a + certain “depth”, with subexpressions beyond the + depth replaced by ellipses. This flag sets the + depth.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <option>-ddump-simpl-stats</option> + <indexterm><primary><option>-ddump-simpl-stats option</option></primary></indexterm> + </term> + <listitem> + <para>Dump statistics about how many of each kind of + transformation too place. If you add + <option>-dppr-debug</option> you get more detailed + information.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <option>-ddump-rn-trace</option> + <indexterm><primary><option>-ddump-rn-trace</option></primary></indexterm> + </term> + <listitem> + <para>Make the renamer be *real* chatty about what it is + upto.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <option>-ddump-rn-stats</option> + <indexterm><primary><option>-dshow-rn-stats</option></primary></indexterm> + </term> + <listitem> + <para>Print out summary of what kind of information the renamer + had to bring in.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <option>-dshow-unused-imports</option> + <indexterm><primary><option>-dshow-unused-imports</option></primary></indexterm> + </term> + <listitem> + <para>Have the renamer report what imports does not + contribute.</para> + </listitem> + </varlistentry> + </variablelist> + </sect2> + + <sect2 id="checking-consistency"> + <title>Checking for consistency</title> + + <indexterm><primary>consistency checks</primary></indexterm> + <indexterm><primary>lint</primary></indexterm> + + <variablelist> + + <varlistentry> + <term> + <option>-dcore-lint</option> + <indexterm><primary><option>-dcore-lint</option></primary></indexterm> + </term> + <listitem> + <para>Turn on heavyweight intra-pass sanity-checking within + GHC, at Core level. (It checks GHC's sanity, not yours.)</para> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <option>-dstg-lint</option>: + <indexterm><primary><option>-dstg-lint</option></primary></indexterm> + </term> + <listitem> + <para>Ditto for STG level. (NOTE: currently doesn't work).</para> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <option>-dusagesp-lint</option>: + <indexterm><primary><option>-dstg-lint</option></primary></indexterm> + </term> + <listitem> + <para>Turn on checks around UsageSP inference + (<option>-fusagesp</option>). This verifies various simple + properties of the results of the inference, and also warns + if any identifier with a used-once annotation before the + inference has a used-many annotation afterwards; this could + indicate a non-worksafe transformation is being + applied.</para> + </listitem> + </varlistentry> + </variablelist> + </sect2> + + <sect2> + <title>How to read Core syntax (from some <option>-ddump</option> + flags)</title> + + <indexterm><primary>reading Core syntax</primary></indexterm> + <indexterm><primary>Core syntax, how to read</primary></indexterm> + + <para>Let's do this by commenting an example. It's from doing + <option>-ddump-ds</option> on this code: + +<programlisting> +skip2 m = m : skip2 (m+2) +</programlisting> + + Before we jump in, a word about names of things. Within GHC, + variables, type constructors, etc., are identified by their + “Uniques.” These are of the form `letter' plus + `number' (both loosely interpreted). The `letter' gives some idea + of where the Unique came from; e.g., <literal>_</literal> + means “built-in type variable”; <literal>t</literal> + means “from the typechecker”; <literal>s</literal> + means “from the simplifier”; and so on. The `number' + is printed fairly compactly in a `base-62' format, which everyone + hates except me (WDP).</para> + + <para>Remember, everything has a “Unique” and it is + usually printed out when debugging, in some form or another. So + here we go…</para> + +<programlisting> +Desugared: +Main.skip2{-r1L6-} :: _forall_ a$_4 =>{{Num a$_4}} -> a$_4 -> [a$_4] + +--# `r1L6' is the Unique for Main.skip2; +--# `_4' is the Unique for the type-variable (template) `a' +--# `{{Num a$_4}}' is a dictionary argument + +_NI_ + +--# `_NI_' means "no (pragmatic) information" yet; it will later +--# evolve into the GHC_PRAGMA info that goes into interface files. + +Main.skip2{-r1L6-} = + /\ _4 -> \ d.Num.t4Gt -> + let { + {- CoRec -} + +.t4Hg :: _4 -> _4 -> _4 + _NI_ + +.t4Hg = (+{-r3JH-} _4) d.Num.t4Gt + + fromInt.t4GS :: Int{-2i-} -> _4 + _NI_ + fromInt.t4GS = (fromInt{-r3JX-} _4) d.Num.t4Gt + +--# The `+' class method (Unique: r3JH) selects the addition code +--# from a `Num' dictionary (now an explicit lambda'd argument). +--# Because Core is 2nd-order lambda-calculus, type applications +--# and lambdas (/\) are explicit. So `+' is first applied to a +--# type (`_4'), then to a dictionary, yielding the actual addition +--# function that we will use subsequently... + +--# We play the exact same game with the (non-standard) class method +--# `fromInt'. Unsurprisingly, the type `Int' is wired into the +--# compiler. + + lit.t4Hb :: _4 + _NI_ + lit.t4Hb = + let { + ds.d4Qz :: Int{-2i-} + _NI_ + ds.d4Qz = I#! 2# + } in fromInt.t4GS ds.d4Qz + +--# `I# 2#' is just the literal Int `2'; it reflects the fact that +--# GHC defines `data Int = I# Int#', where Int# is the primitive +--# unboxed type. (see relevant info about unboxed types elsewhere...) + +--# The `!' after `I#' indicates that this is a *saturated* +--# application of the `I#' data constructor (i.e., not partially +--# applied). + + skip2.t3Ja :: _4 -> [_4] + _NI_ + skip2.t3Ja = + \ m.r1H4 -> + let { ds.d4QQ :: [_4] + _NI_ + ds.d4QQ = + let { + ds.d4QY :: _4 + _NI_ + ds.d4QY = +.t4Hg m.r1H4 lit.t4Hb + } in skip2.t3Ja ds.d4QY + } in + :! _4 m.r1H4 ds.d4QQ + + {- end CoRec -} + } in skip2.t3Ja +</programlisting> + + <para>(“It's just a simple functional language” is an + unregisterised trademark of Peyton Jones Enterprises, plc.)</para> + + </sect2> + + <sect2 id="unreg"> + <title>Unregisterised compilation</title> + <indexterm><primary>unregisterised compilation</primary></indexterm> + + <para>The term "unregisterised" really means "compile via vanilla + C", disabling some of the platform-specific tricks that GHC + normally uses to make programs go faster. When compiling + unregisterised, GHC simply generates a C file which is compiled + via gcc.</para> + + <para>Unregisterised compilation can be useful when porting GHC to + a new machine, since it reduces the prerequisite tools to + <command>gcc</command>, <command>as</command>, and + <command>ld</command> and nothing more, and furthermore the amount + of platform-specific code that needs to be written in order to get + unregisterised compilation going is usually fairly small.</para> + + <variablelist> + <varlistentry> + <term> + <option>-unreg</option>: + <indexterm><primary><option>-unreg</option></primary></indexterm> + </term> + <listitem> + <para>Compile via vanilla ANSI C only, turning off + platform-specific optimisations. NOTE: in order to use + <option>-unreg</option>, you need to have a set of libraries + (including the RTS) built for unregisterised compilation. + This amounts to building GHC with way "u" enabled.</para> + </listitem> + </varlistentry> + </variablelist> + </sect2> + +</sect1> + +<!-- Emacs stuff: + ;;; Local Variables: *** + ;;; mode: xml *** + ;;; sgml-parent-document: ("users_guide.xml" "book" "chapter" "sect1") *** + ;;; End: *** + --> diff --git a/docs/users_guide/ffi-chap.xml b/docs/users_guide/ffi-chap.xml new file mode 100644 index 0000000000..e1374c4610 --- /dev/null +++ b/docs/users_guide/ffi-chap.xml @@ -0,0 +1,411 @@ +<?xml version="1.0" encoding="iso-8859-1"?> +<!-- FFI docs as a chapter --> + +<chapter id="ffi"> + <title> +Foreign function interface (FFI) + </title> + + <para>GHC (mostly) conforms to the Haskell 98 Foreign Function Interface + Addendum 1.0, whose definition is available from <ulink url="http://haskell.org/"><literal>http://haskell.org/</literal></ulink>.</para> + + <para>To enable FFI support in GHC, give the <option>-fffi</option><indexterm><primary><option>-fffi</option></primary> + </indexterm>flag, or +the <option>-fglasgow-exts</option><indexterm><primary><option>-fglasgow-exts</option></primary> + </indexterm> flag which implies <option>-fffi</option> +.</para> + + <para>The FFI support in GHC diverges from the Addendum in the following ways:</para> + + <itemizedlist> + <listitem> + <para>Syntactic forms and library functions proposed in earlier versions + of the FFI are still supported for backwards compatibility.</para> + </listitem> + + <listitem> + <para>GHC implements a number of GHC-specific extensions to the FFI + Addendum. These extensions are described in <xref linkend="sec-ffi-ghcexts" />, but please note that programs using + these features are not portable. Hence, these features should be + avoided where possible.</para> + </listitem> + </itemizedlist> + + <para>The FFI libraries are documented in the accompanying library + documentation; see for example the <literal>Foreign</literal> + module.</para> + + <sect1 id="sec-ffi-ghcexts"> + <title>GHC extensions to the FFI Addendum</title> + + <para>The FFI features that are described in this section are specific to + GHC. Avoid them where possible to not compromise the portability of the + resulting code.</para> + + <sect2> + <title>Unboxed types</title> + + <para>The following unboxed types may be used as basic foreign types + (see FFI Addendum, Section 3.2): <literal>Int#</literal>, + <literal>Word#</literal>, <literal>Char#</literal>, + <literal>Float#</literal>, <literal>Double#</literal>, + <literal>Addr#</literal>, <literal>StablePtr# a</literal>, + <literal>MutableByteArray#</literal>, <literal>ForeignObj#</literal>, + and <literal>ByteArray#</literal>.</para> + </sect2> + + </sect1> + + <sect1 id="sec-ffi-ghc"> + <title>Using the FFI with GHC</title> + + <para>The following sections also give some hints and tips on the + use of the foreign function interface in GHC.</para> + + <sect2 id="foreign-export-ghc"> + <title>Using <literal>foreign export</literal> and <literal>foreign import ccall "wrapper"</literal> with GHC</title> + + <indexterm><primary><literal>foreign export + </literal></primary><secondary>with GHC</secondary> + </indexterm> + + <para>When GHC compiles a module (say <filename>M.hs</filename>) + which uses <literal>foreign export</literal> or + <literal>foreign import "wrapper"</literal>, it generates two + additional files, <filename>M_stub.c</filename> and + <filename>M_stub.h</filename>. GHC will automatically compile + <filename>M_stub.c</filename> to generate + <filename>M_stub.o</filename> at the same time.</para> + + <para>For a plain <literal>foreign export</literal>, the file + <filename>M_stub.h</filename> contains a C prototype for the + foreign exported function, and <filename>M_stub.c</filename> + contains its definition. For example, if we compile the + following module:</para> + +<programlisting> +module Foo where + +foreign export ccall foo :: Int -> IO Int + +foo :: Int -> IO Int +foo n = return (length (f n)) + +f :: Int -> [Int] +f 0 = [] +f n = n:(f (n-1))</programlisting> + + <para>Then <filename>Foo_stub.h</filename> will contain + something like this:</para> + +<programlisting> +#include "HsFFI.h" +extern HsInt foo(HsInt a0);</programlisting> + + <para>and <filename>Foo_stub.c</filename> contains the + compiler-generated definition of <literal>foo()</literal>. To + invoke <literal>foo()</literal> from C, just <literal>#include + "Foo_stub.h"</literal> and call <literal>foo()</literal>.</para> + + <para>The <filename>foo_stub.c</filename> and + <filename>foo_stub.h</filename> files can be redirected using the + <option>-stubdir</option> option; see <xref linkend="options-output" + />.</para> + + <sect3 id="using-own-main"> + <title>Using your own <literal>main()</literal></title> + + <para>Normally, GHC's runtime system provides a + <literal>main()</literal>, which arranges to invoke + <literal>Main.main</literal> in the Haskell program. However, + you might want to link some Haskell code into a program which + has a main function written in another language, say C. In + order to do this, you have to initialize the Haskell runtime + system explicitly.</para> + + <para>Let's take the example from above, and invoke it from a + standalone C program. Here's the C code:</para> + +<programlisting> +#include <stdio.h> +#include "HsFFI.h" + +#ifdef __GLASGOW_HASKELL__ +#include "foo_stub.h" +#endif + +#ifdef __GLASGOW_HASKELL__ +extern void __stginit_Foo ( void ); +#endif + +int main(int argc, char *argv[]) +{ + int i; + + hs_init(&argc, &argv); +#ifdef __GLASGOW_HASKELL__ + hs_add_root(__stginit_Foo); +#endif + + for (i = 0; i < 5; i++) { + printf("%d\n", foo(2500)); + } + + hs_exit(); + return 0; +}</programlisting> + + <para>We've surrounded the GHC-specific bits with + <literal>#ifdef __GLASGOW_HASKELL__</literal>; the rest of the + code should be portable across Haskell implementations that + support the FFI standard.</para> + + <para>The call to <literal>hs_init()</literal> + initializes GHC's runtime system. Do NOT try to invoke any + Haskell functions before calling + <literal>hs_init()</literal>: strange things will + undoubtedly happen.</para> + + <para>We pass <literal>argc</literal> and + <literal>argv</literal> to <literal>hs_init()</literal> + so that it can separate out any arguments for the RTS + (i.e. those arguments between + <literal>+RTS...-RTS</literal>).</para> + + <para>Next, we call + <function>hs_add_root</function><indexterm><primary><function>hs_add_root</function></primary> + </indexterm>, a GHC-specific interface which is required to + initialise the Haskell modules in the program. The argument + to <function>hs_add_root</function> should be the name of the + initialization function for the "root" module in your program + - in other words, the module which directly or indirectly + imports all the other Haskell modules in the program. In a + standalone Haskell program the root module is normally + <literal>Main</literal>, but when you are using Haskell code + from a library it may not be. If your program has multiple + root modules, then you can call + <function>hs_add_root</function> multiple times, one for each + root. The name of the initialization function for module + <replaceable>M</replaceable> is + <literal>__stginit_<replaceable>M</replaceable></literal>, and + it may be declared as an external function symbol as in the + code above.</para> + + <para>After we've finished invoking our Haskell functions, we + can call <literal>hs_exit()</literal>, which + terminates the RTS. It runs any outstanding finalizers and + generates any profiling or stats output that might have been + requested.</para> + + <para>There can be multiple calls to + <literal>hs_init()</literal>, but each one should be matched + by one (and only one) call to + <literal>hs_exit()</literal><footnote><para>The outermost + <literal>hs_exit()</literal> will actually de-initialise the + system. NOTE that currently GHC's runtime cannot reliably + re-initialise after this has happened.</para> + </footnote>.</para> + + <para>NOTE: when linking the final program, it is normally + easiest to do the link using GHC, although this isn't + essential. If you do use GHC, then don't forget the flag + <option>-no-hs-main</option><indexterm><primary><option>-no-hs-main</option></primary> + </indexterm>, otherwise GHC will try to link + to the <literal>Main</literal> Haskell module.</para> + </sect3> + + <sect3 id="foreign-export-dynamic-ghc"> + <title>Using <literal>foreign import ccall "wrapper"</literal> with GHC</title> + + <indexterm><primary><literal>foreign import + ccall "wrapper"</literal></primary><secondary>with GHC</secondary> + </indexterm> + + <para>When <literal>foreign import ccall "wrapper"</literal> is used + in a Haskell module, The C stub file <filename>M_stub.c</filename> + generated by GHC contains small helper functions used by the code + generated for the imported wrapper, so it must be linked in to the + final program. When linking the program, remember to include + <filename>M_stub.o</filename> in the final link command line, or + you'll get link errors for the missing function(s) (this isn't + necessary when building your program with <literal>ghc + ––make</literal>, as GHC will automatically link in the + correct bits).</para> + </sect3> + </sect2> + + <sect2 id="glasgow-foreign-headers"> + <title>Using function headers</title> + + <indexterm><primary>C calls, function headers</primary></indexterm> + + <para>When generating C (using the <option>-fvia-C</option> + directive), one can assist the C compiler in detecting type + errors by using the <option>-#include</option> directive + (<xref linkend="options-C-compiler"/>) to provide + <filename>.h</filename> files containing function + headers.</para> + + <para>For example,</para> + +<programlisting> +#include "HsFFI.h" + +void initialiseEFS (HsInt size); +HsInt terminateEFS (void); +HsForeignObj emptyEFS(void); +HsForeignObj updateEFS (HsForeignObj a, HsInt i, HsInt x); +HsInt lookupEFS (HsForeignObj a, HsInt i); +</programlisting> + + <para>The types <literal>HsInt</literal>, + <literal>HsForeignObj</literal> etc. are described in the H98 FFI + Addendum.</para> + + <para>Note that this approach is only + <emphasis>essential</emphasis> for returning + <literal>float</literal>s (or if <literal>sizeof(int) != + sizeof(int *)</literal> on your architecture) but is a Good + Thing for anyone who cares about writing solid code. You're + crazy not to do it.</para> + +<para> +What if you are importing a module from another package, and +a cross-module inlining exposes a foreign call that needs a supporting +<option>-#include</option>? If the imported module is from the same package as +the module being compiled, you should supply all the <option>-#include</option> +that you supplied when compiling the imported module. If the imported module comes +from another package, you won't necessarily know what the appropriate +<option>-#include</option> options are; but they should be in the package +configuration, which GHC knows about. So if you are building a package, remember +to put all those <option>-#include</option> options into the package configuration. +See the <literal>c_includes</literal> field in <xref linkend="package-management"/>. +</para> + +<para> +It is also possible, according the FFI specification, to put the +<option>-#include</option> option in the foreign import +declaration itself: +<programlisting> + foreign import "foo.h f" f :: Int -> IO Int +</programlisting> +When compiling this module, GHC will generate a C file that includes +the specified <option>-#include</option>. However, GHC +<emphasis>disables</emphasis> cross-module inlining for such foreign +calls, because it doesn't transport the <option>-#include</option> +information across module boundaries. (There is no fundamental reason for this; +it was just tiresome to implement. The wrapper, which unboxes the arguments +etc, is still inlined across modules.) So if you want the foreign call itself +to be inlined across modules, use the command-line and package-configuration +<option>-#include</option> mechanism. +</para> + + <sect3 id="finding-header-files"> + <title>Finding Header files</title> + + <para>Header files named by the <option>-#include</option> + option or in a <literal>foreign import</literal> declaration + are searched for using the C compiler's usual search path. + You can add directories to this search path using the + <option>-I</option> option (see <xref + linkend="c-pre-processor"/>).</para> + + <para>Note: header files are ignored unless compiling via C. + If you had been compiling your code using the native code + generator (the default) and suddenly switch to compiling via + C, then you can get unexpected errors about missing include + files. Compiling via C is enabled automatically when certain + options are given (eg. <option>-O</option> and + <option>-prof</option> both enable + <option>-fvia-C</option>).</para> + </sect3> + + </sect2> + + <sect2> + <title>Memory Allocation</title> + + <para>The FFI libraries provide several ways to allocate memory + for use with the FFI, and it isn't always clear which way is the + best. This decision may be affected by how efficient a + particular kind of allocation is on a given compiler/platform, + so this section aims to shed some light on how the different + kinds of allocation perform with GHC.</para> + + <variablelist> + <varlistentry> + <term><literal>alloca</literal> and friends</term> + <listitem> + <para>Useful for short-term allocation when the allocation + is intended to scope over a given <literal>IO</literal> + computation. This kind of allocation is commonly used + when marshalling data to and from FFI functions.</para> + + <para>In GHC, <literal>alloca</literal> is implemented + using <literal>MutableByteArray#</literal>, so allocation + and deallocation are fast: much faster than C's + <literal>malloc/free</literal>, but not quite as fast as + stack allocation in C. Use <literal>alloca</literal> + whenever you can.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>mallocForeignPtr</literal></term> + <listitem> + <para>Useful for longer-term allocation which requires + garbage collection. If you intend to store the pointer to + the memory in a foreign data structure, then + <literal>mallocForeignPtr</literal> is + <emphasis>not</emphasis> a good choice, however.</para> + + <para>In GHC, <literal>mallocForeignPtr</literal> is also + implemented using <literal>MutableByteArray#</literal>. + Although the memory is pointed to by a + <literal>ForeignPtr</literal>, there are no actual + finalizers involved (unless you add one with + <literal>addForeignPtrFinalizer</literal>), and the + deallocation is done using GC, so + <literal>mallocForeignPtr</literal> is normally very + cheap.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>malloc/free</literal></term> + <listitem> + <para>If all else fails, then you need to resort to + <literal>Foreign.malloc</literal> and + <literal>Foreign.free</literal>. These are just wrappers + around the C functions of the same name, and their + efficiency will depend ultimately on the implementations + of these functions in your platform's C library. We + usually find <literal>malloc</literal> and + <literal>free</literal> to be significantly slower than + the other forms of allocation above.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>Foreign.Marshal.Pool</literal></term> + <listitem> + <para>Pools are currently implemented using + <literal>malloc/free</literal>, so while they might be a + more convenient way to structure your memory allocation + than using one of the other forms of allocation, they + won't be any more efficient. We do plan to provide an + improved-performance implementation of Pools in the + future, however.</para> + </listitem> + </varlistentry> + </variablelist> + </sect2> + </sect1> +</chapter> + +<!-- Emacs stuff: + ;;; Local Variables: *** + ;;; mode: xml *** + ;;; sgml-parent-document: ("users_guide.xml" "book" "chapter") *** + ;;; End: *** + --> diff --git a/docs/users_guide/flags.xml b/docs/users_guide/flags.xml new file mode 100644 index 0000000000..e288da2fb2 --- /dev/null +++ b/docs/users_guide/flags.xml @@ -0,0 +1,1894 @@ +<?xml version="1.0" encoding="iso-8859-1"?> + <sect1 id="flag-reference"> + <title>Flag reference</title> + + <para>This section is a quick-reference for GHC's command-line + flags. For each flag, we also list its static/dynamic status (see + <xref linkend="static-dynamic-flags"/>), and the flag's opposite + (if available).</para> + + <sect2> + <title>Help and verbosity options</title> + + <para><xref linkend="options-help"/></para> + + <informaltable> + <tgroup cols="4" align="left" colsep="1" rowsep="1"> + <thead> + <row> + <entry>Flag</entry> + <entry>Description</entry> + <entry>Static/Dynamic</entry> + <entry>Reverse</entry> + </row> + </thead> + <tbody> + <row> + <entry><option>-?</option></entry> + <entry>help</entry> + <entry>mode</entry> + <entry>-</entry> + </row> + <row> + <entry><option>-help</option></entry> + <entry>help</entry> + <entry>mode</entry> + <entry>-</entry> + </row> + <row> + <entry><option>-v</option></entry> + <entry>verbose mode (equivalent to <option>-v3</option>)</entry> + <entry>dynamic</entry> + <entry>-</entry> + </row> + <row> + <entry><option>-v</option><replaceable>n</replaceable></entry> + <entry>set verbosity level</entry> + <entry>dynamic</entry> + <entry>-</entry> + </row> + <row> + <entry><option>-V</option></entry> + <entry>display GHC version</entry> + <entry>mode</entry> + <entry>-</entry> + </row> + <row> + <entry><option>––version</option></entry> + <entry>display GHC version</entry> + <entry>mode</entry> + <entry>-</entry> + </row> + <row> + <entry><option>––numeric-version</option></entry> + <entry>display GHC version (numeric only)</entry> + <entry>mode</entry> + <entry>-</entry> + </row> + <row> + <entry><option>––print-libdir</option></entry> + <entry>display GHC library directory</entry> + <entry>mode</entry> + <entry>-</entry> + </row> + <row> + <entry><option>-ferror-spans</option></entry> + <entry>output full span in error messages</entry> + <entry>static</entry> + <entry>-</entry> + </row> + <row> + <entry><option>-Rghc-timing</option></entry> + <entry>Summarise timing stats for GHC (same as <literal>+RTS -tstderr</literal>)</entry> + <entry>static</entry> + <entry>-</entry> + </row> + </tbody> + </tgroup> + </informaltable> + + </sect2> + <sect2> + <title>Which phases to run</title> + + <para><xref linkend="options-order"/></para> + + <informaltable> + <tgroup cols="4" align="left" colsep="1" rowsep="1"> + <thead> + <row> + <entry>Flag</entry> + <entry>Description</entry> + <entry>Static/Dynamic</entry> + <entry>Reverse</entry> + </row> + </thead> + <tbody> + <row> + <entry><option>-E</option></entry> + <entry>Stop after preprocessing (<literal>.hspp</literal> file)</entry> + <entry>mode</entry> + <entry>-</entry> + </row> + <row> + <entry><option>-C</option></entry> + <entry>Stop after generating C (<literal>.hc</literal> file)</entry> + <entry>mode</entry> + <entry>-</entry> + </row> + <row> + <entry><option>-S</option></entry> + <entry>Stop after generating assembly (<literal>.s</literal> file)</entry> + <entry>mode</entry> + <entry>-</entry> + </row> + <row> + <entry><option>-c</option></entry> + <entry>Do not link</entry> + <entry>dynamic</entry> + <entry>-</entry> + </row> + <row> + <entry><option>-x</option> <replaceable>suffix</replaceable></entry> + <entry>Override default behaviour for source files</entry> + <entry>static</entry> + <entry>-</entry> + </row> + </tbody> + </tgroup> + </informaltable> + </sect2> + + <sect2> + <title>Alternative modes of operation</title> + + <para><xref linkend="modes"/></para> + + <informaltable> + <tgroup cols="4" align="left" colsep="1" rowsep="1"> + <thead> + <row> + <entry>Flag</entry> + <entry>Description</entry> + <entry>Static/Dynamic</entry> + <entry>Reverse</entry> + </row> + </thead> + <tbody> + <row> + <entry><option>--interactive</option></entry> + <entry>Interactive mode - normally used by just running <command>ghci</command></entry> + <entry>mode</entry> + <entry>-</entry> + </row> + <row> + <entry><option>--make</option></entry> + <entry>Build a multi-module Haskell program, automatically figuring out dependencies. Likely to be much easier, and faster, than using <command>make</command>.</entry> + <entry>mode</entry> + <entry>-</entry> + </row> + <row> + <entry><option>-e <replaceable>expr</replaceable></option></entry> + <entry>Evaluate <replaceable>expr</replaceable></entry> + <entry>mode</entry> + <entry>-</entry> + </row> + <row> + <entry><option>-M</option></entry> + <entry>Generate dependency information suitable for use in a <filename>Makefile</filename>.</entry> + <entry>mode</entry> + <entry>-</entry> + </row> + </tbody> + </tgroup> + </informaltable> + </sect2> + + <sect2> + <title>Redirecting output</title> + + <para><xref linkend="options-output"/></para> + + <informaltable> + <tgroup cols="4" align="left" colsep="1" rowsep="1"> + <thead> + <row> + <entry>Flag</entry> + <entry>Description</entry> + <entry>Static/Dynamic</entry> + <entry>Reverse</entry> + </row> + </thead> + <tbody> + <row> + <entry><option>-hcsuf</option> <replaceable>suffix</replaceable></entry> + <entry>set the suffix to use for intermediate C files</entry> + <entry>dynamic</entry> + <entry>-</entry> + </row> + <row> + <entry><option>-hidir</option> <replaceable>dir</replaceable></entry> + <entry>set directory for interface files</entry> + <entry>dynamic</entry> + <entry>-</entry> + </row> + <row> + <entry><option>-hisuf</option> <replaceable>suffix</replaceable></entry> + <entry>set the suffix to use for interface files</entry> + <entry>dynamic</entry> + <entry>-</entry> + </row> + <row> + <entry><option>-o</option> <replaceable>filename</replaceable></entry> + <entry>set output filename</entry> + <entry>dynamic</entry> + <entry>-</entry> + </row> + <row> + <entry><option>-odir</option> <replaceable>dir</replaceable></entry> + <entry>set output directory</entry> + <entry>dynamic</entry> + <entry>-</entry> + </row> + <row> + <entry><option>-ohi</option> <replaceable>filename</replaceable></entry> + <entry>set the filename in which to put the interface</entry> + <entry>dynamic</entry> + <entry></entry> + </row> + <row> + <entry><option>-osuf</option> <replaceable>suffix</replaceable></entry> + <entry>set the output file suffix</entry> + <entry>dynamic</entry> + <entry>-</entry> + </row> + <row> + <entry><option>-stubdir</option> <replaceable>dir</replaceable></entry> + <entry>redirect FFi stub files</entry> + <entry>dynamic</entry> + <entry>-</entry> + </row> + </tbody> + </tgroup> + </informaltable> + </sect2> + + <sect2> + <title>Keeping intermediate files</title> + + <para><xref linkend="keeping-intermediates"/></para> + + <informaltable> + <tgroup cols="4" align="left" colsep="1" rowsep="1"> + <thead> + <row> + <entry>Flag</entry> + <entry>Description</entry> + <entry>Static/Dynamic</entry> + <entry>Reverse</entry> + </row> + </thead> + <tbody> + <row> + <entry><option>-keep-hc-file</option></entry> + <entry>retain intermediate <literal>.hc</literal> files</entry> + <entry>dynamic</entry> + <entry>-</entry> + </row> + <row> + <entry><option>-keep-s-file</option></entry> + <entry>retain intermediate <literal>.s</literal> files</entry> + <entry>dynamic</entry> + <entry>-</entry> + </row> + <row> + <entry><option>-keep-raw-s-file</option></entry> + <entry>retain intermediate <literal>.raw_s</literal> files</entry> + <entry>dynamic</entry> + <entry>-</entry> + </row> + <row> + <entry><option>-keep-tmp-files</option></entry> + <entry>retain all intermediate temporary files</entry> + <entry>dynamic</entry> + <entry>-</entry> + </row> + </tbody> + </tgroup> + </informaltable> + </sect2> + + <sect2> + <title>Temporary files</title> + + <para><xref linkend="temp-files"/></para> + + <informaltable> + <tgroup cols="4" align="left" colsep="1" rowsep="1"> + <thead> + <row> + <entry>Flag</entry> + <entry>Description</entry> + <entry>Static/Dynamic</entry> + <entry>Reverse</entry> + </row> + </thead> + <tbody> + <row> + <entry><option>-tmpdir</option></entry> + <entry>set the directory for temporary files</entry> + <entry>dynamic</entry> + <entry>-</entry> + </row> + </tbody> + </tgroup> + </informaltable> + </sect2> + + <sect2> + <title>Finding imports</title> + + <para><xref linkend="search-path"/></para> + + <informaltable> + <tgroup cols="4" align="left" colsep="1" rowsep="1"> + <thead> + <row> + <entry>Flag</entry> + + <entry>Description</entry> + <entry>Static/Dynamic</entry> + <entry>Reverse</entry> + </row> + </thead> + <tbody> + <row> + <entry><option>-i</option><replaceable>dir1</replaceable>:<replaceable>dir2</replaceable>:...</entry> + <entry>add <replaceable>dir</replaceable>, + <replaceable>dir2</replaceable>, etc. to import path</entry> + <entry>dynamic</entry> + <entry>-</entry> + </row> + <row> + <entry><option>-i</option></entry> + <entry>Empty the import directory list</entry> + <entry>dynamic</entry> + <entry>-</entry> + </row> + </tbody> + </tgroup> + </informaltable> + </sect2> + + <sect2> + <title>Interface file options</title> + + <para><xref linkend="hi-options"/></para> + + <informaltable> + <tgroup cols="4" align="left" colsep="1" rowsep="1"> + <thead> + <row> + <entry>Flag</entry> + + <entry>Description</entry> + <entry>Static/Dynamic</entry> + <entry>Reverse</entry> + </row> + </thead> + <tbody> + <row> + <entry><option>-ddump-hi</option></entry> + <entry>Dump the new interface to stdout</entry> + <entry>dynamic</entry> + <entry>-</entry> + </row> + <row> + <entry><option>-ddump-hi-diffs</option></entry> + <entry>Show the differences vs. the old interface</entry> + <entry>dynamic</entry> + <entry>-</entry> + </row> + <row> + <entry><option>-ddump-minimal-imports</option></entry> + <entry>Dump a minimal set of imports</entry> + <entry>dynamic</entry> + <entry>-</entry> + </row> + <row> + <entry><option>--show-iface</option> <replaceable>file</replaceable></entry> + <entry>Read the interface in + <replaceable>file</replaceable> and dump it as text to + <literal>stdout</literal>.</entry> + <entry>mode</entry> + <entry>-</entry> + </row> + </tbody> + </tgroup> + </informaltable> + </sect2> + + <sect2> + <title>Recompilation checking</title> + + <para><xref linkend="recomp"/></para> + + <informaltable> + <tgroup cols="4" align="left" colsep="1" rowsep="1"> + <thead> + <row> + <entry>Flag</entry> + + <entry>Description</entry> + <entry>Static/Dynamic</entry> + <entry>Reverse</entry> + </row> + </thead> + <tbody> + <row> + <entry><option>-no-recomp</option></entry> + <entry>Turn off recompilation checking; implied by any + <option>-ddump-X</option> option</entry> + <entry>dynamic</entry> + <entry><option>-recomp</option></entry> + </row> + </tbody> + </tgroup> + </informaltable> + </sect2> + + <sect2> + <title>Interactive-mode options</title> + + <para><xref linkend="ghci-dot-files"/></para> + + <informaltable> + <tgroup cols="4" align="left" colsep="1" rowsep="1"> + <thead> + <row> + <entry>Flag</entry> + <entry>Description</entry> + <entry>Static/Dynamic</entry> + <entry>Reverse</entry> + </row> + </thead> + <tbody> + <row> + <entry><option>-ignore-dot-ghci</option></entry> + <entry>Disable reading of <filename>.ghci</filename> files</entry> + <entry>static</entry> + <entry>-</entry> + </row> + <row> + <entry><option>-read-dot-ghci</option></entry> + <entry>Enable reading of <filename>.ghci</filename> files</entry> + <entry>static</entry> + <entry>-</entry> + </row> + </tbody> + </tgroup> + </informaltable> + </sect2> + + <sect2> + <title>Packages</title> + + <para><xref linkend="packages"/></para> + + <informaltable> + <tgroup cols="4" align="left" colsep="1" rowsep="1"> + <thead> + <row> + <entry>Flag</entry> + <entry>Description</entry> + <entry>Static/Dynamic</entry> + <entry>Reverse</entry> + </row> + </thead> + <tbody> + <row> + <entry><option>-package</option> <replaceable>P</replaceable></entry> + <entry>Expose package <replaceable>P</replaceable></entry> + <entry>dynamic</entry> + <entry>-</entry> + </row> + <row> + <entry><option>-hide-all-packages</option></entry> + <entry>Hide all packages by default</entry> + <entry>static</entry> + <entry>-</entry> + </row> + <row> + <entry><option>-hide-package</option> <replaceable>name</replaceable></entry> + <entry>Hide package <replaceable>P</replaceable></entry> + <entry>dynamic</entry> + <entry>-</entry> + </row> + <row> + <entry><option>-ignore-package</option> <replaceable>name</replaceable></entry> + <entry>Ignore package <replaceable>P</replaceable></entry> + <entry>dynamic</entry> + <entry>-</entry> + </row> + <row> + <entry><option>-package-conf</option> <replaceable>file</replaceable></entry> + <entry>Load more packages from <replaceable>file</replaceable></entry> + <entry>dynamic</entry> + <entry>-</entry> + </row> + <row> + <entry><option>-no-user-package-conf</option></entry> + <entry>Don't load the user's package config file.</entry> + <entry>dynamic</entry> + <entry>-</entry> + </row> + </tbody> + </tgroup> + </informaltable> + </sect2> + + <sect2> + <title>Language options</title> + + <para><xref linkend="options-language"/></para> + + <informaltable> + <tgroup cols="4" align="left" colsep="1" rowsep="1"> + <thead> + <row> + <entry>Flag</entry> + <entry>Description</entry> + <entry>Static/Dynamic</entry> + <entry>Reverse</entry> + </row> + </thead> + <tbody> + <row> + <entry><option>-fallow-overlapping-instances</option></entry> + <entry>Enable overlapping instances</entry> + <entry>dynamic</entry> + <entry><option>-fno-allow-overlapping-instances</option></entry> + </row> + <row> + <entry><option>-fallow-undecidable-instances</option></entry> + <entry>Enable undecidable instances</entry> + <entry>dynamic</entry> + <entry><option>-fno-allow-undecidable-instances</option></entry> + </row> + <row> + <entry><option>-fallow-incoherent-instances</option></entry> + <entry>Enable incoherent instances. + Implies <option>-fallow-overlapping-instances</option> </entry> + <entry>dynamic</entry> + <entry><option>-fno-allow-incoherent-instances</option></entry> + </row> + <row> + <entry><option>-farrows</option></entry> + <entry>Enable arrow notation extension</entry> + <entry>dynamic</entry> + <entry><option>-fno-arrows</option></entry> + </row> + <row> + <entry><option>-fcontext-stack</option><replaceable>n</replaceable></entry> + <entry>set the limit for context reduction</entry> + <entry>static</entry> + <entry><option>-</option></entry> + </row> + <row> + <entry><option>-ffi</option> or <option>-fffi</option></entry> + <entry>Enable foreign function interface (implied by + <option>-fglasgow-exts</option>)</entry> + <entry>dynamic</entry> + <entry><option>-fno-ffi</option></entry> + </row> + <row> + <entry><option>-fgenerics</option></entry> + <entry>Enable generics</entry> + <entry>dynamic</entry> + <entry><option>-fno-fgenerics</option></entry> + </row> + <row> + <entry><option>-fglasgow-exts</option></entry> + <entry>Enable most language extensions</entry> + <entry>dynamic</entry> + <entry><option>-fno-glasgow-exts</option></entry> + </row> + <row> + <entry><option>-fimplicit-params</option></entry> + <entry>Enable Implicit Parameters. + Implied by <option>-fglasgow-exts</option>.</entry> + <entry>dynamic</entry> + <entry><option>-fno-implicit-params</option></entry> + </row> + <row> + <entry><option>-firrefutable-tuples</option></entry> + <entry>Make tuple pattern matching irrefutable</entry> + <entry>dynamic</entry> + <entry><option>-fno-irrefutable-tuples</option></entry> + </row> + <row> + <entry><option>-fno-implicit-prelude</option></entry> + <entry>Don't implicitly <literal>import Prelude</literal></entry> + <entry>dynamic</entry> + <entry><option>-fimplicit-prelude</option></entry> + </row> + <row> + <entry><option>-fno-monomorphism-restriction</option></entry> + <entry>Disable the monomorphism restriction</entry> + <entry>dynamic</entry> + <entry><option>-fmonomorphism-restriction</option></entry> + </row> + <row> + <entry><option>-fscoped-type-variables</option></entry> + <entry>Enable lexically-scoped type variables. + Implied by <option>-fglasgow-exts</option>.</entry> + <entry>dynamic</entry> + <entry><option>-fno-scoped-type-variables</option></entry> + </row> + <row> + <entry><option>-fth</option></entry> + <entry>Enable Template Haskell. + Implied by <option>-fglasgow-exts</option>.</entry> + <entry>dynamic</entry> + <entry><option>-fno-th</option></entry> + </row> + </tbody> + </tgroup> + </informaltable> + </sect2> + + <sect2> + <title>Warnings</title> + + <para>(<xref linkend="options-sanity"/></para> + + <informaltable> + <tgroup cols="4" align="left" colsep="1" rowsep="1"> + <thead> + <row> + <entry>Flag</entry> + <entry>Description</entry> + <entry>Static/Dynamic</entry> + <entry>Reverse</entry> + </row> + </thead> + <tbody> + <row> + <entry><option>-W</option></entry> + <entry>enable normal warnings</entry> + <entry>dynamic</entry> + <entry><option>-w</option></entry> + </row> + <row> + <entry><option>-w</option></entry> + <entry>disable all warnings</entry> + <entry>dynamic</entry> + <entry>-</entry> + </row> + <row> + <entry><option>-Wall</option></entry> + <entry>enable all warnings</entry> + <entry>dynamic</entry> + <entry><option>-w</option></entry> + </row> + <row> + <entry><option>-Werror</option></entry> + <entry>make warnings fatal</entry> + <entry>dynamic</entry> + <entry></entry> + </row> + + <row> + <entry><option>-fwarn-deprecations</option></entry> + <entry>warn about uses of functions & types that are deprecated</entry> + <entry>dynamic</entry> + <entry><option>-fno-warn-deprecations</option></entry> + </row> + + <row> + <entry><option>-fwarn-duplicate-exports</option></entry> + <entry>warn when an entity is exported multiple times</entry> + <entry>dynamic</entry> + <entry><option>-fno-warn-duplicate-exports</option></entry> + </row> + + <row> + <entry><option>-fwarn-hi-shadowing</option></entry> + <entry>warn when a <literal>.hi</literal> file in the + current directory shadows a library</entry> + <entry>dynamic</entry> + <entry><option>-fno-warn-hi-shadowing</option></entry> + </row> + + <row> + <entry><option>-fwarn-incomplete-patterns</option></entry> + <entry>warn when a pattern match could fail</entry> + <entry>dynamic</entry> + <entry><option>-fno-warn-incomplete-patterns</option></entry> + </row> + + <row> + <entry><option>-fwarn-incomplete-record-updates</option></entry> + <entry>warn when a record update could fail</entry> + <entry>dynamic</entry> + <entry><option>-fno-warn-incomplete-record-updates</option></entry> + </row> + + <row> + <entry><option>-fwarn-misc</option></entry> + <entry>enable miscellaneous warnings</entry> + <entry>dynamic</entry> + <entry><option>-fno-warn-misc</option></entry> + </row> + + <row> + <entry><option>-fwarn-missing-fields</option></entry> + <entry>warn when fields of a record are uninitialised</entry> + <entry>dynamic</entry> + <entry><option>-fno-warn-missing-fields</option></entry> + </row> + + <row> + <entry><option>-fwarn-missing-methods</option></entry> + <entry>warn when class methods are undefined</entry> + <entry>dynamic</entry> + <entry><option>-fno-warn-missing-methods</option></entry> + </row> + + <row> + <entry><option>-fwarn-missing-signatures</option></entry> + <entry>warn about top-level functions without signatures</entry> + <entry>dynamic</entry> + <entry><option>-fno-warn-missing-signatures</option></entry> + </row> + + <row> + <entry><option>-fwarn-name-shadowing</option></entry> + <entry>warn when names are shadowed</entry> + <entry>dynamic</entry> + <entry><option>-fno-warn-name-shadowing</option></entry> + </row> + + <row> + <entry><option>-fwarn-oprhans</option></entry> + <entry>warn when the module contains "orphan" instance declarations + or rewrite rules</entry> + <entry>dynamic</entry> + <entry><option>-fno-warn-orphans</option></entry> + </row> + + <row> + <entry><option>-fwarn-overlapping-patterns</option></entry> + <entry>warn about overlapping patterns</entry> + <entry>dynamic</entry> + <entry><option>-fno-warn-overlapping-patterns</option></entry> + </row> + + <row> + <entry><option>-fwarn-simple-patterns</option></entry> + <entry>warn about lambda-patterns that can fail</entry> + <entry>dynamic</entry> + <entry><option>-fno-warn-simple-patterns</option></entry> + </row> + + <row> + <entry><option>-fwarn-type-defaults</option></entry> + <entry>warn when defaulting happens</entry> + <entry>dynamic</entry> + <entry><option>-fno-warn-type-defaults</option></entry> + </row> + + <row> + <entry><option>-fwarn-unused-binds</option></entry> + <entry>warn about bindings that are unused</entry> + <entry>dynamic</entry> + <entry><option>-fno-warn-unused-binds</option></entry> + </row> + + <row> + <entry><option>-fwarn-unused-imports</option></entry> + <entry>warn about unnecessary imports</entry> + <entry>dynamic</entry> + <entry><option>-fno-warn-unused-imports</option></entry> + </row> + + <row> + <entry><option>-fwarn-unused-matches</option></entry> + <entry>warn about variables in patterns that aren't used</entry> + <entry>dynamic</entry> + <entry><option>-fno-warn-unused-matches</option></entry> + </row> + + </tbody> + </tgroup> + </informaltable> + + </sect2> + <sect2> + <title>Optimisation levels</title> + + <para><xref linkend="options-optimise"/></para> + + <informaltable> + <tgroup cols="4" align="left" colsep="1" rowsep="1"> + <thead> + <row> + <entry>Flag</entry> + <entry>Description</entry> + <entry>Static/Dynamic</entry> + <entry>Reverse</entry> + </row> + </thead> + <tbody> + <row> + <entry><option>-O</option></entry> + <entry>Enable default optimisation (level 1)</entry> + <entry>dynamic</entry> + <entry><option>-O0</option></entry> + </row> + <row> + <entry><option>-O</option><replaceable>n</replaceable></entry> + <entry>Set optimisation level <replaceable>n</replaceable></entry> + <entry>dynamic</entry> + <entry><option>-O0</option></entry> + </row> + </tbody> + </tgroup> + </informaltable> + + </sect2> + <sect2> + <title>Individual optimisations</title> + + <para><xref linkend="options-f"/></para> + + <informaltable> + <tgroup cols="4" align="left" colsep="1" rowsep="1"> + <thead> + <row> + <entry>Flag</entry> + <entry>Description</entry> + <entry>Static/Dynamic</entry> + <entry>Reverse</entry> + </row> + </thead> + <tbody> + <row> + <entry><option>-fcase-merge</option></entry> + <entry>Enable case-merging</entry> + <entry>dynamic</entry> + <entry><option>-fno-case-merge</option></entry> + </row> + + <row> + <entry><option>-fdicts-strict</option></entry> + <entry>Make dictionaries strict</entry> + <entry>static</entry> + <entry><option>-fno-dicts-strict</option></entry> + </row> + + <row> + <entry><option>-fdo-eta-reduction</option></entry> + <entry>Enable eta-reduction</entry> + <entry>dynamic</entry> + <entry><option>-fno-do-eta-reduction</option></entry> + </row> + + <row> + <entry><option>-fdo-lambda-eta-expansion</option></entry> + <entry>Enable lambda eta-reduction</entry> + <entry>dynamic</entry> + <entry><option>-fno-do-lambda-eta-expansion</option></entry> + </row> + + <row> + <entry><option>-fexcess-precision</option></entry> + <entry>Enable excess intermediate precision</entry> + <entry>dynamic</entry> + <entry><option>-fno-excess-precision</option></entry> + </row> + + <row> + <entry><option>-frules-off</option></entry> + <entry>Switch off all rewrite rules (including rules + generated by automatic specialisation of overloaded functions)</entry> + <entry>static</entry> + <entry><option>-frules-off</option></entry> + </row> + + <row> + <entry><option>-fignore-asserts</option></entry> + <entry>Ignore assertions in the source</entry> + <entry>dynamic</entry> + <entry><option>-fno-ignore-asserts</option></entry> + </row> + + <row> + <entry><option>-fignore-interface-pragmas</option></entry> + <entry>Ignore pragmas in interface files</entry> + <entry>dynamic</entry> + <entry><option>-fno-ignore-interface-pragmas</option></entry> + </row> + + <row> + <entry><option>-fliberate-case-threshold</option></entry> + <entry>Tweak the liberate-case optimisation (default: 10)</entry> + <entry>static</entry> + <entry><option>-fno-liberate-case-threshold</option></entry> + </row> + + <row> + <entry><option>-fomit-interface-pragmas</option></entry> + <entry>Don't generate interface pragmas</entry> + <entry>dynamic</entry> + <entry><option>-fno-omit-interface-pragmas</option></entry> + </row> + + <row> + <entry><option>-fmax-worker-args</option></entry> + <entry>If a worker has that many arguments, none will be + unpacked anymore (default: 10)</entry> + <entry>static</entry> + <entry>-</entry> + </row> + + <row> + <entry><option>-fmax-simplifier-iterations</option></entry> + <entry>Set the max iterations for the simplifier</entry> + <entry>dynamic</entry> + <entry>-</entry> + </row> + + <row> + <entry><option>-fno-state-hack</option></entry> + <entry>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.</entry> + <entry>static</entry> + <entry>-</entry> + </row> + + <row> + <entry><option>-fno-cse</option></entry> + <entry>Turn off common sub-expression</entry> + <entry>dynamic</entry> + <entry>-</entry> + </row> + + <row> + <entry><option>-fno-full-laziness</option></entry> + <entry>Turn off full laziness (floating bindings outwards).</entry> + <entry>dynamic</entry> + <entry>-ffull-laziness</entry> + </row> + + <row> + <entry><option>-fno-pre-inlining</option></entry> + <entry>Turn off pre-inlining</entry> + <entry>static</entry> + <entry>-</entry> + </row> + + <row> + <entry><option>-fno-strictness</option></entry> + <entry>Turn off strictness analysis</entry> + <entry>dynamic</entry> + <entry>-</entry> + </row> + + <row> + <entry><option>-funbox-strict-fields</option></entry> + <entry>Flatten strict constructor fields</entry> + <entry>dynamic</entry> + <entry><option>-fno-unbox-strict-fields</option></entry> + </row> + + <row> + <entry><option>-funfolding-creation-threshold</option></entry> + <entry>Tweak unfolding settings</entry> + <entry>static</entry> + <entry><option>-fno-unfolding-creation-threshold</option></entry> + </row> + + <row> + <entry><option>-funfolding-fun-discount</option></entry> + <entry>Tweak unfolding settings</entry> + <entry>static</entry> + <entry><option>-fno-unfolding-fun-discount</option></entry> + </row> + + <row> + <entry><option>-funfolding-keeness-factor</option></entry> + <entry>Tweak unfolding settings</entry> + <entry>static</entry> + <entry><option>-fno-unfolding-keeness-factor</option></entry> + </row> + + <row> + <entry><option>-funfolding-update-in-place</option></entry> + <entry>Tweak unfolding settings</entry> + <entry>static</entry> + <entry><option>-fno-unfolding-update-in-place</option></entry> + </row> + + <row> + <entry><option>-funfolding-use-threshold</option></entry> + <entry>Tweak unfolding settings</entry> + <entry>static</entry> + <entry><option>-fno-unfolding-use-threshold</option></entry> + </row> + </tbody> + </tgroup> + </informaltable> + </sect2> + + <sect2> + <title>Profiling options</title> + + <para><xref linkend="profiling"/></para> + + <informaltable> + <tgroup cols="4" align="left" colsep="1" rowsep="1"> + <thead> + <row> + <entry>Flag</entry> + <entry>Description</entry> + <entry>Static/Dynamic</entry> + <entry>Reverse</entry> + </row> + </thead> + <tbody> + <row> + <entry><option>-auto</option></entry> + <entry>Auto-add <literal>_scc_</literal>s to all + exported functions</entry> + <entry>static</entry> + <entry><option>-no-auto</option></entry> + </row> + <row> + <entry><option>-auto-all</option></entry> + <entry>Auto-add <literal>_scc_</literal>s to all + top-level functions</entry> + <entry>static</entry> + <entry><option>-no-auto-all</option></entry> + </row> + <row> + <entry><option>-auto-dicts</option></entry> + <entry>Auto-add <literal>_scc_</literal>s to all dictionaries</entry> + <entry>static</entry> + <entry><option>-no-auto-dicts</option></entry> + </row> + <row> + <entry><option>-caf-all</option></entry> + <entry>Auto-add <literal>_scc_</literal>s to all CAFs</entry> + <entry>static</entry> + <entry><option>-no-caf-all</option></entry> + </row> + <row> + <entry><option>-prof</option></entry> + <entry>Turn on profiling</entry> + <entry>static</entry> + <entry>-</entry> + </row> + <row> + <entry><option>-ticky</option></entry> + <entry>Turn on ticky-ticky profiling</entry> + <entry>static</entry> + <entry>-</entry> + </row> + </tbody> + </tgroup> + </informaltable> + </sect2> + + <sect2> + <title>Parallelism options</title> + + <para><xref linkend="sec-using-parallel"/></para> + + <informaltable> + <tgroup cols="4" align="left" colsep="1" rowsep="1"> + <thead> + <row> + <entry>Flag</entry> + <entry>Description</entry> + <entry>Static/Dynamic</entry> + <entry>Reverse</entry> + </row> + </thead> + <tbody> + <row> + <entry><option>-gransim</option></entry> + <entry>Enable GRANSIM</entry> + <entry>static</entry> + <entry>-</entry> + </row> + <row> + <entry><option>-parallel</option></entry> + <entry>Enable Parallel Haskell</entry> + <entry>static</entry> + <entry>-</entry> + </row> + <row> + <entry><option>-smp</option></entry> + <entry>Enable SMP support</entry> + <entry>static</entry> + <entry>-</entry> + </row> + </tbody> + </tgroup> + </informaltable> + </sect2> + + <sect2> + <title>C pre-processor options</title> + + <para><xref linkend="c-pre-processor"/></para> + + <informaltable> + <tgroup cols="4" align="left" colsep="1" rowsep="1"> + <thead> + <row> + <entry>Flag</entry> + <entry>Description</entry> + <entry>Static/Dynamic</entry> + <entry>Reverse</entry> + </row> + </thead> + <tbody> + <row> + <entry><option>-cpp</option></entry> + <entry>Run the C pre-processor on Haskell source files</entry> + <entry>dynamic</entry> + <entry>-</entry> + </row> + <row> + <entry><option>-D</option><replaceable>symbol</replaceable><optional>=<replaceable>value</replaceable></optional></entry> + <entry>Define a symbol in the C pre-processor</entry> + <entry>dynamic</entry> + <entry><option>-U</option><replaceable>symbol</replaceable></entry> + </row> + <row> + <entry><option>-U</option><replaceable>symbol</replaceable></entry> + <entry>Undefine a symbol in the C pre-processor</entry> + <entry>dynamic</entry> + <entry>-</entry> + </row> + <row> + <entry><option>-I</option><replaceable>dir</replaceable></entry> + <entry>Add <replaceable>dir</replaceable> to the + directory search list for <literal>#include</literal> files</entry> + <entry>dynamic</entry> + <entry>-</entry> + </row> + </tbody> + </tgroup> + </informaltable> + </sect2> + + <sect2> + <title>C compiler options</title> + + <para><xref linkend="options-C-compiler"/></para> + <informaltable> + <tgroup cols="4" align="left" colsep="1" rowsep="1"> + <thead> + <row> + <entry>Flag</entry> + <entry>Description</entry> + <entry>Static/Dynamic</entry> + <entry>Reverse</entry> + </row> + </thead> + <tbody> + <row> + <entry><option>-#include</option> <replaceable>file</replaceable></entry> + <entry>Include <replaceable>file</replaceable> when + compiling the <filename>.hc</filename> file</entry> + <entry>dynamic</entry> + <entry>-</entry> + </row> + </tbody> + </tgroup> + </informaltable> + </sect2> + + <sect2> + <title>Code generation options</title> + + <para><xref linkend="options-codegen"/></para> + + <informaltable> + <tgroup cols="4" align="left" colsep="1" rowsep="1"> + <thead> + <row> + <entry>Flag</entry> + <entry>Description</entry> + <entry>Static/Dynamic</entry> + <entry>Reverse</entry> + </row> + </thead> + <tbody> + <row> + <entry><option>-fasm</option></entry> + <entry>Use the native code generator</entry> + <entry>dynamic</entry> + <entry>-fvia-C</entry> + </row> + <row> + <entry><option>-fvia-C</option></entry> + <entry>Compile via C</entry> + <entry>dynamic</entry> + <entry>-fasm</entry> + </row> + <row> + <entry><option>-fno-code</option></entry> + <entry>Omit code generation</entry> + <entry>mode</entry> + <entry>-</entry> + </row> + </tbody> + </tgroup> + </informaltable> + </sect2> + + <sect2> + <title>Linking options</title> + + <para><xref linkend="options-linker"/></para> + + <informaltable> + <tgroup cols="4" align="left" colsep="1" rowsep="1"> + <thead> + <row> + <entry>Flag</entry> + <entry>Description</entry> + <entry>Static/Dynamic</entry> + <entry>Reverse</entry> + </row> + </thead> + <tbody> + <row> + <entry><option>-dynamic</option></entry> + <entry>Use dynamic Haskell libraries (if available)</entry> + <entry>static</entry> + <entry>-</entry> + </row> + <row> + <entry><option>-framework</option> <replaceable>name</replaceable></entry> + <entry>On Darwin/MacOS X only, link in the framework <replaceable>name</replaceable>. + This option corresponds to the <option>-framework</option> option for Apple's Linker.</entry> + <entry>dynamic</entry> + <entry>-</entry> + </row> + <row> + <entry><option>-framework-path</option> <replaceable>name</replaceable></entry> + <entry>On Darwin/MacOS X only, add <replaceable>dir</replaceable> to the list of + directories searched for frameworks. + This option corresponds to the <option>-F</option> option for Apple's Linker.</entry> + <entry>dynamic</entry> + <entry>-</entry> + </row> + <row> + <entry><option>-l</option><replaceable>lib</replaceable></entry> + <entry>Link in library <replaceable>lib</replaceable></entry> + <entry>dynamic</entry> + <entry>-</entry> + </row> + <row> + <entry><option>-L</option><replaceable>dir</replaceable></entry> + <entry>Add <replaceable>dir</replaceable> to the list of + directories searched for libraries</entry> + <entry>dynamic</entry> + <entry>-</entry> + </row> + <row> + <entry><option>-main-is</option></entry> + <entry>Set main function</entry> + <entry>dynamic</entry> + <entry>-</entry> + </row> + <row> + <entry><option>--mk-dll</option></entry> + <entry>DLL-creation mode (Windows only)</entry> + <entry>dynamic</entry> + <entry>-</entry> + </row> + <row> + <entry><option>-no-hs-main</option></entry> + <entry>Don't assume this program contains <literal>main</literal></entry> + <entry>dynamic</entry> + <entry>-</entry> + </row> + <row> + <entry><option>-no-link</option></entry> + <entry>Omit linking</entry> + <entry>dynamic</entry> + <entry>-</entry> + </row> + <row> + <entry><option>-package</option> <replaceable>name</replaceable></entry> + <entry>Link in package <replaceable>name</replaceable></entry> + <entry>dynamic</entry> + <entry>-</entry> + </row> + <row> + <entry><option>-split-objs</option></entry> + <entry>Split objects (for libraries)</entry> + <entry>dynamic</entry> + <entry>-</entry> + </row> + <row> + <entry><option>-static</option></entry> + <entry>Use static Haskell libraries</entry> + <entry>static</entry> + <entry>-</entry> + </row> + <row> + <entry><option>-threaded</option></entry> + <entry>Use the threaded runtime</entry> + <entry>static</entry> + <entry>-</entry> + </row> + <row> + <entry><option>-debug</option></entry> + <entry>Use the debugging runtime</entry> + <entry>static</entry> + <entry>-</entry> + </row> + </tbody> + </tgroup> + </informaltable> + </sect2> + + <sect2> + <title>Replacing phases</title> + + <para><xref linkend="replacing-phases"/></para> + + <informaltable> + <tgroup cols="4" align="left" colsep="1" rowsep="1"> + <thead> + <row> + <entry>Flag</entry> + <entry>Description</entry> + <entry>Static/Dynamic</entry> + <entry>Reverse</entry> + </row> + </thead> + <tbody> + <row> + <entry><option>-pgmL</option> <replaceable>cmd</replaceable></entry> + <entry>Use <replaceable>cmd</replaceable> as the literate pre-processor</entry> + <entry>dynamic</entry> + <entry>-</entry> + </row> + <row> + <entry><option>-pgmP</option> <replaceable>cmd</replaceable></entry> + <entry>Use <replaceable>cmd</replaceable> as the C + pre-processor (with <option>-cpp</option> only)</entry> + <entry>dynamic</entry> + <entry>-</entry> + </row> + <row> + <entry><option>-pgmc</option> <replaceable>cmd</replaceable></entry> + <entry>Use <replaceable>cmd</replaceable> as the C compiler</entry> + <entry>dynamic</entry> + <entry>-</entry> + </row> + <row> + <entry><option>-pgma</option> <replaceable>cmd</replaceable></entry> + <entry>Use <replaceable>cmd</replaceable> as the assembler</entry> + <entry>dynamic</entry> + <entry>-</entry> + </row> + <row> + <entry><option>-pgml</option> <replaceable>cmd</replaceable></entry> + <entry>Use <replaceable>cmd</replaceable> as the linker</entry> + <entry>dynamic</entry> + <entry>-</entry> + </row> + <row> + <entry><option>-pgmdll</option> <replaceable>cmd</replaceable></entry> + <entry>Use <replaceable>cmd</replaceable> as the DLL generator</entry> + <entry>dynamic</entry> + <entry>-</entry> + </row> + <row> + <entry><option>-pgmdep</option> <replaceable>cmd</replaceable></entry> + <entry>Use <replaceable>cmd</replaceable> as the dependency generator</entry> + <entry>dyanmic</entry> + <entry>-</entry> + </row> + <row> + <entry><option>-pgmF</option> <replaceable>cmd</replaceable></entry> + <entry>Use <replaceable>cmd</replaceable> as the pre-processor + (with <option>-F</option> only)</entry> + <entry>dynamic</entry> + <entry>-</entry> + </row> + </tbody> + </tgroup> + </informaltable> + <indexterm><primary><option>-pgmL</option></primary></indexterm> + <indexterm><primary><option>-pgmP</option></primary></indexterm> + <indexterm><primary><option>-pgmc</option></primary></indexterm> + <indexterm><primary><option>-pgma</option></primary></indexterm> + <indexterm><primary><option>-pgml</option></primary></indexterm> + <indexterm><primary><option>-pgmdll</option></primary></indexterm> + <indexterm><primary><option>-pgmdep</option></primary></indexterm> + <indexterm><primary><option>-pgmF</option></primary></indexterm> + + </sect2> + + <sect2> + <title>Forcing options to particular phases</title> + + <para><xref linkend="forcing-options-through"/></para> + + <informaltable> + <tgroup cols="4" align="left" colsep="1" rowsep="1"> + <thead> + <row> + <entry>Flag</entry> + <entry>Description</entry> + <entry>Static/Dynamic</entry> + <entry>Reverse</entry> + </row> + </thead> + <tbody> + <row> + <entry><option>-optL</option> <replaceable>option</replaceable></entry> + <entry>pass <replaceable>option</replaceable> to the literate pre-processor</entry> + <entry>dynamic</entry> + <entry>-</entry> + </row> + <row> + <entry><option>-optP</option> <replaceable>option</replaceable></entry> + <entry>pass <replaceable>option</replaceable> to cpp (with + <option>-cpp</option> only)</entry> + <entry>dynamic</entry> + <entry>-</entry> + </row> + <row> + <entry><option>-optF</option> <replaceable>option</replaceable></entry> + <entry>pass <replaceable>option</replaceable> to the + custom pre-processor</entry> + <entry>dynamic</entry> + <entry>-</entry> + </row> + <row> + <entry><option>-optc</option> <replaceable>option</replaceable></entry> + <entry>pass <replaceable>option</replaceable> to the C compiler</entry> + <entry>dynamic</entry> + <entry>-</entry> + </row> + <row> + <entry><option>-opta</option> <replaceable>option</replaceable></entry> + <entry>pass <replaceable>option</replaceable> to the assembler</entry> + <entry>dynamic</entry> + <entry>-</entry> + </row> + <row> + <entry><option>-optl</option> <replaceable>option</replaceable></entry> + <entry>pass <replaceable>option</replaceable> to the linker</entry> + <entry>dynamic</entry> + <entry>-</entry> + </row> + <row> + <entry><option>-optdll</option> <replaceable>option</replaceable></entry> + <entry>pass <replaceable>option</replaceable> to the DLL generator</entry> + <entry>dynamic</entry> + <entry>-</entry> + </row> + <row> + <entry><option>-optdep</option> <replaceable>option</replaceable></entry> + <entry>pass <replaceable>option</replaceable> to the dependency generator</entry> + <entry>dynamic</entry> + <entry>-</entry> + </row> + </tbody> + </tgroup> + </informaltable> + </sect2> + + <sect2> + <title>Platform-specific options</title> + + <para><xref linkend="options-platform"/></para> + + <informaltable> + <tgroup cols="4" align="left" colsep="1" rowsep="1"> + <thead> + <row> + <entry>Flag</entry> + <entry>Description</entry> + <entry>Static/Dynamic</entry> + <entry>Reverse</entry> + </row> + </thead> + <tbody> + <row> + <entry><option>-mv8</option></entry> + <entry>(SPARC only) enable version 8 support</entry> + <entry>static</entry> + <entry>-</entry> + </row> + <row> + <entry><option>-monly-[32]-regs</option></entry> + <entry>(x86 only) give some registers back to the C compiler</entry> + <entry>dynamic</entry> + <entry>-</entry> + </row> + </tbody> + </tgroup> + </informaltable> + </sect2> + + + <sect2> + <title>External core file options</title> + + <para><xref linkend="ext-core"/></para> + + <informaltable> + <tgroup cols="4" align="left" colsep="1" rowsep="1"> + <thead> + <row> + <entry>Flag</entry> + <entry>Description</entry> + <entry>Static/Dynamic</entry> + <entry>Reverse</entry> + </row> + </thead> + <tbody> + <row> + <entry><option>-fext-core</option></entry> + <entry>Generate <filename>.hcr</filename> external Core files</entry> + <entry>static</entry> + <entry>-</entry> + </row> + </tbody> + </tgroup> + </informaltable> + </sect2> + + + <sect2> + <title>Compiler debugging options</title> + + <para><xref linkend="options-debugging"/></para> + + <informaltable> + <tgroup cols="4" align="left" colsep="1" rowsep="1"> + <thead> + <row> + <entry>Flag</entry> + <entry>Description</entry> + <entry>Static/Dynamic</entry> + <entry>Reverse</entry> + </row> + </thead> + <tbody> + <row> + <entry><option>-dcore-lint</option></entry> + <entry>Turn on internal sanity checking</entry> + <entry>dynamic</entry> + <entry>-</entry> + </row> + <row> + <entry><option>-ddump-absC</option></entry> + <entry>Dump abstract C</entry> + <entry>dynamic</entry> + <entry>-</entry> + </row> + <row> + <entry><option>-ddump-asm</option></entry> + <entry>Dump assembly</entry> + <entry>dynamic</entry> + <entry>-</entry> + </row> + <row> + <entry><option>-ddump-bcos</option></entry> + <entry>Dump interpreter byte code</entry> + <entry>dynamic</entry> + <entry>-</entry> + </row> + <row> + <entry><option>-ddump-cpranal</option></entry> + <entry>Dump output from CPR analysis</entry> + <entry>dynamic</entry> + <entry>-</entry> + </row> + <row> + <entry><option>-ddump-cse</option></entry> + <entry>Dump CSE output</entry> + <entry>dynamic</entry> + <entry>-</entry> + </row> + <row> + <entry><option>-ddump-deriv</option></entry> + <entry>Dump deriving output</entry> + <entry>dynamic</entry> + <entry>-</entry> + </row> + <row> + <entry><option>-ddump-ds</option></entry> + <entry>Dump desugarer output</entry> + <entry>dynamic</entry> + <entry>-</entry> + </row> + <row> + <entry><option>-ddump-flatC</option></entry> + <entry>Dump “flat” C</entry> + <entry>dynamic</entry> + <entry>-</entry> + </row> + <row> + <entry><option>-ddump-foreign</option></entry> + <entry>Dump <literal>foreign export</literal> stubs</entry> + <entry>dynamic</entry> + <entry>-</entry> + </row> + <row> + <entry><option>-ddump-inlinings</option></entry> + <entry>Dump inlining info</entry> + <entry>dynamic</entry> + <entry>-</entry> + </row> + <row> + <entry><option>-ddump-occur-anal</option></entry> + <entry>Dump occurrence analysis output</entry> + <entry>dynamic</entry> + <entry>-</entry> + </row> + <row> + <entry><option>-ddump-parsed</option></entry> + <entry>Dump parse tree</entry> + <entry>dynamic</entry> + <entry>-</entry> + </row> + <row> + <entry><option>-ddump-realC</option></entry> + <entry>Dump “real” C</entry> + <entry>dynamic</entry> + <entry>-</entry> + </row> + <row> + <entry><option>-ddump-rn</option></entry> + <entry>Dump renamer output</entry> + <entry>dynamic</entry> + <entry>-</entry> + </row> + <row> + <entry><option>-ddump-rules</option></entry> + <entry>Dump rules</entry> + <entry>dynamic</entry> + <entry>-</entry> + </row> + <row> + <entry><option>-ddump-sat</option></entry> + <entry>Dump saturated output</entry> + <entry>dynamic</entry> + <entry>-</entry> + </row> + <row> + <entry><option>-ddump-simpl</option></entry> + <entry>Dump final simplifier output</entry> + <entry>dynamic</entry> + <entry>-</entry> + </row> + <row> + <entry><option>-ddump-simpl-iterations</option></entry> + <entry>Dump output from each simplifier iteration</entry> + <entry>dynamic</entry> + <entry>-</entry> + </row> + <row> + <entry><option>-ddump-spec</option></entry> + <entry>Dump specialiser output</entry> + <entry>dynamic</entry> + <entry>-</entry> + </row> + <row> + <entry><option>-ddump-stg</option></entry> + <entry>Dump final STG</entry> + <entry>dynamic</entry> + <entry>-</entry> + </row> + <row> + <entry><option>-ddump-stranal</option></entry> + <entry>Dump strictness analyser output</entry> + <entry>dynamic</entry> + <entry>-</entry> + </row> + <row> + <entry><option>-ddump-tc</option></entry> + <entry>Dump typechecker output</entry> + <entry>dynamic</entry> + <entry>-</entry> + </row> + <row> + <entry><option>-ddump-types</option></entry> + <entry>Dump type signatures</entry> + <entry>dynamic</entry> + <entry>-</entry> + </row> + <row> + <entry><option>-ddump-usagesp</option></entry> + <entry>Dump UsageSP analysis output</entry> + <entry>dynamic</entry> + <entry>-</entry> + </row> + <row> + <entry><option>-ddump-worker-wrapper</option></entry> + <entry>Dump worker-wrapper output</entry> + <entry>dynamic</entry> + <entry>-</entry> + </row> + <row> + <entry><option>-ddump-rn-trace</option></entry> + <entry>Trace renamer</entry> + <entry>dynamic</entry> + <entry>-</entry> + </row> + <row> + <entry><option>-ddump-rn-stats</option></entry> + <entry>Renamer stats</entry> + <entry>dynamic</entry> + <entry>-</entry> + </row> + <row> + <entry><option>-ddump-stix</option></entry> + <entry>Native code generator intermediate form</entry> + <entry>dynamic</entry> + <entry>-</entry> + </row> + <row> + <entry><option>-ddump-simpl-stats</option></entry> + <entry>Dump simplifier stats</entry> + <entry>dynamic</entry> + <entry>-</entry> + </row> + <row> + <entry><option>-dppr-debug</option></entry> + <entry>Turn on debug printing (more verbose)</entry> + <entry>static</entry> + <entry>-</entry> + </row> + <row> + <entry><option>-dppr-noprags</option></entry> + <entry>Don't output pragma info in dumps</entry> + <entry>static</entry> + <entry>-</entry> + </row> + <row> + <entry><option>-dppr-user-length</option></entry> + <entry>Set the depth for printing expressions in error msgs</entry> + <entry>static</entry> + <entry>-</entry> + </row> + <row> + <entry><option>-dsource-stats</option></entry> + <entry>Dump haskell source stats</entry> + <entry>dynamic</entry> + <entry>-</entry> + </row> + <row> + <entry><option>-dstg-lint</option></entry> + <entry>STG pass sanity checking</entry> + <entry>dynamic</entry> + <entry>-</entry> + </row> + <row> + <entry><option>-dstg-stats</option></entry> + <entry>Dump STG stats</entry> + <entry>dynamic</entry> + <entry>-</entry> + </row> + <row> + <entry><option>-dusagesp-lint</option></entry> + <entry>UsageSP sanity checker</entry> + <entry>dynamic</entry> + <entry>-</entry> + </row> + <row> + <entry><option>-dverbose-core2core</option></entry> + <entry>Show output from each core-to-core pass</entry> + <entry>dynamic</entry> + <entry>-</entry> + </row> + <row> + <entry><option>-dverbose-stg2stg</option></entry> + <entry>Show output from each STG-to-STG pass</entry> + <entry>dynamic</entry> + <entry>-</entry> + </row> + <row> + <entry><option>-unreg</option></entry> + <entry>Enable unregisterised compilation</entry> + <entry>static</entry> + <entry>-</entry> + </row> + </tbody> + </tgroup> + </informaltable> + </sect2> + + <sect2> + <title>Misc compiler options</title> + + <informaltable> + <tgroup cols="4" align="left" colsep="1" rowsep="1"> + <thead> + <row> + <entry>Flag</entry> + <entry>Description</entry> + <entry>Static/Dynamic</entry> + <entry>Reverse</entry> + </row> + </thead> + <tbody> + <row> + <entry><option>-femit-extern-decls</option></entry> + <entry>???</entry> + <entry>static</entry> + <entry>-</entry> + </row> + <row> + <entry><option>-fno-hi-version-check</option></entry> + <entry>Don't complain about <literal>.hi</literal> file mismatches</entry> + <entry>static</entry> + <entry>-</entry> + </row> + <row> + <entry><option>-dno-black-holing</option></entry> + <entry>Turn off black holing (probably doesn't work)</entry> + <entry>static</entry> + <entry>-</entry> + </row> + <row> + <entry><option>-fno-method-sharing</option></entry> + <entry>Don't share specialisations of overloaded functions</entry> + <entry>static</entry> + <entry>-</entry> + </row> + <row> + <entry><option>-fhistory-size</option></entry> + <entry>Set simplification history size</entry> + <entry>static</entry> + <entry>-</entry> + </row> + <row> + <entry><option>-funregisterised</option></entry> + <entry>Unregisterised compilation (use <option>-unreg</option> instead)</entry> + <entry>static</entry> + <entry>-</entry> + </row> + <row> + <entry><option>-fno-asm-mangling</option></entry> + <entry>Turn off assembly mangling (use <option>-unreg</option> instead)</entry> + <entry>dynamic</entry> + <entry>-</entry> + </row> + </tbody> + </tgroup> + </informaltable> + </sect2> + </sect1> + + +<!-- +Still to document: + +Misc: + , ( "H" , HasArg (setHeapSize . fromIntegral . decodeSize) ) + + -Bdir +--> + +<!-- Emacs stuff: + ;;; Local Variables: *** + ;;; mode: xml *** + ;;; sgml-parent-document: ("users_guide.xml" "book" "chapter") *** + ;;; End: *** + --> diff --git a/docs/users_guide/ghci.xml b/docs/users_guide/ghci.xml new file mode 100644 index 0000000000..786815d484 --- /dev/null +++ b/docs/users_guide/ghci.xml @@ -0,0 +1,1500 @@ +<?xml version="1.0" encoding="iso-8859-1"?> +<chapter id="ghci"> + <title>Using GHCi</title> + <indexterm><primary>GHCi</primary></indexterm> + <indexterm><primary>interpreter</primary><see>GHCi</see></indexterm> + <indexterm><primary>interactive</primary><see>GHCi</see></indexterm> + + <para>GHCi<footnote> + <para>The ‘i’ stands for “Interactive”</para> + </footnote> + is GHC's interactive environment, in which Haskell expressions can + be interactively evaluated and programs can be interpreted. If + you're familiar with <ulink url="http://www.haskell.org/hugs/">Hugs</ulink><indexterm><primary>Hugs</primary> + </indexterm>, then you'll be right at home with GHCi. However, GHCi + also has support for interactively loading compiled code, as well as + supporting all<footnote><para>except <literal>foreign export</literal>, at the moment</para> + </footnote> the language extensions that GHC provides.</para> + <indexterm><primary>FFI</primary><secondary>GHCi support</secondary></indexterm> + <indexterm><primary>Foreign Function Interface</primary><secondary>GHCi support</secondary></indexterm> + + <sect1> + <title>Introduction to GHCi</title> + + <para>Let's start with an example GHCi session. You can fire up + GHCi with the command <literal>ghci</literal>:</para> + +<screen> +$ ghci + ___ ___ _ + / _ \ /\ /\/ __(_) + / /_\// /_/ / / | | GHC Interactive, version 5.04, for Haskell 98. +/ /_\\/ __ / /___| | http://www.haskell.org/ghc/ +\____/\/ /_/\____/|_| Type :? for help. + +Loading package base ... linking ... done. +Loading package haskell98 ... linking ... done. +Prelude> +</screen> + + <para>There may be a short pause while GHCi loads the prelude and + standard libraries, after which the prompt is shown. If we follow + the instructions and type <literal>:?</literal> for help, we + get:</para> + +<screen> + Commands available from the prompt: + + <stmt> evaluate/run <stmt> + :add <filename> ... add module(s) to the current target set + :browse [*]<module> display the names defined by <module> + :cd <dir> change directory to <dir> + :def <cmd> <expr> define a command :<cmd> + :help, :? display this list of commands + :info [<name> ...] display information about the given names + :load <filename> ... load module(s) and their dependents + :module [+/-] [*]<mod> ... set the context for expression evaluation + :reload reload the current module set + + :set <option> ... set options + :set args <arg> ... set the arguments returned by System.getArgs + :set prog <progname> set the value returned by System.getProgName + :set prompt <prompt> set the prompt used in GHCi + + :show modules show the currently loaded modules + :show bindings show the current bindings made at the prompt + + :ctags [<file>] create tags file for Vi (default: "tags") + :etags [<file>] create tags file for Emacs (defauilt: "TAGS") + :type <expr> show the type of <expr> + :kind <type> show the kind of <type> + :undef <cmd> undefine user-defined command :<cmd> + :unset <option> ... unset options + :quit exit GHCi + :!<command> run the shell command <command> + + Options for `:set' and `:unset': + + +r revert top-level expressions after each evaluation + +s print timing/memory stats after each evaluation + +t print type after evaluation + -<flags> most GHC command line flags can also be set here + (eg. -v2, -fglasgow-exts, etc.) +</screen> + + <para>We'll explain most of these commands as we go along. For + Hugs users: many things work the same as in Hugs, so you should be + able to get going straight away.</para> + + <para>Haskell expressions can be typed at the prompt:</para> + <indexterm><primary>prompt</primary><secondary>GHCi</secondary> + </indexterm> + +<screen> +Prelude> 1+2 +3 +Prelude> let x = 42 in x / 9 +4.666666666666667 +Prelude> +</screen> + + <para>GHCi interprets the whole line as an expression to evaluate. + The expression may not span several lines - as soon as you press + enter, GHCi will attempt to evaluate it.</para> + </sect1> + + <sect1> + <title>Loading source files</title> + + <para>Suppose we have the following Haskell source code, which we + place in a file <filename>Main.hs</filename>:</para> + +<programlisting> +main = print (fac 20) + +fac 0 = 1 +fac n = n * fac (n-1) +</programlisting> + + <para>You can save <filename>Main.hs</filename> anywhere you like, + but if you save it somewhere other than the current + directory<footnote><para>If you started up GHCi from the command + line then GHCi's current directory is the same as the current + directory of the shell from which it was started. If you started + GHCi from the “Start” menu in Windows, then the + current directory is probably something like + <filename>C:\Documents and Settings\<replaceable>user + name</replaceable></filename>.</para> </footnote> then we will + need to change to the right directory in GHCi:</para> + +<screen> +Prelude> :cd <replaceable>dir</replaceable> +</screen> + + <para>where <replaceable>dir</replaceable> is the directory (or + folder) in which you saved <filename>Main.hs</filename>.</para> + + <para>To load a Haskell source file into GHCi, use the + <literal>:load</literal> command:</para> + <indexterm><primary><literal>:load</literal></primary></indexterm> + +<screen> +Prelude> :load Main +Compiling Main ( Main.hs, interpreted ) +Ok, modules loaded: Main. +*Main> +</screen> + + <para>GHCi has loaded the <literal>Main</literal> module, and the + prompt has changed to “<literal>*Main></literal>” to + indicate that the current context for expressions typed at the + prompt is the <literal>Main</literal> module we just loaded (we'll + explain what the <literal>*</literal> means later in <xref + linkend="ghci-scope"/>). So we can now type expressions involving + the functions from <filename>Main.hs</filename>:</para> + +<screen> +*Main> fac 17 +355687428096000 +</screen> + + <para>Loading a multi-module program is just as straightforward; + just give the name of the “topmost” module to the + <literal>:load</literal> command (hint: <literal>:load</literal> + can be abbreviated to <literal>:l</literal>). The topmost module + will normally be <literal>Main</literal>, but it doesn't have to + be. GHCi will discover which modules are required, directly or + indirectly, by the topmost module, and load them all in dependency + order.</para> + + <sect2 id="ghci-modules-filenames"> + <title>Modules vs. filenames</title> + <indexterm><primary>modules</primary><secondary>and filenames</secondary></indexterm> + <indexterm><primary>filenames</primary><secondary>of modules</secondary></indexterm> + + <para>Question: How does GHC find the filename which contains + module <replaceable>M</replaceable>? Answer: it looks for the + file <literal><replaceable>M</replaceable>.hs</literal>, or + <literal><replaceable>M</replaceable>.lhs</literal>. This means + that for most modules, the module name must match the filename. + If it doesn't, GHCi won't be able to find it.</para> + + <para>There is one exception to this general rule: when you load + a program with <literal>:load</literal>, or specify it when you + invoke <literal>ghci</literal>, you can give a filename rather + than a module name. This filename is loaded if it exists, and + it may contain any module you like. This is particularly + convenient if you have several <literal>Main</literal> modules + in the same directory and you can't call them all + <filename>Main.hs</filename>.</para> + + <para>The search path for finding source files is specified with + the <option>-i</option> option on the GHCi command line, like + so:</para> +<screen>ghci -i<replaceable>dir<subscript>1</subscript></replaceable>:...:<replaceable>dir<subscript>n</subscript></replaceable></screen> + + <para>or it can be set using the <literal>:set</literal> command + from within GHCi (see <xref + linkend="ghci-cmd-line-options"/>)<footnote><para>Note that in + GHCi, and <option>––make</option> mode, the <option>-i</option> + option is used to specify the search path for + <emphasis>source</emphasis> files, whereas in standard + batch-compilation mode the <option>-i</option> option is used to + specify the search path for interface files, see <xref + linkend="search-path"/>.</para> </footnote></para> + + <para>One consequence of the way that GHCi follows dependencies + to find modules to load is that every module must have a source + file. The only exception to the rule is modules that come from + a package, including the <literal>Prelude</literal> and standard + libraries such as <literal>IO</literal> and + <literal>Complex</literal>. If you attempt to load a module for + which GHCi can't find a source file, even if there are object + and interface files for the module, you'll get an error + message.</para> + </sect2> + + <sect2> + <title>Making changes and recompilation</title> + <indexterm><primary><literal>:reload</literal></primary></indexterm> + + <para>If you make some changes to the source code and want GHCi + to recompile the program, give the <literal>:reload</literal> + command. The program will be recompiled as necessary, with GHCi + doing its best to avoid actually recompiling modules if their + external dependencies haven't changed. This is the same + mechanism we use to avoid re-compiling modules in the batch + compilation setting (see <xref linkend="recomp"/>).</para> + </sect2> + </sect1> + + <sect1 id="ghci-compiled"> + <title>Loading compiled code</title> + <indexterm><primary>compiled code</primary><secondary>in GHCi</secondary></indexterm> + + <para>When you load a Haskell source module into GHCi, it is + normally converted to byte-code and run using the interpreter. + However, interpreted code can also run alongside compiled code in + GHCi; indeed, normally when GHCi starts, it loads up a compiled + copy of the <literal>base</literal> package, which contains the + <literal>Prelude</literal>.</para> + + <para>Why should we want to run compiled code? Well, compiled + code is roughly 10x faster than interpreted code, but takes about + 2x longer to produce (perhaps longer if optimisation is on). So + it pays to compile the parts of a program that aren't changing + very often, and use the interpreter for the code being actively + developed.</para> + + <para>When loading up source files with <literal>:load</literal>, + GHCi looks for any corresponding compiled object files, and will + use one in preference to interpreting the source if possible. For + example, suppose we have a 4-module program consisting of modules + A, B, C, and D. Modules B and C both import D only, + and A imports both B & C:</para> +<screen> + A + / \ + B C + \ / + D +</screen> + <para>We can compile D, then load the whole program, like this:</para> +<screen> +Prelude> :! ghc -c D.hs +Prelude> :load A +Skipping D ( D.hs, D.o ) +Compiling C ( C.hs, interpreted ) +Compiling B ( B.hs, interpreted ) +Compiling A ( A.hs, interpreted ) +Ok, modules loaded: A, B, C, D. +*Main> +</screen> + + <para>In the messages from the compiler, we see that it skipped D, + and used the object file <filename>D.o</filename>. The message + <literal>Skipping</literal> <replaceable>module</replaceable> + indicates that compilation for <replaceable>module</replaceable> + isn't necessary, because the source and everything it depends on + is unchanged since the last compilation.</para> + + <para>At any time you can use the command + <literal>:show modules</literal> + to get a list of the modules currently loaded + into GHCi:</para> + +<screen> +*Main> :show modules +D ( D.hs, D.o ) +C ( C.hs, interpreted ) +B ( B.hs, interpreted ) +A ( A.hs, interpreted ) +*Main></screen> + + <para>If we now modify the source of D (or pretend to: using Unix + command <literal>touch</literal> on the source file is handy for + this), the compiler will no longer be able to use the object file, + because it might be out of date:</para> + +<screen> +*Main> :! touch D.hs +*Main> :reload +Compiling D ( D.hs, interpreted ) +Skipping C ( C.hs, interpreted ) +Skipping B ( B.hs, interpreted ) +Skipping A ( A.hs, interpreted ) +Ok, modules loaded: A, B, C, D. +*Main> +</screen> + + <para>Note that module D was compiled, but in this instance + because its source hadn't really changed, its interface remained + the same, and the recompilation checker determined that A, B and C + didn't need to be recompiled.</para> + + <para>So let's try compiling one of the other modules:</para> + +<screen> +*Main> :! ghc -c C.hs +*Main> :load A +Compiling D ( D.hs, interpreted ) +Compiling C ( C.hs, interpreted ) +Compiling B ( B.hs, interpreted ) +Compiling A ( A.hs, interpreted ) +Ok, modules loaded: A, B, C, D. +</screen> + + <para>We didn't get the compiled version of C! What happened? + Well, in GHCi a compiled module may only depend on other compiled + modules, and in this case C depends on D, which doesn't have an + object file, so GHCi also rejected C's object file. Ok, so let's + also compile D:</para> + +<screen> +*Main> :! ghc -c D.hs +*Main> :reload +Ok, modules loaded: A, B, C, D. +</screen> + + <para>Nothing happened! Here's another lesson: newly compiled + modules aren't picked up by <literal>:reload</literal>, only + <literal>:load</literal>:</para> + +<screen> +*Main> :load A +Skipping D ( D.hs, D.o ) +Skipping C ( C.hs, C.o ) +Compiling B ( B.hs, interpreted ) +Compiling A ( A.hs, interpreted ) +Ok, modules loaded: A, B, C, D. +</screen> + + <para>HINT: since GHCi will only use a compiled object file if it + can sure that the compiled version is up-to-date, a good technique + when working on a large program is to occasionally run + <literal>ghc ––make</literal> to compile the whole project (say + before you go for lunch :-), then continue working in the + interpreter. As you modify code, the new modules will be + interpreted, but the rest of the project will remain + compiled.</para> + + </sect1> + + <sect1> + <title>Interactive evaluation at the prompt</title> + + <para>When you type an expression at the prompt, GHCi immediately + evaluates and prints the result: +<screen> +Prelude> reverse "hello" +"olleh" +Prelude> 5+5 +10 +</screen> +</para> + +<sect2><title>I/O actions at the prompt</title> + +<para>GHCi does more than simple expression evaluation at the prompt. +If you type something of type <literal>IO a</literal> for some + <literal>a</literal>, then GHCi <emphasis>executes</emphasis> it + as an IO-computation. +<screen> +Prelude> "hello" +"hello" +Prelude> putStrLn "hello" +hello +</screen> +Furthermore, GHCi will print the result of the I/O action if (and only +if): +<itemizedlist> + <listitem><para>The result type is an instance of <literal>Show</literal>.</para></listitem> + <listitem><para>The result type is not + <literal>()</literal>.</para></listitem> +</itemizedlist> +For example, remembering that <literal>putStrLn :: String -> IO ()</literal>: +<screen> +Prelude> putStrLn "hello" +hello +Prelude> do { putStrLn "hello"; return "yes" } +hello +"yes" +</screen> +</para></sect2> + + <sect2> + <title>Using <literal>do-</literal>notation at the prompt</title> + <indexterm><primary>do-notation</primary><secondary>in GHCi</secondary></indexterm> + <indexterm><primary>statements</primary><secondary>in GHCi</secondary></indexterm> + + <para>GHCi actually accepts <firstterm>statements</firstterm> + rather than just expressions at the prompt. This means you can + bind values and functions to names, and use them in future + expressions or statements.</para> + + <para>The syntax of a statement accepted at the GHCi prompt is + exactly the same as the syntax of a statement in a Haskell + <literal>do</literal> expression. However, there's no monad + overloading here: statements typed at the prompt must be in the + <literal>IO</literal> monad. +<screen> +Prelude> x <- return 42 +42 +Prelude> print x +42 +Prelude> +</screen> + The statement <literal>x <- return 42</literal> means + “execute <literal>return 42</literal> in the + <literal>IO</literal> monad, and bind the result to + <literal>x</literal>”. We can then use + <literal>x</literal> in future statements, for example to print + it as we did above.</para> + + <para>GHCi will print the result of a statement if and only if: + <itemizedlist> + <listitem> + <para>The statement is not a binding, or it is a monadic binding + (<literal>p <- e</literal>) that binds exactly one + variable.</para> + </listitem> + <listitem> + <para>The variable's type is not polymorphic, is not + <literal>()</literal>, and is an instance of + <literal>Show</literal></para> + </listitem> + </itemizedlist> + </para> + + <para>Of course, you can also bind normal non-IO expressions + using the <literal>let</literal>-statement:</para> +<screen> +Prelude> let x = 42 +Prelude> x +42 +Prelude> +</screen> + <para>Another important difference between the two types of binding + is that the monadic bind (<literal>p <- e</literal>) is + <emphasis>strict</emphasis> (it evaluates <literal>e</literal>), + whereas with the <literal>let</literal> form, the expression + isn't evaluated immediately:</para> +<screen> +Prelude> let x = error "help!" +Prelude> print x +*** Exception: help! +Prelude> +</screen> + + <para>Note that <literal>let</literal> bindings do not automatically + print the value bound, unlike monadic bindings.</para> + + <para>Any exceptions raised during the evaluation or execution + of the statement are caught and printed by the GHCi command line + interface (for more information on exceptions, see the module + <literal>Control.Exception</literal> in the libraries + documentation).</para> + + <para>Every new binding shadows any existing bindings of the + same name, including entities that are in scope in the current + module context.</para> + + <para>WARNING: temporary bindings introduced at the prompt only + last until the next <literal>:load</literal> or + <literal>:reload</literal> command, at which time they will be + simply lost. However, they do survive a change of context with + <literal>:module</literal>: the temporary bindings just move to + the new location.</para> + + <para>HINT: To get a list of the bindings currently in scope, use the + <literal>:show bindings</literal> command:</para> + +<screen> +Prelude> :show bindings +x :: Int +Prelude></screen> + + <para>HINT: if you turn on the <literal>+t</literal> option, + GHCi will show the type of each variable bound by a statement. + For example:</para> + <indexterm><primary><literal>+t</literal></primary></indexterm> +<screen> +Prelude> :set +t +Prelude> let (x:xs) = [1..] +x :: Integer +xs :: [Integer] +</screen> + + </sect2> + + <sect2 id="ghci-scope"> + <title>What's really in scope at the prompt?</title> + + <para>When you type an expression at the prompt, what + identifiers and types are in scope? GHCi provides a flexible + way to control exactly how the context for an expression is + constructed. Let's start with the simple cases; when you start + GHCi the prompt looks like this:</para> + +<screen>Prelude></screen> + + <para>Which indicates that everything from the module + <literal>Prelude</literal> is currently in scope. If we now + load a file into GHCi, the prompt will change:</para> + +<screen> +Prelude> :load Main.hs +Compiling Main ( Main.hs, interpreted ) +*Main> +</screen> + + <para>The new prompt is <literal>*Main</literal>, which + indicates that we are typing expressions in the context of the + top-level of the <literal>Main</literal> module. Everything + that is in scope at the top-level in the module + <literal>Main</literal> we just loaded is also in scope at the + prompt (probably including <literal>Prelude</literal>, as long + as <literal>Main</literal> doesn't explicitly hide it).</para> + + <para>The syntax + <literal>*<replaceable>module</replaceable></literal> indicates + that it is the full top-level scope of + <replaceable>module</replaceable> that is contributing to the + scope for expressions typed at the prompt. Without the + <literal>*</literal>, just the exports of the module are + visible.</para> + + <para>We're not limited to a single module: GHCi can combine + scopes from multiple modules, in any mixture of + <literal>*</literal> and non-<literal>*</literal> forms. GHCi + combines the scopes from all of these modules to form the scope + that is in effect at the prompt. For technical reasons, GHCi + can only support the <literal>*</literal>-form for modules which + are interpreted, so compiled modules and package modules can + only contribute their exports to the current scope.</para> + + <para>The scope is manipulated using the + <literal>:module</literal> command. For example, if the current + scope is <literal>Prelude</literal>, then we can bring into + scope the exports from the module <literal>IO</literal> like + so:</para> + +<screen> +Prelude> :module +IO +Prelude,IO> hPutStrLn stdout "hello\n" +hello +Prelude,IO> +</screen> + + <para>(Note: <literal>:module</literal> can be shortened to + <literal>:m</literal>). The full syntax of the + <literal>:module</literal> command is:</para> + +<screen> +:module <optional>+|-</optional> <optional>*</optional><replaceable>mod<subscript>1</subscript></replaceable> ... <optional>*</optional><replaceable>mod<subscript>n</subscript></replaceable> +</screen> + + <para>Using the <literal>+</literal> form of the + <literal>module</literal> commands adds modules to the current + scope, and <literal>-</literal> removes them. Without either + <literal>+</literal> or <literal>-</literal>, the current scope + is replaced by the set of modules specified. Note that if you + use this form and leave out <literal>Prelude</literal>, GHCi + will assume that you really wanted the + <literal>Prelude</literal> and add it in for you (if you don't + want the <literal>Prelude</literal>, then ask to remove it with + <literal>:m -Prelude</literal>).</para> + + <para>The scope is automatically set after a + <literal>:load</literal> command, to the most recently loaded + "target" module, in a <literal>*</literal>-form if possible. + For example, if you say <literal>:load foo.hs bar.hs</literal> + and <filename>bar.hs</filename> contains module + <literal>Bar</literal>, then the scope will be set to + <literal>*Bar</literal> if <literal>Bar</literal> is + interpreted, or if <literal>Bar</literal> is compiled it will be + set to <literal>Prelude,Bar</literal> (GHCi automatically adds + <literal>Prelude</literal> if it isn't present and there aren't + any <literal>*</literal>-form modules).</para> + + <para>With multiple modules in scope, especially multiple + <literal>*</literal>-form modules, it is likely that name + clashes will occur. Haskell specifies that name clashes are + only reported when an ambiguous identifier is used, and GHCi + behaves in the same way for expressions typed at the + prompt.</para> + + <sect3> + <title>Qualified names</title> + + <para>To make life slightly easier, the GHCi prompt also + behaves as if there is an implicit <literal>import + qualified</literal> declaration for every module in every + package, and every module currently loaded into GHCi.</para> + </sect3> + </sect2> + + + <sect2> + <title>The <literal>it</literal> variable</title> + <indexterm><primary><literal>it</literal></primary> + </indexterm> + + <para>Whenever an expression (or a non-binding statement, to be + precise) is typed at the prompt, GHCi implicitly binds its value + to the variable <literal>it</literal>. For example:</para> +<screen> +Prelude> 1+2 +3 +Prelude> it * 2 +6 +</screen> + <para>What actually happens is that GHCi typechecks the + expression, and if it doesn't have an <literal>IO</literal> type, + then it transforms it as follows: an expression + <replaceable>e</replaceable> turns into +<screen> + let it = <replaceable>e</replaceable>; + print it +</screen> + which is then run as an IO-action.</para> + + <para>Hence, the original expression must have a type which is an + instance of the <literal>Show</literal> class, or GHCi will + complain:</para> + +<screen> +Prelude> id +No instance for `Show (a -> a)' +arising from use of `print' +in a `do' expression pattern binding: print it +</screen> + + <para>The error message contains some clues as to the + transformation happening internally.</para> + + <para>If the expression was instead of type <literal>IO a</literal> for + some <literal>a</literal>, then <literal>it</literal> will be + bound to the result of the <literal>IO</literal> computation, + which is of type <literal>a</literal>. eg.:</para> +<screen> +Prelude> Time.getClockTime +Prelude> print it +Wed Mar 14 12:23:13 GMT 2001 +</screen> + + <para>The corresponding translation for an IO-typed + <replaceable>e</replaceable> is +<screen> + it <- <replaceable>e</replaceable> +</screen> + </para> + + <para>Note that <literal>it</literal> is shadowed by the new + value each time you evaluate a new expression, and the old value + of <literal>it</literal> is lost.</para> + + </sect2> + + <sect2> + <title>Type defaulting in GHCi</title> + <indexterm><primary>Type default</primary></indexterm> + <indexterm><primary><literal>Show</literal> class</primary></indexterm> + <para> + Consider this GHCi session: +<programlisting> + ghci> reverse [] +</programlisting> + What should GHCi do? Strictly speaking, the program is ambiguous. <literal>show (reverse [])</literal> + (which is what GHCi computes here) has type <literal>Show a => a</literal> and how that displays depends + on the type <literal>a</literal>. For example: +<programlisting> + ghci> (reverse []) :: String + "" + ghci> (reverse []) :: [Int] + [] +</programlisting> + However, it is tiresome for the user to have to specify the type, so GHCi extends Haskell's type-defaulting + rules (Section 4.3.4 of the Haskell 98 Report (Revised)) as follows. The + standard rules take each group of constraints <literal>(C1 a, C2 a, ..., Cn + a)</literal> for each type variable <literal>a</literal>, and defaults the + type variable if + <itemizedlist> + <listitem><para> The type variable <literal>a</literal> + appears in no other constraints </para></listitem> + <listitem><para> All the classes <literal>Ci</literal> are standard.</para></listitem> + <listitem><para> At least one of the classes <literal>Ci</literal> is + numeric.</para></listitem> + </itemizedlist> + At the GHCi prompt, the second and third rules are relaxed as follows + (differences italicised): + <itemizedlist> + <listitem><para> <emphasis>All</emphasis> of the classes + <literal>Ci</literal> are single-parameter type classes.</para></listitem> + <listitem><para> At least one of the classes <literal>Ci</literal> is + numeric, <emphasis>or is <literal>Show</literal>, + <literal>Eq</literal>, or <literal>Ord</literal></emphasis>.</para></listitem> + </itemizedlist> + </para> + </sect2> + </sect1> + + <sect1 id="ghci-invocation"> + <title>Invoking GHCi</title> + <indexterm><primary>invoking</primary><secondary>GHCi</secondary></indexterm> + <indexterm><primary><option>––interactive</option></primary></indexterm> + + <para>GHCi is invoked with the command <literal>ghci</literal> or + <literal>ghc ––interactive</literal>. One or more modules or + filenames can also be specified on the command line; this + instructs GHCi to load the specified modules or filenames (and all + the modules they depend on), just as if you had said + <literal>:load <replaceable>modules</replaceable></literal> at the + GHCi prompt (see <xref linkend="ghci-commands"/>). For example, to + start GHCi and load the program whose topmost module is in the + file <literal>Main.hs</literal>, we could say:</para> + +<screen> +$ ghci Main.hs +</screen> + + <para>Most of the command-line options accepted by GHC (see <xref + linkend="using-ghc"/>) also make sense in interactive mode. The ones + that don't make sense are mostly obvious; for example, GHCi + doesn't generate interface files, so options related to interface + file generation won't have any effect.</para> + + <sect2> + <title>Packages</title> + <indexterm><primary>packages</primary><secondary>with GHCi</secondary></indexterm> + + <para>Most packages (see <xref linkend="using-packages"/>) are + available without needing to specify any extra flags at all: + they will be automatically loaded the first time they are + needed.</para> + + <para>For non-auto packages, however, you need to request the + package be loaded by using the <literal>-package</literal> flag:</para> + +<screen> +$ ghci -package data + ___ ___ _ + / _ \ /\ /\/ __(_) + / /_\// /_/ / / | | GHC Interactive, version 5.05, for Haskell 98. +/ /_\\/ __ / /___| | http://www.haskell.org/ghc/ +\____/\/ /_/\____/|_| Type :? for help. + +Loading package base ... linking ... done. +Loading package haskell98 ... linking ... done. +Loading package lang ... linking ... done. +Loading package concurrent ... linking ... done. +Loading package readline ... linking ... done. +Loading package unix ... linking ... done. +Loading package posix ... linking ... done. +Loading package util ... linking ... done. +Loading package data ... linking ... done. +Prelude> +</screen> + + <para>The following command works to load new packages into a + running GHCi:</para> + +<screen> +Prelude> :set -package <replaceable>name</replaceable> +</screen> + + <para>But note that doing this will cause all currently loaded + modules to be unloaded, and you'll be dumped back into the + <literal>Prelude</literal>.</para> + </sect2> + + <sect2> + <title>Extra libraries</title> + <indexterm><primary>libraries</primary><secondary>with GHCi</secondary></indexterm> + + <para>Extra libraries may be specified on the command line using + the normal <literal>-l<replaceable>lib</replaceable></literal> + option. (The term <emphasis>library</emphasis> here refers to + libraries of foreign object code; for using libraries of Haskell + source code, see <xref linkend="ghci-modules-filenames"/>.) For + example, to load the “m” library:</para> + +<screen> +$ ghci -lm +</screen> + + <para>On systems with <literal>.so</literal>-style shared + libraries, the actual library loaded will the + <filename>lib<replaceable>lib</replaceable>.so</filename>. GHCi + searches the following places for libraries, in this order:</para> + + <itemizedlist> + <listitem> + <para>Paths specified using the + <literal>-L<replaceable>path</replaceable></literal> + command-line option,</para> + </listitem> + <listitem> + <para>the standard library search path for your system, + which on some systems may be overridden by setting the + <literal>LD_LIBRARY_PATH</literal> environment + variable.</para> + </listitem> + </itemizedlist> + + <para>On systems with <literal>.dll</literal>-style shared + libraries, the actual library loaded will be + <filename><replaceable>lib</replaceable>.dll</filename>. Again, + GHCi will signal an error if it can't find the library.</para> + + <para>GHCi can also load plain object files + (<literal>.o</literal> or <literal>.obj</literal> depending on + your platform) from the command-line. Just add the name the + object file to the command line.</para> + + <para>Ordering of <option>-l</option> options matters: a library + should be mentioned <emphasis>before</emphasis> the libraries it + depends on (see <xref linkend="options-linker"/>).</para> + </sect2> + + </sect1> + + <sect1 id="ghci-commands"> + <title>GHCi commands</title> + + <para>GHCi commands all begin with + ‘<literal>:</literal>’ and consist of a single command + name followed by zero or more parameters. The command name may be + abbreviated, as long as the abbreviation is not ambiguous. All of + the builtin commands, with the exception of + <literal>:unset</literal> and <literal>:undef</literal>, may be + abbreviated to a single letter.</para> + + <variablelist> + <varlistentry> + <term> + <literal>:add</literal> <replaceable>module</replaceable> ... + <indexterm><primary><literal>:add</literal></primary></indexterm> + </term> + <listitem> + <para>Add <replaceable>module</replaceable>(s) to the + current <firstterm>target set</firstterm>, and perform a + reload.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <literal>:browse</literal> <optional><literal>*</literal></optional><replaceable>module</replaceable> ... + <indexterm><primary><literal>:browse</literal></primary></indexterm> + </term> + <listitem> + <para>Displays the identifiers defined by the module + <replaceable>module</replaceable>, which must be either + loaded into GHCi or be a member of a package. If the + <literal>*</literal> symbol is placed before the module + name, then <emphasis>all</emphasis> the identifiers defined + in <replaceable>module</replaceable> are shown; otherwise + the list is limited to the exports of + <replaceable>module</replaceable>. The + <literal>*</literal>-form is only available for modules + which are interpreted; for compiled modules (including + modules from packages) only the non-<literal>*</literal> + form of <literal>:browse</literal> is available.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <literal>:cd</literal> <replaceable>dir</replaceable> + <indexterm><primary><literal>:cd</literal></primary></indexterm> + </term> + <listitem> + <para>Changes the current working directory to + <replaceable>dir</replaceable>. A + ‘<literal>˜</literal>’ symbol at the + beginning of <replaceable>dir</replaceable> will be replaced + by the contents of the environment variable + <literal>HOME</literal>.</para> + + <para>NOTE: changing directories causes all currently loaded + modules to be unloaded. This is because the search path is + usually expressed using relative directories, and changing + the search path in the middle of a session is not + supported.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <literal>:def</literal> <replaceable>name</replaceable> <replaceable>expr</replaceable> + <indexterm><primary><literal>:def</literal></primary></indexterm> + </term> + <listitem> + <para>The command <literal>:def</literal> + <replaceable>name</replaceable> + <replaceable>expr</replaceable> defines a new GHCi command + <literal>:<replaceable>name</replaceable></literal>, + implemented by the Haskell expression + <replaceable>expr</replaceable>, which must have type + <literal>String -> IO String</literal>. When + <literal>:<replaceable>name</replaceable> + <replaceable>args</replaceable></literal> is typed at the + prompt, GHCi will run the expression + <literal>(<replaceable>name</replaceable> + <replaceable>args</replaceable>)</literal>, take the + resulting <literal>String</literal>, and feed it back into + GHCi as a new sequence of commands. Separate commands in + the result must be separated by + ‘<literal>\n</literal>’.</para> + + <para>That's all a little confusing, so here's a few + examples. To start with, here's a new GHCi command which + doesn't take any arguments or produce any results, it just + outputs the current date & time:</para> + +<screen> +Prelude> let date _ = Time.getClockTime >>= print >> return "" +Prelude> :def date date +Prelude> :date +Fri Mar 23 15:16:40 GMT 2001 +</screen> + + <para>Here's an example of a command that takes an argument. + It's a re-implementation of <literal>:cd</literal>:</para> + +<screen> +Prelude> let mycd d = Directory.setCurrentDirectory d >> return "" +Prelude> :def mycd mycd +Prelude> :mycd .. +</screen> + + <para>Or I could define a simple way to invoke + “<literal>ghc ––make Main</literal>” in the + current directory:</para> + +<screen> +Prelude> :def make (\_ -> return ":! ghc ––make Main") +</screen> + + <para>We can define a command that reads GHCi input from a + file. This might be useful for creating a set of bindings + that we want to repeatedly load into the GHCi session:</para> + +<screen> +Prelude> :def . readFile +Prelude> :. cmds.ghci +</screen> + + <para>Notice that we named the command + <literal>:.</literal>, by analogy with the + ‘<literal>.</literal>’ Unix shell command that + does the same thing.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <literal>:help</literal> + <indexterm><primary><literal>:help</literal></primary></indexterm> + </term> + <term> + <literal>:?</literal> + <indexterm><primary><literal>:?</literal></primary></indexterm> + </term> + <listitem> + <para>Displays a list of the available commands.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <literal>:info</literal> <replaceable>name</replaceable> ... + <indexterm><primary><literal>:info</literal></primary></indexterm> + </term> + <listitem> + <para>Displays information about the given name(s). For + example, if <replaceable>name</replaceable> is a class, then + the class methods and their types will be printed; if + <replaceable>name</replaceable> is a type constructor, then + its definition will be printed; if + <replaceable>name</replaceable> is a function, then its type + will be printed. If <replaceable>name</replaceable> has + been loaded from a source file, then GHCi will also display + the location of its definition in the source.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <literal>:load</literal> <replaceable>module</replaceable> ... + <indexterm><primary><literal>:load</literal></primary></indexterm> + </term> + <listitem> + <para>Recursively loads the specified + <replaceable>module</replaceable>s, and all the modules they + depend on. Here, each <replaceable>module</replaceable> + must be a module name or filename, but may not be the name + of a module in a package.</para> + + <para>All previously loaded modules, except package modules, + are forgotten. The new set of modules is known as the + <firstterm>target set</firstterm>. Note that + <literal>:load</literal> can be used without any arguments + to unload all the currently loaded modules and + bindings.</para> + + <para>After a <literal>:load</literal> command, the current + context is set to:</para> + + <itemizedlist> + <listitem> + <para><replaceable>module</replaceable>, if it was loaded + successfully, or</para> + </listitem> + <listitem> + <para>the most recently successfully loaded module, if + any other modules were loaded as a result of the current + <literal>:load</literal>, or</para> + </listitem> + <listitem> + <para><literal>Prelude</literal> otherwise.</para> + </listitem> + </itemizedlist> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <literal>:module <optional>+|-</optional> <optional>*</optional><replaceable>mod<subscript>1</subscript></replaceable> ... <optional>*</optional><replaceable>mod<subscript>n</subscript></replaceable></literal> + <indexterm><primary><literal>:module</literal></primary></indexterm> + </term> + <listitem> + <para>Sets or modifies the current context for statements + typed at the prompt. See <xref linkend="ghci-scope"/> for + more details.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <literal>:quit</literal> + <indexterm><primary><literal>:quit</literal></primary></indexterm> + </term> + <listitem> + <para>Quits GHCi. You can also quit by typing a control-D + at the prompt.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <literal>:reload</literal> + <indexterm><primary><literal>:reload</literal></primary></indexterm> + </term> + <listitem> + <para>Attempts to reload the current target set (see + <literal>:load</literal>) if any of the modules in the set, + or any dependent module, has changed. Note that this may + entail loading new modules, or dropping modules which are no + longer indirectly required by the target.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <literal>:set</literal> <optional><replaceable>option</replaceable>...</optional> + <indexterm><primary><literal>:set</literal></primary></indexterm> + </term> + <listitem> + <para>Sets various options. See <xref linkend="ghci-set"/> + for a list of available options. The + <literal>:set</literal> command by itself shows which + options are currently set.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <literal>:set</literal> <literal>args</literal> <replaceable>arg</replaceable> ... + <indexterm><primary><literal>:set args</literal></primary></indexterm> + </term> + <listitem> + <para>Sets the list of arguments which are returned when the + program calls <literal>System.getArgs</literal><indexterm><primary>getArgs</primary> + </indexterm>.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <literal>:set</literal> <literal>prog</literal> <replaceable>prog</replaceable> + <indexterm><primary><literal>:set prog</literal></primary></indexterm> + </term> + <listitem> + <para>Sets the string to be returned when the program calls + <literal>System.getProgName</literal><indexterm><primary>getProgName</primary> + </indexterm>.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <literal>:set</literal> <literal>prompt</literal> <replaceable>prompt</replaceable> + </term> + <listitem> + <para>Sets the string to be used as the prompt in GHCi. + Inside <replaceable>prompt</replaceable>, the sequence + <literal>%s</literal> is replaced by the names of the + modules currently in scope, and <literal>%%</literal> is + replaced by <literal>%</literal>.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <literal>:show bindings</literal> + <indexterm><primary><literal>:show bindings</literal></primary></indexterm> + </term> + <listitem> + <para>Show the bindings made at the prompt and their + types.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <literal>:show modules</literal> + <indexterm><primary><literal>:show modules</literal></primary></indexterm> + </term> + <listitem> + <para>Show the list of modules currently load.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <literal>:ctags</literal> <optional><replaceable>filename</replaceable></optional> + <literal>:etags</literal> <optional><replaceable>filename</replaceable></optional> + <indexterm><primary><literal>:etags</literal></primary> + </indexterm> + <indexterm><primary><literal>:etags</literal></primary> + </indexterm> + </term> + <listitem> + <para>Generates a “tags” file for Vi-style editors + (<literal>:ctags</literal>) or Emacs-style editors (<literal>etags</literal>). If + no filename is specified, the defaulit <filename>tags</filename> or + <filename>TAGS</filename> is + used, respectively. Tags for all the functions, constructors and + types in the currently loaded modules are created. All modules must + be interpreted for these commands to work.</para> + <para>See also <xref linkend="hasktags" />.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <literal>:type</literal> <replaceable>expression</replaceable> + <indexterm><primary><literal>:type</literal></primary></indexterm> + </term> + <listitem> + <para>Infers and prints the type of + <replaceable>expression</replaceable>, including explicit + forall quantifiers for polymorphic types. The monomorphism + restriction is <emphasis>not</emphasis> applied to the + expression during type inference.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <literal>:kind</literal> <replaceable>type</replaceable> + <indexterm><primary><literal>:kind</literal></primary></indexterm> + </term> + <listitem> + <para>Infers and prints the kind of + <replaceable>type</replaceable>. The latter can be an arbitrary + type expression, including a partial application of a type constructor, + such as <literal>Either Int</literal>.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <literal>:undef</literal> <replaceable>name</replaceable> + <indexterm><primary><literal>:undef</literal></primary></indexterm> + </term> + <listitem> + <para>Undefines the user-defined command + <replaceable>name</replaceable> (see <literal>:def</literal> + above).</para> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <literal>:unset</literal> <replaceable>option</replaceable>... + <indexterm><primary><literal>:unset</literal></primary></indexterm> + </term> + <listitem> + <para>Unsets certain options. See <xref linkend="ghci-set"/> + for a list of available options.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <literal>:!</literal> <replaceable>command</replaceable>... + <indexterm><primary><literal>:!</literal></primary></indexterm> + <indexterm><primary>shell commands</primary><secondary>in GHCi</secondary></indexterm> + </term> + <listitem> + <para>Executes the shell command + <replaceable>command</replaceable>.</para> + </listitem> + </varlistentry> + + </variablelist> + </sect1> + + <sect1 id="ghci-set"> + <title>The <literal>:set</literal> command</title> + <indexterm><primary><literal>:set</literal></primary></indexterm> + + <para>The <literal>:set</literal> command sets two types of + options: GHCi options, which begin with + ‘<literal>+</literal>” and “command-line” + options, which begin with ‘-’. </para> + + <para>NOTE: at the moment, the <literal>:set</literal> command + doesn't support any kind of quoting in its arguments: quotes will + not be removed and cannot be used to group words together. For + example, <literal>:set -DFOO='BAR BAZ'</literal> will not do what + you expect.</para> + + <sect2> + <title>GHCi options</title> + <indexterm><primary>options</primary><secondary>GHCi</secondary> + </indexterm> + + <para>GHCi options may be set using <literal>:set</literal> and + unset using <literal>:unset</literal>.</para> + + <para>The available GHCi options are:</para> + + <variablelist> + <varlistentry> + <term> + <literal>+r</literal> + <indexterm><primary><literal>+r</literal></primary></indexterm> + <indexterm><primary>CAFs</primary><secondary>in GHCi</secondary></indexterm> + <indexterm><primary>Constant Applicative Form</primary><see>CAFs</see></indexterm> + </term> + <listitem> + <para>Normally, any evaluation of top-level expressions + (otherwise known as CAFs or Constant Applicative Forms) in + loaded modules is retained between evaluations. Turning + on <literal>+r</literal> causes all evaluation of + top-level expressions to be discarded after each + evaluation (they are still retained + <emphasis>during</emphasis> a single evaluation).</para> + + <para>This option may help if the evaluated top-level + expressions are consuming large amounts of space, or if + you need repeatable performance measurements.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <literal>+s</literal> + <indexterm><primary><literal>+s</literal></primary></indexterm> + </term> + <listitem> + <para>Display some stats after evaluating each expression, + including the elapsed time and number of bytes allocated. + NOTE: the allocation figure is only accurate to the size + of the storage manager's allocation area, because it is + calculated at every GC. Hence, you might see values of + zero if no GC has occurred.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <literal>+t</literal> + <indexterm><primary><literal>+t</literal></primary></indexterm> + </term> + <listitem> + <para>Display the type of each variable bound after a + statement is entered at the prompt. If the statement is a + single expression, then the only variable binding will be + for the variable + ‘<literal>it</literal>’.</para> + </listitem> + </varlistentry> + </variablelist> + </sect2> + + <sect2 id="ghci-cmd-line-options"> + <title>Setting GHC command-line options in GHCi</title> + + <para>Normal GHC command-line options may also be set using + <literal>:set</literal>. For example, to turn on + <option>-fglasgow-exts</option>, you would say:</para> + +<screen> +Prelude> :set -fglasgow-exts +</screen> + + <para>Any GHC command-line option that is designated as + <firstterm>dynamic</firstterm> (see the table in <xref + linkend="flag-reference"/>), may be set using + <literal>:set</literal>. To unset an option, you can set the + reverse option:</para> + <indexterm><primary>dynamic</primary><secondary>options</secondary></indexterm> + +<screen> +Prelude> :set -fno-glasgow-exts +</screen> + + <para><xref linkend="flag-reference"/> lists the reverse for each + option where applicable.</para> + + <para>Certain static options (<option>-package</option>, + <option>-I</option>, <option>-i</option>, and + <option>-l</option> in particular) will also work, but some may + not take effect until the next reload.</para> + <indexterm><primary>static</primary><secondary>options</secondary></indexterm> + </sect2> + </sect1> + + <sect1 id="ghci-dot-files"> + <title>The <filename>.ghci</filename> file</title> + <indexterm><primary><filename>.ghci</filename></primary><secondary>file</secondary> + </indexterm> + <indexterm><primary>startup</primary><secondary>files, GHCi</secondary> + </indexterm> + + <para>When it starts, GHCi always reads and executes commands from + <filename>$HOME/.ghci</filename>, followed by + <filename>./.ghci</filename>.</para> + + <para>The <filename>.ghci</filename> in your home directory is + most useful for turning on favourite options (eg. <literal>:set + +s</literal>), and defining useful macros. Placing a + <filename>.ghci</filename> file in a directory with a Haskell + project is a useful way to set certain project-wide options so you + don't have to type them everytime you start GHCi: eg. if your + project uses GHC extensions and CPP, and has source files in three + subdirectories A B and C, you might put the following lines in + <filename>.ghci</filename>:</para> + +<screen> +:set -fglasgow-exts -cpp +:set -iA:B:C +</screen> + + <para>(Note that strictly speaking the <option>-i</option> flag is + a static one, but in fact it works to set it using + <literal>:set</literal> like this. The changes won't take effect + until the next <literal>:load</literal>, though.)</para> + + <para>Two command-line options control whether the + <filename>.ghci</filename> files are read:</para> + + <variablelist> + <varlistentry> + <term> + <option>-ignore-dot-ghci</option> + <indexterm><primary><option>-ignore-dot-ghci</option></primary></indexterm> + </term> + <listitem> + <para>Don't read either <filename>./.ghci</filename> or + <filename>$HOME/.ghci</filename> when starting up.</para> + </listitem> + </varlistentry> + <varlistentry> + <term> + <option>-read-dot-ghci</option> + <indexterm><primary><option>-read-dot-ghci</option></primary></indexterm> + </term> + <listitem> + <para>Read <filename>.ghci</filename> and + <filename>$HOME/.ghci</filename>. This is normally the + default, but the <option>-read-dot-ghci</option> option may + be used to override a previous + <option>-ignore-dot-ghci</option> option.</para> + </listitem> + </varlistentry> + </variablelist> + + </sect1> + + <sect1> + <title>FAQ and Things To Watch Out For</title> + + <variablelist> + <varlistentry> + <term>The interpreter can't load modules with foreign export + declarations!</term> + <listitem> + <para>Unfortunately not. We haven't implemented it yet. + Please compile any offending modules by hand before loading + them into GHCi.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <literal>-O</literal> doesn't work with GHCi! + <indexterm><primary><option>-O</option></primary></indexterm> + </term> + <listitem> + <para>For technical reasons, the bytecode compiler doesn't + interact well with one of the optimisation passes, so we + have disabled optimisation when using the interpreter. This + isn't a great loss: you'll get a much bigger win by + compiling the bits of your code that need to go fast, rather + than interpreting them with optimisation turned on.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term>Unboxed tuples don't work with GHCi</term> + <listitem> + <para>That's right. You can always compile a module that + uses unboxed tuples and load it into GHCi, however. + (Incidentally the previous point, namely that + <literal>-O</literal> is incompatible with GHCi, is because + the bytecode compiler can't deal with unboxed + tuples).</para> + </listitem> + </varlistentry> + + <varlistentry> + <term>Concurrent threads don't carry on running when GHCi is + waiting for input.</term> + <listitem> + <para>No, they don't. This is because the Haskell binding + to the GNU readline library doesn't support reading from the + terminal in a non-blocking way, which is required to work + properly with GHC's concurrency model.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term>After using <literal>getContents</literal>, I can't use + <literal>stdin</literal> again until I do + <literal>:load</literal> or <literal>:reload</literal>.</term> + + <listitem> + <para>This is the defined behaviour of + <literal>getContents</literal>: it puts the stdin Handle in + a state known as <firstterm>semi-closed</firstterm>, wherein + any further I/O operations on it are forbidden. Because I/O + state is retained between computations, the semi-closed + state persists until the next <literal>:load</literal> or + <literal>:reload</literal> command.</para> + + <para>You can make <literal>stdin</literal> reset itself + after every evaluation by giving GHCi the command + <literal>:set +r</literal>. This works because + <literal>stdin</literal> is just a top-level expression that + can be reverted to its unevaluated state in the same way as + any other top-level expression (CAF).</para> + </listitem> + </varlistentry> + + </variablelist> + </sect1> + +</chapter> + +<!-- Emacs stuff: + ;;; Local Variables: *** + ;;; mode: xml *** + ;;; sgml-parent-document: ("users_guide.xml" "book" "chapter") *** + ;;; End: *** + --> diff --git a/docs/users_guide/glasgow_exts.xml b/docs/users_guide/glasgow_exts.xml new file mode 100644 index 0000000000..beaaad616a --- /dev/null +++ b/docs/users_guide/glasgow_exts.xml @@ -0,0 +1,6264 @@ +<?xml version="1.0" encoding="iso-8859-1"?> +<para> +<indexterm><primary>language, GHC</primary></indexterm> +<indexterm><primary>extensions, GHC</primary></indexterm> +As with all known Haskell systems, GHC implements some extensions to +the language. They are all enabled by options; by default GHC +understands only plain Haskell 98. +</para> + +<para> +Some of the Glasgow extensions serve to give you access to the +underlying facilities with which we implement Haskell. Thus, you can +get at the Raw Iron, if you are willing to write some non-portable +code at a more primitive level. You need not be “stuck” +on performance because of the implementation costs of Haskell's +“high-level” features—you can always code +“under” them. In an extreme case, you can write all your +time-critical code in C, and then just glue it together with Haskell! +</para> + +<para> +Before you get too carried away working at the lowest level (e.g., +sloshing <literal>MutableByteArray#</literal>s around your +program), you may wish to check if there are libraries that provide a +“Haskellised veneer” over the features you want. The +separate <ulink url="../libraries/index.html">libraries +documentation</ulink> describes all the libraries that come with GHC. +</para> + +<!-- LANGUAGE OPTIONS --> + <sect1 id="options-language"> + <title>Language options</title> + + <indexterm><primary>language</primary><secondary>option</secondary> + </indexterm> + <indexterm><primary>options</primary><secondary>language</secondary> + </indexterm> + <indexterm><primary>extensions</primary><secondary>options controlling</secondary> + </indexterm> + + <para>These flags control what variation of the language are + permitted. Leaving out all of them gives you standard Haskell + 98.</para> + + <para>NB. turning on an option that enables special syntax + <emphasis>might</emphasis> cause working Haskell 98 code to fail + to compile, perhaps because it uses a variable name which has + become a reserved word. So, together with each option below, we + list the special syntax which is enabled by this option. We use + notation and nonterminal names from the Haskell 98 lexical syntax + (see the Haskell 98 Report). There are two classes of special + syntax:</para> + + <itemizedlist> + <listitem> + <para>New reserved words and symbols: character sequences + which are no longer available for use as identifiers in the + program.</para> + </listitem> + <listitem> + <para>Other special syntax: sequences of characters that have + a different meaning when this particular option is turned + on.</para> + </listitem> + </itemizedlist> + + <para>We are only listing syntax changes here that might affect + existing working programs (i.e. "stolen" syntax). Many of these + extensions will also enable new context-free syntax, but in all + cases programs written to use the new syntax would not be + compilable without the option enabled.</para> + + <variablelist> + + <varlistentry> + <term> + <option>-fglasgow-exts</option>: + <indexterm><primary><option>-fglasgow-exts</option></primary></indexterm> + </term> + <listitem> + <para>This simultaneously enables all of the extensions to + Haskell 98 described in <xref + linkend="ghc-language-features"/>, except where otherwise + noted. </para> + + <para>New reserved words: <literal>forall</literal> (only in + types), <literal>mdo</literal>.</para> + + <para>Other syntax stolen: + <replaceable>varid</replaceable>{<literal>#</literal>}, + <replaceable>char</replaceable><literal>#</literal>, + <replaceable>string</replaceable><literal>#</literal>, + <replaceable>integer</replaceable><literal>#</literal>, + <replaceable>float</replaceable><literal>#</literal>, + <replaceable>float</replaceable><literal>##</literal>, + <literal>(#</literal>, <literal>#)</literal>, + <literal>|)</literal>, <literal>{|</literal>.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <option>-ffi</option> and <option>-fffi</option>: + <indexterm><primary><option>-ffi</option></primary></indexterm> + <indexterm><primary><option>-fffi</option></primary></indexterm> + </term> + <listitem> + <para>This option enables the language extension defined in the + Haskell 98 Foreign Function Interface Addendum plus deprecated + syntax of previous versions of the FFI for backwards + compatibility.</para> + + <para>New reserved words: <literal>foreign</literal>.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <option>-fno-monomorphism-restriction</option>: + <indexterm><primary><option>-fno-monomorphism-restriction</option></primary></indexterm> + </term> + <listitem> + <para> Switch off the Haskell 98 monomorphism restriction. + Independent of the <option>-fglasgow-exts</option> + flag. </para> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <option>-fallow-overlapping-instances</option> + <indexterm><primary><option>-fallow-overlapping-instances</option></primary></indexterm> + </term> + <term> + <option>-fallow-undecidable-instances</option> + <indexterm><primary><option>-fallow-undecidable-instances</option></primary></indexterm> + </term> + <term> + <option>-fallow-incoherent-instances</option> + <indexterm><primary><option>-fallow-incoherent-instances</option></primary></indexterm> + </term> + <term> + <option>-fcontext-stack</option> + <indexterm><primary><option>-fcontext-stack</option></primary></indexterm> + </term> + <listitem> + <para> See <xref linkend="instance-decls"/>. Only relevant + if you also use <option>-fglasgow-exts</option>.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <option>-finline-phase</option> + <indexterm><primary><option>-finline-phase</option></primary></indexterm> + </term> + <listitem> + <para>See <xref linkend="rewrite-rules"/>. Only relevant if + you also use <option>-fglasgow-exts</option>.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <option>-farrows</option> + <indexterm><primary><option>-farrows</option></primary></indexterm> + </term> + <listitem> + <para>See <xref linkend="arrow-notation"/>. Independent of + <option>-fglasgow-exts</option>.</para> + + <para>New reserved words/symbols: <literal>rec</literal>, + <literal>proc</literal>, <literal>-<</literal>, + <literal>>-</literal>, <literal>-<<</literal>, + <literal>>>-</literal>.</para> + + <para>Other syntax stolen: <literal>(|</literal>, + <literal>|)</literal>.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <option>-fgenerics</option> + <indexterm><primary><option>-fgenerics</option></primary></indexterm> + </term> + <listitem> + <para>See <xref linkend="generic-classes"/>. Independent of + <option>-fglasgow-exts</option>.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-fno-implicit-prelude</option></term> + <listitem> + <para><indexterm><primary>-fno-implicit-prelude + option</primary></indexterm> GHC normally imports + <filename>Prelude.hi</filename> files for you. If you'd + rather it didn't, then give it a + <option>-fno-implicit-prelude</option> option. The idea is + that you can then import a Prelude of your own. (But don't + call it <literal>Prelude</literal>; the Haskell module + namespace is flat, and you must not conflict with any + Prelude module.)</para> + + <para>Even though you have not imported the Prelude, most of + the built-in syntax still refers to the built-in Haskell + Prelude types and values, as specified by the Haskell + Report. For example, the type <literal>[Int]</literal> + still means <literal>Prelude.[] Int</literal>; tuples + continue to refer to the standard Prelude tuples; the + translation for list comprehensions continues to use + <literal>Prelude.map</literal> etc.</para> + + <para>However, <option>-fno-implicit-prelude</option> does + change the handling of certain built-in syntax: see <xref + linkend="rebindable-syntax"/>.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-fimplicit-params</option></term> + <listitem> + <para>Enables implicit parameters (see <xref + linkend="implicit-parameters"/>). Currently also implied by + <option>-fglasgow-exts</option>.</para> + + <para>Syntax stolen: + <literal>?<replaceable>varid</replaceable></literal>, + <literal>%<replaceable>varid</replaceable></literal>.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-fscoped-type-variables</option></term> + <listitem> + <para>Enables lexically-scoped type variables (see <xref + linkend="scoped-type-variables"/>). Implied by + <option>-fglasgow-exts</option>.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-fth</option></term> + <listitem> + <para>Enables Template Haskell (see <xref + linkend="template-haskell"/>). Currently also implied by + <option>-fglasgow-exts</option>.</para> + + <para>Syntax stolen: <literal>[|</literal>, + <literal>[e|</literal>, <literal>[p|</literal>, + <literal>[d|</literal>, <literal>[t|</literal>, + <literal>$(</literal>, + <literal>$<replaceable>varid</replaceable></literal>.</para> + </listitem> + </varlistentry> + + </variablelist> + </sect1> + +<!-- UNBOXED TYPES AND PRIMITIVE OPERATIONS --> +<!-- included from primitives.sgml --> +<!-- &primitives; --> +<sect1 id="primitives"> + <title>Unboxed types and primitive operations</title> + +<para>GHC is built on a raft of primitive data types and operations. +While you really can use this stuff to write fast code, + we generally find it a lot less painful, and more satisfying in the + long run, to use higher-level language features and libraries. With + any luck, the code you write will be optimised to the efficient + unboxed version in any case. And if it isn't, we'd like to know + about it.</para> + +<para>We do not currently have good, up-to-date documentation about the +primitives, perhaps because they are mainly intended for internal use. +There used to be a long section about them here in the User Guide, but it +became out of date, and wrong information is worse than none.</para> + +<para>The Real Truth about what primitive types there are, and what operations +work over those types, is held in the file +<filename>fptools/ghc/compiler/prelude/primops.txt.pp</filename>. +This file is used directly to generate GHC's primitive-operation definitions, so +it is always correct! It is also intended for processing into text.</para> + +<para> Indeed, +the result of such processing is part of the description of the + <ulink + url="http://haskell.cs.yale.edu/ghc/docs/papers/core.ps.gz">External + Core language</ulink>. +So that document is a good place to look for a type-set version. +We would be very happy if someone wanted to volunteer to produce an SGML +back end to the program that processes <filename>primops.txt</filename> so that +we could include the results here in the User Guide.</para> + +<para>What follows here is a brief summary of some main points.</para> + +<sect2 id="glasgow-unboxed"> +<title>Unboxed types +</title> + +<para> +<indexterm><primary>Unboxed types (Glasgow extension)</primary></indexterm> +</para> + +<para>Most types in GHC are <firstterm>boxed</firstterm>, which means +that values of that type are represented by a pointer to a heap +object. The representation of a Haskell <literal>Int</literal>, for +example, is a two-word heap object. An <firstterm>unboxed</firstterm> +type, however, is represented by the value itself, no pointers or heap +allocation are involved. +</para> + +<para> +Unboxed types correspond to the “raw machine” types you +would use in C: <literal>Int#</literal> (long int), +<literal>Double#</literal> (double), <literal>Addr#</literal> +(void *), etc. The <emphasis>primitive operations</emphasis> +(PrimOps) on these types are what you might expect; e.g., +<literal>(+#)</literal> is addition on +<literal>Int#</literal>s, and is the machine-addition that we all +know and love—usually one instruction. +</para> + +<para> +Primitive (unboxed) types cannot be defined in Haskell, and are +therefore built into the language and compiler. Primitive types are +always unlifted; that is, a value of a primitive type cannot be +bottom. We use the convention that primitive types, values, and +operations have a <literal>#</literal> suffix. +</para> + +<para> +Primitive values are often represented by a simple bit-pattern, such +as <literal>Int#</literal>, <literal>Float#</literal>, +<literal>Double#</literal>. But this is not necessarily the case: +a primitive value might be represented by a pointer to a +heap-allocated object. Examples include +<literal>Array#</literal>, the type of primitive arrays. A +primitive array is heap-allocated because it is too big a value to fit +in a register, and would be too expensive to copy around; in a sense, +it is accidental that it is represented by a pointer. If a pointer +represents a primitive value, then it really does point to that value: +no unevaluated thunks, no indirections…nothing can be at the +other end of the pointer than the primitive value. +A numerically-intensive program using unboxed types can +go a <emphasis>lot</emphasis> faster than its “standard” +counterpart—we saw a threefold speedup on one example. +</para> + +<para> +There are some restrictions on the use of primitive types: +<itemizedlist> +<listitem><para>The main restriction +is that you can't pass a primitive value to a polymorphic +function or store one in a polymorphic data type. This rules out +things like <literal>[Int#]</literal> (i.e. lists of primitive +integers). The reason for this restriction is that polymorphic +arguments and constructor fields are assumed to be pointers: if an +unboxed integer is stored in one of these, the garbage collector would +attempt to follow it, leading to unpredictable space leaks. Or a +<function>seq</function> operation on the polymorphic component may +attempt to dereference the pointer, with disastrous results. Even +worse, the unboxed value might be larger than a pointer +(<literal>Double#</literal> for instance). +</para> +</listitem> +<listitem><para> You cannot bind a variable with an unboxed type +in a <emphasis>top-level</emphasis> binding. +</para></listitem> +<listitem><para> You cannot bind a variable with an unboxed type +in a <emphasis>recursive</emphasis> binding. +</para></listitem> +<listitem><para> You may bind unboxed variables in a (non-recursive, +non-top-level) pattern binding, but any such variable causes the entire +pattern-match +to become strict. For example: +<programlisting> + data Foo = Foo Int Int# + + f x = let (Foo a b, w) = ..rhs.. in ..body.. +</programlisting> +Since <literal>b</literal> has type <literal>Int#</literal>, the entire pattern +match +is strict, and the program behaves as if you had written +<programlisting> + data Foo = Foo Int Int# + + f x = case ..rhs.. of { (Foo a b, w) -> ..body.. } +</programlisting> +</para> +</listitem> +</itemizedlist> +</para> + +</sect2> + +<sect2 id="unboxed-tuples"> +<title>Unboxed Tuples +</title> + +<para> +Unboxed tuples aren't really exported by <literal>GHC.Exts</literal>, +they're available by default with <option>-fglasgow-exts</option>. An +unboxed tuple looks like this: +</para> + +<para> + +<programlisting> +(# e_1, ..., e_n #) +</programlisting> + +</para> + +<para> +where <literal>e_1..e_n</literal> are expressions of any +type (primitive or non-primitive). The type of an unboxed tuple looks +the same. +</para> + +<para> +Unboxed tuples are used for functions that need to return multiple +values, but they avoid the heap allocation normally associated with +using fully-fledged tuples. When an unboxed tuple is returned, the +components are put directly into registers or on the stack; the +unboxed tuple itself does not have a composite representation. Many +of the primitive operations listed in <literal>primops.txt.pp</literal> return unboxed +tuples. +In particular, the <literal>IO</literal> and <literal>ST</literal> monads use unboxed +tuples to avoid unnecessary allocation during sequences of operations. +</para> + +<para> +There are some pretty stringent restrictions on the use of unboxed tuples: +<itemizedlist> +<listitem> + +<para> +Values of unboxed tuple types are subject to the same restrictions as +other unboxed types; i.e. they may not be stored in polymorphic data +structures or passed to polymorphic functions. + +</para> +</listitem> +<listitem> + +<para> +No variable can have an unboxed tuple type, nor may a constructor or function +argument have an unboxed tuple type. The following are all illegal: + + +<programlisting> + data Foo = Foo (# Int, Int #) + + f :: (# Int, Int #) -> (# Int, Int #) + f x = x + + g :: (# Int, Int #) -> Int + g (# a,b #) = a + + h x = let y = (# x,x #) in ... +</programlisting> +</para> +</listitem> +</itemizedlist> +</para> +<para> +The typical use of unboxed tuples is simply to return multiple values, +binding those multiple results with a <literal>case</literal> expression, thus: +<programlisting> + f x y = (# x+1, y-1 #) + g x = case f x x of { (# a, b #) -> a + b } +</programlisting> +You can have an unboxed tuple in a pattern binding, thus +<programlisting> + f x = let (# p,q #) = h x in ..body.. +</programlisting> +If the types of <literal>p</literal> and <literal>q</literal> are not unboxed, +the resulting binding is lazy like any other Haskell pattern binding. The +above example desugars like this: +<programlisting> + f x = let t = case h x o f{ (# p,q #) -> (p,q) + p = fst t + q = snd t + in ..body.. +</programlisting> +Indeed, the bindings can even be recursive. +</para> + +</sect2> +</sect1> + + +<!-- ====================== SYNTACTIC EXTENSIONS ======================= --> + +<sect1 id="syntax-extns"> +<title>Syntactic extensions</title> + + <!-- ====================== HIERARCHICAL MODULES ======================= --> + + <sect2 id="hierarchical-modules"> + <title>Hierarchical Modules</title> + + <para>GHC supports a small extension to the syntax of module + names: a module name is allowed to contain a dot + <literal>‘.’</literal>. This is also known as the + “hierarchical module namespace” extension, because + it extends the normally flat Haskell module namespace into a + more flexible hierarchy of modules.</para> + + <para>This extension has very little impact on the language + itself; modules names are <emphasis>always</emphasis> fully + qualified, so you can just think of the fully qualified module + name as <quote>the module name</quote>. In particular, this + means that the full module name must be given after the + <literal>module</literal> keyword at the beginning of the + module; for example, the module <literal>A.B.C</literal> must + begin</para> + +<programlisting>module A.B.C</programlisting> + + + <para>It is a common strategy to use the <literal>as</literal> + keyword to save some typing when using qualified names with + hierarchical modules. For example:</para> + +<programlisting> +import qualified Control.Monad.ST.Strict as ST +</programlisting> + + <para>For details on how GHC searches for source and interface + files in the presence of hierarchical modules, see <xref + linkend="search-path"/>.</para> + + <para>GHC comes with a large collection of libraries arranged + hierarchically; see the accompanying library documentation. + There is an ongoing project to create and maintain a stable set + of <quote>core</quote> libraries used by several Haskell + compilers, and the libraries that GHC comes with represent the + current status of that project. For more details, see <ulink + url="http://www.haskell.org/~simonmar/libraries/libraries.html">Haskell + Libraries</ulink>.</para> + + </sect2> + + <!-- ====================== PATTERN GUARDS ======================= --> + +<sect2 id="pattern-guards"> +<title>Pattern guards</title> + +<para> +<indexterm><primary>Pattern guards (Glasgow extension)</primary></indexterm> +The discussion that follows is an abbreviated version of Simon Peyton Jones's original <ulink url="http://research.microsoft.com/~simonpj/Haskell/guards.html">proposal</ulink>. (Note that the proposal was written before pattern guards were implemented, so refers to them as unimplemented.) +</para> + +<para> +Suppose we have an abstract data type of finite maps, with a +lookup operation: + +<programlisting> +lookup :: FiniteMap -> Int -> Maybe Int +</programlisting> + +The lookup returns <function>Nothing</function> if the supplied key is not in the domain of the mapping, and <function>(Just v)</function> otherwise, +where <varname>v</varname> is the value that the key maps to. Now consider the following definition: +</para> + +<programlisting> +clunky env var1 var2 | ok1 && ok2 = val1 + val2 +| otherwise = var1 + var2 +where + m1 = lookup env var1 + m2 = lookup env var2 + ok1 = maybeToBool m1 + ok2 = maybeToBool m2 + val1 = expectJust m1 + val2 = expectJust m2 +</programlisting> + +<para> +The auxiliary functions are +</para> + +<programlisting> +maybeToBool :: Maybe a -> Bool +maybeToBool (Just x) = True +maybeToBool Nothing = False + +expectJust :: Maybe a -> a +expectJust (Just x) = x +expectJust Nothing = error "Unexpected Nothing" +</programlisting> + +<para> +What is <function>clunky</function> doing? The guard <literal>ok1 && +ok2</literal> checks that both lookups succeed, using +<function>maybeToBool</function> to convert the <function>Maybe</function> +types to booleans. The (lazily evaluated) <function>expectJust</function> +calls extract the values from the results of the lookups, and binds the +returned values to <varname>val1</varname> and <varname>val2</varname> +respectively. If either lookup fails, then clunky takes the +<literal>otherwise</literal> case and returns the sum of its arguments. +</para> + +<para> +This is certainly legal Haskell, but it is a tremendously verbose and +un-obvious way to achieve the desired effect. Arguably, a more direct way +to write clunky would be to use case expressions: +</para> + +<programlisting> +clunky env var1 var1 = case lookup env var1 of + Nothing -> fail + Just val1 -> case lookup env var2 of + Nothing -> fail + Just val2 -> val1 + val2 +where + fail = val1 + val2 +</programlisting> + +<para> +This is a bit shorter, but hardly better. Of course, we can rewrite any set +of pattern-matching, guarded equations as case expressions; that is +precisely what the compiler does when compiling equations! The reason that +Haskell provides guarded equations is because they allow us to write down +the cases we want to consider, one at a time, independently of each other. +This structure is hidden in the case version. Two of the right-hand sides +are really the same (<function>fail</function>), and the whole expression +tends to become more and more indented. +</para> + +<para> +Here is how I would write clunky: +</para> + +<programlisting> +clunky env var1 var1 + | Just val1 <- lookup env var1 + , Just val2 <- lookup env var2 + = val1 + val2 +...other equations for clunky... +</programlisting> + +<para> +The semantics should be clear enough. The qualifiers are matched in order. +For a <literal><-</literal> qualifier, which I call a pattern guard, the +right hand side is evaluated and matched against the pattern on the left. +If the match fails then the whole guard fails and the next equation is +tried. If it succeeds, then the appropriate binding takes place, and the +next qualifier is matched, in the augmented environment. Unlike list +comprehensions, however, the type of the expression to the right of the +<literal><-</literal> is the same as the type of the pattern to its +left. The bindings introduced by pattern guards scope over all the +remaining guard qualifiers, and over the right hand side of the equation. +</para> + +<para> +Just as with list comprehensions, boolean expressions can be freely mixed +with among the pattern guards. For example: +</para> + +<programlisting> +f x | [y] <- x + , y > 3 + , Just z <- h y + = ... +</programlisting> + +<para> +Haskell's current guards therefore emerge as a special case, in which the +qualifier list has just one element, a boolean expression. +</para> +</sect2> + + <!-- ===================== Recursive do-notation =================== --> + +<sect2 id="mdo-notation"> +<title>The recursive do-notation +</title> + +<para> The recursive do-notation (also known as mdo-notation) is implemented as described in +"A recursive do for Haskell", +Levent Erkok, John Launchbury", +Haskell Workshop 2002, pages: 29-37. Pittsburgh, Pennsylvania. +</para> +<para> +The do-notation of Haskell does not allow <emphasis>recursive bindings</emphasis>, +that is, the variables bound in a do-expression are visible only in the textually following +code block. Compare this to a let-expression, where bound variables are visible in the entire binding +group. It turns out that several applications can benefit from recursive bindings in +the do-notation, and this extension provides the necessary syntactic support. +</para> +<para> +Here is a simple (yet contrived) example: +</para> +<programlisting> +import Control.Monad.Fix + +justOnes = mdo xs <- Just (1:xs) + return xs +</programlisting> +<para> +As you can guess <literal>justOnes</literal> will evaluate to <literal>Just [1,1,1,...</literal>. +</para> + +<para> +The Control.Monad.Fix library introduces the <literal>MonadFix</literal> class. It's definition is: +</para> +<programlisting> +class Monad m => MonadFix m where + mfix :: (a -> m a) -> m a +</programlisting> +<para> +The function <literal>mfix</literal> +dictates how the required recursion operation should be performed. If recursive bindings are required for a monad, +then that monad must be declared an instance of the <literal>MonadFix</literal> class. +For details, see the above mentioned reference. +</para> +<para> +The following instances of <literal>MonadFix</literal> are automatically provided: List, Maybe, IO. +Furthermore, the Control.Monad.ST and Control.Monad.ST.Lazy modules provide the instances of the MonadFix class +for Haskell's internal state monad (strict and lazy, respectively). +</para> +<para> +There are three important points in using the recursive-do notation: +<itemizedlist> +<listitem><para> +The recursive version of the do-notation uses the keyword <literal>mdo</literal> (rather +than <literal>do</literal>). +</para></listitem> + +<listitem><para> +You should <literal>import Control.Monad.Fix</literal>. +(Note: Strictly speaking, this import is required only when you need to refer to the name +<literal>MonadFix</literal> in your program, but the import is always safe, and the programmers +are encouraged to always import this module when using the mdo-notation.) +</para></listitem> + +<listitem><para> +As with other extensions, ghc should be given the flag <literal>-fglasgow-exts</literal> +</para></listitem> +</itemizedlist> +</para> + +<para> +The web page: <ulink url="http://www.cse.ogi.edu/PacSoft/projects/rmb">http://www.cse.ogi.edu/PacSoft/projects/rmb</ulink> +contains up to date information on recursive monadic bindings. +</para> + +<para> +Historical note: The old implementation of the mdo-notation (and most +of the existing documents) used the name +<literal>MonadRec</literal> for the class and the corresponding library. +This name is not supported by GHC. +</para> + +</sect2> + + + <!-- ===================== PARALLEL LIST COMPREHENSIONS =================== --> + + <sect2 id="parallel-list-comprehensions"> + <title>Parallel List Comprehensions</title> + <indexterm><primary>list comprehensions</primary><secondary>parallel</secondary> + </indexterm> + <indexterm><primary>parallel list comprehensions</primary> + </indexterm> + + <para>Parallel list comprehensions are a natural extension to list + comprehensions. List comprehensions can be thought of as a nice + syntax for writing maps and filters. Parallel comprehensions + extend this to include the zipWith family.</para> + + <para>A parallel list comprehension has multiple independent + branches of qualifier lists, each separated by a `|' symbol. For + example, the following zips together two lists:</para> + +<programlisting> + [ (x, y) | x <- xs | y <- ys ] +</programlisting> + + <para>The behavior of parallel list comprehensions follows that of + zip, in that the resulting list will have the same length as the + shortest branch.</para> + + <para>We can define parallel list comprehensions by translation to + regular comprehensions. Here's the basic idea:</para> + + <para>Given a parallel comprehension of the form: </para> + +<programlisting> + [ e | p1 <- e11, p2 <- e12, ... + | q1 <- e21, q2 <- e22, ... + ... + ] +</programlisting> + + <para>This will be translated to: </para> + +<programlisting> + [ e | ((p1,p2), (q1,q2), ...) <- zipN [(p1,p2) | p1 <- e11, p2 <- e12, ...] + [(q1,q2) | q1 <- e21, q2 <- e22, ...] + ... + ] +</programlisting> + + <para>where `zipN' is the appropriate zip for the given number of + branches.</para> + + </sect2> + +<sect2 id="rebindable-syntax"> +<title>Rebindable syntax</title> + + + <para>GHC allows most kinds of built-in syntax to be rebound by + the user, to facilitate replacing the <literal>Prelude</literal> + with a home-grown version, for example.</para> + + <para>You may want to define your own numeric class + hierarchy. It completely defeats that purpose if the + literal "1" means "<literal>Prelude.fromInteger + 1</literal>", which is what the Haskell Report specifies. + So the <option>-fno-implicit-prelude</option> flag causes + the following pieces of built-in syntax to refer to + <emphasis>whatever is in scope</emphasis>, not the Prelude + versions: + + <itemizedlist> + <listitem> + <para>An integer literal <literal>368</literal> means + "<literal>fromInteger (368::Integer)</literal>", rather than + "<literal>Prelude.fromInteger (368::Integer)</literal>". +</para> </listitem> + + <listitem><para>Fractional literals are handed in just the same way, + except that the translation is + <literal>fromRational (3.68::Rational)</literal>. +</para> </listitem> + + <listitem><para>The equality test in an overloaded numeric pattern + uses whatever <literal>(==)</literal> is in scope. +</para> </listitem> + + <listitem><para>The subtraction operation, and the + greater-than-or-equal test, in <literal>n+k</literal> patterns + use whatever <literal>(-)</literal> and <literal>(>=)</literal> are in scope. + </para></listitem> + + <listitem> + <para>Negation (e.g. "<literal>- (f x)</literal>") + means "<literal>negate (f x)</literal>", both in numeric + patterns, and expressions. + </para></listitem> + + <listitem> + <para>"Do" notation is translated using whatever + functions <literal>(>>=)</literal>, + <literal>(>>)</literal>, and <literal>fail</literal>, + are in scope (not the Prelude + versions). List comprehensions, mdo (<xref linkend="mdo-notation"/>), and parallel array + comprehensions, are unaffected. </para></listitem> + + <listitem> + <para>Arrow + notation (see <xref linkend="arrow-notation"/>) + uses whatever <literal>arr</literal>, + <literal>(>>>)</literal>, <literal>first</literal>, + <literal>app</literal>, <literal>(|||)</literal> and + <literal>loop</literal> functions are in scope. But unlike the + other constructs, the types of these functions must match the + Prelude types very closely. Details are in flux; if you want + to use this, ask! + </para></listitem> + </itemizedlist> +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 emample, the +static semantics of the literal <literal>368</literal> +is exactly that of <literal>fromInteger (368::Integer)</literal>; it's fine for +<literal>fromInteger</literal> to have any of the types: +<programlisting> +fromInteger :: Integer -> Integer +fromInteger :: forall a. Foo a => Integer -> a +fromInteger :: Num a => a -> Integer +fromInteger :: Integer -> Bool -> Bool +</programlisting> +</para> + + <para>Be warned: this is an experimental facility, with + fewer checks than usual. Use <literal>-dcore-lint</literal> + to typecheck the desugared program. If Core Lint is happy + you should be all right.</para> + +</sect2> +</sect1> + + +<!-- TYPE SYSTEM EXTENSIONS --> +<sect1 id="type-extensions"> +<title>Type system extensions</title> + + +<sect2> +<title>Data types and type synonyms</title> + +<sect3 id="nullary-types"> +<title>Data types with no constructors</title> + +<para>With the <option>-fglasgow-exts</option> flag, GHC lets you declare +a data type with no constructors. For example:</para> + +<programlisting> + data S -- S :: * + data T a -- T :: * -> * +</programlisting> + +<para>Syntactically, the declaration lacks the "= constrs" part. The +type can be parameterised over types of any kind, but if the kind is +not <literal>*</literal> then an explicit kind annotation must be used +(see <xref linkend="sec-kinding"/>).</para> + +<para>Such data types have only one value, namely bottom. +Nevertheless, they can be useful when defining "phantom types".</para> +</sect3> + +<sect3 id="infix-tycons"> +<title>Infix type constructors, classes, and type variables</title> + +<para> +GHC allows type constructors, classes, and type variables to be operators, and +to be written infix, very much like expressions. More specifically: +<itemizedlist> +<listitem><para> + A type constructor or class can be an operator, beginning with a colon; e.g. <literal>:*:</literal>. + The lexical syntax is the same as that for data constructors. + </para></listitem> +<listitem><para> + Data type and type-synonym declarations can be written infix, parenthesised + if you want further arguments. E.g. +<screen> + data a :*: b = Foo a b + type a :+: b = Either a b + class a :=: b where ... + + data (a :**: b) x = Baz a b x + type (a :++: b) y = Either (a,b) y +</screen> + </para></listitem> +<listitem><para> + Types, and class constraints, can be written infix. For example + <screen> + x :: Int :*: Bool + f :: (a :=: b) => a -> b + </screen> + </para></listitem> +<listitem><para> + A type variable can be an (unqualified) operator e.g. <literal>+</literal>. + The lexical syntax is the same as that for variable operators, excluding "(.)", + "(!)", and "(*)". In a binding position, the operator must be + parenthesised. For example: +<programlisting> + type T (+) = Int + Int + f :: T Either + f = Left 3 + + liftA2 :: Arrow (~>) + => (a -> b -> c) -> (e ~> a) -> (e ~> b) -> (e ~> c) + liftA2 = ... +</programlisting> + </para></listitem> +<listitem><para> + Back-quotes work + as for expressions, both for type constructors and type variables; e.g. <literal>Int `Either` Bool</literal>, or + <literal>Int `a` Bool</literal>. Similarly, parentheses work the same; e.g. <literal>(:*:) Int Bool</literal>. + </para></listitem> +<listitem><para> + Fixities may be declared for type constructors, or classes, just as for data constructors. However, + one cannot distinguish between the two in a fixity declaration; a fixity declaration + sets the fixity for a data constructor and the corresponding type constructor. For example: +<screen> + infixl 7 T, :*: +</screen> + sets the fixity for both type constructor <literal>T</literal> and data constructor <literal>T</literal>, + and similarly for <literal>:*:</literal>. + <literal>Int `a` Bool</literal>. + </para></listitem> +<listitem><para> + Function arrow is <literal>infixr</literal> with fixity 0. (This might change; I'm not sure what it should be.) + </para></listitem> + +</itemizedlist> +</para> +</sect3> + +<sect3 id="type-synonyms"> +<title>Liberalised type synonyms</title> + +<para> +Type synonyms are like macros at the type level, and +GHC does validity checking on types <emphasis>only after expanding type synonyms</emphasis>. +That means that GHC can be very much more liberal about type synonyms than Haskell 98: +<itemizedlist> +<listitem> <para>You can write a <literal>forall</literal> (including overloading) +in a type synonym, thus: +<programlisting> + type Discard a = forall b. Show b => a -> b -> (a, String) + + f :: Discard a + f x y = (x, show y) + + g :: Discard Int -> (Int,Bool) -- A rank-2 type + g f = f Int True +</programlisting> +</para> +</listitem> + +<listitem><para> +You can write an unboxed tuple in a type synonym: +<programlisting> + type Pr = (# Int, Int #) + + h :: Int -> Pr + h x = (# x, x #) +</programlisting> +</para></listitem> + +<listitem><para> +You can apply a type synonym to a forall type: +<programlisting> + type Foo a = a -> a -> Bool + + f :: Foo (forall b. b->b) +</programlisting> +After expanding the synonym, <literal>f</literal> has the legal (in GHC) type: +<programlisting> + f :: (forall b. b->b) -> (forall b. b->b) -> Bool +</programlisting> +</para></listitem> + +<listitem><para> +You can apply a type synonym to a partially applied type synonym: +<programlisting> + type Generic i o = forall x. i x -> o x + type Id x = x + + foo :: Generic Id [] +</programlisting> +After expanding the synonym, <literal>foo</literal> has the legal (in GHC) type: +<programlisting> + foo :: forall x. x -> [x] +</programlisting> +</para></listitem> + +</itemizedlist> +</para> + +<para> +GHC currently does kind checking before expanding synonyms (though even that +could be changed.) +</para> +<para> +After expanding type synonyms, GHC does validity checking on types, looking for +the following mal-formedness which isn't detected simply by kind checking: +<itemizedlist> +<listitem><para> +Type constructor applied to a type involving for-alls. +</para></listitem> +<listitem><para> +Unboxed tuple on left of an arrow. +</para></listitem> +<listitem><para> +Partially-applied type synonym. +</para></listitem> +</itemizedlist> +So, for example, +this will be rejected: +<programlisting> + type Pr = (# Int, Int #) + + h :: Pr -> Int + h x = ... +</programlisting> +because GHC does not allow unboxed tuples on the left of a function arrow. +</para> +</sect3> + + +<sect3 id="existential-quantification"> +<title>Existentially quantified data constructors +</title> + +<para> +The idea of using existential quantification in data type declarations +was suggested by Perry, and implemented in Hope+ (Nigel Perry, <emphasis>The Implementation +of Practical Functional Programming Languages</emphasis>, PhD Thesis, University of +London, 1991). It was later formalised by Laufer and Odersky +(<emphasis>Polymorphic type inference and abstract data types</emphasis>, +TOPLAS, 16(5), pp1411-1430, 1994). +It's been in Lennart +Augustsson's <command>hbc</command> Haskell compiler for several years, and +proved very useful. Here's the idea. Consider the declaration: +</para> + +<para> + +<programlisting> + data Foo = forall a. MkFoo a (a -> Bool) + | Nil +</programlisting> + +</para> + +<para> +The data type <literal>Foo</literal> has two constructors with types: +</para> + +<para> + +<programlisting> + MkFoo :: forall a. a -> (a -> Bool) -> Foo + Nil :: Foo +</programlisting> + +</para> + +<para> +Notice that the type variable <literal>a</literal> in the type of <function>MkFoo</function> +does not appear in the data type itself, which is plain <literal>Foo</literal>. +For example, the following expression is fine: +</para> + +<para> + +<programlisting> + [MkFoo 3 even, MkFoo 'c' isUpper] :: [Foo] +</programlisting> + +</para> + +<para> +Here, <literal>(MkFoo 3 even)</literal> packages an integer with a function +<function>even</function> that maps an integer to <literal>Bool</literal>; and <function>MkFoo 'c' +isUpper</function> packages a character with a compatible function. These +two things are each of type <literal>Foo</literal> and can be put in a list. +</para> + +<para> +What can we do with a value of type <literal>Foo</literal>?. In particular, +what happens when we pattern-match on <function>MkFoo</function>? +</para> + +<para> + +<programlisting> + f (MkFoo val fn) = ??? +</programlisting> + +</para> + +<para> +Since all we know about <literal>val</literal> and <function>fn</function> is that they +are compatible, the only (useful) thing we can do with them is to +apply <function>fn</function> to <literal>val</literal> to get a boolean. For example: +</para> + +<para> + +<programlisting> + f :: Foo -> Bool + f (MkFoo val fn) = fn val +</programlisting> + +</para> + +<para> +What this allows us to do is to package heterogenous values +together with a bunch of functions that manipulate them, and then treat +that collection of packages in a uniform manner. You can express +quite a bit of object-oriented-like programming this way. +</para> + +<sect4 id="existential"> +<title>Why existential? +</title> + +<para> +What has this to do with <emphasis>existential</emphasis> quantification? +Simply that <function>MkFoo</function> has the (nearly) isomorphic type +</para> + +<para> + +<programlisting> + MkFoo :: (exists a . (a, a -> Bool)) -> Foo +</programlisting> + +</para> + +<para> +But Haskell programmers can safely think of the ordinary +<emphasis>universally</emphasis> quantified type given above, thereby avoiding +adding a new existential quantification construct. +</para> + +</sect4> + +<sect4> +<title>Type classes</title> + +<para> +An easy extension is to allow +arbitrary contexts before the constructor. For example: +</para> + +<para> + +<programlisting> +data Baz = forall a. Eq a => Baz1 a a + | forall b. Show b => Baz2 b (b -> b) +</programlisting> + +</para> + +<para> +The two constructors have the types you'd expect: +</para> + +<para> + +<programlisting> +Baz1 :: forall a. Eq a => a -> a -> Baz +Baz2 :: forall b. Show b => b -> (b -> b) -> Baz +</programlisting> + +</para> + +<para> +But when pattern matching on <function>Baz1</function> the matched values can be compared +for equality, and when pattern matching on <function>Baz2</function> the first matched +value can be converted to a string (as well as applying the function to it). +So this program is legal: +</para> + +<para> + +<programlisting> + f :: Baz -> String + f (Baz1 p q) | p == q = "Yes" + | otherwise = "No" + f (Baz2 v fn) = show (fn v) +</programlisting> + +</para> + +<para> +Operationally, in a dictionary-passing implementation, the +constructors <function>Baz1</function> and <function>Baz2</function> must store the +dictionaries for <literal>Eq</literal> and <literal>Show</literal> respectively, and +extract it on pattern matching. +</para> + +<para> +Notice the way that the syntax fits smoothly with that used for +universal quantification earlier. +</para> + +</sect4> + +<sect4> +<title>Record Constructors</title> + +<para> +GHC allows existentials to be used with records syntax as well. For example: + +<programlisting> +data Counter a = forall self. NewCounter + { _this :: self + , _inc :: self -> self + , _display :: self -> IO () + , tag :: a + } +</programlisting> +Here <literal>tag</literal> is a public field, with a well-typed selector +function <literal>tag :: Counter a -> a</literal>. The <literal>self</literal> +type is hidden from the outside; any attempt to apply <literal>_this</literal>, +<literal>_inc</literal> or <literal>_output</literal> as functions will raise a +compile-time error. In other words, <emphasis>GHC defines a record selector function +only for fields whose type does not mention the existentially-quantified variables</emphasis>. +(This example used an underscore in the fields for which record selectors +will not be defined, but that is only programming style; GHC ignores them.) +</para> + +<para> +To make use of these hidden fields, we need to create some helper functions: + +<programlisting> +inc :: Counter a -> Counter a +inc (NewCounter x i d t) = NewCounter + { _this = i x, _inc = i, _display = d, tag = t } + +display :: Counter a -> IO () +display NewCounter{ _this = x, _display = d } = d x +</programlisting> + +Now we can define counters with different underlying implementations: + +<programlisting> +counterA :: Counter String +counterA = NewCounter + { _this = 0, _inc = (1+), _display = print, tag = "A" } + +counterB :: Counter String +counterB = NewCounter + { _this = "", _inc = ('#':), _display = putStrLn, tag = "B" } + +main = do + display (inc counterA) -- prints "1" + display (inc (inc counterB)) -- prints "##" +</programlisting> + +In GADT declarations (see <xref linkend="gadt"/>), the explicit +<literal>forall</literal> may be omitted. For example, we can express +the same <literal>Counter a</literal> using GADT: + +<programlisting> +data Counter a where + NewCounter { _this :: self + , _inc :: self -> self + , _display :: self -> IO () + , tag :: a + } + :: Counter a +</programlisting> + +At the moment, record update syntax is only supported for Haskell 98 data types, +so the following function does <emphasis>not</emphasis> work: + +<programlisting> +-- This is invalid; use explicit NewCounter instead for now +setTag :: Counter a -> a -> Counter a +setTag obj t = obj{ tag = t } +</programlisting> + +</para> + +</sect4> + + +<sect4> +<title>Restrictions</title> + +<para> +There are several restrictions on the ways in which existentially-quantified +constructors can be use. +</para> + +<para> + +<itemizedlist> +<listitem> + +<para> + When pattern matching, each pattern match introduces a new, +distinct, type for each existential type variable. These types cannot +be unified with any other type, nor can they escape from the scope of +the pattern match. For example, these fragments are incorrect: + + +<programlisting> +f1 (MkFoo a f) = a +</programlisting> + + +Here, the type bound by <function>MkFoo</function> "escapes", because <literal>a</literal> +is the result of <function>f1</function>. One way to see why this is wrong is to +ask what type <function>f1</function> has: + + +<programlisting> + f1 :: Foo -> a -- Weird! +</programlisting> + + +What is this "<literal>a</literal>" in the result type? Clearly we don't mean +this: + + +<programlisting> + f1 :: forall a. Foo -> a -- Wrong! +</programlisting> + + +The original program is just plain wrong. Here's another sort of error + + +<programlisting> + f2 (Baz1 a b) (Baz1 p q) = a==q +</programlisting> + + +It's ok to say <literal>a==b</literal> or <literal>p==q</literal>, but +<literal>a==q</literal> is wrong because it equates the two distinct types arising +from the two <function>Baz1</function> constructors. + + +</para> +</listitem> +<listitem> + +<para> +You can't pattern-match on an existentially quantified +constructor in a <literal>let</literal> or <literal>where</literal> group of +bindings. So this is illegal: + + +<programlisting> + f3 x = a==b where { Baz1 a b = x } +</programlisting> + +Instead, use a <literal>case</literal> expression: + +<programlisting> + f3 x = case x of Baz1 a b -> a==b +</programlisting> + +In general, you can only pattern-match +on an existentially-quantified constructor in a <literal>case</literal> expression or +in the patterns of a function definition. + +The reason for this restriction is really an implementation one. +Type-checking binding groups is already a nightmare without +existentials complicating the picture. Also an existential pattern +binding at the top level of a module doesn't make sense, because it's +not clear how to prevent the existentially-quantified type "escaping". +So for now, there's a simple-to-state restriction. We'll see how +annoying it is. + +</para> +</listitem> +<listitem> + +<para> +You can't use existential quantification for <literal>newtype</literal> +declarations. So this is illegal: + + +<programlisting> + newtype T = forall a. Ord a => MkT a +</programlisting> + + +Reason: a value of type <literal>T</literal> must be represented as a +pair of a dictionary for <literal>Ord t</literal> and a value of type +<literal>t</literal>. That contradicts the idea that +<literal>newtype</literal> should have no concrete representation. +You can get just the same efficiency and effect by using +<literal>data</literal> instead of <literal>newtype</literal>. If +there is no overloading involved, then there is more of a case for +allowing an existentially-quantified <literal>newtype</literal>, +because the <literal>data</literal> version does carry an +implementation cost, but single-field existentially quantified +constructors aren't much use. So the simple restriction (no +existential stuff on <literal>newtype</literal>) stands, unless there +are convincing reasons to change it. + + +</para> +</listitem> +<listitem> + +<para> + You can't use <literal>deriving</literal> to define instances of a +data type with existentially quantified data constructors. + +Reason: in most cases it would not make sense. For example:# + +<programlisting> +data T = forall a. MkT [a] deriving( Eq ) +</programlisting> + +To derive <literal>Eq</literal> in the standard way we would need to have equality +between the single component of two <function>MkT</function> constructors: + +<programlisting> +instance Eq T where + (MkT a) == (MkT b) = ??? +</programlisting> + +But <varname>a</varname> and <varname>b</varname> have distinct types, and so can't be compared. +It's just about possible to imagine examples in which the derived instance +would make sense, but it seems altogether simpler simply to prohibit such +declarations. Define your own instances! +</para> +</listitem> + +</itemizedlist> + +</para> + +</sect4> +</sect3> + +</sect2> + + + +<sect2 id="multi-param-type-classes"> +<title>Class declarations</title> + +<para> +This section, and the next one, documents GHC's type-class extensions. +There's lots of background in the paper <ulink +url="http://research.microsoft.com/~simonpj/Papers/type-class-design-space" >Type +classes: exploring the design space</ulink > (Simon Peyton Jones, Mark +Jones, Erik Meijer). +</para> +<para> +All the extensions are enabled by the <option>-fglasgow-exts</option> flag. +</para> + +<sect3> +<title>Multi-parameter type classes</title> +<para> +Multi-parameter type classes are permitted. For example: + + +<programlisting> + class Collection c a where + union :: c a -> c a -> c a + ...etc. +</programlisting> + +</para> +</sect3> + +<sect3> +<title>The superclasses of a class declaration</title> + +<para> +There are no restrictions on the context in a class declaration +(which introduces superclasses), except that the class hierarchy must +be acyclic. So these class declarations are OK: + + +<programlisting> + class Functor (m k) => FiniteMap m k where + ... + + class (Monad m, Monad (t m)) => Transform t m where + lift :: m a -> (t m) a +</programlisting> + + +</para> +<para> +As in Haskell 98, The class hierarchy must be acyclic. However, the definition +of "acyclic" involves only the superclass relationships. For example, +this is OK: + + +<programlisting> + class C a where { + op :: D b => a -> b -> b + } + + class C a => D a where { ... } +</programlisting> + + +Here, <literal>C</literal> is a superclass of <literal>D</literal>, but it's OK for a +class operation <literal>op</literal> of <literal>C</literal> to mention <literal>D</literal>. (It +would not be OK for <literal>D</literal> to be a superclass of <literal>C</literal>.) +</para> +</sect3> + + + + +<sect3 id="class-method-types"> +<title>Class method types</title> + +<para> +Haskell 98 prohibits class method types to mention constraints on the +class type variable, thus: +<programlisting> + class Seq s a where + fromList :: [a] -> s a + elem :: Eq a => a -> s a -> Bool +</programlisting> +The type of <literal>elem</literal> is illegal in Haskell 98, because it +contains the constraint <literal>Eq a</literal>, constrains only the +class type variable (in this case <literal>a</literal>). +GHC lifts this restriction. +</para> + + +</sect3> +</sect2> + +<sect2 id="functional-dependencies"> +<title>Functional dependencies +</title> + +<para> Functional dependencies are implemented as described by Mark Jones +in “<ulink url="http://www.cse.ogi.edu/~mpj/pubs/fundeps.html">Type Classes with Functional Dependencies</ulink>”, Mark P. Jones, +In Proceedings of the 9th European Symposium on Programming, +ESOP 2000, Berlin, Germany, March 2000, Springer-Verlag LNCS 1782, +. +</para> +<para> +Functional dependencies are introduced by a vertical bar in the syntax of a +class declaration; e.g. +<programlisting> + class (Monad m) => MonadState s m | m -> s where ... + + class Foo a b c | a b -> c where ... +</programlisting> +There should be more documentation, but there isn't (yet). Yell if you need it. +</para> + +<sect3><title>Rules for functional dependencies </title> +<para> +In a class declaration, all of the class type variables must be reachable (in the sense +mentioned in <xref linkend="type-restrictions"/>) +from the free variables of each method type. +For example: + +<programlisting> + class Coll s a where + empty :: s + insert :: s -> a -> s +</programlisting> + +is not OK, because the type of <literal>empty</literal> doesn't mention +<literal>a</literal>. Functional dependencies can make the type variable +reachable: +<programlisting> + class Coll s a | s -> a where + empty :: s + insert :: s -> a -> s +</programlisting> + +Alternatively <literal>Coll</literal> might be rewritten + +<programlisting> + class Coll s a where + empty :: s a + insert :: s a -> a -> s a +</programlisting> + + +which makes the connection between the type of a collection of +<literal>a</literal>'s (namely <literal>(s a)</literal>) and the element type <literal>a</literal>. +Occasionally this really doesn't work, in which case you can split the +class like this: + + +<programlisting> + class CollE s where + empty :: s + + class CollE s => Coll s a where + insert :: s -> a -> s +</programlisting> +</para> +</sect3> + + +<sect3> +<title>Background on functional dependencies</title> + +<para>The following description of the motivation and use of functional dependencies is taken +from the Hugs user manual, reproduced here (with minor changes) by kind +permission of Mark Jones. +</para> +<para> +Consider the following class, intended as part of a +library for collection types: +<programlisting> + class Collects e ce where + empty :: ce + insert :: e -> ce -> ce + member :: e -> ce -> Bool +</programlisting> +The type variable e used here represents the element type, while ce is the type +of the container itself. Within this framework, we might want to define +instances of this class for lists or characteristic functions (both of which +can be used to represent collections of any equality type), bit sets (which can +be used to represent collections of characters), or hash tables (which can be +used to represent any collection whose elements have a hash function). Omitting +standard implementation details, this would lead to the following declarations: +<programlisting> + instance Eq e => Collects e [e] where ... + instance Eq e => Collects e (e -> Bool) where ... + instance Collects Char BitSet where ... + instance (Hashable e, Collects a ce) + => Collects e (Array Int ce) where ... +</programlisting> +All this looks quite promising; we have a class and a range of interesting +implementations. Unfortunately, there are some serious problems with the class +declaration. First, the empty function has an ambiguous type: +<programlisting> + empty :: Collects e ce => ce +</programlisting> +By "ambiguous" we mean that there is a type variable e that appears on the left +of the <literal>=></literal> symbol, but not on the right. The problem with +this is that, according to the theoretical foundations of Haskell overloading, +we cannot guarantee a well-defined semantics for any term with an ambiguous +type. +</para> +<para> +We can sidestep this specific problem by removing the empty member from the +class declaration. However, although the remaining members, insert and member, +do not have ambiguous types, we still run into problems when we try to use +them. For example, consider the following two functions: +<programlisting> + f x y = insert x . insert y + g = f True 'a' +</programlisting> +for which GHC infers the following types: +<programlisting> + f :: (Collects a c, Collects b c) => a -> b -> c -> c + g :: (Collects Bool c, Collects Char c) => c -> c +</programlisting> +Notice that the type for f allows the two parameters x and y to be assigned +different types, even though it attempts to insert each of the two values, one +after the other, into the same collection. If we're trying to model collections +that contain only one type of value, then this is clearly an inaccurate +type. Worse still, the definition for g is accepted, without causing a type +error. As a result, the error in this code will not be flagged at the point +where it appears. Instead, it will show up only when we try to use g, which +might even be in a different module. +</para> + +<sect4><title>An attempt to use constructor classes</title> + +<para> +Faced with the problems described above, some Haskell programmers might be +tempted to use something like the following version of the class declaration: +<programlisting> + class Collects e c where + empty :: c e + insert :: e -> c e -> c e + member :: e -> c e -> Bool +</programlisting> +The key difference here is that we abstract over the type constructor c that is +used to form the collection type c e, and not over that collection type itself, +represented by ce in the original class declaration. This avoids the immediate +problems that we mentioned above: empty has type <literal>Collects e c => c +e</literal>, which is not ambiguous. +</para> +<para> +The function f from the previous section has a more accurate type: +<programlisting> + f :: (Collects e c) => e -> e -> c e -> c e +</programlisting> +The function g from the previous section is now rejected with a type error as +we would hope because the type of f does not allow the two arguments to have +different types. +This, then, is an example of a multiple parameter class that does actually work +quite well in practice, without ambiguity problems. +There is, however, a catch. This version of the Collects class is nowhere near +as general as the original class seemed to be: only one of the four instances +for <literal>Collects</literal> +given above can be used with this version of Collects because only one of +them---the instance for lists---has a collection type that can be written in +the form c e, for some type constructor c, and element type e. +</para> +</sect4> + +<sect4><title>Adding functional dependencies</title> + +<para> +To get a more useful version of the Collects class, Hugs provides a mechanism +that allows programmers to specify dependencies between the parameters of a +multiple parameter class (For readers with an interest in theoretical +foundations and previous work: The use of dependency information can be seen +both as a generalization of the proposal for `parametric type classes' that was +put forward by Chen, Hudak, and Odersky, or as a special case of Mark Jones's +later framework for "improvement" of qualified types. The +underlying ideas are also discussed in a more theoretical and abstract setting +in a manuscript [implparam], where they are identified as one point in a +general design space for systems of implicit parameterization.). + +To start with an abstract example, consider a declaration such as: +<programlisting> + class C a b where ... +</programlisting> +which tells us simply that C can be thought of as a binary relation on types +(or type constructors, depending on the kinds of a and b). Extra clauses can be +included in the definition of classes to add information about dependencies +between parameters, as in the following examples: +<programlisting> + class D a b | a -> b where ... + class E a b | a -> b, b -> a where ... +</programlisting> +The notation <literal>a -> b</literal> used here between the | and where +symbols --- not to be +confused with a function type --- indicates that the a parameter uniquely +determines the b parameter, and might be read as "a determines b." Thus D is +not just a relation, but actually a (partial) function. Similarly, from the two +dependencies that are included in the definition of E, we can see that E +represents a (partial) one-one mapping between types. +</para> +<para> +More generally, dependencies take the form <literal>x1 ... xn -> y1 ... ym</literal>, +where x1, ..., xn, and y1, ..., yn are type variables with n>0 and +m>=0, meaning that the y parameters are uniquely determined by the x +parameters. Spaces can be used as separators if more than one variable appears +on any single side of a dependency, as in <literal>t -> a b</literal>. Note that a class may be +annotated with multiple dependencies using commas as separators, as in the +definition of E above. Some dependencies that we can write in this notation are +redundant, and will be rejected because they don't serve any useful +purpose, and may instead indicate an error in the program. Examples of +dependencies like this include <literal>a -> a </literal>, +<literal>a -> a a </literal>, +<literal>a -> </literal>, etc. There can also be +some redundancy if multiple dependencies are given, as in +<literal>a->b</literal>, + <literal>b->c </literal>, <literal>a->c </literal>, and +in which some subset implies the remaining dependencies. Examples like this are +not treated as errors. Note that dependencies appear only in class +declarations, and not in any other part of the language. In particular, the +syntax for instance declarations, class constraints, and types is completely +unchanged. +</para> +<para> +By including dependencies in a class declaration, we provide a mechanism for +the programmer to specify each multiple parameter class more precisely. The +compiler, on the other hand, is responsible for ensuring that the set of +instances that are in scope at any given point in the program is consistent +with any declared dependencies. For example, the following pair of instance +declarations cannot appear together in the same scope because they violate the +dependency for D, even though either one on its own would be acceptable: +<programlisting> + instance D Bool Int where ... + instance D Bool Char where ... +</programlisting> +Note also that the following declaration is not allowed, even by itself: +<programlisting> + instance D [a] b where ... +</programlisting> +The problem here is that this instance would allow one particular choice of [a] +to be associated with more than one choice for b, which contradicts the +dependency specified in the definition of D. More generally, this means that, +in any instance of the form: +<programlisting> + instance D t s where ... +</programlisting> +for some particular types t and s, the only variables that can appear in s are +the ones that appear in t, and hence, if the type t is known, then s will be +uniquely determined. +</para> +<para> +The benefit of including dependency information is that it allows us to define +more general multiple parameter classes, without ambiguity problems, and with +the benefit of more accurate types. To illustrate this, we return to the +collection class example, and annotate the original definition of <literal>Collects</literal> +with a simple dependency: +<programlisting> + class Collects e ce | ce -> e where + empty :: ce + insert :: e -> ce -> ce + member :: e -> ce -> Bool +</programlisting> +The dependency <literal>ce -> e</literal> 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. +</para> +<para> +What about the ambiguity problems that we encountered with the original +definition? The empty function still has type Collects e ce => ce, but it is no +longer necessary to regard that as an ambiguous type: Although the variable e +does not appear on the right of the => symbol, the dependency for class +Collects tells us that it is uniquely determined by ce, which does appear on +the right of the => symbol. Hence the context in which empty is used can still +give enough information to determine types for both ce and e, without +ambiguity. More generally, we need only regard a type as ambiguous if it +contains a variable on the left of the => that is not uniquely determined +(either directly or indirectly) by the variables on the right. +</para> +<para> +Dependencies also help to produce more accurate types for user defined +functions, and hence to provide earlier detection of errors, and less cluttered +types for programmers to work with. Recall the previous definition for a +function f: +<programlisting> + f x y = insert x y = insert x . insert y +</programlisting> +for which we originally obtained a type: +<programlisting> + f :: (Collects a c, Collects b c) => a -> b -> c -> c +</programlisting> +Given the dependency information that we have for Collects, however, we can +deduce that a and b must be equal because they both appear as the second +parameter in a Collects constraint with the same first parameter c. Hence we +can infer a shorter and more accurate type for f: +<programlisting> + f :: (Collects a c) => a -> a -> c -> c +</programlisting> +In a similar way, the earlier definition of g will now be flagged as a type error. +</para> +<para> +Although we have given only a few examples here, it should be clear that the +addition of dependency information can help to make multiple parameter classes +more useful in practice, avoiding ambiguity problems, and allowing more general +sets of instance declarations. +</para> +</sect4> +</sect3> +</sect2> + +<sect2 id="instance-decls"> +<title>Instance declarations</title> + +<sect3 id="instance-rules"> +<title>Relaxed rules for instance declarations</title> + +<para>An instance declaration has the form +<screen> + instance ( <replaceable>assertion</replaceable><subscript>1</subscript>, ..., <replaceable>assertion</replaceable><subscript>n</subscript>) => <replaceable>class</replaceable> <replaceable>type</replaceable><subscript>1</subscript> ... <replaceable>type</replaceable><subscript>m</subscript> where ... +</screen> +The part before the "<literal>=></literal>" is the +<emphasis>context</emphasis>, while the part after the +"<literal>=></literal>" is the <emphasis>head</emphasis> of the instance declaration. +</para> + +<para> +In Haskell 98 the head of an instance declaration +must be of the form <literal>C (T a1 ... an)</literal>, where +<literal>C</literal> is the class, <literal>T</literal> is a type constructor, +and the <literal>a1 ... an</literal> are distinct type variables. +Furthermore, the assertions in the context of the instance declaration +must be of the form <literal>C a</literal> where <literal>a</literal> +is a type variable that occurs in the head. +</para> +<para> +The <option>-fglasgow-exts</option> flag loosens these restrictions +considerably. Firstly, multi-parameter type classes are permitted. Secondly, +the context and head of the instance declaration can each consist of arbitrary +(well-kinded) assertions <literal>(C t1 ... tn)</literal> subject only to the +following rules: +<orderedlist> +<listitem><para> +For each assertion in the context: +<orderedlist> +<listitem><para>No type variable has more occurrences in the assertion than in the head</para></listitem> +<listitem><para>The assertion has fewer constructors and variables (taken together + and counting repetitions) than the head</para></listitem> +</orderedlist> +</para></listitem> + +<listitem><para>The coverage condition. For each functional dependency, +<replaceable>tvs</replaceable><subscript>left</subscript> <literal>-></literal> +<replaceable>tvs</replaceable><subscript>right</subscript>, of the class, +every type variable in +S(<replaceable>tvs</replaceable><subscript>right</subscript>) must appear in +S(<replaceable>tvs</replaceable><subscript>left</subscript>), where S is the +substitution mapping each type variable in the class declaration to the +corresponding type in the instance declaration. +</para></listitem> +</orderedlist> +These restrictions ensure that context reduction terminates: each reduction +step makes the problem smaller by at least one +constructor. For example, the following would make the type checker +loop if it wasn't excluded: +<programlisting> + instance C a => C a where ... +</programlisting> +For example, these are OK: +<programlisting> + instance C Int [a] -- Multiple parameters + instance Eq (S [a]) -- Structured type in head + + -- Repeated type variable in head + instance C4 a a => C4 [a] [a] + instance Stateful (ST s) (MutVar s) + + -- Head can consist of type variables only + instance C a + instance (Eq a, Show b) => C2 a b + + -- Non-type variables in context + instance Show (s a) => Show (Sized s a) + instance C2 Int a => C3 Bool [a] + instance C2 Int a => C3 [a] b +</programlisting> +But these are not: +<programlisting> + -- Context assertion no smaller than head + instance C a => C a where ... + -- (C b b) has more more occurrences of b than the head + instance C b b => Foo [b] where ... +</programlisting> +</para> + +<para> +The same restrictions apply to instances generated by +<literal>deriving</literal> clauses. Thus the following is accepted: +<programlisting> + data MinHeap h a = H a (h a) + deriving (Show) +</programlisting> +because the derived instance +<programlisting> + instance (Show a, Show (h a)) => Show (MinHeap h a) +</programlisting> +conforms to the above rules. +</para> + +<para> +A useful idiom permitted by the above rules is as follows. +If one allows overlapping instance declarations then it's quite +convenient to have a "default instance" declaration that applies if +something more specific does not: +<programlisting> + instance C a where + op = ... -- Default +</programlisting> +</para> +</sect3> + +<sect3 id="undecidable-instances"> +<title>Undecidable instances</title> + +<para> +Sometimes even the rules of <xref linkend="instance-rules"/> are too onerous. +For example, sometimes you might want to use the following to get the +effect of a "class synonym": +<programlisting> + class (C1 a, C2 a, C3 a) => C a where { } + + instance (C1 a, C2 a, C3 a) => C a where { } +</programlisting> +This allows you to write shorter signatures: +<programlisting> + f :: C a => ... +</programlisting> +instead of +<programlisting> + f :: (C1 a, C2 a, C3 a) => ... +</programlisting> +The restrictions on functional dependencies (<xref +linkend="functional-dependencies"/>) are particularly troublesome. +It is tempting to introduce type variables in the context that do not appear in +the head, something that is excluded by the normal rules. For example: +<programlisting> + class HasConverter a b | a -> b where + convert :: a -> b + + data Foo a = MkFoo a + + instance (HasConverter a b,Show b) => Show (Foo a) where + show (MkFoo value) = show (convert value) +</programlisting> +This is dangerous territory, however. Here, for example, is a program that would make the +typechecker loop: +<programlisting> + class D a + class F a b | a->b + instance F [a] [[a]] + instance (D c, F a c) => D [a] -- 'c' is not mentioned in the head +</programlisting> +Similarly, it can be tempting to lift the coverage condition: +<programlisting> + class Mul a b c | a b -> c where + (.*.) :: a -> b -> c + + instance Mul Int Int Int where (.*.) = (*) + instance Mul Int Float Float where x .*. y = fromIntegral x * y + instance Mul a b c => Mul a [b] [c] where x .*. v = map (x.*.) v +</programlisting> +The third instance declaration does not obey the coverage condition; +and indeed the (somewhat strange) definition: +<programlisting> + f = \ b x y -> if b then x .*. [y] else y +</programlisting> +makes instance inference go into a loop, because it requires the constraint +<literal>(Mul a [b] b)</literal>. +</para> +<para> +Nevertheless, GHC allows you to experiment with more liberal rules. If you use +the experimental flag <option>-fallow-undecidable-instances</option> +<indexterm><primary>-fallow-undecidable-instances +option</primary></indexterm>, you can use arbitrary +types in both an instance context and instance head. Termination is ensured by having a +fixed-depth recursion stack. If you exceed the stack depth you get a +sort of backtrace, and the opportunity to increase the stack depth +with <option>-fcontext-stack</option><emphasis>N</emphasis>. +</para> + +</sect3> + + +<sect3 id="instance-overlap"> +<title>Overlapping instances</title> +<para> +In general, <emphasis>GHC requires that that it be unambiguous which instance +declaration +should be used to resolve a type-class constraint</emphasis>. This behaviour +can be modified by two flags: <option>-fallow-overlapping-instances</option> +<indexterm><primary>-fallow-overlapping-instances +</primary></indexterm> +and <option>-fallow-incoherent-instances</option> +<indexterm><primary>-fallow-incoherent-instances +</primary></indexterm>, as this section discusses.</para> +<para> +When GHC tries to resolve, say, the constraint <literal>C Int Bool</literal>, +it tries to match every instance declaration against the +constraint, +by instantiating the head of the instance declaration. For example, consider +these declarations: +<programlisting> + instance context1 => C Int a where ... -- (A) + instance context2 => C a Bool where ... -- (B) + instance context3 => C Int [a] where ... -- (C) + instance context4 => C Int [Int] where ... -- (D) +</programlisting> +The instances (A) and (B) match the constraint <literal>C Int Bool</literal>, +but (C) and (D) do not. When matching, GHC takes +no account of the context of the instance declaration +(<literal>context1</literal> etc). +GHC's default behaviour is that <emphasis>exactly one instance must match the +constraint it is trying to resolve</emphasis>. +It is fine for there to be a <emphasis>potential</emphasis> of overlap (by +including both declarations (A) and (B), say); an error is only reported if a +particular constraint matches more than one. +</para> + +<para> +The <option>-fallow-overlapping-instances</option> flag instructs GHC to allow +more than one instance to match, provided there is a most specific one. For +example, the constraint <literal>C Int [Int]</literal> matches instances (A), +(C) and (D), but the last is more specific, and hence is chosen. If there is no +most-specific match, the program is rejected. +</para> +<para> +However, GHC is conservative about committing to an overlapping instance. For example: +<programlisting> + f :: [b] -> [b] + f x = ... +</programlisting> +Suppose that from the RHS of <literal>f</literal> we get the constraint +<literal>C Int [b]</literal>. But +GHC does not commit to instance (C), because in a particular +call of <literal>f</literal>, <literal>b</literal> might be instantiate +to <literal>Int</literal>, in which case instance (D) would be more specific still. +So GHC rejects the program. If you add the flag <option>-fallow-incoherent-instances</option>, +GHC will instead pick (C), without complaining about +the problem of subsequent instantiations. +</para> +<para> +The willingness to be overlapped or incoherent is a property of +the <emphasis>instance declaration</emphasis> itself, controlled by the +presence or otherwise of the <option>-fallow-overlapping-instances</option> +and <option>-fallow-incoherent-instances</option> flags when that mdodule is +being defined. Neither flag is required in a module that imports and uses the +instance declaration. Specifically, during the lookup process: +<itemizedlist> +<listitem><para> +An instance declaration is ignored during the lookup process if (a) a more specific +match is found, and (b) the instance declaration was compiled with +<option>-fallow-overlapping-instances</option>. The flag setting for the +more-specific instance does not matter. +</para></listitem> +<listitem><para> +Suppose an instance declaration does not matche the constraint being looked up, but +does unify with it, so that it might match when the constraint is further +instantiated. Usually GHC will regard this as a reason for not committing to +some other constraint. But if the instance declaration was compiled with +<option>-fallow-incoherent-instances</option>, GHC will skip the "does-it-unify?" +check for that declaration. +</para></listitem> +</itemizedlist> +All this makes it possible for a library author to design a library that relies on +overlapping instances without the library client having to know. +</para> +<para>The <option>-fallow-incoherent-instances</option> flag implies the +<option>-fallow-overlapping-instances</option> flag, but not vice versa. +</para> +</sect3> + +<sect3> +<title>Type synonyms in the instance head</title> + +<para> +<emphasis>Unlike Haskell 98, instance heads may use type +synonyms</emphasis>. (The instance "head" is the bit after the "=>" in an instance decl.) +As always, using a type synonym is just shorthand for +writing the RHS of the type synonym definition. For example: + + +<programlisting> + type Point = (Int,Int) + instance C Point where ... + instance C [Point] where ... +</programlisting> + + +is legal. However, if you added + + +<programlisting> + instance C (Int,Int) where ... +</programlisting> + + +as well, then the compiler will complain about the overlapping +(actually, identical) instance declarations. As always, type synonyms +must be fully applied. You cannot, for example, write: + + +<programlisting> + type P a = [[a]] + instance Monad P where ... +</programlisting> + + +This design decision is independent of all the others, and easily +reversed, but it makes sense to me. + +</para> +</sect3> + + +</sect2> + +<sect2 id="type-restrictions"> +<title>Type signatures</title> + +<sect3><title>The context of a type signature</title> +<para> +Unlike Haskell 98, constraints in types do <emphasis>not</emphasis> have to be of +the form <emphasis>(class type-variable)</emphasis> or +<emphasis>(class (type-variable type-variable ...))</emphasis>. Thus, +these type signatures are perfectly OK +<programlisting> + g :: Eq [a] => ... + g :: Ord (T a ()) => ... +</programlisting> +</para> +<para> +GHC imposes the following restrictions on the constraints in a type signature. +Consider the type: + +<programlisting> + forall tv1..tvn (c1, ...,cn) => type +</programlisting> + +(Here, we write the "foralls" explicitly, although the Haskell source +language omits them; in Haskell 98, all the free type variables of an +explicit source-language type signature are universally quantified, +except for the class type variables in a class declaration. However, +in GHC, you can give the foralls if you want. See <xref linkend="universal-quantification"/>). +</para> + +<para> + +<orderedlist> +<listitem> + +<para> + <emphasis>Each universally quantified type variable +<literal>tvi</literal> must be reachable from <literal>type</literal></emphasis>. + +A type variable <literal>a</literal> is "reachable" if it it appears +in the same constraint as either a type variable free in in +<literal>type</literal>, or another reachable type variable. +A value with a type that does not obey +this reachability restriction cannot be used without introducing +ambiguity; that is why the type is rejected. +Here, for example, is an illegal type: + + +<programlisting> + forall a. Eq a => Int +</programlisting> + + +When a value with this type was used, the constraint <literal>Eq tv</literal> +would be introduced where <literal>tv</literal> is a fresh type variable, and +(in the dictionary-translation implementation) the value would be +applied to a dictionary for <literal>Eq tv</literal>. The difficulty is that we +can never know which instance of <literal>Eq</literal> to use because we never +get any more information about <literal>tv</literal>. +</para> +<para> +Note +that the reachability condition is weaker than saying that <literal>a</literal> is +functionally dependent on a type variable free in +<literal>type</literal> (see <xref +linkend="functional-dependencies"/>). The reason for this is there +might be a "hidden" dependency, in a superclass perhaps. So +"reachable" is a conservative approximation to "functionally dependent". +For example, consider: +<programlisting> + class C a b | a -> b where ... + class C a b => D a b where ... + f :: forall a b. D a b => a -> a +</programlisting> +This is fine, because in fact <literal>a</literal> does functionally determine <literal>b</literal> +but that is not immediately apparent from <literal>f</literal>'s type. +</para> +</listitem> +<listitem> + +<para> + <emphasis>Every constraint <literal>ci</literal> must mention at least one of the +universally quantified type variables <literal>tvi</literal></emphasis>. + +For example, this type is OK because <literal>C a b</literal> mentions the +universally quantified type variable <literal>b</literal>: + + +<programlisting> + forall a. C a b => burble +</programlisting> + + +The next type is illegal because the constraint <literal>Eq b</literal> does not +mention <literal>a</literal>: + + +<programlisting> + forall a. Eq b => burble +</programlisting> + + +The reason for this restriction is milder than the other one. The +excluded types are never useful or necessary (because the offending +context doesn't need to be witnessed at this point; it can be floated +out). Furthermore, floating them out increases sharing. Lastly, +excluding them is a conservative choice; it leaves a patch of +territory free in case we need it later. + +</para> +</listitem> + +</orderedlist> + +</para> +</sect3> + +<sect3 id="hoist"> +<title>For-all hoisting</title> +<para> +It is often convenient to use generalised type synonyms (see <xref linkend="type-synonyms"/>) at the right hand +end of an arrow, thus: +<programlisting> + type Discard a = forall b. a -> b -> a + + g :: Int -> Discard Int + g x y z = x+y +</programlisting> +Simply expanding the type synonym would give +<programlisting> + g :: Int -> (forall b. Int -> b -> Int) +</programlisting> +but GHC "hoists" the <literal>forall</literal> to give the isomorphic type +<programlisting> + g :: forall b. Int -> Int -> b -> Int +</programlisting> +In general, the rule is this: <emphasis>to determine the type specified by any explicit +user-written type (e.g. in a type signature), GHC expands type synonyms and then repeatedly +performs the transformation:</emphasis> +<programlisting> + <emphasis>type1</emphasis> -> forall a1..an. <emphasis>context2</emphasis> => <emphasis>type2</emphasis> +==> + forall a1..an. <emphasis>context2</emphasis> => <emphasis>type1</emphasis> -> <emphasis>type2</emphasis> +</programlisting> +(In fact, GHC tries to retain as much synonym information as possible for use in +error messages, but that is a usability issue.) This rule applies, of course, whether +or not the <literal>forall</literal> comes from a synonym. For example, here is another +valid way to write <literal>g</literal>'s type signature: +<programlisting> + g :: Int -> Int -> forall b. b -> Int +</programlisting> +</para> +<para> +When doing this hoisting operation, GHC eliminates duplicate constraints. For +example: +<programlisting> + type Foo a = (?x::Int) => Bool -> a + g :: Foo (Foo Int) +</programlisting> +means +<programlisting> + g :: (?x::Int) => Bool -> Bool -> Int +</programlisting> +</para> +</sect3> + + +</sect2> + +<sect2 id="implicit-parameters"> +<title>Implicit parameters</title> + +<para> Implicit parameters are implemented as described in +"Implicit parameters: dynamic scoping with static types", +J Lewis, MB Shields, E Meijer, J Launchbury, +27th ACM Symposium on Principles of Programming Languages (POPL'00), +Boston, Jan 2000. +</para> + +<para>(Most of the following, stil rather incomplete, documentation is +due to Jeff Lewis.)</para> + +<para>Implicit parameter support is enabled with the option +<option>-fimplicit-params</option>.</para> + +<para> +A variable is called <emphasis>dynamically bound</emphasis> when it is bound by the calling +context of a function and <emphasis>statically bound</emphasis> when bound by the callee's +context. In Haskell, all variables are statically bound. Dynamic +binding of variables is a notion that goes back to Lisp, but was later +discarded in more modern incarnations, such as Scheme. Dynamic binding +can be very confusing in an untyped language, and unfortunately, typed +languages, in particular Hindley-Milner typed languages like Haskell, +only support static scoping of variables. +</para> +<para> +However, by a simple extension to the type class system of Haskell, we +can support dynamic binding. Basically, we express the use of a +dynamically bound variable as a constraint on the type. These +constraints lead to types of the form <literal>(?x::t') => t</literal>, which says "this +function uses a dynamically-bound variable <literal>?x</literal> +of type <literal>t'</literal>". For +example, the following expresses the type of a sort function, +implicitly parameterized by a comparison function named <literal>cmp</literal>. +<programlisting> + sort :: (?cmp :: a -> a -> Bool) => [a] -> [a] +</programlisting> +The dynamic binding constraints are just a new form of predicate in the type class system. +</para> +<para> +An implicit parameter occurs in an expression using the special form <literal>?x</literal>, +where <literal>x</literal> is +any valid identifier (e.g. <literal>ord ?x</literal> is a valid expression). +Use of this construct also introduces a new +dynamic-binding constraint in the type of the expression. +For example, the following definition +shows how we can define an implicitly parameterized sort function in +terms of an explicitly parameterized <literal>sortBy</literal> function: +<programlisting> + sortBy :: (a -> a -> Bool) -> [a] -> [a] + + sort :: (?cmp :: a -> a -> Bool) => [a] -> [a] + sort = sortBy ?cmp +</programlisting> +</para> + +<sect3> +<title>Implicit-parameter type constraints</title> +<para> +Dynamic binding constraints behave just like other type class +constraints in that they are automatically propagated. Thus, when a +function is used, its implicit parameters are inherited by the +function that called it. For example, our <literal>sort</literal> function might be used +to pick out the least value in a list: +<programlisting> + least :: (?cmp :: a -> a -> Bool) => [a] -> a + least xs = fst (sort xs) +</programlisting> +Without lifting a finger, the <literal>?cmp</literal> parameter is +propagated to become a parameter of <literal>least</literal> as well. With explicit +parameters, the default is that parameters must always be explicit +propagated. With implicit parameters, the default is to always +propagate them. +</para> +<para> +An implicit-parameter type constraint differs from other type class constraints in the +following way: All uses of a particular implicit parameter must have +the same type. This means that the type of <literal>(?x, ?x)</literal> +is <literal>(?x::a) => (a,a)</literal>, and not +<literal>(?x::a, ?x::b) => (a, b)</literal>, as would be the case for type +class constraints. +</para> + +<para> You can't have an implicit parameter in the context of a class or instance +declaration. For example, both these declarations are illegal: +<programlisting> + class (?x::Int) => C a where ... + instance (?x::a) => Foo [a] where ... +</programlisting> +Reason: exactly which implicit parameter you pick up depends on exactly where +you invoke a function. But the ``invocation'' of instance declarations is done +behind the scenes by the compiler, so it's hard to figure out exactly where it is done. +Easiest thing is to outlaw the offending types.</para> +<para> +Implicit-parameter constraints do not cause ambiguity. For example, consider: +<programlisting> + f :: (?x :: [a]) => Int -> Int + f n = n + length ?x + + g :: (Read a, Show a) => String -> String + g s = show (read s) +</programlisting> +Here, <literal>g</literal> has an ambiguous type, and is rejected, but <literal>f</literal> +is fine. The binding for <literal>?x</literal> at <literal>f</literal>'s call site is +quite unambiguous, and fixes the type <literal>a</literal>. +</para> +</sect3> + +<sect3> +<title>Implicit-parameter bindings</title> + +<para> +An implicit parameter is <emphasis>bound</emphasis> using the standard +<literal>let</literal> or <literal>where</literal> binding forms. +For example, we define the <literal>min</literal> function by binding +<literal>cmp</literal>. +<programlisting> + min :: [a] -> a + min = let ?cmp = (<=) in least +</programlisting> +</para> +<para> +A group of implicit-parameter bindings may occur anywhere a normal group of Haskell +bindings can occur, except at top level. That is, they can occur in a <literal>let</literal> +(including in a list comprehension, or do-notation, or pattern guards), +or a <literal>where</literal> clause. +Note the following points: +<itemizedlist> +<listitem><para> +An implicit-parameter binding group must be a +collection of simple bindings to implicit-style variables (no +function-style bindings, and no type signatures); these bindings are +neither polymorphic or recursive. +</para></listitem> +<listitem><para> +You may not mix implicit-parameter bindings with ordinary bindings in a +single <literal>let</literal> +expression; use two nested <literal>let</literal>s instead. +(In the case of <literal>where</literal> you are stuck, since you can't nest <literal>where</literal> clauses.) +</para></listitem> + +<listitem><para> +You may put multiple implicit-parameter bindings in a +single binding group; but they are <emphasis>not</emphasis> treated +as a mutually recursive group (as ordinary <literal>let</literal> bindings are). +Instead they are treated as a non-recursive group, simultaneously binding all the implicit +parameter. The bindings are not nested, and may be re-ordered without changing +the meaning of the program. +For example, consider: +<programlisting> + f t = let { ?x = t; ?y = ?x+(1::Int) } in ?x + ?y +</programlisting> +The use of <literal>?x</literal> in the binding for <literal>?y</literal> does not "see" +the binding for <literal>?x</literal>, so the type of <literal>f</literal> is +<programlisting> + f :: (?x::Int) => Int -> Int +</programlisting> +</para></listitem> +</itemizedlist> +</para> + +</sect3> + +<sect3><title>Implicit parameters and polymorphic recursion</title> + +<para> +Consider these two definitions: +<programlisting> + len1 :: [a] -> Int + len1 xs = let ?acc = 0 in len_acc1 xs + + len_acc1 [] = ?acc + len_acc1 (x:xs) = let ?acc = ?acc + (1::Int) in len_acc1 xs + + ------------ + + len2 :: [a] -> Int + len2 xs = let ?acc = 0 in len_acc2 xs + + len_acc2 :: (?acc :: Int) => [a] -> Int + len_acc2 [] = ?acc + len_acc2 (x:xs) = let ?acc = ?acc + (1::Int) in len_acc2 xs +</programlisting> +The only difference between the two groups is that in the second group +<literal>len_acc</literal> is given a type signature. +In the former case, <literal>len_acc1</literal> is monomorphic in its own +right-hand side, so the implicit parameter <literal>?acc</literal> is not +passed to the recursive call. In the latter case, because <literal>len_acc2</literal> +has a type signature, the recursive call is made to the +<emphasis>polymoprhic</emphasis> version, which takes <literal>?acc</literal> +as an implicit parameter. So we get the following results in GHCi: +<programlisting> + Prog> len1 "hello" + 0 + Prog> len2 "hello" + 5 +</programlisting> +Adding a type signature dramatically changes the result! This is a rather +counter-intuitive phenomenon, worth watching out for. +</para> +</sect3> + +<sect3><title>Implicit parameters and monomorphism</title> + +<para>GHC applies the dreaded Monomorphism Restriction (section 4.5.5 of the +Haskell Report) to implicit parameters. For example, consider: +<programlisting> + f :: Int -> Int + f v = let ?x = 0 in + let y = ?x + v in + let ?x = 5 in + y +</programlisting> +Since the binding for <literal>y</literal> falls under the Monomorphism +Restriction it is not generalised, so the type of <literal>y</literal> is +simply <literal>Int</literal>, not <literal>(?x::Int) => Int</literal>. +Hence, <literal>(f 9)</literal> returns result <literal>9</literal>. +If you add a type signature for <literal>y</literal>, then <literal>y</literal> +will get type <literal>(?x::Int) => Int</literal>, so the occurrence of +<literal>y</literal> in the body of the <literal>let</literal> will see the +inner binding of <literal>?x</literal>, so <literal>(f 9)</literal> will return +<literal>14</literal>. +</para> +</sect3> +</sect2> + +<sect2 id="linear-implicit-parameters"> +<title>Linear implicit parameters</title> +<para> +Linear implicit parameters are an idea developed by Koen Claessen, +Mark Shields, and Simon PJ. They address the long-standing +problem that monads seem over-kill for certain sorts of problem, notably: +</para> +<itemizedlist> +<listitem> <para> distributing a supply of unique names </para> </listitem> +<listitem> <para> distributing a supply of random numbers </para> </listitem> +<listitem> <para> distributing an oracle (as in QuickCheck) </para> </listitem> +</itemizedlist> + +<para> +Linear implicit parameters are just like ordinary implicit parameters, +except that they are "linear" -- that is, they cannot be copied, and +must be explicitly "split" instead. Linear implicit parameters are +written '<literal>%x</literal>' instead of '<literal>?x</literal>'. +(The '/' in the '%' suggests the split!) +</para> +<para> +For example: +<programlisting> + import GHC.Exts( Splittable ) + + data NameSupply = ... + + splitNS :: NameSupply -> (NameSupply, NameSupply) + newName :: NameSupply -> Name + + instance Splittable NameSupply where + split = splitNS + + + f :: (%ns :: NameSupply) => Env -> Expr -> Expr + f env (Lam x e) = Lam x' (f env e) + where + x' = newName %ns + env' = extend env x x' + ...more equations for f... +</programlisting> +Notice that the implicit parameter %ns is consumed +<itemizedlist> +<listitem> <para> once by the call to <literal>newName</literal> </para> </listitem> +<listitem> <para> once by the recursive call to <literal>f</literal> </para></listitem> +</itemizedlist> +</para> +<para> +So the translation done by the type checker makes +the parameter explicit: +<programlisting> + f :: NameSupply -> Env -> Expr -> Expr + f ns env (Lam x e) = Lam x' (f ns1 env e) + where + (ns1,ns2) = splitNS ns + x' = newName ns2 + env = extend env x x' +</programlisting> +Notice the call to 'split' introduced by the type checker. +How did it know to use 'splitNS'? Because what it really did +was to introduce a call to the overloaded function 'split', +defined by the class <literal>Splittable</literal>: +<programlisting> + class Splittable a where + split :: a -> (a,a) +</programlisting> +The instance for <literal>Splittable NameSupply</literal> tells GHC how to implement +split for name supplies. But we can simply write +<programlisting> + g x = (x, %ns, %ns) +</programlisting> +and GHC will infer +<programlisting> + g :: (Splittable a, %ns :: a) => b -> (b,a,a) +</programlisting> +The <literal>Splittable</literal> class is built into GHC. It's exported by module +<literal>GHC.Exts</literal>. +</para> +<para> +Other points: +<itemizedlist> +<listitem> <para> '<literal>?x</literal>' and '<literal>%x</literal>' +are entirely distinct implicit parameters: you + can use them together and they won't intefere with each other. </para> +</listitem> + +<listitem> <para> You can bind linear implicit parameters in 'with' clauses. </para> </listitem> + +<listitem> <para>You cannot have implicit parameters (whether linear or not) + in the context of a class or instance declaration. </para></listitem> +</itemizedlist> +</para> + +<sect3><title>Warnings</title> + +<para> +The monomorphism restriction is even more important than usual. +Consider the example above: +<programlisting> + f :: (%ns :: NameSupply) => Env -> Expr -> Expr + f env (Lam x e) = Lam x' (f env e) + where + x' = newName %ns + env' = extend env x x' +</programlisting> +If we replaced the two occurrences of x' by (newName %ns), which is +usually a harmless thing to do, we get: +<programlisting> + f :: (%ns :: NameSupply) => Env -> Expr -> Expr + f env (Lam x e) = Lam (newName %ns) (f env e) + where + env' = extend env x (newName %ns) +</programlisting> +But now the name supply is consumed in <emphasis>three</emphasis> places +(the two calls to newName,and the recursive call to f), so +the result is utterly different. Urk! We don't even have +the beta rule. +</para> +<para> +Well, this is an experimental change. With implicit +parameters we have already lost beta reduction anyway, and +(as John Launchbury puts it) we can't sensibly reason about +Haskell programs without knowing their typing. +</para> + +</sect3> + +<sect3><title>Recursive functions</title> +<para>Linear implicit parameters can be particularly tricky when you have a recursive function +Consider +<programlisting> + foo :: %x::T => Int -> [Int] + foo 0 = [] + foo n = %x : foo (n-1) +</programlisting> +where T is some type in class Splittable.</para> +<para> +Do you get a list of all the same T's or all different T's +(assuming that split gives two distinct T's back)? +</para><para> +If you supply the type signature, taking advantage of polymorphic +recursion, you get what you'd probably expect. Here's the +translated term, where the implicit param is made explicit: +<programlisting> + foo x 0 = [] + foo x n = let (x1,x2) = split x + in x1 : foo x2 (n-1) +</programlisting> +But if you don't supply a type signature, GHC uses the Hindley +Milner trick of using a single monomorphic instance of the function +for the recursive calls. That is what makes Hindley Milner type inference +work. So the translation becomes +<programlisting> + foo x = let + foom 0 = [] + foom n = x : foom (n-1) + in + foom +</programlisting> +Result: 'x' is not split, and you get a list of identical T's. So the +semantics of the program depends on whether or not foo has a type signature. +Yikes! +</para><para> +You may say that this is a good reason to dislike linear implicit parameters +and you'd be right. That is why they are an experimental feature. +</para> +</sect3> + +</sect2> + +<sect2 id="sec-kinding"> +<title>Explicitly-kinded quantification</title> + +<para> +Haskell infers the kind of each type variable. Sometimes it is nice to be able +to give the kind explicitly as (machine-checked) documentation, +just as it is nice to give a type signature for a function. On some occasions, +it is essential to do so. For example, in his paper "Restricted Data Types in Haskell" (Haskell Workshop 1999) +John Hughes had to define the data type: +<screen> + data Set cxt a = Set [a] + | Unused (cxt a -> ()) +</screen> +The only use for the <literal>Unused</literal> constructor was to force the correct +kind for the type variable <literal>cxt</literal>. +</para> +<para> +GHC now instead allows you to specify the kind of a type variable directly, wherever +a type variable is explicitly bound. Namely: +<itemizedlist> +<listitem><para><literal>data</literal> declarations: +<screen> + data Set (cxt :: * -> *) a = Set [a] +</screen></para></listitem> +<listitem><para><literal>type</literal> declarations: +<screen> + type T (f :: * -> *) = f Int +</screen></para></listitem> +<listitem><para><literal>class</literal> declarations: +<screen> + class (Eq a) => C (f :: * -> *) a where ... +</screen></para></listitem> +<listitem><para><literal>forall</literal>'s in type signatures: +<screen> + f :: forall (cxt :: * -> *). Set cxt Int +</screen></para></listitem> +</itemizedlist> +</para> + +<para> +The parentheses are required. Some of the spaces are required too, to +separate the lexemes. If you write <literal>(f::*->*)</literal> you +will get a parse error, because "<literal>::*->*</literal>" is a +single lexeme in Haskell. +</para> + +<para> +As part of the same extension, you can put kind annotations in types +as well. Thus: +<screen> + f :: (Int :: *) -> Int + g :: forall a. a -> (a :: *) +</screen> +The syntax is +<screen> + atype ::= '(' ctype '::' kind ') +</screen> +The parentheses are required. +</para> +</sect2> + + +<sect2 id="universal-quantification"> +<title>Arbitrary-rank polymorphism +</title> + +<para> +Haskell type signatures are implicitly quantified. The new keyword <literal>forall</literal> +allows us to say exactly what this means. For example: +</para> +<para> +<programlisting> + g :: b -> b +</programlisting> +means this: +<programlisting> + g :: forall b. (b -> b) +</programlisting> +The two are treated identically. +</para> + +<para> +However, GHC's type system supports <emphasis>arbitrary-rank</emphasis> +explicit universal quantification in +types. +For example, all the following types are legal: +<programlisting> + f1 :: forall a b. a -> b -> a + g1 :: forall a b. (Ord a, Eq b) => a -> b -> a + + f2 :: (forall a. a->a) -> Int -> Int + g2 :: (forall a. Eq a => [a] -> a -> Bool) -> Int -> Int + + f3 :: ((forall a. a->a) -> Int) -> Bool -> Bool +</programlisting> +Here, <literal>f1</literal> and <literal>g1</literal> are rank-1 types, and +can be written in standard Haskell (e.g. <literal>f1 :: a->b->a</literal>). +The <literal>forall</literal> makes explicit the universal quantification that +is implicitly added by Haskell. +</para> +<para> +The functions <literal>f2</literal> and <literal>g2</literal> have rank-2 types; +the <literal>forall</literal> is on the left of a function arrow. As <literal>g2</literal> +shows, the polymorphic type on the left of the function arrow can be overloaded. +</para> +<para> +The function <literal>f3</literal> has a rank-3 type; +it has rank-2 types on the left of a function arrow. +</para> +<para> +GHC allows types of arbitrary rank; you can nest <literal>forall</literal>s +arbitrarily deep in function arrows. (GHC used to be restricted to rank 2, but +that restriction has now been lifted.) +In particular, a forall-type (also called a "type scheme"), +including an operational type class context, is legal: +<itemizedlist> +<listitem> <para> On the left of a function arrow </para> </listitem> +<listitem> <para> On the right of a function arrow (see <xref linkend="hoist"/>) </para> </listitem> +<listitem> <para> As the argument of a constructor, or type of a field, in a data type declaration. For +example, any of the <literal>f1,f2,f3,g1,g2</literal> above would be valid +field type signatures.</para> </listitem> +<listitem> <para> As the type of an implicit parameter </para> </listitem> +<listitem> <para> In a pattern type signature (see <xref linkend="scoped-type-variables"/>) </para> </listitem> +</itemizedlist> +There is one place you cannot put a <literal>forall</literal>: +you cannot instantiate a type variable with a forall-type. So you cannot +make a forall-type the argument of a type constructor. So these types are illegal: +<programlisting> + x1 :: [forall a. a->a] + x2 :: (forall a. a->a, Int) + x3 :: Maybe (forall a. a->a) +</programlisting> +Of course <literal>forall</literal> becomes a keyword; you can't use <literal>forall</literal> as +a type variable any more! +</para> + + +<sect3 id="univ"> +<title>Examples +</title> + +<para> +In a <literal>data</literal> or <literal>newtype</literal> declaration one can quantify +the types of the constructor arguments. Here are several examples: +</para> + +<para> + +<programlisting> +data T a = T1 (forall b. b -> b -> b) a + +data MonadT m = MkMonad { return :: forall a. a -> m a, + bind :: forall a b. m a -> (a -> m b) -> m b + } + +newtype Swizzle = MkSwizzle (Ord a => [a] -> [a]) +</programlisting> + +</para> + +<para> +The constructors have rank-2 types: +</para> + +<para> + +<programlisting> +T1 :: forall a. (forall b. b -> b -> b) -> a -> T a +MkMonad :: forall m. (forall a. a -> m a) + -> (forall a b. m a -> (a -> m b) -> m b) + -> MonadT m +MkSwizzle :: (Ord a => [a] -> [a]) -> Swizzle +</programlisting> + +</para> + +<para> +Notice that you don't need to use a <literal>forall</literal> if there's an +explicit context. For example in the first argument of the +constructor <function>MkSwizzle</function>, an implicit "<literal>forall a.</literal>" is +prefixed to the argument type. The implicit <literal>forall</literal> +quantifies all type variables that are not already in scope, and are +mentioned in the type quantified over. +</para> + +<para> +As for type signatures, implicit quantification happens for non-overloaded +types too. So if you write this: + +<programlisting> + data T a = MkT (Either a b) (b -> b) +</programlisting> + +it's just as if you had written this: + +<programlisting> + data T a = MkT (forall b. Either a b) (forall b. b -> b) +</programlisting> + +That is, since the type variable <literal>b</literal> isn't in scope, it's +implicitly universally quantified. (Arguably, it would be better +to <emphasis>require</emphasis> explicit quantification on constructor arguments +where that is what is wanted. Feedback welcomed.) +</para> + +<para> +You construct values of types <literal>T1, MonadT, Swizzle</literal> by applying +the constructor to suitable values, just as usual. For example, +</para> + +<para> + +<programlisting> + a1 :: T Int + a1 = T1 (\xy->x) 3 + + a2, a3 :: Swizzle + a2 = MkSwizzle sort + a3 = MkSwizzle reverse + + a4 :: MonadT Maybe + a4 = let r x = Just x + b m k = case m of + Just y -> k y + Nothing -> Nothing + in + MkMonad r b + + mkTs :: (forall b. b -> b -> b) -> a -> [T a] + mkTs f x y = [T1 f x, T1 f y] +</programlisting> + +</para> + +<para> +The type of the argument can, as usual, be more general than the type +required, as <literal>(MkSwizzle reverse)</literal> shows. (<function>reverse</function> +does not need the <literal>Ord</literal> constraint.) +</para> + +<para> +When you use pattern matching, the bound variables may now have +polymorphic types. For example: +</para> + +<para> + +<programlisting> + f :: T a -> a -> (a, Char) + f (T1 w k) x = (w k x, w 'c' 'd') + + g :: (Ord a, Ord b) => Swizzle -> [a] -> (a -> b) -> [b] + g (MkSwizzle s) xs f = s (map f (s xs)) + + h :: MonadT m -> [m a] -> m [a] + h m [] = return m [] + h m (x:xs) = bind m x $ \y -> + bind m (h m xs) $ \ys -> + return m (y:ys) +</programlisting> + +</para> + +<para> +In the function <function>h</function> we use the record selectors <literal>return</literal> +and <literal>bind</literal> to extract the polymorphic bind and return functions +from the <literal>MonadT</literal> data structure, rather than using pattern +matching. +</para> +</sect3> + +<sect3> +<title>Type inference</title> + +<para> +In general, type inference for arbitrary-rank types is undecidable. +GHC uses an algorithm proposed by Odersky and Laufer ("Putting type annotations to work", POPL'96) +to get a decidable algorithm by requiring some help from the programmer. +We do not yet have a formal specification of "some help" but the rule is this: +</para> +<para> +<emphasis>For a lambda-bound or case-bound variable, x, either the programmer +provides an explicit polymorphic type for x, or GHC's type inference will assume +that x's type has no foralls in it</emphasis>. +</para> +<para> +What does it mean to "provide" an explicit type for x? You can do that by +giving a type signature for x directly, using a pattern type signature +(<xref linkend="scoped-type-variables"/>), thus: +<programlisting> + \ f :: (forall a. a->a) -> (f True, f 'c') +</programlisting> +Alternatively, you can give a type signature to the enclosing +context, which GHC can "push down" to find the type for the variable: +<programlisting> + (\ f -> (f True, f 'c')) :: (forall a. a->a) -> (Bool,Char) +</programlisting> +Here the type signature on the expression can be pushed inwards +to give a type signature for f. Similarly, and more commonly, +one can give a type signature for the function itself: +<programlisting> + h :: (forall a. a->a) -> (Bool,Char) + h f = (f True, f 'c') +</programlisting> +You don't need to give a type signature if the lambda bound variable +is a constructor argument. Here is an example we saw earlier: +<programlisting> + f :: T a -> a -> (a, Char) + f (T1 w k) x = (w k x, w 'c' 'd') +</programlisting> +Here we do not need to give a type signature to <literal>w</literal>, because +it is an argument of constructor <literal>T1</literal> and that tells GHC all +it needs to know. +</para> + +</sect3> + + +<sect3 id="implicit-quant"> +<title>Implicit quantification</title> + +<para> +GHC performs implicit quantification as follows. <emphasis>At the top level (only) of +user-written types, if and only if there is no explicit <literal>forall</literal>, +GHC finds all the type variables mentioned in the type that are not already +in scope, and universally quantifies them.</emphasis> For example, the following pairs are +equivalent: +<programlisting> + f :: a -> a + f :: forall a. a -> a + + g (x::a) = let + h :: a -> b -> b + h x y = y + in ... + g (x::a) = let + h :: forall b. a -> b -> b + h x y = y + in ... +</programlisting> +</para> +<para> +Notice that GHC does <emphasis>not</emphasis> find the innermost possible quantification +point. For example: +<programlisting> + f :: (a -> a) -> Int + -- MEANS + f :: forall a. (a -> a) -> Int + -- NOT + f :: (forall a. a -> a) -> Int + + + g :: (Ord a => a -> a) -> Int + -- MEANS the illegal type + g :: forall a. (Ord a => a -> a) -> Int + -- NOT + g :: (forall a. Ord a => a -> a) -> Int +</programlisting> +The latter produces an illegal type, which you might think is silly, +but at least the rule is simple. If you want the latter type, you +can write your for-alls explicitly. Indeed, doing so is strongly advised +for rank-2 types. +</para> +</sect3> +</sect2> + + + + +<sect2 id="scoped-type-variables"> +<title>Scoped type variables +</title> + +<para> +A <emphasis>lexically scoped type variable</emphasis> can be bound by: +<itemizedlist> +<listitem><para>A declaration type signature (<xref linkend="decl-type-sigs"/>)</para></listitem> +<listitem><para>A pattern type signature (<xref linkend="pattern-type-sigs"/>)</para></listitem> +<listitem><para>A result type signature (<xref linkend="result-type-sigs"/>)</para></listitem> +</itemizedlist> +For example: +<programlisting> +f (xs::[a]) = ys ++ ys + where + ys :: [a] + ys = reverse xs +</programlisting> +The pattern <literal>(xs::[a])</literal> includes a type signature for <varname>xs</varname>. +This brings the type variable <literal>a</literal> into scope; it scopes over +all the patterns and right hand sides for this equation for <function>f</function>. +In particular, it is in scope at the type signature for <varname>y</varname>. +</para> + +<para> +At ordinary type signatures, such as that for <varname>ys</varname>, any type variables +mentioned in the type signature <emphasis>that are not in scope</emphasis> are +implicitly universally quantified. (If there are no type variables in +scope, all type variables mentioned in the signature are universally +quantified, which is just as in Haskell 98.) In this case, since <varname>a</varname> +is in scope, it is not universally quantified, so the type of <varname>ys</varname> is +the same as that of <varname>xs</varname>. In Haskell 98 it is not possible to declare +a type for <varname>ys</varname>; a major benefit of scoped type variables is that +it becomes possible to do so. +</para> + +<para> +Scoped type variables are implemented in both GHC and Hugs. Where the +implementations differ from the specification below, those differences +are noted. +</para> + +<para> +So much for the basic idea. Here are the details. +</para> + +<sect3> +<title>What a scoped type variable means</title> +<para> +A lexically-scoped type variable is simply +the name for a type. The restriction it expresses is that all occurrences +of the same name mean the same type. For example: +<programlisting> + f :: [Int] -> Int -> Int + f (xs::[a]) (y::a) = (head xs + y) :: a +</programlisting> +The pattern type signatures on the left hand side of +<literal>f</literal> express the fact that <literal>xs</literal> +must be a list of things of some type <literal>a</literal>; and that <literal>y</literal> +must have this same type. The type signature on the expression <literal>(head xs)</literal> +specifies that this expression must have the same type <literal>a</literal>. +<emphasis>There is no requirement that the type named by "<literal>a</literal>" is +in fact a type variable</emphasis>. Indeed, in this case, the type named by "<literal>a</literal>" is +<literal>Int</literal>. (This is a slight liberalisation from the original rather complex +rules, which specified that a pattern-bound type variable should be universally quantified.) +For example, all of these are legal:</para> + +<programlisting> + t (x::a) (y::a) = x+y*2 + + f (x::a) (y::b) = [x,y] -- a unifies with b + + g (x::a) = x + 1::Int -- a unifies with Int + + h x = let k (y::a) = [x,y] -- a is free in the + in k x -- environment + + k (x::a) True = ... -- a unifies with Int + k (x::Int) False = ... + + w :: [b] -> [b] + w (x::a) = x -- a unifies with [b] +</programlisting> + +</sect3> + +<sect3> +<title>Scope and implicit quantification</title> + +<para> + +<itemizedlist> +<listitem> + +<para> +All the type variables mentioned in a pattern, +that are not already in scope, +are brought into scope by the pattern. We describe this set as +the <emphasis>type variables bound by the pattern</emphasis>. +For example: +<programlisting> + f (x::a) = let g (y::(a,b)) = fst y + in + g (x,True) +</programlisting> +The pattern <literal>(x::a)</literal> brings the type variable +<literal>a</literal> into scope, as well as the term +variable <literal>x</literal>. The pattern <literal>(y::(a,b))</literal> +contains an occurrence of the already-in-scope type variable <literal>a</literal>, +and brings into scope the type variable <literal>b</literal>. +</para> +</listitem> + +<listitem> +<para> +The type variable(s) bound by the pattern have the same scope +as the term variable(s) bound by the pattern. For example: +<programlisting> + let + f (x::a) = <...rhs of f...> + (p::b, q::b) = (1,2) + in <...body of let...> +</programlisting> +Here, the type variable <literal>a</literal> scopes over the right hand side of <literal>f</literal>, +just like <literal>x</literal> does; while the type variable <literal>b</literal> scopes over the +body of the <literal>let</literal>, and all the other definitions in the <literal>let</literal>, +just like <literal>p</literal> and <literal>q</literal> do. +Indeed, the newly bound type variables also scope over any ordinary, separate +type signatures in the <literal>let</literal> group. +</para> +</listitem> + + +<listitem> +<para> +The type variables bound by the pattern may be +mentioned in ordinary type signatures or pattern +type signatures anywhere within their scope. + +</para> +</listitem> + +<listitem> +<para> + In ordinary type signatures, any type variable mentioned in the +signature that is in scope is <emphasis>not</emphasis> universally quantified. + +</para> +</listitem> + +<listitem> + +<para> + Ordinary type signatures do not bring any new type variables +into scope (except in the type signature itself!). So this is illegal: + +<programlisting> + f :: a -> a + f x = x::a +</programlisting> + +It's illegal because <varname>a</varname> is not in scope in the body of <function>f</function>, +so the ordinary signature <literal>x::a</literal> is equivalent to <literal>x::forall a.a</literal>; +and that is an incorrect typing. + +</para> +</listitem> + +<listitem> +<para> +The pattern type signature is a monotype: +</para> + +<itemizedlist> +<listitem> <para> +A pattern type signature cannot contain any explicit <literal>forall</literal> quantification. +</para> </listitem> + +<listitem> <para> +The type variables bound by a pattern type signature can only be instantiated to monotypes, +not to type schemes. +</para> </listitem> + +<listitem> <para> +There is no implicit universal quantification on pattern type signatures (in contrast to +ordinary type signatures). +</para> </listitem> + +</itemizedlist> + +</listitem> + +<listitem> +<para> + +The type variables in the head of a <literal>class</literal> or <literal>instance</literal> declaration +scope over the methods defined in the <literal>where</literal> part. For example: + + +<programlisting> + class C a where + op :: [a] -> a + + op xs = let ys::[a] + ys = reverse xs + in + head ys +</programlisting> + + +(Not implemented in Hugs yet, Dec 98). +</para> +</listitem> + +</itemizedlist> + +</para> + +</sect3> + +<sect3 id="decl-type-sigs"> +<title>Declaration type signatures</title> +<para>A declaration type signature that has <emphasis>explicit</emphasis> +quantification (using <literal>forall</literal>) brings into scope the +explicitly-quantified +type variables, in the definition of the named function(s). For example: +<programlisting> + f :: forall a. [a] -> [a] + f (x:xs) = xs ++ [ x :: a ] +</programlisting> +The "<literal>forall a</literal>" brings "<literal>a</literal>" into scope in +the definition of "<literal>f</literal>". +</para> +<para>This only happens if the quantification in <literal>f</literal>'s type +signature is explicit. For example: +<programlisting> + g :: [a] -> [a] + g (x:xs) = xs ++ [ x :: a ] +</programlisting> +This program will be rejected, because "<literal>a</literal>" does not scope +over the definition of "<literal>f</literal>", so "<literal>x::a</literal>" +means "<literal>x::forall a. a</literal>" by Haskell's usual implicit +quantification rules. +</para> +</sect3> + +<sect3 id="pattern-type-sigs"> +<title>Where a pattern type signature can occur</title> + +<para> +A pattern type signature can occur in any pattern. For example: +<itemizedlist> + +<listitem> +<para> +A pattern type signature can be on an arbitrary sub-pattern, not +just on a variable: + + +<programlisting> + f ((x,y)::(a,b)) = (y,x) :: (b,a) +</programlisting> + + +</para> +</listitem> +<listitem> + +<para> + Pattern type signatures, including the result part, can be used +in lambda abstractions: + +<programlisting> + (\ (x::a, y) :: a -> x) +</programlisting> +</para> +</listitem> +<listitem> + +<para> + Pattern type signatures, including the result part, can be used +in <literal>case</literal> expressions: + +<programlisting> + case e of { ((x::a, y) :: (a,b)) -> x } +</programlisting> + +Note that the <literal>-></literal> symbol in a case alternative +leads to difficulties when parsing a type signature in the pattern: in +the absence of the extra parentheses in the example above, the parser +would try to interpret the <literal>-></literal> as a function +arrow and give a parse error later. + +</para> + +</listitem> + +<listitem> +<para> +To avoid ambiguity, the type after the “<literal>::</literal>” in a result +pattern signature on a lambda or <literal>case</literal> must be atomic (i.e. a single +token or a parenthesised type of some sort). To see why, +consider how one would parse this: + + +<programlisting> + \ x :: a -> b -> x +</programlisting> + + +</para> +</listitem> + +<listitem> + +<para> + Pattern type signatures can bind existential type variables. +For example: + + +<programlisting> + data T = forall a. MkT [a] + + f :: T -> T + f (MkT [t::a]) = MkT t3 + where + t3::[a] = [t,t,t] +</programlisting> + + +</para> +</listitem> + + +<listitem> + +<para> +Pattern type signatures +can be used in pattern bindings: + +<programlisting> + f x = let (y, z::a) = x in ... + f1 x = let (y, z::Int) = x in ... + f2 (x::(Int,a)) = let (y, z::a) = x in ... + f3 :: (b->b) = \x -> x +</programlisting> + +In all such cases, the binding is not generalised over the pattern-bound +type variables. Thus <literal>f3</literal> is monomorphic; <literal>f3</literal> +has type <literal>b -> b</literal> for some type <literal>b</literal>, +and <emphasis>not</emphasis> <literal>forall b. b -> b</literal>. +In contrast, the binding +<programlisting> + f4 :: b->b + f4 = \x -> x +</programlisting> +makes a polymorphic function, but <literal>b</literal> is not in scope anywhere +in <literal>f4</literal>'s scope. + +</para> +</listitem> +</itemizedlist> +</para> +<para>Pattern type signatures are completely orthogonal to ordinary, separate +type signatures. The two can be used independently or together.</para> + +</sect3> + +<sect3 id="result-type-sigs"> +<title>Result type signatures</title> + +<para> +The result type of a function can be given a signature, thus: + + +<programlisting> + f (x::a) :: [a] = [x,x,x] +</programlisting> + + +The final <literal>:: [a]</literal> after all the patterns gives a signature to the +result type. Sometimes this is the only way of naming the type variable +you want: + + +<programlisting> + f :: Int -> [a] -> [a] + f n :: ([a] -> [a]) = let g (x::a, y::a) = (y,x) + in \xs -> map g (reverse xs `zip` xs) +</programlisting> + +</para> +<para> +The type variables bound in a result type signature scope over the right hand side +of the definition. However, consider this corner-case: +<programlisting> + rev1 :: [a] -> [a] = \xs -> reverse xs + + foo ys = rev (ys::[a]) +</programlisting> +The signature on <literal>rev1</literal> is considered a pattern type signature, not a result +type signature, and the type variables it binds have the same scope as <literal>rev1</literal> +itself (i.e. the right-hand side of <literal>rev1</literal> and the rest of the module too). +In particular, the expression <literal>(ys::[a])</literal> is OK, because the type variable <literal>a</literal> +is in scope (otherwise it would mean <literal>(ys::forall a.[a])</literal>, which would be rejected). +</para> +<para> +As mentioned above, <literal>rev1</literal> is made monomorphic by this scoping rule. +For example, the following program would be rejected, because it claims that <literal>rev1</literal> +is polymorphic: +<programlisting> + rev1 :: [b] -> [b] + rev1 :: [a] -> [a] = \xs -> reverse xs +</programlisting> +</para> + +<para> +Result type signatures are not yet implemented in Hugs. +</para> + +</sect3> + +</sect2> + +<sect2 id="deriving-typeable"> +<title>Deriving clause for classes <literal>Typeable</literal> and <literal>Data</literal></title> + +<para> +Haskell 98 allows the programmer to add "<literal>deriving( Eq, Ord )</literal>" to a data type +declaration, to generate a standard instance declaration for classes specified in the <literal>deriving</literal> clause. +In Haskell 98, the only classes that may appear in the <literal>deriving</literal> clause are the standard +classes <literal>Eq</literal>, <literal>Ord</literal>, +<literal>Enum</literal>, <literal>Ix</literal>, <literal>Bounded</literal>, <literal>Read</literal>, and <literal>Show</literal>. +</para> +<para> +GHC extends this list with two more classes that may be automatically derived +(provided the <option>-fglasgow-exts</option> flag is specified): +<literal>Typeable</literal>, and <literal>Data</literal>. These classes are defined in the library +modules <literal>Data.Typeable</literal> and <literal>Data.Generics</literal> respectively, and the +appropriate class must be in scope before it can be mentioned in the <literal>deriving</literal> clause. +</para> +<para>An instance of <literal>Typeable</literal> can only be derived if the +data type has seven or fewer type parameters, all of kind <literal>*</literal>. +The reason for this is that the <literal>Typeable</literal> class is derived using the scheme +described in +<ulink url="http://research.microsoft.com/%7Esimonpj/papers/hmap/gmap2.ps"> +Scrap More Boilerplate: Reflection, Zips, and Generalised Casts +</ulink>. +(Section 7.4 of the paper describes the multiple <literal>Typeable</literal> classes that +are used, and only <literal>Typeable1</literal> up to +<literal>Typeable7</literal> are provided in the library.) +In other cases, there is nothing to stop the programmer writing a <literal>TypableX</literal> +class, whose kind suits that of the data type constructor, and +then writing the data type instance by hand. +</para> +</sect2> + +<sect2 id="newtype-deriving"> +<title>Generalised derived instances for newtypes</title> + +<para> +When you define an abstract type using <literal>newtype</literal>, you may want +the new type to inherit some instances from its representation. In +Haskell 98, you can inherit instances of <literal>Eq</literal>, <literal>Ord</literal>, +<literal>Enum</literal> and <literal>Bounded</literal> by deriving them, but for any +other classes you have to write an explicit instance declaration. For +example, if you define + +<programlisting> + newtype Dollars = Dollars Int +</programlisting> + +and you want to use arithmetic on <literal>Dollars</literal>, you have to +explicitly define an instance of <literal>Num</literal>: + +<programlisting> + instance Num Dollars where + Dollars a + Dollars b = Dollars (a+b) + ... +</programlisting> +All the instance does is apply and remove the <literal>newtype</literal> +constructor. It is particularly galling that, since the constructor +doesn't appear at run-time, this instance declaration defines a +dictionary which is <emphasis>wholly equivalent</emphasis> to the <literal>Int</literal> +dictionary, only slower! +</para> + + +<sect3> <title> Generalising the deriving clause </title> +<para> +GHC now permits such instances to be derived instead, so one can write +<programlisting> + newtype Dollars = Dollars Int deriving (Eq,Show,Num) +</programlisting> + +and the implementation uses the <emphasis>same</emphasis> <literal>Num</literal> dictionary +for <literal>Dollars</literal> as for <literal>Int</literal>. Notionally, the compiler +derives an instance declaration of the form + +<programlisting> + instance Num Int => Num Dollars +</programlisting> + +which just adds or removes the <literal>newtype</literal> constructor according to the type. +</para> +<para> + +We can also derive instances of constructor classes in a similar +way. For example, suppose we have implemented state and failure monad +transformers, such that + +<programlisting> + instance Monad m => Monad (State s m) + instance Monad m => Monad (Failure m) +</programlisting> +In Haskell 98, we can define a parsing monad by +<programlisting> + type Parser tok m a = State [tok] (Failure m) a +</programlisting> + +which is automatically a monad thanks to the instance declarations +above. With the extension, we can make the parser type abstract, +without needing to write an instance of class <literal>Monad</literal>, via + +<programlisting> + newtype Parser tok m a = Parser (State [tok] (Failure m) a) + deriving Monad +</programlisting> +In this case the derived instance declaration is of the form +<programlisting> + instance Monad (State [tok] (Failure m)) => Monad (Parser tok m) +</programlisting> + +Notice that, since <literal>Monad</literal> is a constructor class, the +instance is a <emphasis>partial application</emphasis> of the new type, not the +entire left hand side. We can imagine that the type declaration is +``eta-converted'' to generate the context of the instance +declaration. +</para> +<para> + +We can even derive instances of multi-parameter classes, provided the +newtype is the last class parameter. In this case, a ``partial +application'' of the class appears in the <literal>deriving</literal> +clause. For example, given the class + +<programlisting> + class StateMonad s m | m -> s where ... + instance Monad m => StateMonad s (State s m) where ... +</programlisting> +then we can derive an instance of <literal>StateMonad</literal> for <literal>Parser</literal>s by +<programlisting> + newtype Parser tok m a = Parser (State [tok] (Failure m) a) + deriving (Monad, StateMonad [tok]) +</programlisting> + +The derived instance is obtained by completing the application of the +class to the new type: + +<programlisting> + instance StateMonad [tok] (State [tok] (Failure m)) => + StateMonad [tok] (Parser tok m) +</programlisting> +</para> +<para> + +As a result of this extension, all derived instances in newtype + declarations are treated uniformly (and implemented just by reusing +the dictionary for the representation type), <emphasis>except</emphasis> +<literal>Show</literal> and <literal>Read</literal>, which really behave differently for +the newtype and its representation. +</para> +</sect3> + +<sect3> <title> A more precise specification </title> +<para> +Derived instance declarations are constructed as follows. Consider the +declaration (after expansion of any type synonyms) + +<programlisting> + newtype T v1...vn = T' (S t1...tk vk+1...vn) deriving (c1...cm) +</programlisting> + +where + <itemizedlist> +<listitem><para> + <literal>S</literal> is a type constructor, +</para></listitem> +<listitem><para> + The <literal>t1...tk</literal> are types, +</para></listitem> +<listitem><para> + The <literal>vk+1...vn</literal> are type variables which do not occur in any of + the <literal>ti</literal>, and +</para></listitem> +<listitem><para> + The <literal>ci</literal> are partial applications of + classes of the form <literal>C t1'...tj'</literal>, where the arity of <literal>C</literal> + is exactly <literal>j+1</literal>. That is, <literal>C</literal> lacks exactly one type argument. +</para></listitem> +<listitem><para> + None of the <literal>ci</literal> is <literal>Read</literal>, <literal>Show</literal>, + <literal>Typeable</literal>, or <literal>Data</literal>. 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. +</para></listitem> +</itemizedlist> +Then, for each <literal>ci</literal>, the derived instance +declaration is: +<programlisting> + instance ci (S t1...tk vk+1...v) => ci (T v1...vp) +</programlisting> +where <literal>p</literal> is chosen so that <literal>T v1...vp</literal> is of the +right <emphasis>kind</emphasis> for the last parameter of class <literal>Ci</literal>. +</para> +<para> + +As an example which does <emphasis>not</emphasis> work, consider +<programlisting> + newtype NonMonad m s = NonMonad (State s m s) deriving Monad +</programlisting> +Here we cannot derive the instance +<programlisting> + instance Monad (State s m) => Monad (NonMonad m) +</programlisting> + +because the type variable <literal>s</literal> occurs in <literal>State s m</literal>, +and so cannot be "eta-converted" away. It is a good thing that this +<literal>deriving</literal> clause is rejected, because <literal>NonMonad m</literal> is +not, in fact, a monad --- for the same reason. Try defining +<literal>>>=</literal> with the correct type: you won't be able to. +</para> +<para> + +Notice also that the <emphasis>order</emphasis> of class parameters becomes +important, since we can only derive instances for the last one. If the +<literal>StateMonad</literal> class above were instead defined as + +<programlisting> + class StateMonad m s | m -> s where ... +</programlisting> + +then we would not have been able to derive an instance for the +<literal>Parser</literal> type above. We hypothesise that multi-parameter +classes usually have one "main" parameter for which deriving new +instances is most interesting. +</para> +<para>Lastly, all of this applies only for classes other than +<literal>Read</literal>, <literal>Show</literal>, <literal>Typeable</literal>, +and <literal>Data</literal>, for which the built-in derivation applies (section +4.3.3. of the Haskell Report). +(For the standard classes <literal>Eq</literal>, <literal>Ord</literal>, +<literal>Ix</literal>, and <literal>Bounded</literal> it is immaterial whether +the standard method is used or the one described here.) +</para> +</sect3> + +</sect2> + +<sect2 id="typing-binds"> +<title>Generalised typing of mutually recursive bindings</title> + +<para> +The Haskell Report specifies that a group of bindings (at top level, or in a +<literal>let</literal> or <literal>where</literal>) should be sorted into +strongly-connected components, and then type-checked in dependency order +(<ulink url="http://haskell.org/onlinereport/decls.html#sect4.5.1">Haskell +Report, Section 4.5.1</ulink>). +As each group is type-checked, any binders of the group that +have +an explicit type signature are put in the type environment with the specified +polymorphic type, +and all others are monomorphic until the group is generalised +(<ulink url="http://haskell.org/onlinereport/decls.html#sect4.5.2">Haskell Report, Section 4.5.2</ulink>). +</para> + +<para>Following a suggestion of Mark Jones, in his paper +<ulink url="http://www.cse.ogi.edu/~mpj/thih/">Typing Haskell in +Haskell</ulink>, +GHC implements a more general scheme. If <option>-fglasgow-exts</option> is +specified: +<emphasis>the dependency analysis ignores references to variables that have an explicit +type signature</emphasis>. +As a result of this refined dependency analysis, the dependency groups are smaller, and more bindings will +typecheck. For example, consider: +<programlisting> + f :: Eq a => a -> Bool + f x = (x == x) || g True || g "Yes" + + g y = (y <= y) || f True +</programlisting> +This is rejected by Haskell 98, but under Jones's scheme the definition for +<literal>g</literal> is typechecked first, separately from that for +<literal>f</literal>, +because the reference to <literal>f</literal> in <literal>g</literal>'s right +hand side is ingored by the dependency analysis. Then <literal>g</literal>'s +type is generalised, to get +<programlisting> + g :: Ord a => a -> Bool +</programlisting> +Now, the defintion for <literal>f</literal> is typechecked, with this type for +<literal>g</literal> in the type environment. +</para> + +<para> +The same refined dependency analysis also allows the type signatures of +mutually-recursive functions to have different contexts, something that is illegal in +Haskell 98 (Section 4.5.2, last sentence). With +<option>-fglasgow-exts</option> +GHC only insists that the type signatures of a <emphasis>refined</emphasis> group have identical +type signatures; in practice this means that only variables bound by the same +pattern binding must have the same context. For example, this is fine: +<programlisting> + f :: Eq a => a -> Bool + f x = (x == x) || g True + + g :: Ord a => a -> Bool + g y = (y <= y) || f True +</programlisting> +</para> +</sect2> + +</sect1> +<!-- ==================== End of type system extensions ================= --> + +<!-- ====================== Generalised algebraic data types ======================= --> + +<sect1 id="gadt"> +<title>Generalised Algebraic Data Types</title> + +<para>Generalised Algebraic Data Types (GADTs) generalise ordinary algebraic data types by allowing you +to give the type signatures of constructors explicitly. For example: +<programlisting> + data Term a where + Lit :: Int -> Term Int + Succ :: Term Int -> Term Int + IsZero :: Term Int -> Term Bool + If :: Term Bool -> Term a -> Term a -> Term a + Pair :: Term a -> Term b -> Term (a,b) +</programlisting> +Notice that the return type of the constructors is not always <literal>Term a</literal>, as is the +case with ordinary vanilla data types. Now we can write a well-typed <literal>eval</literal> function +for these <literal>Terms</literal>: +<programlisting> + eval :: Term a -> a + eval (Lit i) = i + eval (Succ t) = 1 + eval t + eval (IsZero t) = eval t == 0 + eval (If b e1 e2) = if eval b then eval e1 else eval e2 + eval (Pair e1 e2) = (eval e1, eval e2) +</programlisting> +These and many other examples are given in papers by Hongwei Xi, and Tim Sheard. +</para> +<para> The extensions to GHC are these: +<itemizedlist> +<listitem><para> + Data type declarations have a 'where' form, as exemplified above. The type signature of +each constructor is independent, and is implicitly universally quantified as usual. Unlike a normal +Haskell data type declaration, the type variable(s) in the "<literal>data Term a where</literal>" header +have no scope. Indeed, one can write a kind signature instead: +<programlisting> + data Term :: * -> * where ... +</programlisting> +or even a mixture of the two: +<programlisting> + data Foo a :: (* -> *) -> * where ... +</programlisting> +The type variables (if given) may be explicitly kinded, so we could also write the header for <literal>Foo</literal> +like this: +<programlisting> + data Foo a (b :: * -> *) where ... +</programlisting> +</para></listitem> + +<listitem><para> +There are no restrictions on the type of the data constructor, except that the result +type must begin with the type constructor being defined. For example, in the <literal>Term</literal> data +type above, the type of each constructor must end with <literal> ... -> Term ...</literal>. +</para></listitem> + +<listitem><para> +You can use record syntax on a GADT-style data type declaration: + +<programlisting> + data Term a where + Lit { val :: Int } :: Term Int + Succ { num :: Term Int } :: Term Int + Pred { num :: Term Int } :: Term Int + IsZero { arg :: Term Int } :: Term Bool + Pair { arg1 :: Term a + , arg2 :: Term b + } :: Term (a,b) + If { cnd :: Term Bool + , tru :: Term a + , fls :: Term a + } :: Term a +</programlisting> +For every constructor that has a field <literal>f</literal>, (a) the type of +field <literal>f</literal> must be the same; and (b) the +result type of the constructor must be the same; both modulo alpha conversion. +Hence, in our example, we cannot merge the <literal>num</literal> and <literal>arg</literal> +fields above into a +single name. Although their field types are both <literal>Term Int</literal>, +their selector functions actually have different types: + +<programlisting> + num :: Term Int -> Term Int + arg :: Term Bool -> Term Int +</programlisting> + +At the moment, record updates are not yet possible with GADT, so support is +limited to record construction, selection and pattern matching: + +<programlisting> + someTerm :: Term Bool + someTerm = IsZero { arg = Succ { num = Lit { val = 0 } } } + + eval :: Term a -> a + eval Lit { val = i } = i + eval Succ { num = t } = eval t + 1 + eval Pred { num = t } = eval t - 1 + eval IsZero { arg = t } = eval t == 0 + eval Pair { arg1 = t1, arg2 = t2 } = (eval t1, eval t2) + eval t@If{} = if eval (cnd t) then eval (tru t) else eval (fls t) +</programlisting> + +</para></listitem> + +<listitem><para> +You can use strictness annotations, in the obvious places +in the constructor type: +<programlisting> + data Term a where + Lit :: !Int -> Term Int + If :: Term Bool -> !(Term a) -> !(Term a) -> Term a + Pair :: Term a -> Term b -> Term (a,b) +</programlisting> +</para></listitem> + +<listitem><para> +You can use a <literal>deriving</literal> clause on a GADT-style data type +declaration, but only if the data type could also have been declared in +Haskell-98 syntax. For example, these two declarations are equivalent +<programlisting> + data Maybe1 a where { + Nothing1 :: Maybe a ; + Just1 :: a -> Maybe a + } deriving( Eq, Ord ) + + data Maybe2 a = Nothing2 | Just2 a + deriving( Eq, Ord ) +</programlisting> +This simply allows you to declare a vanilla Haskell-98 data type using the +<literal>where</literal> form without losing the <literal>deriving</literal> clause. +</para></listitem> + +<listitem><para> +Pattern matching causes type refinement. For example, in the right hand side of the equation +<programlisting> + eval :: Term a -> a + eval (Lit i) = ... +</programlisting> +the type <literal>a</literal> is refined to <literal>Int</literal>. (That's the whole point!) +A precise specification of the type rules is beyond what this user manual aspires to, but there is a paper +about the ideas: "Wobbly types: practical type inference for generalised algebraic data types", on Simon PJ's home page.</para> + +<para> The general principle is this: <emphasis>type refinement is only carried out based on user-supplied type annotations</emphasis>. +So if no type signature is supplied for <literal>eval</literal>, no type refinement happens, and lots of obscure error messages will +occur. However, the refinement is quite general. For example, if we had: +<programlisting> + eval :: Term a -> a -> a + eval (Lit i) j = i+j +</programlisting> +the pattern match causes the type <literal>a</literal> to be refined to <literal>Int</literal> (because of the type +of the constructor <literal>Lit</literal>, and that refinement also applies to the type of <literal>j</literal>, and +the result type of the <literal>case</literal> expression. Hence the addition <literal>i+j</literal> is legal. +</para> +</listitem> +</itemizedlist> +</para> + +<para>Notice that GADTs generalise existential types. For example, these two declarations are equivalent: +<programlisting> + data T a = forall b. MkT b (b->a) + data T' a where { MKT :: b -> (b->a) -> T' a } +</programlisting> +</para> +</sect1> + +<!-- ====================== End of Generalised algebraic data types ======================= --> + +<!-- ====================== TEMPLATE HASKELL ======================= --> + +<sect1 id="template-haskell"> +<title>Template Haskell</title> + +<para>Template Haskell allows you to do compile-time meta-programming in Haskell. There is a "home page" for +Template Haskell at <ulink url="http://www.haskell.org/th/"> +http://www.haskell.org/th/</ulink>, while +the background to +the main technical innovations is discussed in "<ulink +url="http://research.microsoft.com/~simonpj/papers/meta-haskell"> +Template Meta-programming for Haskell</ulink>" (Proc Haskell Workshop 2002). +The details of the Template Haskell design are still in flux. Make sure you +consult the <ulink url="http://www.haskell.org/ghc/docs/latest/html/libraries/index.html">online library reference material</ulink> +(search for the type ExpQ). +[Temporary: many changes to the original design are described in + <ulink url="http://research.microsoft.com/~simonpj/tmp/notes2.ps">"http://research.microsoft.com/~simonpj/tmp/notes2.ps"</ulink>. +Not all of these changes are in GHC 6.2.] +</para> + +<para> The first example from that paper is set out below as a worked example to help get you started. +</para> + +<para> +The documentation here describes the realisation in GHC. (It's rather sketchy just now; +Tim Sheard is going to expand it.) +</para> + + <sect2> + <title>Syntax</title> + + <para> Template Haskell has the following new syntactic + constructions. You need to use the flag + <option>-fth</option><indexterm><primary><option>-fth</option></primary> + </indexterm>to switch these syntactic extensions on + (<option>-fth</option> is currently implied by + <option>-fglasgow-exts</option>, but you are encouraged to + specify it explicitly).</para> + + <itemizedlist> + <listitem><para> + A splice is written <literal>$x</literal>, where <literal>x</literal> is an + identifier, or <literal>$(...)</literal>, where the "..." is an arbitrary expression. + There must be no space between the "$" and the identifier or parenthesis. This use + of "$" overrides its meaning as an infix operator, just as "M.x" overrides the meaning + of "." as an infix operator. If you want the infix operator, put spaces around it. + </para> + <para> A splice can occur in place of + <itemizedlist> + <listitem><para> an expression; the spliced expression must + have type <literal>Q Exp</literal></para></listitem> + <listitem><para> a list of top-level declarations; ; the spliced expression must have type <literal>Q [Dec]</literal></para></listitem> + <listitem><para> [Planned, but not implemented yet.] a + type; the spliced expression must have type <literal>Q Typ</literal>.</para></listitem> + </itemizedlist> + (Note that the syntax for a declaration splice uses "<literal>$</literal>" not "<literal>splice</literal>" as in + the paper. Also the type of the enclosed expression must be <literal>Q [Dec]</literal>, not <literal>[Q Dec]</literal> + as in the paper.) + </para></listitem> + + + <listitem><para> + A expression quotation is written in Oxford brackets, thus: + <itemizedlist> + <listitem><para> <literal>[| ... |]</literal>, where the "..." is an expression; + the quotation has type <literal>Expr</literal>.</para></listitem> + <listitem><para> <literal>[d| ... |]</literal>, where the "..." is a list of top-level declarations; + the quotation has type <literal>Q [Dec]</literal>.</para></listitem> + <listitem><para> [Planned, but not implemented yet.] <literal>[t| ... |]</literal>, where the "..." is a type; + the quotation has type <literal>Type</literal>.</para></listitem> + </itemizedlist></para></listitem> + + <listitem><para> + Reification is written thus: + <itemizedlist> + <listitem><para> <literal>reifyDecl T</literal>, where <literal>T</literal> is a type constructor; this expression + has type <literal>Dec</literal>. </para></listitem> + <listitem><para> <literal>reifyDecl C</literal>, where <literal>C</literal> is a class; has type <literal>Dec</literal>.</para></listitem> + <listitem><para> <literal>reifyType f</literal>, where <literal>f</literal> is an identifier; has type <literal>Typ</literal>.</para></listitem> + <listitem><para> Still to come: fixities </para></listitem> + + </itemizedlist></para> + </listitem> + + + </itemizedlist> +</sect2> + +<sect2> <title> Using Template Haskell </title> +<para> +<itemizedlist> + <listitem><para> + The data types and monadic constructor functions for Template Haskell are in the library + <literal>Language.Haskell.THSyntax</literal>. + </para></listitem> + + <listitem><para> + You can only run a function at compile time if it is imported from another module. That is, + you can't define a function in a module, and call it from within a splice in the same module. + (It would make sense to do so, but it's hard to implement.) + </para></listitem> + + <listitem><para> + The flag <literal>-ddump-splices</literal> shows the expansion of all top-level splices as they happen. + </para></listitem> + <listitem><para> + If you are building GHC from source, you need at least a stage-2 bootstrap compiler to + run Template Haskell. A stage-1 compiler will reject the TH constructs. Reason: TH + compiles and runs a program, and then looks at the result. So it's important that + the program it compiles produces results whose representations are identical to + those of the compiler itself. + </para></listitem> +</itemizedlist> +</para> +<para> Template Haskell works in any mode (<literal>--make</literal>, <literal>--interactive</literal>, + or file-at-a-time). There used to be a restriction to the former two, but that restriction + has been lifted. +</para> +</sect2> + +<sect2> <title> A Template Haskell Worked Example </title> +<para>To help you get over the confidence barrier, try out this skeletal worked example. + First cut and paste the two modules below into "Main.hs" and "Printf.hs":</para> + +<programlisting> + +{- Main.hs -} +module Main where + +-- Import our template "pr" +import Printf ( pr ) + +-- The splice operator $ takes the Haskell source code +-- generated at compile time by "pr" and splices it into +-- the argument of "putStrLn". +main = putStrLn ( $(pr "Hello") ) + + +{- Printf.hs -} +module Printf where + +-- Skeletal printf from the paper. +-- It needs to be in a separate module to the one where +-- you intend to use it. + +-- Import some Template Haskell syntax +import Language.Haskell.TH + +-- Describe a format string +data Format = D | S | L String + +-- Parse a format string. This is left largely to you +-- as we are here interested in building our first ever +-- Template Haskell program and not in building printf. +parse :: String -> [Format] +parse s = [ L s ] + +-- Generate Haskell source code from a parsed representation +-- of the format string. This code will be spliced into +-- the module which calls "pr", at compile time. +gen :: [Format] -> ExpQ +gen [D] = [| \n -> show n |] +gen [S] = [| \s -> s |] +gen [L s] = stringE s + +-- Here we generate the Haskell code for the splice +-- from an input format string. +pr :: String -> ExpQ +pr s = gen (parse s) +</programlisting> + +<para>Now run the compiler (here we are a Cygwin prompt on Windows): +</para> +<programlisting> +$ ghc --make -fth main.hs -o main.exe +</programlisting> + +<para>Run "main.exe" and here is your output:</para> + +<programlisting> +$ ./main +Hello +</programlisting> + +</sect2> + +</sect1> + +<!-- ===================== Arrow notation =================== --> + +<sect1 id="arrow-notation"> +<title>Arrow notation +</title> + +<para>Arrows are a generalization of monads introduced by John Hughes. +For more details, see +<itemizedlist> + +<listitem> +<para> +“Generalising Monads to Arrows”, +John Hughes, in <citetitle>Science of Computer Programming</citetitle> 37, +pp67–111, May 2000. +</para> +</listitem> + +<listitem> +<para> +“<ulink url="http://www.soi.city.ac.uk/~ross/papers/notation.html">A New Notation for Arrows</ulink>”, +Ross Paterson, in <citetitle>ICFP</citetitle>, Sep 2001. +</para> +</listitem> + +<listitem> +<para> +“<ulink url="http://www.soi.city.ac.uk/~ross/papers/fop.html">Arrows and Computation</ulink>”, +Ross Paterson, in <citetitle>The Fun of Programming</citetitle>, +Palgrave, 2003. +</para> +</listitem> + +</itemizedlist> +and the arrows web page at +<ulink url="http://www.haskell.org/arrows/"><literal>http://www.haskell.org/arrows/</literal></ulink>. +With the <option>-farrows</option> flag, GHC supports the arrow +notation described in the second of these papers. +What follows is a brief introduction to the notation; +it won't make much sense unless you've read Hughes's paper. +This notation is translated to ordinary Haskell, +using combinators from the +<ulink url="../libraries/base/Control-Arrow.html"><literal>Control.Arrow</literal></ulink> +module. +</para> + +<para>The extension adds a new kind of expression for defining arrows: +<screen> +<replaceable>exp</replaceable><superscript>10</superscript> ::= ... + | proc <replaceable>apat</replaceable> -> <replaceable>cmd</replaceable> +</screen> +where <literal>proc</literal> is a new keyword. +The variables of the pattern are bound in the body of the +<literal>proc</literal>-expression, +which is a new sort of thing called a <firstterm>command</firstterm>. +The syntax of commands is as follows: +<screen> +<replaceable>cmd</replaceable> ::= <replaceable>exp</replaceable><superscript>10</superscript> -< <replaceable>exp</replaceable> + | <replaceable>exp</replaceable><superscript>10</superscript> -<< <replaceable>exp</replaceable> + | <replaceable>cmd</replaceable><superscript>0</superscript> +</screen> +with <replaceable>cmd</replaceable><superscript>0</superscript> up to +<replaceable>cmd</replaceable><superscript>9</superscript> defined using +infix operators as for expressions, and +<screen> +<replaceable>cmd</replaceable><superscript>10</superscript> ::= \ <replaceable>apat</replaceable> ... <replaceable>apat</replaceable> -> <replaceable>cmd</replaceable> + | let <replaceable>decls</replaceable> in <replaceable>cmd</replaceable> + | if <replaceable>exp</replaceable> then <replaceable>cmd</replaceable> else <replaceable>cmd</replaceable> + | case <replaceable>exp</replaceable> of { <replaceable>calts</replaceable> } + | do { <replaceable>cstmt</replaceable> ; ... <replaceable>cstmt</replaceable> ; <replaceable>cmd</replaceable> } + | <replaceable>fcmd</replaceable> + +<replaceable>fcmd</replaceable> ::= <replaceable>fcmd</replaceable> <replaceable>aexp</replaceable> + | ( <replaceable>cmd</replaceable> ) + | (| <replaceable>aexp</replaceable> <replaceable>cmd</replaceable> ... <replaceable>cmd</replaceable> |) + +<replaceable>cstmt</replaceable> ::= let <replaceable>decls</replaceable> + | <replaceable>pat</replaceable> <- <replaceable>cmd</replaceable> + | rec { <replaceable>cstmt</replaceable> ; ... <replaceable>cstmt</replaceable> [;] } + | <replaceable>cmd</replaceable> +</screen> +where <replaceable>calts</replaceable> are like <replaceable>alts</replaceable> +except that the bodies are commands instead of expressions. +</para> + +<para> +Commands produce values, but (like monadic computations) +may yield more than one value, +or none, and may do other things as well. +For the most part, familiarity with monadic notation is a good guide to +using commands. +However the values of expressions, even monadic ones, +are determined by the values of the variables they contain; +this is not necessarily the case for commands. +</para> + +<para> +A simple example of the new notation is the expression +<screen> +proc x -> f -< x+1 +</screen> +We call this a <firstterm>procedure</firstterm> or +<firstterm>arrow abstraction</firstterm>. +As with a lambda expression, the variable <literal>x</literal> +is a new variable bound within the <literal>proc</literal>-expression. +It refers to the input to the arrow. +In the above example, <literal>-<</literal> is not an identifier but an +new reserved symbol used for building commands from an expression of arrow +type and an expression to be fed as input to that arrow. +(The weird look will make more sense later.) +It may be read as analogue of application for arrows. +The above example is equivalent to the Haskell expression +<screen> +arr (\ x -> x+1) >>> f +</screen> +That would make no sense if the expression to the left of +<literal>-<</literal> involves the bound variable <literal>x</literal>. +More generally, the expression to the left of <literal>-<</literal> +may not involve any <firstterm>local variable</firstterm>, +i.e. a variable bound in the current arrow abstraction. +For such a situation there is a variant <literal>-<<</literal>, as in +<screen> +proc x -> f x -<< x+1 +</screen> +which is equivalent to +<screen> +arr (\ x -> (f x, x+1)) >>> app +</screen> +so in this case the arrow must belong to the <literal>ArrowApply</literal> +class. +Such an arrow is equivalent to a monad, so if you're using this form +you may find a monadic formulation more convenient. +</para> + +<sect2> +<title>do-notation for commands</title> + +<para> +Another form of command is a form of <literal>do</literal>-notation. +For example, you can write +<screen> +proc x -> do + y <- f -< x+1 + g -< 2*y + let z = x+y + t <- h -< x*z + returnA -< t+z +</screen> +You can read this much like ordinary <literal>do</literal>-notation, +but with commands in place of monadic expressions. +The first line sends the value of <literal>x+1</literal> as an input to +the arrow <literal>f</literal>, and matches its output against +<literal>y</literal>. +In the next line, the output is discarded. +The arrow <function>returnA</function> is defined in the +<ulink url="../libraries/base/Control-Arrow.html"><literal>Control.Arrow</literal></ulink> +module as <literal>arr id</literal>. +The above example is treated as an abbreviation for +<screen> +arr (\ x -> (x, x)) >>> + first (arr (\ x -> x+1) >>> f) >>> + arr (\ (y, x) -> (y, (x, y))) >>> + first (arr (\ y -> 2*y) >>> g) >>> + arr snd >>> + arr (\ (x, y) -> let z = x+y in ((x, z), z)) >>> + first (arr (\ (x, z) -> x*z) >>> h) >>> + arr (\ (t, z) -> t+z) >>> + returnA +</screen> +Note that variables not used later in the composition are projected out. +After simplification using rewrite rules (see <xref linkend="rewrite-rules"/>) +defined in the +<ulink url="../libraries/base/Control-Arrow.html"><literal>Control.Arrow</literal></ulink> +module, this reduces to +<screen> +arr (\ x -> (x+1, x)) >>> + first f >>> + arr (\ (y, x) -> (2*y, (x, y))) >>> + first g >>> + arr (\ (_, (x, y)) -> let z = x+y in (x*z, z)) >>> + first h >>> + arr (\ (t, z) -> t+z) +</screen> +which is what you might have written by hand. +With arrow notation, GHC keeps track of all those tuples of variables for you. +</para> + +<para> +Note that although the above translation suggests that +<literal>let</literal>-bound variables like <literal>z</literal> must be +monomorphic, the actual translation produces Core, +so polymorphic variables are allowed. +</para> + +<para> +It's also possible to have mutually recursive bindings, +using the new <literal>rec</literal> keyword, as in the following example: +<programlisting> +counter :: ArrowCircuit a => a Bool Int +counter = proc reset -> do + rec output <- returnA -< if reset then 0 else next + next <- delay 0 -< output+1 + returnA -< output +</programlisting> +The translation of such forms uses the <function>loop</function> combinator, +so the arrow concerned must belong to the <literal>ArrowLoop</literal> class. +</para> + +</sect2> + +<sect2> +<title>Conditional commands</title> + +<para> +In the previous example, we used a conditional expression to construct the +input for an arrow. +Sometimes we want to conditionally execute different commands, as in +<screen> +proc (x,y) -> + if f x y + then g -< x+1 + else h -< y+2 +</screen> +which is translated to +<screen> +arr (\ (x,y) -> if f x y then Left x else Right y) >>> + (arr (\x -> x+1) >>> f) ||| (arr (\y -> y+2) >>> g) +</screen> +Since the translation uses <function>|||</function>, +the arrow concerned must belong to the <literal>ArrowChoice</literal> class. +</para> + +<para> +There are also <literal>case</literal> commands, like +<screen> +case input of + [] -> f -< () + [x] -> g -< x+1 + x1:x2:xs -> do + y <- h -< (x1, x2) + ys <- k -< xs + returnA -< y:ys +</screen> +The syntax is the same as for <literal>case</literal> expressions, +except that the bodies of the alternatives are commands rather than expressions. +The translation is similar to that of <literal>if</literal> commands. +</para> + +</sect2> + +<sect2> +<title>Defining your own control structures</title> + +<para> +As we're seen, arrow notation provides constructs, +modelled on those for expressions, +for sequencing, value recursion and conditionals. +But suitable combinators, +which you can define in ordinary Haskell, +may also be used to build new commands out of existing ones. +The basic idea is that a command defines an arrow from environments to values. +These environments assign values to the free local variables of the command. +Thus combinators that produce arrows from arrows +may also be used to build commands from commands. +For example, the <literal>ArrowChoice</literal> class includes a combinator +<programlisting> +ArrowChoice a => (<+>) :: a e c -> a e c -> a e c +</programlisting> +so we can use it to build commands: +<programlisting> +expr' = proc x -> do + returnA -< x + <+> do + symbol Plus -< () + y <- term -< () + expr' -< x + y + <+> do + symbol Minus -< () + y <- term -< () + expr' -< x - y +</programlisting> +(The <literal>do</literal> on the first line is needed to prevent the first +<literal><+> ...</literal> from being interpreted as part of the +expression on the previous line.) +This is equivalent to +<programlisting> +expr' = (proc x -> returnA -< x) + <+> (proc x -> do + symbol Plus -< () + y <- term -< () + expr' -< x + y) + <+> (proc x -> do + symbol Minus -< () + y <- term -< () + expr' -< x - y) +</programlisting> +It is essential that this operator be polymorphic in <literal>e</literal> +(representing the environment input to the command +and thence to its subcommands) +and satisfy the corresponding naturality property +<screen> +arr k >>> (f <+> g) = (arr k >>> f) <+> (arr k >>> g) +</screen> +at least for strict <literal>k</literal>. +(This should be automatic if you're not using <function>seq</function>.) +This ensures that environments seen by the subcommands are environments +of the whole command, +and also allows the translation to safely trim these environments. +The operator must also not use any variable defined within the current +arrow abstraction. +</para> + +<para> +We could define our own operator +<programlisting> +untilA :: ArrowChoice a => a e () -> a e Bool -> a e () +untilA body cond = proc x -> + if cond x then returnA -< () + else do + body -< x + untilA body cond -< x +</programlisting> +and use it in the same way. +Of course this infix syntax only makes sense for binary operators; +there is also a more general syntax involving special brackets: +<screen> +proc x -> do + y <- f -< x+1 + (|untilA (increment -< x+y) (within 0.5 -< x)|) +</screen> +</para> + +</sect2> + +<sect2> +<title>Primitive constructs</title> + +<para> +Some operators will need to pass additional inputs to their subcommands. +For example, in an arrow type supporting exceptions, +the operator that attaches an exception handler will wish to pass the +exception that occurred to the handler. +Such an operator might have a type +<screen> +handleA :: ... => a e c -> a (e,Ex) c -> a e c +</screen> +where <literal>Ex</literal> is the type of exceptions handled. +You could then use this with arrow notation by writing a command +<screen> +body `handleA` \ ex -> handler +</screen> +so that if an exception is raised in the command <literal>body</literal>, +the variable <literal>ex</literal> is bound to the value of the exception +and the command <literal>handler</literal>, +which typically refers to <literal>ex</literal>, is entered. +Though the syntax here looks like a functional lambda, +we are talking about commands, and something different is going on. +The input to the arrow represented by a command consists of values for +the free local variables in the command, plus a stack of anonymous values. +In all the prior examples, this stack was empty. +In the second argument to <function>handleA</function>, +this stack consists of one value, the value of the exception. +The command form of lambda merely gives this value a name. +</para> + +<para> +More concretely, +the values on the stack are paired to the right of the environment. +So operators like <function>handleA</function> that pass +extra inputs to their subcommands can be designed for use with the notation +by pairing the values with the environment in this way. +More precisely, the type of each argument of the operator (and its result) +should have the form +<screen> +a (...(e,t1), ... tn) t +</screen> +where <replaceable>e</replaceable> is a polymorphic variable +(representing the environment) +and <replaceable>ti</replaceable> are the types of the values on the stack, +with <replaceable>t1</replaceable> being the <quote>top</quote>. +The polymorphic variable <replaceable>e</replaceable> must not occur in +<replaceable>a</replaceable>, <replaceable>ti</replaceable> or +<replaceable>t</replaceable>. +However the arrows involved need not be the same. +Here are some more examples of suitable operators: +<screen> +bracketA :: ... => a e b -> a (e,b) c -> a (e,c) d -> a e d +runReader :: ... => a e c -> a' (e,State) c +runState :: ... => a e c -> a' (e,State) (c,State) +</screen> +We can supply the extra input required by commands built with the last two +by applying them to ordinary expressions, as in +<screen> +proc x -> do + s <- ... + (|runReader (do { ... })|) s +</screen> +which adds <literal>s</literal> to the stack of inputs to the command +built using <function>runReader</function>. +</para> + +<para> +The command versions of lambda abstraction and application are analogous to +the expression versions. +In particular, the beta and eta rules describe equivalences of commands. +These three features (operators, lambda abstraction and application) +are the core of the notation; everything else can be built using them, +though the results would be somewhat clumsy. +For example, we could simulate <literal>do</literal>-notation by defining +<programlisting> +bind :: Arrow a => a e b -> a (e,b) c -> a e c +u `bind` f = returnA &&& u >>> f + +bind_ :: Arrow a => a e b -> a e c -> a e c +u `bind_` f = u `bind` (arr fst >>> f) +</programlisting> +We could simulate <literal>if</literal> by defining +<programlisting> +cond :: ArrowChoice a => a e b -> a e b -> a (e,Bool) b +cond f g = arr (\ (e,b) -> if b then Left e else Right e) >>> f ||| g +</programlisting> +</para> + +</sect2> + +<sect2> +<title>Differences with the paper</title> + +<itemizedlist> + +<listitem> +<para>Instead of a single form of arrow application (arrow tail) with two +translations, the implementation provides two forms +<quote><literal>-<</literal></quote> (first-order) +and <quote><literal>-<<</literal></quote> (higher-order). +</para> +</listitem> + +<listitem> +<para>User-defined operators are flagged with banana brackets instead of +a new <literal>form</literal> keyword. +</para> +</listitem> + +</itemizedlist> + +</sect2> + +<sect2> +<title>Portability</title> + +<para> +Although only GHC implements arrow notation directly, +there is also a preprocessor +(available from the +<ulink url="http://www.haskell.org/arrows/">arrows web page</ulink>) +that translates arrow notation into Haskell 98 +for use with other Haskell systems. +You would still want to check arrow programs with GHC; +tracing type errors in the preprocessor output is not easy. +Modules intended for both GHC and the preprocessor must observe some +additional restrictions: +<itemizedlist> + +<listitem> +<para> +The module must import +<ulink url="../libraries/base/Control-Arrow.html"><literal>Control.Arrow</literal></ulink>. +</para> +</listitem> + +<listitem> +<para> +The preprocessor cannot cope with other Haskell extensions. +These would have to go in separate modules. +</para> +</listitem> + +<listitem> +<para> +Because the preprocessor targets Haskell (rather than Core), +<literal>let</literal>-bound variables are monomorphic. +</para> +</listitem> + +</itemizedlist> +</para> + +</sect2> + +</sect1> + +<!-- ==================== ASSERTIONS ================= --> + +<sect1 id="sec-assertions"> +<title>Assertions +<indexterm><primary>Assertions</primary></indexterm> +</title> + +<para> +If you want to make use of assertions in your standard Haskell code, you +could define a function like the following: +</para> + +<para> + +<programlisting> +assert :: Bool -> a -> a +assert False x = error "assertion failed!" +assert _ x = x +</programlisting> + +</para> + +<para> +which works, but gives you back a less than useful error message -- +an assertion failed, but which and where? +</para> + +<para> +One way out is to define an extended <function>assert</function> function which also +takes a descriptive string to include in the error message and +perhaps combine this with the use of a pre-processor which inserts +the source location where <function>assert</function> was used. +</para> + +<para> +Ghc offers a helping hand here, doing all of this for you. For every +use of <function>assert</function> in the user's source: +</para> + +<para> + +<programlisting> +kelvinToC :: Double -> Double +kelvinToC k = assert (k >= 0.0) (k+273.15) +</programlisting> + +</para> + +<para> +Ghc will rewrite this to also include the source location where the +assertion was made, +</para> + +<para> + +<programlisting> +assert pred val ==> assertError "Main.hs|15" pred val +</programlisting> + +</para> + +<para> +The rewrite is only performed by the compiler when it spots +applications of <function>Control.Exception.assert</function>, so you +can still define and use your own versions of +<function>assert</function>, should you so wish. If not, import +<literal>Control.Exception</literal> to make use +<function>assert</function> in your code. +</para> + +<para> +GHC ignores assertions when optimisation is turned on with the + <option>-O</option><indexterm><primary><option>-O</option></primary></indexterm> flag. That is, expressions of the form +<literal>assert pred e</literal> will be rewritten to +<literal>e</literal>. You can also disable assertions using the + <option>-fignore-asserts</option> + option<indexterm><primary><option>-fignore-asserts</option></primary> + </indexterm>.</para> + +<para> +Assertion failures can be caught, see the documentation for the +<literal>Control.Exception</literal> library for the details. +</para> + +</sect1> + + +<!-- =============================== PRAGMAS =========================== --> + + <sect1 id="pragmas"> + <title>Pragmas</title> + + <indexterm><primary>pragma</primary></indexterm> + + <para>GHC supports several pragmas, or instructions to the + compiler placed in the source code. Pragmas don't normally affect + the meaning of the program, but they might affect the efficiency + of the generated code.</para> + + <para>Pragmas all take the form + +<literal>{-# <replaceable>word</replaceable> ... #-}</literal> + + where <replaceable>word</replaceable> indicates the type of + pragma, and is followed optionally by information specific to that + type of pragma. Case is ignored in + <replaceable>word</replaceable>. The various values for + <replaceable>word</replaceable> that GHC understands are described + in the following sections; any pragma encountered with an + unrecognised <replaceable>word</replaceable> is (silently) + ignored.</para> + + <sect2 id="deprecated-pragma"> + <title>DEPRECATED pragma</title> + <indexterm><primary>DEPRECATED</primary> + </indexterm> + + <para>The DEPRECATED pragma lets you specify that a particular + function, class, or type, is deprecated. There are two + forms. + + <itemizedlist> + <listitem> + <para>You can deprecate an entire module thus:</para> +<programlisting> + module Wibble {-# DEPRECATED "Use Wobble instead" #-} where + ... +</programlisting> + <para>When you compile any module that import + <literal>Wibble</literal>, GHC will print the specified + message.</para> + </listitem> + + <listitem> + <para>You can deprecate a function, class, type, or data constructor, with the + following top-level declaration:</para> +<programlisting> + {-# DEPRECATED f, C, T "Don't use these" #-} +</programlisting> + <para>When you compile any module that imports and uses any + of the specified entities, GHC will print the specified + message.</para> + <para> You can only depecate entities declared at top level in the module + being compiled, and you can only use unqualified names in the list of + entities being deprecated. A capitalised name, such as <literal>T</literal> + refers to <emphasis>either</emphasis> the type constructor <literal>T</literal> + <emphasis>or</emphasis> the data constructor <literal>T</literal>, or both if + both are in scope. If both are in scope, there is currently no way to deprecate + one without the other (c.f. fixities <xref linkend="infix-tycons"/>).</para> + </listitem> + </itemizedlist> + Any use of the deprecated item, or of anything from a deprecated + module, will be flagged with an appropriate message. However, + deprecations are not reported for + (a) uses of a deprecated function within its defining module, and + (b) uses of a deprecated function in an export list. + The latter reduces spurious complaints within a library + in which one module gathers together and re-exports + the exports of several others. + </para> + <para>You can suppress the warnings with the flag + <option>-fno-warn-deprecations</option>.</para> + </sect2> + + <sect2 id="include-pragma"> + <title>INCLUDE pragma</title> + + <para>The <literal>INCLUDE</literal> pragma is for specifying the names + of C header files that should be <literal>#include</literal>'d into + the C source code generated by the compiler for the current module (if + compiling via C). For example:</para> + +<programlisting> +{-# INCLUDE "foo.h" #-} +{-# INCLUDE <stdio.h> #-}</programlisting> + + <para>The <literal>INCLUDE</literal> pragma(s) must appear at the top of + your source file with any <literal>OPTIONS_GHC</literal> + pragma(s).</para> + + <para>An <literal>INCLUDE</literal> pragma is the preferred alternative + to the <option>-#include</option> option (<xref + linkend="options-C-compiler" />), because the + <literal>INCLUDE</literal> pragma is understood by other + compilers. Yet another alternative is to add the include file to each + <literal>foreign import</literal> declaration in your code, but we + don't recommend using this approach with GHC.</para> + </sect2> + + <sect2 id="inline-noinline-pragma"> + <title>INLINE and NOINLINE pragmas</title> + + <para>These pragmas control the inlining of function + definitions.</para> + + <sect3 id="inline-pragma"> + <title>INLINE pragma</title> + <indexterm><primary>INLINE</primary></indexterm> + + <para>GHC (with <option>-O</option>, as always) tries to + inline (or “unfold”) functions/values that are + “small enough,” thus avoiding the call overhead + and possibly exposing other more-wonderful optimisations. + Normally, if GHC decides a function is “too + expensive” to inline, it will not do so, nor will it + export that unfolding for other modules to use.</para> + + <para>The sledgehammer you can bring to bear is the + <literal>INLINE</literal><indexterm><primary>INLINE + pragma</primary></indexterm> pragma, used thusly:</para> + +<programlisting> +key_function :: Int -> String -> (Bool, Double) + +#ifdef __GLASGOW_HASKELL__ +{-# INLINE key_function #-} +#endif +</programlisting> + + <para>(You don't need to do the C pre-processor carry-on + unless you're going to stick the code through HBC—it + doesn't like <literal>INLINE</literal> pragmas.)</para> + + <para>The major effect of an <literal>INLINE</literal> pragma + is to declare a function's “cost” to be very low. + The normal unfolding machinery will then be very keen to + inline it.</para> + + <para>Syntactically, an <literal>INLINE</literal> pragma for a + function can be put anywhere its type signature could be + put.</para> + + <para><literal>INLINE</literal> pragmas are a particularly + good idea for the + <literal>then</literal>/<literal>return</literal> (or + <literal>bind</literal>/<literal>unit</literal>) functions in + a monad. For example, in GHC's own + <literal>UniqueSupply</literal> monad code, we have:</para> + +<programlisting> +#ifdef __GLASGOW_HASKELL__ +{-# INLINE thenUs #-} +{-# INLINE returnUs #-} +#endif +</programlisting> + + <para>See also the <literal>NOINLINE</literal> pragma (<xref + linkend="noinline-pragma"/>).</para> + </sect3> + + <sect3 id="noinline-pragma"> + <title>NOINLINE pragma</title> + + <indexterm><primary>NOINLINE</primary></indexterm> + <indexterm><primary>NOTINLINE</primary></indexterm> + + <para>The <literal>NOINLINE</literal> pragma does exactly what + you'd expect: it stops the named function from being inlined + by the compiler. You shouldn't ever need to do this, unless + you're very cautious about code size.</para> + + <para><literal>NOTINLINE</literal> is a synonym for + <literal>NOINLINE</literal> (<literal>NOINLINE</literal> is + specified by Haskell 98 as the standard way to disable + inlining, so it should be used if you want your code to be + portable).</para> + </sect3> + + <sect3 id="phase-control"> + <title>Phase control</title> + + <para> Sometimes you want to control exactly when in GHC's + pipeline the INLINE pragma is switched on. Inlining happens + only during runs of the <emphasis>simplifier</emphasis>. Each + run of the simplifier has a different <emphasis>phase + number</emphasis>; the phase number decreases towards zero. + If you use <option>-dverbose-core2core</option> you'll see the + sequence of phase numbers for successive runs of the + simplifier. In an INLINE pragma you can optionally specify a + phase number, thus:</para> + + <itemizedlist> + <listitem> + <para>You can say "inline <literal>f</literal> in Phase 2 + and all subsequent phases": +<programlisting> + {-# INLINE [2] f #-} +</programlisting> + </para> + </listitem> + + <listitem> + <para>You can say "inline <literal>g</literal> in all + phases up to, but not including, Phase 3": +<programlisting> + {-# INLINE [~3] g #-} +</programlisting> + </para> + </listitem> + + <listitem> + <para>If you omit the phase indicator, you mean "inline in + all phases".</para> + </listitem> + </itemizedlist> + + <para>You can use a phase number on a NOINLINE pragma too:</para> + + <itemizedlist> + <listitem> + <para>You can say "do not inline <literal>f</literal> + until Phase 2; in Phase 2 and subsequently behave as if + there was no pragma at all": +<programlisting> + {-# NOINLINE [2] f #-} +</programlisting> + </para> + </listitem> + + <listitem> + <para>You can say "do not inline <literal>g</literal> in + Phase 3 or any subsequent phase; before that, behave as if + there was no pragma": +<programlisting> + {-# NOINLINE [~3] g #-} +</programlisting> + </para> + </listitem> + + <listitem> + <para>If you omit the phase indicator, you mean "never + inline this function".</para> + </listitem> + </itemizedlist> + + <para>The same phase-numbering control is available for RULES + (<xref linkend="rewrite-rules"/>).</para> + </sect3> + </sect2> + + <sect2 id="language-pragma"> + <title>LANGUAGE pragma</title> + + <indexterm><primary>LANGUAGE</primary><secondary>pragma</secondary></indexterm> + <indexterm><primary>pragma</primary><secondary>LANGUAGE</secondary></indexterm> + + <para>This allows language extensions to be enabled in a portable way. + It is the intention that all Haskell compilers support the + <literal>LANGUAGE</literal> pragma with the same syntax, although not + all extensions are supported by all compilers, of + course. The <literal>LANGUAGE</literal> pragma should be used instead + of <literal>OPTIONS_GHC</literal>, if possible.</para> + + <para>For example, to enable the FFI and preprocessing with CPP:</para> + +<programlisting>{-# LANGUAGE ForeignFunctionInterface, CPP #-}</programlisting> + + <para>Any extension from the <literal>Extension</literal> type defined in + <ulink + url="../libraries/Cabal/Language-Haskell-Extension.html"><literal>Language.Haskell.Extension</literal></ulink> may be used. GHC will report an error if any of the requested extensions are not supported.</para> + </sect2> + + + <sect2 id="line-pragma"> + <title>LINE pragma</title> + + <indexterm><primary>LINE</primary><secondary>pragma</secondary></indexterm> + <indexterm><primary>pragma</primary><secondary>LINE</secondary></indexterm> + <para>This pragma is similar to C's <literal>#line</literal> + pragma, and is mainly for use in automatically generated Haskell + code. It lets you specify the line number and filename of the + original code; for example</para> + +<programlisting>{-# LINE 42 "Foo.vhs" #-}</programlisting> + + <para>if you'd generated the current file from something called + <filename>Foo.vhs</filename> and this line corresponds to line + 42 in the original. GHC will adjust its error messages to refer + to the line/file named in the <literal>LINE</literal> + pragma.</para> + </sect2> + + <sect2 id="options-pragma"> + <title>OPTIONS_GHC pragma</title> + <indexterm><primary>OPTIONS_GHC</primary> + </indexterm> + <indexterm><primary>pragma</primary><secondary>OPTIONS_GHC</secondary> + </indexterm> + + <para>The <literal>OPTIONS_GHC</literal> pragma is used to specify + additional options that are given to the compiler when compiling + this source file. See <xref linkend="source-file-options"/> for + details.</para> + + <para>Previous versions of GHC accepted <literal>OPTIONS</literal> rather + than <literal>OPTIONS_GHC</literal>, but that is now deprecated.</para> + </sect2> + + <sect2 id="rules"> + <title>RULES pragma</title> + + <para>The RULES pragma lets you specify rewrite rules. It is + described in <xref linkend="rewrite-rules"/>.</para> + </sect2> + + <sect2 id="specialize-pragma"> + <title>SPECIALIZE pragma</title> + + <indexterm><primary>SPECIALIZE pragma</primary></indexterm> + <indexterm><primary>pragma, SPECIALIZE</primary></indexterm> + <indexterm><primary>overloading, death to</primary></indexterm> + + <para>(UK spelling also accepted.) For key overloaded + functions, you can create extra versions (NB: more code space) + specialised to particular types. Thus, if you have an + overloaded function:</para> + +<programlisting> + hammeredLookup :: Ord key => [(key, value)] -> key -> value +</programlisting> + + <para>If it is heavily used on lists with + <literal>Widget</literal> keys, you could specialise it as + follows:</para> + +<programlisting> + {-# SPECIALIZE hammeredLookup :: [(Widget, value)] -> Widget -> value #-} +</programlisting> + + <para>A <literal>SPECIALIZE</literal> pragma for a function can + be put anywhere its type signature could be put.</para> + + <para>A <literal>SPECIALIZE</literal> has the effect of generating + (a) a specialised version of the function and (b) a rewrite rule + (see <xref linkend="rewrite-rules"/>) that rewrites a call to the + un-specialised function into a call to the specialised one.</para> + + <para>The type in a SPECIALIZE pragma can be any type that is less + polymorphic than the type of the original function. In concrete terms, + if the original function is <literal>f</literal> then the pragma +<programlisting> + {-# SPECIALIZE f :: <type> #-} +</programlisting> + is valid if and only if the defintion +<programlisting> + f_spec :: <type> + f_spec = f +</programlisting> + is valid. Here are some examples (where we only give the type signature + for the original function, not its code): +<programlisting> + f :: Eq a => a -> b -> b + {-# SPECIALISE f :: Int -> b -> b #-} + + g :: (Eq a, Ix b) => a -> b -> b + {-# SPECIALISE g :: (Eq a) => a -> Int -> Int #-} + + h :: Eq a => a -> a -> a + {-# SPECIALISE h :: (Eq a) => [a] -> [a] -> [a] #-} +</programlisting> +The last of these examples will generate a +RULE with a somewhat-complex left-hand side (try it yourself), so it might not fire very +well. If you use this kind of specialisation, let us know how well it works. +</para> + +<para>A <literal>SPECIALIZE</literal> pragma can optionally be followed with a +<literal>INLINE</literal> or <literal>NOINLINE</literal> pragma, optionally +followed by a phase, as described in <xref linkend="inline-noinline-pragma"/>. +The <literal>INLINE</literal> pragma affects the specialised verison of the +function (only), and applies even if the function is recursive. The motivating +example is this: +<programlisting> +-- A GADT for arrays with type-indexed representation +data Arr e where + ArrInt :: !Int -> ByteArray# -> Arr Int + ArrPair :: !Int -> Arr e1 -> Arr e2 -> Arr (e1, e2) + +(!:) :: Arr e -> Int -> e +{-# SPECIALISE INLINE (!:) :: Arr Int -> Int -> Int #-} +{-# SPECIALISE INLINE (!:) :: Arr (a, b) -> Int -> (a, b) #-} +(ArrInt _ ba) !: (I# i) = I# (indexIntArray# ba i) +(ArrPair _ a1 a2) !: i = (a1 !: i, a2 !: i) +</programlisting> +Here, <literal>(!:)</literal> is a recursive function that indexes arrays +of type <literal>Arr e</literal>. Consider a call to <literal>(!:)</literal> +at type <literal>(Int,Int)</literal>. The second specialisation will fire, and +the specialised function will be inlined. It has two calls to +<literal>(!:)</literal>, +both at type <literal>Int</literal>. Both these calls fire the first +specialisation, whose body is also inlined. The result is a type-based +unrolling of the indexing function.</para> +<para>Warning: you can make GHC diverge by using <literal>SPECIALISE INLINE</literal> +on an ordinarily-recursive function.</para> + + <para>Note: In earlier versions of GHC, it was possible to provide your own + specialised function for a given type: + +<programlisting> +{-# SPECIALIZE hammeredLookup :: [(Int, value)] -> Int -> value = intLookup #-} +</programlisting> + + This feature has been removed, as it is now subsumed by the + <literal>RULES</literal> pragma (see <xref linkend="rule-spec"/>).</para> + + </sect2> + +<sect2 id="specialize-instance-pragma"> +<title>SPECIALIZE instance pragma +</title> + +<para> +<indexterm><primary>SPECIALIZE pragma</primary></indexterm> +<indexterm><primary>overloading, death to</primary></indexterm> +Same idea, except for instance declarations. For example: + +<programlisting> +instance (Eq a) => Eq (Foo a) where { + {-# SPECIALIZE instance Eq (Foo [(Int, Bar)]) #-} + ... usual stuff ... + } +</programlisting> +The pragma must occur inside the <literal>where</literal> part +of the instance declaration. +</para> +<para> +Compatible with HBC, by the way, except perhaps in the placement +of the pragma. +</para> + +</sect2> + + <sect2 id="unpack-pragma"> + <title>UNPACK pragma</title> + + <indexterm><primary>UNPACK</primary></indexterm> + + <para>The <literal>UNPACK</literal> indicates to the compiler + that it should unpack the contents of a constructor field into + the constructor itself, removing a level of indirection. For + example:</para> + +<programlisting> +data T = T {-# UNPACK #-} !Float + {-# UNPACK #-} !Float +</programlisting> + + <para>will create a constructor <literal>T</literal> containing + two unboxed floats. This may not always be an optimisation: if + the <function>T</function> constructor is scrutinised and the + floats passed to a non-strict function for example, they will + have to be reboxed (this is done automatically by the + compiler).</para> + + <para>Unpacking constructor fields should only be used in + conjunction with <option>-O</option>, in order to expose + unfoldings to the compiler so the reboxing can be removed as + often as possible. For example:</para> + +<programlisting> +f :: T -> Float +f (T f1 f2) = f1 + f2 +</programlisting> + + <para>The compiler will avoid reboxing <function>f1</function> + and <function>f2</function> by inlining <function>+</function> + on floats, but only when <option>-O</option> is on.</para> + + <para>Any single-constructor data is eligible for unpacking; for + example</para> + +<programlisting> +data T = T {-# UNPACK #-} !(Int,Int) +</programlisting> + + <para>will store the two <literal>Int</literal>s directly in the + <function>T</function> constructor, by flattening the pair. + Multi-level unpacking is also supported:</para> + +<programlisting> +data T = T {-# UNPACK #-} !S +data S = S {-# UNPACK #-} !Int {-# UNPACK #-} !Int +</programlisting> + + <para>will store two unboxed <literal>Int#</literal>s + directly in the <function>T</function> constructor. The + unpacker can see through newtypes, too.</para> + + <para>If a field cannot be unpacked, you will not get a warning, + so it might be an idea to check the generated code with + <option>-ddump-simpl</option>.</para> + + <para>See also the <option>-funbox-strict-fields</option> flag, + which essentially has the effect of adding + <literal>{-# UNPACK #-}</literal> to every strict + constructor field.</para> + </sect2> + +</sect1> + +<!-- ======================= REWRITE RULES ======================== --> + +<sect1 id="rewrite-rules"> +<title>Rewrite rules + +<indexterm><primary>RULES pragma</primary></indexterm> +<indexterm><primary>pragma, RULES</primary></indexterm> +<indexterm><primary>rewrite rules</primary></indexterm></title> + +<para> +The programmer can specify rewrite rules as part of the source program +(in a pragma). GHC applies these rewrite rules wherever it can, provided (a) +the <option>-O</option> flag (<xref linkend="options-optimise"/>) is on, +and (b) the <option>-frules-off</option> flag +(<xref linkend="options-f"/>) is not specified. +</para> + +<para> +Here is an example: + +<programlisting> + {-# RULES + "map/map" forall f g xs. map f (map g xs) = map (f.g) xs + #-} +</programlisting> + +</para> + +<sect2> +<title>Syntax</title> + +<para> +From a syntactic point of view: + +<itemizedlist> +<listitem> + +<para> + There may be zero or more rules in a <literal>RULES</literal> pragma. +</para> +</listitem> + +<listitem> + +<para> + Each rule has a name, enclosed in double quotes. The name itself has +no significance at all. It is only used when reporting how many times the rule fired. +</para> +</listitem> + +<listitem> +<para> +A rule may optionally have a phase-control number (see <xref linkend="phase-control"/>), +immediately after the name of the rule. Thus: +<programlisting> + {-# RULES + "map/map" [2] forall f g xs. map f (map g xs) = map (f.g) xs + #-} +</programlisting> +The "[2]" means that the rule is active in Phase 2 and subsequent phases. The inverse +notation "[~2]" is also accepted, meaning that the rule is active up to, but not including, +Phase 2. +</para> +</listitem> + + +<listitem> + +<para> + Layout applies in a <literal>RULES</literal> pragma. Currently no new indentation level +is set, so you must lay out your rules starting in the same column as the +enclosing definitions. +</para> +</listitem> + +<listitem> + +<para> + Each variable mentioned in a rule must either be in scope (e.g. <function>map</function>), +or bound by the <literal>forall</literal> (e.g. <function>f</function>, <function>g</function>, <function>xs</function>). The variables bound by +the <literal>forall</literal> are called the <emphasis>pattern</emphasis> variables. They are separated +by spaces, just like in a type <literal>forall</literal>. +</para> +</listitem> +<listitem> + +<para> + A pattern variable may optionally have a type signature. +If the type of the pattern variable is polymorphic, it <emphasis>must</emphasis> have a type signature. +For example, here is the <literal>foldr/build</literal> rule: + +<programlisting> +"fold/build" forall k z (g::forall b. (a->b->b) -> b -> b) . + foldr k z (build g) = g k z +</programlisting> + +Since <function>g</function> has a polymorphic type, it must have a type signature. + +</para> +</listitem> +<listitem> + +<para> +The left hand side of a rule must consist of a top-level variable applied +to arbitrary expressions. For example, this is <emphasis>not</emphasis> OK: + +<programlisting> +"wrong1" forall e1 e2. case True of { True -> e1; False -> e2 } = e1 +"wrong2" forall f. f True = True +</programlisting> + +In <literal>"wrong1"</literal>, the LHS is not an application; in <literal>"wrong2"</literal>, the LHS has a pattern variable +in the head. +</para> +</listitem> +<listitem> + +<para> + A rule does not need to be in the same module as (any of) the +variables it mentions, though of course they need to be in scope. +</para> +</listitem> +<listitem> + +<para> + Rules are automatically exported from a module, just as instance declarations are. +</para> +</listitem> + +</itemizedlist> + +</para> + +</sect2> + +<sect2> +<title>Semantics</title> + +<para> +From a semantic point of view: + +<itemizedlist> +<listitem> + +<para> +Rules are only applied if you use the <option>-O</option> flag. +</para> +</listitem> + +<listitem> +<para> + Rules are regarded as left-to-right rewrite rules. +When GHC finds an expression that is a substitution instance of the LHS +of a rule, it replaces the expression by the (appropriately-substituted) RHS. +By "a substitution instance" we mean that the LHS can be made equal to the +expression by substituting for the pattern variables. + +</para> +</listitem> +<listitem> + +<para> + The LHS and RHS of a rule are typechecked, and must have the +same type. + +</para> +</listitem> +<listitem> + +<para> + GHC makes absolutely no attempt to verify that the LHS and RHS +of a rule have the same meaning. That is undecidable in general, and +infeasible in most interesting cases. The responsibility is entirely the programmer's! + +</para> +</listitem> +<listitem> + +<para> + GHC makes no attempt to make sure that the rules are confluent or +terminating. For example: + +<programlisting> + "loop" forall x,y. f x y = f y x +</programlisting> + +This rule will cause the compiler to go into an infinite loop. + +</para> +</listitem> +<listitem> + +<para> + If more than one rule matches a call, GHC will choose one arbitrarily to apply. + +</para> +</listitem> +<listitem> +<para> + GHC currently uses a very simple, syntactic, matching algorithm +for matching a rule LHS with an expression. It seeks a substitution +which makes the LHS and expression syntactically equal modulo alpha +conversion. The pattern (rule), but not the expression, is eta-expanded if +necessary. (Eta-expanding the expression can lead to laziness bugs.) +But not beta conversion (that's called higher-order matching). +</para> + +<para> +Matching is carried out on GHC's intermediate language, which includes +type abstractions and applications. So a rule only matches if the +types match too. See <xref linkend="rule-spec"/> below. +</para> +</listitem> +<listitem> + +<para> + GHC keeps trying to apply the rules as it optimises the program. +For example, consider: + +<programlisting> + let s = map f + t = map g + in + s (t xs) +</programlisting> + +The expression <literal>s (t xs)</literal> does not match the rule <literal>"map/map"</literal>, but GHC +will substitute for <varname>s</varname> and <varname>t</varname>, giving an expression which does match. +If <varname>s</varname> or <varname>t</varname> was (a) used more than once, and (b) large or a redex, then it would +not be substituted, and the rule would not fire. + +</para> +</listitem> +<listitem> + +<para> + In the earlier phases of compilation, GHC inlines <emphasis>nothing +that appears on the LHS of a rule</emphasis>, because once you have substituted +for something you can't match against it (given the simple minded +matching). So if you write the rule + +<programlisting> + "map/map" forall f,g. map f . map g = map (f.g) +</programlisting> + +this <emphasis>won't</emphasis> match the expression <literal>map f (map g xs)</literal>. +It will only match something written with explicit use of ".". +Well, not quite. It <emphasis>will</emphasis> match the expression + +<programlisting> +wibble f g xs +</programlisting> + +where <function>wibble</function> is defined: + +<programlisting> +wibble f g = map f . map g +</programlisting> + +because <function>wibble</function> will be inlined (it's small). + +Later on in compilation, GHC starts inlining even things on the +LHS of rules, but still leaves the rules enabled. This inlining +policy is controlled by the per-simplification-pass flag <option>-finline-phase</option><emphasis>n</emphasis>. + +</para> +</listitem> +<listitem> + +<para> + All rules are implicitly exported from the module, and are therefore +in force in any module that imports the module that defined the rule, directly +or indirectly. (That is, if A imports B, which imports C, then C's rules are +in force when compiling A.) The situation is very similar to that for instance +declarations. +</para> +</listitem> + +</itemizedlist> + +</para> + +</sect2> + +<sect2> +<title>List fusion</title> + +<para> +The RULES mechanism is used to implement fusion (deforestation) of common list functions. +If a "good consumer" consumes an intermediate list constructed by a "good producer", the +intermediate list should be eliminated entirely. +</para> + +<para> +The following are good producers: + +<itemizedlist> +<listitem> + +<para> + List comprehensions +</para> +</listitem> +<listitem> + +<para> + Enumerations of <literal>Int</literal> and <literal>Char</literal> (e.g. <literal>['a'..'z']</literal>). +</para> +</listitem> +<listitem> + +<para> + Explicit lists (e.g. <literal>[True, False]</literal>) +</para> +</listitem> +<listitem> + +<para> + The cons constructor (e.g <literal>3:4:[]</literal>) +</para> +</listitem> +<listitem> + +<para> + <function>++</function> +</para> +</listitem> + +<listitem> +<para> + <function>map</function> +</para> +</listitem> + +<listitem> +<para> + <function>filter</function> +</para> +</listitem> +<listitem> + +<para> + <function>iterate</function>, <function>repeat</function> +</para> +</listitem> +<listitem> + +<para> + <function>zip</function>, <function>zipWith</function> +</para> +</listitem> + +</itemizedlist> + +</para> + +<para> +The following are good consumers: + +<itemizedlist> +<listitem> + +<para> + List comprehensions +</para> +</listitem> +<listitem> + +<para> + <function>array</function> (on its second argument) +</para> +</listitem> +<listitem> + +<para> + <function>length</function> +</para> +</listitem> +<listitem> + +<para> + <function>++</function> (on its first argument) +</para> +</listitem> + +<listitem> +<para> + <function>foldr</function> +</para> +</listitem> + +<listitem> +<para> + <function>map</function> +</para> +</listitem> +<listitem> + +<para> + <function>filter</function> +</para> +</listitem> +<listitem> + +<para> + <function>concat</function> +</para> +</listitem> +<listitem> + +<para> + <function>unzip</function>, <function>unzip2</function>, <function>unzip3</function>, <function>unzip4</function> +</para> +</listitem> +<listitem> + +<para> + <function>zip</function>, <function>zipWith</function> (but on one argument only; if both are good producers, <function>zip</function> +will fuse with one but not the other) +</para> +</listitem> +<listitem> + +<para> + <function>partition</function> +</para> +</listitem> +<listitem> + +<para> + <function>head</function> +</para> +</listitem> +<listitem> + +<para> + <function>and</function>, <function>or</function>, <function>any</function>, <function>all</function> +</para> +</listitem> +<listitem> + +<para> + <function>sequence_</function> +</para> +</listitem> +<listitem> + +<para> + <function>msum</function> +</para> +</listitem> +<listitem> + +<para> + <function>sortBy</function> +</para> +</listitem> + +</itemizedlist> + +</para> + + <para> +So, for example, the following should generate no intermediate lists: + +<programlisting> +array (1,10) [(i,i*i) | i <- map (+ 1) [0..9]] +</programlisting> + +</para> + +<para> +This list could readily be extended; if there are Prelude functions that you use +a lot which are not included, please tell us. +</para> + +<para> +If you want to write your own good consumers or producers, look at the +Prelude definitions of the above functions to see how to do so. +</para> + +</sect2> + +<sect2 id="rule-spec"> +<title>Specialisation +</title> + +<para> +Rewrite rules can be used to get the same effect as a feature +present in earlier versions of GHC. +For example, suppose that: + +<programlisting> +genericLookup :: Ord a => Table a b -> a -> b +intLookup :: Table Int b -> Int -> b +</programlisting> + +where <function>intLookup</function> is an implementation of +<function>genericLookup</function> that works very fast for +keys of type <literal>Int</literal>. You might wish +to tell GHC to use <function>intLookup</function> instead of +<function>genericLookup</function> whenever the latter was called with +type <literal>Table Int b -> Int -> b</literal>. +It used to be possible to write + +<programlisting> +{-# SPECIALIZE genericLookup :: Table Int b -> Int -> b = intLookup #-} +</programlisting> + +This feature is no longer in GHC, but rewrite rules let you do the same thing: + +<programlisting> +{-# RULES "genericLookup/Int" genericLookup = intLookup #-} +</programlisting> + +This slightly odd-looking rule instructs GHC to replace +<function>genericLookup</function> by <function>intLookup</function> +<emphasis>whenever the types match</emphasis>. +What is more, this rule does not need to be in the same +file as <function>genericLookup</function>, unlike the +<literal>SPECIALIZE</literal> pragmas which currently do (so that they +have an original definition available to specialise). +</para> + +<para>It is <emphasis>Your Responsibility</emphasis> to make sure that +<function>intLookup</function> really behaves as a specialised version +of <function>genericLookup</function>!!!</para> + +<para>An example in which using <literal>RULES</literal> for +specialisation will Win Big: + +<programlisting> +toDouble :: Real a => a -> Double +toDouble = fromRational . toRational + +{-# RULES "toDouble/Int" toDouble = i2d #-} +i2d (I# i) = D# (int2Double# i) -- uses Glasgow prim-op directly +</programlisting> + +The <function>i2d</function> function is virtually one machine +instruction; the default conversion—via an intermediate +<literal>Rational</literal>—is obscenely expensive by +comparison. +</para> + +</sect2> + +<sect2> +<title>Controlling what's going on</title> + +<para> + +<itemizedlist> +<listitem> + +<para> + Use <option>-ddump-rules</option> to see what transformation rules GHC is using. +</para> +</listitem> +<listitem> + +<para> + Use <option>-ddump-simpl-stats</option> to see what rules are being fired. +If you add <option>-dppr-debug</option> you get a more detailed listing. +</para> +</listitem> +<listitem> + +<para> + The definition of (say) <function>build</function> in <filename>GHC/Base.lhs</filename> looks llike this: + +<programlisting> + build :: forall a. (forall b. (a -> b -> b) -> b -> b) -> [a] + {-# INLINE build #-} + build g = g (:) [] +</programlisting> + +Notice the <literal>INLINE</literal>! That prevents <literal>(:)</literal> from being inlined when compiling +<literal>PrelBase</literal>, so that an importing module will “see” the <literal>(:)</literal>, and can +match it on the LHS of a rule. <literal>INLINE</literal> prevents any inlining happening +in the RHS of the <literal>INLINE</literal> thing. I regret the delicacy of this. + +</para> +</listitem> +<listitem> + +<para> + In <filename>libraries/base/GHC/Base.lhs</filename> look at the rules for <function>map</function> to +see how to write rules that will do fusion and yet give an efficient +program even if fusion doesn't happen. More rules in <filename>GHC/List.lhs</filename>. +</para> +</listitem> + +</itemizedlist> + +</para> + +</sect2> + +<sect2 id="core-pragma"> + <title>CORE pragma</title> + + <indexterm><primary>CORE pragma</primary></indexterm> + <indexterm><primary>pragma, CORE</primary></indexterm> + <indexterm><primary>core, annotation</primary></indexterm> + +<para> + The external core format supports <quote>Note</quote> annotations; + the <literal>CORE</literal> pragma gives a way to specify what these + should be in your Haskell source code. Syntactically, core + annotations are attached to expressions and take a Haskell string + literal as an argument. The following function definition shows an + example: + +<programlisting> +f x = ({-# CORE "foo" #-} show) ({-# CORE "bar" #-} x) +</programlisting> + + Semantically, this is equivalent to: + +<programlisting> +g x = show x +</programlisting> +</para> + +<para> + However, when external for is generated (via + <option>-fext-core</option>), there will be Notes attached to the + expressions <function>show</function> and <varname>x</varname>. + The core function declaration for <function>f</function> is: +</para> + +<programlisting> + f :: %forall a . GHCziShow.ZCTShow a -> + a -> GHCziBase.ZMZN GHCziBase.Char = + \ @ a (zddShow::GHCziShow.ZCTShow a) (eta::a) -> + (%note "foo" + %case zddShow %of (tpl::GHCziShow.ZCTShow a) + {GHCziShow.ZCDShow + (tpl1::GHCziBase.Int -> + a -> + GHCziBase.ZMZN GHCziBase.Char -> GHCziBase.ZMZN GHCziBase.Cha +r) + (tpl2::a -> GHCziBase.ZMZN GHCziBase.Char) + (tpl3::GHCziBase.ZMZN a -> + GHCziBase.ZMZN GHCziBase.Char -> GHCziBase.ZMZN GHCziBase.Cha +r) -> + tpl2}) + (%note "foo" + eta); +</programlisting> + +<para> + Here, we can see that the function <function>show</function> (which + has been expanded out to a case expression over the Show dictionary) + has a <literal>%note</literal> attached to it, as does the + expression <varname>eta</varname> (which used to be called + <varname>x</varname>). +</para> + +</sect2> + +</sect1> + +<sect1 id="generic-classes"> +<title>Generic classes</title> + + <para>(Note: support for generic classes is currently broken in + GHC 5.02).</para> + +<para> +The ideas behind this extension are described in detail in "Derivable type classes", +Ralf Hinze and Simon Peyton Jones, Haskell Workshop, Montreal Sept 2000, pp94-105. +An example will give the idea: +</para> + +<programlisting> + import Generics + + class Bin a where + toBin :: a -> [Int] + fromBin :: [Int] -> (a, [Int]) + + toBin {| Unit |} Unit = [] + toBin {| a :+: b |} (Inl x) = 0 : toBin x + toBin {| a :+: b |} (Inr y) = 1 : toBin y + toBin {| a :*: b |} (x :*: y) = toBin x ++ toBin y + + fromBin {| Unit |} bs = (Unit, bs) + fromBin {| a :+: b |} (0:bs) = (Inl x, bs') where (x,bs') = fromBin bs + fromBin {| a :+: b |} (1:bs) = (Inr y, bs') where (y,bs') = fromBin bs + fromBin {| a :*: b |} bs = (x :*: y, bs'') where (x,bs' ) = fromBin bs + (y,bs'') = fromBin bs' +</programlisting> +<para> +This class declaration explains how <literal>toBin</literal> and <literal>fromBin</literal> +work for arbitrary data types. They do so by giving cases for unit, product, and sum, +which are defined thus in the library module <literal>Generics</literal>: +</para> +<programlisting> + data Unit = Unit + data a :+: b = Inl a | Inr b + data a :*: b = a :*: b +</programlisting> +<para> +Now you can make a data type into an instance of Bin like this: +<programlisting> + instance (Bin a, Bin b) => Bin (a,b) + instance Bin a => Bin [a] +</programlisting> +That is, just leave off the "where" clause. Of course, you can put in the +where clause and over-ride whichever methods you please. +</para> + + <sect2> + <title> Using generics </title> + <para>To use generics you need to</para> + <itemizedlist> + <listitem> + <para>Use the flags <option>-fglasgow-exts</option> (to enable the extra syntax), + <option>-fgenerics</option> (to generate extra per-data-type code), + and <option>-package lang</option> (to make the <literal>Generics</literal> library + available. </para> + </listitem> + <listitem> + <para>Import the module <literal>Generics</literal> from the + <literal>lang</literal> package. This import brings into + scope the data types <literal>Unit</literal>, + <literal>:*:</literal>, and <literal>:+:</literal>. (You + don't need this import if you don't mention these types + explicitly; for example, if you are simply giving instance + declarations.)</para> + </listitem> + </itemizedlist> + </sect2> + +<sect2> <title> Changes wrt the paper </title> +<para> +Note that the type constructors <literal>:+:</literal> and <literal>:*:</literal> +can be written infix (indeed, you can now use +any operator starting in a colon as an infix type constructor). Also note that +the type constructors are not exactly as in the paper (Unit instead of 1, etc). +Finally, note that the syntax of the type patterns in the class declaration +uses "<literal>{|</literal>" and "<literal>|}</literal>" brackets; curly braces +alone would ambiguous when they appear on right hand sides (an extension we +anticipate wanting). +</para> +</sect2> + +<sect2> <title>Terminology and restrictions</title> +<para> +Terminology. A "generic default method" in a class declaration +is one that is defined using type patterns as above. +A "polymorphic default method" is a default method defined as in Haskell 98. +A "generic class declaration" is a class declaration with at least one +generic default method. +</para> + +<para> +Restrictions: +<itemizedlist> +<listitem> +<para> +Alas, we do not yet implement the stuff about constructor names and +field labels. +</para> +</listitem> + +<listitem> +<para> +A generic class can have only one parameter; you can't have a generic +multi-parameter class. +</para> +</listitem> + +<listitem> +<para> +A default method must be defined entirely using type patterns, or entirely +without. So this is illegal: +<programlisting> + class Foo a where + op :: a -> (a, Bool) + op {| Unit |} Unit = (Unit, True) + op x = (x, False) +</programlisting> +However it is perfectly OK for some methods of a generic class to have +generic default methods and others to have polymorphic default methods. +</para> +</listitem> + +<listitem> +<para> +The type variable(s) in the type pattern for a generic method declaration +scope over the right hand side. So this is legal (note the use of the type variable ``p'' in a type signature on the right hand side: +<programlisting> + class Foo a where + op :: a -> Bool + op {| p :*: q |} (x :*: y) = op (x :: p) + ... +</programlisting> +</para> +</listitem> + +<listitem> +<para> +The type patterns in a generic default method must take one of the forms: +<programlisting> + a :+: b + a :*: b + Unit +</programlisting> +where "a" and "b" are type variables. Furthermore, all the type patterns for +a single type constructor (<literal>:*:</literal>, say) must be identical; they +must use the same type variables. So this is illegal: +<programlisting> + class Foo a where + op :: a -> Bool + op {| a :+: b |} (Inl x) = True + op {| p :+: q |} (Inr y) = False +</programlisting> +The type patterns must be identical, even in equations for different methods of the class. +So this too is illegal: +<programlisting> + class Foo a where + op1 :: a -> Bool + op1 {| a :*: b |} (x :*: y) = True + + op2 :: a -> Bool + op2 {| p :*: q |} (x :*: y) = False +</programlisting> +(The reason for this restriction is that we gather all the equations for a particular type consructor +into a single generic instance declaration.) +</para> +</listitem> + +<listitem> +<para> +A generic method declaration must give a case for each of the three type constructors. +</para> +</listitem> + +<listitem> +<para> +The type for a generic method can be built only from: + <itemizedlist> + <listitem> <para> Function arrows </para> </listitem> + <listitem> <para> Type variables </para> </listitem> + <listitem> <para> Tuples </para> </listitem> + <listitem> <para> Arbitrary types not involving type variables </para> </listitem> + </itemizedlist> +Here are some example type signatures for generic methods: +<programlisting> + op1 :: a -> Bool + op2 :: Bool -> (a,Bool) + op3 :: [Int] -> a -> a + op4 :: [a] -> Bool +</programlisting> +Here, op1, op2, op3 are OK, but op4 is rejected, because it has a type variable +inside a list. +</para> +<para> +This restriction is an implementation restriction: we just havn't got around to +implementing the necessary bidirectional maps over arbitrary type constructors. +It would be relatively easy to add specific type constructors, such as Maybe and list, +to the ones that are allowed.</para> +</listitem> + +<listitem> +<para> +In an instance declaration for a generic class, the idea is that the compiler +will fill in the methods for you, based on the generic templates. However it can only +do so if + <itemizedlist> + <listitem> + <para> + The instance type is simple (a type constructor applied to type variables, as in Haskell 98). + </para> + </listitem> + <listitem> + <para> + No constructor of the instance type has unboxed fields. + </para> + </listitem> + </itemizedlist> +(Of course, these things can only arise if you are already using GHC extensions.) +However, you can still give an instance declarations for types which break these rules, +provided you give explicit code to override any generic default methods. +</para> +</listitem> + +</itemizedlist> +</para> + +<para> +The option <option>-ddump-deriv</option> dumps incomprehensible stuff giving details of +what the compiler does with generic declarations. +</para> + +</sect2> + +<sect2> <title> Another example </title> +<para> +Just to finish with, here's another example I rather like: +<programlisting> + class Tag a where + nCons :: a -> Int + nCons {| Unit |} _ = 1 + nCons {| a :*: b |} _ = 1 + nCons {| a :+: b |} _ = nCons (bot::a) + nCons (bot::b) + + tag :: a -> Int + tag {| Unit |} _ = 1 + tag {| a :*: b |} _ = 1 + tag {| a :+: b |} (Inl x) = tag x + tag {| a :+: b |} (Inr y) = nCons (bot::a) + tag y +</programlisting> +</para> +</sect2> +</sect1> + + + +<!-- Emacs stuff: + ;;; Local Variables: *** + ;;; mode: xml *** + ;;; sgml-parent-document: ("users_guide.xml" "book" "chapter" "sect1") *** + ;;; End: *** + --> + diff --git a/docs/users_guide/gone_wrong.xml b/docs/users_guide/gone_wrong.xml new file mode 100644 index 0000000000..d31087c164 --- /dev/null +++ b/docs/users_guide/gone_wrong.xml @@ -0,0 +1,213 @@ +<?xml version="1.0" encoding="iso-8859-1"?> +<chapter id="wrong"> + <title>What to do when something goes wrong</title> + + <indexterm><primary>problems</primary></indexterm> + + <para>If you still have a problem after consulting this section, + then you may have found a <emphasis>bug</emphasis>—please + report it! See <xref linkend="bug-reporting"/> for details on how to + report a bug and a list of things we'd like to know about your bug. + If in doubt, send a report—we love mail from irate users + :-!</para> + + <para>(<xref linkend="vs-Haskell-defn"/>, which describes Glasgow + Haskell's shortcomings vs. the Haskell language definition, may + also be of interest.)</para> + + <sect1 id="wrong-compiler"> + <title>When the compiler “does the wrong thing”</title> + + <indexterm><primary>compiler problems</primary></indexterm> + <indexterm><primary>problems with the compiler</primary></indexterm> + + <variablelist> + <varlistentry> + <term>“Help! The compiler crashed (or `panic'd)!”</term> + <listitem> + <para>These events are <emphasis>always</emphasis> bugs in + the GHC system—please report them.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term>“This is a terrible error message.”</term> + <listitem> + <para>If you think that GHC could have produced a better + error message, please report it as a bug.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term>“What about this warning from the C + compiler?”</term> + <listitem> + <para>For example: “…warning: `Foo' declared + `static' but never defined.” Unsightly, but shouldn't + be a problem.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term>Sensitivity to <filename>.hi</filename> interface files:</term> + <listitem> + <para>GHC is very sensitive about interface files. For + example, if it picks up a non-standard + <filename>Prelude.hi</filename> file, pretty terrible things + will happen. If you turn on + <option>-fno-implicit-prelude</option><indexterm><primary>-fno-implicit-prelude + option</primary></indexterm>, the compiler will almost + surely die, unless you know what you are doing.</para> + + <para>Furthermore, as sketched below, you may have big + problems running programs compiled using unstable + interfaces.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term>“I think GHC is producing incorrect code”:</term> + <listitem> + <para>Unlikely :-) A useful be-more-paranoid option to give + to GHC is + <option>-dcore-lint</option><indexterm><primary>-dcore-lint + option</primary></indexterm>; this causes a + “lint” pass to check for errors (notably type + errors) after each Core-to-Core transformation pass. We run + with <option>-dcore-lint</option> on all the time; it costs + about 5% in compile time.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term>“Why did I get a link error?”</term> + <listitem> + <para>If the linker complains about not finding + <literal>_<something>_fast</literal>, + then something is inconsistent: you probably didn't compile + modules in the proper dependency order.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term>“Is this line number right?”</term> + <listitem> + <para>On this score, GHC usually does pretty well, + especially if you “allow” it to be off by one or + two. In the case of an instance or class declaration, the + line number may only point you to the declaration, not to a + specific method.</para> + + <para>Please report line-number errors that you find + particularly unhelpful.</para> + </listitem> + </varlistentry> + </variablelist> + </sect1> + + <sect1 id="wrong-compilee"> + <title>When your program “does the wrong thing”</title> + + <indexterm><primary>problems running your program</primary></indexterm> + + <para>(For advice about overly slow or memory-hungry Haskell + programs, please see <xref + linkend="sooner-faster-quicker"/>).</para> + + <variablelist> + + <varlistentry> + <term>“Help! My program crashed!”</term> + <listitem> + <para>(e.g., a `segmentation fault' or `core dumped') + <indexterm><primary>segmentation + fault</primary></indexterm></para> + + <para>If your program has no foreign calls in it, and no + calls to known-unsafe functions (such as + <literal>unsafePerformIO</literal>) then a crash is always a + BUG in the GHC system, except in one case: If your program + is made of several modules, each module must have been + compiled after any modules on which it depends (unless you + use <filename>.hi-boot</filename> files, in which case these + <emphasis>must</emphasis> be correct with respect to the + module source).</para> + + <para>For example, if an interface is lying about the type + of an imported value then GHC may well generate duff code + for the importing module. <emphasis>This applies to pragmas + inside interfaces too!</emphasis> If the pragma is lying + (e.g., about the “arity” of a value), then duff + code may result. Furthermore, arities may change even if + types do not.</para> + + <para>In short, if you compile a module and its interface + changes, then all the modules that import that interface + <emphasis>must</emphasis> be re-compiled.</para> + + <para>A useful option to alert you when interfaces change is + <option>-hi-diffs</option><indexterm><primary>-hi-diffs + option</primary></indexterm>. It will run + <command>diff</command> on the changed interface file, + before and after, when applicable.</para> + + <para>If you are using <command>make</command>, GHC can + automatically generate the dependencies required in order to + make sure that every module <emphasis>is</emphasis> + up-to-date with respect to its imported interfaces. Please + see <xref linkend="sec-makefile-dependencies"/>.</para> + + <para>If you are down to your + last-compile-before-a-bug-report, we would recommend that + you add a <option>-dcore-lint</option> option (for extra + checking) to your compilation options.</para> + + <para>So, before you report a bug because of a core dump, + you should probably:</para> + +<screen> +% rm *.o # scrub your object files +% make my_prog # re-make your program; use -hi-diffs to highlight changes; + # as mentioned above, use -dcore-lint to be more paranoid +% ./my_prog ... # retry... +</screen> + + <para>Of course, if you have foreign calls in your program + then all bets are off, because you can trash the heap, the + stack, or whatever.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term>“My program entered an `absent' argument.”</term> + <listitem> + <para>This is definitely caused by a bug in GHC. Please + report it (see <xref linkend="bug-reporting"/>).</para> + </listitem> + </varlistentry> + + <varlistentry> + <term>“What's with this `arithmetic (or `floating') + exception' ”?</term> + <listitem> + <para><literal>Int</literal>, <literal>Float</literal>, and + <literal>Double</literal> arithmetic is + <emphasis>unchecked</emphasis>. Overflows, underflows and + loss of precision are either silent or reported as an + exception by the operating system (depending on the + platform). Divide-by-zero <emphasis>may</emphasis> cause an + untrapped exception (please report it if it does).</para> + </listitem> + </varlistentry> + + </variablelist> + </sect1> + +</chapter> + +<!-- Emacs stuff: + ;;; Local Variables: *** + ;;; mode: xml *** + ;;; sgml-parent-document: ("users_guide.xml" "book" "chapter") *** + ;;; End: *** + --> diff --git a/docs/users_guide/installing.xml b/docs/users_guide/installing.xml new file mode 100644 index 0000000000..9f8e4c9eb8 --- /dev/null +++ b/docs/users_guide/installing.xml @@ -0,0 +1,875 @@ +<?xml version="1.0" encoding="iso-8859-1"?> +<chapter id="sec-installing-bin-distrib"> + <title>Installing GHC</title> +<indexterm><primary>binary installations</primary></indexterm> +<indexterm><primary>installation, of binaries</primary></indexterm> + +<para> +Installing from binary distributions is easiest, and recommended! +(Why binaries? Because GHC is a Haskell compiler written in Haskell, +so you've got to bootstrap it somehow. We provide machine-generated +C-files-from-Haskell for this purpose, but it's really quite a pain to +use them. If you must build GHC from its sources, using a +binary-distributed GHC to do so is a sensible way to proceed. For the +other <literal>fptools</literal> programs, many are written in +Haskell, so binary distributions allow you to install them without +having a Haskell compiler.) +</para> + +<para>This guide is in several parts:</para> + + <itemizedlist> + <listitem> + <para> Installing on Unix-a-likes (<xref + linkend="sec-unix-a-likes"/>). </para> + </listitem> + <listitem> + <para> Installing on Windows (<xref + linkend="sec-install-windows"/>). </para> + </listitem> + <listitem> + <para> The layout of installed files (<xref + linkend="sec-install-files"/>). You don't need to know this to + install GHC, but it's useful if you are changing the + implementation.</para> + </listitem> + </itemizedlist> + + <sect1 id="sec-unix-a-likes"><title>Installing on Unix-a-likes</title> + + <sect2> + <title>When a platform-specific package is available</title> + + <para>For certain platforms, we provide GHC binaries packaged + using the native package format for the platform. This is + likely to be by far the best way to install GHC for your + platform if one of these packages is available, since + dependencies will automatically be handled and the package + system normally provides a way to uninstall the package at a + later date.</para> + + <para>We generally provide the following packages:</para> + + <variablelist> + <varlistentry> + <term>RedHat or SuSE Linux/x86</term> + <listitem> + <para>RPM source & binary packages for RedHat and SuSE + Linux (x86 only) are available for most major + releases.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term>Debian Linux/x86</term> + <listitem> + <para>Debian packages for Linux (x86 only), also for most + major releases.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term>FreeBSD/x86</term> + <listitem> + <para>On FreeBSD/x86, GHC can be installed using either + the ports tree (<literal>cd /usr/ports/lang/ghc && make + install</literal>) or from a pre-compiled package + available from your local FreeBSD mirror.</para> + </listitem> + </varlistentry> + </variablelist> + + <para>Other platform-specific packages may be available, check + the GHC download page for details.</para> + </sect2> + +<sect2> +<title>GHC binary distributions</title> + +<para> +<indexterm><primary>bundles of binary stuff</primary></indexterm> +</para> + +<para> +Binary distributions come in “bundles,” one bundle per file called +<literal><replaceable>bundle</replaceable>-<replaceable>platform</replaceable>.tar.gz</literal>. (See the building guide for the definition of a platform.) Suppose that you untar a binary-distribution bundle, thus: +</para> + +<para> + +<screen> +% cd /your/scratch/space +% gunzip < ghc-x.xx-sun-sparc-solaris2.tar.gz | tar xvf -</screen> + +</para> + +<para> +Then you should find a single directory, +<literal>ghc-<replaceable>version</replaceable></literal>, with the +following structure: +</para> + +<para> +<indexterm><primary>binary distribution, layout</primary></indexterm> +<indexterm><primary>directory layout (binary distributions)</primary></indexterm> +<variablelist> + +<varlistentry> +<term><literal>Makefile.in</literal></term> +<listitem> +<para> +the raw material from which the <literal>Makefile</literal> +will be made (<xref linkend="sec-install"/>). +</para> +</listitem></varlistentry> +<varlistentry> +<term><literal>configure</literal></term> +<listitem> +<para> +the configuration script (<xref linkend="sec-install"/>). +</para> +</listitem></varlistentry> +<varlistentry> +<term><literal>README</literal></term> +<listitem> +<para> +Contains this file summary. +</para> +</listitem></varlistentry> +<varlistentry> +<term><literal>INSTALL</literal></term> +<listitem> +<para> +Contains this description of how to install +the bundle. +</para> +</listitem></varlistentry> +<varlistentry> +<term><literal>ANNOUNCE</literal></term> +<listitem> +<para> +The announcement message for the bundle. +</para> +</listitem></varlistentry> +<varlistentry> +<term><literal>NEWS</literal></term> +<listitem> +<para> +release notes for the bundle—a longer version +of <literal>ANNOUNCE</literal>. For GHC, the release notes are contained in the User +Guide and this file isn't present. +</para> +</listitem></varlistentry> +<varlistentry> + <term><literal>bin/<replaceable>platform</replaceable></literal></term> +<listitem> +<para> +contains platform-specific executable +files to be invoked directly by the user. These are the files that +must end up in your path. +</para> +</listitem></varlistentry> +<varlistentry> +<term><literal>lib/<replaceable>platform</replaceable>/</literal></term> +<listitem> +<para> +contains platform-specific support +files for the installation. Typically there is a subdirectory for +each <literal>fptools</literal> project, whose name is the name of the project with its +version number. For example, for GHC there would be a sub-directory +<literal>ghc-x.xx</literal>/ where <literal>x.xx</literal> is the version number of GHC in the bundle. +</para> + +<para> +These sub-directories have the following general structure: +</para> + +<para> +<variablelist> + +<varlistentry> +<term><literal>libHSstd.a</literal> etc:</term> +<listitem> +<para> +supporting library archives. +</para> +</listitem></varlistentry> +<varlistentry> +<term><literal>ghc-iface.prl</literal> etc:</term> +<listitem> +<para> +support scripts. +</para> +</listitem></varlistentry> +<varlistentry> +<term><literal>import/</literal></term> +<listitem> +<para> +<indexterm><primary>Interface files</primary></indexterm> (<literal>.hi</literal>) for the prelude. +</para> +</listitem></varlistentry> +<varlistentry> +<term><literal>include/</literal></term> +<listitem> +<para> +A few C <literal>#include</literal> files. +</para> +</listitem></varlistentry> +</variablelist> +</para> +</listitem></varlistentry> +<varlistentry> +<term><literal>share/</literal></term> +<listitem> +<para> +contains platform-independent support files +for the installation. Again, there is a sub-directory for each +<literal>fptools</literal> project. +</para> +</listitem></varlistentry> +<varlistentry> +<term><literal>html/</literal></term> +<listitem> +<para> +contains HTML documentation files (one +sub-directory per project). +</para> +</listitem></varlistentry> +</variablelist> +</para> + +<sect3 id="sec-install"> +<title>Installing</title> + +<para> +OK, so let's assume that you have unpacked your chosen bundles. What +next? Well, you will at least need to run the +<literal>configure</literal><indexterm><primary>configure</primary></indexterm> +script by changing directory into the top-level directory for the +bundle and typing <literal>./configure</literal>. That should convert +<literal>Makefile.in</literal> to <literal>Makefile</literal>. +</para> + +<para> +<indexterm><primary>installing in-place</primary></indexterm> +<indexterm><primary>in-place installation</primary></indexterm> +You can now either start using the tools <emphasis>in-situ</emphasis> without going +through any installation process, just type <literal>make in-place</literal> to set the +tools up for this. You'll also want to add the path which <literal>make</literal> will +now echo to your <literal>PATH</literal> environment variable. This option is useful if +you simply want to try out the package and/or you don't have the +necessary privileges (or inclination) to properly install the tools +locally. Note that if you do decide to install the package `properly' +at a later date, you have to go through the installation steps that +follow. +</para> + +<para> +To install a package, you'll have to do the following: +</para> + +<para> + +<orderedlist> +<listitem> + +<para> + Edit the <literal>Makefile</literal> and check the settings of the following variables: + +<indexterm><primary>directories, installation</primary></indexterm> +<indexterm><primary>installation directories</primary></indexterm> + +<variablelist> + +<varlistentry> +<term><literal>platform</literal></term> +<listitem> +<para> +the platform you are going to install for. +</para> +</listitem></varlistentry> +<varlistentry> +<term><literal>bindir</literal></term> +<listitem> +<para> +the directory in which to install user-invokable +binaries. +</para> +</listitem></varlistentry> +<varlistentry> +<term><literal>libdir</literal></term> +<listitem> +<para> +the directory in which to install +platform-dependent support files. +</para> +</listitem></varlistentry> +<varlistentry> +<term><literal>datadir</literal></term> +<listitem> +<para> +the directory in which to install +platform-independent support files. +</para> +</listitem></varlistentry> +<varlistentry> +<term><literal>infodir</literal></term> +<listitem> +<para> +the directory in which to install Emacs info +files. +</para> +</listitem></varlistentry> +<varlistentry> +<term><literal>htmldir</literal></term> +<listitem> +<para> +the directory in which to install HTML +documentation. +</para> +</listitem></varlistentry> +<varlistentry> +<term><literal>dvidir</literal></term> +<listitem> +<para> +the directory in which to install DVI +documentation. +</para> +</listitem></varlistentry> +</variablelist> + +The values for these variables can be set through invocation of the +<command>configure</command><indexterm><primary>configure</primary></indexterm> +script that comes with the distribution, but doing an optical diff to +see if the values match your expectations is always a Good Idea. +</para> + +<para> +<emphasis>Instead of running <command>configure</command>, it is +perfectly OK to copy <filename>Makefile.in</filename> to +<filename>Makefile</filename> and set all these variables directly +yourself. But do it right!</emphasis> +</para> + +</listitem> +<listitem> + +<para> +Run <literal>make install</literal>. This <emphasis> +should</emphasis> work with ordinary Unix +<literal>make</literal>—no need for fancy stuff like GNU +<literal>make</literal>. + +</para> +</listitem> +<listitem> + +<para> +<literal>rehash</literal> (t?csh or zsh users), so your shell will see the new +stuff in your bin directory. + +</para> +</listitem> +<listitem> + +<para> + Once done, test your “installation” as suggested in +<xref linkend="sec-GHC-test"/>. Be sure to use a <literal>-v</literal> +option, so you can see exactly what pathnames it's using. + +If things don't work as expected, check the list of known pitfalls in +the building guide. +</para> +</listitem> + +</orderedlist> + +</para> + +<para> +<indexterm><primary>link, installed as ghc</primary></indexterm> +When installing the user-invokable binaries, this installation +procedure will install GHC as <literal>ghc-x.xx</literal> where <literal>x.xx</literal> is the version +number of GHC. It will also make a link (in the binary installation +directory) from <literal>ghc</literal> to <literal>ghc-x.xx</literal>. If you install multiple versions +of GHC then the last one “wins”, and “<literal>ghc</literal>” will invoke the last +one installed. You can change this manually if you want. But +regardless, <literal>ghc-x.xx</literal> should always invoke GHC version <literal>x.xx</literal>. +</para> + +</sect3> + + +<sect3> +<title>What bundles there are</title> + +<para> +<indexterm><primary>bundles, binary</primary></indexterm> There are +plenty of “non-basic” GHC bundles. The files for them are +called +<literal>ghc-x.xx-<replaceable>bundle</replaceable>-<replaceable>platform</replaceable>.tar.gz</literal>, +where the <replaceable>platform</replaceable> is as above, and +<replaceable>bundle</replaceable> is one of these: +</para> + +<para> +<variablelist> + +<varlistentry> +<term><literal>prof</literal>:</term> +<listitem> +<para> +Profiling with cost-centres. You probably want this. +<indexterm><primary>profiling bundles</primary></indexterm> +<indexterm><primary>bundles, profiling</primary></indexterm> +</para> +</listitem></varlistentry> +<varlistentry> +<term><literal>par</literal>:</term> +<listitem> +<para> +Parallel Haskell features (sits on top of PVM). +You'll want this if you're into that kind of thing. +<indexterm><primary>parallel bundles</primary></indexterm> +<indexterm><primary>bundles, parallel</primary></indexterm> +</para> +</listitem></varlistentry> +<varlistentry> +<term><literal>gran</literal>:</term> +<listitem> +<para> +The “GranSim” parallel-Haskell simulator +(hmm… mainly for implementors). +<indexterm><primary>bundles, gransim</primary></indexterm> +<indexterm><primary>gransim bundles</primary></indexterm> +</para> +</listitem></varlistentry> +<varlistentry> +<term><literal>ticky</literal>:</term> +<listitem> +<para> +“Ticky-ticky” profiling; very detailed +information about “what happened when I ran this program”—really +for implementors. +<indexterm><primary>bundles, ticky-ticky</primary></indexterm> +<indexterm><primary>ticky-ticky bundles</primary></indexterm> +</para> +</listitem></varlistentry> +</variablelist> +</para> + +<para> +One likely scenario is that you will grab <emphasis>two</emphasis> +binary bundles—basic, and profiling. We don't usually make the +rest, although you can build them yourself from a source distribution. +</para> + +<para>The various GHC bundles are designed to be unpacked into the +same directory; then installing as per the directions above will +install the whole lot in one go. Note: you <emphasis>must</emphasis> +at least have the basic GHC binary distribution bundle, these extra +bundles won't install on their own.</para> + +</sect3> + +<sect3 id="sec-GHC-test"> +<title>Testing that GHC seems to be working +</title> + +<para> +<indexterm><primary>testing a new GHC</primary></indexterm> +</para> + +<para> +The way to do this is, of course, to compile and run <emphasis>this</emphasis> program +(in a file <literal>Main.hs</literal>): +</para> + +<para> + +<programlisting> +main = putStr "Hello, world!\n" +</programlisting> + +</para> + +<para> +Compile the program, using the <literal>-v</literal> (verbose) flag to verify that +libraries, etc., are being found properly: + +<screen> +% ghc -v -o hello Main.hs</screen> + +</para> + +<para> +Now run it: + +<screen> +% ./hello +Hello, world!</screen> + +</para> + +<para> +Some simple-but-profitable tests are to compile and run the notorious +<literal>nfib</literal><indexterm><primary>nfib</primary></indexterm> program, using different numeric types. Start with +<literal>nfib :: Int -> Int</literal>, and then try <literal>Integer</literal>, <literal>Float</literal>, <literal>Double</literal>, +<literal>Rational</literal> and perhaps the overloaded version. Code for this is +distributed in <literal>ghc/misc/examples/nfib/</literal> in a source distribution. +</para> + +<para>For more information on how to “drive” GHC, read +on...</para> + +</sect3> + +</sect2> + +</sect1> + + +<sect1 id="sec-install-windows"><title>Installing on Windows</title> + +<para> +Getting the Glasgow Haskell Compiler (post 5.02) to run on Windows platforms is +a snap: the Installshield does everything you need. +</para> + +<sect2><title>Installing GHC on Windows</title> + +<para> +To install GHC, use the following steps: +</para> +<itemizedlist> +<listitem><para>Download the Installshield <filename>setup.exe</filename> +from the GHC download page +<ulink +url="http://www.haskell.org/ghc">haskell.org</ulink>. +</para></listitem> + +<listitem><para>Run <filename>setup.exe</filename>. +On Windows, all of GHC's files are installed in a single directory. +If you choose ``Custom'' from the list of install options, you will be given a +choice about where this directory is; otherwise it will be installed +in <filename>c:/ghc/<replaceable>ghc-version</replaceable></filename>. +The executable binary for GHC will be installed in the <filename>bin/</filename> sub-directory +of the installation directory you choose. +</para> +<para>(If you have already installed the same version of GHC, Installshield will offer to "modify", +or "remove" GHC. Choose "remove"; then run <filename>setup.exe</filename> a +second time. This time it should offer to install.) +</para> +<para> +When installation is complete, you should find GHCi and the GHC documentation are +available in your Start menu under "Start/Programs/Glasgow Haskell Compiler". +</para> +</listitem> + +<listitem><para> +The final dialogue box from the install process reminds you where the GHC binary +has been installed (usually <filename>c:/ghc/<replaceable>ghc-version</replaceable>/bin/</filename>. +If you want to invoke GHC from a command line, add this +to your PATH environment variable. +</para></listitem> + +<listitem><para> +GHC needs a directory in which to create, and later delete, temporary files. +It uses the standard Windows procedure <literal>GetTempPath()</literal> to +find a suitable directory. This procedure returns: +<itemizedlist> +<listitem><para>The path in environment variable TMP, +if TMP is set.</para></listitem> +<listitem><para>Otherwise, the path in environment variable TEMP, +if TEMP is set.</para></listitem> +<listitem><para>Otherwise, there is a per-user default which varies +between versions of Windows. On NT and XP-ish versions, it might +be: +<filename>c:\Documents and Settings\<username>\Local Settings\Temp</filename> +</para></listitem> +</itemizedlist> +The main point is that if you don't do anything GHC will work fine; +but if you want to control where the directory is, you can do so by +setting TMP or TEMP. +</para></listitem> + +<listitem> +<para> +To test the fruits of your labour, try now to compile a simple +Haskell program: +</para> + +<screen> +bash$ cat main.hs +module Main(main) where + +main = putStrLn "Hello, world!" +bash$ ghc -o main main.hs +.. +bash$ ./main +Hello, world! +bash$ </screen> +</listitem> +</itemizedlist> + +<para> +You do <emphasis>not</emphasis> need the Cygwin toolchain, or anything +else, to install and run GHC. +</para> +<para> +An installation of GHC requires about 140M of disk space. +To run GHC comfortably, your machine should have at least +64M of memory. +</para> +</sect2> + +<sect2><title>Moving GHC around</title> +<para> +At the moment, GHC installs in a fixed place (<filename>c:/ghc/ghc-x.yy</filename>, +but once it is installed, you can freely move the entire GHC tree just by copying +the <filename>ghc-x.yy</filename> directory. (You may need to fix up +the links in "Start/Programs/Glasgow Haskell Compiler" if you do this.) +</para> +<para> +It is OK to put GHC tree in a directory whose path involves spaces. However, +don't do this if you use want to use GHC with the Cygwin tools, +because Cygwin can get confused when this happens. +We havn't quite got to the bottom of this, but so far as we know it's not +a problem with GHC itself. Nevertheless, just to keep life simple we usually +put GHC in a place with a space-free path. +</para> +</sect2> + +<sect2 id="winfaq"> +<title>Installing ghc-win32 FAQ</title> + + <variablelist> + <varlistentry> + <term>I'm having trouble with symlinks.</term> + <listitem> + <para>Symlinks only work under Cygwin (<xref linkend="sec-install" />), so binaries not linked to the Cygwin + DLL, in particular those built for Mingwin, will not work with + symlinks.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term>I'm getting “permission denied” messages from the + <command>rm</command> or <command>mv</command>.</term> + <listitem> + <para>This can have various causes: trying to rename a directory + when an Explorer window is open on it tends to fail. Closing the + window generally cures the problem, but sometimes its cause is + more mysterious, and logging off and back on or rebooting may be + the quickest cure.</para> + </listitem> + </varlistentry> + </variablelist> + +<!-- doesn't add much value any longer; leave out [sof 7/2002]. +<para> +Further information on using GHC under Windows can be found in <ulink +url="http://www.dcs.gla.ac.uk/~sof/ghc-win32.html">Sigbjørn Finne's +pages</ulink>. Note: ignore the installation instructions, which are rather +out of date; the <emphasis>Miscellaneous</emphasis> section at the bottom of +the page is of most interest, covering topics beyond the scope of this +manual. +</para> +--> +</sect2> + +</sect1> + + +<sect1 id="sec-install-files"><title>The layout of installed files</title> + +<para> +This section describes what files get installed where. You don't need to know it +if you are simply installing GHC, but it is vital information if you are changing +the implementation. +</para> +<para> GHC is installed in two directory trees:</para> +<variablelist> +<varlistentry> +<term>Library directory,</term> +<listitem> <para> known as <filename>$(libdir)</filename>, holds all the +support files needed to run GHC. On Unix, this +directory is usually something like <filename>/usr/lib/ghc/ghc-5.02</filename>. </para> +</listitem> +</varlistentry> +<varlistentry> +<term>Binary directory</term> +<listitem> <para> known as <filename>$(bindir)</filename>, holds executables that +the user is expected to invoke. +Notably, it contains +<filename>ghc</filename> and <filename>ghci</filename>. On Unix, this directory +can be anywhere, but is typically something like <filename>/usr/local/bin</filename>. On Windows, +however, this directory <emphasis>must be</emphasis> <filename>$(libdir)/bin</filename>. +</para> +</listitem> +</varlistentry> +</variablelist> + +<para> +When GHC runs, it must know where its library directory is. +It finds this out in one of two ways: +</para> +<itemizedlist> +<listitem> +<para> +<filename>$(libdir)</filename> is passed to GHC using the <option>-B</option> flag. +On Unix (but not Windows), the installed <filename>ghc</filename> is just a one-line +shell script that invokes the real GHC, passing a suitable <option>-B</option> flag. +[All the user-supplied flags +follow, and a later <option>-B</option> flag overrides an earlier one, so a user-supplied +one wins.] +</para> +</listitem> +<listitem> +<para> On Windows (but not Unix), if no <option>-B</option> flag is given, GHC uses a system +call to find the directory in which the running GHC executable lives, and derives +<filename>$(libdir)</filename> from that. [Unix lacks such a system call.] +That is why <filename>$(bindir)</filename> must be <filename>$(libdir)/bin</filename>. +</para> +</listitem> +</itemizedlist> + +<sect2> <title>The binary directory</title> + +<para>The binary directory, <filename>$(bindir)</filename> contains user-visible +executables, notably <filename>ghc</filename> and <filename>ghci</filename>. +You should add it to your <literal>$PATH</literal> +</para> + +<para>On Unix, the user-invokable <filename>ghc</filename> invokes <filename>$(libdir)/ghc-<replaceable>version</replaceable></filename>, +passing a suitable <option>-B</option> flag to tell <filename>ghc-<replaceable>version</replaceable></filename> where +<filename>$(libdir)</filename> is. +Similarly <filename>ghci</filename>, except the extra flag <literal>--interactive</literal> is passed. +</para> + +<para>On Win32, the user-invokable <filename>ghc</filename> binary +is the Real Thing (no intervening +shell scripts or <filename>.bat</filename> files). +Reason: we sometimes invoke GHC with very long command lines, +and <filename>cmd.exe</filename> (which executes <filename>.bat</filename> files) +truncates them. Similarly <filename>ghci</filename> is a C wrapper program that invokes <filename>ghc --interactive</filename> +(passing on all other arguments), not a <filename>.bat</filename> file. +</para> + + +</sect2> + +<sect2> <title>The library directory</title> + +<para>The layout of the library directory, <filename>$(libdir)</filename> is almost identical on +Windows and Unix, as follows. Differences between Windows and Unix +are noted thus <literal>[Win32 only]</literal> and are commented below.</para> + +<programlisting> + $(libdir)/ + package.conf GHC package configuration + ghc-usage.txt Message displayed by ghc ––help + + bin/ [Win32 only] User-visible binaries + ghc.exe + ghci.exe + + unlit Remove literate markup + + touchy.exe [Win32 only] + perl.exe [Win32 only] + gcc.exe [Win32 only] + + ghc-x.xx GHC executable [Unix only] + + ghc-split Asm code splitter + ghc-asm Asm code mangler + + gcc-lib/ [Win32 only] Support files for gcc + specs gcc configuration + + cpp0.exe gcc support binaries + as.exe + ld.exe + + crt0.o Standard + ..etc.. binaries + + libmingw32.a Standard + ..etc.. libraries + + *.h Include files + + imports/ GHC interface files + std/*.hi 'std' library + lang/*.hi 'lang' library + ..etc.. + + include/ C header files + StgMacros.h GHC-specific + ..etc... header files + + mingw/*.h [Win32 only] Mingwin header files + + libHSrts.a GHC library archives + libHSstd.a + libHSlang.a + ..etc.. + + HSstd1.o GHC library linkables + HSstd2.o (used by ghci, which does + HSlang.o not grok .a files yet) +</programlisting> + +<para>Note that: +<itemizedlist> + + <listitem> + <para><filename>$(libdir)</filename> also contains support + binaries. These are <emphasis>not</emphasis> expected to be + on the user's <filename>PATH</filename>, but and are invoked + directly by GHC. In the Makefile system, this directory is + also called <filename>$(libexecdir)</filename>, but + <emphasis>you are not free to change it</emphasis>. It must + be the same as <filename>$(libdir)</filename>.</para> + </listitem> + +<listitem> +<para>We distribute <filename>gcc</filename> with the Win32 distribution of GHC, so that users +don't need to install <filename>gcc</filename>, nor need to care about which version it is. +All <filename>gcc</filename>'s support files are kept in <filename>$(libdir)/gcc-lib/</filename>. +</para> +</listitem> + +<listitem> +<para>Similarly, we distribute <filename>perl</filename> and a <filename>touch</filename> +replacement (<filename>touchy.exe</filename>) +with the Win32 distribution of GHC. </para> +</listitem> + + <listitem> + <para>The support programs <filename>ghc-split</filename> + and <filename>ghc-asm</filename> are Perl scripts. The + first line says <literal>#!/bin/perl</literal>; on Unix, the + script is indeed invoked as a shell script, which invokes + Perl; on Windows, GHC invokes + <filename>$(libdir)/perl.exe</filename> directly, which + treats the <literal>#!/bin/perl</literal> as a comment. + Reason: on Windows we want to invoke the Perl distributed + with GHC, rather than assume some installed one. </para> + </listitem> +</itemizedlist> +</para> + +</sect2> + +</sect1> + +</chapter> + +<!-- Emacs stuff: + ;;; Local Variables: *** + ;;; mode: xml *** + ;;; sgml-parent-document: ("users_guide.xml" "book" "chapter") *** + ;;; End: *** + --> diff --git a/docs/users_guide/intro.xml b/docs/users_guide/intro.xml new file mode 100644 index 0000000000..d4b6a1241f --- /dev/null +++ b/docs/users_guide/intro.xml @@ -0,0 +1,409 @@ +<?xml version="1.0" encoding="iso-8859-1"?> +<chapter id="introduction-GHC"> + <title>Introduction to GHC</title> + + <para>This is a guide to using the Glasgow Haskell Compiler (GHC): + an interactive and batch compilation system for the <ulink + url="http://www.haskell.org/">Haskell 98</ulink> + language.</para> + + <para>GHC has two main components: an interactive Haskell + interpreter (also known as GHCi), described in <xref + linkend="ghci"/>, and a batch compiler, described throughout <xref + linkend="using-ghc"/>. In fact, GHC consists of a single program + which is just run with different options to provide either the + interactive or the batch system.</para> + + <para>The batch compiler can be used alongside GHCi: compiled + modules can be loaded into an interactive session and used in the + same way as interpreted code, and in fact when using GHCi most of + the library code will be pre-compiled. This means you get the best + of both worlds: fast pre-compiled library code, and fast compile + turnaround for the parts of your program being actively + developed.</para> + + <para>GHC supports numerous language extensions, including + concurrency, a foreign function interface, exceptions, type system + extensions such as multi-parameter type classes, local universal and + existential quantification, functional dependencies, scoped type + variables and explicit unboxed types. These are all described in + <xref linkend="ghc-language-features"/>.</para> + + <para>GHC has a comprehensive optimiser, so when you want to Really + Go For It (and you've got time to spare) GHC can produce pretty fast + code. Alternatively, the default option is to compile as fast as + possible while not making too much effort to optimise the generated + code (although GHC probably isn't what you'd describe as a fast + compiler :-).</para> + + <para>GHC's profiling system supports “cost centre + stacks”: a way of seeing the profile of a Haskell program in a + call-graph like structure. See <xref linkend="profiling"/> for more + details.</para> + + <para>GHC comes with a large collection of libraries, with + everything from parser combinators to networking. The libraries are + described in separate documentation.</para> + + <sect1 id="mailing-lists-GHC"> + <title>Meta-information: Web sites, mailing lists, etc.</title> + + <indexterm><primary>mailing lists, Glasgow Haskell</primary></indexterm> + <indexterm><primary>Glasgow Haskell mailing lists</primary></indexterm> + + <para>On the World-Wide Web, there are several URLs of likely + interest:</para> + + <itemizedlist> + <listitem> + <para><ulink url="http://www.haskell.org/" >Haskell home + page</ulink></para> + </listitem> + + <listitem> + <para><ulink url="http://www.haskell.org/ghc/">GHC home + page</ulink></para> + </listitem> + + <listitem> + <para><ulink + url="http://www.cs.nott.ac.uk/~gmh/faq.html">comp.lang.functional + FAQ</ulink></para> + </listitem> + + </itemizedlist> + + <para>We run the following mailing lists about Glasgow Haskell. + We encourage you to join, as you feel is appropriate.</para> + + <variablelist> + <varlistentry> + <term>glasgow-haskell-users:</term> + <listitem> + <para>This list is for GHC users to chat among themselves. + If you have a specific question about GHC, please check the + <ulink + url="http://hackage.haskell.org/trac/ghc/wiki/FAQ">FAQ</ulink> + first.</para> + + <variablelist> + <varlistentry> + <term>list email address:</term> + <listitem> + <para><email>glasgow-haskell-users@haskell.org</email></para> + </listitem> + </varlistentry> + + <varlistentry> + <term>subscribe at:</term> + <listitem> + <para><ulink + url="http://www.haskell.org/mailman/listinfo/glasgow-haskell-users"><literal>http://www.haskell.org/mailman/listinfo/glasgow-haskell-users</literal></ulink>.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term>admin email address:</term> + <listitem> + <para><email>glasgow-haskell-users-admin@haskell.org</email></para> + </listitem> + </varlistentry> + + <varlistentry> + <term>list archives:</term> + <listitem> + <para><ulink + url="http://www.haskell.org/pipermail/glasgow-haskell-users/"><literal>http://www.haskell.org/pipermail/glasgow-haskell-users/</literal></ulink></para> + </listitem> + </varlistentry> + </variablelist> + </listitem> + </varlistentry> + + <varlistentry> + <term>glasgow-haskell-bugs:</term> + <listitem> + <para>Send bug reports for GHC to this address! The sad and + lonely people who subscribe to this list will muse upon + what's wrong and what you might do about it.</para> + + <variablelist> + <varlistentry> + <term>list email address:</term> + <listitem> + <para><email>glasgow-haskell-bugs@haskell.org</email></para> + </listitem> + </varlistentry> + + <varlistentry> + <term>subscribe at:</term> + <listitem> + <para><ulink + url="http://www.haskell.org/mailman/listinfo/glasgow-haskell-bugs"><literal>http://www.haskell.org/mailman/listinfo/glasgow-haskell-bugs</literal></ulink>.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term>admin email address:</term> + <listitem> + <para><email>glasgow-haskell-bugs-admin@haskell.org</email></para> + </listitem> + </varlistentry> + + <varlistentry> + <term>list archives:</term> + <listitem> + <para><ulink + url="http://www.haskell.org/pipermail/glasgow-haskell-bugs/"><literal>http://www.haskell.org/pipermail/glasgow-haskell-bugs/</literal></ulink></para> + </listitem> + </varlistentry> + </variablelist> + </listitem> + </varlistentry> + + <varlistentry> + <term>cvs-ghc:</term> + <listitem> + <para>The hardcore GHC developers hang out here. This list + also gets commit message from the CVS repository. There are + several other similar lists for other parts of the CVS + repository (eg. <literal>cvs-hslibs</literal>, + <literal>cvs-happy</literal>, <literal>cvs-hdirect</literal> + etc.)</para> + + <variablelist> + <varlistentry> + <term>list email address:</term> + <listitem> + <para><email>cvs-ghc@haskell.org</email></para> + </listitem> + </varlistentry> + + <varlistentry> + <term>subscribe at:</term> + <listitem> + <para><ulink + url="http://www.haskell.org/mailman/listinfo/cvs-ghc"><literal>http://www.haskell.org/mailman/listinfo/cvs-ghc</literal></ulink>.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term>admin email address:</term> + <listitem> + <para><email>cvs-ghc-admin@haskell.org</email></para> + </listitem> + </varlistentry> + + <varlistentry> + <term>list archives:</term> + <listitem> + <para><ulink + url="http://www.haskell.org/pipermail/cvs-ghc/"><literal>http://www.haskell.org/pipermail/cvs-ghc/</literal></ulink></para> + </listitem> + </varlistentry> + </variablelist> + </listitem> + </varlistentry> + </variablelist> + + <para>There are several other haskell and GHC-related mailing + lists served by <literal>www.haskell.org</literal>. Go to <ulink + url="http://www.haskell.org/mailman/listinfo/"><literal>http://www.haskell.org/mailman/listinfo/</literal></ulink> + for the full list.</para> + + <para>Some Haskell-related discussion also takes place in the + Usenet newsgroup <literal>comp.lang.functional</literal>.</para> + + </sect1> + + <sect1 id="bug-reporting"> + <title>Reporting bugs in GHC</title> + <indexterm><primary>bugs</primary><secondary>reporting</secondary> + </indexterm> + <indexterm><primary>reporting bugs</primary> + </indexterm> + + <para>Glasgow Haskell is a changing system so there are sure to be + bugs in it. </para> + + <para>To report a bug, either:</para> + + <itemizedlist> + <listitem> + <para>Preferred: <ulink + url="http://hackage.haskell.org/trac/ghc/newticket?type=bug">Create + a new bug</ulink>, and enter your bug report. You can also + search the bug database here to make sure your bug hasn't already + been reported (if it has, it might still help to add information + from your experience to the existing report).</para> + </listitem> + <listitem> + <para>Bug reports can also be emailed to + <email>glasgow-haskell-bugs@haskell.org</email>. </para> + </listitem> + </itemizedlist> + + <sect2> + <title>How do I tell if I should report my bug?</title> + + <para>Take a look at the <ulink + url="http://hackage.haskell.org/trac/ghc/wiki/FAQ">FAQ</ulink> and <xref + linkend="wrong"/>, which will give you some guidance as to + whether the behaviour you're seeing is really a bug or + not.</para> + + <para>If it is a bug, then it might have been reported before: + try searching on the <ulink + url="http://hackage.haskell.org/trac/ghc">bug tracker</ulink>, + and failing that, try <ulink + url="http://www.google.com">Google</ulink>.</para> + + <para>If in doubt, just report it.</para> + </sect2> + + <sect2> + <title>What to put in a bug report</title> + <indexterm><primary>bug reports</primary><secondary>contents</secondary></indexterm> + + <para>The name of the bug-reporting game is: facts, facts, + facts. Don't omit them because “Oh, they won't be + interested…”</para> + + <orderedlist> + <listitem> + <para>What kind of machine are you running on, and exactly + what version of the operating system are you using? (on a + Unix system, <command>uname -a</command> or <command>cat + /etc/motd</command> will show the desired information.) In + the bug tracker, this information can be given in the + “Architecture” and “Operating + system” fields.</para> + </listitem> + + <listitem> + <para>What version of GCC are you using? <command>gcc -v</command> will tell you.</para> + </listitem> + + <listitem> + <para>Run the sequence of compiles/runs that caused the + offending behaviour, cut-and-paste the whole session into + the bug report. We'd prefer to see the whole thing.</para> + </listitem> + + <listitem> + <para>Add the -v flag when running GHC, so we can see exactly + what was run, what versions of things you have, etc.</para> + </listitem> + + <listitem> + <para>What is the program behaviour that is wrong, in your + opinion?</para> + </listitem> + + <listitem> + <para>If practical, please attach or send enough source + files for us to duplicate the problem.</para> + </listitem> + + <listitem> + <para>If you are a Hero and track down the problem in the + compilation-system sources, please send us patches (either + <literal>darcs send</literal>, plain patches, or just whole + files if you prefer).</para> + </listitem> + </orderedlist> + </sect2> + </sect1> + + <sect1 id="version-numbering"> + <title>GHC version numbering policy</title> + <indexterm><primary>version, of ghc</primary></indexterm> + + <para>As of GHC version 6.0, we have adopted the following policy + for numbering GHC versions:</para> + + <variablelist> + <varlistentry> + <term>Stable Releases</term> + <listitem> + <para>These are numbered <literal><replaceable>x</replaceable>.<replaceable>y</replaceable>.<replaceable>z</replaceable></literal>, where + <replaceable>y</replaceable> is <emphasis>even</emphasis>, and + <replaceable>z</replaceable> is the patchlevel number (the trailing + <literal>.<replaceable>z</replaceable></literal> can be omitted if <replaceable>z</replaceable> + is zero). Patchlevels are bug-fix releases only, and never + change the programmer interface to any system-supplied code. + However, if you install a new patchlevel over an old one you + will need to recompile any code that was compiled against the + old libraries.</para> + + <para>The value of <literal>__GLASGOW_HASKELL__</literal> + (see <xref linkend="c-pre-processor"/>) for a major release + <literal><replaceable>x</replaceable>.<replaceable>y</replaceable>.<replaceable>z</replaceable></literal> + is the integer <replaceable>xyy</replaceable> (if + <replaceable>y</replaceable> is a single digit, then a leading zero + is added, so for example in version 6.2 of GHC, + <literal>__GLASGOW_HASKELL__==602</literal>).</para> + <indexterm> + <primary><literal>__GLASGOW_HASKELL__</literal></primary> + </indexterm> + </listitem> + </varlistentry> + + <varlistentry> + <term>Snapshots/unstable releases</term> + <listitem> + <para>We may make snapshot releases of the current + development sources from time to time, and the current + sources are always available via the CVS repository (see the + <ulink url="http://www.haskell.org/ghc/">GHC web + site</ulink> for details).</para> + + <para>Snapshot releases are named + <literal><replaceable>x</replaceable>.<replaceable>y</replaceable>.YYYYMMDD</literal> + where <literal>YYYYMMDD</literal> is the date of the sources + from which the snapshot was built. In theory, you can check + out the exact same sources from the CVS repository using + this date.</para> + + <para>If <replaceable>y</replaceable> is odd, then this is a + snapshot of the CVS HEAD (the main development branch). If + <replaceable>y</replaceable> is even, then it is a snapshot + of the stable branch between patchlevel releases. For + example, <literal>6.3.20040225</literal> would be a snapshot + of the HEAD, but <literal>6.2.20040225</literal> would be a + snapshot of the <literal>6.2</literal> branch.</para> + + <para>The value of <literal>__GLASGOW_HASKELL__</literal> + for a snapshot release is the integer + <replaceable>xyy</replaceable>. You should never write any + conditional code which tests for this value, however: since + interfaces change on a day-to-day basis, and we don't have + finer granularity in the values of + <literal>__GLASGOW_HASKELL__</literal>, you should only + conditionally compile using predicates which test whether + <literal>__GLASGOW_HASKELL__</literal> is equal to, later + than, or earlier than a given major release.</para> + <indexterm> + <primary><literal>__GLASGOW_HASKELL__</literal></primary> + </indexterm> + </listitem> + </varlistentry> + </variablelist> + + <para>The version number of your copy of GHC can be found by + invoking <literal>ghc</literal> with the + <literal>––version</literal> flag (see <xref + linkend="options-help"/>).</para> + </sect1> + + +&relnotes; + +</chapter> + +<!-- Emacs stuff: + ;;; Local Variables: *** + ;;; mode: xml *** + ;;; sgml-parent-document: ("users_guide.xml" "book" "chapter") *** + ;;; End: *** + --> diff --git a/docs/users_guide/lang.xml b/docs/users_guide/lang.xml new file mode 100644 index 0000000000..7e9621ed8b --- /dev/null +++ b/docs/users_guide/lang.xml @@ -0,0 +1,15 @@ +<?xml version="1.0" encoding="iso-8859-1"?> +<chapter id="ghc-language-features"> +<title>GHC Language Features</title> + +&glasgowexts; +∥ + +</chapter> + +<!-- Emacs stuff: + ;;; Local Variables: *** + ;;; mode: xml *** + ;;; sgml-parent-document: ("users_guide.xml" "book" "chapter") *** + ;;; End: *** + --> diff --git a/docs/users_guide/license.xml b/docs/users_guide/license.xml new file mode 100644 index 0000000000..55e2395a7c --- /dev/null +++ b/docs/users_guide/license.xml @@ -0,0 +1,66 @@ +<?xml version="1.0" encoding="iso-8859-1"?> +<preface id="License"> +<title>The Glasgow Haskell Compiler License</title> + +<para> +Copyright 2002, The University Court of the University of Glasgow. +All rights reserved. +</para> + +<para> +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: +</para> + +<para> +<itemizedlist> + +<listitem> +<para> +Redistributions of source code must retain the above copyright notice, +this list of conditions and the following disclaimer. +</para> +</listitem> + +<listitem> +<para> +Redistributions in binary form must reproduce the above copyright notice, +this list of conditions and the following disclaimer in the documentation +and/or other materials provided with the distribution. +</para> +</listitem> + +<listitem> +<para> +Neither name of the University nor the names of its contributors may be +used to endorse or promote products derived from this software without +specific prior written permission. +</para> +</listitem> + +</itemizedlist> +</para> + +<para> +THIS SOFTWARE IS PROVIDED BY THE UNIVERSITY COURT OF THE UNIVERSITY OF +GLASGOW AND THE CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, +INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE +UNIVERSITY COURT OF THE UNIVERSITY OF GLASGOW OR THE CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY +OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH +DAMAGE. +</para> + +</preface> + +<!-- Emacs stuff: + ;;; Local Variables: *** + ;;; mode: xml *** + ;;; sgml-parent-document: ("users_guide.xml" "book" "preface") *** + ;;; End: *** + --> diff --git a/docs/users_guide/packages.xml b/docs/users_guide/packages.xml new file mode 100644 index 0000000000..3bd65c66ce --- /dev/null +++ b/docs/users_guide/packages.xml @@ -0,0 +1,1193 @@ +<?xml version="1.0" encoding="iso-8859-1"?> + <sect1 id="packages"> + <title> +Packages + </title> + <indexterm><primary>packages</primary></indexterm> + + <para>A package is a library of Haskell modules known to the compiler. GHC + comes with several packages: see the accompanying + <ulink url="../libraries/index.html">library documentation</ulink>.</para> + + <para>Using a package couldn't be simpler: if you're using + <option>--make</option> or GHCi, then most of the installed packages will be + automatically available to your program without any further options. The + exceptions to this rule are covered below in <xref + linkend="using-packages" />.</para> + + <para>Building your own packages is also quite straightforward: we provide + the <ulink url="http://www.haskell.org/cabal/">Cabal</ulink> infrastructure which + automates the process of configuring, building, installing and distributing + a package. All you need to do is write a simple configuration file, put a + few files in the right places, and you have a package. See the + <ulink url="../Cabal/index.html">Cabal documentation</ulink> + for details, and also the Cabal libraries (<ulink url="../libraries/Cabal/Distribution-Simple.html">Distribution.Simple</ulink>, + for example).</para> + + <sect2 id="using-packages"> + <title>Using Packages + </title> + <indexterm><primary>packages</primary> + <secondary>using</secondary></indexterm> + + <para>To see which packages are installed, use the + <literal>ghc-pkg</literal> command:</para> + +<screen> +$ ghc-pkg list +/usr/lib/ghc-6.4/package.conf: + base-1.0, haskell98-1.0, template-haskell-1.0, mtl-1.0, unix-1.0, + Cabal-1.0, haskell-src-1.0, parsec-1.0, network-1.0, + QuickCheck-1.0, HUnit-1.1, fgl-1.0, X11-1.1, HGL-3.1, OpenGL-2.0, + GLUT-2.0, stm-1.0, readline-1.0, (lang-1.0), (concurrent-1.0), + (posix-1.0), (util-1.0), (data-1.0), (text-1.0), (net-1.0), + (hssource-1.0), rts-1.0 + </screen> + + <para>Packages are either exposed or hidden. Only + modules from exposed packages may be imported by your Haskell code; if + you try to import a module from a hidden package, GHC will emit an error + message.</para> + + <para>Each package has an exposed flag, which says whether it is exposed by + default or not. Packages hidden by default are listed in + parentheses (eg. <literal>(lang-1.0)</literal>) in the output from + <literal>ghc-pkg list</literal>. To expose a package which is hidden by + default, use the <option>-package</option> + flag (see below).</para> + + <para>To see which modules are exposed by a package:</para> + +<screen> +$ ghc-pkg field network exposed-modules +exposed-modules: Network.BSD, + Network.CGI, + Network.Socket, + Network.URI, + Network +</screen> + + <para>In general, packages containing hierarchical modules are usually + exposed by default. However, it is possible for two packages to contain + the same module: in this case, only one of the packages should be + exposed. It is an error to import a module that belongs to more than one + exposed package.</para> + + <para>The GHC command line options that control packages are:</para> + + <variablelist> + <varlistentry> + <term> + <option>-package <replaceable>P</replaceable></option> + <indexterm><primary><option>-package</option></primary></indexterm> + </term> + <listitem> + <para>This option causes package <replaceable>P</replaceable> to be + exposed. The package <replaceable>P</replaceable> can be specified + in full with its version number + (e.g. <literal>network-1.0</literal>) or the version number can be + omitted if there is only one version of the package + installed.</para> + + <para>If there are multiple versions of <replaceable>P</replaceable> + installed, then all other versions will become hidden.</para> + + <para>The <option>-package <replaceable>P</replaceable></option> + option also causes package <replaceable>P</replaceable> to be + linked into the resulting executable. In + <option>––make</option> mode and GHCi, the compiler + normally determines which packages are required by the current + Haskell modules, and links only those. In batch mode however, the + dependency information isn't available, and explicit + <option>-package</option> options must be given when linking.</para> + + <para>For example, to link a program consisting of objects + <filename>Foo.o</filename> and <filename>Main.o</filename>, where + we made use of the <literal>network</literal> package, we need to + give GHC the <literal>-package</literal> flag thus: + +<screen>$ ghc -o myprog Foo.o Main.o -package network</screen> + + The same flag is necessary even if we compiled the modules from + source, because GHC still reckons it's in batch mode: + +<screen>$ ghc -o myprog Foo.hs Main.hs -package network</screen> + + In <literal>--make</literal> and <literal>--interactive</literal> + modes (<xref linkend="modes" />), however, GHC figures out the + packages required for linking without further assistance.</para> + + <para>The one other time you might need to use + <option>-package</option> to force linking a package is when the + package does not contain any Haskell modules (it might contain a C + library only, for example). In that case, GHC + will never discover a dependency on it, so it has to be mentioned + explicitly.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-hide-all-packages</option> + <indexterm><primary><option>-hide-package</option></primary> + </indexterm></term> + <listitem> + <para>Ignore the exposed flag on installed packages, and hide them + all by default. If you use + this flag, then any packages you require (including + <literal>base</literal>) need to be explicitly exposed using + <option>-package</option> options.</para> + + <para>This is a good way to insulate your program from differences + in the globally exposed packages, and being explicit about package + dependencies is a Good Thing.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-hide-package</option> <replaceable>P</replaceable> + <indexterm><primary><option>-hide-package</option></primary> + </indexterm></term> + <listitem> + <para>This option does the opposite of <option>-package</option>: it + causes the specified package to be <firstterm>hidden</firstterm>, + which means that none of its modules will be available for import + by Haskell <literal>import</literal> directives.</para> + + <para>Note that the package might still end up being linked into the + final program, if it is a dependency (direct or indirect) of + another exposed package.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-ignore-package</option> <replaceable>P</replaceable> + <indexterm><primary><option>-ignore-package</option></primary> + </indexterm></term> + <listitem> + <para>Causes the compiler to behave as if package + <replaceable>P</replaceable>, and any packages that depend on + <literal>P</literal>, are not installed at all.</para> + + <para>Saying <literal>-ignore-package P</literal> is the same as + giving <literal>-hide-package</literal> flags for + <literal>P</literal> and all the packages that depend on + <literal>P</literal>. Sometimes we don't know ahead of time which + packages will be installed that depend on <literal>P</literal>, + which is when the <literal>-ignore-package</literal> flag can be + useful.</para> + </listitem> + </varlistentry> + </variablelist> + </sect2> + + <sect2 id="package-overlaps"> + <title>The module overlap restriction</title> + + <para>The module names in a Haskell program must be distinct. + This doesn't sound like a severe restriction, but in a Haskell program + using multiple packages with interdependencies, difficulties can start to + arise. You should be aware of what the module overlap + restriction means, and how to avoid it.</para> + + <para>GHC knows which packages are <emphasis>in use</emphasis> by your + program: a package is in use if you imported something from it, or if it + is a dependency of some other package in use. There must be no conflicts + between the packages in use; a conflict is when two packages contain + a module with the same name. If + GHC detects a conflict, it will issue a message stating which packages + are in conflict, and which modules are overlapping.</para> + + <para>For example, a conflict might arise if you use two packages, say P + and Q, which respectively depend on two different versions of another + package, say <literal>R-1.0</literal> and <literal>R-2.0</literal>. The + two versions of <literal>R</literal> are likely to contain at least some + of the same modules, so this situation would be a conflict.</para> + </sect2> + + <sect2 id="package-databases"> + <title>Package Databases</title> + + <para>A package database is a file, normally called + <literal>package.conf</literal> which contains descriptions of installed + packages. GHC usually knows about two package databases:</para> + + <itemizedlist> + <listitem> + <para>The global package database, which comes with your GHC + installation.</para> + </listitem> + <listitem> + <para>A package database private to each user. On Unix + systems this will be + <filename>$HOME/.ghc/<replaceable>arch</replaceable>-<replaceable>os</replaceable>-<replaceable>version</replaceable>/package.conf</filename>, and on + Windows it will be something like + <filename>C:\Documents And Settings\<replaceable>user</replaceable>\ghc</filename>. + The <literal>ghc-pkg</literal> tool knows where this file should be + located, and will create it if it doesn't exist (see <xref linkend="package-management" />).</para> + </listitem> + </itemizedlist> + + <para>When GHC starts up, it reads the contents of these two package + databases, and builds up a list of the packages it knows about. You can + see GHC's package table by running GHC with the <option>-v</option> + flag.</para> + + <para>Package databases may overlap: for example, packages in the user + database will override those of the same name in the global + database.</para> + + <para>You can control the loading of package databses using the following + GHC options:</para> + + <variablelist> + <varlistentry> + <term> + <option>-package-conf <replaceable>file</replaceable></option> + <indexterm><primary><option>-package-conf</option></primary></indexterm> + </term> + <listitem> + <para>Read in the package configuration file + <replaceable>file</replaceable> in addition to the system + default file and the user's local file. Packages in additional + files read this way will override those in the global and user + databases.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-no-user-package-conf</option> + <indexterm><primary><option>-no-user-package-conf</option></primary> + </indexterm> + </term> + <listitem> + <para>Prevent loading of the user's local package database.</para> + </listitem> + </varlistentry> + </variablelist> + + <para>To create a new package database, just create + a new file and put the string + <quote><literal>[]</literal></quote> in it. Packages can be + added to the file using the + <literal>ghc-pkg</literal> tool, described in <xref + linkend="package-management"/>.</para> + + <sect3 id="ghc-package-path"> + <title>The <literal>GHC_PACKAGE_PATH</literal> environment variable</title> + <indexterm><primary>Environment variable</primary><secondary><literal>GHC_PACKAGE_PATH</literal></secondary> + </indexterm> + <indexterm><primary><literal>GHC_PACKAGE_PATH</literal></primary></indexterm> + <para>The <literal>GHC_PACKAGE_PATH</literal> environment variable may be + set to a <literal>:</literal>-separated (<literal>;</literal>-separated + on Windows) list of files containing package databases. This list of + package databases is used by GHC and ghc-pkg, with earlier databases in + the list overriding later ones. This order was chosen to match the + behaviour of the <literal>PATH</literal> environment variable; think of + it as a list of package databases that are searched left-to-right for + packages.</para> + + <para>If <literal>GHC_PACKAGE_PATH</literal> ends in a separator, then + the default user and system package databases are appended, in that + order. e.g. to augment the usual set of packages with a database of + your own, you could say (on Unix): +<screen> +$ export GHC_PACKAGE_PATH=$HOME/.my-ghc-packages.conf:</screen> + (use <literal>;</literal> instead of <literal>:</literal> on + Windows).</para> + + <para>To check whether your <literal>GHC_PACKAGE_PATH</literal> setting + is doing the right thing, <literal>ghc-pkg list</literal> will list all + the databases in use, in the reverse order they are searched.</para> + + </sect3> + </sect2> + + <sect2 id="building-packages"> + <title>Building a package from Haskell source</title> + <indexterm><primary>packages</primary> + <secondary>building</secondary></indexterm> + + <para>We don't recommend building packages the hard way. Instead, use the + <ulink url="../Cabal/index.html">Cabal</ulink> infrastructure + if possible. If your package is particularly complicated or requires a + lot of configuration, then you might have to fall back to the low-level + mechanisms, so a few hints for those brave souls follow.</para> + + <itemizedlist> + <listitem> + <para>You need to build an "installed package info" file for + passing to <literal>ghc-pkg</literal> when installing your + package. The contents of this file are described in <xref + linkend="installed-pkg-info" />.</para> + </listitem> + + <listitem> + <para>The Haskell code in a package may be built into one or + more archive libraries + (e.g. <filename>libHSfoo.a</filename>), or a single DLL on + Windows (e.g. <filename>HSfoo.dll</filename>). The + restriction to a single DLL on Windows is because the + package system is used to tell the compiler when it should + make an inter-DLL call rather than an intra-DLL call + (inter-DLL calls require an extra + indirection). <emphasis>Building packages as DLLs doesn't + work at the moment; see <xref linkend="win32-dlls-create"/> + for the gory details.</emphasis> + </para> + + <para>Building a static library is done by using the + <literal>ar</literal> tool, like so:</para> + +<screen>ar cqs libHSfoo.a A.o B.o C.o ...</screen> + + <para>where <filename>A.o</filename>, + <filename>B.o</filename> and so on are the compiled Haskell + modules, and <filename>libHSfoo.a</filename> is the library + you wish to create. The syntax may differ slightly on your + system, so check the documentation if you run into + difficulties.</para> + + <para>Versions of the Haskell libraries for use with GHCi + may also be included: GHCi cannot load <literal>.a</literal> + files directly, instead it will look for an object file + called <filename>HSfoo.o</filename> and load that. On some + systems, the <literal>ghc-pkg</literal> tool can + automatically build the GHCi version of each library, see + <xref linkend="package-management"/>. To build these + libraries by hand from the <literal>.a</literal> archive, it + is possible to use GNU <command>ld</command> as + follows:</para> + +<screen>ld -r ––whole-archive -o HSfoo.o libHSfoo.a</screen> + + <para>(replace + <literal>––--whole-archive</literal> with + <literal>–all_load</literal> on MacOS X)</para> + + <para>GHC does not maintain detailed cross-package + dependency information. It does remember which modules in + other packages the current module depends on, but not which + things within those imported things.</para> + </listitem> + </itemizedlist> + + <para>It is worth noting that on Windows, when each package + is built as a DLL, since a reference to a DLL costs an extra + indirection, intra-package references are cheaper than + inter-package references. Of course, this applies to the + <filename>Main</filename> package as well.</para> + </sect2> + + <sect2 id="package-management"> + <title>Package management (the <literal>ghc-pkg</literal> command)</title> + <indexterm><primary>packages</primary> + <secondary>management</secondary></indexterm> + + <para>The <literal>ghc-pkg</literal> tool allows packages to be + added or removed from a package database. By default, + the system-wide package database is modified, but alternatively + the user's local package database or another specified + file can be used.</para> + + <para>To see what package databases are in use, say + <literal>ghc-pkg list</literal>. The stack of databases that + <literal>ghc-pkg</literal> knows about can be modified using the + <literal>GHC_PACKAGE_PATH</literal> environment variable (see <xref + linkend="ghc-package-path" />, and using + <literal>--package-conf</literal> options on the + <literal>ghc-pkg</literal> command line.</para> + + <para>When asked to modify a database, <literal>ghc-pkg</literal> modifies + the global database by default. Specifying <option>--user</option> + causes it to act on the user database, or <option>--package-conf</option> + can be used to act on another database entirely. When multiple of these + options are given, the rightmost one is used as the database to act + upon.</para> + + <para>If the environment variable <literal>GHC_PACKAGE_PATH</literal> is + set, and its value does not end in a separator (<literal>:</literal> on + Unix, <literal>;</literal> on Windows), then the last database is + considered to be the global database, and will be modified by default by + <literal>ghc-pkg</literal>. The intention here is that + <literal>GHC_PACKAGE_PATH</literal> can be used to create a virtual + package environment into which Cabal packages can be installed without + setting anything other than <literal>GHC_PACKAGE_PATH</literal>.</para> + + <para>The <literal>ghc-pkg</literal> program may be run in the ways listed + below. Where a package name is required, the package can be named in + full including the version number + (e.g. <literal>network-1.0</literal>), or without the version number. + Naming a package without the version number matches all versions of the + package; the specified action will be applied to all the matching + packages. A package specifier that matches all version of the package + can also be written <replaceable>pkg</replaceable><literal>-*</literal>, + to make it clearer that multiple packages are being matched.</para> + + <variablelist> + <varlistentry> + <term><literal>ghc-pkg register <replaceable>file</replaceable></literal></term> + <listitem> + <para>Reads a package specification from + <replaceable>file</replaceable> (which may be “<literal>-</literal>” + to indicate standard input), + and adds it to the database of installed packages. The syntax of + <replaceable>file</replaceable> is given in <xref + linkend="installed-pkg-info" />.</para> + + <para>The package specification must be a package that isn't already + installed.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>ghc-pkg update <replaceable>file</replaceable></literal></term> + <listitem> + <para>The same as <literal>register</literal>, except that if a + package of the same name is already installed, it is + replaced by the new one.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>ghc-pkg unregister <replaceable>P</replaceable></literal></term> + <listitem> + <para>Remove the specified package from the database.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>ghc-pkg expose <replaceable>P</replaceable></literal></term> + <listitem> + <para>Sets the <literal>exposed</literal> flag for package + <replaceable>P</replaceable> to <literal>True</literal>.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>ghc-pkg hide <replaceable>P</replaceable></literal></term> + <listitem> + <para>Sets the <literal>exposed</literal> flag for package + <replaceable>P</replaceable> to <literal>False</literal>.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>ghc-pkg list [<replaceable>P</replaceable>] [<option>--simple-output</option>]</literal></term> + <listitem> + <para>This option displays the currently installed + packages, for each of the databases known to + <literal>ghc-pkg</literal>. That includes the global database, the + user's local database, and any further files specified using the + <option>-f</option> option on the command line.</para> + + <para>Hidden packages (those for which the <literal>exposed</literal> + flag is <literal>False</literal>) are shown in parentheses in the + list of packages.</para> + + <para>If an optional package identifier <replaceable>P</replaceable> + is given, then only packages matching that identifier are + shown.</para> + + <para>If the option <option>--simple-output</option> is given, then + the packages are listed on a single line separated by spaces, and + the database names are not included. This is intended to make it + easier to parse the output of <literal>ghc-pkg list</literal> using + a script.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>ghc-pkg latest <replaceable>P</replaceable></literal></term> + <listitem> + <para>Prints the latest available version of package + <replaceable>P</replaceable>.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>ghc-pkg describe <replaceable>P</replaceable></literal></term> + <listitem> + <para>Emit the full description of the specified package. The + description is in the form of an + <literal>InstalledPackageInfo</literal>, the same as the input file + format for <literal>ghc-pkg register</literal>. See <xref + linkend="installed-pkg-info" /> for details.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>ghc-pkg field <replaceable>P</replaceable> <replaceable>field</replaceable></literal></term> + <listitem> + <para>Show just a single field of the installed package description + for <literal>P</literal>.</para> + </listitem> + </varlistentry> + </variablelist> + + <para>Additionally, the following flags are accepted by + <literal>ghc-pkg</literal>:</para> + + <variablelist> + <varlistentry> + <term> + <option>––auto-ghci-libs</option><indexterm><primary><option>––auto-ghci-libs</option></primary> + </indexterm> + </term> + <listitem> + <para>Automatically generate the GHCi + <filename>.o</filename> version of each + <filename>.a</filename> Haskell library, using GNU ld (if + that is available). Without this option, + <literal>ghc-pkg</literal> will warn if GHCi versions of + any Haskell libraries in the package don't exist.</para> + + <para>GHCi <literal>.o</literal> libraries don't + necessarily have to live in the same directory as the + corresponding <literal>.a</literal> library. However, + this option will cause the GHCi library to be created in + the same directory as the <literal>.a</literal> + library.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <option>-f</option> <replaceable>file</replaceable> + <indexterm><primary><option>-f</option></primary> + </indexterm> + </term> + <term> + <option>-package-conf</option> <replaceable>file</replaceable> + <indexterm><primary><option>-package-conf</option></primary> + </indexterm> + </term> + <listitem> + <para>Adds <replaceable>file</replaceable> to the stack of package + databases. Additionally, <replaceable>file</replaceable> will + also be the database modified by a <literal>register</literal>, + <literal>unregister</literal>, <literal>expose</literal> or + <literal>hide</literal> command, unless it is overriden by a later + <option>--package-conf</option>, <option>--user</option> or + <option>--global</option> option.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <option>––force</option> + <indexterm><primary> + <option>––force</option> + </primary></indexterm> + </term> + <listitem> + <para>Causes <literal>ghc-pkg</literal> to ignore missing + dependencies, directories and libraries when registering a package, + and just go ahead and add it anyway. This might be useful if your + package installation system needs to add the package to + GHC before building and installing the files.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <option>––global</option><indexterm><primary><option>––global</option></primary> + </indexterm> + </term> + <listitem> + <para>Operate on the global package database (this is the default). + This flag affects the <literal>register</literal>, + <literal>update</literal>, <literal>unregister</literal>, + <literal>expose</literal>, and <literal>hide</literal> + commands.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <option>––help</option><indexterm><primary><option>––help</option></primary> + </indexterm> + </term> + <term> + <option>-?</option><indexterm><primary><option>-?</option></primary> + </indexterm> + </term> + <listitem> + <para>Outputs the command-line syntax.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <option>––user</option><indexterm><primary><option>––user</option></primary> + </indexterm> + </term> + <listitem> + <para>Operate on the current user's local package database. + This flag affects the <literal>register</literal>, + <literal>update</literal>, <literal>unregister</literal>, + <literal>expose</literal>, and <literal>hide</literal> + commands.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <option>-V</option><indexterm><primary><option>-V</option></primary> + </indexterm> + </term> + <term> + <option>––version</option><indexterm><primary><option>––version</option></primary> + </indexterm> + </term> + <listitem> + <para>Output the <literal>ghc-pkg</literal> version number.</para> + </listitem> + </varlistentry> + </variablelist> + + <para>When modifying the package database + <replaceable>file</replaceable>, a copy of the original file is + saved in <replaceable>file</replaceable><literal>.old</literal>, + so in an emergency you can always restore the old settings by + copying the old file back again.</para> + + </sect2> + + <sect2 id="installed-pkg-info"> + <title> + <literal>InstalledPackageInfo</literal>: a package specification + </title> + + <para>A package specification is a Haskell record; in particular, it is the + record <ulink + url="../libraries/Cabal/Distribution-InstalledPackageInfo.html#%tInstalledPackageInfo">InstalledPackageInfo</ulink> in the module Distribution.InstalledPackageInfo, which is part of the Cabal package distributed with GHC.</para> + + <para>An <literal>InstalledPackageInfo</literal> has a human + readable/writable syntax. The functions + <literal>parseInstalledPackageInfo</literal> and + <literal>showInstalledPackageInfo</literal> read and write this syntax + respectively. Here's an example of the + <literal>InstalledPackageInfo</literal> for the <literal>unix</literal> package:</para> + +<screen> +$ ghc-pkg describe unix +name: unix +version: 1.0 +license: BSD3 +copyright: +maintainer: libraries@haskell.org +stability: +homepage: +package-url: +description: +category: +author: +exposed: True +exposed-modules: System.Posix, + System.Posix.DynamicLinker.Module, + System.Posix.DynamicLinker.Prim, + System.Posix.Directory, + System.Posix.DynamicLinker, + System.Posix.Env, + System.Posix.Error, + System.Posix.Files, + System.Posix.IO, + System.Posix.Process, + System.Posix.Resource, + System.Posix.Temp, + System.Posix.Terminal, + System.Posix.Time, + System.Posix.Unistd, + System.Posix.User, + System.Posix.Signals.Exts +import-dirs: /usr/lib/ghc-6.4/libraries/unix +library-dirs: /usr/lib/ghc-6.4/libraries/unix +hs-libraries: HSunix +extra-libraries: HSunix_cbits, dl +include-dirs: /usr/lib/ghc-6.4/libraries/unix/include +includes: HsUnix.h +depends: base-1.0 +</screen> + + <para>The full <ulink url="../Cabal/index.html">Cabal documentation</ulink> + is still in preparation (at time of writing), so in the meantime + here is a brief description of the syntax of this file:</para> + + <para>A package description consists of a number of field/value pairs. A + field starts with the field name in the left-hand column followed by a + “<literal>:</literal>”, and the value continues until the next line that begins in the + left-hand column, or the end of file.</para> + + <para>The syntax of the value depends on the field. The various field + types are:</para> + + <variablelist> + <varlistentry> + <term>freeform</term> + <listitem> + <para>Any arbitrary string, no interpretation or parsing is + done.</para> + </listitem> + </varlistentry> + <varlistentry> + <term>string</term> + <listitem> + <para>A sequence of non-space characters, or a sequence of arbitrary + characters surrounded by quotes <literal>"...."</literal>.</para> + </listitem> + </varlistentry> + <varlistentry> + <term>string list</term> + <listitem> + <para>A sequence of strings, separated by commas. The sequence may + be empty.</para> + </listitem> + </varlistentry> + </variablelist> + + <para>In addition, there are some fields with special syntax (e.g. package + names, version, dependencies).</para> + + <para>The allowed fields, with their types, are:</para> + + <variablelist> + <varlistentry> + <term> + <literal>name</literal> + <indexterm><primary><literal>name</literal></primary><secondary>package specification</secondary></indexterm> + </term> + <listitem> + <para>The package's name (without the version).</para> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <literal>version</literal> + <indexterm><primary><literal>version</literal></primary><secondary>package specification</secondary></indexterm> + </term> + <listitem> + <para>The package's version, usually in the form + <literal>A.B</literal> (any number of components are allowed).</para> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <literal>license</literal> + <indexterm><primary><literal>auto</literal></primary><secondary>package specification</secondary></indexterm> + </term> + <listitem> + <para>(string) The type of license under which this package is distributed. + This field is a value of the <ulink + url="../libraries/Cabal/Distribution-License.html#t:License"><literal>License</literal></ulink> type.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <literal>license-file</literal> + <indexterm><primary><literal>license-file</literal></primary><secondary>package specification</secondary></indexterm> + </term> + <listitem> + <para>(optional string) The name of a file giving detailed license + information for this package.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <literal>copyright</literal> + <indexterm><primary><literal>copyright</literal></primary><secondary>package specification</secondary></indexterm> + </term> + <listitem> + <para>(optional freeform) The copyright string.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <literal>maintainer</literal> + <indexterm><primary><literal>maintainer</literal></primary><secondary>package specification</secondary></indexterm> + </term> + <listitem> + <para>(optinoal freeform) The email address of the package's maintainer.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <literal>stability</literal> + <indexterm><primary><literal>stability</literal></primary><secondary>package specification</secondary></indexterm> + </term> + <listitem> + <para>(optional freeform) A string describing the stability of the package + (eg. stable, provisional or experimental).</para> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <literal>homepage</literal> + <indexterm><primary><literal>homepage</literal></primary><secondary>package specification</secondary></indexterm> + </term> + <listitem> + <para>(optional freeform) URL of the package's home page.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <literal>package-url</literal> + <indexterm><primary><literal>package-url</literal></primary><secondary>package specification</secondary></indexterm> + </term> + <listitem> + <para>(optional freeform) URL of a downloadable distribution for this + package. The distribution should be a Cabal package.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <literal>description</literal> + <indexterm><primary><literal>description</literal></primary><secondary>package specification</secondary></indexterm> + </term> + <listitem> + <para>(optional freeform) Description of the package.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <literal>category</literal> + <indexterm><primary><literal>category</literal></primary><secondary>package specification</secondary></indexterm> + </term> + <listitem> + <para>(optinoal freeform) Which category the package belongs to. This field + is for use in conjunction with a future centralised package + distribution framework, tentatively titled Hackage.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <literal>author</literal> + <indexterm><primary><literal>author</literal></primary><secondary>package specification</secondary></indexterm> + </term> + <listitem> + <para>(optional freeform) Author of the package.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <literal>exposed</literal> + <indexterm><primary><literal>exposed</literal></primary><secondary>package specification</secondary></indexterm> + </term> + <listitem> + <para>(bool) Whether the package is exposed or not.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <literal>exposed-modules</literal> + <indexterm><primary><literal>exposed-modules</literal></primary><secondary>package specification</secondary></indexterm> + </term> + <listitem> + <para>(string list) modules exposed by this package.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <literal>hidden-modules</literal> + <indexterm><primary><literal>hidden-modules</literal></primary><secondary>package specification</secondary></indexterm> + </term> + <listitem> + <para>(string list) modules provided by this package, + but not exposed to the programmer. These modules cannot be + imported, but they are still subject to the overlapping constraint: + no other package in the same program may provide a module of the + same name.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <literal>import-dirs</literal> + <indexterm><primary><literal>import-dirs</literal></primary><secondary>package specification</secondary></indexterm> + </term> + <listitem> + <para>(string list) A list of directories containing interface files + (<literal>.hi</literal> files) for this package.</para> + + <para>If the package contains profiling libraries, then + the interface files for those library modules should have + the suffix <literal>.p_hi</literal>. So the package can + contain both normal and profiling versions of the same + library without conflict (see also + <literal>library_dirs</literal> below).</para> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <literal>library-dirs</literal> + <indexterm><primary><literal>library-dirs</literal></primary><secondary>package specification</secondary></indexterm> + </term> + <listitem> + <para>(string list) A list of directories containing libraries for this + package.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <literal>hs-libraries</literal> + <indexterm><primary><literal>hs-libraries</literal></primary><secondary>package specification</secondary></indexterm> + </term> + <listitem> + <para>(string list) A list of libraries containing Haskell code for this + package, with the <literal>.a</literal> or + <literal>.dll</literal> suffix omitted. When packages are + built as libraries, the + <literal>lib</literal> prefix is also omitted.</para> + + <para>For use with GHCi, each library should have an + object file too. The name of the object file does + <emphasis>not</emphasis> have a <literal>lib</literal> + prefix, and has the normal object suffix for your + platform.</para> + + <para>For example, if we specify a Haskell library as + <filename>HSfoo</filename> in the package spec, then the + various flavours of library that GHC actually uses will be + called:</para> + <variablelist> + <varlistentry> + <term><filename>libHSfoo.a</filename></term> + <listitem> + <para>The name of the library on Unix and Windows + (mingw) systems. Note that we don't support + building dynamic libraries of Haskell code on Unix + systems.</para> + </listitem> + </varlistentry> + <varlistentry> + <term><filename>HSfoo.dll</filename></term> + <listitem> + <para>The name of the dynamic library on Windows + systems (optional).</para> + </listitem> + </varlistentry> + <varlistentry> + <term><filename>HSfoo.o</filename></term> + <term><filename>HSfoo.obj</filename></term> + <listitem> + <para>The object version of the library used by + GHCi.</para> + </listitem> + </varlistentry> + </variablelist> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <literal>extra-libraries</literal> + <indexterm><primary><literal>extra-libraries</literal></primary><secondary>package specification</secondary></indexterm> + </term> + <listitem> + <para>(string list) A list of extra libraries for this package. The + difference between <literal>hs-libraries</literal> and + <literal>extra-libraries</literal> is that + <literal>hs-libraries</literal> normally have several + versions, to support profiling, parallel and other build + options. The various versions are given different + suffixes to distinguish them, for example the profiling + version of the standard prelude library is named + <filename>libHSbase_p.a</filename>, with the + <literal>_p</literal> indicating that this is a profiling + version. The suffix is added automatically by GHC for + <literal>hs-libraries</literal> only, no suffix is added + for libraries in + <literal>extra-libraries</literal>.</para> + + <para>The libraries listed in + <literal>extra-libraries</literal> may be any libraries + supported by your system's linker, including dynamic + libraries (<literal>.so</literal> on Unix, + <literal>.DLL</literal> on Windows).</para> + + <para>Also, <literal>extra-libraries</literal> are placed + on the linker command line after the + <literal>hs-libraries</literal> for the same package. If + your package has dependencies in the other direction (i.e. + <literal>extra-libraries</literal> depends on + <literal>hs-libraries</literal>), and the libraries are + static, you might need to make two separate + packages.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <literal>include-dirs</literal> + <indexterm><primary><literal>include-dirs</literal></primary><secondary>package specification</secondary></indexterm> + </term> + <listitem> + <para>(string list) A list of directories containing C includes for this + package.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <literal>includes</literal> + <indexterm><primary><literal>includes</literal></primary><secondary>package specification</secondary></indexterm> + </term> + <listitem> + <para>(string list) A list of files to include for via-C compilations + using this package. Typically the include file(s) will + contain function prototypes for any C functions used in + the package, in case they end up being called as a result + of Haskell functions from the package being + inlined.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <literal>depends</literal> + <indexterm><primary><literal>depends</literal></primary><secondary>package specification</secondary></indexterm> + </term> + <listitem> + <para>(package name list) Packages on which this package depends. This field contains + packages with explicit versions are required, except that when + submitting a package to <literal>ghc-pkg register</literal>, the + versions will be filled in if they are unambiguous.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <literal>hugs-options</literal> + <indexterm><primary><literal>hugs-options</literal></primary><secondary>package specification</secondary></indexterm> + </term> + <listitem> + <para>(string list) Options to pass to Hugs for this package.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <literal>cc-options</literal> + <indexterm><primary><literal>cc-options</literal></primary><secondary>package specification</secondary></indexterm> + </term> + <listitem> + <para>(string list) Extra arguments to be added to the gcc command line + when this package is being used (only for via-C + compilations).</para> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <literal>ld-options</literal> + <indexterm><primary><literal>ld-options</literal></primary><secondary>package specification</secondary></indexterm> + </term> + <listitem> + <para>(string list) Extra arguments to be added to the + <command>gcc</command> command line (for linking) when + this package is being used.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <literal>framework-dirs</literal> + <indexterm><primary><literal>framework-dirs</literal></primary><secondary>package specification</secondary></indexterm> + </term> + <listitem> + <para>(string list) On Darwin/MacOS X, a list of directories containing + frameworks for this package. This corresponds to the + <option>-framework-path</option> option. It is ignored on all other + platforms.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <literal>frameworks</literal> + <indexterm><primary><literal>frameworks</literal></primary><secondary>package specification</secondary></indexterm> + </term> + <listitem> + <para>(string list) On Darwin/MacOS X, a list of frameworks to link to. This + corresponds to the <option>-framework</option> option. Take a look + at Apple's developer documentation to find out what frameworks + actually are. This entry is ignored on all other platforms.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <literal>haddock-interfaces</literal> + <indexterm><primary><literal>haddock-interfaces</literal></primary><secondary>package specification</secondary></indexterm> + </term> + <listitem> + <para>(string list) A list of filenames containing <ulink + url="http://www.haskell.org/haddock/">Haddock</ulink> interface + files (<literal>.haddock</literal> files) for this package.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <literal>haddock-html</literal> + <indexterm><primary><literal>haddock-html</literal></primary><secondary>package specification</secondary></indexterm> + </term> + <listitem> + <para>(optional string) The directory containing the Haddock-generated HTML + for this package.</para> + </listitem> + </varlistentry> + </variablelist> + +<!-- This isn't true any more. I'm not sure if we still need it -SDM + <para> + The <literal>ghc-pkg</literal> tool performs expansion of + environment variables occurring in input package specifications. + So, if the <literal>mypkg</literal> was added to the package + database as follows: + </para> +<screen> + $ installdir=/usr/local/lib ghc-pkg -a < mypkg.pkg +</screen> + + <para> + The occurrence of <literal>${installdir}</literal> is replaced + with <literal>/usr/local/lib</literal> in the package data that + is added for <literal>mypkg</literal>. + </para> + + <para> + This feature enables the distribution of package specification + files that can be easily configured when installing. + </para> + + <para>For examples of more package specifications, take a look + at the <literal>package.conf</literal> in your GHC + installation.</para> + +--> + + </sect2> + </sect1> + +<!-- Emacs stuff: + ;;; Local Variables: *** + ;;; mode: xml *** + ;;; sgml-parent-document: ("users_guide.xml" "book" "chapter" "sect1") *** + ;;; End: *** + --> diff --git a/docs/users_guide/parallel.xml b/docs/users_guide/parallel.xml new file mode 100644 index 0000000000..11c2547898 --- /dev/null +++ b/docs/users_guide/parallel.xml @@ -0,0 +1,210 @@ +<?xml version="1.0" encoding="iso-8859-1"?> +<sect1 id="concurrent-and-parallel"> +<title>Concurrent and Parallel Haskell</title> + +<para> +<indexterm><primary>Concurrent Haskell</primary></indexterm> +<indexterm><primary>Parallel Haskell</primary></indexterm> +Concurrent and Parallel Haskell are Glasgow extensions to Haskell +which let you structure your program as a group of independent +`threads'. +</para> + +<para> +Concurrent and Parallel Haskell have very different purposes. +</para> + +<para> +Concurrent Haskell is for applications which have an inherent +structure of interacting, concurrent tasks (i.e. `threads'). Threads +in such programs may be <emphasis>required</emphasis>. For example, if a concurrent thread has been spawned to handle a mouse click, it isn't +optional—the user wants something done! +</para> + +<para> +A Concurrent Haskell program implies multiple `threads' running within +a single Unix process on a single processor. +</para> + +<para> +You will find at least one paper about Concurrent Haskell hanging off +of <ulink url="http://research.microsoft.com/~simonpj/">Simon Peyton +Jones's Web page</ulink>. +</para> + +<para> +Parallel Haskell is about <emphasis>speed</emphasis>—spawning +threads onto multiple processors so that your program will run faster. +The `threads' are always <emphasis>advisory</emphasis>—if the +runtime system thinks it can get the job done more quickly by +sequential execution, then fine. +</para> + +<para> +A Parallel Haskell program implies multiple processes running on +multiple processors, under a PVM (Parallel Virtual Machine) framework. +An MPI interface is under development but not fully functional, yet. +</para> + +<para> +Parallel Haskell is still relatively new; it is more about “research +fun” than about “speed.” That will change. +</para> + +<para> +Check the <ulink url="http://www.cee.hw.ac.uk/~dsg/gph/">GPH Page</ulink> +for more information on “GPH” (Haskell98 with extensions for +parallel execution), the latest version of “GUM” (the runtime +system to enable parallel executions) and papers on research issues. A +list of publications about GPH and about GUM is also available from Simon's +Web Page. +</para> + +<para> +Some details about Parallel Haskell follow. For more information +about concurrent Haskell, see the module +<literal>Control.Concurrent</literal> in the library documentation. +</para> + +<sect2> +<title>Features specific to Parallel Haskell +<indexterm><primary>Parallel Haskell—features</primary></indexterm></title> + +<sect3> +<title>The <literal>Parallel</literal> interface (recommended) +<indexterm><primary>Parallel interface</primary></indexterm></title> + +<para> +GHC provides two functions for controlling parallel execution, through +the <literal>Parallel</literal> interface: +</para> + +<para> + +<programlisting> +interface Parallel where +infixr 0 `par` +infixr 1 `seq` + +par :: a -> b -> b +seq :: a -> b -> b +</programlisting> + +</para> + +<para> +The expression <literal>(x `par` y)</literal> <emphasis>sparks</emphasis> the evaluation of <literal>x</literal> +(to weak head normal form) and returns <literal>y</literal>. Sparks are queued for +execution in FIFO order, but are not executed immediately. At the +next heap allocation, the currently executing thread will yield +control to the scheduler, and the scheduler will start a new thread +(until reaching the active thread limit) for each spark which has not +already been evaluated to WHNF. +</para> + +<para> +The expression <literal>(x `seq` y)</literal> evaluates <literal>x</literal> to weak head normal +form and then returns <literal>y</literal>. The <function>seq</function> primitive can be used to +force evaluation of an expression beyond WHNF, or to impose a desired +execution sequence for the evaluation of an expression. +</para> + +<para> +For example, consider the following parallel version of our old +nemesis, <function>nfib</function>: +</para> + +<para> + +<programlisting> +import Parallel + +nfib :: Int -> Int +nfib n | n <= 1 = 1 + | otherwise = par n1 (seq n2 (n1 + n2 + 1)) + where n1 = nfib (n-1) + n2 = nfib (n-2) +</programlisting> + +</para> + +<para> +For values of <varname>n</varname> greater than 1, we use <function>par</function> to spark a thread +to evaluate <literal>nfib (n-1)</literal>, and then we use <function>seq</function> to force the +parent thread to evaluate <literal>nfib (n-2)</literal> before going on to add +together these two subexpressions. In this divide-and-conquer +approach, we only spark a new thread for one branch of the computation +(leaving the parent to evaluate the other branch). Also, we must use +<function>seq</function> to ensure that the parent will evaluate <varname>n2</varname> <emphasis>before</emphasis> +<varname>n1</varname> in the expression <literal>(n1 + n2 + 1)</literal>. It is not sufficient to +reorder the expression as <literal>(n2 + n1 + 1)</literal>, because the compiler may +not generate code to evaluate the addends from left to right. +</para> + +</sect3> + +<sect3> +<title>Underlying functions and primitives +<indexterm><primary>parallelism primitives</primary></indexterm> +<indexterm><primary>primitives for parallelism</primary></indexterm></title> + +<para> +The functions <function>par</function> and <function>seq</function> are wired into GHC, and unfold +into uses of the <function>par#</function> and <function>seq#</function> primitives, respectively. If +you'd like to see this with your very own eyes, just run GHC with the +<option>-ddump-simpl</option> option. (Anything for a good time…) +</para> + +</sect3> + +<sect3> +<title>Scheduling policy for concurrent threads +<indexterm><primary>Scheduling—concurrent</primary></indexterm> +<indexterm><primary>Concurrent scheduling</primary></indexterm></title> + +<para> +Runnable threads are scheduled in round-robin fashion. Context +switches are signalled by the generation of new sparks or by the +expiry of a virtual timer (the timer interval is configurable with the +<option>-C[<num>]</option><indexterm><primary>-C<num> RTS option (concurrent, +parallel)</primary></indexterm> RTS option). However, a context switch doesn't +really happen until the current heap block is full. You can't get any +faster context switching than this. +</para> + +<para> +When a context switch occurs, pending sparks which have not already +been reduced to weak head normal form are turned into new threads. +However, there is a limit to the number of active threads (runnable or +blocked) which are allowed at any given time. This limit can be +adjusted with the <option>-t<num></option><indexterm><primary>-t <num> RTS option (concurrent, parallel)</primary></indexterm> +RTS option (the default is 32). Once the +thread limit is reached, any remaining sparks are deferred until some +of the currently active threads are completed. +</para> + +</sect3> + +<sect3> +<title>Scheduling policy for parallel threads +<indexterm><primary>Scheduling—parallel</primary></indexterm> +<indexterm><primary>Parallel scheduling</primary></indexterm></title> + +<para> +In GUM we use an unfair scheduler, which means that a thread continues to +perform graph reduction until it blocks on a closure under evaluation, on a +remote closure or until the thread finishes. +</para> + +</sect3> + +</sect2> + +</sect1> + +<!-- Emacs stuff: + ;;; Local Variables: *** + ;;; mode: xml *** + ;;; sgml-parent-document: ("users_guide.xml" "book" "chapter" "sect1") *** + ;;; End: *** + --> diff --git a/docs/users_guide/phases.xml b/docs/users_guide/phases.xml new file mode 100644 index 0000000000..fd034a305a --- /dev/null +++ b/docs/users_guide/phases.xml @@ -0,0 +1,874 @@ +<?xml version="1.0" encoding="iso-8859-1"?> +<sect1 id="options-phases"> + <title>Options related to a particular phase</title> + + <sect2 id="replacing-phases"> + <title>Replacing the program for one or more phases</title> + <indexterm><primary>phases, changing</primary></indexterm> + + <para>You may specify that a different program be used for one + of the phases of the compilation system, in place of whatever + the <command>ghc</command> has wired into it. For example, you + might want to try a different assembler. The following options + allow you to change the external program used for a given + compilation phase:</para> + + <variablelist> + <varlistentry> + <term> + <option>-pgmL</option> <replaceable>cmd</replaceable> + <indexterm><primary><option>-pgmL</option></primary></indexterm> + </term> + <listitem> + <para>Use <replaceable>cmd</replaceable> as the literate + pre-processor.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <option>-pgmP</option> <replaceable>cmd</replaceable> + <indexterm><primary><option>-pgmP</option></primary></indexterm> + </term> + <listitem> + <para>Use <replaceable>cmd</replaceable> as the C + pre-processor (with <option>-cpp</option> only).</para> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <option>-pgmc</option> <replaceable>cmd</replaceable> + <indexterm><primary><option>-pgmc</option></primary></indexterm> + </term> + <listitem> + <para>Use <replaceable>cmd</replaceable> as the C + compiler.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <option>-pgma</option> <replaceable>cmd</replaceable> + <indexterm><primary><option>-pgma</option></primary></indexterm> + </term> + <listitem> + <para>Use <replaceable>cmd</replaceable> as the + assembler.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <option>-pgml</option> <replaceable>cmd</replaceable> + <indexterm><primary><option>-pgml</option></primary></indexterm> + </term> + <listitem> + <para>Use <replaceable>cmd</replaceable> as the + linker.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <option>-pgmdll</option> <replaceable>cmd</replaceable> + <indexterm><primary><option>-pgmdll</option></primary></indexterm> + </term> + <listitem> + <para>Use <replaceable>cmd</replaceable> as the DLL + generator.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <option>-pgmdep</option> <replaceable>cmd</replaceable> + <indexterm><primary><option>-pgmdep</option></primary></indexterm> + </term> + <listitem> + <para>Use <replaceable>cmd</replaceable> as the dependency + generator.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <option>-pgmF</option> <replaceable>cmd</replaceable> + <indexterm><primary><option>-pgmF</option></primary></indexterm> + </term> + <listitem> + <para>Use <replaceable>cmd</replaceable> as the + pre-processor (with <option>-F</option> only).</para> + </listitem> + </varlistentry> + + + </variablelist> + </sect2> + + <sect2 id="forcing-options-through"> + <title>Forcing options to a particular phase</title> + <indexterm><primary>forcing GHC-phase options</primary></indexterm> + + <para>Options can be forced through to a particlar compilation + phase, using the following flags:</para> + + <variablelist> + <varlistentry> + <term> + <option>-optL</option> <replaceable>option</replaceable> + <indexterm><primary><option>-optL</option></primary></indexterm> + </term> + <listitem> + <para>Pass <replaceable>option</replaceable> to the + literate pre-processor</para> + </listitem> + </varlistentry> + <varlistentry> + <term> + <option>-optP</option> <replaceable>option</replaceable> + <indexterm><primary><option>-optP</option></primary></indexterm> + </term> + <listitem> + <para>Pass <replaceable>option</replaceable> to CPP (makes + sense only if <option>-cpp</option> is also on).</para> + </listitem> + </varlistentry> + <varlistentry> + <term> + <option>-optF</option> <replaceable>option</replaceable> + <indexterm><primary><option>-optF</option></primary></indexterm> + </term> + <listitem> + <para>Pass <replaceable>option</replaceable> to the + custom pre-processor (see <xref linkend="pre-processor"/>).</para> + </listitem> + </varlistentry> + <varlistentry> + <term> + <option>-optc</option> <replaceable>option</replaceable> + <indexterm><primary><option>-optc</option></primary></indexterm> + </term> + <listitem> + <para>Pass <replaceable>option</replaceable> to the C compiler.</para> + </listitem> + </varlistentry> + <varlistentry> + <term> + <option>-opta</option> <replaceable>option</replaceable> + <indexterm><primary><option>-opta</option></primary></indexterm> + </term> + <listitem> + <para>Pass <replaceable>option</replaceable> to the assembler.</para> + </listitem> + </varlistentry> + <varlistentry> + <term> + <option>-optl</option> <replaceable>option</replaceable> + <indexterm><primary><option>-optl</option></primary></indexterm> + </term> + <listitem> + <para>Pass <replaceable>option</replaceable> to the linker.</para> + </listitem> + </varlistentry> + <varlistentry> + <term> + <option>-optdll</option> <replaceable>option</replaceable> + <indexterm><primary><option>-optdll</option></primary></indexterm> + </term> + <listitem> + <para>Pass <replaceable>option</replaceable> to the DLL generator.</para> + </listitem> + </varlistentry> + <varlistentry> + <term> + <option>-optdep</option> <replaceable>option</replaceable> + <indexterm><primary><option>-optdep</option></primary></indexterm> + </term> + <listitem> + <para>Pass <replaceable>option</replaceable> to the + dependency generator.</para> + </listitem> + </varlistentry> + </variablelist> + + <para>So, for example, to force an <option>-Ewurble</option> + option to the assembler, you would tell the driver + <option>-opta-Ewurble</option> (the dash before the E is + required).</para> + + <para>GHC is itself a Haskell program, so if you need to pass + options directly to GHC's runtime system you can enclose them in + <literal>+RTS ... -RTS</literal> (see <xref + linkend="runtime-control"/>).</para> + + </sect2> + + <sect2 id="c-pre-processor"> + <title>Options affecting the C pre-processor</title> + + <indexterm><primary>pre-processing: cpp</primary></indexterm> + <indexterm><primary>C pre-processor options</primary></indexterm> + <indexterm><primary>cpp, pre-processing with</primary></indexterm> + + <variablelist> + + <varlistentry> + <term> + <option>-cpp</option> + <indexterm><primary><option>-cpp</option></primary></indexterm> + </term> + <listitem> + <para>The C pre-processor <command>cpp</command> is run + over your Haskell code only if the <option>-cpp</option> + option <indexterm><primary>-cpp + option</primary></indexterm> is given. Unless you are + building a large system with significant doses of + conditional compilation, you really shouldn't need + it.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <option>-D</option><replaceable>symbol</replaceable><optional>=<replaceable>value</replaceable></optional> + <indexterm><primary><option>-D</option></primary></indexterm> + </term> + <listitem> + <para>Define macro <replaceable>symbol</replaceable> in the + usual way. NB: does <emphasis>not</emphasis> affect + <option>-D</option> macros passed to the C compiler + when compiling via C! For those, use the + <option>-optc-Dfoo</option> hack… (see <xref + linkend="forcing-options-through"/>).</para> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <option>-U</option><replaceable>symbol</replaceable> + <indexterm><primary><option>-U</option></primary></indexterm> + </term> + <listitem> + <para> Undefine macro <replaceable>symbol</replaceable> in the + usual way.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <option>-I</option><replaceable>dir</replaceable> + <indexterm><primary><option>-I</option></primary></indexterm> + </term> + <listitem> + <para> Specify a directory in which to look for + <literal>#include</literal> files, in the usual C + way.</para> + </listitem> + </varlistentry> + </variablelist> + + <para>The GHC driver pre-defines several macros when processing + Haskell source code (<filename>.hs</filename> or + <filename>.lhs</filename> files).</para> + + <para>The symbols defined by GHC are listed below. To check which + symbols are defined by your local GHC installation, the following + trick is useful:</para> + +<screen>$ ghc -E -optP-dM -cpp foo.hs +$ cat foo.hspp</screen> + + <para>(you need a file <filename>foo.hs</filename>, but it isn't + actually used).</para> + + <variablelist> + <varlistentry> + <term> + <constant>__HASKELL98__</constant> + <indexterm><primary><literal>__HASKELL98__</literal></primary></indexterm> + </term> + <listitem> + <para>If defined, this means that GHC supports the + language defined by the Haskell 98 report.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <constant>__HASKELL__=98</constant> + <indexterm><primary><constant>__HASKELL__=98</constant></primary></indexterm> + </term> + <listitem> + <para>In GHC 4.04 and later, the + <constant>__HASKELL__</constant> + macro is defined as having the value + <constant>98</constant>.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <constant>__HASKELL1__</constant> + <indexterm><primary><constant>__HASKELL1__</constant></primary></indexterm> + </term> + <listitem> + <para>If defined to <replaceable>n</replaceable>, that + means GHC supports the Haskell language defined in the + Haskell report version <emphasis>1.n</emphasis>. + Currently 5. This macro is deprecated, and will probably + disappear in future versions.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <constant>__GLASGOW_HASKELL__</constant> + <indexterm><primary><constant>__GLASGOW_HASKELL__</constant></primary></indexterm> + </term> + <listitem> + <para>For version + <literal><replaceable>x</replaceable>.<replaceable>y</replaceable>.<replaceable>z</replaceable></literal> + of GHC, the value of + <constant>__GLASGOW_HASKELL__</constant> + is the integer <replaceable>xyy</replaceable> (if + <replaceable>y</replaceable> is a single digit, then a leading zero + is added, so for example in version 6.2 of GHC, + <literal>__GLASGOW_HASKELL__==602</literal>). More + information in <xref linkend="version-numbering"/>.</para> + + <para>With any luck, + <constant>__GLASGOW_HASKELL__</constant> + will be undefined in all other implementations that + support C-style pre-processing.</para> + + <para>(For reference: the comparable symbols for other + systems are: + <constant>__HUGS__</constant> + for Hugs, + <constant>__NHC__</constant> + for nhc98, and + <constant>__HBC__</constant> + for hbc.)</para> + + <para>NB. This macro is set when pre-processing both + Haskell source and C source, including the C source + generated from a Haskell module + (i.e. <filename>.hs</filename>, <filename>.lhs</filename>, + <filename>.c</filename> and <filename>.hc</filename> + files).</para> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <constant>__CONCURRENT_HASKELL__</constant> + <indexterm><primary><constant>__CONCURRENT_HASKELL__</constant></primary></indexterm> + </term> + <listitem> + <para>This symbol is defined when pre-processing Haskell + (input) and pre-processing C (GHC output). Since GHC from + verion 4.00 now supports concurrent haskell by default, + this symbol is always defined.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <constant>__PARALLEL_HASKELL__</constant> + <indexterm><primary><constant>__PARALLEL_HASKELL__</constant></primary></indexterm> + </term> + <listitem> + <para>Only defined when <option>-parallel</option> is in + use! This symbol is defined when pre-processing Haskell + (input) and pre-processing C (GHC output).</para> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <constant><replaceable>os</replaceable>_HOST_OS=1</constant> + </term> + <listitem> + <para>This define allows conditional compilation based on + the Operating System, where<replaceable>os</replaceable> is + the name of the current Operating System + (eg. <literal>linux</literal>, <literal>mingw32</literal> + for Windows, <literal>solaris</literal>, etc.).</para> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <constant><replaceable>arch</replaceable>_HOST_ARCH=1</constant> + </term> + <listitem> + <para>This define allows conditional compilation based on + the host architecture, where<replaceable>arch</replaceable> + is the name of the current architecture + (eg. <literal>i386</literal>, <literal>x86_64</literal>, + <literal>powerpc</literal>, <literal>sparc</literal>, + etc.).</para> + </listitem> + </varlistentry> + </variablelist> + + <sect3 id="cpp-string-gaps"> + <title>CPP and string gaps</title> + + <para>A small word of warning: <option>-cpp</option> is not + friendly to “string gaps”.<indexterm><primary>-cpp + vs string gaps</primary></indexterm><indexterm><primary>string + gaps vs -cpp</primary></indexterm>. In other words, strings + such as the following:</para> + +<programlisting>strmod = "\ +\ p \ +\ "</programlisting> + + <para>don't work with <option>-cpp</option>; + <filename>/usr/bin/cpp</filename> elides the backslash-newline + pairs.</para> + + <para>However, it appears that if you add a space at the end + of the line, then <command>cpp</command> (at least GNU + <command>cpp</command> and possibly other + <command>cpp</command>s) leaves the backslash-space pairs + alone and the string gap works as expected.</para> + </sect3> + </sect2> + + <sect2 id="pre-processor"> + <title>Options affecting a Haskell pre-processor</title> + + <indexterm><primary>pre-processing: custom</primary></indexterm> + <indexterm><primary>Pre-processor options</primary></indexterm> + + <variablelist> + <varlistentry> + <term> + <option>-F</option> + <indexterm><primary><option>-F</option></primary></indexterm> + </term> + <listitem> + <para>A custom pre-processor is run over your Haskell + source file only if the <option>-F</option> option + <indexterm><primary>-F</primary></indexterm> is + given.</para> + + <para>Running a custom pre-processor at compile-time is in + some settings appropriate and useful. The + <option>-F</option> option lets you run a pre-processor as + part of the overall GHC compilation pipeline, which has + the advantage over running a Haskell pre-processor + separately in that it works in interpreted mode and you + can continue to take reap the benefits of GHC's + recompilation checker.</para> + + <para>The pre-processor is run just before the Haskell + compiler proper processes the Haskell input, but after the + literate markup has been stripped away and (possibly) the + C pre-processor has washed the Haskell input.</para> + + <para>Use + <option>-pgmF <replaceable>cmd</replaceable></option> + to select the program to use as the preprocessor. When + invoked, the <replaceable>cmd</replaceable> pre-processor + is given at least three arguments on its command-line: the + first argument is the name of the original source file, + the second is the name of the file holding the input, and + the third is the name of the file where + <replaceable>cmd</replaceable> should write its output + to.</para> + + <para>Additional arguments to the pre-processor can be + passed in using the <option>-optF</option> option. These + are fed to <replaceable>cmd</replaceable> on the command + line after the three standard input and output + arguments.</para> + </listitem> + </varlistentry> + </variablelist> + </sect2> + + <sect2 id="options-C-compiler"> + <title>Options affecting the C compiler (if applicable)</title> + + <indexterm><primary>include-file options</primary></indexterm> + <indexterm><primary>C compiler options</primary></indexterm> + <indexterm><primary>GCC options</primary></indexterm> + + <para>If you are compiling with lots of foreign calls, you may + need to tell the C compiler about some + <literal>#include</literal> files. The Right Way to do this is to + add an <literal>INCLUDE</literal> pragma to the top of your source file + (<xref linkend="include-pragma" />):</para> + +<programlisting>{-# INCLUDE <X/Xlib.h> #-}</programlisting> + + <para>Sometimes this isn't convenient. In those cases there's an + equivalent command-line option:</para> + +<screen>% ghc -c '-#include <X/Xlib.h>' Xstuff.lhs</screen> + + <indexterm><primary><option>-#include</option></primary> + </indexterm> + + </sect2> + + <sect2 id="options-codegen"> + <title>Options affecting code generation</title> + + <variablelist> + <varlistentry> + <term> + <option>-fasm</option> + <indexterm><primary><option>-fasm</option></primary></indexterm> + </term> + <listitem> + <para>Use GHC's native code generator rather than + compiling via C. This will compile faster (up to twice as + fast), but may produce code that is slightly slower than + compiling via C. <option>-fasm</option> is the default + when optimisation is off (see <xref + linkend="options-optimise"/>).</para> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <option>-fvia-C</option> + <indexterm><primary><option>-fvia-C</option></primary></indexterm> + </term> + <listitem> + <para>Compile via C instead of using the native code + generator. This is default for optimised compilations, + and on architectures for which GHC doesn't have a native + code generator.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <option>-fno-code</option> + <indexterm><primary><option>-fno-code</option></primary></indexterm> + </term> + <listitem> + <para>Omit code generation (and all later phases) + altogether. Might be of some use if you just want to see + dumps of the intermediate compilation phases.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <option>-fPIC</option> + <indexterm><primary><option>-fPIC</option></primary></indexterm> + </term> + <listitem> + <para>Generate position-independent code (code that can be put into + shared libraries). This currently works on Mac OS X; it works on + PowerPC Linux when using the native code generator (-fasm). + It is not quite ready to be used yet for x86 Linux. + On Windows, position-independent code is never used, + and on PowerPC64 Linux, position-independent code is always used, + so the flag is a no-op on those platforms.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <option>-dynamic</option> + </term> + <listitem> + <para>When generating code, assume that entities imported from a + different package will reside in a different shared library or + binary. This currently works on Mac OS X; it works on PowerPC Linux when + using the native code generator. As with <option>-fPIC</option>, + x86 Linux support is not quite ready yet. Windows is not supported, + and it is a no-op on PowerPC64 Linux.</para> + <para>Note that this option also causes GHC to use shared libraries + when linking.</para> + </listitem> + </varlistentry> + </variablelist> + </sect2> + + <sect2 id="options-linker"> + <title>Options affecting linking</title> + + <indexterm><primary>linker options</primary></indexterm> + <indexterm><primary>ld options</primary></indexterm> + + + <para>GHC has to link your code with various libraries, possibly + including: user-supplied, GHC-supplied, and system-supplied + (<option>-lm</option> math library, for example).</para> + + <variablelist> + + <varlistentry> + <term> + <option>-l</option><replaceable>lib</replaceable> + <indexterm><primary><option>-l</option></primary></indexterm> + </term> + <listitem> + <para>Link in the <replaceable>lib</replaceable> library. + On Unix systems, this will be in a file called + <filename>lib<replaceable>lib</replaceable>.a</filename> + or + <filename>lib<replaceable>lib</replaceable>.so</filename> + which resides somewhere on the library directories path.</para> + + <para>Because of the sad state of most UNIX linkers, the + order of such options does matter. If library + <replaceable>foo</replaceable> requires library + <replaceable>bar</replaceable>, then in general + <option>-l</option><replaceable>foo</replaceable> should + come <emphasis>before</emphasis> + <option>-l</option><replaceable>bar</replaceable> on the + command line.</para> + + <para>There's one other gotcha to bear in mind when using + external libraries: if the library contains a + <literal>main()</literal> function, then this will be + linked in preference to GHC's own + <literal>main()</literal> function + (eg. <literal>libf2c</literal> and <literal>libl</literal> + have their own <literal>main()</literal>s). This is + because GHC's <literal>main()</literal> comes from the + <literal>HSrts</literal> library, which is normally + included <emphasis>after</emphasis> all the other + libraries on the linker's command line. To force GHC's + <literal>main()</literal> to be used in preference to any + other <literal>main()</literal>s from external libraries, + just add the option <option>-lHSrts</option> before any + other libraries on the command line.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <option>-c</option> + <indexterm><primary><option>-c</option></primary></indexterm> + </term> + <listitem> + <para>Omits the link step. This option can be used with + <option>––make</option> to avoid the automatic linking + that takes place if the program contains a <literal>Main</literal> + module.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <option>-package</option> <replaceable>name</replaceable> + <indexterm><primary><option>-package</option></primary></indexterm> + </term> + <listitem> + <para>If you are using a Haskell “package” + (see <xref linkend="packages"/>), don't forget to add the + relevant <option>-package</option> option when linking the + program too: it will cause the appropriate libraries to be + linked in with the program. Forgetting the + <option>-package</option> option will likely result in + several pages of link errors.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <option>-framework</option> <replaceable>name</replaceable> + <indexterm><primary><option>-framework</option></primary></indexterm> + </term> + <listitem> + <para>On Darwin/MacOS X only, link in the framework <replaceable>name</replaceable>. + This option corresponds to the <option>-framework</option> option for Apple's Linker. + Please note that frameworks and packages are two different things - frameworks don't + contain any haskell code. Rather, they are Apple's way of packaging shared libraries. + To link to Apple's “Carbon” API, for example, you'd use + <option>-framework Carbon</option>. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <option>-L</option><replaceable>dir</replaceable> + <indexterm><primary><option>-L</option></primary></indexterm> + </term> + <listitem> + <para>Where to find user-supplied libraries… + Prepend the directory <replaceable>dir</replaceable> to + the library directories path.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <option>-framework-path</option><replaceable>dir</replaceable> + <indexterm><primary><option>-framework-path</option></primary></indexterm> + </term> + <listitem> + <para>On Darwin/MacOS X only, prepend the directory <replaceable>dir</replaceable> to + the framework directories path. This option corresponds to the <option>-F</option> + option for Apple's Linker (<option>-F</option> already means something else for GHC).</para> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <option>-split-objs</option> + <indexterm><primary><option>-split-objs</option></primary></indexterm> + </term> + <listitem> + <para>Tell the linker to split the single object file that + would normally be generated into multiple object files, + one per top-level Haskell function or type in the module. + We use this feature for building GHC's libraries libraries + (warning: don't use it unless you know what you're + doing!).</para> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <option>-static</option> + <indexterm><primary><option>-static</option></primary></indexterm> + </term> + <listitem> + <para>Tell the linker to avoid shared Haskell libraries, + if possible. This is the default.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <option>-dynamic</option> + <indexterm><primary><option>-dynamic</option></primary></indexterm> + </term> + <listitem> + <para>Tell the linker to use shared Haskell libraries, if + available (this option is only supported on Mac OS X at the + moment, and also note that your distribution of GHC may + not have been supplied with shared libraries).</para> + <para>Note that this option also has an effect on + code generation (see above).</para> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <option>-main-is <replaceable>thing</replaceable></option> + <indexterm><primary><option>-main-is</option></primary></indexterm> + <indexterm><primary>specifying your own main function</primary></indexterm> + </term> + <listitem> + <para> The normal rule in Haskell is that your program must supply a <literal>main</literal> + function in module <literal>Main</literal>. When testing, it is often convenient + to change which function is the "main" one, and the <option>-main-is</option> flag + allows you to do so. The <replaceable>thing</replaceable> can be one of: + <itemizedlist> + <listitem><para>A lower-case identifier <literal>foo</literal>. GHC assumes that the main function is <literal>Main.foo</literal>.</para></listitem> + <listitem><para>An module name <literal>A</literal>. GHC assumes that the main function is <literal>A.main</literal>.</para></listitem> + <listitem><para>An qualified name <literal>A.foo</literal>. GHC assumes that the main function is <literal>A.foo</literal>.</para></listitem> + </itemizedlist> + Strictly speaking, <option>-main-is</option> is not a link-phase flag at all; it has no effect on the link step. + The flag must be specified when compiling the module containing the specified main function (e.g. module <literal>A</literal> + in the latter two items above). It has no effect for other modules, + and hence can safely be given to <literal>ghc --make</literal>. + However, if all the modules are otherwise up to date, you may need to force + recompilation both of the module where the new "main" is, and of the + module where the "main" function used to be; + <literal>ghc</literal> is not clever + enough to figure out that they both need recompiling. You can + force recompilation by removing the object file, or by using the + <option>-no-recomp</option> flag. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <option>-no-hs-main</option> + <indexterm><primary><option>-no-hs-main</option></primary></indexterm> + <indexterm><primary>linking Haskell libraries with foreign code</primary></indexterm> + </term> + <listitem> + <para>In the event you want to include ghc-compiled code + as part of another (non-Haskell) program, the RTS will not + be supplying its definition of <function>main()</function> + at link-time, you will have to. To signal that to the + compiler when linking, use + <option>-no-hs-main</option>. See also <xref linkend="using-own-main"/>.</para> + + <para>Notice that since the command-line passed to the + linker is rather involved, you probably want to use + <command>ghc</command> to do the final link of your + `mixed-language' application. This is not a requirement + though, just try linking once with <option>-v</option> on + to see what options the driver passes through to the + linker.</para> + + <para>The <option>-no-hs-main</option> flag can also be + used to persuade the compiler to do the link step in + <option>--make</option> mode when there is no Haskell + <literal>Main</literal> module present (normally the + compiler will not attempt linking when there is no + <literal>Main</literal>).</para> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <option>-debug</option> + <indexterm><primary><option>-debug</option></primary></indexterm> + </term> + <listitem> + <para>Link the program with a debugging version of the + runtime system. The debugging runtime turns on numerous + assertions and sanity checks, and provides extra options + for producing debugging output at runtime (run the program + with <literal>+RTS -?</literal> to see a list).</para> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <option>-threaded</option> + <indexterm><primary><option>-threaded</option></primary></indexterm> + </term> + <listitem> + <para>Link the program with the "threaded" runtime system. + This version of the runtime is designed to be used in + programs that use multiple operating-system threads. It + supports calls to foreign-exported functions from multiple + OS threads. Calls to foreign functions are made using the + same OS thread that created the Haskell thread (if it was + created by a call-in), or an arbitrary OS thread otherwise + (if the Haskell thread was created by + <literal>forkIO</literal>).</para> + + <para>More details on the use of "bound threads" in the + threaded runtime can be found in the <ulink + url="../libraries/base/Control.Concurrent.html"><literal>Control.Concurrent</literal></ulink> module.</para> + + <para>The threaded RTS does <emphasis>not</emphasis> + support using multiple CPUs to speed up execution of a + multi-threaded Haskell program. The GHC runtime platform + is still single-threaded, but using the + <option>-threaded</option> option it can be used safely in + a multi-threaded environment.</para> + </listitem> + </varlistentry> + </variablelist> + </sect2> + +</sect1> + +<!-- Emacs stuff: + ;;; Local Variables: *** + ;;; mode: xml *** + ;;; sgml-parent-document: ("users_guide.xml" "book" "chapter" "sect1") *** + ;;; End: *** + --> diff --git a/docs/users_guide/primitives.xml b/docs/users_guide/primitives.xml new file mode 100644 index 0000000000..e41bb59ee1 --- /dev/null +++ b/docs/users_guide/primitives.xml @@ -0,0 +1,1215 @@ +<?xml version="1.0" encoding="iso-8859-1"?> +<!-- UNBOXED TYPES AND PRIMITIVE OPERATIONS --> + +<sect1 id="primitives"> + <title>Unboxed types and primitive operations</title> + <indexterm><primary>GHC.Exts module</primary></indexterm> + + <para>This chapter defines all the types which are primitive in + Glasgow Haskell, and the operations provided for them. You bring + them into scope by importing module <literal>GHC.Exts</literal>.</para> + + <para>Note: while you really can use this stuff to write fast code, + we generally find it a lot less painful, and more satisfying in the + long run, to use higher-level language features and libraries. With + any luck, the code you write will be optimised to the efficient + unboxed version in any case. And if it isn't, we'd like to know + about it.</para> + +<sect2 id="glasgow-unboxed"> +<title>Unboxed types +</title> + +<para> +<indexterm><primary>Unboxed types (Glasgow extension)</primary></indexterm> +</para> + +<para>Most types in GHC are <firstterm>boxed</firstterm>, which means +that values of that type are represented by a pointer to a heap +object. The representation of a Haskell <literal>Int</literal>, for +example, is a two-word heap object. An <firstterm>unboxed</firstterm> +type, however, is represented by the value itself, no pointers or heap +allocation are involved. +</para> + +<para> +Unboxed types correspond to the “raw machine” types you +would use in C: <literal>Int#</literal> (long int), +<literal>Double#</literal> (double), <literal>Addr#</literal> +(void *), etc. The <emphasis>primitive operations</emphasis> +(PrimOps) on these types are what you might expect; e.g., +<literal>(+#)</literal> is addition on +<literal>Int#</literal>s, and is the machine-addition that we all +know and love—usually one instruction. +</para> + +<para> +Primitive (unboxed) types cannot be defined in Haskell, and are +therefore built into the language and compiler. Primitive types are +always unlifted; that is, a value of a primitive type cannot be +bottom. We use the convention that primitive types, values, and +operations have a <literal>#</literal> suffix. +</para> + +<para> +Primitive values are often represented by a simple bit-pattern, such +as <literal>Int#</literal>, <literal>Float#</literal>, +<literal>Double#</literal>. But this is not necessarily the case: +a primitive value might be represented by a pointer to a +heap-allocated object. Examples include +<literal>Array#</literal>, the type of primitive arrays. A +primitive array is heap-allocated because it is too big a value to fit +in a register, and would be too expensive to copy around; in a sense, +it is accidental that it is represented by a pointer. If a pointer +represents a primitive value, then it really does point to that value: +no unevaluated thunks, no indirections…nothing can be at the +other end of the pointer than the primitive value. +</para> + +<para> +There are some restrictions on the use of primitive types, the main +one being that you can't pass a primitive value to a polymorphic +function or store one in a polymorphic data type. This rules out +things like <literal>[Int#]</literal> (i.e. lists of primitive +integers). The reason for this restriction is that polymorphic +arguments and constructor fields are assumed to be pointers: if an +unboxed integer is stored in one of these, the garbage collector would +attempt to follow it, leading to unpredictable space leaks. Or a +<function>seq</function> operation on the polymorphic component may +attempt to dereference the pointer, with disastrous results. Even +worse, the unboxed value might be larger than a pointer +(<literal>Double#</literal> for instance). +</para> + +<para> +Nevertheless, A numerically-intensive program using unboxed types can +go a <emphasis>lot</emphasis> faster than its “standard” +counterpart—we saw a threefold speedup on one example. +</para> + +</sect2> + +<sect2 id="unboxed-tuples"> +<title>Unboxed Tuples +</title> + +<para> +Unboxed tuples aren't really exported by <literal>GHC.Exts</literal>, +they're available by default with <option>-fglasgow-exts</option>. An +unboxed tuple looks like this: +</para> + +<para> + +<programlisting> +(# e_1, ..., e_n #) +</programlisting> + +</para> + +<para> +where <literal>e_1..e_n</literal> are expressions of any +type (primitive or non-primitive). The type of an unboxed tuple looks +the same. +</para> + +<para> +Unboxed tuples are used for functions that need to return multiple +values, but they avoid the heap allocation normally associated with +using fully-fledged tuples. When an unboxed tuple is returned, the +components are put directly into registers or on the stack; the +unboxed tuple itself does not have a composite representation. Many +of the primitive operations listed in this section return unboxed +tuples. +</para> + +<para> +There are some pretty stringent restrictions on the use of unboxed tuples: +</para> + +<para> + +<itemizedlist> +<listitem> + +<para> + Unboxed tuple types are subject to the same restrictions as +other unboxed types; i.e. they may not be stored in polymorphic data +structures or passed to polymorphic functions. + +</para> +</listitem> +<listitem> + +<para> + Unboxed tuples may only be constructed as the direct result of +a function, and may only be deconstructed with a <literal>case</literal> expression. +eg. the following are valid: + + +<programlisting> +f x y = (# x+1, y-1 #) +g x = case f x x of { (# a, b #) -> a + b } +</programlisting> + + +but the following are invalid: + + +<programlisting> +f x y = g (# x, y #) +g (# x, y #) = x + y +</programlisting> + + +</para> +</listitem> +<listitem> + +<para> + No variable can have an unboxed tuple type. This is illegal: + + +<programlisting> +f :: (# Int, Int #) -> (# Int, Int #) +f x = x +</programlisting> + + +because <literal>x</literal> has an unboxed tuple type. + +</para> +</listitem> + +</itemizedlist> + +</para> + +<para> +Note: we may relax some of these restrictions in the future. +</para> + +<para> +The <literal>IO</literal> and <literal>ST</literal> monads use unboxed +tuples to avoid unnecessary allocation during sequences of operations. +</para> + +</sect2> + +<sect2> +<title>Character and numeric types</title> + +<indexterm><primary>character types, primitive</primary></indexterm> +<indexterm><primary>numeric types, primitive</primary></indexterm> +<indexterm><primary>integer types, primitive</primary></indexterm> +<indexterm><primary>floating point types, primitive</primary></indexterm> +<para> +There are the following obvious primitive types: +</para> + +<programlisting> +type Char# +type Int# +type Word# +type Addr# +type Float# +type Double# +type Int64# +type Word64# +</programlisting> + +<indexterm><primary><literal>Char#</literal></primary></indexterm> +<indexterm><primary><literal>Int#</literal></primary></indexterm> +<indexterm><primary><literal>Word#</literal></primary></indexterm> +<indexterm><primary><literal>Addr#</literal></primary></indexterm> +<indexterm><primary><literal>Float#</literal></primary></indexterm> +<indexterm><primary><literal>Double#</literal></primary></indexterm> +<indexterm><primary><literal>Int64#</literal></primary></indexterm> +<indexterm><primary><literal>Word64#</literal></primary></indexterm> + +<para> +If you really want to know their exact equivalents in C, see +<filename>ghc/includes/StgTypes.h</filename> in the GHC source tree. +</para> + +<para> +Literals for these types may be written as follows: +</para> + +<para> + +<programlisting> +1# an Int# +1.2# a Float# +1.34## a Double# +'a'# a Char#; for weird characters, use e.g. '\o<octal>'# +"a"# an Addr# (a `char *'); only characters '\0'..'\255' allowed +</programlisting> + +<indexterm><primary>literals, primitive</primary></indexterm> +<indexterm><primary>constants, primitive</primary></indexterm> +<indexterm><primary>numbers, primitive</primary></indexterm> +</para> + +</sect2> + +<sect2> +<title>Comparison operations</title> + +<para> +<indexterm><primary>comparisons, primitive</primary></indexterm> +<indexterm><primary>operators, comparison</primary></indexterm> +</para> + +<para> + +<programlisting> +{>,>=,==,/=,<,<=}# :: Int# -> Int# -> Bool + +{gt,ge,eq,ne,lt,le}Char# :: Char# -> Char# -> Bool + -- ditto for Word# and Addr# +</programlisting> + +<indexterm><primary><literal>>#</literal></primary></indexterm> +<indexterm><primary><literal>>=#</literal></primary></indexterm> +<indexterm><primary><literal>==#</literal></primary></indexterm> +<indexterm><primary><literal>/=#</literal></primary></indexterm> +<indexterm><primary><literal><#</literal></primary></indexterm> +<indexterm><primary><literal><=#</literal></primary></indexterm> +<indexterm><primary><literal>gt{Char,Word,Addr}#</literal></primary></indexterm> +<indexterm><primary><literal>ge{Char,Word,Addr}#</literal></primary></indexterm> +<indexterm><primary><literal>eq{Char,Word,Addr}#</literal></primary></indexterm> +<indexterm><primary><literal>ne{Char,Word,Addr}#</literal></primary></indexterm> +<indexterm><primary><literal>lt{Char,Word,Addr}#</literal></primary></indexterm> +<indexterm><primary><literal>le{Char,Word,Addr}#</literal></primary></indexterm> +</para> + +</sect2> + +<sect2> +<title>Primitive-character operations</title> + +<para> +<indexterm><primary>characters, primitive operations</primary></indexterm> +<indexterm><primary>operators, primitive character</primary></indexterm> +</para> + +<para> + +<programlisting> +ord# :: Char# -> Int# +chr# :: Int# -> Char# +</programlisting> + +<indexterm><primary><literal>ord#</literal></primary></indexterm> +<indexterm><primary><literal>chr#</literal></primary></indexterm> +</para> + +</sect2> + +<sect2> +<title>Primitive-<literal>Int</literal> operations</title> + +<para> +<indexterm><primary>integers, primitive operations</primary></indexterm> +<indexterm><primary>operators, primitive integer</primary></indexterm> +</para> + +<para> + +<programlisting> +{+,-,*,quotInt,remInt,gcdInt}# :: Int# -> Int# -> Int# +negateInt# :: Int# -> Int# + +iShiftL#, iShiftRA#, iShiftRL# :: Int# -> Int# -> Int# + -- shift left, right arithmetic, right logical + +addIntC#, subIntC#, mulIntC# :: Int# -> Int# -> (# Int#, Int# #) + -- add, subtract, multiply with carry +</programlisting> + +<indexterm><primary><literal>+#</literal></primary></indexterm> +<indexterm><primary><literal>-#</literal></primary></indexterm> +<indexterm><primary><literal>*#</literal></primary></indexterm> +<indexterm><primary><literal>quotInt#</literal></primary></indexterm> +<indexterm><primary><literal>remInt#</literal></primary></indexterm> +<indexterm><primary><literal>gcdInt#</literal></primary></indexterm> +<indexterm><primary><literal>iShiftL#</literal></primary></indexterm> +<indexterm><primary><literal>iShiftRA#</literal></primary></indexterm> +<indexterm><primary><literal>iShiftRL#</literal></primary></indexterm> +<indexterm><primary><literal>addIntC#</literal></primary></indexterm> +<indexterm><primary><literal>subIntC#</literal></primary></indexterm> +<indexterm><primary><literal>mulIntC#</literal></primary></indexterm> +<indexterm><primary>shift operations, integer</primary></indexterm> +</para> + +<para> +<emphasis>Note:</emphasis> No error/overflow checking! +</para> + +</sect2> + +<sect2> +<title>Primitive-<literal>Double</literal> and <literal>Float</literal> operations</title> + +<para> +<indexterm><primary>floating point numbers, primitive</primary></indexterm> +<indexterm><primary>operators, primitive floating point</primary></indexterm> +</para> + +<para> + +<programlisting> +{+,-,*,/}## :: Double# -> Double# -> Double# +{<,<=,==,/=,>=,>}## :: Double# -> Double# -> Bool +negateDouble# :: Double# -> Double# +double2Int# :: Double# -> Int# +int2Double# :: Int# -> Double# + +{plus,minus,times,divide}Float# :: Float# -> Float# -> Float# +{gt,ge,eq,ne,lt,le}Float# :: Float# -> Float# -> Bool +negateFloat# :: Float# -> Float# +float2Int# :: Float# -> Int# +int2Float# :: Int# -> Float# +</programlisting> + +</para> + +<para> +<indexterm><primary><literal>+##</literal></primary></indexterm> +<indexterm><primary><literal>-##</literal></primary></indexterm> +<indexterm><primary><literal>*##</literal></primary></indexterm> +<indexterm><primary><literal>/##</literal></primary></indexterm> +<indexterm><primary><literal><##</literal></primary></indexterm> +<indexterm><primary><literal><=##</literal></primary></indexterm> +<indexterm><primary><literal>==##</literal></primary></indexterm> +<indexterm><primary><literal>=/##</literal></primary></indexterm> +<indexterm><primary><literal>>=##</literal></primary></indexterm> +<indexterm><primary><literal>>##</literal></primary></indexterm> +<indexterm><primary><literal>negateDouble#</literal></primary></indexterm> +<indexterm><primary><literal>double2Int#</literal></primary></indexterm> +<indexterm><primary><literal>int2Double#</literal></primary></indexterm> +</para> + +<para> +<indexterm><primary><literal>plusFloat#</literal></primary></indexterm> +<indexterm><primary><literal>minusFloat#</literal></primary></indexterm> +<indexterm><primary><literal>timesFloat#</literal></primary></indexterm> +<indexterm><primary><literal>divideFloat#</literal></primary></indexterm> +<indexterm><primary><literal>gtFloat#</literal></primary></indexterm> +<indexterm><primary><literal>geFloat#</literal></primary></indexterm> +<indexterm><primary><literal>eqFloat#</literal></primary></indexterm> +<indexterm><primary><literal>neFloat#</literal></primary></indexterm> +<indexterm><primary><literal>ltFloat#</literal></primary></indexterm> +<indexterm><primary><literal>leFloat#</literal></primary></indexterm> +<indexterm><primary><literal>negateFloat#</literal></primary></indexterm> +<indexterm><primary><literal>float2Int#</literal></primary></indexterm> +<indexterm><primary><literal>int2Float#</literal></primary></indexterm> +</para> + +<para> +And a full complement of trigonometric functions: +</para> + +<para> + +<programlisting> +expDouble# :: Double# -> Double# +logDouble# :: Double# -> Double# +sqrtDouble# :: Double# -> Double# +sinDouble# :: Double# -> Double# +cosDouble# :: Double# -> Double# +tanDouble# :: Double# -> Double# +asinDouble# :: Double# -> Double# +acosDouble# :: Double# -> Double# +atanDouble# :: Double# -> Double# +sinhDouble# :: Double# -> Double# +coshDouble# :: Double# -> Double# +tanhDouble# :: Double# -> Double# +powerDouble# :: Double# -> Double# -> Double# +</programlisting> + +<indexterm><primary>trigonometric functions, primitive</primary></indexterm> +</para> + +<para> +similarly for <literal>Float#</literal>. +</para> + +<para> +There are two coercion functions for <literal>Float#</literal>/<literal>Double#</literal>: +</para> + +<para> + +<programlisting> +float2Double# :: Float# -> Double# +double2Float# :: Double# -> Float# +</programlisting> + +<indexterm><primary><literal>float2Double#</literal></primary></indexterm> +<indexterm><primary><literal>double2Float#</literal></primary></indexterm> +</para> + +<para> +The primitive version of <function>decodeDouble</function> +(<function>encodeDouble</function> is implemented as an external C +function): +</para> + +<para> + +<programlisting> +decodeDouble# :: Double# -> PrelNum.ReturnIntAndGMP +</programlisting> + +<indexterm><primary><literal>encodeDouble#</literal></primary></indexterm> +<indexterm><primary><literal>decodeDouble#</literal></primary></indexterm> +</para> + +<para> +(And the same for <literal>Float#</literal>s.) +</para> + +</sect2> + +<sect2 id="integer-operations"> +<title>Operations on/for <literal>Integers</literal> (interface to GMP) +</title> + +<para> +<indexterm><primary>arbitrary precision integers</primary></indexterm> +<indexterm><primary>Integer, operations on</primary></indexterm> +</para> + +<para> +We implement <literal>Integers</literal> (arbitrary-precision +integers) using the GNU multiple-precision (GMP) package (version +2.0.2). +</para> + +<para> +The data type for <literal>Integer</literal> is either a small +integer, represented by an <literal>Int</literal>, or a large integer +represented using the pieces required by GMP's +<literal>MP_INT</literal> in <filename>gmp.h</filename> (see +<filename>gmp.info</filename> in +<filename>ghc/includes/runtime/gmp</filename>). It comes out as: +</para> + +<para> + +<programlisting> +data Integer = S# Int# -- small integers + | J# Int# ByteArray# -- large integers +</programlisting> + +<indexterm><primary>Integer type</primary></indexterm> The primitive +ops to support large <literal>Integers</literal> use the +“pieces” of the representation, and are as follows: +</para> + +<para> + +<programlisting> +negateInteger# :: Int# -> ByteArray# -> Integer + +{plus,minus,times}Integer#, gcdInteger#, + quotInteger#, remInteger#, divExactInteger# + :: Int# -> ByteArray# + -> Int# -> ByteArray# + -> (# Int#, ByteArray# #) + +cmpInteger# + :: Int# -> ByteArray# + -> Int# -> ByteArray# + -> Int# -- -1 for <; 0 for ==; +1 for > + +cmpIntegerInt# + :: Int# -> ByteArray# + -> Int# + -> Int# -- -1 for <; 0 for ==; +1 for > + +gcdIntegerInt# :: + :: Int# -> ByteArray# + -> Int# + -> Int# + +divModInteger#, quotRemInteger# + :: Int# -> ByteArray# + -> Int# -> ByteArray# + -> (# Int#, ByteArray#, + Int#, ByteArray# #) + +integer2Int# :: Int# -> ByteArray# -> Int# + +int2Integer# :: Int# -> Integer -- NB: no error-checking on these two! +word2Integer# :: Word# -> Integer + +addr2Integer# :: Addr# -> Integer + -- the Addr# is taken to be a `char *' string + -- to be converted into an Integer. +</programlisting> + +<indexterm><primary><literal>negateInteger#</literal></primary></indexterm> +<indexterm><primary><literal>plusInteger#</literal></primary></indexterm> +<indexterm><primary><literal>minusInteger#</literal></primary></indexterm> +<indexterm><primary><literal>timesInteger#</literal></primary></indexterm> +<indexterm><primary><literal>quotInteger#</literal></primary></indexterm> +<indexterm><primary><literal>remInteger#</literal></primary></indexterm> +<indexterm><primary><literal>gcdInteger#</literal></primary></indexterm> +<indexterm><primary><literal>gcdIntegerInt#</literal></primary></indexterm> +<indexterm><primary><literal>divExactInteger#</literal></primary></indexterm> +<indexterm><primary><literal>cmpInteger#</literal></primary></indexterm> +<indexterm><primary><literal>divModInteger#</literal></primary></indexterm> +<indexterm><primary><literal>quotRemInteger#</literal></primary></indexterm> +<indexterm><primary><literal>integer2Int#</literal></primary></indexterm> +<indexterm><primary><literal>int2Integer#</literal></primary></indexterm> +<indexterm><primary><literal>word2Integer#</literal></primary></indexterm> +<indexterm><primary><literal>addr2Integer#</literal></primary></indexterm> +</para> + +</sect2> + +<sect2> +<title>Words and addresses</title> + +<para> +<indexterm><primary>word, primitive type</primary></indexterm> +<indexterm><primary>address, primitive type</primary></indexterm> +<indexterm><primary>unsigned integer, primitive type</primary></indexterm> +<indexterm><primary>pointer, primitive type</primary></indexterm> +</para> + +<para> +A <literal>Word#</literal> is used for bit-twiddling operations. +It is the same size as an <literal>Int#</literal>, but has no sign +nor any arithmetic operations. + +<programlisting> +type Word# -- Same size/etc as Int# but *unsigned* +type Addr# -- A pointer from outside the "Haskell world" (from C, probably); + -- described under "arrays" +</programlisting> + +<indexterm><primary><literal>Word#</literal></primary></indexterm> +<indexterm><primary><literal>Addr#</literal></primary></indexterm> +</para> + +<para> +<literal>Word#</literal>s and <literal>Addr#</literal>s have +the usual comparison operations. Other +unboxed-<literal>Word</literal> ops (bit-twiddling and coercions): +</para> + +<para> + +<programlisting> +{gt,ge,eq,ne,lt,le}Word# :: Word# -> Word# -> Bool + +and#, or#, xor# :: Word# -> Word# -> Word# + -- standard bit ops. + +quotWord#, remWord# :: Word# -> Word# -> Word# + -- word (i.e. unsigned) versions are different from int + -- versions, so we have to provide these explicitly. + +not# :: Word# -> Word# + +shiftL#, shiftRL# :: Word# -> Int# -> Word# + -- shift left, right logical + +int2Word# :: Int# -> Word# -- just a cast, really +word2Int# :: Word# -> Int# +</programlisting> + +<indexterm><primary>bit operations, Word and Addr</primary></indexterm> +<indexterm><primary><literal>gtWord#</literal></primary></indexterm> +<indexterm><primary><literal>geWord#</literal></primary></indexterm> +<indexterm><primary><literal>eqWord#</literal></primary></indexterm> +<indexterm><primary><literal>neWord#</literal></primary></indexterm> +<indexterm><primary><literal>ltWord#</literal></primary></indexterm> +<indexterm><primary><literal>leWord#</literal></primary></indexterm> +<indexterm><primary><literal>and#</literal></primary></indexterm> +<indexterm><primary><literal>or#</literal></primary></indexterm> +<indexterm><primary><literal>xor#</literal></primary></indexterm> +<indexterm><primary><literal>not#</literal></primary></indexterm> +<indexterm><primary><literal>quotWord#</literal></primary></indexterm> +<indexterm><primary><literal>remWord#</literal></primary></indexterm> +<indexterm><primary><literal>shiftL#</literal></primary></indexterm> +<indexterm><primary><literal>shiftRA#</literal></primary></indexterm> +<indexterm><primary><literal>shiftRL#</literal></primary></indexterm> +<indexterm><primary><literal>int2Word#</literal></primary></indexterm> +<indexterm><primary><literal>word2Int#</literal></primary></indexterm> +</para> + +<para> +Unboxed-<literal>Addr</literal> ops (C casts, really): + +<programlisting> +{gt,ge,eq,ne,lt,le}Addr# :: Addr# -> Addr# -> Bool + +int2Addr# :: Int# -> Addr# +addr2Int# :: Addr# -> Int# +addr2Integer# :: Addr# -> (# Int#, ByteArray# #) +</programlisting> + +<indexterm><primary><literal>gtAddr#</literal></primary></indexterm> +<indexterm><primary><literal>geAddr#</literal></primary></indexterm> +<indexterm><primary><literal>eqAddr#</literal></primary></indexterm> +<indexterm><primary><literal>neAddr#</literal></primary></indexterm> +<indexterm><primary><literal>ltAddr#</literal></primary></indexterm> +<indexterm><primary><literal>leAddr#</literal></primary></indexterm> +<indexterm><primary><literal>int2Addr#</literal></primary></indexterm> +<indexterm><primary><literal>addr2Int#</literal></primary></indexterm> +<indexterm><primary><literal>addr2Integer#</literal></primary></indexterm> +</para> + +<para> +The casts between <literal>Int#</literal>, +<literal>Word#</literal> and <literal>Addr#</literal> +correspond to null operations at the machine level, but are required +to keep the Haskell type checker happy. +</para> + +<para> +Operations for indexing off of C pointers +(<literal>Addr#</literal>s) to snatch values are listed under +“arrays”. +</para> + +</sect2> + +<sect2> +<title>Arrays</title> + +<para> +<indexterm><primary>arrays, primitive</primary></indexterm> +</para> + +<para> +The type <literal>Array# elt</literal> is the type of primitive, +unpointed arrays of values of type <literal>elt</literal>. +</para> + +<para> + +<programlisting> +type Array# elt +</programlisting> + +<indexterm><primary><literal>Array#</literal></primary></indexterm> +</para> + +<para> +<literal>Array#</literal> is more primitive than a Haskell +array—indeed, the Haskell <literal>Array</literal> interface is +implemented using <literal>Array#</literal>—in that an +<literal>Array#</literal> is indexed only by +<literal>Int#</literal>s, starting at zero. It is also more +primitive by virtue of being unboxed. That doesn't mean that it isn't +a heap-allocated object—of course, it is. Rather, being unboxed +means that it is represented by a pointer to the array itself, and not +to a thunk which will evaluate to the array (or to bottom). The +components of an <literal>Array#</literal> are themselves boxed. +</para> + +<para> +The type <literal>ByteArray#</literal> is similar to +<literal>Array#</literal>, except that it contains just a string +of (non-pointer) bytes. +</para> + +<para> + +<programlisting> +type ByteArray# +</programlisting> + +<indexterm><primary><literal>ByteArray#</literal></primary></indexterm> +</para> + +<para> +Arrays of these types are useful when a Haskell program wishes to +construct a value to pass to a C procedure. It is also possible to use +them to build (say) arrays of unboxed characters for internal use in a +Haskell program. Given these uses, <literal>ByteArray#</literal> +is deliberately a bit vague about the type of its components. +Operations are provided to extract values of type +<literal>Char#</literal>, <literal>Int#</literal>, +<literal>Float#</literal>, <literal>Double#</literal>, and +<literal>Addr#</literal> from arbitrary offsets within a +<literal>ByteArray#</literal>. (For type +<literal>Foo#</literal>, the $i$th offset gets you the $i$th +<literal>Foo#</literal>, not the <literal>Foo#</literal> at +byte-position $i$. Mumble.) (If you want a +<literal>Word#</literal>, grab an <literal>Int#</literal>, +then coerce it.) +</para> + +<para> +Lastly, we have static byte-arrays, of type +<literal>Addr#</literal> [mentioned previously]. (Remember +the duality between arrays and pointers in C.) Arrays of this types +are represented by a pointer to an array in the world outside Haskell, +so this pointer is not followed by the garbage collector. In other +respects they are just like <literal>ByteArray#</literal>. They +are only needed in order to pass values from C to Haskell. +</para> + +</sect2> + +<sect2> +<title>Reading and writing</title> + +<para> +Primitive arrays are linear, and indexed starting at zero. +</para> + +<para> +The size and indices of a <literal>ByteArray#</literal>, <literal>Addr#</literal>, and +<literal>MutableByteArray#</literal> are all in bytes. It's up to the program to +calculate the correct byte offset from the start of the array. This +allows a <literal>ByteArray#</literal> to contain a mixture of values of different +type, which is often needed when preparing data for and unpicking +results from C. (Umm…not true of indices…WDP 95/09) +</para> + +<para> +<emphasis>Should we provide some <literal>sizeOfDouble#</literal> constants?</emphasis> +</para> + +<para> +Out-of-range errors on indexing should be caught by the code which +uses the primitive operation; the primitive operations themselves do +<emphasis>not</emphasis> check for out-of-range indexes. The intention is that the +primitive ops compile to one machine instruction or thereabouts. +</para> + +<para> +We use the terms “reading” and “writing” to refer to accessing +<emphasis>mutable</emphasis> arrays (see <xref linkend="sect-mutable">), and +“indexing” to refer to reading a value from an <emphasis>immutable</emphasis> +array. +</para> + +<para> +Immutable byte arrays are straightforward to index (all indices are in +units of the size of the object being read): + +<programlisting> +indexCharArray# :: ByteArray# -> Int# -> Char# +indexIntArray# :: ByteArray# -> Int# -> Int# +indexAddrArray# :: ByteArray# -> Int# -> Addr# +indexFloatArray# :: ByteArray# -> Int# -> Float# +indexDoubleArray# :: ByteArray# -> Int# -> Double# + +indexCharOffAddr# :: Addr# -> Int# -> Char# +indexIntOffAddr# :: Addr# -> Int# -> Int# +indexFloatOffAddr# :: Addr# -> Int# -> Float# +indexDoubleOffAddr# :: Addr# -> Int# -> Double# +indexAddrOffAddr# :: Addr# -> Int# -> Addr# + -- Get an Addr# from an Addr# offset +</programlisting> + +<indexterm><primary><literal>indexCharArray#</literal></primary></indexterm> +<indexterm><primary><literal>indexIntArray#</literal></primary></indexterm> +<indexterm><primary><literal>indexAddrArray#</literal></primary></indexterm> +<indexterm><primary><literal>indexFloatArray#</literal></primary></indexterm> +<indexterm><primary><literal>indexDoubleArray#</literal></primary></indexterm> +<indexterm><primary><literal>indexCharOffAddr#</literal></primary></indexterm> +<indexterm><primary><literal>indexIntOffAddr#</literal></primary></indexterm> +<indexterm><primary><literal>indexFloatOffAddr#</literal></primary></indexterm> +<indexterm><primary><literal>indexDoubleOffAddr#</literal></primary></indexterm> +<indexterm><primary><literal>indexAddrOffAddr#</literal></primary></indexterm> +</para> + +<para> +The last of these, <function>indexAddrOffAddr#</function>, extracts an <literal>Addr#</literal> using an offset +from another <literal>Addr#</literal>, thereby providing the ability to follow a chain of +C pointers. +</para> + +<para> +Something a bit more interesting goes on when indexing arrays of boxed +objects, because the result is simply the boxed object. So presumably +it should be entered—we never usually return an unevaluated +object! This is a pain: primitive ops aren't supposed to do +complicated things like enter objects. The current solution is to +return a single element unboxed tuple (see <xref linkend="unboxed-tuples">). +</para> + +<para> + +<programlisting> +indexArray# :: Array# elt -> Int# -> (# elt #) +</programlisting> + +<indexterm><primary><literal>indexArray#</literal></primary></indexterm> +</para> + +</sect2> + +<sect2> +<title>The state type</title> + +<para> +<indexterm><primary><literal>state, primitive type</literal></primary></indexterm> +<indexterm><primary><literal>State#</literal></primary></indexterm> +</para> + +<para> +The primitive type <literal>State#</literal> represents the state of a state +transformer. It is parameterised on the desired type of state, which +serves to keep states from distinct threads distinct from one another. +But the <emphasis>only</emphasis> effect of this parameterisation is in the type +system: all values of type <literal>State#</literal> are represented in the same way. +Indeed, they are all represented by nothing at all! The code +generator “knows” to generate no code, and allocate no registers +etc, for primitive states. +</para> + +<para> + +<programlisting> +type State# s +</programlisting> + +</para> + +<para> +The type <literal>GHC.RealWorld</literal> is truly opaque: there are no values defined +of this type, and no operations over it. It is “primitive” in that +sense - but it is <emphasis>not unlifted!</emphasis> Its only role in life is to be +the type which distinguishes the <literal>IO</literal> state transformer. +</para> + +<para> + +<programlisting> +data RealWorld +</programlisting> + +</para> + +</sect2> + +<sect2> +<title>State of the world</title> + +<para> +A single, primitive, value of type <literal>State# RealWorld</literal> is provided. +</para> + +<para> + +<programlisting> +realWorld# :: State# RealWorld +</programlisting> + +<indexterm><primary>realWorld# state object</primary></indexterm> +</para> + +<para> +(Note: in the compiler, not a <literal>PrimOp</literal>; just a mucho magic +<literal>Id</literal>. Exported from <literal>GHC</literal>, though). +</para> + +</sect2> + +<sect2 id="sect-mutable"> +<title>Mutable arrays</title> + +<para> +<indexterm><primary>mutable arrays</primary></indexterm> +<indexterm><primary>arrays, mutable</primary></indexterm> +Corresponding to <literal>Array#</literal> and <literal>ByteArray#</literal>, we have the types of +mutable versions of each. In each case, the representation is a +pointer to a suitable block of (mutable) heap-allocated storage. +</para> + +<para> + +<programlisting> +type MutableArray# s elt +type MutableByteArray# s +</programlisting> + +<indexterm><primary><literal>MutableArray#</literal></primary></indexterm> +<indexterm><primary><literal>MutableByteArray#</literal></primary></indexterm> +</para> + +<sect3> +<title>Allocation</title> + +<para> +<indexterm><primary>mutable arrays, allocation</primary></indexterm> +<indexterm><primary>arrays, allocation</primary></indexterm> +<indexterm><primary>allocation, of mutable arrays</primary></indexterm> +</para> + +<para> +Mutable arrays can be allocated. Only pointer-arrays are initialised; +arrays of non-pointers are filled in by “user code” rather than by +the array-allocation primitive. Reason: only the pointer case has to +worry about GC striking with a partly-initialised array. +</para> + +<para> + +<programlisting> +newArray# :: Int# -> elt -> State# s -> (# State# s, MutableArray# s elt #) + +newCharArray# :: Int# -> State# s -> (# State# s, MutableByteArray# s elt #) +newIntArray# :: Int# -> State# s -> (# State# s, MutableByteArray# s elt #) +newAddrArray# :: Int# -> State# s -> (# State# s, MutableByteArray# s elt #) +newFloatArray# :: Int# -> State# s -> (# State# s, MutableByteArray# s elt #) +newDoubleArray# :: Int# -> State# s -> (# State# s, MutableByteArray# s elt #) +</programlisting> + +<indexterm><primary><literal>newArray#</literal></primary></indexterm> +<indexterm><primary><literal>newCharArray#</literal></primary></indexterm> +<indexterm><primary><literal>newIntArray#</literal></primary></indexterm> +<indexterm><primary><literal>newAddrArray#</literal></primary></indexterm> +<indexterm><primary><literal>newFloatArray#</literal></primary></indexterm> +<indexterm><primary><literal>newDoubleArray#</literal></primary></indexterm> +</para> + +<para> +The size of a <literal>ByteArray#</literal> is given in bytes. +</para> + +</sect3> + +<sect3> +<title>Reading and writing</title> + +<para> +<indexterm><primary>arrays, reading and writing</primary></indexterm> +</para> + +<para> + +<programlisting> +readArray# :: MutableArray# s elt -> Int# -> State# s -> (# State# s, elt #) +readCharArray# :: MutableByteArray# s -> Int# -> State# s -> (# State# s, Char# #) +readIntArray# :: MutableByteArray# s -> Int# -> State# s -> (# State# s, Int# #) +readAddrArray# :: MutableByteArray# s -> Int# -> State# s -> (# State# s, Addr# #) +readFloatArray# :: MutableByteArray# s -> Int# -> State# s -> (# State# s, Float# #) +readDoubleArray# :: MutableByteArray# s -> Int# -> State# s -> (# State# s, Double# #) + +writeArray# :: MutableArray# s elt -> Int# -> elt -> State# s -> State# s +writeCharArray# :: MutableByteArray# s -> Int# -> Char# -> State# s -> State# s +writeIntArray# :: MutableByteArray# s -> Int# -> Int# -> State# s -> State# s +writeAddrArray# :: MutableByteArray# s -> Int# -> Addr# -> State# s -> State# s +writeFloatArray# :: MutableByteArray# s -> Int# -> Float# -> State# s -> State# s +writeDoubleArray# :: MutableByteArray# s -> Int# -> Double# -> State# s -> State# s +</programlisting> + +<indexterm><primary><literal>readArray#</literal></primary></indexterm> +<indexterm><primary><literal>readCharArray#</literal></primary></indexterm> +<indexterm><primary><literal>readIntArray#</literal></primary></indexterm> +<indexterm><primary><literal>readAddrArray#</literal></primary></indexterm> +<indexterm><primary><literal>readFloatArray#</literal></primary></indexterm> +<indexterm><primary><literal>readDoubleArray#</literal></primary></indexterm> +<indexterm><primary><literal>writeArray#</literal></primary></indexterm> +<indexterm><primary><literal>writeCharArray#</literal></primary></indexterm> +<indexterm><primary><literal>writeIntArray#</literal></primary></indexterm> +<indexterm><primary><literal>writeAddrArray#</literal></primary></indexterm> +<indexterm><primary><literal>writeFloatArray#</literal></primary></indexterm> +<indexterm><primary><literal>writeDoubleArray#</literal></primary></indexterm> +</para> + +</sect3> + +<sect3> +<title>Equality</title> + +<para> +<indexterm><primary>arrays, testing for equality</primary></indexterm> +</para> + +<para> +One can take “equality” of mutable arrays. What is compared is the +<emphasis>name</emphasis> or reference to the mutable array, not its contents. +</para> + +<para> + +<programlisting> +sameMutableArray# :: MutableArray# s elt -> MutableArray# s elt -> Bool +sameMutableByteArray# :: MutableByteArray# s -> MutableByteArray# s -> Bool +</programlisting> + +<indexterm><primary><literal>sameMutableArray#</literal></primary></indexterm> +<indexterm><primary><literal>sameMutableByteArray#</literal></primary></indexterm> +</para> + +</sect3> + +<sect3> +<title>Freezing mutable arrays</title> + +<para> +<indexterm><primary>arrays, freezing mutable</primary></indexterm> +<indexterm><primary>freezing mutable arrays</primary></indexterm> +<indexterm><primary>mutable arrays, freezing</primary></indexterm> +</para> + +<para> +Only unsafe-freeze has a primitive. (Safe freeze is done directly in Haskell +by copying the array and then using <function>unsafeFreeze</function>.) +</para> + +<para> + +<programlisting> +unsafeFreezeArray# :: MutableArray# s elt -> State# s -> (# State# s, Array# s elt #) +unsafeFreezeByteArray# :: MutableByteArray# s -> State# s -> (# State# s, ByteArray# #) +</programlisting> + +<indexterm><primary><literal>unsafeFreezeArray#</literal></primary></indexterm> +<indexterm><primary><literal>unsafeFreezeByteArray#</literal></primary></indexterm> +</para> + +</sect3> + +</sect2> + +<sect2> +<title>Synchronizing variables (M-vars)</title> + +<para> +<indexterm><primary>synchronising variables (M-vars)</primary></indexterm> +<indexterm><primary>M-Vars</primary></indexterm> +</para> + +<para> +Synchronising variables are the primitive type used to implement +Concurrent Haskell's MVars (see the Concurrent Haskell paper for +the operational behaviour of these operations). +</para> + +<para> + +<programlisting> +type MVar# s elt -- primitive + +newMVar# :: State# s -> (# State# s, MVar# s elt #) +takeMVar# :: SynchVar# s elt -> State# s -> (# State# s, elt #) +putMVar# :: SynchVar# s elt -> State# s -> State# s +</programlisting> + +<indexterm><primary><literal>SynchVar#</literal></primary></indexterm> +<indexterm><primary><literal>newSynchVar#</literal></primary></indexterm> +<indexterm><primary><literal>takeMVar</literal></primary></indexterm> +<indexterm><primary><literal>putMVar</literal></primary></indexterm> +</para> + +</sect2> + +<sect2 id="glasgow-prim-arrays"> +<title>Primitive arrays, mutable and otherwise +</title> + +<para> +<indexterm><primary>primitive arrays (Glasgow extension)</primary></indexterm> +<indexterm><primary>arrays, primitive (Glasgow extension)</primary></indexterm> +</para> + +<para> +GHC knows about quite a few flavours of Large Swathes of Bytes. +</para> + +<para> +First, GHC distinguishes between primitive arrays of (boxed) Haskell +objects (type <literal>Array# obj</literal>) and primitive arrays of bytes (type +<literal>ByteArray#</literal>). +</para> + +<para> +Second, it distinguishes between… +<variablelist> + +<varlistentry> +<term>Immutable:</term> +<listitem> +<para> +Arrays that do not change (as with “standard” Haskell arrays); you +can only read from them. Obviously, they do not need the care and +attention of the state-transformer monad. +</para> +</listitem> +</varlistentry> +<varlistentry> +<term>Mutable:</term> +<listitem> +<para> +Arrays that may be changed or “mutated.” All the operations on them +live within the state-transformer monad and the updates happen +<emphasis>in-place</emphasis>. +</para> +</listitem> +</varlistentry> +<varlistentry> +<term>“Static” (in C land):</term> +<listitem> +<para> +A C routine may pass an <literal>Addr#</literal> pointer back into Haskell land. There +are then primitive operations with which you may merrily grab values +over in C land, by indexing off the “static” pointer. +</para> +</listitem> +</varlistentry> +<varlistentry> +<term>“Stable” pointers:</term> +<listitem> +<para> +If, for some reason, you wish to hand a Haskell pointer (i.e., +<emphasis>not</emphasis> an unboxed value) to a C routine, you first make the +pointer “stable,” so that the garbage collector won't forget that it +exists. That is, GHC provides a safe way to pass Haskell pointers to +C. +</para> + +<para> +Please see the module <literal>Foreign.StablePtr</literal> in the +library documentation for more details. +</para> +</listitem> +</varlistentry> +<varlistentry> +<term>“Foreign objects”:</term> +<listitem> +<para> +A “foreign object” is a safe way to pass an external object (a +C-allocated pointer, say) to Haskell and have Haskell do the Right +Thing when it no longer references the object. So, for example, C +could pass a large bitmap over to Haskell and say “please free this +memory when you're done with it.” +</para> + +<para> +Please see module <literal>Foreign.ForeignPtr</literal> in the library +documentatation for more details. +</para> +</listitem> +</varlistentry> +</variablelist> +</para> + +<para> +The libraries documentatation gives more details on all these +“primitive array” types and the operations on them. +</para> + +</sect2> + +</sect1> + +<!-- Emacs stuff: + ;;; Local Variables: *** + ;;; mode: xml *** + ;;; sgml-parent-document: ("users_guide.xml" "book" "chapter" "sect1") *** + ;;; End: *** + --> diff --git a/docs/users_guide/profiling.xml b/docs/users_guide/profiling.xml new file mode 100644 index 0000000000..a88c8bbf4c --- /dev/null +++ b/docs/users_guide/profiling.xml @@ -0,0 +1,1440 @@ +<?xml version="1.0" encoding="iso-8859-1"?> +<chapter id="profiling"> + <title>Profiling</title> + <indexterm><primary>profiling</primary> + </indexterm> + <indexterm><primary>cost-centre profiling</primary></indexterm> + + <para> Glasgow Haskell comes with a time and space profiling + system. Its purpose is to help you improve your understanding of + your program's execution behaviour, so you can improve it.</para> + + <para> Any comments, suggestions and/or improvements you have are + welcome. Recommended “profiling tricks” would be + especially cool! </para> + + <para>Profiling a program is a three-step process:</para> + + <orderedlist> + <listitem> + <para> Re-compile your program for profiling with the + <literal>-prof</literal> option, and probably one of the + <literal>-auto</literal> or <literal>-auto-all</literal> + options. These options are described in more detail in <xref + linkend="prof-compiler-options"/> </para> + <indexterm><primary><literal>-prof</literal></primary> + </indexterm> + <indexterm><primary><literal>-auto</literal></primary> + </indexterm> + <indexterm><primary><literal>-auto-all</literal></primary> + </indexterm> + </listitem> + + <listitem> + <para> Run your program with one of the profiling options, eg. + <literal>+RTS -p -RTS</literal>. This generates a file of + profiling information.</para> + <indexterm><primary><option>-p</option></primary><secondary>RTS + option</secondary></indexterm> + </listitem> + + <listitem> + <para> Examine the generated profiling information, using one of + GHC's profiling tools. The tool to use will depend on the kind + of profiling information generated.</para> + </listitem> + + </orderedlist> + + <sect1 id="cost-centres"> + <title>Cost centres and cost-centre stacks</title> + + <para>GHC's profiling system assigns <firstterm>costs</firstterm> + to <firstterm>cost centres</firstterm>. A cost is simply the time + or space required to evaluate an expression. Cost centres are + program annotations around expressions; all costs incurred by the + annotated expression are assigned to the enclosing cost centre. + Furthermore, GHC will remember the stack of enclosing cost centres + for any given expression at run-time and generate a call-graph of + cost attributions.</para> + + <para>Let's take a look at an example:</para> + + <programlisting> +main = print (nfib 25) +nfib n = if n < 2 then 1 else nfib (n-1) + nfib (n-2) +</programlisting> + + <para>Compile and run this program as follows:</para> + + <screen> +$ ghc -prof -auto-all -o Main Main.hs +$ ./Main +RTS -p +121393 +$ +</screen> + + <para>When a GHC-compiled program is run with the + <option>-p</option> RTS option, it generates a file called + <filename><prog>.prof</filename>. In this case, the file + will contain something like this:</para> + +<screen> + Fri May 12 14:06 2000 Time and Allocation Profiling Report (Final) + + Main +RTS -p -RTS + + total time = 0.14 secs (7 ticks @ 20 ms) + total alloc = 8,741,204 bytes (excludes profiling overheads) + +COST CENTRE MODULE %time %alloc + +nfib Main 100.0 100.0 + + + individual inherited +COST CENTRE MODULE entries %time %alloc %time %alloc + +MAIN MAIN 0 0.0 0.0 100.0 100.0 + main Main 0 0.0 0.0 0.0 0.0 + CAF PrelHandle 3 0.0 0.0 0.0 0.0 + CAF PrelAddr 1 0.0 0.0 0.0 0.0 + CAF Main 6 0.0 0.0 100.0 100.0 + main Main 1 0.0 0.0 100.0 100.0 + nfib Main 242785 100.0 100.0 100.0 100.0 +</screen> + + + <para>The first part of the file gives the program name and + options, and the total time and total memory allocation measured + during the run of the program (note that the total memory + allocation figure isn't the same as the amount of + <emphasis>live</emphasis> memory needed by the program at any one + time; the latter can be determined using heap profiling, which we + will describe shortly).</para> + + <para>The second part of the file is a break-down by cost centre + of the most costly functions in the program. In this case, there + was only one significant function in the program, namely + <function>nfib</function>, and it was responsible for 100% + of both the time and allocation costs of the program.</para> + + <para>The third and final section of the file gives a profile + break-down by cost-centre stack. This is roughly a call-graph + profile of the program. In the example above, it is clear that + the costly call to <function>nfib</function> came from + <function>main</function>.</para> + + <para>The time and allocation incurred by a given part of the + program is displayed in two ways: “individual”, which + are the costs incurred by the code covered by this cost centre + stack alone, and “inherited”, which includes the costs + incurred by all the children of this node.</para> + + <para>The usefulness of cost-centre stacks is better demonstrated + by modifying the example slightly:</para> + + <programlisting> +main = print (f 25 + g 25) +f n = nfib n +g n = nfib (n `div` 2) +nfib n = if n < 2 then 1 else nfib (n-1) + nfib (n-2) +</programlisting> + + <para>Compile and run this program as before, and take a look at + the new profiling results:</para> + +<screen> +COST CENTRE MODULE scc %time %alloc %time %alloc + +MAIN MAIN 0 0.0 0.0 100.0 100.0 + main Main 0 0.0 0.0 0.0 0.0 + CAF PrelHandle 3 0.0 0.0 0.0 0.0 + CAF PrelAddr 1 0.0 0.0 0.0 0.0 + CAF Main 9 0.0 0.0 100.0 100.0 + main Main 1 0.0 0.0 100.0 100.0 + g Main 1 0.0 0.0 0.0 0.2 + nfib Main 465 0.0 0.2 0.0 0.2 + f Main 1 0.0 0.0 100.0 99.8 + nfib Main 242785 100.0 99.8 100.0 99.8 +</screen> + + <para>Now although we had two calls to <function>nfib</function> + in the program, it is immediately clear that it was the call from + <function>f</function> which took all the time.</para> + + <para>The actual meaning of the various columns in the output is:</para> + + <variablelist> + <varlistentry> + <term>entries</term> + <listitem> + <para>The number of times this particular point in the call + graph was entered.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term>individual %time</term> + <listitem> + <para>The percentage of the total run time of the program + spent at this point in the call graph.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term>individual %alloc</term> + <listitem> + <para>The percentage of the total memory allocations + (excluding profiling overheads) of the program made by this + call.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term>inherited %time</term> + <listitem> + <para>The percentage of the total run time of the program + spent below this point in the call graph.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term>inherited %alloc</term> + <listitem> + <para>The percentage of the total memory allocations + (excluding profiling overheads) of the program made by this + call and all of its sub-calls.</para> + </listitem> + </varlistentry> + </variablelist> + + <para>In addition you can use the <option>-P</option> RTS option + <indexterm><primary><option>-P</option></primary></indexterm> to + get the following additional information:</para> + + <variablelist> + <varlistentry> + <term><literal>ticks</literal></term> + <listitem> + <para>The raw number of time “ticks” which were + attributed to this cost-centre; from this, we get the + <literal>%time</literal> figure mentioned + above.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>bytes</literal></term> + <listitem> + <para>Number of bytes allocated in the heap while in this + cost-centre; again, this is the raw number from which we get + the <literal>%alloc</literal> figure mentioned + above.</para> + </listitem> + </varlistentry> + </variablelist> + + <para>What about recursive functions, and mutually recursive + groups of functions? Where are the costs attributed? Well, + although GHC does keep information about which groups of functions + called each other recursively, this information isn't displayed in + the basic time and allocation profile, instead the call-graph is + flattened into a tree. The XML profiling tool (described in <xref + linkend="prof-xml-tool"/>) will be able to display real loops in + the call-graph.</para> + + <sect2><title>Inserting cost centres by hand</title> + + <para>Cost centres are just program annotations. When you say + <option>-auto-all</option> to the compiler, it automatically + inserts a cost centre annotation around every top-level function + in your program, but you are entirely free to add the cost + centre annotations yourself.</para> + + <para>The syntax of a cost centre annotation is</para> + + <programlisting> + {-# SCC "name" #-} <expression> +</programlisting> + + <para>where <literal>"name"</literal> is an arbitrary string, + that will become the name of your cost centre as it appears + in the profiling output, and + <literal><expression></literal> is any Haskell + expression. An <literal>SCC</literal> annotation extends as + far to the right as possible when parsing.</para> + + </sect2> + + <sect2 id="prof-rules"> + <title>Rules for attributing costs</title> + + <para>The cost of evaluating any expression in your program is + attributed to a cost-centre stack using the following rules:</para> + + <itemizedlist> + <listitem> + <para>If the expression is part of the + <firstterm>one-off</firstterm> costs of evaluating the + enclosing top-level definition, then costs are attributed to + the stack of lexically enclosing <literal>SCC</literal> + annotations on top of the special <literal>CAF</literal> + cost-centre. </para> + </listitem> + + <listitem> + <para>Otherwise, costs are attributed to the stack of + lexically-enclosing <literal>SCC</literal> annotations, + appended to the cost-centre stack in effect at the + <firstterm>call site</firstterm> of the current top-level + definition<footnote> <para>The call-site is just the place + in the source code which mentions the particular function or + variable.</para></footnote>. Notice that this is a recursive + definition.</para> + </listitem> + + <listitem> + <para>Time spent in foreign code (see <xref linkend="ffi"/>) + is always attributed to the cost centre in force at the + Haskell call-site of the foreign function.</para> + </listitem> + </itemizedlist> + + <para>What do we mean by one-off costs? Well, Haskell is a lazy + language, and certain expressions are only ever evaluated once. + For example, if we write:</para> + + <programlisting> +x = nfib 25 +</programlisting> + + <para>then <varname>x</varname> will only be evaluated once (if + at all), and subsequent demands for <varname>x</varname> will + immediately get to see the cached result. The definition + <varname>x</varname> is called a CAF (Constant Applicative + Form), because it has no arguments.</para> + + <para>For the purposes of profiling, we say that the expression + <literal>nfib 25</literal> belongs to the one-off costs of + evaluating <varname>x</varname>.</para> + + <para>Since one-off costs aren't strictly speaking part of the + call-graph of the program, they are attributed to a special + top-level cost centre, <literal>CAF</literal>. There may be one + <literal>CAF</literal> cost centre for each module (the + default), or one for each top-level definition with any one-off + costs (this behaviour can be selected by giving GHC the + <option>-caf-all</option> flag).</para> + + <indexterm><primary><literal>-caf-all</literal></primary> + </indexterm> + + <para>If you think you have a weird profile, or the call-graph + doesn't look like you expect it to, feel free to send it (and + your program) to us at + <email>glasgow-haskell-bugs@haskell.org</email>.</para> + </sect2> + </sect1> + + <sect1 id="prof-compiler-options"> + <title>Compiler options for profiling</title> + + <indexterm><primary>profiling</primary><secondary>options</secondary></indexterm> + <indexterm><primary>options</primary><secondary>for profiling</secondary></indexterm> + + <variablelist> + <varlistentry> + <term> + <option>-prof</option>: + <indexterm><primary><option>-prof</option></primary></indexterm> + </term> + <listitem> + <para> To make use of the profiling system + <emphasis>all</emphasis> modules must be compiled and linked + with the <option>-prof</option> option. Any + <literal>SCC</literal> annotations you've put in your source + will spring to life.</para> + + <para> Without a <option>-prof</option> option, your + <literal>SCC</literal>s are ignored; so you can compile + <literal>SCC</literal>-laden code without changing + it.</para> + </listitem> + </varlistentry> + </variablelist> + + <para>There are a few other profiling-related compilation options. + Use them <emphasis>in addition to</emphasis> + <option>-prof</option>. These do not have to be used consistently + for all modules in a program.</para> + + <variablelist> + <varlistentry> + <term> + <option>-auto</option>: + <indexterm><primary><option>-auto</option></primary></indexterm> + <indexterm><primary>cost centres</primary><secondary>automatically inserting</secondary></indexterm> + </term> + <listitem> + <para> GHC will automatically add + <function>_scc_</function> constructs for all + top-level, exported functions.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <option>-auto-all</option>: + <indexterm><primary><option>-auto-all</option></primary></indexterm> + </term> + <listitem> + <para> <emphasis>All</emphasis> top-level functions, + exported or not, will be automatically + <function>_scc_</function>'d.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <option>-caf-all</option>: + <indexterm><primary><option>-caf-all</option></primary></indexterm> + </term> + <listitem> + <para> 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…</para> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <option>-ignore-scc</option>: + <indexterm><primary><option>-ignore-scc</option></primary></indexterm> + </term> + <listitem> + <para>Ignore any <function>_scc_</function> + constructs, so a module which already has + <function>_scc_</function>s can be compiled + for profiling with the annotations ignored.</para> + </listitem> + </varlistentry> + + </variablelist> + + </sect1> + + <sect1 id="prof-time-options"> + <title>Time and allocation profiling</title> + + <para>To generate a time and allocation profile, give one of the + following RTS options to the compiled program when you run it (RTS + options should be enclosed between <literal>+RTS...-RTS</literal> + as usual):</para> + + <variablelist> + <varlistentry> + <term> + <option>-p</option> or <option>-P</option>: + <indexterm><primary><option>-p</option></primary></indexterm> + <indexterm><primary><option>-P</option></primary></indexterm> + <indexterm><primary>time profile</primary></indexterm> + </term> + <listitem> + <para>The <option>-p</option> option produces a standard + <emphasis>time profile</emphasis> report. It is written + into the file + <filename><replaceable>program</replaceable>.prof</filename>.</para> + + <para>The <option>-P</option> option produces a more + detailed report containing the actual time and allocation + data as well. (Not used much.)</para> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <option>-px</option>: + <indexterm><primary><option>-px</option></primary></indexterm> + </term> + <listitem> + <para>The <option>-px</option> option generates profiling + information in the XML format understood by our new + profiling tool, see <xref linkend="prof-xml-tool"/>.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <option>-xc</option> + <indexterm><primary><option>-xc</option></primary><secondary>RTS option</secondary></indexterm> + </term> + <listitem> + <para>This option makes use of the extra information + maintained by the cost-centre-stack profiler to provide + useful information about the location of runtime errors. + See <xref linkend="rts-options-debugging"/>.</para> + </listitem> + </varlistentry> + + </variablelist> + + </sect1> + + <sect1 id="prof-heap"> + <title>Profiling memory usage</title> + + <para>In addition to profiling the time and allocation behaviour + of your program, you can also generate a graph of its memory usage + over time. This is useful for detecting the causes of + <firstterm>space leaks</firstterm>, when your program holds on to + more memory at run-time that it needs to. Space leaks lead to + longer run-times due to heavy garbage collector activity, and may + even cause the program to run out of memory altogether.</para> + + <para>To generate a heap profile from your program:</para> + + <orderedlist> + <listitem> + <para>Compile the program for profiling (<xref + linkend="prof-compiler-options"/>).</para> + </listitem> + <listitem> + <para>Run it with one of the heap profiling options described + below (eg. <option>-hc</option> for a basic producer profile). + This generates the file + <filename><replaceable>prog</replaceable>.hp</filename>.</para> + </listitem> + <listitem> + <para>Run <command>hp2ps</command> to produce a Postscript + file, + <filename><replaceable>prog</replaceable>.ps</filename>. The + <command>hp2ps</command> utility is described in detail in + <xref linkend="hp2ps"/>.</para> + </listitem> + <listitem> + <para>Display the heap profile using a postscript viewer such + as <application>Ghostview</application>, or print it out on a + Postscript-capable printer.</para> + </listitem> + </orderedlist> + + <sect2 id="rts-options-heap-prof"> + <title>RTS options for heap profiling</title> + + <para>There are several different kinds of heap profile that can + be generated. All the different profile types yield a graph of + live heap against time, but they differ in how the live heap is + broken down into bands. The following RTS options select which + break-down to use:</para> + + <variablelist> + <varlistentry> + <term> + <option>-hc</option> + <indexterm><primary><option>-hc</option></primary><secondary>RTS option</secondary></indexterm> + </term> + <listitem> + <para>Breaks down the graph by the cost-centre stack which + produced the data.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <option>-hm</option> + <indexterm><primary><option>-hm</option></primary><secondary>RTS option</secondary></indexterm> + </term> + <listitem> + <para>Break down the live heap by the module containing + the code which produced the data.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <option>-hd</option> + <indexterm><primary><option>-hd</option></primary><secondary>RTS option</secondary></indexterm> + </term> + <listitem> + <para>Breaks down the graph by <firstterm>closure + description</firstterm>. For actual data, the description + is just the constructor name, for other closures it is a + compiler-generated string identifying the closure.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <option>-hy</option> + <indexterm><primary><option>-hy</option></primary><secondary>RTS option</secondary></indexterm> + </term> + <listitem> + <para>Breaks down the graph by + <firstterm>type</firstterm>. For closures which have + function type or unknown/polymorphic type, the string will + represent an approximation to the actual type.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <option>-hr</option> + <indexterm><primary><option>-hr</option></primary><secondary>RTS option</secondary></indexterm> + </term> + <listitem> + <para>Break down the graph by <firstterm>retainer + set</firstterm>. Retainer profiling is described in more + detail below (<xref linkend="retainer-prof"/>).</para> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <option>-hb</option> + <indexterm><primary><option>-hb</option></primary><secondary>RTS option</secondary></indexterm> + </term> + <listitem> + <para>Break down the graph by + <firstterm>biography</firstterm>. Biographical profiling + is described in more detail below (<xref + linkend="biography-prof"/>).</para> + </listitem> + </varlistentry> + </variablelist> + + <para>In addition, the profile can be restricted to heap data + which satisfies certain criteria - for example, you might want + to display a profile by type but only for data produced by a + certain module, or a profile by retainer for a certain type of + data. Restrictions are specified as follows:</para> + + <variablelist> + <varlistentry> + <term> + <option>-hc</option><replaceable>name</replaceable>,... + <indexterm><primary><option>-hc</option></primary><secondary>RTS option</secondary></indexterm> + </term> + <listitem> + <para>Restrict the profile to closures produced by + cost-centre stacks with one of the specified cost centres + at the top.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <option>-hC</option><replaceable>name</replaceable>,... + <indexterm><primary><option>-hC</option></primary><secondary>RTS option</secondary></indexterm> + </term> + <listitem> + <para>Restrict the profile to closures produced by + cost-centre stacks with one of the specified cost centres + anywhere in the stack.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <option>-hm</option><replaceable>module</replaceable>,... + <indexterm><primary><option>-hm</option></primary><secondary>RTS option</secondary></indexterm> + </term> + <listitem> + <para>Restrict the profile to closures produced by the + specified modules.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <option>-hd</option><replaceable>desc</replaceable>,... + <indexterm><primary><option>-hd</option></primary><secondary>RTS option</secondary></indexterm> + </term> + <listitem> + <para>Restrict the profile to closures with the specified + description strings.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <option>-hy</option><replaceable>type</replaceable>,... + <indexterm><primary><option>-hy</option></primary><secondary>RTS option</secondary></indexterm> + </term> + <listitem> + <para>Restrict the profile to closures with the specified + types.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <option>-hr</option><replaceable>cc</replaceable>,... + <indexterm><primary><option>-hr</option></primary><secondary>RTS option</secondary></indexterm> + </term> + <listitem> + <para>Restrict the profile to closures with retainer sets + containing cost-centre stacks with one of the specified + cost centres at the top.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <option>-hb</option><replaceable>bio</replaceable>,... + <indexterm><primary><option>-hb</option></primary><secondary>RTS option</secondary></indexterm> + </term> + <listitem> + <para>Restrict the profile to closures with one of the + specified biographies, where + <replaceable>bio</replaceable> is one of + <literal>lag</literal>, <literal>drag</literal>, + <literal>void</literal>, or <literal>use</literal>.</para> + </listitem> + </varlistentry> + </variablelist> + + <para>For example, the following options will generate a + retainer profile restricted to <literal>Branch</literal> and + <literal>Leaf</literal> constructors:</para> + +<screen> +<replaceable>prog</replaceable> +RTS -hr -hdBranch,Leaf +</screen> + + <para>There can only be one "break-down" option + (eg. <option>-hr</option> in the example above), but there is no + limit on the number of further restrictions that may be applied. + All the options may be combined, with one exception: GHC doesn't + currently support mixing the <option>-hr</option> and + <option>-hb</option> options.</para> + + <para>There are two more options which relate to heap + profiling:</para> + + <variablelist> + <varlistentry> + <term> + <option>-i<replaceable>secs</replaceable></option>: + <indexterm><primary><option>-i</option></primary></indexterm> + </term> + <listitem> + <para>Set the profiling (sampling) interval to + <replaceable>secs</replaceable> seconds (the default is + 0.1 second). Fractions are allowed: for example + <option>-i0.2</option> will get 5 samples per second. + This only affects heap profiling; time profiles are always + sampled on a 1/50 second frequency.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <option>-xt</option> + <indexterm><primary><option>-xt</option></primary><secondary>RTS option</secondary></indexterm> + </term> + <listitem> + <para>Include the memory occupied by threads in a heap + profile. Each thread takes up a small area for its thread + state in addition to the space allocated for its stack + (stacks normally start small and then grow as + necessary).</para> + + <para>This includes the main thread, so using + <option>-xt</option> is a good way to see how much stack + space the program is using.</para> + + <para>Memory occupied by threads and their stacks is + labelled as “TSO” when displaying the profile + by closure description or type description.</para> + </listitem> + </varlistentry> + </variablelist> + + </sect2> + + <sect2 id="retainer-prof"> + <title>Retainer Profiling</title> + + <para>Retainer profiling is designed to help answer questions + like <quote>why is this data being retained?</quote>. We start + by defining what we mean by a retainer:</para> + + <blockquote> + <para>A retainer is either the system stack, or an unevaluated + closure (thunk).</para> + </blockquote> + + <para>In particular, constructors are <emphasis>not</emphasis> + retainers.</para> + + <para>An object B retains object A if (i) B is a retainer object and + (ii) object A can be reached by recursively following pointers + starting from object B, but not meeting any other retainer + objects on the way. Each live object is retained by one or more + retainer objects, collectively called its retainer set, or its + <firstterm>retainer set</firstterm>, or its + <firstterm>retainers</firstterm>.</para> + + <para>When retainer profiling is requested by giving the program + the <option>-hr</option> option, a graph is generated which is + broken down by retainer set. A retainer set is displayed as a + set of cost-centre stacks; because this is usually too large to + fit on the profile graph, each retainer set is numbered and + shown abbreviated on the graph along with its number, and the + full list of retainer sets is dumped into the file + <filename><replaceable>prog</replaceable>.prof</filename>.</para> + + <para>Retainer profiling requires multiple passes over the live + heap in order to discover the full retainer set for each + object, which can be quite slow. So we set a limit on the + maximum size of a retainer set, where all retainer sets larger + than the maximum retainer set size are replaced by the special + set <literal>MANY</literal>. The maximum set size defaults to 8 + and can be altered with the <option>-R</option> RTS + option:</para> + + <variablelist> + <varlistentry> + <term><option>-R</option><replaceable>size</replaceable></term> + <listitem> + <para>Restrict the number of elements in a retainer set to + <replaceable>size</replaceable> (default 8).</para> + </listitem> + </varlistentry> + </variablelist> + + <sect3> + <title>Hints for using retainer profiling</title> + + <para>The definition of retainers is designed to reflect a + common cause of space leaks: a large structure is retained by + an unevaluated computation, and will be released once the + computation is forced. A good example is looking up a value in + a finite map, where unless the lookup is forced in a timely + manner the unevaluated lookup will cause the whole mapping to + be retained. These kind of space leaks can often be + eliminated by forcing the relevant computations to be + performed eagerly, using <literal>seq</literal> or strictness + annotations on data constructor fields.</para> + + <para>Often a particular data structure is being retained by a + chain of unevaluated closures, only the nearest of which will + be reported by retainer profiling - for example A retains B, B + retains C, and C retains a large structure. There might be a + large number of Bs but only a single A, so A is really the one + we're interested in eliminating. However, retainer profiling + will in this case report B as the retainer of the large + structure. To move further up the chain of retainers, we can + ask for another retainer profile but this time restrict the + profile to B objects, so we get a profile of the retainers of + B:</para> + +<screen> +<replaceable>prog</replaceable> +RTS -hr -hcB +</screen> + + <para>This trick isn't foolproof, because there might be other + B closures in the heap which aren't the retainers we are + interested in, but we've found this to be a useful technique + in most cases.</para> + </sect3> + </sect2> + + <sect2 id="biography-prof"> + <title>Biographical Profiling</title> + + <para>A typical heap object may be in one of the following four + states at each point in its lifetime:</para> + + <itemizedlist> + <listitem> + <para>The <firstterm>lag</firstterm> stage, which is the + time between creation and the first use of the + object,</para> + </listitem> + <listitem> + <para>the <firstterm>use</firstterm> stage, which lasts from + the first use until the last use of the object, and</para> + </listitem> + <listitem> + <para>The <firstterm>drag</firstterm> stage, which lasts + from the final use until the last reference to the object + is dropped.</para> + </listitem> + <listitem> + <para>An object which is never used is said to be in the + <firstterm>void</firstterm> state for its whole + lifetime.</para> + </listitem> + </itemizedlist> + + <para>A biographical heap profile displays the portion of the + live heap in each of the four states listed above. Usually the + most interesting states are the void and drag states: live heap + in these states is more likely to be wasted space than heap in + the lag or use states.</para> + + <para>It is also possible to break down the heap in one or more + of these states by a different criteria, by restricting a + profile by biography. For example, to show the portion of the + heap in the drag or void state by producer: </para> + +<screen> +<replaceable>prog</replaceable> +RTS -hc -hbdrag,void +</screen> + + <para>Once you know the producer or the type of the heap in the + drag or void states, the next step is usually to find the + retainer(s):</para> + +<screen> +<replaceable>prog</replaceable> +RTS -hr -hc<replaceable>cc</replaceable>... +</screen> + + <para>NOTE: this two stage process is required because GHC + cannot currently profile using both biographical and retainer + information simultaneously.</para> + </sect2> + + <sect2 id="mem-residency"> + <title>Actual memory residency</title> + + <para>How does the heap residency reported by the heap profiler relate to + the actual memory residency of your program when you run it? You might + see a large discrepancy between the residency reported by the heap + profiler, and the residency reported by tools on your system + (eg. <literal>ps</literal> or <literal>top</literal> on Unix, or the + Task Manager on Windows). There are several reasons for this:</para> + + <itemizedlist> + <listitem> + <para>There is an overhead of profiling itself, which is subtracted + from the residency figures by the profiler. This overhead goes + away when compiling without profiling support, of course. The + space overhead is currently 2 extra + words per heap object, which probably results in + about a 30% overhead.</para> + </listitem> + + <listitem> + <para>Garbage collection requires more memory than the actual + residency. The factor depends on the kind of garbage collection + algorithm in use: a major GC in the standard + generation copying collector will usually require 3L bytes of + memory, where L is the amount of live data. This is because by + default (see the <option>+RTS -F</option> option) we allow the old + generation to grow to twice its size (2L) before collecting it, and + we require additionally L bytes to copy the live data into. When + using compacting collection (see the <option>+RTS -c</option> + option), this is reduced to 2L, and can further be reduced by + tweaking the <option>-F</option> option. Also add the size of the + allocation area (currently a fixed 512Kb).</para> + </listitem> + + <listitem> + <para>The stack isn't counted in the heap profile by default. See the + <option>+RTS -xt</option> option.</para> + </listitem> + + <listitem> + <para>The program text itself, the C stack, any non-heap data (eg. data + allocated by foreign libraries, and data allocated by the RTS), and + <literal>mmap()</literal>'d memory are not counted in the heap profile.</para> + </listitem> + </itemizedlist> + </sect2> + + </sect1> + + <sect1 id="prof-xml-tool"> + <title>Graphical time/allocation profile</title> + + <para>You can view the time and allocation profiling graph of your + program graphically, using <command>ghcprof</command>. This is a + new tool with GHC 4.08, and will eventually be the de-facto + standard way of viewing GHC profiles<footnote><para>Actually this + isn't true any more, we are working on a new tool for + displaying heap profiles using Gtk+HS, so + <command>ghcprof</command> may go away at some point in the future.</para> + </footnote></para> + + <para>To run <command>ghcprof</command>, you need + <productname>uDraw(Graph)</productname> installed, which can be + obtained from <ulink + url="http://www.informatik.uni-bremen.de/uDrawGraph/en/uDrawGraph/uDrawGraph.html"><citetitle>uDraw(Graph)</citetitle></ulink>. Install one of + the binary + distributions, and set your + <envar>UDG_HOME</envar> environment variable to point to the + installation directory.</para> + + <para><command>ghcprof</command> uses an XML-based profiling log + format, and you therefore need to run your program with a + different option: <option>-px</option>. The file generated is + still called <filename><prog>.prof</filename>. To see the + profile, run <command>ghcprof</command> like this:</para> + + <indexterm><primary><option>-px</option></primary></indexterm> + +<screen> +$ ghcprof <prog>.prof +</screen> + + <para>which should pop up a window showing the call-graph of your + program in glorious detail. More information on using + <command>ghcprof</command> can be found at <ulink + url="http://www.dcs.warwick.ac.uk/people/academic/Stephen.Jarvis/profiler/index.html"><citetitle>The + Cost-Centre Stack Profiling Tool for + GHC</citetitle></ulink>.</para> + + </sect1> + + <sect1 id="hp2ps"> + <title><command>hp2ps</command>––heap profile to PostScript</title> + + <indexterm><primary><command>hp2ps</command></primary></indexterm> + <indexterm><primary>heap profiles</primary></indexterm> + <indexterm><primary>postscript, from heap profiles</primary></indexterm> + <indexterm><primary><option>-h<break-down></option></primary></indexterm> + + <para>Usage:</para> + +<screen> +hp2ps [flags] [<file>[.hp]] +</screen> + + <para>The program + <command>hp2ps</command><indexterm><primary>hp2ps + program</primary></indexterm> converts a heap profile as produced + by the <option>-h<break-down></option> runtime option into a + PostScript graph of the heap profile. By convention, the file to + be processed by <command>hp2ps</command> has a + <filename>.hp</filename> extension. The PostScript output is + written to <filename><file>@.ps</filename>. If + <filename><file></filename> is omitted entirely, then the + program behaves as a filter.</para> + + <para><command>hp2ps</command> is distributed in + <filename>ghc/utils/hp2ps</filename> in a GHC source + distribution. It was originally developed by Dave Wakeling as part + of the HBC/LML heap profiler.</para> + + <para>The flags are:</para> + + <variablelist> + + <varlistentry> + <term><option>-d</option></term> + <listitem> + <para>In order to make graphs more readable, + <command>hp2ps</command> sorts the shaded bands for each + identifier. The default sort ordering is for the bands with + the largest area to be stacked on top of the smaller ones. + The <option>-d</option> option causes rougher bands (those + representing series of values with the largest standard + deviations) to be stacked on top of smoother ones.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-b</option></term> + <listitem> + <para>Normally, <command>hp2ps</command> puts the title of + the graph in a small box at the top of the page. However, if + the JOB string is too long to fit in a small box (more than + 35 characters), then <command>hp2ps</command> will choose to + use a big box instead. The <option>-b</option> option + forces <command>hp2ps</command> to use a big box.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-e<float>[in|mm|pt]</option></term> + <listitem> + <para>Generate encapsulated PostScript suitable for + inclusion in LaTeX documents. Usually, the PostScript graph + is drawn in landscape mode in an area 9 inches wide by 6 + inches high, and <command>hp2ps</command> arranges for this + area to be approximately centred on a sheet of a4 paper. + This format is convenient of studying the graph in detail, + but it is unsuitable for inclusion in LaTeX documents. The + <option>-e</option> option causes the graph to be drawn in + portrait mode, with float specifying the width in inches, + millimetres or points (the default). The resulting + PostScript file conforms to the Encapsulated PostScript + (EPS) convention, and it can be included in a LaTeX document + using Rokicki's dvi-to-PostScript converter + <command>dvips</command>.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-g</option></term> + <listitem> + <para>Create output suitable for the <command>gs</command> + PostScript previewer (or similar). In this case the graph is + printed in portrait mode without scaling. The output is + unsuitable for a laser printer.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-l</option></term> + <listitem> + <para>Normally a profile is limited to 20 bands with + additional identifiers being grouped into an + <literal>OTHER</literal> band. The <option>-l</option> flag + removes this 20 band and limit, producing as many bands as + necessary. No key is produced as it won't fit!. It is useful + for creation time profiles with many bands.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-m<int></option></term> + <listitem> + <para>Normally a profile is limited to 20 bands with + additional identifiers being grouped into an + <literal>OTHER</literal> band. The <option>-m</option> flag + specifies an alternative band limit (the maximum is + 20).</para> + + <para><option>-m0</option> requests the band limit to be + removed. As many bands as necessary are produced. However no + key is produced as it won't fit! It is useful for displaying + creation time profiles with many bands.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-p</option></term> + <listitem> + <para>Use previous parameters. By default, the PostScript + graph is automatically scaled both horizontally and + vertically so that it fills the page. However, when + preparing a series of graphs for use in a presentation, it + is often useful to draw a new graph using the same scale, + shading and ordering as a previous one. The + <option>-p</option> flag causes the graph to be drawn using + the parameters determined by a previous run of + <command>hp2ps</command> on <filename>file</filename>. These + are extracted from <filename>file@.aux</filename>.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-s</option></term> + <listitem> + <para>Use a small box for the title.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-t<float></option></term> + <listitem> + <para>Normally trace elements which sum to a total of less + than 1% of the profile are removed from the + profile. The <option>-t</option> option allows this + percentage to be modified (maximum 5%).</para> + + <para><option>-t0</option> requests no trace elements to be + removed from the profile, ensuring that all the data will be + displayed.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-c</option></term> + <listitem> + <para>Generate colour output.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-y</option></term> + <listitem> + <para>Ignore marks.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-?</option></term> + <listitem> + <para>Print out usage information.</para> + </listitem> + </varlistentry> + </variablelist> + + + <sect2 id="manipulating-hp"> + <title>Manipulating the hp file</title> + +<para>(Notes kindly offered by Jan-Willhem Maessen.)</para> + +<para> +The <filename>FOO.hp</filename> file produced when you ask for the +heap profile of a program <filename>FOO</filename> is a text file with a particularly +simple structure. Here's a representative example, with much of the +actual data omitted: +<screen> +JOB "FOO -hC" +DATE "Thu Dec 26 18:17 2002" +SAMPLE_UNIT "seconds" +VALUE_UNIT "bytes" +BEGIN_SAMPLE 0.00 +END_SAMPLE 0.00 +BEGIN_SAMPLE 15.07 + ... sample data ... +END_SAMPLE 15.07 +BEGIN_SAMPLE 30.23 + ... sample data ... +END_SAMPLE 30.23 +... etc. +BEGIN_SAMPLE 11695.47 +END_SAMPLE 11695.47 +</screen> +The first four lines (<literal>JOB</literal>, <literal>DATE</literal>, <literal>SAMPLE_UNIT</literal>, <literal>VALUE_UNIT</literal>) form a +header. Each block of lines starting with <literal>BEGIN_SAMPLE</literal> and ending +with <literal>END_SAMPLE</literal> forms a single sample (you can think of this as a +vertical slice of your heap profile). The hp2ps utility should accept +any input with a properly-formatted header followed by a series of +*complete* samples. +</para> +</sect2> + + <sect2> + <title>Zooming in on regions of your profile</title> + +<para> +You can look at particular regions of your profile simply by loading a +copy of the <filename>.hp</filename> file into a text editor and deleting the unwanted +samples. The resulting <filename>.hp</filename> file can be run through <command>hp2ps</command> and viewed +or printed. +</para> +</sect2> + + <sect2> + <title>Viewing the heap profile of a running program</title> + +<para> +The <filename>.hp</filename> file is generated incrementally as your +program runs. In principle, running <command>hp2ps</command> on the incomplete file +should produce a snapshot of your program's heap usage. However, the +last sample in the file may be incomplete, causing <command>hp2ps</command> to fail. If +you are using a machine with UNIX utilities installed, it's not too +hard to work around this problem (though the resulting command line +looks rather Byzantine): +<screen> + head -`fgrep -n END_SAMPLE FOO.hp | tail -1 | cut -d : -f 1` FOO.hp \ + | hp2ps > FOO.ps +</screen> + +The command <command>fgrep -n END_SAMPLE FOO.hp</command> finds the +end of every complete sample in <filename>FOO.hp</filename>, and labels each sample with +its ending line number. We then select the line number of the last +complete sample using <command>tail</command> and <command>cut</command>. This is used as a +parameter to <command>head</command>; the result is as if we deleted the final +incomplete sample from <filename>FOO.hp</filename>. This results in a properly-formatted +.hp file which we feed directly to <command>hp2ps</command>. +</para> +</sect2> + <sect2> + <title>Viewing a heap profile in real time</title> + +<para> +The <command>gv</command> and <command>ghostview</command> programs +have a "watch file" option can be used to view an up-to-date heap +profile of your program as it runs. Simply generate an incremental +heap profile as described in the previous section. Run <command>gv</command> on your +profile: +<screen> + gv -watch -seascape FOO.ps +</screen> +If you forget the <literal>-watch</literal> flag you can still select +"Watch file" from the "State" menu. Now each time you generate a new +profile <filename>FOO.ps</filename> the view will update automatically. +</para> + +<para> +This can all be encapsulated in a little script: +<screen> + #!/bin/sh + head -`fgrep -n END_SAMPLE FOO.hp | tail -1 | cut -d : -f 1` FOO.hp \ + | hp2ps > FOO.ps + gv -watch -seascape FOO.ps & + while [ 1 ] ; do + sleep 10 # We generate a new profile every 10 seconds. + head -`fgrep -n END_SAMPLE FOO.hp | tail -1 | cut -d : -f 1` FOO.hp \ + | hp2ps > FOO.ps + done +</screen> +Occasionally <command>gv</command> will choke as it tries to read an incomplete copy of +<filename>FOO.ps</filename> (because <command>hp2ps</command> is still running as an update +occurs). A slightly more complicated script works around this +problem, by using the fact that sending a SIGHUP to gv will cause it +to re-read its input file: +<screen> + #!/bin/sh + head -`fgrep -n END_SAMPLE FOO.hp | tail -1 | cut -d : -f 1` FOO.hp \ + | hp2ps > FOO.ps + gv FOO.ps & + gvpsnum=$! + while [ 1 ] ; do + sleep 10 + head -`fgrep -n END_SAMPLE FOO.hp | tail -1 | cut -d : -f 1` FOO.hp \ + | hp2ps > FOO.ps + kill -HUP $gvpsnum + done +</screen> +</para> +</sect2> + + + </sect1> + + <sect1 id="ticky-ticky"> + <title>Using “ticky-ticky” profiling (for implementors)</title> + <indexterm><primary>ticky-ticky profiling</primary></indexterm> + + <para>(ToDo: document properly.)</para> + + <para>It is possible to compile Glasgow Haskell programs so that + they will count lots and lots of interesting things, e.g., number + of updates, number of data constructors entered, etc., etc. We + call this “ticky-ticky” + profiling,<indexterm><primary>ticky-ticky + profiling</primary></indexterm> <indexterm><primary>profiling, + ticky-ticky</primary></indexterm> because that's the sound a Sun4 + makes when it is running up all those counters + (<emphasis>slowly</emphasis>).</para> + + <para>Ticky-ticky profiling is mainly intended for implementors; + it is quite separate from the main “cost-centre” + profiling system, intended for all users everywhere.</para> + + <para>To be able to use ticky-ticky profiling, you will need to + have built appropriate libraries and things when you made the + system. See “Customising what libraries to build,” in + the installation guide.</para> + + <para>To get your compiled program to spit out the ticky-ticky + numbers, use a <option>-r</option> RTS + option<indexterm><primary>-r RTS option</primary></indexterm>. + See <xref linkend="runtime-control"/>.</para> + + <para>Compiling your program with the <option>-ticky</option> + switch yields an executable that performs these counts. Here is a + sample ticky-ticky statistics file, generated by the invocation + <command>foo +RTS -rfoo.ticky</command>.</para> + +<screen> + foo +RTS -rfoo.ticky + + +ALLOCATIONS: 3964631 (11330900 words total: 3999476 admin, 6098829 goods, 1232595 slop) + total words: 2 3 4 5 6+ + 69647 ( 1.8%) function values 50.0 50.0 0.0 0.0 0.0 +2382937 ( 60.1%) thunks 0.0 83.9 16.1 0.0 0.0 +1477218 ( 37.3%) data values 66.8 33.2 0.0 0.0 0.0 + 0 ( 0.0%) big tuples + 2 ( 0.0%) black holes 0.0 100.0 0.0 0.0 0.0 + 0 ( 0.0%) prim things + 34825 ( 0.9%) partial applications 0.0 0.0 0.0 100.0 0.0 + 2 ( 0.0%) thread state objects 0.0 0.0 0.0 0.0 100.0 + +Total storage-manager allocations: 3647137 (11882004 words) + [551104 words lost to speculative heap-checks] + +STACK USAGE: + +ENTERS: 9400092 of which 2005772 (21.3%) direct to the entry code + [the rest indirected via Node's info ptr] +1860318 ( 19.8%) thunks +3733184 ( 39.7%) data values +3149544 ( 33.5%) function values + [of which 1999880 (63.5%) bypassed arg-satisfaction chk] + 348140 ( 3.7%) partial applications + 308906 ( 3.3%) normal indirections + 0 ( 0.0%) permanent indirections + +RETURNS: 5870443 +2137257 ( 36.4%) from entering a new constructor + [the rest from entering an existing constructor] +2349219 ( 40.0%) vectored [the rest unvectored] + +RET_NEW: 2137257: 32.5% 46.2% 21.3% 0.0% 0.0% 0.0% 0.0% 0.0% 0.0% +RET_OLD: 3733184: 2.8% 67.9% 29.3% 0.0% 0.0% 0.0% 0.0% 0.0% 0.0% +RET_UNBOXED_TUP: 2: 0.0% 0.0%100.0% 0.0% 0.0% 0.0% 0.0% 0.0% 0.0% + +RET_VEC_RETURN : 2349219: 0.0% 0.0%100.0% 0.0% 0.0% 0.0% 0.0% 0.0% 0.0% + +UPDATE FRAMES: 2241725 (0 omitted from thunks) +SEQ FRAMES: 1 +CATCH FRAMES: 1 +UPDATES: 2241725 + 0 ( 0.0%) data values + 34827 ( 1.6%) partial applications + [2 in place, 34825 allocated new space] +2206898 ( 98.4%) updates to existing heap objects (46 by squeezing) +UPD_CON_IN_NEW: 0: 0 0 0 0 0 0 0 0 0 +UPD_PAP_IN_NEW: 34825: 0 0 0 34825 0 0 0 0 0 + +NEW GEN UPDATES: 2274700 ( 99.9%) + +OLD GEN UPDATES: 1852 ( 0.1%) + +Total bytes copied during GC: 190096 + +************************************************** +3647137 ALLOC_HEAP_ctr +11882004 ALLOC_HEAP_tot + 69647 ALLOC_FUN_ctr + 69647 ALLOC_FUN_adm + 69644 ALLOC_FUN_gds + 34819 ALLOC_FUN_slp + 34831 ALLOC_FUN_hst_0 + 34816 ALLOC_FUN_hst_1 + 0 ALLOC_FUN_hst_2 + 0 ALLOC_FUN_hst_3 + 0 ALLOC_FUN_hst_4 +2382937 ALLOC_UP_THK_ctr + 0 ALLOC_SE_THK_ctr + 308906 ENT_IND_ctr + 0 E!NT_PERM_IND_ctr requires +RTS -Z +[... lots more info omitted ...] + 0 GC_SEL_ABANDONED_ctr + 0 GC_SEL_MINOR_ctr + 0 GC_SEL_MAJOR_ctr + 0 GC_FAILED_PROMOTION_ctr + 47524 GC_WORDS_COPIED_ctr +</screen> + + <para>The formatting of the information above the row of asterisks + is subject to change, but hopefully provides a useful + human-readable summary. Below the asterisks <emphasis>all + counters</emphasis> maintained by the ticky-ticky system are + dumped, in a format intended to be machine-readable: zero or more + spaces, an integer, a space, the counter name, and a newline.</para> + + <para>In fact, not <emphasis>all</emphasis> counters are + necessarily dumped; compile- or run-time flags can render certain + counters invalid. In this case, either the counter will simply + not appear, or it will appear with a modified counter name, + possibly along with an explanation for the omission (notice + <literal>ENT_PERM_IND_ctr</literal> appears + with an inserted <literal>!</literal> above). Software analysing + this output should always check that it has the counters it + expects. Also, beware: some of the counters can have + <emphasis>large</emphasis> values!</para> + + </sect1> + +</chapter> + +<!-- Emacs stuff: + ;;; Local Variables: *** + ;;; mode: xml *** + ;;; sgml-parent-document: ("users_guide.xml" "book" "chapter") *** + ;;; End: *** + --> diff --git a/docs/users_guide/runtime_control.xml b/docs/users_guide/runtime_control.xml new file mode 100644 index 0000000000..daed07cee3 --- /dev/null +++ b/docs/users_guide/runtime_control.xml @@ -0,0 +1,622 @@ +<?xml version="1.0" encoding="iso-8859-1"?> +<sect1 id="runtime-control"> + <title>Running a compiled program</title> + + <indexterm><primary>runtime control of Haskell programs</primary></indexterm> + <indexterm><primary>running, compiled program</primary></indexterm> + <indexterm><primary>RTS options</primary></indexterm> + + <para>To make an executable program, the GHC system compiles your + code and then links it with a non-trivial runtime system (RTS), + which handles storage management, profiling, etc.</para> + + <para>You have some control over the behaviour of the RTS, by giving + special command-line arguments to your program.</para> + + <para>When your Haskell program starts up, its RTS extracts + command-line arguments bracketed between + <option>+RTS</option><indexterm><primary><option>+RTS</option></primary></indexterm> + and + <option>-RTS</option><indexterm><primary><option>-RTS</option></primary></indexterm> + as its own. For example:</para> + +<screen> +% ./a.out -f +RTS -p -S -RTS -h foo bar +</screen> + + <para>The RTS will snaffle <option>-p</option> <option>-S</option> + for itself, and the remaining arguments <literal>-f -h foo bar</literal> + will be handed to your program if/when it calls + <function>System.getArgs</function>.</para> + + <para>No <option>-RTS</option> option is required if the + runtime-system options extend to the end of the command line, as in + this example:</para> + +<screen> +% hls -ltr /usr/etc +RTS -A5m +</screen> + + <para>If you absolutely positively want all the rest of the options + in a command line to go to the program (and not the RTS), use a + <option>––RTS</option><indexterm><primary><option>--RTS</option></primary></indexterm>.</para> + + <para>As always, for RTS options that take + <replaceable>size</replaceable>s: If the last character of + <replaceable>size</replaceable> is a K or k, multiply by 1000; if an + M or m, by 1,000,000; if a G or G, by 1,000,000,000. (And any + wraparound in the counters is <emphasis>your</emphasis> + fault!)</para> + + <para>Giving a <literal>+RTS -f</literal> + <indexterm><primary><option>-f</option></primary><secondary>RTS option</secondary></indexterm> option + will print out the RTS options actually available in your program + (which vary, depending on how you compiled).</para> + + <para>NOTE: since GHC is itself compiled by GHC, you can change RTS + options in the compiler using the normal + <literal>+RTS ... -RTS</literal> + combination. eg. to increase the maximum heap + size for a compilation to 128M, you would add + <literal>+RTS -M128m -RTS</literal> + to the command line.</para> + + <sect2 id="rts-optinos-environment"> + <title>Setting global RTS options</title> + + <indexterm><primary>RTS options</primary><secondary>from the environment</secondary></indexterm> + <indexterm><primary>environment variable</primary><secondary>for + setting RTS options</secondary></indexterm> + + <para>RTS options are also taken from the environment variable + <envar>GHCRTS</envar><indexterm><primary><envar>GHCRTS</envar></primary> + </indexterm>. For example, to set the maximum heap size + to 128M for all GHC-compiled programs (using an + <literal>sh</literal>-like shell):</para> + +<screen> + GHCRTS='-M128m' + export GHCRTS +</screen> + + <para>RTS options taken from the <envar>GHCRTS</envar> environment + variable can be overridden by options given on the command + line.</para> + + </sect2> + + <sect2 id="rts-options-gc"> + <title>RTS options to control the garbage collector</title> + + <indexterm><primary>garbage collector</primary><secondary>options</secondary></indexterm> + <indexterm><primary>RTS options</primary><secondary>garbage collection</secondary></indexterm> + + <para>There are several options to give you precise control over + garbage collection. Hopefully, you won't need any of these in + normal operation, but there are several things that can be tweaked + for maximum performance.</para> + + <variablelist> + + <varlistentry> + <term> + <option>-A</option><replaceable>size</replaceable> + <indexterm><primary><option>-A</option></primary><secondary>RTS option</secondary></indexterm> + <indexterm><primary>allocation area, size</primary></indexterm> + </term> + <listitem> + <para>[Default: 256k] Set the allocation area size + used by the garbage collector. The allocation area + (actually generation 0 step 0) is fixed and is never resized + (unless you use <option>-H</option>, below).</para> + + <para>Increasing the allocation area size may or may not + give better performance (a bigger allocation area means + worse cache behaviour but fewer garbage collections and less + promotion).</para> + + <para>With only 1 generation (<option>-G1</option>) the + <option>-A</option> option specifies the minimum allocation + area, since the actual size of the allocation area will be + resized according to the amount of data in the heap (see + <option>-F</option>, below).</para> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <option>-c</option> + <indexterm><primary><option>-c</option></primary><secondary>RTS option</secondary></indexterm> + <indexterm><primary>garbage collection</primary><secondary>compacting</secondary></indexterm> + <indexterm><primary>compacting garbage collection</primary></indexterm> + </term> + <listitem> + <para>Use a compacting algorithm for collecting the oldest + generation. By default, the oldest generation is collected + using a copying algorithm; this option causes it to be + compacted in-place instead. The compaction algorithm is + slower than the copying algorithm, but the savings in memory + use can be considerable.</para> + + <para>For a given heap size (using the <option>-H</option> + option), compaction can in fact reduce the GC cost by + allowing fewer GCs to be performed. This is more likely + when the ratio of live data to heap size is high, say + >30%.</para> + + <para>NOTE: compaction doesn't currently work when a single + generation is requested using the <option>-G1</option> + option.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-c</option><replaceable>n</replaceable></term> + + <listitem> + <para>[Default: 30] Automatically enable + compacting collection when the live data exceeds + <replaceable>n</replaceable>% of the maximum heap size + (see the <option>-M</option> option). Note that the maximum + heap size is unlimited by default, so this option has no + effect unless the maximum heap size is set with + <option>-M</option><replaceable>size</replaceable>. </para> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <option>-F</option><replaceable>factor</replaceable> + <indexterm><primary><option>-F</option></primary><secondary>RTS option</secondary></indexterm> + <indexterm><primary>heap size, factor</primary></indexterm> + </term> + <listitem> + + <para>[Default: 2] This option controls the amount + of memory reserved for the older generations (and in the + case of a two space collector the size of the allocation + area) as a factor of the amount of live data. For example, + if there was 2M of live data in the oldest generation when + we last collected it, then by default we'll wait until it + grows to 4M before collecting it again.</para> + + <para>The default seems to work well here. If you have + plenty of memory, it is usually better to use + <option>-H</option><replaceable>size</replaceable> than to + increase + <option>-F</option><replaceable>factor</replaceable>.</para> + + <para>The <option>-F</option> setting will be automatically + reduced by the garbage collector when the maximum heap size + (the <option>-M</option><replaceable>size</replaceable> + setting) is approaching.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <option>-G</option><replaceable>generations</replaceable> + <indexterm><primary><option>-G</option></primary><secondary>RTS option</secondary></indexterm> + <indexterm><primary>generations, number of</primary></indexterm> + </term> + <listitem> + <para>[Default: 2] Set the number of generations + used by the garbage collector. The default of 2 seems to be + good, but the garbage collector can support any number of + generations. Anything larger than about 4 is probably not a + good idea unless your program runs for a + <emphasis>long</emphasis> time, because the oldest + generation will hardly ever get collected.</para> + + <para>Specifying 1 generation with <option>+RTS -G1</option> + gives you a simple 2-space collector, as you would expect. + In a 2-space collector, the <option>-A</option> option (see + above) specifies the <emphasis>minimum</emphasis> allocation + area size, since the allocation area will grow with the + amount of live data in the heap. In a multi-generational + collector the allocation area is a fixed size (unless you + use the <option>-H</option> option, see below).</para> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <option>-H</option><replaceable>size</replaceable> + <indexterm><primary><option>-H</option></primary><secondary>RTS option</secondary></indexterm> + <indexterm><primary>heap size, suggested</primary></indexterm> + </term> + <listitem> + <para>[Default: 0] This option provides a + “suggested heap size” for the garbage collector. The + garbage collector will use about this much memory until the + program residency grows and the heap size needs to be + expanded to retain reasonable performance.</para> + + <para>By default, the heap will start small, and grow and + shrink as necessary. This can be bad for performance, so if + you have plenty of memory it's worthwhile supplying a big + <option>-H</option><replaceable>size</replaceable>. For + improving GC performance, using + <option>-H</option><replaceable>size</replaceable> is + usually a better bet than + <option>-A</option><replaceable>size</replaceable>.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <option>-I</option><replaceable>seconds</replaceable> + <indexterm><primary><option>-H</option></primary> + <secondary>RTS option</secondary> + </indexterm> + <indexterm><primary>idle GC</primary> + </indexterm> + </term> + <listitem> + <para>(default: 0.3) In the threaded and SMP versions of the RTS (see + <option>-threaded</option>, <xref linkend="options-linker" />), a + major GC is automatically performed if the runtime has been idle + (no Haskell computation has been running) for a period of time. + The amount of idle time which must pass before a GC is performed is + set by the <option>-I</option><replaceable>seconds</replaceable> + option. Specifying <option>-I0</option> disables the idle GC.</para> + + <para>For an interactive application, it is probably a good idea to + use the idle GC, because this will allow finalizers to run and + deadlocked threads to be detected in the idle time when no Haskell + computation is happening. Also, it will mean that a GC is less + likely to happen when the application is busy, and so + responsiveness may be improved. However, if the amount of live data in + the heap is particularly large, then the idle GC can cause a + significant delay, and too small an interval could adversely affect + interactive responsiveness.</para> + + <para>This is an experimental feature, please let us know if it + causes problems and/or could benefit from further tuning.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <option>-k</option><replaceable>size</replaceable> + <indexterm><primary><option>-k</option></primary><secondary>RTS option</secondary></indexterm> + <indexterm><primary>stack, minimum size</primary></indexterm> + </term> + <listitem> + <para>[Default: 1k] Set the initial stack size for + new threads. Thread stacks (including the main thread's + stack) live on the heap, and grow as required. The default + value is good for concurrent applications with lots of small + threads; if your program doesn't fit this model then + increasing this option may help performance.</para> + + <para>The main thread is normally started with a slightly + larger heap to cut down on unnecessary stack growth while + the program is starting up.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <option>-K</option><replaceable>size</replaceable> + <indexterm><primary><option>-K</option></primary><secondary>RTS option</secondary></indexterm> + <indexterm><primary>stack, maximum size</primary></indexterm> + </term> + <listitem> + <para>[Default: 8M] Set the maximum stack size for + an individual thread to <replaceable>size</replaceable> + bytes. This option is there purely to stop the program + eating up all the available memory in the machine if it gets + into an infinite loop.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <option>-m</option><replaceable>n</replaceable> + <indexterm><primary><option>-m</option></primary><secondary>RTS option</secondary></indexterm> + <indexterm><primary>heap, minimum free</primary></indexterm> + </term> + <listitem> + <para>Minimum % <replaceable>n</replaceable> of heap + which must be available for allocation. The default is + 3%.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <option>-M</option><replaceable>size</replaceable> + <indexterm><primary><option>-M</option></primary><secondary>RTS option</secondary></indexterm> + <indexterm><primary>heap size, maximum</primary></indexterm> + </term> + <listitem> + <para>[Default: unlimited] Set the maximum heap size to + <replaceable>size</replaceable> bytes. The heap normally + grows and shrinks according to the memory requirements of + the program. The only reason for having this option is to + stop the heap growing without bound and filling up all the + available swap space, which at the least will result in the + program being summarily killed by the operating + system.</para> + + <para>The maximum heap size also affects other garbage + collection parameters: when the amount of live data in the + heap exceeds a certain fraction of the maximum heap size, + compacting collection will be automatically enabled for the + oldest generation, and the <option>-F</option> parameter + will be reduced in order to avoid exceeding the maximum heap + size.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <option>-s</option><replaceable>file</replaceable> + <indexterm><primary><option>-s</option></primary><secondary>RTS option</secondary></indexterm> + </term> + <term> + <option>-S</option><replaceable>file</replaceable> + <indexterm><primary><option>-S</option></primary><secondary>RTS option</secondary></indexterm> + </term> + <listitem> + <para>Write modest (<option>-s</option>) or verbose + (<option>-S</option>) garbage-collector statistics into file + <replaceable>file</replaceable>. The default + <replaceable>file</replaceable> is + <filename><replaceable>program</replaceable>.stat</filename>. The + <replaceable>file</replaceable> <constant>stderr</constant> + is treated specially, with the output really being sent to + <constant>stderr</constant>.</para> + + <para>This option is useful for watching how the storage + manager adjusts the heap size based on the current amount of + live data.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <option>-t<replaceable>file</replaceable></option> + <indexterm><primary><option>-t</option></primary><secondary>RTS option</secondary></indexterm> + </term> + <listitem> + <para>Write a one-line GC stats summary after running the + program. This output is in the same format as that produced + by the <option>-Rghc-timing</option> option.</para> + + <para>As with <option>-s</option>, the default + <replaceable>file</replaceable> is + <filename><replaceable>program</replaceable>.stat</filename>. The + <replaceable>file</replaceable> <constant>stderr</constant> + is treated specially, with the output really being sent to + <constant>stderr</constant>.</para> + </listitem> + </varlistentry> + </variablelist> + + </sect2> + + <sect2> + <title>RTS options for profiling and Concurrent/Parallel Haskell</title> + + <para>The RTS options related to profiling are described in <xref + linkend="rts-options-heap-prof"/>; and those for concurrent/parallel + stuff, in <xref linkend="parallel-rts-opts"/>.</para> + </sect2> + + <sect2 id="rts-options-debugging"> + <title>RTS options for hackers, debuggers, and over-interested + souls</title> + + <indexterm><primary>RTS options, hacking/debugging</primary></indexterm> + + <para>These RTS options might be used (a) to avoid a GHC bug, + (b) to see “what's really happening”, or + (c) because you feel like it. Not recommended for everyday + use!</para> + + <variablelist> + + <varlistentry> + <term> + <option>-B</option> + <indexterm><primary><option>-B</option></primary><secondary>RTS option</secondary></indexterm> + </term> + <listitem> + <para>Sound the bell at the start of each (major) garbage + collection.</para> + + <para>Oddly enough, people really do use this option! Our + pal in Durham (England), Paul Callaghan, writes: “Some + people here use it for a variety of + purposes—honestly!—e.g., confirmation that the + code/machine is doing something, infinite loop detection, + gauging cost of recently added code. Certain people can even + tell what stage [the program] is in by the beep + pattern. But the major use is for annoying others in the + same office…”</para> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <option>-D</option><replaceable>num</replaceable> + <indexterm><primary>-D</primary><secondary>RTS option</secondary></indexterm> + </term> + <listitem> + <para>An RTS debugging flag; varying quantities of output + depending on which bits are set in + <replaceable>num</replaceable>. Only works if the RTS was + compiled with the <option>DEBUG</option> option.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <option>-r</option><replaceable>file</replaceable> + <indexterm><primary><option>-r</option></primary><secondary>RTS option</secondary></indexterm> + <indexterm><primary>ticky ticky profiling</primary></indexterm> + <indexterm><primary>profiling</primary><secondary>ticky ticky</secondary></indexterm> + </term> + <listitem> + <para>Produce “ticky-ticky” statistics at the + end of the program run. The <replaceable>file</replaceable> + business works just like on the <option>-S</option> RTS + option (above).</para> + + <para>“Ticky-ticky” statistics are counts of + various program actions (updates, enters, etc.) The program + must have been compiled using + <option>-ticky</option><indexterm><primary><option>-ticky</option></primary></indexterm> + (a.k.a. “ticky-ticky profiling”), and, for it to + be really useful, linked with suitable system libraries. + Not a trivial undertaking: consult the installation guide on + how to set things up for easy “ticky-ticky” + profiling. For more information, see <xref + linkend="ticky-ticky"/>.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <option>-xc</option> + <indexterm><primary><option>-xc</option></primary><secondary>RTS option</secondary></indexterm> + </term> + <listitem> + <para>(Only available when the program is compiled for + profiling.) When an exception is raised in the program, + this option causes the current cost-centre-stack to be + dumped to <literal>stderr</literal>.</para> + + <para>This can be particularly useful for debugging: if your + program is complaining about a <literal>head []</literal> + error and you haven't got a clue which bit of code is + causing it, compiling with <literal>-prof + -auto-all</literal> and running with <literal>+RTS -xc + -RTS</literal> will tell you exactly the call stack at the + point the error was raised.</para> + + <para>The output contains one line for each exception raised + in the program (the program might raise and catch several + exceptions during its execution), where each line is of the + form:</para> + +<screen> +< cc<subscript>1</subscript>, ..., cc<subscript>n</subscript> > +</screen> + <para>each <literal>cc</literal><subscript>i</subscript> is + a cost centre in the program (see <xref + linkend="cost-centres"/>), and the sequence represents the + “call stack” at the point the exception was + raised. The leftmost item is the innermost function in the + call stack, and the rightmost item is the outermost + function.</para> + + </listitem> + </varlistentry> + + <varlistentry> + <term> + <option>-Z</option> + <indexterm><primary><option>-Z</option></primary><secondary>RTS option</secondary></indexterm> + </term> + <listitem> + <para>Turn <emphasis>off</emphasis> “update-frame + squeezing” at garbage-collection time. (There's no + particularly good reason to turn it off, except to ensure + the accuracy of certain data collected regarding thunk entry + counts.)</para> + </listitem> + </varlistentry> + </variablelist> + + </sect2> + + <sect2 id="rts-hooks"> + <title>“Hooks” to change RTS behaviour</title> + + <indexterm><primary>hooks</primary><secondary>RTS</secondary></indexterm> + <indexterm><primary>RTS hooks</primary></indexterm> + <indexterm><primary>RTS behaviour, changing</primary></indexterm> + + <para>GHC lets you exercise rudimentary control over the RTS + settings for any given program, by compiling in a + “hook” that is called by the run-time system. The RTS + contains stub definitions for all these hooks, but by writing your + own version and linking it on the GHC command line, you can + override the defaults.</para> + + <para>Owing to the vagaries of DLL linking, these hooks don't work + under Windows when the program is built dynamically.</para> + + <para>The hook <literal>ghc_rts_opts</literal><indexterm><primary><literal>ghc_rts_opts</literal></primary> + </indexterm>lets you set RTS + options permanently for a given program. A common use for this is + to give your program a default heap and/or stack size that is + greater than the default. For example, to set <literal>-H128m + -K1m</literal>, place the following definition in a C source + file:</para> + +<programlisting> +char *ghc_rts_opts = "-H128m -K1m"; +</programlisting> + + <para>Compile the C file, and include the object file on the + command line when you link your Haskell program.</para> + + <para>These flags are interpreted first, before any RTS flags from + the <literal>GHCRTS</literal> environment variable and any flags + on the command line.</para> + + <para>You can also change the messages printed when the runtime + system “blows up,” e.g., on stack overflow. The hooks + for these are as follows:</para> + + <variablelist> + + <varlistentry> + <term> + <function>void OutOfHeapHook (unsigned long, unsigned long)</function> + <indexterm><primary><function>OutOfHeapHook</function></primary></indexterm> + </term> + <listitem> + <para>The heap-overflow message.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <function>void StackOverflowHook (long int)</function> + <indexterm><primary><function>StackOverflowHook</function></primary></indexterm> + </term> + <listitem> + <para>The stack-overflow message.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <function>void MallocFailHook (long int)</function> + <indexterm><primary><function>MallocFailHook</function></primary></indexterm> + </term> + <listitem> + <para>The message printed if <function>malloc</function> + fails.</para> + </listitem> + </varlistentry> + </variablelist> + + <para>For examples of the use of these hooks, see GHC's own + versions in the file + <filename>ghc/compiler/parser/hschooks.c</filename> in a GHC + source tree.</para> + </sect2> +</sect1> + +<!-- Emacs stuff: + ;;; Local Variables: *** + ;;; mode: xml *** + ;;; sgml-parent-document: ("users_guide.xml" "book" "chapter" "sect1") *** + ;;; End: *** + --> diff --git a/docs/users_guide/separate_compilation.xml b/docs/users_guide/separate_compilation.xml new file mode 100644 index 0000000000..c33ff2175b --- /dev/null +++ b/docs/users_guide/separate_compilation.xml @@ -0,0 +1,1213 @@ +<?xml version="1.0" encoding="iso-8859-1"?> + <sect1 id="separate-compilation"> + <title>Filenames and separate compilation</title> + + <indexterm><primary>separate compilation</primary></indexterm> + <indexterm><primary>recompilation checker</primary></indexterm> + <indexterm><primary>make and recompilation</primary></indexterm> + + <para>This section describes what files GHC expects to find, what + files it creates, where these files are stored, and what options + affect this behaviour.</para> + + <para>Note that this section is written with + <firstterm>hierarchical modules</firstterm> in mind (see <xref + linkend="hierarchical-modules"/>); hierarchical modules are an + extension to Haskell 98 which extends the lexical syntax of + module names to include a dot ‘.’. Non-hierarchical + modules are thus a special case in which none of the module names + contain dots.</para> + + <para>Pathname conventions vary from system to system. In + particular, the directory separator is + ‘<literal>/</literal>’ on Unix systems and + ‘<literal>\</literal>’ on Windows systems. In the + sections that follow, we shall consistently use + ‘<literal>/</literal>’ as the directory separator; + substitute this for the appropriate character for your + system.</para> + + <sect2 id="source-files"> + <title>Haskell source files</title> + + <indexterm><primary>filenames</primary></indexterm> + + <para>Each Haskell source module should be placed in a file on + its own.</para> + + <para>Usually, the file should be named after the module name, + replacing dots in the module name by directory separators. For + example, on a Unix system, the module <literal>A.B.C</literal> + should be placed in the file <literal>A/B/C.hs</literal>, + relative to some base directory. If the module is not going to + be imported by another module (<literal>Main</literal>, for + example), then you are free to use any filename for it.</para> + + <indexterm><primary>unicode</primary></indexterm> + + <para> GHC assumes that source files are + ASCII<indexterm><primary>ASCII</primary></indexterm> or + UTF-8<indexterm><primary>UTF-8</primary></indexterm> only, other + encodings<indexterm><primary>encoding</primary></indexterm> are + not recognised. However, invalid UTF-8 sequences will be + ignored in comments, so it is possible to use other encodings + such as + Latin-1<indexterm><primary>Latin-1</primary></indexterm>, as + long as the non-comment source code is ASCII only.</para> + </sect2> + + <sect2 id="output-files"> + <title>Output files</title> + + <indexterm><primary>interface files</primary></indexterm> + <indexterm><primary><literal>.hi</literal> files</primary></indexterm> + <indexterm><primary>object files</primary></indexterm> + <indexterm><primary><literal>.o</literal> files</primary></indexterm> + + <para>When asked to compile a source file, GHC normally + generates two files: an <firstterm>object file</firstterm>, and + an <firstterm>interface file</firstterm>. </para> + + <para>The object file, which normally ends in a + <literal>.o</literal> suffix, contains the compiled code for the + module.</para> + + <para>The interface file, + which normally ends in a <literal>.hi</literal> suffix, contains + the information that GHC needs in order to compile further + modules that depend on this module. It contains things like the + types of exported functions, definitions of data types, and so + on. It is stored in a binary format, so don't try to read one; + use the <option>--show-iface</option> option instead (see <xref + linkend="hi-options"/>).</para> + + <para>You should think of the object file and the interface file as a + pair, since the interface file is in a sense a compiler-readable + description of the contents of the object file. If the + interface file and object file get out of sync for any reason, + then the compiler may end up making assumptions about the object + file that aren't true; trouble will almost certainly follow. + For this reason, we recommend keeping object files and interface + files in the same place (GHC does this by default, but it is + possible to override the defaults as we'll explain + shortly).</para> + + <para>Every module has a <emphasis>module name</emphasis> + defined in its source code (<literal>module A.B.C where + ...</literal>).</para> + + <para>The name of the object file generated by GHC is derived + according to the following rules, where + <replaceable>osuf</replaceable> is the object-file suffix (this + can be changed with the <option>-osuf</option> option).</para> + + <itemizedlist> + <listitem> + <para>If there is no <option>-odir</option> option (the + default), then the object filename is derived from the + source filename (ignoring the module name) by replacing the + suffix with <replaceable>osuf</replaceable>.</para> + </listitem> + <listitem> + <para>If + <option>-odir</option> <replaceable>dir</replaceable> + has been specified, then the object filename is + <replaceable>dir</replaceable>/<replaceable>mod</replaceable>.<replaceable>osuf</replaceable>, + where <replaceable>mod</replaceable> is the module name with + dots replaced by slashes.</para> + </listitem> + </itemizedlist> + + <para>The name of the interface file is derived using the same + rules, except that the suffix is + <replaceable>hisuf</replaceable> (<literal>.hi</literal> by + default) instead of <replaceable>osuf</replaceable>, and the + relevant options are <option>-hidir</option> and + <option>-hisuf</option> instead of <option>-odir</option> and + <option>-osuf</option> respectively.</para> + + <para>For example, if GHC compiles the module + <literal>A.B.C</literal> in the file + <filename>src/A/B/C.hs</filename>, with no + <literal>-odir</literal> or <literal>-hidir</literal> flags, the + interface file will be put in <literal>src/A/B/C.hi</literal> + and the object file in <literal>src/A/B/C.o</literal>.</para> + + <para>For any module that is imported, GHC requires that the + name of the module in the import statement exactly matches the + name of the module in the interface file (or source file) found + using the strategy specified in <xref linkend="search-path"/>. + This means that for most modules, the source file name should + match the module name.</para> + + <para>However, note that it is reasonable to have a module + <literal>Main</literal> in a file named + <filename>foo.hs</filename>, but this only works because GHC + never needs to search for the interface for module + <literal>Main</literal> (because it is never imported). It is + therefore possible to have several <literal>Main</literal> + modules in separate source files in the same directory, and GHC + will not get confused.</para> + + <para>In batch compilation mode, the name of the object file can + also be overridden using the <option>-o</option> option, and the + name of the interface file can be specified directly using the + <option>-ohi</option> option.</para> + </sect2> + + <sect2 id="search-path"> + <title>The search path</title> + + <indexterm><primary>search path</primary> + </indexterm> + <indexterm><primary>interface files, finding them</primary></indexterm> + <indexterm><primary>finding interface files</primary></indexterm> + + <para>In your program, you import a module + <literal>Foo</literal> by saying <literal>import Foo</literal>. + In <option>--make</option> mode or GHCi, GHC will look for a + source file for <literal>Foo</literal> and arrange to compile it + first. Without <option>--make</option>, GHC will look for the + interface file for <literal>Foo</literal>, which should have + been created by an earlier compilation of + <literal>Foo</literal>. GHC uses the same strategy in each of + these cases for finding the appropriate file.</para> + + <para>This strategy is as follows: GHC keeps a list of + directories called the <firstterm>search path</firstterm>. For + each of these directories, it tries appending + <replaceable>basename</replaceable><literal>.</literal><replaceable>extension</replaceable> + to the directory, and checks whether the file exists. The value + of <replaceable>basename</replaceable> is the module name with + dots replaced by the directory separator ('/' or '\', depending + on the system), and <replaceable>extension</replaceable> is a + source extension (<literal>hs</literal>, <literal>lhs</literal>) + if we are in <option>--make</option> mode and GHCi, or + <replaceable>hisuf</replaceable> otherwise.</para> + + <para>For example, suppose the search path contains directories + <literal>d1</literal>, <literal>d2</literal>, and + <literal>d3</literal>, and we are in <literal>--make</literal> + mode looking for the source file for a module + <literal>A.B.C</literal>. GHC will look in + <literal>d1/A/B/C.hs</literal>, <literal>d1/A/B/C.lhs</literal>, + <literal>d2/A/B/C.hs</literal>, and so on.</para> + + <para>The search path by default contains a single directory: + <quote>.</quote> (i.e. the current directory). The following + options can be used to add to or change the contents of the + search path:</para> + + <variablelist> + <varlistentry> + <term><option>-i<replaceable>dirs</replaceable></option></term> + <listitem> + <para><indexterm><primary><option>-i<replaceable>dirs</replaceable></option> + </primary></indexterm>This flag appends a colon-separated + list of <filename>dirs</filename> to the search path.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-i</option></term> + <listitem> + <para>resets the search path back to nothing.</para> + </listitem> + </varlistentry> + </variablelist> + + <para>This isn't the whole story: GHC also looks for modules in + pre-compiled libraries, known as packages. See the section on + packages (<xref linkend="packages"/>), for details.</para> + </sect2> + + <sect2 id="options-output"> + <title>Redirecting the compilation output(s)</title> + + <indexterm><primary>output-directing options</primary></indexterm> + <indexterm><primary>redirecting compilation output</primary></indexterm> + + <variablelist> + <varlistentry> + <term> + <option>-o</option> <replaceable>file</replaceable> + <indexterm><primary><option>-o</option></primary></indexterm> + </term> + <listitem> + <para>GHC's compiled output normally goes into a + <filename>.hc</filename>, <filename>.o</filename>, etc., + file, depending on the last-run compilation phase. The + option <option>-o <replaceable>file</replaceable></option> + re-directs the output of that last-run phase to + <replaceable>file</replaceable>.</para> + + <para>Note: this “feature” can be + counterintuitive: <command>ghc -C -o foo.o + foo.hs</command> will put the intermediate C code in the + file <filename>foo.o</filename>, name + notwithstanding!</para> + + <para>This option is most often used when creating an + executable file, to set the filename of the executable. + For example: +<screen> ghc -o prog --make Main</screen> + + will compile the program starting with module + <literal>Main</literal> and put the executable in the + file <literal>prog</literal>.</para> + + <para>Note: on Windows, if the result is an executable + file, the extension "<filename>.exe</filename>" is added + if the specified filename does not already have an + extension. Thus +<programlisting> + ghc -o foo Main.hs +</programlisting> + will compile and link the module + <filename>Main.hs</filename>, and put the resulting + executable in <filename>foo.exe</filename> (not + <filename>foo</filename>).</para> + + <para>If you use <command>ghc --make</command> and you don't + use the <option>-o</option>, the name GHC will choose + for the executable will be based on the name of the file + containing the module <literal>Main</literal>. + Note that with GHC the <literal>Main</literal> module doesn't + have to be put in file <filename>Main.hs</filename>. + Thus both +<programlisting> + ghc --make Prog +</programlisting> + and +<programlisting> + ghc --make Prog.hs +</programlisting> + will produce <filename>Prog</filename> (or + <filename>Prog.exe</filename> if you are on Windows).</para> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <option>-odir</option> <replaceable>dir</replaceable> + <indexterm><primary><option>-odir</option></primary></indexterm> + </term> + <listitem> + <para>Redirects object files to directory + <replaceable>dir</replaceable>. For example:</para> + +<screen> +$ ghc -c parse/Foo.hs parse/Bar.hs gurgle/Bumble.hs -odir `arch` +</screen> + + <para>The object files, <filename>Foo.o</filename>, + <filename>Bar.o</filename>, and + <filename>Bumble.o</filename> would be put into a + subdirectory named after the architecture of the executing + machine (<filename>x86</filename>, + <filename>mips</filename>, etc).</para> + + <para>Note that the <option>-odir</option> option does + <emphasis>not</emphasis> affect where the interface files + are put; use the <option>-hidir</option> option for that. + In the above example, they would still be put in + <filename>parse/Foo.hi</filename>, + <filename>parse/Bar.hi</filename>, and + <filename>gurgle/Bumble.hi</filename>.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <option>-ohi</option> <replaceable>file</replaceable> + <indexterm><primary><option>-ohi</option></primary></indexterm> + </term> + <listitem> + <para>The interface output may be directed to another file + <filename>bar2/Wurble.iface</filename> with the option + <option>-ohi bar2/Wurble.iface</option> (not + recommended).</para> + + <para>WARNING: if you redirect the interface file + somewhere that GHC can't find it, then the recompilation + checker may get confused (at the least, you won't get any + recompilation avoidance). We recommend using a + combination of <option>-hidir</option> and + <option>-hisuf</option> options instead, if + possible.</para> + + <para>To avoid generating an interface at all, you could + use this option to redirect the interface into the bit + bucket: <literal>-ohi /dev/null</literal>, for + example.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <option>-hidir</option> <replaceable>dir</replaceable> + <indexterm><primary><option>-hidir</option></primary></indexterm> + </term> + <listitem> + <para>Redirects all generated interface files into + <replaceable>dir</replaceable>, instead of the + default.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <option>-stubdir</option> <replaceable>dir</replaceable> + <indexterm><primary><option>-stubdir</option></primary></indexterm> + </term> + <listitem> + <para>Redirects all generated FFI stub files into + <replaceable>dir</replaceable>. Stub files are generated when the + Haskell source contains a <literal>foreign export</literal> or + <literal>foreign import "&wrapper"</literal> declaration (see <xref + linkend="foreign-export-ghc" />). The <option>-stubdir</option> + option behaves in exactly the same way as <option>-odir</option> + and <option>-hidir</option> with respect to hierarchical + modules.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <option>-osuf</option> <replaceable>suffix</replaceable> + <indexterm><primary><option>-osuf</option></primary></indexterm> + </term> + <term> + <option>-hisuf</option> <replaceable>suffix</replaceable> + <indexterm><primary><option>-hisuf</option></primary></indexterm> + </term> + <term> + <option>-hcsuf</option> <replaceable>suffix</replaceable> + <indexterm><primary><option>-hcsuf</option></primary></indexterm> + </term> + <listitem> + <para>The <option>-osuf</option> + <replaceable>suffix</replaceable> will change the + <literal>.o</literal> 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.</para> + + <para>Similarly, the <option>-hisuf</option> + <replaceable>suffix</replaceable> will change the + <literal>.hi</literal> file suffix for non-system + interface files (see <xref linkend="hi-options"/>).</para> + + <para>Finally, the option <option>-hcsuf</option> + <replaceable>suffix</replaceable> will change the + <literal>.hc</literal> file suffix for compiler-generated + intermediate C files.</para> + + <para>The <option>-hisuf</option>/<option>-osuf</option> + game is particularly useful if you want to compile a + program both with and without profiling, in the same + directory. You can say: + <screen> + ghc ...</screen> + to get the ordinary version, and + <screen> + ghc ... -osuf prof.o -hisuf prof.hi -prof -auto-all</screen> + to get the profiled version.</para> + </listitem> + </varlistentry> + </variablelist> + </sect2> + + <sect2 id="keeping-intermediates"> + <title>Keeping Intermediate Files</title> + <indexterm><primary>intermediate files, saving</primary> + </indexterm> + <indexterm><primary><literal>.hc</literal> files, saving</primary> + </indexterm> + <indexterm><primary><literal>.s</literal> files, saving</primary> + </indexterm> + + <para>The following options are useful for keeping certain + intermediate files around, when normally GHC would throw these + away after compilation:</para> + + <variablelist> + <varlistentry> + <term> + <option>-keep-hc-files</option> + <indexterm><primary><option>-keep-hc-files</option></primary></indexterm> + </term> + <listitem> + <para>Keep intermediate <literal>.hc</literal> files when + doing <literal>.hs</literal>-to-<literal>.o</literal> + compilations via C (NOTE: <literal>.hc</literal> files + aren't generated when using the native code generator, you + may need to use <option>-fvia-C</option> to force them + to be produced).</para> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <option>-keep-s-files</option> + <indexterm><primary><option>-keep-s-files</option></primary></indexterm> + </term> + <listitem> + <para>Keep intermediate <literal>.s</literal> files.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <option>-keep-raw-s-files</option> + <indexterm><primary><option>-keep-raw-s-files</option></primary></indexterm> + </term> + <listitem> + <para>Keep intermediate <literal>.raw-s</literal> files. + These are the direct output from the C compiler, before + GHC does “assembly mangling” to produce the + <literal>.s</literal> file. Again, these are not produced + when using the native code generator.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <option>-keep-tmp-files</option> + <indexterm><primary><option>-keep-tmp-files</option></primary></indexterm> + <indexterm><primary>temporary files</primary><secondary>keeping</secondary></indexterm> + </term> + <listitem> + <para>Instructs the GHC driver not to delete any of its + temporary files, which it normally keeps in + <literal>/tmp</literal> (or possibly elsewhere; see <xref + linkend="temp-files"/>). Running GHC with + <option>-v</option> will show you what temporary files + were generated along the way.</para> + </listitem> + </varlistentry> + </variablelist> + </sect2> + + <sect2 id="temp-files"> + <title>Redirecting temporary files</title> + + <indexterm> + <primary>temporary files</primary> + <secondary>redirecting</secondary> + </indexterm> + + <variablelist> + <varlistentry> + <term> + <option>-tmpdir</option> + <indexterm><primary><option>-tmpdir</option></primary></indexterm> + </term> + <listitem> + <para>If you have trouble because of running out of space + in <filename>/tmp</filename> (or wherever your + installation thinks temporary files should go), you may + use the <option>-tmpdir + <dir></option><indexterm><primary>-tmpdir + <dir> option</primary></indexterm> option to specify + an alternate directory. For example, <option>-tmpdir + .</option> says to put temporary files in the current + working directory.</para> + + <para>Alternatively, use your <constant>TMPDIR</constant> + environment variable.<indexterm><primary>TMPDIR + environment variable</primary></indexterm> Set it to the + name of the directory where temporary files should be put. + GCC and other programs will honour the + <constant>TMPDIR</constant> variable as well.</para> + + <para>Even better idea: Set the + <constant>DEFAULT_TMPDIR</constant> make variable when + building GHC, and never worry about + <constant>TMPDIR</constant> again. (see the build + documentation).</para> + </listitem> + </varlistentry> + </variablelist> + </sect2> + + <sect2 id="hi-options"> + <title>Other options related to interface files</title> + <indexterm><primary>interface files, options</primary></indexterm> + + <variablelist> + <varlistentry> + <term> + <option>-ddump-hi</option> + <indexterm><primary><option>-ddump-hi</option></primary></indexterm> + </term> + <listitem> + <para>Dumps the new interface to standard output.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <option>-ddump-hi-diffs</option> + <indexterm><primary><option>-ddump-hi-diffs</option></primary></indexterm> + </term> + <listitem> + <para>The compiler does not overwrite an existing + <filename>.hi</filename> interface file if the new one is + the same as the old one; this is friendly to + <command>make</command>. When an interface does change, + it is often enlightening to be informed. The + <option>-ddump-hi-diffs</option> option will make GHC run + <command>diff</command> on the old and new + <filename>.hi</filename> files.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <option>-ddump-minimal-imports</option> + <indexterm><primary><option>-ddump-minimal-imports</option></primary></indexterm> + </term> + <listitem> + <para>Dump to the file "M.imports" (where M is the module + being compiled) a "minimal" set of import declarations. + You can safely replace all the import declarations in + "M.hs" with those found in "M.imports". Why would you + want to do that? Because the "minimal" imports (a) import + everything explicitly, by name, and (b) import nothing + that is not required. It can be quite painful to maintain + this property by hand, so this flag is intended to reduce + the labour.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <option>--show-iface</option> <replaceable>file</replaceable> + <indexterm><primary><option>--show-iface</option></primary></indexterm> + </term> + <listitem> + <para>Where <replaceable>file</replaceable> is the name of + an interface file, dumps the contents of that interface in + a human-readable (ish) format.</para> + </listitem> + </varlistentry> + </variablelist> + </sect2> + + <sect2 id="recomp"> + <title>The recompilation checker</title> + + <indexterm><primary>recompilation checker</primary></indexterm> + + <variablelist> + <varlistentry> + <term> + <option>-no-recomp</option> + <indexterm><primary><option>-recomp</option></primary></indexterm> + <indexterm><primary><option>-no-recomp</option></primary></indexterm> + </term> + <listitem> + <para>Turn off recompilation checking (which is on by + default). Recompilation checking normally stops + compilation early, leaving an existing + <filename>.o</filename> file in place, if it can be + determined that the module does not need to be + recompiled.</para> + </listitem> + </varlistentry> + </variablelist> + + <para>In the olden days, GHC compared the newly-generated + <filename>.hi</filename> file with the previous version; if they + were identical, it left the old one alone and didn't change its + modification date. In consequence, importers of a module with + an unchanged output <filename>.hi</filename> file were not + recompiled.</para> + + <para>This doesn't work any more. Suppose module + <literal>C</literal> imports module <literal>B</literal>, and + <literal>B</literal> imports module <literal>A</literal>. So + changes to module <literal>A</literal> might require module + <literal>C</literal> to be recompiled, and hence when + <filename>A.hi</filename> changes we should check whether + <literal>C</literal> should be recompiled. However, the + dependencies of <literal>C</literal> will only list + <literal>B.hi</literal>, not <literal>A.hi</literal>, and some + changes to <literal>A</literal> (changing the definition of a + function that appears in an inlining of a function exported by + <literal>B</literal>, say) may conceivably not change + <filename>B.hi</filename> one jot. So now…</para> + + <para>GHC keeps a version number on each interface file, and on + each type signature within the interface file. It also keeps in + every interface file a list of the version numbers of everything + it used when it last compiled the file. If the source file's + modification date is earlier than the <filename>.o</filename> + file's date (i.e. the source hasn't changed since the file was + last compiled), and the recompilation checking is on, GHC will be + clever. It compares the version numbers on the things it needs + this time with the version numbers on the things it needed last + time (gleaned from the interface file of the module being + compiled); if they are all the same it stops compiling rather + early in the process saying “Compilation IS NOT + required”. What a beautiful sight!</para> + + <para>Patrick Sansom had a workshop paper about how all this is + done (though the details have changed quite a bit). <ulink + url="mailto:sansom@dcs.gla.ac.uk">Ask him</ulink> if you want a + copy.</para> + + </sect2> + + <sect2 id="mutual-recursion"> + <title>How to compile mutually recursive modules</title> + + <indexterm><primary>module system, recursion</primary></indexterm> + <indexterm><primary>recursion, between modules</primary></indexterm> + + <para>GHC supports the compilation of mutually recursive modules. + This section explains how.</para> + + <para>Every cycle in the module import graph must be broken by a <filename>hs-boot</filename> file. + Suppose that modules <filename>A.hs</filename> and <filename>B.hs</filename> are Haskell source files, + thus: +<programlisting> +module A where + import B( TB(..) ) + + newtype TA = MkTA Int + + f :: TB -> TA + f (MkTB x) = MkTA x + +module B where + import {-# SOURCE #-} A( TA(..) ) + + data TB = MkTB !Int + + g :: TA -> TB + g (MkTA x) = MkTB x +</programlisting> +<indexterm><primary><literal>hs-boot</literal> + files</primary></indexterm> <indexterm><primary>importing, + <literal>hi-boot</literal> files</primary></indexterm> +Here <filename>A</filename> imports <filename>B</filename>, but <filename>B</filename> imports +<filename>A</filename> with a <literal>{-# SOURCE #-}</literal> pragma, which breaks the +circular dependency. For every module <filename>A.hs</filename> that is <literal>{-# SOURCE #-}</literal>-imported +in this way there must exist a souce file <literal>A.hs-boot</literal>. This file contains an abbreviated +version of <filename>A.hs</filename>, thus: +<programlisting> +module A where + newtype TA = MkTA Int +</programlisting> +</para> +<para>To compile these three files, issue the following commands: +<programlisting> + ghc -c A.hs-boot -- Poduces A.hi-boot, A.o-boot + ghc -c B.hs -- Consumes A.hi-boot, produces B.hi, B.o + ghc -c A.hs -- Consumes B.hi, produces A.hi, A.o + ghc -o foo A.o B.o -- Linking the program +</programlisting> +</para> +<para>There are several points to note here: +<itemizedlist> +<listitem> + <para>The file <filename>A.hs-boot</filename> is a programmer-written source file. + It must live in the same directory as its parent source file <filename>A.hs</filename>. + Currently, if you use a literate source file <filename>A.lhs</filename> you must + also use a literate boot file, <filename>A.lhs-boot</filename>; and vice versa. + </para></listitem> + +<listitem><para> + A <filename>hs-boot</filename> file is compiled by GHC, just like a <filename>hs</filename> file: +<programlisting> + ghc -c A.hs-boot +</programlisting> +When a hs-boot file <filename>A.hs-boot</filename> + is compiled, it is checked for scope and type errors. + When its parent module <filename>A.hs</filename> is compiled, the two are compared, and + an error is reported if the two are inconsistent. + </para></listitem> + + <listitem> + <para> Just as compiling <filename>A.hs</filename> produces an + interface file <filename>A.hi</filename>, and an object file + <filename>A.o</filename>, so compiling + <filename>A.hs-boot</filename> produces an interface file + <filename>A.hi-boot</filename>, and an pseudo-object file + <filename>A.o-boot</filename>: </para> + + <itemizedlist> + <listitem> + <para>The pseudo-object file <filename>A.o-boot</filename> is + empty (don't link it!), but it is very useful when using a + Makefile, to record when the <filename>A.hi-boot</filename> was + last brought up to date (see <xref + linkend="using-make"/>).</para> + </listitem> + + <listitem> + <para>The <filename>hi-boot</filename> generated by compiling a + <filename>hs-boot</filename> file is in the same + machine-generated binary format as any other GHC-generated + interface file (e.g. <filename>B.hi</filename>). You can + display its contents with <command>ghc + --show-iface</command>. If you specify a directory for + interface files, the <option>-ohidir</option> flag, then that + affects <filename>hi-boot</filename> files + too.</para> + </listitem> + </itemizedlist> + </listitem> + + <listitem><para> If hs-boot files are considered distinct from their parent source + files, and if a <literal>{-# SOURCE #-}</literal> import is considered to refer to the + hs-boot file, then the module import graph must have no cycles. The command + <command>ghc -M</command> will report an error if a cycle is found. + </para></listitem> + + <listitem><para> A module <literal>M</literal> that is + <literal>{-# SOURCE #-}</literal>-imported in a program will usually also be + ordinarily imported elsewhere. If not, <command>ghc --make</command> + automatically adds <literal>M</literal> to the set of moudles it tries to + compile and link, to ensure that <literal>M</literal>'s implementation is included in + the final program. + </para></listitem> +</itemizedlist> +</para> +<para> +A hs-boot file need only contain the bare + minimum of information needed to get the bootstrapping process + started. For example, it doesn't need to contain declarations + for <emphasis>everything</emphasis> that module + <literal>A</literal> exports, only the things required by the + module(s) that import <literal>A</literal> recursively.</para> +<para>A hs-boot file is written in a subset of Haskell: +<itemizedlist> +<listitem><para> The module header (including the export list), and import statements, are exactly as in +Haskell, and so are the scoping rules. + Hence, to mention a non-Prelude type or class, you must import it.</para></listitem> + +<listitem><para> There must be no value declarations, but there can be type signatures for +values. For example: +<programlisting> + double :: Int -> Int +</programlisting> +</para></listitem> +<listitem><para> Fixity declarations are exactly as in Haskell.</para></listitem> +<listitem><para> Type synonym declarations are exactly as in Haskell.</para></listitem> +<listitem><para> A data type declaration can either be given in full, exactly as in Haskell, or it +can be given abstractly, by omitting the '=' sign and everything that follows. For example: +<programlisting> + data T a b +</programlisting> + In a <emphasis>source</emphasis> program + this would declare TA to have no constructors (a GHC extension: see <xref linkend="nullary-types"/>), + but in an hi-boot file it means "I don't know or care what the constructors are". + This is the most common form of data type declaration, because it's easy to get right. + You <emphasis>can</emphasis> also write out the constructors but, if you do so, you must write + it out precisely as in its real definition.</para> + <para> + If you do not write out the constructors, you may need to give a kind + annotation (<xref linkend="sec-kinding"/>), to tell + GHC the kind of the type variable, if it is not "*". (In source files, this is worked out + from the way the type variable is used in the constructors.) For example: +<programlisting> + data R (x :: * -> *) y +</programlisting> +</para></listitem> +<listitem><para> Class declarations is exactly as in Haskell, except that you may not put +default method declarations. You can also omit all the class methods entirely. +</para></listitem> +<listitem><para> Do not include instance declarations. There is a complication to do with +how the dictionary functions are named. It may well work, but it's not a well-tested feature. + </para></listitem> +</itemizedlist> +</para> + </sect2> + + + <sect2 id="using-make"> + <title>Using <command>make</command></title> + + <indexterm><primary><literal>make</literal></primary></indexterm> + + <para>It is reasonably straightforward to set up a + <filename>Makefile</filename> to use with GHC, assuming you name + your source files the same as your modules. Thus:</para> + +<programlisting> +HC = ghc +HC_OPTS = -cpp $(EXTRA_HC_OPTS) + +SRCS = Main.lhs Foo.lhs Bar.lhs +OBJS = Main.o Foo.o Bar.o + +.SUFFIXES : .o .hs .hi .lhs .hc .s + +cool_pgm : $(OBJS) + rm -f $@ + $(HC) -o $@ $(HC_OPTS) $(OBJS) + +# Standard suffix rules +.o.hi: + @: + +.lhs.o: + $(HC) -c $< $(HC_OPTS) + +.hs.o: + $(HC) -c $< $(HC_OPTS) + +.o-boot.hi-boot: + @: + +.lhs-boot.o-boot: + $(HC) -c $< $(HC_OPTS) + +.hs-boot.o-boot: + $(HC) -c $< $(HC_OPTS) + +# Inter-module dependencies +Foo.o Foo.hc Foo.s : Baz.hi # Foo imports Baz +Main.o Main.hc Main.s : Foo.hi Baz.hi # Main imports Foo and Baz +</programlisting> + + <para>(Sophisticated <command>make</command> variants may + achieve some of the above more elegantly. Notably, + <command>gmake</command>'s pattern rules let you write the more + comprehensible:</para> + +<programlisting> +%.o : %.lhs + $(HC) -c $< $(HC_OPTS) +</programlisting> + + <para>What we've shown should work with any + <command>make</command>.)</para> + + <para>Note the cheesy <literal>.o.hi</literal> rule: It records + the dependency of the interface (<filename>.hi</filename>) file + on the source. The rule says a <filename>.hi</filename> file + can be made from a <filename>.o</filename> file by + doing…nothing. Which is true.</para> + <para> Note that the suffix rules are all repeated twice, once + for normal Haskell source files, and once for <filename>hs-boot</filename> + files (see <xref linkend="mutual-recursion"/>).</para> + + <para>Note also the inter-module dependencies at the end of the + Makefile, which take the form + +<programlisting> +Foo.o Foo.hc Foo.s : Baz.hi # Foo imports Baz +</programlisting> + + They tell <command>make</command> that if any of + <literal>Foo.o</literal>, <literal>Foo.hc</literal> or + <literal>Foo.s</literal> have an earlier modification date than + <literal>Baz.hi</literal>, then the out-of-date file must be + brought up to date. To bring it up to date, + <literal>make</literal> looks for a rule to do so; one of the + preceding suffix rules does the job nicely. These dependencies + can be generated automatically by <command>ghc</command>; see + <xref linkend="sec-makefile-dependencies"/></para> + + </sect2> + + <sect2 id="sec-makefile-dependencies"> + <title>Dependency generation</title> + <indexterm><primary>dependencies in Makefiles</primary></indexterm> + <indexterm><primary>Makefile dependencies</primary></indexterm> + + <para>Putting inter-dependencies of the form <literal>Foo.o : + Bar.hi</literal> into your <filename>Makefile</filename> by + hand is rather error-prone. Don't worry, GHC has support for + automatically generating the required dependencies. Add the + following to your <filename>Makefile</filename>:</para> + +<programlisting> +depend : + ghc -M $(HC_OPTS) $(SRCS) +</programlisting> + + <para>Now, before you start compiling, and any time you change + the <literal>imports</literal> in your program, do + <command>make depend</command> before you do <command>make + cool_pgm</command>. The command <command>ghc -M</command> will + append the needed dependencies to your + <filename>Makefile</filename>.</para> + + <para>In general, <command>ghc -M Foo</command> does the following. + For each module <literal>M</literal> in the set + <literal>Foo</literal> plus all its imports (transitively), + it adds to the Makefile: + <itemizedlist> + <listitem><para>A line recording the dependence of the object file on the source file. +<programlisting> +M.o : M.hs +</programlisting> +(or <literal>M.lhs</literal> if that is the filename you used). + </para></listitem> + <listitem><para> For each import declaration <literal>import X</literal> in <literal>M</literal>, + a line recording the dependence of <literal>M</literal> on <literal>X</literal>: +<programlisting> +M.o : X.hi +</programlisting></para></listitem> + <listitem><para> For each import declaration <literal>import {-# SOURCE #-} X</literal> in <literal>M</literal>, + a line recording the dependence of <literal>M</literal> on <literal>X</literal>: +<programlisting> +M.o : X.hi-boot +</programlisting> + (See <xref linkend="mutual-recursion"/> for details of + <literal>hi-boot</literal> style interface files.) + </para></listitem> + </itemizedlist> + If <literal>M</literal> imports multiple modules, then there will + be multiple lines with <filename>M.o</filename> as the + target.</para> + <para>There is no need to list all of the source files as arguments to the <command>ghc -M</command> command; + <command>ghc</command> traces the dependencies, just like <command>ghc --make</command> + (a new feature in GHC 6.4).</para> + + <para>Note that <literal>ghc -M</literal> needs to find a <emphasis>source + file</emphasis> for each module in the dependency graph, so that it can + parse the import declarations and follow dependencies. Any pre-compiled + modules without source files must therefore belong to a + package<footnote><para>This is a change in behaviour relative to 6.2 and + earlier.</para> + </footnote>.</para> + + <para>By default, <command>ghc -M</command> generates all the + dependencies, and then concatenates them onto the end of + <filename>makefile</filename> (or + <filename>Makefile</filename> if <filename>makefile</filename> + doesn't exist) bracketed by the lines "<literal># DO NOT + DELETE: Beginning of Haskell dependencies</literal>" and + "<literal># DO NOT DELETE: End of Haskell + dependencies</literal>". If these lines already exist in the + <filename>makefile</filename>, then the old dependencies are + deleted first.</para> + + <para>Don't forget to use the same <option>-package</option> + options on the <literal>ghc -M</literal> command line as you + would when compiling; this enables the dependency generator to + locate any imported modules that come from packages. The + package modules won't be included in the dependencies + generated, though (but see the + <option>––include-pkg-deps</option> option below).</para> + + <para>The dependency generation phase of GHC can take some + additional options, which you may find useful. For historical + reasons, each option passed to the dependency generator from + the GHC command line must be preceded by + <literal>-optdep</literal>. For example, to pass <literal>-f + .depend</literal> to the dependency generator, you say + +<screen> +ghc -M -optdep-f -optdep.depend ... +</screen> + + The options which affect dependency generation are:</para> + + <variablelist> + <varlistentry> + <term><option>-w</option></term> + <listitem> + <para>Turn off warnings about interface file shadowing.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-v2</option></term> + <listitem> + <para>Print a full list of the module depenencies to stdout. + (This is the standard verbosity flag, so the list will + also be displayed with <option>-v3</option> and + <option>-v4</option>; + <xref linkend ="options-help"/>.)</para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-f</option> <replaceable>file</replaceable></term> + <listitem> + <para>Use <replaceable>file</replaceable> as the makefile, + rather than <filename>makefile</filename> or + <filename>Makefile</filename>. If + <replaceable>file</replaceable> doesn't exist, + <command>mkdependHS</command> creates it. We often use + <option>-f .depend</option> to put the dependencies in + <filename>.depend</filename> and then + <command>include</command> the file + <filename>.depend</filename> into + <filename>Makefile</filename>.</para> + </listitem> + </varlistentry> + +<!-- Retired with the move away from 'mkdependHS'. + <varlistentry> + <term><option>-o <osuf></option></term> + <listitem> + <para>Use <filename>.<osuf></filename> as the + "target file" suffix ( default: <literal>o</literal>). + Multiple <option>-o</option> flags are permitted + (GHC2.05 onwards). Thus "<option>-o hc -o o</option>" + will generate dependencies for <filename>.hc</filename> + and <filename>.o</filename> files.</para> + </listitem> + </varlistentry> +--> + <varlistentry> + <term><option>-s <suf></option></term> + <listitem> + <para>Make extra dependencies that declare that files + with suffix + <filename>.<suf>_<osuf></filename> + depend on interface files with suffix + <filename>.<suf>_hi</filename>, or (for + <literal>{-# SOURCE #-}</literal> + imports) on <filename>.hi-boot</filename>. Multiple + <option>-s</option> flags are permitted. For example, + <option>-o hc -s a -s b</option> will make dependencies + for <filename>.hc</filename> on + <filename>.hi</filename>, + <filename>.a_hc</filename> on + <filename>.a_hi</filename>, and + <filename>.b_hc</filename> on + <filename>.b_hi</filename>. (Useful in + conjunction with NoFib "ways".)</para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>––exclude-module=<file></option></term> + <listitem> + <para>Regard <filename><file></filename> as + "stable"; i.e., exclude it from having dependencies on + it.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-x</option></term> + <listitem> + <para>same as <option>––exclude-module</option></para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>––exclude-directory=<dirs></option></term> + <listitem> + <para>Regard the colon-separated list of directories + <filename><dirs></filename> as containing stable, + don't generate any dependencies on modules + therein.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>––include-module=<file></option></term> + <listitem> + <para>Regard <filename><file></filename> as not + "stable"; i.e., generate dependencies on it (if + any). This option is normally used in conjunction with + the <option>––exclude-directory</option> option.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>––include-pkg-deps</option></term> + <listitem> + <para>Regard modules imported from packages as unstable, + i.e., generate dependencies on any imported package modules + (including <literal>Prelude</literal>, and all other + standard Haskell libraries). Dependencies are not traced + recursively into packages; dependencies are only generated for + home-package modules on external-package modules directly imported + by the home package module. + This option is normally + only used by the various system libraries.</para> + </listitem> + </varlistentry> + </variablelist> + + </sect2> + + <sect2 id="orphan-modules"> + <title>Orphan modules and instance declarations</title> + +<para> Haskell specifies that when compiling module M, any instance +declaration in any module "below" M is visible. (Module A is "below" +M if A is imported directly by M, or if A is below a module that M imports directly.) +In principle, GHC must therefore read the interface files of every module below M, +just in case they contain an instance declaration that matters to M. This would +be a disaster in practice, so GHC tries to be clever. </para> + +<para>In particular, if an instance declaration is in the same module as the definition +of any type or class mentioned in the head of the instance declaration, then +GHC has to visit that interface file anyway. Example:</para> +<programlisting> + module A where + instance C a => D (T a) where ... + data T a = ... +</programlisting> +<para> The instance declaration is only relevant if the type T is in use, and if +so, GHC will have visited A's interface file to find T's definition. </para> + +<para> The only problem comes when a module contains an instance declaration +and GHC has no other reason for visiting the module. Example: +<programlisting> + module Orphan where + instance C a => D (T a) where ... + class C a where ... +</programlisting> +Here, neither D nor T is declared in module Orphan. +We call such modules ``orphan modules'', +defined thus:</para> +<itemizedlist> + <listitem> <para> An <emphasis>orphan module</emphasis> + <indexterm><primary>orphan module</primary></indexterm> + contains at least one <emphasis>orphan instance</emphasis> or at + least one <emphasis>orphan rule</emphasis>.</para> </listitem> + + <listitem><para> An instance declaration in a module M is an <emphasis>orphan instance</emphasis> if + <indexterm><primary>orphan instance</primary></indexterm> + none of the type constructors + or classes mentioned in the instance head (the part after the ``<literal>=></literal>'') are declared + in M.</para> + + <para> Only the instance head counts. In the example above, it is not good enough for C's declaration + to be in module A; it must be the declaration of D or T.</para> + </listitem> + + <listitem><para> A rewrite rule in a module M is an <emphasis>orphan rule</emphasis> + <indexterm><primary>orphan rule</primary></indexterm> + if none of the variables, type constructors, + or classes that are free in the left hand side of the rule are declared in M. + </para> </listitem> + </itemizedlist> + + +<para> GHC identifies orphan modules, and visits the interface file of +every orphan module below the module being compiled. This is usually +wasted work, but there is no avoiding it. You should therefore do +your best to have as few orphan modules as possible. + +</para> + +<para> You can identify an orphan module by looking in its interface +file, <filename>M.hi</filename>, using the +<option>--show-iface</option>. If there is a ``!'' on the first line, +GHC considers it an orphan module. +</para> +</sect2> + + </sect1> + +<!-- Emacs stuff: + ;;; Local Variables: *** + ;;; mode: xml *** + ;;; sgml-parent-document: ("users_guide.xml" "book" "chapter" "sect1") *** + ;;; End: *** + --> diff --git a/docs/users_guide/sooner.xml b/docs/users_guide/sooner.xml new file mode 100644 index 0000000000..1aba5d1af0 --- /dev/null +++ b/docs/users_guide/sooner.xml @@ -0,0 +1,602 @@ +<?xml version="1.0" encoding="iso-8859-1"?> +<chapter id="sooner-faster-quicker"> +<title>Advice on: sooner, faster, smaller, thriftier</title> + +<para>Please advise us of other “helpful hints” that +should go here!</para> + +<sect1 id="sooner"> +<title>Sooner: producing a program more quickly +</title> + +<indexterm><primary>compiling faster</primary></indexterm> +<indexterm><primary>faster compiling</primary></indexterm> + + <variablelist> + <varlistentry> + <term>Don't use <option>-O</option> or (especially) <option>-O2</option>:</term> + <listitem> + <para>By using them, you are telling GHC that you are + willing to suffer longer compilation times for + better-quality code.</para> + + <para>GHC is surprisingly zippy for normal compilations + without <option>-O</option>!</para> + </listitem> + </varlistentry> + + <varlistentry> + <term>Use more memory:</term> + <listitem> + <para>Within reason, more memory for heap space means less + garbage collection for GHC, which means less compilation + time. If you use the <option>-Rghc-timing</option> option, + you'll get a garbage-collector report. (Again, you can use + the cheap-and-nasty <option>+RTS -Sstderr -RTS</option> + option to send the GC stats straight to standard + error.)</para> + + <para>If it says you're using more than 20% of total + time in garbage collecting, then more memory would + help.</para> + + <para>If the heap size is approaching the maximum (64M by + default), and you have lots of memory, try increasing the + maximum with the + <option>-M<size></option><indexterm><primary>-M<size> + option</primary></indexterm> option, e.g.: <command>ghc -c + -O -M1024m Foo.hs</command>.</para> + + <para>Increasing the default allocation area size used by + the compiler's RTS might also help: use the + <option>-A<size></option><indexterm><primary>-A<size> + option</primary></indexterm> option.</para> + + <para>If GHC persists in being a bad memory citizen, please + report it as a bug.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term>Don't use too much memory!</term> + <listitem> + <para>As soon as GHC plus its “fellow citizens” + (other processes on your machine) start using more than the + <emphasis>real memory</emphasis> on your machine, and the + machine starts “thrashing,” <emphasis>the party + is over</emphasis>. Compile times will be worse than + terrible! Use something like the csh-builtin + <command>time</command> command to get a report on how many + page faults you're getting.</para> + + <para>If you don't know what virtual memory, thrashing, and + page faults are, or you don't know the memory configuration + of your machine, <emphasis>don't</emphasis> try to be clever + about memory use: you'll just make your life a misery (and + for other people, too, probably).</para> + </listitem> + </varlistentry> + + <varlistentry> + <term>Try to use local disks when linking:</term> + <listitem> + <para>Because Haskell objects and libraries tend to be + large, it can take many real seconds to slurp the bits + to/from a remote filesystem.</para> + + <para>It would be quite sensible to + <emphasis>compile</emphasis> on a fast machine using + remotely-mounted disks; then <emphasis>link</emphasis> on a + slow machine that had your disks directly mounted.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term>Don't derive/use <function>Read</function> unnecessarily:</term> + <listitem> + <para>It's ugly and slow.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term>GHC compiles some program constructs slowly:</term> + <listitem> + <para>Deeply-nested list comprehensions seem to be one such; + in the past, very large constant tables were bad, + too.</para> + + <para>We'd rather you reported such behaviour as a bug, so + that we can try to correct it.</para> + + <para>The part of the compiler that is occasionally prone to + wandering off for a long time is the strictness analyser. + You can turn this off individually with + <option>-fno-strictness</option>. + <indexterm><primary>-fno-strictness + anti-option</primary></indexterm></para> + + <para>To figure out which part of the compiler is badly + behaved, the + <option>-v2</option><indexterm><primary><option>-v</option></primary> + </indexterm> option is your friend.</para> + + <para>If your module has big wads of constant data, GHC may + produce a huge basic block that will cause the native-code + generator's register allocator to founder. Bring on + <option>-fvia-C</option><indexterm><primary>-fvia-C + option</primary></indexterm> (not that GCC will be that + quick about it, either).</para> + </listitem> + </varlistentry> + + <varlistentry> + <term>Explicit <literal>import</literal> declarations:</term> + <listitem> + <para>Instead of saying <literal>import Foo</literal>, say + <literal>import Foo (...stuff I want...)</literal> You can + get GHC to tell you the minimal set of required imports by + using the <option>-ddump-minimal-imports</option> option + (see <xref linkend="hi-options"/>).</para> + + <para>Truthfully, the reduction on compilation time will be + very small. However, judicious use of + <literal>import</literal> declarations can make a program + easier to understand, so it may be a good idea + anyway.</para> + </listitem> + </varlistentry> + </variablelist> + </sect1> + + <sect1 id="faster"> + <title>Faster: producing a program that runs quicker</title> + + <indexterm><primary>faster programs, how to produce</primary></indexterm> + + <para>The key tool to use in making your Haskell program run + faster are GHC's profiling facilities, described separately in + <xref linkend="profiling"/>. There is <emphasis>no + substitute</emphasis> for finding where your program's time/space + is <emphasis>really</emphasis> going, as opposed to where you + imagine it is going.</para> + + <para>Another point to bear in mind: By far the best way to + improve a program's performance <emphasis>dramatically</emphasis> + is to use better algorithms. Once profiling has thrown the + spotlight on the guilty time-consumer(s), it may be better to + re-think your program than to try all the tweaks listed below.</para> + + <para>Another extremely efficient way to make your program snappy + is to use library code that has been Seriously Tuned By Someone + Else. You <emphasis>might</emphasis> be able to write a better + quicksort than the one in <literal>Data.List</literal>, but it + will take you much longer than typing <literal>import + Data.List</literal>.</para> + + <para>Please report any overly-slow GHC-compiled programs. Since + GHC doesn't have any credible competition in the performance + department these days it's hard to say what overly-slow means, so + just use your judgement! Of course, if a GHC compiled program + runs slower than the same program compiled with NHC or Hugs, then + it's definitely a bug.</para> + + <variablelist> + <varlistentry> + <term>Optimise, using <option>-O</option> or <option>-O2</option>:</term> + <listitem> + <para>This is the most basic way to make your program go + faster. Compilation time will be slower, especially with + <option>-O2</option>.</para> + + <para>At present, <option>-O2</option> is nearly + indistinguishable from <option>-O</option>.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term>Compile via C and crank up GCC:</term> + <listitem> + <para>The native code-generator is designed to be quick, not + mind-bogglingly clever. Better to let GCC have a go, as it + tries much harder on register allocation, etc.</para> + + <para>At the moment, if you turn on <option>-O</option> you + get GCC instead. This may change in the future.</para> + + <para>So, when we want very fast code, we use: <option>-O + -fvia-C</option>.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term>Overloaded functions are not your friend:</term> + <listitem> + <para>Haskell's overloading (using type classes) is elegant, + neat, etc., etc., but it is death to performance if left to + linger in an inner loop. How can you squash it?</para> + + <variablelist> + <varlistentry> + <term>Give explicit type signatures:</term> + <listitem> + <para>Signatures are the basic trick; putting them on + exported, top-level functions is good + software-engineering practice, anyway. (Tip: using + <option>-fwarn-missing-signatures</option><indexterm><primary>-fwarn-missing-signatures + option</primary></indexterm> can help enforce good + signature-practice).</para> + + <para>The automatic specialisation of overloaded + functions (with <option>-O</option>) should take care + of overloaded local and/or unexported functions.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term>Use <literal>SPECIALIZE</literal> pragmas:</term> + <listitem> + <indexterm><primary>SPECIALIZE pragma</primary></indexterm> + <indexterm><primary>overloading, death to</primary></indexterm> + + <para>Specialize the overloading on key functions in + your program. See <xref linkend="specialize-pragma"/> + and <xref linkend="specialize-instance-pragma"/>.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term>“But how do I know where overloading is creeping in?”:</term> + <listitem> + <para>A low-tech way: grep (search) your interface + files for overloaded type signatures. You can view + interface files using the + <option>--show-iface</option> option (see <xref + linkend="hi-options"/>). + +<programlisting> +% ghc --show-iface Foo.hi | egrep '^[a-z].*::.*=>' +</programlisting> +</para> + </listitem> + </varlistentry> + </variablelist> + </listitem> + </varlistentry> + + <varlistentry> + <term>Strict functions are your dear friends:</term> + <listitem> + <para>and, among other things, lazy pattern-matching is your + enemy.</para> + + <para>(If you don't know what a “strict + function” is, please consult a functional-programming + textbook. A sentence or two of explanation here probably + would not do much good.)</para> + + <para>Consider these two code fragments: + +<programlisting> +f (Wibble x y) = ... # strict + +f arg = let { (Wibble x y) = arg } in ... # lazy +</programlisting> + + The former will result in far better code.</para> + + <para>A less contrived example shows the use of + <literal>cases</literal> instead of <literal>lets</literal> + to get stricter code (a good thing): + +<programlisting> +f (Wibble x y) # beautiful but slow + = let + (a1, b1, c1) = unpackFoo x + (a2, b2, c2) = unpackFoo y + in ... + +f (Wibble x y) # ugly, and proud of it + = case (unpackFoo x) of { (a1, b1, c1) -> + case (unpackFoo y) of { (a2, b2, c2) -> + ... + }} +</programlisting> + + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term>GHC loves single-constructor data-types:</term> + <listitem> + <para>It's all the better if a function is strict in a + single-constructor type (a type with only one + data-constructor; for example, tuples are single-constructor + types).</para> + </listitem> + </varlistentry> + + <varlistentry> + <term>Newtypes are better than datatypes:</term> + <listitem> + <para>If your datatype has a single constructor with a + single field, use a <literal>newtype</literal> declaration + instead of a <literal>data</literal> declaration. The + <literal>newtype</literal> will be optimised away in most + cases.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term>“How do I find out a function's strictness?”</term> + <listitem> + <para>Don't guess—look it up.</para> + + <para>Look for your function in the interface file, then for + the third field in the pragma; it should say + <literal>__S <string></literal>. The + <literal><string></literal> gives the strictness of + the function's arguments. <function>L</function> is lazy + (bad), <function>S</function> and <function>E</function> are + strict (good), <function>P</function> is + “primitive” (good), <function>U(...)</function> + is strict and “unpackable” (very good), and + <function>A</function> is absent (very good).</para> + + <para>For an “unpackable” + <function>U(...)</function> argument, the info inside tells + the strictness of its components. So, if the argument is a + pair, and it says <function>U(AU(LSS))</function>, that + means “the first component of the pair isn't used; the + second component is itself unpackable, with three components + (lazy in the first, strict in the second \& + third).”</para> + + <para>If the function isn't exported, just compile with the + extra flag <option>-ddump-simpl</option>; next to the + signature for any binder, it will print the self-same + pragmatic information as would be put in an interface file. + (Besides, Core syntax is fun to look at!)</para> + </listitem> + </varlistentry> + + <varlistentry> + <term>Force key functions to be <literal>INLINE</literal>d (esp. monads):</term> + <listitem> + <para>Placing <literal>INLINE</literal> pragmas on certain + functions that are used a lot can have a dramatic effect. + See <xref linkend="inline-pragma"/>.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term>Explicit <literal>export</literal> list:</term> + <listitem> + <para>If you do not have an explicit export list in a + module, GHC must assume that everything in that module will + be exported. This has various pessimising effects. For + example, if a bit of code is actually + <emphasis>unused</emphasis> (perhaps because of unfolding + effects), GHC will not be able to throw it away, because it + is exported and some other module may be relying on its + existence.</para> + + <para>GHC can be quite a bit more aggressive with pieces of + code if it knows they are not exported.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term>Look at the Core syntax!</term> + <listitem> + <para>(The form in which GHC manipulates your code.) Just + run your compilation with <option>-ddump-simpl</option> + (don't forget the <option>-O</option>).</para> + + <para>If profiling has pointed the finger at particular + functions, look at their Core code. <literal>lets</literal> + are bad, <literal>cases</literal> are good, dictionaries + (<literal>d.<Class>.<Unique></literal>) [or + anything overloading-ish] are bad, nested lambdas are + bad, explicit data constructors are good, primitive + operations (e.g., <literal>eqInt#</literal>) are + good,…</para> + </listitem> + </varlistentry> + + <varlistentry> + <term>Use strictness annotations:</term> + <listitem> + <para>Putting a strictness annotation ('!') on a constructor + field helps in two ways: it adds strictness to the program, + which gives the strictness analyser more to work with, and + it might help to reduce space leaks.</para> + + <para>It can also help in a third way: when used with + <option>-funbox-strict-fields</option> (see <xref + linkend="options-f"/>), a strict field can be unpacked or + unboxed in the constructor, and one or more levels of + indirection may be removed. Unpacking only happens for + single-constructor datatypes (<literal>Int</literal> is a + good candidate, for example).</para> + + <para>Using <option>-funbox-strict-fields</option> is only + really a good idea in conjunction with <option>-O</option>, + because otherwise the extra packing and unpacking won't be + optimised away. In fact, it is possible that + <option>-funbox-strict-fields</option> may worsen + performance even <emphasis>with</emphasis> + <option>-O</option>, but this is unlikely (let us know if it + happens to you).</para> + </listitem> + </varlistentry> + + <varlistentry> + <term>Use unboxed types (a GHC extension):</term> + <listitem> + <para>When you are <emphasis>really</emphasis> desperate for + speed, and you want to get right down to the “raw + bits.” Please see <xref linkend="glasgow-unboxed"/> for + some information about using unboxed types.</para> + + <para>Before resorting to explicit unboxed types, try using + strict constructor fields and + <option>-funbox-strict-fields</option> first (see above). + That way, your code stays portable.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term>Use <literal>foreign import</literal> (a GHC extension) to plug into fast libraries:</term> + <listitem> + <para>This may take real work, but… There exist piles + of massively-tuned library code, and the best thing is not + to compete with it, but link with it.</para> + + <para><xref linkend="ffi"/> describes the foreign function + interface.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term>Don't use <literal>Float</literal>s:</term> + <listitem> + <para>If you're using <literal>Complex</literal>, definitely + use <literal>Complex Double</literal> rather than + <literal>Complex Float</literal> (the former is specialised + heavily, but the latter isn't).</para> + + <para><literal>Floats</literal> (probably 32-bits) are + almost always a bad idea, anyway, unless you Really Know + What You Are Doing. Use <literal>Double</literal>s. + There's rarely a speed disadvantage—modern machines + will use the same floating-point unit for both. With + <literal>Double</literal>s, you are much less likely to hang + yourself with numerical errors.</para> + + <para>One time when <literal>Float</literal> might be a good + idea is if you have a <emphasis>lot</emphasis> of them, say + a giant array of <literal>Float</literal>s. They take up + half the space in the heap compared to + <literal>Doubles</literal>. However, this isn't true on a + 64-bit machine.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term>Use unboxed arrays (<literal>UArray</literal>)</term> + <listitem> + <para>GHC supports arrays of unboxed elements, for several + basic arithmetic element types including + <literal>Int</literal> and <literal>Char</literal>: see the + <literal>Data.Array.Unboxed</literal> library for details. + These arrays are likely to be much faster than using + standard Haskell 98 arrays from the + <literal>Data.Array</literal> library.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term>Use a bigger heap!</term> + <listitem> + <para>If your program's GC stats + (<option>-S</option><indexterm><primary>-S RTS + option</primary></indexterm> RTS option) indicate that it's + doing lots of garbage-collection (say, more than 20% + of execution time), more memory might help—with the + <option>-M<size></option><indexterm><primary>-M<size> + RTS option</primary></indexterm> or + <option>-A<size></option><indexterm><primary>-A<size> + RTS option</primary></indexterm> RTS options (see <xref + linkend="rts-options-gc"/>).</para> + + <para>This is especially important if your program uses a + lot of mutable arrays of pointers or mutable variables + (i.e. <literal>STArray</literal>, + <literal>IOArray</literal>, <literal>STRef</literal> and + <literal>IORef</literal>, but not <literal>UArray</literal>, + <literal>STUArray</literal> or <literal>IOUArray</literal>). + GHC's garbage collector currently scans these objects on + every collection, so your program won't benefit from + generational GC in the normal way if you use lots of + these. Increasing the heap size to reduce the number of + collections will probably help.</para> + </listitem> + </varlistentry> + </variablelist> + +</sect1> + +<sect1 id="smaller"> +<title>Smaller: producing a program that is smaller +</title> + +<para> +<indexterm><primary>smaller programs, how to produce</primary></indexterm> +</para> + +<para> +Decrease the “go-for-it” threshold for unfolding smallish +expressions. Give a +<option>-funfolding-use-threshold0</option><indexterm><primary>-funfolding-use-threshold0 +option</primary></indexterm> option for the extreme case. (“Only unfoldings with +zero cost should proceed.”) Warning: except in certain specialised +cases (like Happy parsers) this is likely to actually +<emphasis>increase</emphasis> the size of your program, because unfolding +generally enables extra simplifying optimisations to be performed. +</para> + +<para> +Avoid <function>Read</function>. +</para> + +<para> +Use <literal>strip</literal> on your executables. +</para> + +</sect1> + +<sect1 id="thriftier"> +<title>Thriftier: producing a program that gobbles less heap space +</title> + +<para> +<indexterm><primary>memory, using less heap</primary></indexterm> +<indexterm><primary>space-leaks, avoiding</primary></indexterm> +<indexterm><primary>heap space, using less</primary></indexterm> +</para> + +<para> +“I think I have a space leak…” Re-run your program +with <option>+RTS -Sstderr</option>, and remove all doubt! (You'll +see the heap usage get bigger and bigger…) +[Hmmm…this might be even easier with the +<option>-G1</option> RTS option; so… <command>./a.out +RTS +-Sstderr -G1</command>...] +<indexterm><primary>-G RTS option</primary></indexterm> +<indexterm><primary>-Sstderr RTS option</primary></indexterm> +</para> + +<para> +Once again, the profiling facilities (<xref linkend="profiling"/>) are +the basic tool for demystifying the space behaviour of your program. +</para> + +<para> +Strict functions are good for space usage, as they are for time, as +discussed in the previous section. Strict functions get right down to +business, rather than filling up the heap with closures (the system's +notes to itself about how to evaluate something, should it eventually +be required). +</para> + +</sect1> + +</chapter> + +<!-- Emacs stuff: + ;;; Local Variables: *** + ;;; mode: xml *** + ;;; sgml-parent-document: ("users_guide.xml" "book" "chapter") *** + ;;; End: *** + --> diff --git a/docs/users_guide/ug-book.xml.in b/docs/users_guide/ug-book.xml.in new file mode 100644 index 0000000000..c5710f1d77 --- /dev/null +++ b/docs/users_guide/ug-book.xml.in @@ -0,0 +1,30 @@ +<?xml version="1.0" encoding="iso-8859-1"?> +<bookinfo> +<title>@ProjectName@ User's Guide, Version @ProjectVersion@</title> +<author><othername>The GHC Team</othername></author> +<address> +<email>glasgow-haskell-{bugs,users}-request@haskell.org</email> +</address> +</bookinfo> + +&license; +&intro; +&installing; +&ghci; +&using; +&prof; +&sooner; +&lang-features; +&ffi-chap; +&wrong; +&utils; +&win32-dll; +&bugs; + +<index/> +<!-- Emacs stuff: + ;;; Local Variables: *** + ;;; mode: xml *** + ;;; sgml-parent-document: ("users_guide.xml" "book") *** + ;;; End: *** + --> diff --git a/docs/users_guide/ug-ent.xml b/docs/users_guide/ug-ent.xml new file mode 100644 index 0000000000..cad75ab499 --- /dev/null +++ b/docs/users_guide/ug-ent.xml @@ -0,0 +1,23 @@ +<!ENTITY ghci SYSTEM "ghci.xml"> +<!ENTITY flags SYSTEM "flags.xml"> +<!ENTITY license SYSTEM "license.xml"> +<!ENTITY intro SYSTEM "intro.xml" > +<!ENTITY relnotes SYSTEM "6.0-notes.xml" > +<!ENTITY installing SYSTEM "installing.xml" > +<!ENTITY using SYSTEM "using.xml" > +<!ENTITY runtime SYSTEM "runtime_control.xml" > +<!ENTITY prof SYSTEM "profiling.xml" > +<!ENTITY debug SYSTEM "debugging.xml" > +<!ENTITY sooner SYSTEM "sooner.xml" > +<!ENTITY lang-features SYSTEM "lang.xml" > +<!ENTITY glasgowexts SYSTEM "glasgow_exts.xml" > +<!ENTITY packages SYSTEM "packages.xml" > +<!ENTITY parallel SYSTEM "parallel.xml" > +<!ENTITY phases SYSTEM "phases.xml" > +<!ENTITY primitives SYSTEM "primitives.xml" > +<!ENTITY separate SYSTEM "separate_compilation.xml" > +<!ENTITY bugs SYSTEM "bugs.xml" > +<!ENTITY wrong SYSTEM "gone_wrong.xml" > +<!ENTITY utils SYSTEM "utils.xml" > +<!ENTITY win32-dll SYSTEM "win32-dlls.xml"> +<!ENTITY ffi-chap SYSTEM "ffi-chap.xml"> diff --git a/docs/users_guide/users_guide.xml b/docs/users_guide/users_guide.xml new file mode 100644 index 0000000000..740e729b72 --- /dev/null +++ b/docs/users_guide/users_guide.xml @@ -0,0 +1,11 @@ +<?xml version="1.0" encoding="iso-8859-1"?> +<!DOCTYPE book PUBLIC "-//OASIS//DTD DocBook XML V4.2//EN" + "http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd" [ +<!ENTITY % ug-ent SYSTEM "ug-ent.xml"> +%ug-ent; +<!ENTITY ug-book SYSTEM "ug-book.xml"> +]> + +<book id="users-guide"> +&ug-book; +</book> diff --git a/docs/users_guide/using.xml b/docs/users_guide/using.xml new file mode 100644 index 0000000000..8cbcd35fca --- /dev/null +++ b/docs/users_guide/using.xml @@ -0,0 +1,1976 @@ +<?xml version="1.0" encoding="iso-8859-1"?> +<chapter id="using-ghc"> + <title>Using GHC</title> + + <indexterm><primary>GHC, using</primary></indexterm> + <indexterm><primary>using GHC</primary></indexterm> + + <sect1> + <title>Options overview</title> + + <para>GHC's behaviour is controlled by + <firstterm>options</firstterm>, which for historical reasons are + also sometimes referred to as command-line flags or arguments. + Options can be specified in three ways:</para> + + <sect2> + <title>command-line arguments</title> + + <indexterm><primary>structure, command-line</primary></indexterm> + <indexterm><primary>command-line</primary><secondary>arguments</secondary></indexterm> + <indexterm><primary>arguments</primary><secondary>command-line</secondary></indexterm> + + <para>An invocation of GHC takes the following form:</para> + +<screen> +ghc [argument...] +</screen> + + <para>command-line arguments are either options or file names.</para> + + <para>command-line options begin with <literal>-</literal>. + They may <emphasis>not</emphasis> be grouped: + <option>-vO</option> is different from <option>-v -O</option>. + Options need not precede filenames: e.g., <literal>ghc *.o -o + foo</literal>. All options are processed and then applied to + all files; you cannot, for example, invoke <literal>ghc -c -O1 + Foo.hs -O2 Bar.hs</literal> to apply different optimisation + levels to the files <filename>Foo.hs</filename> and + <filename>Bar.hs</filename>.</para> + </sect2> + + <sect2 id="source-file-options"> + <title>command line options in source files</title> + + <indexterm><primary>source-file options</primary></indexterm> + + <para>Sometimes it is useful to make the connection between a + source file and the command-line options it requires quite + tight. For instance, if a Haskell source file uses GHC + extensions, it will always need to be compiled with the + <option>-fglasgow-exts</option> option. Rather than maintaining + the list of per-file options in a <filename>Makefile</filename>, + it is possible to do this directly in the source file using the + <literal>OPTIONS_GHC</literal> pragma <indexterm><primary>OPTIONS_GHC + pragma</primary></indexterm>:</para> + +<programlisting> +{-# OPTIONS_GHC -fglasgow-exts #-} +module X where +... +</programlisting> + + <para><literal>OPTIONS_GHC</literal> pragmas are only looked for at + the top of your source files, upto the first + (non-literate,non-empty) line not containing + <literal>OPTIONS_GHC</literal>. Multiple <literal>OPTIONS_GHC</literal> + pragmas are recognised. Do not put comments before, or on the same line + as, the <literal>OPTIONS_GHC</literal> pragma.</para> + + <para>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 the compiler + maintains internally, so you'll be desperately disappointed if + you try to glob etc. inside <literal>OPTIONS_GHC</literal>.</para> + + <para>NOTE: the contents of OPTIONS_GHC are prepended to the + command-line options, so you <emphasis>do</emphasis> have the + ability to override OPTIONS_GHC settings via the command + line.</para> + + <para>It is not recommended to move all the contents of your + Makefiles into your source files, but in some circumstances, the + <literal>OPTIONS_GHC</literal> pragma is the Right Thing. (If you + use <option>-keep-hc-file-too</option> and have OPTION flags in + your module, the OPTIONS_GHC will get put into the generated .hc + file).</para> + </sect2> + + <sect2> + <title>Setting options in GHCi</title> + + <para>Options may also be modified from within GHCi, using the + <literal>:set</literal> command. See <xref linkend="ghci-set"/> + for more details.</para> + </sect2> + </sect1> + + <sect1 id="static-dynamic-flags"> + <title>Static, Dynamic, and Mode options</title> + <indexterm><primary>static</primary><secondary>options</secondary> + </indexterm> + <indexterm><primary>dynamic</primary><secondary>options</secondary> + </indexterm> + <indexterm><primary>mode</primary><secondary>options</secondary> + </indexterm> + + <para>Each of GHC's command line options is classified as either + <firstterm>static</firstterm> or <firstterm>dynamic</firstterm> or + <firstterm>mode</firstterm>:</para> + + <variablelist> + <varlistentry> + <term>Mode flags</term> + <listitem> + <para>For example, <option>--make</option> or <option>-E</option>. + There may be only a single mode flag on the command line. The + available modes are listed in <xref linkend="modes"/>.</para> + </listitem> + </varlistentry> + <varlistentry> + <term>Dynamic Flags</term> + <listitem> + <para>Most non-mode flags fall into this category. A dynamic flag + may be used on the command line, in a + <literal>GHC_OPTIONS</literal> pragma in a source file, or set + using <literal>:set</literal> in GHCi.</para> + </listitem> + </varlistentry> + <varlistentry> + <term>Static Flags</term> + <listitem> + <para>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.</para> + </listitem> + </varlistentry> + </variablelist> + + <para>The flag reference tables (<xref + linkend="flag-reference"/>) lists the status of each flag.</para> + </sect1> + + <sect1 id="file-suffixes"> + <title>Meaningful file suffixes</title> + + <indexterm><primary>suffixes, file</primary></indexterm> + <indexterm><primary>file suffixes for GHC</primary></indexterm> + + <para>File names with “meaningful” suffixes (e.g., + <filename>.lhs</filename> or <filename>.o</filename>) cause the + “right thing” to happen to those files.</para> + + <variablelist> + + <varlistentry> + <term><filename>.hs</filename></term> + <listitem> + <para>A Haskell module.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <filename>.lhs</filename> + <indexterm><primary><literal>lhs</literal> suffix</primary></indexterm> + </term> + <listitem> + <para>A “literate Haskell” module.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term><filename>.hi</filename></term> + <listitem> + <para>A Haskell interface file, probably + compiler-generated.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term><filename>.hc</filename></term> + <listitem> + <para>Intermediate C file produced by the Haskell + compiler.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term><filename>.c</filename></term> + <listitem> + <para>A C file not produced by the Haskell + compiler.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term><filename>.s</filename></term> + <listitem> + <para>An assembly-language source file, usually produced by + the compiler.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term><filename>.o</filename></term> + <listitem> + <para>An object file, produced by an assembler.</para> + </listitem> + </varlistentry> + </variablelist> + + <para>Files with other suffixes (or without suffixes) are passed + straight to the linker.</para> + + </sect1> + + <sect1 id="modes"> + <title>Modes of operation</title> + + <para>GHC's behaviour is firstly controlled by a mode flag. Only + one of these flags may be given, but it does not necessarily need + to be the first option on the command-line. The available modes + are:</para> + + <variablelist> + <varlistentry> + <term> + <cmdsynopsis><command>ghc</command> + <arg choice='plain'>––interactive</arg> + </cmdsynopsis> + <indexterm><primary>interactive mode</primary></indexterm> + <indexterm><primary>ghci</primary></indexterm> + </term> + <listitem> + <para>Interactive mode, which is also available as + <command>ghci</command>. Interactive mode is described in + more detail in <xref linkend="ghci"/>.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <cmdsynopsis><command>ghc</command> + <arg choice='plain'>––make</arg> + </cmdsynopsis> + <indexterm><primary>make mode</primary></indexterm> + <indexterm><primary><option>––make</option></primary></indexterm> + </term> + <listitem> + <para>In this mode, GHC will build a multi-module Haskell + program automatically, figuring out dependencies for itself. + If you have a straightforward Haskell program, this is + likely to be much easier, and faster, than using + <command>make</command>. Make mode is described in <xref + linkend="make-mode"/>.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <cmdsynopsis><command>ghc</command> + <arg choice='plain'>–e</arg> <arg choice='plain'><replaceable>expr</replaceable></arg> + </cmdsynopsis> + <indexterm><primary>eval mode</primary></indexterm> + </term> + <listitem> + <para>Expression-evaluation mode. This is very similar to + interactive mode, except that there is a single expression + to evaluate (<replaceable>expr</replaceable>) which is given + on the command line. See <xref linkend="eval-mode"/> for + more details.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <cmdsynopsis> + <command>ghc</command> + <group> + <arg>-E</arg> + <arg>-C</arg> + <arg>-S</arg> + <arg>-c</arg> + </group> + </cmdsynopsis> + <indexterm><primary><option>-E</option></primary></indexterm> + <indexterm><primary><option>-C</option></primary></indexterm> + <indexterm><primary><option>-S</option></primary></indexterm> + <indexterm><primary><option>-c</option></primary></indexterm> + </term> + <listitem> + <para>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. This mode also applies if + there is no other mode flag specified on the command line, + in which case it means that the specified files should be + compiled and then linked to form a program. See <xref + linkend="options-order"/>.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <cmdsynopsis> + <command>ghc</command> + <arg choice='plain'>–M</arg> + </cmdsynopsis> + <indexterm><primary>dependency-generation mode</primary></indexterm> + </term> + <listitem> + <para>Dependency-generation mode. In this mode, GHC can be + used to generate dependency information suitable for use in + a <literal>Makefile</literal>. See <xref + linkend="sec-makefile-dependencies"/>.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <cmdsynopsis> + <command>ghc</command> + <arg choice='plain'>––mk-dll</arg> + </cmdsynopsis> + <indexterm><primary>dependency-generation mode</primary></indexterm> + </term> + <listitem> + <para>DLL-creation mode (Windows only). See <xref + linkend="win32-dlls-create"/>.</para> + </listitem> + </varlistentry> + </variablelist> + + <sect2 id="make-mode"> + <title>Using <command>ghc</command> <option>––make</option></title> + <indexterm><primary><option>––make</option></primary></indexterm> + <indexterm><primary>separate compilation</primary></indexterm> + + <para>When given the <option>––make</option> option, + GHC will build a multi-module Haskell program by following + dependencies from a single root module (usually + <literal>Main</literal>). For example, if your + <literal>Main</literal> module is in a file called + <filename>Main.hs</filename>, you could compile and link the + program like this:</para> + +<screen> +ghc ––make Main.hs +</screen> + + <para>The command line may contain any number of source file + names or module names; GHC will figure out all the modules in + the program by following the imports from these initial modules. + It will then attempt to compile each module which is out of + date, and finally if there is a <literal>Main</literal> module, + the program will also be linked into an executable.</para> + + <para>The main advantages to using <literal>ghc + ––make</literal> over traditional + <literal>Makefile</literal>s are:</para> + + <itemizedlist> + <listitem> + <para>GHC doesn't have to be restarted for each compilation, + which means it can cache information between compilations. + Compiling a multi-module program with <literal>ghc + ––make</literal> can be up to twice as fast as + running <literal>ghc</literal> individually on each source + file.</para> + </listitem> + <listitem> + <para>You don't have to write a <literal>Makefile</literal>.</para> + <indexterm><primary><literal>Makefile</literal>s</primary><secondary>avoiding</secondary></indexterm> + </listitem> + <listitem> + <para>GHC re-calculates the dependencies each time it is + invoked, so the dependencies never get out of sync with the + source.</para> + </listitem> + </itemizedlist> + + <para>Any of the command-line options described in the rest of + this chapter can be used with + <option>––make</option>, but note that any options + you give on the command line will apply to all the source files + compiled, so if you want any options to apply to a single source + file only, you'll need to use an <literal>OPTIONS_GHC</literal> + pragma (see <xref linkend="source-file-options"/>).</para> + + <para>If the program needs to be linked with additional objects + (say, some auxiliary C code), then the object files can be + given on the command line and GHC will include them when linking + the executable.</para> + + <para>Note that GHC can only follow dependencies if it has the + source file available, so if your program includes a module for + which there is no source file, even if you have an object and an + interface file for the module, then GHC will complain. The + exception to this rule is for package modules, which may or may + not have source files.</para> + + <para>The source files for the program don't all need to be in + the same directory; the <option>-i</option> option can be used + to add directories to the search path (see <xref + linkend="search-path"/>).</para> + </sect2> + + <sect2 id="eval-mode"> + <title>Expression evaluation mode</title> + + <para>This mode is very similar to interactive mode, except that + there is a single expression to evaluate which is specified on + the command line as an argument to the <option>-e</option> + option:</para> + +<screen> +ghc -e <replaceable>expr</replaceable> +</screen> + + <para>Haskell source files may be named on the command line, and + they will be loaded exactly as in interactive mode. The + expression is evaluated in the context of the loaded + modules.</para> + + <para>For example, to load and run a Haskell program containing + a module <literal>Main</literal>, we might say</para> + +<screen> +ghc -e Main.main Main.hs +</screen> + + <para>or we can just use this mode to evaluate expressions in + the context of the <literal>Prelude</literal>:</para> + +<screen> +$ ghc -e "interact (unlines.map reverse.lines)" +hello +olleh +</screen> + </sect2> + + <sect2 id="options-order"> + <title>Batch compiler mode</title> + + <para>In <emphasis>batch mode</emphasis>, GHC will compile one or more source files + given on the command line.</para> + + <para>The first phase to run is determined by each input-file + suffix, and the last phase is determined by a flag. If no + relevant flag is present, then go all the way through linking. + This table summarises:</para> + + <informaltable> + <tgroup cols="4"> + <colspec align="left"/> + <colspec align="left"/> + <colspec align="left"/> + <colspec align="left"/> + + <thead> + <row> + <entry>Phase of the compilation system</entry> + <entry>Suffix saying “start here”</entry> + <entry>Flag saying “stop after”</entry> + <entry>(suffix of) output file</entry> + </row> + </thead> + <tbody> + <row> + <entry>literate pre-processor</entry> + <entry><literal>.lhs</literal></entry> + <entry>-</entry> + <entry><literal>.hs</literal></entry> + </row> + + <row> + <entry>C pre-processor (opt.) </entry> + <entry><literal>.hs</literal> (with + <option>-cpp</option>)</entry> + <entry><option>-E</option></entry> + <entry><literal>.hspp</literal></entry> + </row> + + <row> + <entry>Haskell compiler</entry> + <entry><literal>.hs</literal></entry> + <entry><option>-C</option>, <option>-S</option></entry> + <entry><literal>.hc</literal>, <literal>.s</literal></entry> + </row> + + <row> + <entry>C compiler (opt.)</entry> + <entry><literal>.hc</literal> or <literal>.c</literal></entry> + <entry><option>-S</option></entry> + <entry><literal>.s</literal></entry> + </row> + + <row> + <entry>assembler</entry> + <entry><literal>.s</literal></entry> + <entry><option>-c</option></entry> + <entry><literal>.o</literal></entry> + </row> + + <row> + <entry>linker</entry> + <entry><replaceable>other</replaceable></entry> + <entry>-</entry> + <entry><filename>a.out</filename></entry> + </row> + </tbody> + </tgroup> + </informaltable> + + <indexterm><primary><option>-C</option></primary></indexterm> + <indexterm><primary><option>-E</option></primary></indexterm> + <indexterm><primary><option>-S</option></primary></indexterm> + <indexterm><primary><option>-c</option></primary></indexterm> + + <para>Thus, a common invocation would be: </para> + +<screen> +ghc -c Foo.hs</screen> + + <para>to compile the Haskell source file + <filename>Foo.hs</filename> to an object file + <filename>Foo.o</filename>.</para> + + <para>Note: What the Haskell compiler proper produces depends on + whether a native-code generator<indexterm><primary>native-code + generator</primary></indexterm> is used (producing assembly + language) or not (producing C). See <xref + linkend="options-codegen"/> for more details.</para> + + <para>Note: C pre-processing is optional, the + <option>-cpp</option><indexterm><primary><option>-cpp</option></primary></indexterm> + flag turns it on. See <xref linkend="c-pre-processor"/> for more + details.</para> + + <para>Note: The option <option>-E</option><indexterm><primary>-E + option</primary></indexterm> runs just the pre-processing passes + of the compiler, dumping the result in a file. Note that this + differs from the previous behaviour of dumping the file to + standard output.</para> + + <sect3 id="overriding-suffixes"> + <title>Overriding the default behaviour for a file</title> + + <para>As described above, the way in which a file is processed by GHC + depends on its suffix. This behaviour can be overriden using the + <option>-x</option> option:</para> + + <variablelist> + <varlistentry> + <term><option>-x</option> <replaceable>suffix</replaceable> + <indexterm><primary><option>-x</option></primary> + </indexterm></term> + <listitem> + <para>Causes all files following this option on the command + line to be processed as if they had the suffix + <replaceable>suffix</replaceable>. For example, to compile a + Haskell module in the file <literal>M.my-hs</literal>, + use <literal>ghc -c -x hs M.my-hs</literal>.</para> + </listitem> + </varlistentry> + </variablelist> + </sect3> + + </sect2> + </sect1> + + <sect1 id="options-help"> + <title>Help and verbosity options</title> + + <indexterm><primary>help options</primary></indexterm> + <indexterm><primary>verbosity options</primary></indexterm> + + <variablelist> + <varlistentry> + <term> + <option>––help</option> + <indexterm><primary><option>––help</option></primary></indexterm> + </term> + <term> + <option>-?</option> + <indexterm><primary><option>-?</option></primary></indexterm> + </term> + <listitem> + <para>Cause GHC to spew a long usage message to standard + output and then exit.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <option>-v</option> + <indexterm><primary><option>-v</option></primary></indexterm> + </term> + <listitem> + <para>The <option>-v</option> option makes GHC + <emphasis>verbose</emphasis>: it reports its version number + and shows (on stderr) exactly how it invokes each phase of + the compilation system. Moreover, it passes the + <option>-v</option> flag to most phases; each reports its + version number (and possibly some other information).</para> + + <para>Please, oh please, use the <option>-v</option> option + when reporting bugs! Knowing that you ran the right bits in + the right order is always the first thing we want to + verify.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <option>-v</option><replaceable>n</replaceable> + <indexterm><primary><option>-v</option></primary></indexterm> + </term> + <listitem> + <para>To provide more control over the compiler's verbosity, + the <option>-v</option> flag takes an optional numeric + argument. Specifying <option>-v</option> on its own is + equivalent to <option>-v3</option>, and the other levels + have the following meanings:</para> + + <variablelist> + <varlistentry> + <term><option>-v0</option></term> + <listitem> + <para>Disable all non-essential messages (this is the + default).</para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-v1</option></term> + <listitem> + <para>Minimal verbosity: print one line per + compilation (this is the default when + <option>––make</option> or + <option>––interactive</option> is on).</para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-v2</option></term> + <listitem> + <para>Print the name of each compilation phase as it + is executed. (equivalent to + <option>-dshow-passes</option>).</para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-v3</option></term> + <listitem> + <para>The same as <option>-v2</option>, except that in + addition the full command line (if appropriate) for + each compilation phase is also printed.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-v4</option></term> + <listitem> + <para>The same as <option>-v3</option> except that the + intermediate program representation after each + compilation phase is also printed (excluding + preprocessed and C/assembly files).</para> + </listitem> + </varlistentry> + </variablelist> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <option>-V</option> + <indexterm><primary><option>-V</option></primary></indexterm> + </term> + <term> + <option>––version</option> + <indexterm><primary><option>––version</option></primary></indexterm> + </term> + <listitem> + <para>Print a one-line string including GHC's version number.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <option>––numeric-version</option> + <indexterm><primary><option>––numeric-version</option></primary></indexterm> + </term> + <listitem> + <para>Print GHC's numeric version number only.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <option>––print-libdir</option> + <indexterm><primary><option>––print-libdir</option></primary></indexterm> + </term> + <listitem> + <para>Print the path to GHC's library directory. This is + the top of the directory tree containing GHC's libraries, + interfaces, and include files (usually something like + <literal>/usr/local/lib/ghc-5.04</literal> on Unix). This + is the value of + <literal>$libdir</literal><indexterm><primary><literal>libdir</literal></primary> + </indexterm>in the package configuration file (see <xref + linkend="packages"/>).</para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-ferror-spans</option> + <indexterm><primary><option>-ferror-spans</option></primary> + </indexterm> + </term> + <listitem> + <para>Causes GHC to emit the full source span of the + syntactic entity relating to an error message. Normally, GHC + emits the source location of the start of the syntactic + entity only.</para> + + <para>For example:</para> + +<screen>test.hs:3:6: parse error on input `where'</screen> + + <para>becomes:</para> + +<screen>test296.hs:3:6-10: parse error on input `where'</screen> + + <para>And multi-line spans are possible too:</para> + +<screen>test.hs:(5,4)-(6,7): + Conflicting definitions for `a' + Bound at: test.hs:5:4 + test.hs:6:7 + In the binding group for: a, b, a</screen> + + <para>Note that line numbers start counting at one, but + column numbers start at zero. This choice was made to + follow existing convention (i.e. this is how Emacs does + it).</para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-Rghc-timing</option> + <indexterm><primary><option>-Rghc-timing</option></primary></indexterm> + </term> + <listitem> + <para>Prints a one-line summary of timing statistics for the + GHC run. This option is equivalent to + <literal>+RTS -tstderr</literal>, see <xref + linkend="rts-options-gc" />. + </para> + </listitem> + </varlistentry> + </variablelist> + </sect1> + + &separate; + + <sect1 id="options-sanity"> + <title>Warnings and sanity-checking</title> + + <indexterm><primary>sanity-checking options</primary></indexterm> + <indexterm><primary>warnings</primary></indexterm> + + + <para>GHC has a number of options that select which types of + non-fatal error messages, otherwise known as warnings, can be + generated during compilation. By default, you get a standard set + of warnings which are generally likely to indicate bugs in your + program. These are: + <option>-fwarn-overlapping-patterns</option>, + <option>-fwarn-deprecations</option>, + <option>-fwarn-duplicate-exports</option>, + <option>-fwarn-missing-fields</option>, and + <option>-fwarn-missing-methods</option>. The following flags are + simple ways to select standard “packages” of warnings: + </para> + + <variablelist> + + <varlistentry> + <term><option>-W</option>:</term> + <listitem> + <indexterm><primary>-W option</primary></indexterm> + <para>Provides the standard warnings plus + <option>-fwarn-incomplete-patterns</option>, + <option>-fwarn-unused-matches</option>, + <option>-fwarn-unused-imports</option>, + <option>-fwarn-misc</option>, and + <option>-fwarn-unused-binds</option>.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-w</option>:</term> + <listitem> + <indexterm><primary><option>-w</option></primary></indexterm> + <para>Turns off all warnings, including the standard ones.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-Wall</option>:</term> + <listitem> + <indexterm><primary><option>-Wall</option></primary></indexterm> + <para>Turns on all warning options.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-Werror</option>:</term> + <listitem> + <indexterm><primary><option>-Werror</option></primary></indexterm> + <para>Makes any warning into a fatal error. Useful so that you don't + miss warnings when doing batch compilation. </para> + </listitem> + </varlistentry> + + </variablelist> + + <para>The full set of warning options is described below. To turn + off any warning, simply give the corresponding + <option>-fno-warn-...</option> option on the command line.</para> + + <variablelist> + + <varlistentry> + <term><option>-fwarn-deprecations</option>:</term> + <listitem> + <indexterm><primary><option>-fwarn-deprecations</option></primary> + </indexterm> + <indexterm><primary>deprecations</primary></indexterm> + <para>Causes a warning to be emitted when a deprecated + function or type is used. Entities can be marked as + deprecated using a pragma, see <xref + linkend="deprecated-pragma"/>.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-fwarn-duplicate-exports</option>:</term> + <listitem> + <indexterm><primary><option>-fwarn-duplicate-exports</option></primary></indexterm> + <indexterm><primary>duplicate exports, warning</primary></indexterm> + <indexterm><primary>export lists, duplicates</primary></indexterm> + + <para>Have the compiler warn about duplicate entries in + export lists. This is useful information if you maintain + large export lists, and want to avoid the continued export + of a definition after you've deleted (one) mention of it in + the export list.</para> + + <para>This option is on by default.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-fwarn-hi-shadowing</option>:</term> + <listitem> + <indexterm><primary><option>-fwarn-hi-shadowing</option></primary></indexterm> + <indexterm><primary>shadowing</primary> + <secondary>interface files</secondary></indexterm> + + <para>Causes the compiler to emit a warning when a module or + interface file in the current directory is shadowing one + with the same module name in a library or other + directory.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-fwarn-incomplete-patterns</option>:</term> + <listitem> + <indexterm><primary><option>-fwarn-incomplete-patterns</option></primary></indexterm> + <indexterm><primary>incomplete patterns, warning</primary></indexterm> + <indexterm><primary>patterns, incomplete</primary></indexterm> + + <para>Similarly for incomplete patterns, the function + <function>g</function> below will fail when applied to + non-empty lists, so the compiler will emit a warning about + this when <option>-fwarn-incomplete-patterns</option> is + enabled.</para> + +<programlisting> +g [] = 2 +</programlisting> + + <para>This option isn't enabled be default because it can be + a bit noisy, and it doesn't always indicate a bug in the + program. However, it's generally considered good practice + to cover all the cases in your functions.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-fwarn-incomplete-record-updates</option>:</term> + <listitem> + <indexterm><primary><option>-fwarn-incomplete-record-updates</option></primary></indexterm> + <indexterm><primary>incomplete record updates, warning</primary></indexterm> + <indexterm><primary>record updates, incomplete</primary></indexterm> + + <para>The function + <function>f</function> below will fail when applied to + <literal>Bar</literal>, so the compiler will emit a warning about + this when <option>-fwarn-incomplete-record-updates</option> is + enabled.</para> + +<programlisting> +data Foo = Foo { x :: Int } + | Bar + +f :: Foo -> Foo +f foo = foo { x = 6 } +</programlisting> + + <para>This option isn't enabled be default because it can be + very noisy, and it often doesn't indicate a bug in the + program.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <option>-fwarn-misc</option>: + <indexterm><primary><option>-fwarn-misc</option></primary></indexterm> + </term> + <listitem> + <para>Turns on warnings for various harmless but untidy + things. This currently includes: importing a type with + <literal>(..)</literal> when the export is abstract, and + listing duplicate class assertions in a qualified type.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <option>-fwarn-missing-fields</option>: + <indexterm><primary><option>-fwarn-missing-fields</option></primary></indexterm> + <indexterm><primary>missing fields, warning</primary></indexterm> + <indexterm><primary>fields, missing</primary></indexterm> + </term> + <listitem> + + <para>This option is on by default, and warns you whenever + the construction of a labelled field constructor isn't + complete, missing initializers for one or more fields. While + not an error (the missing fields are initialised with + bottoms), it is often an indication of a programmer error.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-fwarn-missing-methods</option>:</term> + <listitem> + <indexterm><primary><option>-fwarn-missing-methods</option></primary></indexterm> + <indexterm><primary>missing methods, warning</primary></indexterm> + <indexterm><primary>methods, missing</primary></indexterm> + + <para>This option is on by default, and warns you whenever + an instance declaration is missing one or more methods, and + the corresponding class declaration has no default + declaration for them.</para> + <para>The warning is suppressed if the method name + begins with an underscore. Here's an example where this is useful: + <programlisting> + class C a where + _simpleFn :: a -> String + complexFn :: a -> a -> String + complexFn x y = ... _simpleFn ... + </programlisting> + The idea is that: (a) users of the class will only call <literal>complexFn</literal>; + never <literal>_simpleFn</literal>; and (b) + instance declarations can define either <literal>complexFn</literal> or <literal>_simpleFn</literal>. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-fwarn-missing-signatures</option>:</term> + <listitem> + <indexterm><primary><option>-fwarn-missing-signatures</option></primary></indexterm> + <indexterm><primary>type signatures, missing</primary></indexterm> + + <para>If you would like GHC to check that every top-level + function/value has a type signature, use the + <option>-fwarn-missing-signatures</option> option. This + option is off by default.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-fwarn-name-shadowing</option>:</term> + <listitem> + <indexterm><primary><option>-fwarn-name-shadowing</option></primary></indexterm> + <indexterm><primary>shadowing, warning</primary></indexterm> + + <para>This option causes a warning to be emitted whenever an + inner-scope value has the same name as an outer-scope value, + i.e. the inner value shadows the outer one. This can catch + typographical errors that turn into hard-to-find bugs, e.g., + in the inadvertent cyclic definition <literal>let x = ... x + ... in</literal>.</para> + + <para>Consequently, this option does + <emphasis>will</emphasis> complain about cyclic recursive + definitions.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-fwarn-orphans</option>:</term> + <listitem> + <indexterm><primary><option>-fwarn-orphans</option></primary></indexterm> + <indexterm><primary>orphan instances, warning</primary></indexterm> + <indexterm><primary>orphan rules, warning</primary></indexterm> + + <para>This option causes a warning to be emitted whenever the + module contains an "orphan" instance declaration or rewrite rule. + An instance declartion is an orphan if it appears in a module in + which neither the class nor the type being instanced are declared + in the same module. A rule is an orphan if it is a rule for a + function declared in another module. A module containing any + orphans is called an orphan module.</para> + <para>The trouble with orphans is that GHC must pro-actively read the interface + files for all orphan modules, just in case their instances or rules + play a role, whether or not the module's interface would otherwise + be of any use. Other things being equal, avoid orphan modules.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <option>-fwarn-overlapping-patterns</option>: + <indexterm><primary><option>-fwarn-overlapping-patterns</option></primary></indexterm> + <indexterm><primary>overlapping patterns, warning</primary></indexterm> + <indexterm><primary>patterns, overlapping</primary></indexterm> + </term> + <listitem> + <para>By default, the compiler will warn you if a set of + patterns are overlapping, i.e.,</para> + +<programlisting> +f :: String -> Int +f [] = 0 +f (_:xs) = 1 +f "2" = 2 +</programlisting> + + <para>where the last pattern match in <function>f</function> + won't ever be reached, as the second pattern overlaps + it. More often than not, redundant patterns is a programmer + mistake/error, so this option is enabled by default.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-fwarn-simple-patterns</option>:</term> + <listitem> + <indexterm><primary><option>-fwarn-simple-patterns</option></primary> + </indexterm> + <para>Causes the compiler to warn about lambda-bound + patterns that can fail, eg. <literal>\(x:xs)->...</literal>. + Normally, these aren't treated as incomplete patterns by + <option>-fwarn-incomplete-patterns</option>.</para> + <para>``Lambda-bound patterns'' includes all places where there is a single pattern, + including list comprehensions and do-notation. In these cases, a pattern-match + failure is quite legitimate, and triggers filtering (list comprehensions) or + the monad <literal>fail</literal> operation (monads). For example: + <programlisting> + f :: [Maybe a] -> [a] + f xs = [y | Just y <- xs] + </programlisting> + Switching on <option>-fwarn-simple-patterns</option> will elicit warnings about + these probably-innocent cases, which is why the flag is off by default. </para> + <para> The <literal>deriving( Read )</literal> mechanism produces monadic code with + pattern matches, so you will also get misleading warnings about the compiler-generated + code. (This is arguably a Bad Thing, but it's awkward to fix.)</para> + + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-fwarn-type-defaults</option>:</term> + <listitem> + <indexterm><primary><option>-fwarn-type-defaults</option></primary></indexterm> + <indexterm><primary>defaulting mechanism, warning</primary></indexterm> + <para>Have the compiler warn/inform you where in your source + the Haskell defaulting mechanism for numeric types kicks + in. This is useful information when converting code from a + context that assumed one default into one with another, + e.g., the `default default' for Haskell 1.4 caused the + otherwise unconstrained value <constant>1</constant> to be + given the type <literal>Int</literal>, whereas Haskell 98 + defaults it to <literal>Integer</literal>. This may lead to + differences in performance and behaviour, hence the + usefulness of being non-silent about this.</para> + + <para>This warning is off by default.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-fwarn-unused-binds</option>:</term> + <listitem> + <indexterm><primary><option>-fwarn-unused-binds</option></primary></indexterm> + <indexterm><primary>unused binds, warning</primary></indexterm> + <indexterm><primary>binds, unused</primary></indexterm> + <para>Report any function definitions (and local bindings) + which are unused. For top-level functions, the warning is + only given if the binding is not exported.</para> + <para>A definition is regarded as "used" if (a) it is exported, or (b) it is + mentioned in the right hand side of another definition that is used, or (c) the + function it defines begins with an underscore. The last case provides a + way to suppress unused-binding warnings selectively. </para> + <para> Notice that a variable + is reported as unused even if it appears in the right-hand side of another + unused binding. </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-fwarn-unused-imports</option>:</term> + <listitem> + <indexterm><primary><option>-fwarn-unused-imports</option></primary></indexterm> + <indexterm><primary>unused imports, warning</primary></indexterm> + <indexterm><primary>imports, unused</primary></indexterm> + + <para>Report any modules that are explicitly imported but + never used. However, the form <literal>import M()</literal> is + never reported as an unused import, because it is a useful idiom + for importing instance declarations, which are anonymous in Haskell.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-fwarn-unused-matches</option>:</term> + <listitem> + <indexterm><primary><option>-fwarn-unused-matches</option></primary></indexterm> + <indexterm><primary>unused matches, warning</primary></indexterm> + <indexterm><primary>matches, unused</primary></indexterm> + + <para>Report all unused variables which arise from pattern + matches, including patterns consisting of a single variable. + For instance <literal>f x y = []</literal> would report + <varname>x</varname> and <varname>y</varname> as unused. The + warning is suppressed if the variable name begins with an underscore, thus: + <programlisting> + f _x = True + </programlisting> + </para> + </listitem> + </varlistentry> + + </variablelist> + + <para>If you're feeling really paranoid, the + <option>-dcore-lint</option> + option<indexterm><primary><option>-dcore-lint</option></primary></indexterm> + is a good choice. It turns on heavyweight intra-pass + sanity-checking within GHC. (It checks GHC's sanity, not + yours.)</para> + + </sect1> + + &packages; + + <sect1 id="options-optimise"> + <title>Optimisation (code improvement)</title> + + <indexterm><primary>optimisation</primary></indexterm> + <indexterm><primary>improvement, code</primary></indexterm> + + <para>The <option>-O*</option> options specify convenient + “packages” of optimisation flags; the + <option>-f*</option> options described later on specify + <emphasis>individual</emphasis> optimisations to be turned on/off; + the <option>-m*</option> options specify + <emphasis>machine-specific</emphasis> optimisations to be turned + on/off.</para> + + <sect2 id="optimise-pkgs"> + <title><option>-O*</option>: convenient “packages” of optimisation flags.</title> + + <para>There are <emphasis>many</emphasis> options that affect + the quality of code produced by GHC. Most people only have a + general goal, something like “Compile quickly” or + “Make my program run like greased lightning.” The + following “packages” of optimisations (or lack + thereof) should suffice.</para> + + <para>Note that higher optimisation levels cause more + cross-module optimisation to be performed, which can have an + impact on how much of your program needs to be recompiled when + you change something. This is one reaosn to stick to + no-optimisation when developing code.</para> + + <variablelist> + + <varlistentry> + <term> + No <option>-O*</option>-type option specified: + <indexterm><primary>-O* not specified</primary></indexterm> + </term> + <listitem> + <para>This is taken to mean: “Please compile + quickly; I'm not over-bothered about compiled-code + quality.” So, for example: <command>ghc -c + Foo.hs</command></para> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <option>-O0</option>: + <indexterm><primary><option>-O0</option></primary></indexterm> + </term> + <listitem> + <para>Means “turn off all optimisation”, + reverting to the same settings as if no + <option>-O</option> options had been specified. Saying + <option>-O0</option> can be useful if + eg. <command>make</command> has inserted a + <option>-O</option> on the command line already.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <option>-O</option> or <option>-O1</option>: + <indexterm><primary>-O option</primary></indexterm> + <indexterm><primary>-O1 option</primary></indexterm> + <indexterm><primary>optimise</primary><secondary>normally</secondary></indexterm> + </term> + <listitem> + <para>Means: “Generate good-quality code without + taking too long about it.” Thus, for example: + <command>ghc -c -O Main.lhs</command></para> + + <para><option>-O</option> currently also implies + <option>-fvia-C</option>. This may change in the + future.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <option>-O2</option>: + <indexterm><primary>-O2 option</primary></indexterm> + <indexterm><primary>optimise</primary><secondary>aggressively</secondary></indexterm> + </term> + <listitem> + <para>Means: “Apply every non-dangerous + optimisation, even if it means significantly longer + compile times.”</para> + + <para>The avoided “dangerous” optimisations + are those that can make runtime or space + <emphasis>worse</emphasis> if you're unlucky. They are + normally turned on or off individually.</para> + + <para>At the moment, <option>-O2</option> is + <emphasis>unlikely</emphasis> to produce better code than + <option>-O</option>.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <option>-Ofile <file></option>: + <indexterm><primary>-Ofile <file> option</primary></indexterm> + <indexterm><primary>optimising, customised</primary></indexterm> + </term> + <listitem> + <para>(NOTE: not supported since GHC 4.x. Please ask if + you're interested in this.)</para> + + <para>For those who need <emphasis>absolute</emphasis> + control over <emphasis>exactly</emphasis> what options are + used (e.g., compiler writers, sometimes :-), a list of + options can be put in a file and then slurped in with + <option>-Ofile</option>.</para> + + <para>In that file, comments are of the + <literal>#</literal>-to-end-of-line variety; blank + lines and most whitespace is ignored.</para> + + <para>Please ask if you are baffled and would like an + example of <option>-Ofile</option>!</para> + </listitem> + </varlistentry> + </variablelist> + + <para>We don't use a <option>-O*</option> flag for day-to-day + work. We use <option>-O</option> to get respectable speed; + e.g., when we want to measure something. When we want to go for + broke, we tend to use <option>-O2 -fvia-C</option> (and we go for + lots of coffee breaks).</para> + + <para>The easiest way to see what <option>-O</option> (etc.) + “really mean” is to run with <option>-v</option>, + then stand back in amazement.</para> + </sect2> + + <sect2 id="options-f"> + <title><option>-f*</option>: platform-independent flags</title> + + <indexterm><primary>-f* options (GHC)</primary></indexterm> + <indexterm><primary>-fno-* options (GHC)</primary></indexterm> + + <para>These flags turn on and off individual optimisations. + They are normally set via the <option>-O</option> options + described above, and as such, you shouldn't need to set any of + them explicitly (indeed, doing so could lead to unexpected + results). However, there are one or two that may be of + interest:</para> + + <variablelist> + <varlistentry> + <term><option>-fexcess-precision</option>:</term> + <listitem> + <indexterm><primary><option>-fexcess-precision</option></primary></indexterm> + <para>When this option is given, intermediate floating + point values can have a <emphasis>greater</emphasis> + precision/range than the final type. Generally this is a + good thing, but some programs may rely on the exact + precision/range of + <literal>Float</literal>/<literal>Double</literal> values + and should not use this option for their compilation.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-fignore-asserts</option>:</term> + <listitem> + <indexterm><primary><option>-fignore-asserts</option></primary></indexterm> + <para>Causes GHC to ignore uses of the function + <literal>Exception.assert</literal> in source code (in + other words, rewriting <literal>Exception.assert p + e</literal> to <literal>e</literal> (see <xref + linkend="sec-assertions"/>). This flag is turned on by + <option>-O</option>. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <option>-fno-cse</option> + <indexterm><primary><option>-fno-cse</option></primary></indexterm> + </term> + <listitem> + <para>Turns off the common-sub-expression elimination optimisation. + Can be useful if you have some <literal>unsafePerformIO</literal> + expressions that you don't want commoned-up.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <option>-fno-strictness</option> + <indexterm><primary><option>-fno-strictness</option></primary></indexterm> + </term> + <listitem> + <para>Turns off the strictness analyser; sometimes it eats + too many cycles.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <option>-fno-full-laziness</option> + <indexterm><primary><option>-fno-full-laziness</option></primary></indexterm> + </term> + <listitem> + <para>Turns off the full laziness optimisation (also known as + let-floating). Full laziness increases sharing, which can lead + to increased memory residency.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <option>-fno-state-hack</option> + <indexterm><primary><option>-fno-state-hack</option></primary></indexterm> + </term> + <listitem> + <para>Turn off the "state hack" whereby any lambda with a + <literal>State#</literal> token as argument is considered to be + single-entry, hence it is considered OK to inline things inside + it. This can improve performance of IO and ST monad code, but it + runs the risk of reducing sharing.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <option>-funbox-strict-fields</option>: + <indexterm><primary><option>-funbox-strict-fields</option></primary></indexterm> + <indexterm><primary>strict constructor fields</primary></indexterm> + <indexterm><primary>constructor fields, strict</primary></indexterm> + </term> + <listitem> + <para>This option causes all constructor fields which are + marked strict (i.e. “!”) to be unboxed or + unpacked if possible. It is equivalent to adding an + <literal>UNPACK</literal> pragma to every strict + constructor field (see <xref + linkend="unpack-pragma"/>).</para> + + <para>This option is a bit of a sledgehammer: it might + sometimes make things worse. Selectively unboxing fields + by using <literal>UNPACK</literal> pragmas might be + better.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <option>-funfolding-update-in-place<n></option> + <indexterm><primary><option>-funfolding-update-in-place</option></primary></indexterm> + </term> + <listitem> + <para>Switches on an experimental "optimisation". + Switching it on makes the compiler a little keener to + inline a function that returns a constructor, if the + context is that of a thunk. +<programlisting> + x = plusInt a b +</programlisting> + If we inlined plusInt we might get an opportunity to use + update-in-place for the thunk 'x'.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term> + <option>-funfolding-creation-threshold<n></option>: + <indexterm><primary><option>-funfolding-creation-threshold</option></primary></indexterm> + <indexterm><primary>inlining, controlling</primary></indexterm> + <indexterm><primary>unfolding, controlling</primary></indexterm> + </term> + <listitem> + <para>(Default: 45) Governs the maximum size that GHC will + allow a function unfolding to be. (An unfolding has a + “size” that reflects the cost in terms of + “code bloat” of expanding that unfolding at + at a call site. A bigger function would be assigned a + bigger cost.) </para> + + <para> Consequences: (a) nothing larger than this will be + inlined (unless it has an INLINE pragma); (b) nothing + larger than this will be spewed into an interface + file. </para> + + + <para> Increasing this figure is more likely to result in longer + compile times than faster code. The next option is more + useful:</para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-funfolding-use-threshold<n></option>:</term> + <listitem> + <indexterm><primary><option>-funfolding-use-threshold</option></primary></indexterm> + <indexterm><primary>inlining, controlling</primary></indexterm> + <indexterm><primary>unfolding, controlling</primary></indexterm> + + <para>(Default: 8) This is the magic cut-off figure for + unfolding: below this size, a function definition will be + unfolded at the call-site, any bigger and it won't. The + size computed for a function depends on two things: the + actual size of the expression minus any discounts that + apply (see <option>-funfolding-con-discount</option>).</para> + </listitem> + </varlistentry> + </variablelist> + + </sect2> + + </sect1> + + &phases; + + <sect1 id="sec-using-concurrent"> + <title>Using Concurrent Haskell</title> + <indexterm><primary>Concurrent Haskell</primary><secondary>using</secondary></indexterm> + + <para>GHC supports Concurrent Haskell by default, without requiring a + special option or libraries compiled in a certain way. To get access to + the support libraries for Concurrent Haskell, just import + <ulink + url="../libraries/base/Control-Concurrent.html"><literal>Control.Concurrent</literal></ulink>. More information on Concurrent Haskell is provided in the documentation for that module.</para> + + <para>The following RTS option(s) affect the behaviour of Concurrent + Haskell programs:<indexterm><primary>RTS options, concurrent</primary></indexterm></para> + + <variablelist> + <varlistentry> + <term><option>-C<replaceable>s</replaceable></option></term> + <listitem> + <para><indexterm><primary><option>-C<replaceable>s</replaceable></option></primary><secondary>RTS option</secondary></indexterm> + Sets the context switch interval to <replaceable>s</replaceable> + seconds. A context switch will occur at the next heap block + allocation after the timer expires (a heap block allocation occurs + every 4k of allocation). With <option>-C0</option> or + <option>-C</option>, context switches will occur as often as + possible (at every heap block allocation). By default, context + switches occur every 20ms. Note that GHC's internal timer ticks + every 20ms, and the context switch timer is always a multiple of + this timer, so 20ms is the maximum granularity available for timed + context switches.</para> + </listitem> + </varlistentry> + </variablelist> + </sect1> + +<sect1 id="sec-using-parallel"> +<title>Using parallel Haskell</title> + +<para> +<indexterm><primary>Parallel Haskell</primary><secondary>using</secondary></indexterm> +[NOTE: GHC does not support Parallel Haskell by default, you need to + obtain a special version of GHC from the <ulink + url="http://www.cee.hw.ac.uk/~dsg/gph/">GPH</ulink> site. Also, +you won't be able to execute parallel Haskell programs unless PVM3 +(parallel Virtual Machine, version 3) is installed at your site.] +</para> + +<para> +To compile a Haskell program for parallel execution under PVM, use the +<option>-parallel</option> option,<indexterm><primary>-parallel +option</primary></indexterm> both when compiling <emphasis>and +linking</emphasis>. You will probably want to <literal>import +Control.Parallel</literal> into your Haskell modules. +</para> + +<para> +To run your parallel program, once PVM is going, just invoke it +“as normal”. The main extra RTS option is +<option>-qp<n></option>, to say how many PVM +“processors” your program to run on. (For more details of +all relevant RTS options, please see <xref +linkend="parallel-rts-opts"/>.) +</para> + +<para> +In truth, running parallel Haskell programs and getting information +out of them (e.g., parallelism profiles) is a battle with the vagaries of +PVM, detailed in the following sections. +</para> + +<sect2 id="pvm-dummies"> +<title>Dummy's guide to using PVM</title> + +<para> +<indexterm><primary>PVM, how to use</primary></indexterm> +<indexterm><primary>parallel Haskell—PVM use</primary></indexterm> +Before you can run a parallel program under PVM, you must set the +required environment variables (PVM's idea, not ours); something like, +probably in your <filename>.cshrc</filename> or equivalent: + +<programlisting> +setenv PVM_ROOT /wherever/you/put/it +setenv PVM_ARCH `$PVM_ROOT/lib/pvmgetarch` +setenv PVM_DPATH $PVM_ROOT/lib/pvmd +</programlisting> + +</para> + +<para> +Creating and/or controlling your “parallel machine” is a purely-PVM +business; nothing specific to parallel Haskell. The following paragraphs +describe how to configure your parallel machine interactively. +</para> + +<para> +If you use parallel Haskell regularly on the same machine configuration it +is a good idea to maintain a file with all machine names and to make the +environment variable PVM_HOST_FILE point to this file. Then you can avoid +the interactive operations described below by just saying +</para> + +<programlisting> +pvm $PVM_HOST_FILE +</programlisting> + +<para> +You use the <command>pvm</command><indexterm><primary>pvm command</primary></indexterm> command to start PVM on your +machine. You can then do various things to control/monitor your +“parallel machine;” the most useful being: +</para> + +<para> +<informaltable> +<tgroup cols="2"> +<colspec align="left"/> +<tbody> + +<row> +<entry><keycombo><keycap>Control</keycap><keycap>D</keycap></keycombo></entry> +<entry>exit <command>pvm</command>, leaving it running</entry> +</row> + +<row> +<entry><command>halt</command></entry> +<entry>kill off this “parallel machine” & exit</entry> +</row> + +<row> +<entry><command>add <host></command></entry> +<entry>add <command><host></command> as a processor</entry> +</row> + +<row> +<entry><command>delete <host></command></entry> +<entry>delete <command><host></command></entry> +</row> + +<row> +<entry><command>reset</command></entry> +<entry>kill what's going, but leave PVM up</entry> +</row> + +<row> +<entry><command>conf</command></entry> +<entry>list the current configuration</entry> +</row> + +<row> +<entry><command>ps</command></entry> +<entry>report processes' status</entry> +</row> + +<row> +<entry><command>pstat <pid></command></entry> +<entry>status of a particular process</entry> +</row> + +</tbody> +</tgroup> +</informaltable> +</para> + +<para> +The PVM documentation can tell you much, much more about <command>pvm</command>! +</para> + +</sect2> + +<sect2 id="par-profiles"> +<title>parallelism profiles</title> + +<para> +<indexterm><primary>parallelism profiles</primary></indexterm> +<indexterm><primary>profiles, parallelism</primary></indexterm> +<indexterm><primary>visualisation tools</primary></indexterm> +</para> + +<para> +With parallel Haskell programs, we usually don't care about the +results—only with “how parallel” it was! We want pretty pictures. +</para> + +<para> +parallelism profiles (à la <command>hbcpp</command>) can be generated with the +<option>-qP</option><indexterm><primary>-qP RTS option</primary></indexterm> RTS option. The +per-processor profiling info is dumped into files named +<filename><full-path><program>.gr</filename>. These are then munged into a PostScript picture, +which you can then display. For example, to run your program +<filename>a.out</filename> on 8 processors, then view the parallelism profile, do: +</para> + +<para> + +<screen> +<prompt>$</prompt> ./a.out +RTS -qP -qp8 +<prompt>$</prompt> grs2gr *.???.gr > temp.gr # combine the 8 .gr files into one +<prompt>$</prompt> gr2ps -O temp.gr # cvt to .ps; output in temp.ps +<prompt>$</prompt> ghostview -seascape temp.ps # look at it! +</screen> + +</para> + +<para> +The scripts for processing the parallelism profiles are distributed +in <filename>ghc/utils/parallel/</filename>. +</para> + +</sect2> + +<sect2> +<title>Other useful info about running parallel programs</title> + +<para> +The “garbage-collection statistics” RTS options can be useful for +seeing what parallel programs are doing. If you do either +<option>+RTS -Sstderr</option><indexterm><primary>-Sstderr RTS option</primary></indexterm> or <option>+RTS -sstderr</option>, then +you'll get mutator, garbage-collection, etc., times on standard +error. The standard error of all PE's other than the `main thread' +appears in <filename>/tmp/pvml.nnn</filename>, courtesy of PVM. +</para> + +<para> +Whether doing <option>+RTS -Sstderr</option> or not, a handy way to watch +what's happening overall is: <command>tail -f /tmp/pvml.nnn</command>. +</para> + +</sect2> + +<sect2 id="parallel-rts-opts"> +<title>RTS options for Parallel Haskell +</title> + +<para> +<indexterm><primary>RTS options, parallel</primary></indexterm> +<indexterm><primary>parallel Haskell—RTS options</primary></indexterm> +</para> + +<para> +Besides the usual runtime system (RTS) options +(<xref linkend="runtime-control"/>), there are a few options particularly +for parallel execution. +</para> + +<para> +<variablelist> + +<varlistentry> +<term><option>-qp<N></option>:</term> +<listitem> +<para> +<indexterm><primary>-qp<N> RTS option</primary></indexterm> +(paraLLEL ONLY) Use <literal><N></literal> PVM processors to run this program; +the default is 2. +</para> +</listitem> +</varlistentry> +<varlistentry> +<term><option>-C[<s>]</option>:</term> +<listitem> +<para> +<indexterm><primary>-C<s> RTS option</primary></indexterm> Sets +the context switch interval to <literal><s></literal> seconds. +A context switch will occur at the next heap block allocation after +the timer expires (a heap block allocation occurs every 4k of +allocation). With <option>-C0</option> or <option>-C</option>, +context switches will occur as often as possible (at every heap block +allocation). By default, context switches occur every 20ms. Note that GHC's internal timer ticks every 20ms, and +the context switch timer is always a multiple of this timer, so 20ms +is the maximum granularity available for timed context switches. +</para> +</listitem> +</varlistentry> +<varlistentry> +<term><option>-q[v]</option>:</term> +<listitem> +<para> +<indexterm><primary>-q RTS option</primary></indexterm> +(paraLLEL ONLY) Produce a quasi-parallel profile of thread activity, +in the file <filename><program>.qp</filename>. In the style of <command>hbcpp</command>, this profile +records the movement of threads between the green (runnable) and red +(blocked) queues. If you specify the verbose suboption (<option>-qv</option>), the +green queue is split into green (for the currently running thread +only) and amber (for other runnable threads). We do not recommend +that you use the verbose suboption if you are planning to use the +<command>hbcpp</command> profiling tools or if you are context switching at every heap +check (with <option>-C</option>). +--> +</para> +</listitem> +</varlistentry> +<varlistentry> +<term><option>-qt<num></option>:</term> +<listitem> +<para> +<indexterm><primary>-qt<num> RTS option</primary></indexterm> +(paraLLEL ONLY) Limit the thread pool size, i.e. the number of +threads per processor to <literal><num></literal>. The default is +32. Each thread requires slightly over 1K <emphasis>words</emphasis> in +the heap for thread state and stack objects. (For 32-bit machines, this +translates to 4K bytes, and for 64-bit machines, 8K bytes.) +</para> +</listitem> +</varlistentry> +<!-- no more -HWL +<varlistentry> +<term><option>-d</option>:</term> +<listitem> +<para> +<indexterm><primary>-d RTS option (parallel)</primary></indexterm> +(paraLLEL ONLY) Turn on debugging. It pops up one xterm (or GDB, or +something…) per PVM processor. We use the standard <command>debugger</command> +script that comes with PVM3, but we sometimes meddle with the +<command>debugger2</command> script. We include ours in the GHC distribution, +in <filename>ghc/utils/pvm/</filename>. +</para> +</listitem> +</varlistentry> +--> +<varlistentry> +<term><option>-qe<num></option>:</term> +<listitem> +<para> +<indexterm><primary>-qe<num> RTS option +(parallel)</primary></indexterm> (paraLLEL ONLY) Limit the spark pool size +i.e. the number of pending sparks per processor to +<literal><num></literal>. The default is 100. A larger number may be +appropriate if your program generates large amounts of parallelism +initially. +</para> +</listitem> +</varlistentry> +<varlistentry> +<term><option>-qQ<num></option>:</term> +<listitem> +<para> +<indexterm><primary>-qQ<num> RTS option (parallel)</primary></indexterm> +(paraLLEL ONLY) Set the size of packets transmitted between processors +to <literal><num></literal>. The default is 1024 words. A larger number may be +appropriate if your machine has a high communication cost relative to +computation speed. +</para> +</listitem> +</varlistentry> +<varlistentry> +<term><option>-qh<num></option>:</term> +<listitem> +<para> +<indexterm><primary>-qh<num> RTS option (parallel)</primary></indexterm> +(paraLLEL ONLY) Select a packing scheme. Set the number of non-root thunks to pack in one packet to +<num>-1 (0 means infinity). By default GUM uses full-subgraph +packing, i.e. the entire subgraph with the requested closure as root is +transmitted (provided it fits into one packet). Choosing a smaller value +reduces the amount of pre-fetching of work done in GUM. This can be +advantageous for improving data locality but it can also worsen the balance +of the load in the system. +</para> +</listitem> +</varlistentry> +<varlistentry> +<term><option>-qg<num></option>:</term> +<listitem> +<para> +<indexterm><primary>-qg<num> RTS option +(parallel)</primary></indexterm> (paraLLEL ONLY) Select a globalisation +scheme. This option affects the +generation of global addresses when transferring data. Global addresses are +globally unique identifiers required to maintain sharing in the distributed +graph structure. Currently this is a binary option. With <num>=0 full globalisation is used +(default). This means a global address is generated for every closure that +is transmitted. With <num>=1 a thunk-only globalisation scheme is +used, which generated global address only for thunks. The latter case may +lose sharing of data but has a reduced overhead in packing graph structures +and maintaining internal tables of global addresses. +</para> +</listitem> +</varlistentry> +</variablelist> +</para> + +</sect2> + +</sect1> + + <sect1 id="options-platform"> + <title>Platform-specific Flags</title> + + <indexterm><primary>-m* options</primary></indexterm> + <indexterm><primary>platform-specific options</primary></indexterm> + <indexterm><primary>machine-specific options</primary></indexterm> + + <para>Some flags only make sense for particular target + platforms.</para> + + <variablelist> + + <varlistentry> + <term><option>-mv8</option>:</term> + <listitem> + <para>(SPARC machines)<indexterm><primary>-mv8 option (SPARC + only)</primary></indexterm> Means to pass the like-named + option to GCC; it says to use the Version 8 SPARC + instructions, notably integer multiply and divide. The + similar <option>-m*</option> GCC options for SPARC also + work, actually.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term><option>-monly-[32]-regs</option>:</term> + <listitem> + <para>(iX86 machines)<indexterm><primary>-monly-N-regs + option (iX86 only)</primary></indexterm> GHC tries to + “steal” four registers from GCC, for performance + reasons; it almost always works. However, when GCC is + compiling some modules with four stolen registers, it will + crash, probably saying: + +<screen> +Foo.hc:533: fixed or forbidden register was spilled. +This may be due to a compiler bug or to impossible asm +statements or clauses. +</screen> + + Just give some registers back with + <option>-monly-N-regs</option>. Try `3' first, then `2'. + If `2' doesn't work, please report the bug to us.</para> + </listitem> + </varlistentry> + </variablelist> + + </sect1> + +&runtime; + +<sect1 id="ext-core"> + <title>Generating and compiling External Core Files</title> + + <indexterm><primary>intermediate code generation</primary></indexterm> + + <para>GHC can dump its optimized intermediate code (said to be in “Core” format) + to a file as a side-effect of compilation. Core files, which are given the suffix + <filename>.hcr</filename>, can be read and processed by non-GHC back-end + tools. The Core format is formally described in <ulink url="http://www.haskell.org/ghc/docs/papers/core.ps.gz"> + <citetitle>An External Representation for the GHC Core Language</citetitle></ulink>, + and sample tools (in Haskell) + for manipulating Core files are available in the GHC source distribution + directory <literal>/fptools/ghc/utils/ext-core</literal>. + Note that the format of <literal>.hcr</literal> + files is <emphasis>different</emphasis> (though similar) to the Core output format generated + for debugging purposes (<xref linkend="options-debugging"/>).</para> + + <para>The Core format natively supports notes which you can add to + your source code using the <literal>CORE</literal> pragma (see <xref + linkend="pragmas"/>).</para> + + <variablelist> + + <varlistentry> + <term> + <option>-fext-core</option> + <indexterm><primary><option>-fext-core</option></primary></indexterm> + </term> + <listitem> + <para>Generate <literal>.hcr</literal> files.</para> + </listitem> + </varlistentry> + + </variablelist> + +<para>GHC can also read in External Core files as source; just give the <literal>.hcr</literal> file on +the command line, instead of the <literal>.hs</literal> or <literal>.lhs</literal> Haskell source. +A current infelicity is that you need to give the <literal>-fglasgow-exts</literal> flag too, because +ordinary Haskell 98, when translated to External Core, uses things like rank-2 types.</para> +</sect1> + +&debug; +&flags; + +</chapter> + +<!-- Emacs stuff: + ;;; Local Variables: *** + ;;; mode: xml *** + ;;; sgml-parent-document: ("users_guide.xml" "book" "chapter") *** + ;;; End: *** + --> diff --git a/docs/users_guide/utils.xml b/docs/users_guide/utils.xml new file mode 100644 index 0000000000..6c82f6b38a --- /dev/null +++ b/docs/users_guide/utils.xml @@ -0,0 +1,564 @@ +<?xml version="1.0" encoding="iso-8859-1"?> +<chapter id="utils"> + <title>Other Haskell utility programs</title> + <indexterm><primary>utilities, Haskell</primary></indexterm> + + <para>This section describes other program(s) which we distribute, + that help with the Great Haskell Programming Task.</para> + +<!-- comment: hasktags documentation loosely based on that for hstags --> + +<sect1 id ="hasktags"> + <title>Ctags and Etags for Haskell: <command>hasktags</command></title> + <indexterm><primary><command>hasktags</command></primary></indexterm> + <indexterm><primary>CTAGS for Haskell</primary></indexterm> + + <para><command>hasktags</command> is a very simple Haskell program that produces ctags "tags" and etags "TAGS" files for Haskell programs.</para> + + <para>When loaded into an editor such an NEdit, Vim, or Emacs, this allows one to easily navigate around a multi-file program, finding definitions of functions, types, and constructors.</para> + + <para>Invocation Syntax:</para> + +<screen> +hasktags files +</screen> + +<para>This will read all the files listed in <option>files</option> and produce a ctags "tags" file and an etags "TAGS" file in the current directory.</para> + + <para>Example usage</para> + +<screen> +find -name \*.\*hs | xargs hasktags +</screen> + +<para>This will find all haskell source files in the current directory and below, and create tags files indexing them in the current directory.</para> + + <para><command>hasktags</command> is a simple program that uses simple + parsing rules to find definitions of functions, constructors, and types. It isn't guaranteed to find everything, and will sometimes create false index entries, but it usually gets the job done fairly well. In particular, at present, functions are only indexed if a type signature is given for them.</para> + + <para>Before hasktags, there used to be <command>fptags</command> and <command>hstags</command>, which did essentially the same job, however neither of these seem to be maintained any more.</para> + +<sect2> +<title>Using tags with your editor</title> + +<para>With NEdit, load the "tags" file using "File/Load Tags File". Use "Ctrl-D" to search for a tag.</para> + +<para>With XEmacs, load the "TAGS" file using "visit-tags-table". Use "M-." to search for a tag.</para> + + +</sect2> + +</sect1> + +<!-- comment: hstags doesn't work anymore + + <sect1 id="hstags"> + <title>Emacs `TAGS' for Haskell: <command>hstags</command></title> + <indexterm><primary><command>hstags</command></primary></indexterm> + <indexterm><primary>TAGS for Haskell</primary></indexterm> + + <para>`Tags' is a facility for indexing the definitions of + programming-language things in a multi-file program, and then + using that index to jump around among these definitions.</para> + + <para>Rather than scratch your head, saying “Now where did + we define `foo'?”, you just do (in Emacs) <Literal>M-. foo + RET</Literal>, and You're There! Some people go wild over this + stuff…</para> + + <para>GHC comes with a program <command>hstags</command>, which + build Emacs-able TAGS files. The invocation syntax is:</para> + +<screen> +hstags [GHC-options] file [files...] +</screen> + + <para>The best thing is just to feed it your GHC command-line + flags. A good Makefile entry might be:</para> + +<programlisting> +tags: + $(RM) TAGS + hstags $(GHC_FLAGS) *.lhs +</programlisting> + + <para>The only flags of its own are: <Option>-v</Option> to be + verbose; <Option>-a</Option> to <Emphasis>APPEND</Emphasis> to the + TAGS file, rather than write to it.</para> + + <para>Shortcomings: (1) Instance declarations don't get into + the TAGS file (but the definitions inside them do); as instances + aren't named, this is probably just as well. + (2) Data-constructor definitions don't get in. Go for the + corresponding type constructor instead.</para> + + <para>Actually, GHC also comes with <command>etags</command> + [for C], and <command>perltags</command> [for You + Know What]. And—I cannot tell a lie—there is + Denis Howe's <command>fptags</command> [for Haskell, + etc.] in the <Filename>ghc/CONTRIB</Filename> + section…)</para> + + </sect1> +--> + + <sect1 id="happy"> + <title>“Yacc for Haskell”: <command>happy</command></title> + + <indexterm><primary>Happy</primary></indexterm> + <indexterm><primary>Yacc for Haskell</primary></indexterm> + <indexterm><primary>parser generator for Haskell</primary></indexterm> + + <para>Andy Gill and Simon Marlow have written a parser-generator + for Haskell, called + <command>happy</command>.<indexterm><primary>happy parser + generator</primary></indexterm> <command>Happy</command> is to + Haskell what <command>Yacc</command> is to C.</para> + + <para>You can get <command>happy</command> from <ulink + url="http://www.haskell.org/happy/">the Happy + Homepage</ulink>.</para> + + <para><command>Happy</command> is at its shining best when + compiled by GHC.</para> + + </sect1> + +<!-- we don't distribute this anymore + <sect1 id="pphs"> + <title>Pretty-printing Haskell: <command>pphs</command></title> + <indexterm><primary>pphs</primary></indexterm> + <indexterm><primary>pretty-printing Haskell code</primary></indexterm> + + <para>Andrew Preece has written + <command>pphs</command>,<indexterm><primary>pphs</primary></indexterm><indexterm><primary>pretty-printing + Haskell</primary></indexterm> a utility to pretty-print Haskell + code in LaTeX documents. Keywords in bolds, variables in + italics—that sort of thing. It is good at lining up program + clauses and equals signs, things that are very tiresome to do by + hand.</para> + + <para>The code is distributed with GHC in + <Filename>ghc/CONTRIB/pphs</Filename>.</para> + </sect1> +--> + + <sect1 id="hsc2hs"> + <title>Writing Haskell interfaces to C code: + <command>hsc2hs</command></title> + <indexterm><primary><command>hsc2hs</command></primary> + </indexterm> + + <para>The <command>hsc2hs</command> command can be used to automate + some parts of the process of writing Haskell bindings to C code. + It reads an almost-Haskell source with embedded special + constructs, and outputs a real Haskell file with these constructs + processed, based on information taken from some C headers. The + extra constructs deal with accessing C data from Haskell.</para> + + <para>It may also output a C file which contains additional C + functions to be linked into the program, together with a C header + that gets included into the C code to which the Haskell module + will be compiled (when compiled via C) and into the C file. These + two files are created when the <literal>#def</literal> construct + is used (see below).</para> + + <para>Actually <command>hsc2hs</command> does not output the Haskell + file directly. It creates a C program that includes the headers, + gets automatically compiled and run. That program outputs the + Haskell code.</para> + + <para>In the following, “Haskell file” is the main + output (usually a <literal>.hs</literal> file), “compiled + Haskell file” is the Haskell file after + <command>ghc</command> has compiled it to C (i.e. a + <literal>.hc</literal> file), “C program” is the + program that outputs the Haskell file, “C file” is the + optionally generated C file, and “C header” is its + header file.</para> + + <sect2> + <title>command line syntax</title> + + <para><command>hsc2hs</command> takes input files as arguments, + and flags that modify its behavior:</para> + + <variablelist> + <varlistentry> + <term><literal>-o FILE</literal> or + <literal>––output=FILE</literal></term> + <listitem> + <para>Name of the Haskell file.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>-t FILE</literal> or + <literal>––template=FILE</literal></term> + <listitem> + <para>The template file (see below).</para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>-c PROG</literal> or + <literal>––cc=PROG</literal></term> + <listitem> + <para>The C compiler to use (default: + <command>ghc</command>)</para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>-l PROG</literal> or + <literal>––ld=PROG</literal></term> + <listitem> + <para>The linker to use (default: + <command>gcc</command>).</para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>-C FLAG</literal> or + <literal>––cflag=FLAG</literal></term> + <listitem> + <para>An extra flag to pass to the C compiler.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>-I DIR</literal></term> + <listitem> + <para>Passed to the C compiler.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>-L FLAG</literal> or + <literal>––lflag=FLAG</literal></term> + <listitem> + <para>An extra flag to pass to the linker.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>-i FILE</literal> or + <literal>––include=FILE</literal></term> + <listitem> + <para>As if the appropriate <literal>#include</literal> + directive was placed in the source.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>-D NAME[=VALUE]</literal> or + <literal>––define=NAME[=VALUE]</literal></term> + <listitem> + <para>As if the appropriate <literal>#define</literal> + directive was placed in the source.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>––no-compile</literal></term> + <listitem> + <para>Stop after writing out the intermediate C program to disk. + The file name for the intermediate C program is the input file name + with <literal>.hsc</literal> replaced with <literal>_hsc_make.c</literal>.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>-?</literal> or <literal>––help</literal></term> + <listitem> + <para>Display a summary of the available flags and exit successfully.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>-V</literal> or <literal>––version</literal></term> + <listitem> + <para>Output version information and exit successfully.</para> + </listitem> + </varlistentry> + </variablelist> + + <para>The input file should end with .hsc (it should be plain + Haskell source only; literate Haskell is not supported at the + moment). Output files by default get names with the + <literal>.hsc</literal> suffix replaced:</para> + + <informaltable> + <tgroup cols="2"> + <tbody> + <row> + <entry><literal>.hs</literal></entry> + <entry>Haskell file</entry> + </row> + <row> + <entry><literal>_hsc.h</literal></entry> + <entry>C header</entry> + </row> + <row> + <entry><literal>_hsc.c</literal></entry> + <entry>C file</entry> + </row> + </tbody> + </tgroup> + </informaltable> + + <para>The C program is compiled using the Haskell compiler. This + provides the include path to <filename>HsFFI.h</filename> which + is automatically included into the C program.</para> + + </sect2> + <sect2><title>Input syntax</title> + + <para>All special processing is triggered by + the <literal>#</literal> operator. To output + a literal <literal>#</literal>, write it twice: + <literal>##</literal>. Inside string literals and comments + <literal>#</literal> characters are not processed.</para> + + <para>A <literal>#</literal> is followed by optional + spaces and tabs, an alphanumeric keyword that describes + the kind of processing, and its arguments. Arguments look + like C expressions separated by commas (they are not + written inside parens). They extend up to the nearest + unmatched <literal>)</literal>, <literal>]</literal> or + <literal>}</literal>, or to the end of line if it occurs outside + any <literal>() [] {} '' "" /**/</literal> and is not preceded + by a backslash. Backslash-newline pairs are stripped.</para> + + <para>In addition <literal>#{stuff}</literal> is equivalent + to <literal>#stuff</literal> except that it's self-delimited + and thus needs not to be placed at the end of line or in some + brackets.</para> + + <para>Meanings of specific keywords:</para> + + <variablelist> + + <varlistentry> + <term><literal>#include <file.h></literal></term> + <term><literal>#include "file.h"</literal></term> + <listitem> + <para>The specified file gets included into the C program, + the compiled Haskell file, and the C header. + <literal><HsFFI.h></literal> is included + automatically.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>#define name</literal></term> + <term><literal>#define name value</literal></term> + <term><literal>#undef name</literal></term> + <listitem> + <para>Similar to <literal>#include</literal>. Note that + <literal>#includes</literal> and + <literal>#defines</literal> may be put in the same file + twice so they should not assume otherwise.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>#let name parameters = "definition"</literal></term> + <listitem> + <para>Defines a macro to be applied to the Haskell + source. Parameter names are comma-separated, not + inside parens. Such macro is invoked as other + <literal>#</literal>-constructs, starting with + <literal>#name</literal>. The definition will be + put in the C program inside parens as arguments of + <literal>printf</literal>. To refer to a parameter, + close the quote, put a parameter name and open the + quote again, to let C string literals concatenate. + Or use <literal>printf</literal>'s format directives. + Values of arguments must be given as strings, unless the + macro stringifies them itself using the C preprocessor's + <literal>#parameter</literal> syntax.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>#def C_definition</literal></term> + <listitem> + <para>The definition (of a function, variable, struct or + typedef) is written to the C file, and its prototype or + extern declaration to the C header. Inline functions are + handled correctly. struct definitions and typedefs are + written to the C program too. The + <literal>inline</literal>, <literal>struct</literal> or + <literal>typedef</literal> keyword must come just after + <literal>def</literal>.</para> + + <note><para>A <literal>foreign import</literal> of a + C function may be inlined across a module boundary, + in which case you must arrange for the importing + module to <literal>#include</literal> the C header + file generated by <command>hsc2hs</command> (see + <xref linkend="glasgow-foreign-headers"/>). + For this reason we avoid using <literal>#def</literal> + in the libraries.</para></note> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>#if condition</literal></term> + <term><literal>#ifdef name</literal></term> + <term><literal>#ifndef name</literal></term> + <term><literal>#elif condition</literal></term> + <term><literal>#else</literal></term> + <term><literal>#endif</literal></term> + <term><literal>#error message</literal></term> + <term><literal>#warning message</literal></term> + <listitem> + <para>Conditional compilation directives are passed + unmodified to the C program, C file, and C header. Putting + them in the C program means that appropriate parts of the + Haskell file will be skipped.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>#const C_expression</literal></term> + <listitem> + <para>The expression must be convertible to + <literal>long</literal> or <literal>unsigned + long</literal>. Its value (literal or negated literal) + will be output.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>#const_str C_expression</literal></term> + <listitem> + <para>The expression must be convertible to const char + pointer. Its value (string literal) will be output.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>#type C_type</literal></term> + <listitem> + <para>A Haskell equivalent of the C numeric type will be + output. It will be one of + <literal>{Int,Word}{8,16,32,64}</literal>, + <literal>Float</literal>, <literal>Double</literal>, + <literal>LDouble</literal>.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>#peek struct_type, field</literal></term> + <listitem> + <para>A function that peeks a field of a C struct will be + output. It will have the type + <literal>Storable b => Ptr a -> IO b</literal>. + + The intention is that <literal>#peek</literal> and + <literal>#poke</literal> can be used for implementing the + operations of class <literal>Storable</literal> for a + given C struct (see the + <literal>Foreign.Storable</literal> module in the library + documentation).</para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>#poke struct_type, field</literal></term> + <listitem> + <para>Similarly for poke. It will have the type + <literal>Storable b => Ptr a -> b -> IO ()</literal>.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>#ptr struct_type, field</literal></term> + <listitem> + <para>Makes a pointer to a field struct. It will have the type + <literal>Ptr a -> Ptr b</literal>.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>#offset struct_type, field</literal></term> + <listitem> + <para>Computes the offset, in bytes, of + <literal>field</literal> in + <literal>struct_type</literal>. It will have type + <literal>Int</literal>.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>#size struct_type</literal></term> + <listitem> + <para>Computes the size, in bytes, of + <literal>struct_type</literal>. It will have type + <literal>Int</literal>.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term><literal>#enum type, constructor, value, value, ...</literal></term> + <listitem> + <para>A shortcut for multiple definitions which use + <literal>#const</literal>. Each <literal>value</literal> + is a name of a C integer constant, e.g. enumeration value. + The name will be translated to Haskell by making each + letter following an underscore uppercase, making all the rest + lowercase, and removing underscores. You can supply a different + translation by writing <literal>hs_name = c_value</literal> + instead of a <literal>value</literal>, in which case + <literal>c_value</literal> may be an arbitrary expression. + The <literal>hs_name</literal> will be defined as having the + specified <literal>type</literal>. Its definition is the specified + <literal>constructor</literal> (which in fact may be an expression + or be empty) applied to the appropriate integer value. You can + have multiple <literal>#enum</literal> definitions with the same + <literal>type</literal>; this construct does not emit the type + definition itself.</para> + </listitem> + </varlistentry> + </variablelist> + + </sect2> + + <sect2> + <title>Custom constructs</title> + + <para><literal>#const</literal>, <literal>#type</literal>, + <literal>#peek</literal>, <literal>#poke</literal> and + <literal>#ptr</literal> are not hardwired into the + <command>hsc2hs</command>, but are defined in a C template that is + included in the C program: <filename>template-hsc.h</filename>. + Custom constructs and templates can be used too. Any + <literal>#</literal>-construct with unknown key is expected to + be handled by a C template.</para> + + <para>A C template should define a macro or function with name + prefixed by <literal>hsc_</literal> that handles the construct + by emitting the expansion to stdout. See + <filename>template-hsc.h</filename> for examples.</para> + + <para>Such macros can also be defined directly in the + source. They are useful for making a <literal>#let</literal>-like + macro whose expansion uses other <literal>#let</literal> macros. + Plain <literal>#let</literal> prepends <literal>hsc_</literal> + to the macro name and wraps the definition in a + <literal>printf</literal> call.</para> + + </sect2> + + </sect1> + +</chapter> + +<!-- Emacs stuff: + ;;; Local Variables: *** + ;;; mode: xml *** + ;;; sgml-parent-document: ("users_guide.xml" "book" "chapter") *** + ;;; End: *** + --> diff --git a/docs/users_guide/win32-dlls.xml b/docs/users_guide/win32-dlls.xml new file mode 100644 index 0000000000..959f7ce1b6 --- /dev/null +++ b/docs/users_guide/win32-dlls.xml @@ -0,0 +1,493 @@ +<?xml version="1.0" encoding="iso-8859-1"?> +<chapter id="win32"> +<title>Running GHC on Win32 systems</title> + +<sect1> +<title> +Starting GHC on Win32 platforms</title> + +<para> +The installer that installs GHC on Win32 also sets up the file-suffix associations +for ".hs" and ".lhs" files so that double-clicking them starts <command>ghci</command>. +</para> +<para> +Be aware of that <command>ghc</command> and <command>ghci</command> do +require filenames containing spaces to be escaped using quotes: +<programlisting> + c:\ghc\bin\ghci "c:\\Program Files\\Haskell\\Project.hs" +</programlisting> +If the quotes are left off in the above command, <command>ghci</command> will +interpret the filename as two, "c:\\Program" and "Files\\Haskell\\Project.hs". +</para> + +<!-- not clear whether there are current editions of Win32 OSes that + doesn't do this by default. + +<para> Solution: don't use "Open With...", avoid spaces in file names, +or fiddle with the appropriate registry setting: +<programlisting> + HKEY_CLASSES_ROOT\Unknown\shell\openas\command +</programlisting> +Notice how the "%1" argument is quoted (or not). +</para> +<para> This problem doesn't occur when double-clicking. +</para> +--> + +</sect1> + +<sect1> +<title> +Interacting with the terminal</title> + +<para>By default GHC builds applications that open a console window when they start. +If you want to build a GUI-only application, with no console window, use the flag +<literal>-optl-mwindows</literal> in the link step. +</para> + +<para> <emphasis>Warning:</emphasis> Windows GUI-only programs have no + stdin, stdout or stderr so using the ordinary Haskell + input/output functions will cause your program to fail with an + IO exception, such as: +<screen> + Fail: <stdout>: hPutChar: failed (Bad file descriptor) +</screen> + However using Debug.Trace.trace is alright because it uses + Windows debugging output support rather than stderr.</para> + +<para>For some reason, Mingw ships with the <literal>readline</literal> library, +but not with the <literal>readline</literal> headers. As a result, GHC (like Hugs) does not +use <literal>readline</literal> for interactive input on Windows. +You can get a close simulation by using an emacs shell buffer! +</para> + +</sect1> + +<sect1> +<title> +Differences in library behaviour </title> + +<para> +Some of the standard Haskell libraries behave slightly differently on Windows. + +<itemizedlist> +<listitem> <para> +On Windows, the '<literal>^Z</literal>' character is interpreted as an +end-of-file character, so if you read a file containing this character +the file will appear to end just before it. To avoid this, +use <literal>IOExts.openFileEx</literal> to open a file in binary +(untranslated) mode or change an already opened file handle into +binary mode using <literal>IOExts.hSetBinaryMode</literal>. The +<literal>IOExts</literal> module is part of the +<literal>lang</literal> package. +</para> +</listitem> +</itemizedlist> +</para> +</sect1> + +<sect1> +<title> +Using GHC (and other GHC-compiled executables) with cygwin</title> + +<sect2> +<title>Background</title> <para>The cygwin tools aim to provide a +unix-style API on top of the windows libraries, to facilitate ports of +unix software to windows. To this end, they introduce a unix-style +directory hierarchy under some root directory (typically +<filename>/</filename> is <filename>C:\cygwin\</filename>). Moreover, +everything built against the cygwin API (including the cygwin tools +and programs compiled with cygwin's ghc) will see / as the root of +their file system, happily pretending to work in a typical unix +environment, and finding things like <filename>/bin</filename> and <filename>/usr/include</filename> without +ever explicitly bothering with their actual location on the windows +system (probably <filename>C:\cygwin\bin</filename> and <filename>C:\cygwin\usr\include</filename>). +</para> +</sect2> + +<sect2><title>The problem</title> +<para>GHC, by default, no longer depends on cygwin, but is a native +windows program. It is built using mingw, and it uses mingw's ghc +while compiling your Haskell sources (even if you call it from +cygwin's bash), but what matters here is that - just like any other +normal windows program - neither GHC nor the executables it produces +are aware of cygwin's pretended unix hierarchy. GHC will happily +accept either '/' or '\' as path separators, but it won't know where +to find <filename>/home/joe/Main.hs</filename> or <filename>/bin/bash</filename> +or the like. This causes all +kinds of fun when GHC is used from within cygwin's bash, or in +make-sessions running under cygwin. +</para> +</sect2> + +<sect2><title>Things to do</title> +<itemizedlist> +<listitem> +<para> Don't use absolute paths in make, configure & co if there is any chance + that those might be passed to GHC (or to GHC-compiled programs). Relative + paths are fine because cygwin tools are happy with them and GHC accepts + '/' as path-separator. And relative paths don't depend on where cygwin's + root directory is located, or on which partition or network drive your source + tree happens to reside, as long as you 'cd' there first. +</para></listitem> + +<listitem> +<para> If you have to use absolute paths (beware of the innocent-looking + <literal>ROOT=`pwd`</literal> in makefile hierarchies or configure scripts), cygwin provides + a tool called <command>cygpath</command> that can convert cygwin's unix-style paths to their + actual windows-style counterparts. Many cygwin tools actually accept + absolute windows-style paths (remember, though, that you either need + to escape '\' or convert '\' to '/'), so you should be fine just using those + everywhere. If you need to use tools that do some kind of path-mangling + that depends on unix-style paths (one fun example is trying to interpret ':' + as a separator in path lists..), you can still try to convert paths using + <command>cygpath</command> just before they are passed to GHC and friends. +</para></listitem> + +<listitem> +<para> If you don't have <command>cygpath</command>, you probably don't have cygwin and hence + no problems with it... unless you want to write one build process for several + platforms. Again, relative paths are your friend, but if you have to use + absolute paths, and don't want to use different tools on different platforms, + you can simply write a short Haskell program to print the current directory + (thanks to George Russell for this idea): compiled with GHC, this will give + you the view of the file system that GHC depends on (which will differ + depending on whether GHC is compiled with cygwin's gcc or mingw's + gcc or on a real unix system..) - that little program can also deal with + escaping '\' in paths. Apart from the banner and the startup time, + something like this would also do: +<programlisting> + $ echo "Directory.getCurrentDirectory >>= putStrLn . init . tail . show " | ghci +</programlisting> +</para></listitem> +</itemizedlist> +</sect2> +</sect1> + + +<sect1 id="win32-dlls"> +<title>Building and using Win32 DLLs +</title> + +<para> +<emphasis>Making Haskell libraries into DLLs doesn't work on Windows at the +moment; however, all the machinery is +still there. If you're interested, contact the GHC team. Note that +building an entire Haskell application as a single DLL is still supported: it's + just multi-DLL Haskell programs that don't work. The Windows + distribution of GHC contains static libraries only.</emphasis></para> + +<!-- +<para> +<indexterm><primary>Dynamic link libraries, Win32</primary></indexterm> +<indexterm><primary>DLLs, Win32</primary></indexterm> +On Win32 platforms, the compiler is capable of both producing and using +dynamic link libraries (DLLs) containing ghc-compiled code. This +section shows you how to make use of this facility. +</para> + +<para> +Until recently, <command>strip</command> didn't work reliably on DLLs, so you +should test your version with care, or make sure you have the latest +binutils. Unfortunately, we don't know exactly which version of binutils +cured the problem (it was supposedly fixed some years ago). +</para> + + +<sect2 id="win32-dlls-link"> +<title>Linking with DLLs</title> + +<para> +The default on Win32 platforms is to link applications in such a way +that the executables will use the Prelude and system libraries DLLs, +rather than contain (large chunks of) them. This is transparent at the +command-line, so +</para> + +<para> +<screen> +sh$ cat main.hs +module Main where +main = putStrLn "hello, world!" +sh$ ghc -o main main.hs +ghc: module version changed to 1; reason: no old .hi file +sh$ strip main.exe +sh$ ls -l main.exe +-rwxr-xr-x 1 544 everyone 4608 May 3 17:11 main.exe* +sh$ ./main +hello, world! +sh$ +</screen> +</para> + +<para> +will give you a binary as before, but the <filename>main.exe</filename> +generated will use the Prelude and RTS DLLs instead of linking them in +statically. +</para> + +<para> +4K for a <literal>"hello, world"</literal> application—not bad, huh? :-) +</para> + +</sect2> + +<sect2 id="win32-dlls-linking-static"> +<title>Not linking with DLLs +<indexterm><primary>-static option (Win32)</primary></indexterm></title> + +<para> +If you want to build an executable that doesn't depend on any +ghc-compiled DLLs, use the <option>-static</option> option to link in +the code statically. +</para> + +<para> +Notice that you cannot mix code that has been compiled with +<option>-static</option> and not, so you have to use the <option>-static</option> +option on all the Haskell modules that make up your application. +</para> + +</sect2> +--> + +<sect2 id="win32-dlls-create"> +<title>Creating a DLL</title> + +<para> +<indexterm><primary>Creating a Win32 DLL</primary></indexterm> +<indexterm><primary>––mk-dll</primary></indexterm> +Sealing up your Haskell library inside a DLL is straightforward; +compile up the object files that make up the library, and then build +the DLL by issuing a command of the form: +</para> + +<para> +<screen> +ghc ––mk-dll -o foo.dll bar.o baz.o wibble.a -lfooble +</screen> +</para> + +<para> +By feeding the ghc compiler driver the option <option>––mk-dll</option>, it +will build a DLL rather than produce an executable. The DLL will +consist of all the object files and archives given on the command +line. +</para> + +<!-- +<para> +To create a `static' DLL, i.e. one that does not depend on the GHC DLLs, +use the <option>-static</option> when compiling up your Haskell code and +building the DLL. +</para> +--> + +<para> +A couple of things to notice: +</para> + +<para> + +<itemizedlist> +<!-- +<listitem> +<para> +Since DLLs correspond to packages (see <xref linkend="packages"/>) you need +to use <option>-package-name dll-name</option> when compiling modules that +belong to a DLL if you're going to call them from Haskell. Otherwise, Haskell +code that calls entry points in that DLL will do so incorrectly, and crash. +For similar reasons, you can only compile a single module tree into a DLL, +as <function>startupHaskell</function> needs to be able to call its +initialisation function, and only takes one such argument (see <xref +linkend="win32-dlls-foreign"/>). Hence the modules +you compile into a DLL must have a common root. +</para> +</listitem> +--> + +<listitem> +<para> +By default, the entry points of all the object files will be exported from +the DLL when using <option>––mk-dll</option>. Should you want to constrain +this, you can specify the <emphasis>module definition file</emphasis> to use +on the command line as follows: + +<screen> +ghc ––mk-dll -o .... -optdll––def -optdllMyDef.def +</screen> + +See Microsoft documentation for details, but a module definition file +simply lists what entry points you want to export. Here's one that's +suitable when building a Haskell COM server DLL: + +<programlisting> +EXPORTS + DllCanUnloadNow = DllCanUnloadNow@0 + DllGetClassObject = DllGetClassObject@12 + DllRegisterServer = DllRegisterServer@0 + DllUnregisterServer = DllUnregisterServer@0 +</programlisting> +</para> +</listitem> + +<listitem> +<para> +In addition to creating a DLL, the <option>––mk-dll</option> option also +creates an import library. The import library name is derived from the +name of the DLL, as follows: + +<programlisting> +DLL: HScool.dll ==> import lib: libHScool_imp.a +</programlisting> + +The naming scheme may look a bit weird, but it has the purpose of allowing +the co-existence of import libraries with ordinary static libraries (e.g., +<filename>libHSfoo.a</filename> and +<filename>libHSfoo_imp.a</filename>. + +Additionally, when the compiler driver is linking in non-static mode, it +will rewrite occurrence of <option>-lHSfoo</option> on the command line to +<option>-lHSfoo_imp</option>. By doing this for you, switching from +non-static to static linking is simply a question of adding +<option>-static</option> to your command line. + +</para> +</listitem> +</itemizedlist> +</para> + +</sect2> + + +<sect2 id="win32-dlls-foreign"> +<title>Making DLLs to be called from other languages</title> + +<para> + +If you want to package up Haskell code to be called from other languages, +such as Visual Basic or C++, there are some extra things it is useful to +know. The dirty details are in the <emphasis>Foreign Function +Interface</emphasis> definition, but it can be tricky to work out how to +combine this with DLL building, so here's an example: + +</para> + +<itemizedlist> + +<listitem> +<para> +Use <literal>foreign export</literal> declarations to export the Haskell +functions you want to call from the outside. For example, + +<programlisting> +module Adder where + +adder :: Int -> Int -> IO Int –– gratuitous use of IO +adder x y = return (x+y) + +foreign export stdcall adder :: Int -> Int -> IO Int +</programlisting> +</para> +</listitem> + +<listitem> +<para> +Compile it up: + +<screen> +ghc -c adder.hs -fglasgow-exts +</screen> + +This will produce two files, adder.o and adder_stub.o +</para> +</listitem> + +<listitem> +<para> +compile up a <function>DllMain()</function> that starts up the Haskell +RTS-––a possible implementation is: + +<programlisting> +#include <windows.h> +#include <Rts.h> + +extern void__stginit_Adder(void); + +static char* args[] = { "ghcDll", NULL }; + /* N.B. argv arrays must end with NULL */ +BOOL +STDCALL +DllMain + ( HANDLE hModule + , DWORD reason + , void* reserved + ) +{ + if (reason == DLL_PROCESS_ATTACH) { + /* By now, the RTS DLL should have been hoisted in, but we need to start it up. */ + startupHaskell(1, args, __stginit_Adder); + return TRUE; + } + return TRUE; +} +</programlisting> + +Here, <literal>Adder</literal> is the name of the root module in the module +tree (as mentioned above, there must be a single root module, and hence a +single module tree in the DLL). + +Compile this up: + +<screen> +ghc -c dllMain.c +</screen> +</para> +</listitem> + +<listitem> +<para> +Construct the DLL: + +<screen> +ghc ––mk-dll -o adder.dll adder.o adder_stub.o dllMain.o +</screen> + +</para> +</listitem> + +<listitem> +<para> +Start using <function>adder</function> from VBA-––here's how I would +<constant>Declare</constant> it: + +<programlisting> +Private Declare Function adder Lib "adder.dll" Alias "adder@8" + (ByVal x As Long, ByVal y As Long) As Long +</programlisting> + +Since this Haskell DLL depends on a couple of the DLLs that come with GHC, +make sure that they are in scope/visible. +</para> + +<para> +Building statically linked DLLs is the same as in the previous section: it +suffices to add <option>-static</option> to the commands used to compile up +the Haskell source and build the DLL. +</para> + +</listitem> + +</itemizedlist> + +</sect2> + +</sect1> +</chapter> + +<!-- Emacs stuff: + ;;; Local Variables: *** + ;;; mode: xml *** + ;;; sgml-parent-document: ("users_guide.xml" "book" "chapter") *** + ;;; End: *** + --> |