Improve documentation for Template Haskell
[ghc-hetmet.git] / docs / users_guide / glasgow_exts.xml
index 2857858..da6a125 100644 (file)
@@ -769,7 +769,7 @@ Furthermore, the Control.Monad.ST and Control.Monad.ST.Lazy modules provide the
 for Haskell's internal state monad (strict and lazy, respectively).
 </para>
 <para>
-There are three important points in using the recursive-do notation:
+Here are some 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
@@ -777,7 +777,21 @@ than <literal>do</literal>).
 </para></listitem>
 
 <listitem><para>
-As with other extensions, ghc should be given the flag <literal>-fglasgow-exts</literal>
+It is enabled with the flag <literal>-XRecursiveDo</literal>, which is in turn implied by
+<literal>-fglasgow-exts</literal>.
+</para></listitem>
+
+<listitem><para>
+Unlike ordinary do-notation, but like <literal>let</literal> and <literal>where</literal> bindings,
+name shadowing is not allowed; that is, all the names bound in a single <literal>mdo</literal> must
+be distinct (Section 3.3 of the paper).
+</para></listitem>
+
+<listitem><para>
+Variables bound by a <literal>let</literal> statement in an <literal>mdo</literal>
+are monomorphic in the <literal>mdo</literal> (Section 3.1 of the paper).  However
+GHC breaks the <literal>mdo</literal> into segments to enhance polymorphism,
+and improve termination (Section 3.2 of the paper).
 </para></listitem>
 </itemizedlist>
 </para>
@@ -1902,9 +1916,77 @@ their selector functions actually have different types:
 </para>
 
 </sect2>
+</sect1>
 
 <!-- ====================== End of Generalised algebraic data types =======================  -->
 
+<sect1 id="deriving">
+<title>Extensions to the "deriving" mechanism</title>
+
+<sect2 id="deriving-inferred">
+<title>Inferred context for deriving clauses</title>
+
+<para>
+The Haskell Report is vague about exactly when a <literal>deriving</literal> clause is
+legal.  For example:
+<programlisting>
+  data T0 f a = MkT0 a         deriving( Eq )
+  data T1 f a = MkT1 (f a)     deriving( Eq )
+  data T2 f a = MkT2 (f (f a)) deriving( Eq )
+</programlisting>
+The natural generated <literal>Eq</literal> code would result in these instance declarations:
+<programlisting>
+  instance Eq a         => Eq (T0 f a) where ...
+  instance Eq (f a)     => Eq (T1 f a) where ...
+  instance Eq (f (f a)) => Eq (T2 f a) where ...
+</programlisting>
+The first of these is obviously fine. The second is still fine, although less obviously. 
+The third is not Haskell 98, and risks losing termination of instances.
+</para>
+<para>
+GHC takes a conservative position: it accepts the first two, but not the third.  The  rule is this:
+each constraint in the inferred instance context must consist only of type variables, 
+with no repititions.
+</para>
+<para>
+This rule is applied regardless of flags.  If you want a more exotic context, you can write
+it yourself, using the <link linkend="stand-alone-deriving">standalone deriving mechanism</link>.
+</para>
+</sect2>
+
+<sect2 id="stand-alone-deriving">
+<title>Stand-alone deriving declarations</title>
+
+<para>
+GHC now allows stand-alone <literal>deriving</literal> declarations, enabled by <literal>-XStandaloneDeriving</literal>:
+<programlisting>
+  data Foo a = Bar a | Baz String
+
+  deriving instance Eq a => Eq (Foo a)
+</programlisting>
+The syntax is identical to that of an ordinary instance declaration apart from (a) the keyword
+<literal>deriving</literal>, and (b) the absence of the <literal>where</literal> part.
+You must supply a context (in the example the context is <literal>(Eq a)</literal>), 
+exactly as you would in an ordinary instance declaration.
+(In contrast the context is inferred in a <literal>deriving</literal> clause 
+attached to a data type declaration.) These <literal>deriving instance</literal>
+rules obey the same rules concerning form and termination as ordinary instance declarations,
+controlled by the same flags; see <xref linkend="instance-decls"/>. </para>
+
+<para>The stand-alone syntax is generalised for newtypes in exactly the same
+way that ordinary <literal>deriving</literal> clauses are generalised (<xref linkend="newtype-deriving"/>).
+For example:
+<programlisting>
+  newtype Foo a = MkFoo (State Int a)
+
+  deriving instance MonadState Int Foo
+</programlisting>
+GHC always treats the <emphasis>last</emphasis> parameter of the instance
+(<literal>Foo</literal> in this exmample) as the type whose instance is being derived.
+</para>
+
+</sect2>
+
 
 <sect2 id="deriving-typeable">
 <title>Deriving clause for classes <literal>Typeable</literal> and <literal>Data</literal></title>
@@ -1918,7 +2000,7 @@ classes <literal>Eq</literal>, <literal>Ord</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):
+(provided the <option>-XDeriveDataTypeable</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.
@@ -1972,7 +2054,9 @@ dictionary, only slower!
 
 <sect3> <title> Generalising the deriving clause </title>
 <para>
-GHC now permits such instances to be derived instead, so one can write 
+GHC now permits such instances to be derived instead, 
+using the flag <option>-XGeneralizedNewtypeDeriving</option>,
+so one can write 
 <programlisting> 
   newtype Dollars = Dollars Int deriving (Eq,Show,Num)
 </programlisting> 
@@ -2018,7 +2102,7 @@ In this case the derived instance declaration is of the form
 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
+"eta-converted" to generate the context of the instance
 declaration.
 </para>
 <para>
@@ -2134,41 +2218,13 @@ and <literal>Data</literal>, for which the built-in derivation applies (section
 the standard method is used or the one described here.)
 </para>
 </sect3>
-
-</sect2>
-
-<sect2 id="stand-alone-deriving">
-<title>Stand-alone deriving declarations</title>
-
-<para>
-GHC now allows stand-alone <literal>deriving</literal> declarations, enabled by <literal>-fglasgow-exts</literal>:
-<programlisting>
-  data Foo a = Bar a | Baz String
-
-  derive instance Eq (Foo a)
-</programlisting>
-The token "<literal>derive</literal>" is a keyword only when followed by "<literal>instance</literal>";
-you can use it as a variable name elsewhere.</para>
-<para>The stand-alone syntax is generalised for newtypes in exactly the same
-way that ordinary <literal>deriving</literal> clauses are generalised (<xref linkend="newtype-deriving"/>).
-For example:
-<programlisting>
-  newtype Foo a = MkFoo (State Int a)
-
-  derive instance MonadState Int Foo
-</programlisting>
-GHC always treats the <emphasis>last</emphasis> parameter of the instance
-(<literal>Foo</literal> in this exmample) as the type whose instance is being derived.
-</para>
-
 </sect2>
-
 </sect1>
 
 
 <!-- TYPE SYSTEM EXTENSIONS -->
-<sect1 id="other-type-extensions">
-<title>Other type system extensions</title>
+<sect1 id="type-class-extensions">
+<title>Class and instances declarations</title>
 
 <sect2 id="multi-param-type-classes">
 <title>Class declarations</title>
@@ -2926,6 +2982,86 @@ reversed, but it makes sense to me.
 
 </sect2>
 
+<sect2 id="overloaded-strings">
+<title>Overloaded string literals
+</title>
+
+<para>
+GHC supports <emphasis>overloaded string literals</emphasis>.  Normally a
+string literal has type <literal>String</literal>, but with overloaded string
+literals enabled (with <literal>-XOverloadedStrings</literal>)
+ a string literal has type <literal>(IsString a) => a</literal>.
+</para>
+<para>
+This means that the usual string syntax can be used, e.g., for packed strings
+and other variations of string like types.  String literals behave very much
+like integer literals, i.e., they can be used in both expressions and patterns.
+If used in a pattern the literal with be replaced by an equality test, in the same
+way as an integer literal is.
+</para>
+<para>
+The class <literal>IsString</literal> is defined as:
+<programlisting>
+class IsString a where
+    fromString :: String -> a
+</programlisting>
+The only predefined instance is the obvious one to make strings work as usual:
+<programlisting>
+instance IsString [Char] where
+    fromString cs = cs
+</programlisting>
+The class <literal>IsString</literal> is not in scope by default.  If you want to mention
+it explicitly (for exmaple, to give an instance declaration for it), you can import it
+from module <literal>GHC.Exts</literal>.
+</para>
+<para>
+Haskell's defaulting mechanism is extended to cover string literals, when <option>-XOverloadedStrings</option> is specified.
+Specifically:
+<itemizedlist>
+<listitem><para>
+Each type in a default declaration must be an 
+instance of <literal>Num</literal> <emphasis>or</emphasis> of <literal>IsString</literal>.
+</para></listitem>
+
+<listitem><para>
+The standard defaulting rule (<ulink url="http://haskell.org/onlinereport/decls.html#sect4.3.4">Haskell Report, Section 4.3.4</ulink>)
+is extended thus: defaulting applies when all the unresolved constraints involve standard classes
+<emphasis>or</emphasis> <literal>IsString</literal>; and at least one is a numeric class
+<emphasis>or</emphasis> <literal>IsString</literal>.
+</para></listitem>
+</itemizedlist>
+</para>
+<para>
+A small example:
+<programlisting>
+module Main where
+
+import GHC.Exts( IsString(..) )
+
+newtype MyString = MyString String deriving (Eq, Show)
+instance IsString MyString where
+    fromString = MyString
+
+greet :: MyString -> MyString
+greet "hello" = "world"
+greet other = other
+
+main = do
+    print $ greet "hello"
+    print $ greet "fool"
+</programlisting>
+</para>
+<para>
+Note that deriving <literal>Eq</literal> is necessary for the pattern matching
+to work since it gets translated into an equality comparison.
+</para>
+</sect2>
+
+</sect1>
+
+<sect1 id="other-type-extensions">
+<title>Other type system extensions</title>
+
 <sect2 id="type-restrictions">
 <title>Type signatures</title>
 
@@ -4141,81 +4277,6 @@ pattern binding must have the same context.  For example, this is fine:
 </para>
 </sect2>
 
-<sect2 id="overloaded-strings">
-<title>Overloaded string literals
-</title>
-
-<para>
-GHC supports <emphasis>overloaded string literals</emphasis>.  Normally a
-string literal has type <literal>String</literal>, but with overloaded string
-literals enabled (with <literal>-XOverloadedStrings</literal>)
- a string literal has type <literal>(IsString a) => a</literal>.
-</para>
-<para>
-This means that the usual string syntax can be used, e.g., for packed strings
-and other variations of string like types.  String literals behave very much
-like integer literals, i.e., they can be used in both expressions and patterns.
-If used in a pattern the literal with be replaced by an equality test, in the same
-way as an integer literal is.
-</para>
-<para>
-The class <literal>IsString</literal> is defined as:
-<programlisting>
-class IsString a where
-    fromString :: String -> a
-</programlisting>
-The only predefined instance is the obvious one to make strings work as usual:
-<programlisting>
-instance IsString [Char] where
-    fromString cs = cs
-</programlisting>
-The class <literal>IsString</literal> is not in scope by default.  If you want to mention
-it explicitly (for exmaple, to give an instance declaration for it), you can import it
-from module <literal>GHC.Exts</literal>.
-</para>
-<para>
-Haskell's defaulting mechanism is extended to cover string literals, when <option>-XOverloadedStrings</option> is specified.
-Specifically:
-<itemizedlist>
-<listitem><para>
-Each type in a default declaration must be an 
-instance of <literal>Num</literal> <emphasis>or</emphasis> of <literal>IsString</literal>.
-</para></listitem>
-
-<listitem><para>
-The standard defaulting rule (<ulink url="http://haskell.org/onlinereport/decls.html#sect4.3.4">Haskell Report, Section 4.3.4</ulink>)
-is extended thus: defaulting applies when all the unresolved constraints involve standard classes
-<emphasis>or</emphasis> <literal>IsString</literal>; and at least one is a numeric class
-<emphasis>or</emphasis> <literal>IsString</literal>.
-</para></listitem>
-</itemizedlist>
-</para>
-<para>
-A small example:
-<programlisting>
-module Main where
-
-import GHC.Exts( IsString(..) )
-
-newtype MyString = MyString String deriving (Eq, Show)
-instance IsString MyString where
-    fromString = MyString
-
-greet :: MyString -> MyString
-greet "hello" = "world"
-greet other = other
-
-main = do
-    print $ greet "hello"
-    print $ greet "fool"
-</programlisting>
-</para>
-<para>
-Note that deriving <literal>Eq</literal> is necessary for the pattern matching
-to work since it gets translated into an equality comparison.
-</para>
-</sect2>
-
 <sect2 id="type-families">
 <title>Type families
 </title>
@@ -4261,24 +4322,27 @@ Template Meta-programming for Haskell</ulink>" (Proc Haskell Workshop 2002).
 <para>
 There is a Wiki page about
 Template Haskell at <ulink url="http://haskell.org/haskellwiki/Template_Haskell">
-http://www.haskell.org/th/</ulink>, and that is the best place to look for
+http://www.haskell.org/haskellwiki/Template_Haskell</ulink>, and that is the best place to look for
 further details.
 You may also 
 consult the <ulink
 url="http://www.haskell.org/ghc/docs/latest/html/libraries/index.html">online
 Haskell 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.6.]
+(look for module <literal>Language.Haskell.TH</literal>).
+Many changes to the original design are described in 
+      <ulink url="http://research.microsoft.com/~simonpj/papers/meta-haskell/notes2.ps">
+Notes on Template Haskell version 2</ulink>.
+Not all of these changes are in GHC, however.
 </para>
 
-<para> The first example from that paper is set out below as a worked example to help get you started. 
+<para> The first example from that paper is set out below (<xref linkend="th-example"/>) 
+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.)
+The documentation here describes the realisation of Template Haskell in GHC.  It is not detailed enough to 
+understand Template Haskell; see the <ulink url="http://haskell.org/haskellwiki/Template_Haskell">
+Wiki page</ulink>.
 </para>
 
     <sect2>
@@ -4304,41 +4368,47 @@ Tim Sheard is going to expand it.)
                  <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>
+                   <listitem><para> a list of top-level declarations; the spliced expression must have type <literal>Q [Dec]</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>
+               </para>
+           Inside a splice you can can only call functions defined in imported modules,
+       not functions defined elsewhere in the same module.</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>
+                             the quotation has type <literal>Q Exp</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> <literal>[t| ... |]</literal>, where the "..." is a type;
-                             the quotation has type <literal>Type</literal>.</para></listitem>
+                             the quotation has type <literal>Q Typ</literal>.</para></listitem>
                  </itemizedlist></para></listitem>
 
              <listitem><para>
-                 Reification is written thus:
+                 A name can be quoted with either one or two prefix single quotes:
                  <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><para> <literal>'f</literal> has type <literal>Name</literal>, and names the function <literal>f</literal>.
+                 Similarly <literal>'C</literal> has type <literal>Name</literal> and names the data constructor <literal>C</literal>.
+                 In general <literal>'</literal><replaceable>thing</replaceable> interprets <replaceable>thing</replaceable> in an expression context.
+                    </para></listitem> 
+                   <listitem><para> <literal>''T</literal> has type <literal>Name</literal>, and names the type constructor  <literal>T</literal>.
+                 That is, <literal>''</literal><replaceable>thing</replaceable> interprets <replaceable>thing</replaceable> in a type context.
+                    </para></listitem> 
+                 </itemizedlist>
+                 These <literal>Names</literal> can be used to construct Template Haskell expressions, patterns, delarations etc.  They
+                 may also be given as an argument to the <literal>reify</literal> function.
+                </para>
                </listitem>
 
                  
        </itemizedlist>
+(Compared to the original paper, there are many differnces of detail.
+The syntax for a declaration splice uses "<literal>$</literal>" not "<literal>splice</literal>".
+The type of the enclosed expression must be  <literal>Q [Dec]</literal>, not  <literal>[Q Dec]</literal>.
+Type splices are not implemented, and neither are pattern splices or quotations.
+
 </sect2>
 
 <sect2>  <title> Using Template Haskell </title>
@@ -4381,7 +4451,7 @@ Tim Sheard is going to expand it.)
 </para>
 </sect2>
  
-<sect2>  <title> A Template Haskell Worked Example </title>
+<sect2 id="th-example">  <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>
 
@@ -4421,15 +4491,15 @@ 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 :: [Format] -> Q Exp
 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)
+pr :: String -> Q Exp
+pr s = gen (parse s)
 </programlisting>
 
 <para>Now run the compiler (here we are a Cygwin prompt on Windows):