Fix a lot of things following from Jan's comments.
[matthijs/master-project/report.git] / Chapters / Normalization.tex
index 0700b3acb044d0f4ac7929d0fbddde318f169295..f11788f4348fff5082a7a79bc5290057489b50d1 100644 (file)
   The first step in the core to \small{VHDL} translation process, is normalization. We
   aim to bring the core description into a simpler form, which we can
   subsequently translate into \small{VHDL} easily. This normal form is needed because
-  the full core language is more expressive than \small{VHDL} in some areas and because
-  core can describe expressions that do not have a direct hardware
-  interpretation.
+  the full core language is more expressive than \small{VHDL} in some
+  areas (higher order expressions, limited polymorphism using type
+  classes, etc.) and because core can describe expressions that do not
+  have a direct hardware interpretation.
 
   \section{Normal form}
     The transformations described here have a well-defined goal: To bring the
-    program in a well-defined form that is directly translatable to hardware,
-    while fully preserving the semantics of the program. We refer to this form as
-    the \emph{normal form} of the program. The formal definition of this normal
-    form is quite simple:
+    program in a well-defined form that is directly translatable to
+    \VHDL, while fully preserving the semantics of the program. We refer
+    to this form as the \emph{normal form} of the program. The formal
+    definition of this normal form is quite simple:
 
-    \placedefinition{}{A program is in \emph{normal form} if none of the
-    transformations from this chapter apply.}
+    \placedefinition{}{\startboxed A program is in \emph{normal form} if none of the
+    transformations from this chapter apply.\stopboxed}
 
     Of course, this is an \quote{easy} definition of the normal form, since our
     program will end up in normal form automatically. The more interesting part is
       can't generate any signals that can have multiple types. All types must be
       completely known to generate hardware.
       
-      \item Any \emph{higher order} constructions must be removed. We can't
+      \item All \emph{higher order} constructions must be removed. We can't
       generate a hardware signal that contains a function, so all values,
-      arguments and returns values used must be first order.
+      arguments and return values used must be first order.
 
-      \item Any complex \emph{nested scopes} must be removed. In the \small{VHDL}
+      \item All complex \emph{nested scopes} must be removed. In the \small{VHDL}
       description, every signal is in a single scope. Also, full expressions are
       not supported everywhere (in particular port maps can only map signal
       names and constants, not complete expressions). To make the \small{VHDL}
 
     A very simple example of a program in normal form is given in
     \in{example}[ex:MulSum]. As you can see, all arguments to the function (which
-    will become input ports in the final hardware) are at the outer level.
+    will become input ports in the generated \VHDL) are at the outer level.
     This means that the body of the inner lambda abstraction is never a
     function, but always a plain value.
 
     As the body of the inner lambda abstraction, we see a single (recursive)
     let expression, that binds two variables (\lam{mul} and \lam{sum}). These
-    variables will be signals in the final hardware, bound to the output port
+    variables will be signals in the generated \VHDL, bound to the output port
     of the \lam{*} and \lam{+} components.
 
     The final line (the \quote{return value} of the function) selects the
       newCircle.a(btex $a$ etex) "framed(false)";
       newCircle.b(btex $b$ etex) "framed(false)";
       newCircle.c(btex $c$ etex) "framed(false)";
-      newCircle.sum(btex $res$ etex) "framed(false)";
+      newCircle.sum(btex $sum$ etex) "framed(false)";
 
       % Components
       newCircle.mul(btex * etex);
         {\boxedgraphic{MulSum}}{The architecture described by the normal form.}
       \stopcombination
 
-    The previous example described composing an architecture by calling other
-    functions (operators), resulting in a simple architecture with components and
-    connections. There is of course also some mechanism for choice in the normal
-    form. In a normal Core program, the \emph{case} expression can be used in a
-    few different ways to describe choice. In normal form, this is limited to a
-    very specific form.
+    \in{Example}[ex:MulSum] showed a function that just applied two
+    other functions (multiplication and addition), resulting in a simple
+    architecture with two components and some connections.  There is of
+    course also some mechanism for choice in the normal form. In a
+    normal Core program, the \emph{case} expression can be used in a few
+    different ways to describe choice. In normal form, this is limited
+    to a very specific form.
 
     \in{Example}[ex:AddSubAlu] shows an example describing a
     simple \small{ALU}, which chooses between two operations based on an opcode
     expression scrutinizes the variable \lam{opcode} (and scrutinizing more
     complex expressions is not supported). The case expression can select a
     different variable based on the constructor of \lam{opcode}.
+    \refdef{case expression}
 
     \startbuffer[AddSubAlu]
     alu :: Bit -> Word -> Word -> Word
         {\boxedgraphic{AddSubAlu}}{The architecture described by the normal form.}
       \stopcombination
 
-    As a more complete example, consider \in{example}[ex:NormalComplete]. This
-    example contains everything that is supported in normal form, with the
-    exception of builtin higher order functions. The graphical version of the
-    architecture contains a slightly simplified version, since the state tuple
-    packing and unpacking have been left out. Instead, two seperate registers are
-    drawn. Also note that most synthesis tools will further optimize this
-    architecture by removing the multiplexers at the register input and
-    instead put some gates in front of the register's clock input, but we want
-    to show the architecture as close to the description as possible.
+    As a more complete example, consider
+    \in{example}[ex:NormalComplete]. This example shows everything that
+    is allowed in normal form, except for builtin higher order functions
+    (like \lam{map}). The graphical version of the architecture contains
+    a slightly simplified version, since the state tuple packing and
+    unpacking have been left out. Instead, two separate registers are
+    drawn. Also note that most synthesis tools will further optimize
+    this architecture by removing the multiplexers at the register input
+    and instead put some gates in front of the register's clock input,
+    but we want to show the architecture as close to the description as
+    possible.
 
     As you can see from the previous examples, the generation of the final
     architecture from the normal form is straightforward. In each of the
     \subsection[sec:normalization:intendednormalform]{Intended normal form definition}
       Now we have some intuition for the normal form, we can describe how we want
       the normal form to look like in a slightly more formal manner. The following
-      EBNF-like description completely captures the intended structure (and
-      generates a subset of GHC's core format).
-
-      Some clauses have an expression listed in parentheses. These are conditions
-      that need to apply to the clause.
+      EBNF-like description captures most of the intended structure (and
+      generates a subset of GHC's core format). 
+      
+      There are two things missing: Cast expressions are sometimes
+      allowed by the prototype, but not specified here and the below
+      definition allows uses of state that cannot be translated to \VHDL
+      properly. These two problems are discussed in
+      \in{section}[sec:normalization:castproblems] and
+      \in{section}[sec:normalization:stateproblems] respectively.
+
+      Some clauses have an expression listed behind them in parentheses.
+      These are conditions that need to apply to the clause. The
+      predicates used there (\lam{lvar()}, \lam{representable()},
+      \lam{gvar()}) will be defined in
+      \in{section}[sec:normalization:predicates].
+
+      An expression is in normal form if it matches the first
+      definition, \emph{normal}.
 
-      \defref{intended normal form definition}
       \todo{Fix indentation}
-      \startlambda
+      \startbuffer[IntendedNormal]
       \italic{normal} := \italic{lambda}
-      \italic{lambda} := λvar.\italic{lambda} (representable(var))
+      \italic{lambda} := λvar.\italic{lambda}                        (representable(var))
                       | \italic{toplet} 
-      \italic{toplet} := letrec [\italic{binding}...] in var (representable(var))
-      \italic{binding} := var = \italic{rhs} (representable(rhs))
+      \italic{toplet} := letrec [\italic{binding}...] in var         (representable(var))
+      \italic{binding} := var = \italic{rhs}                         (representable(rhs))
                        -- State packing and unpacking by coercion
-                       | var0 = var1 ▶ State ty (lvar(var1))
-                       | var0 = var1 ▶ ty (var1 :: State ty ∧ lvar(var1))
-      \italic{rhs} := userapp
-                   | builtinapp
+                       | var0 = var1 ▶ State ty                      (lvar(var1))
+                       | var0 = var1 ▶ ty                            (var1 :: State ty ∧ lvar(var1))
+      \italic{rhs} := \italic{userapp}
+                   | \italic{builtinapp}
                    -- Extractor case
-                   | case var of C a0 ... an -> ai (lvar(var))
+                   | case var of C a0 ... an -> ai                   (lvar(var))
                    -- Selector case
-                   | case var of (lvar(var))
-                      [ DEFAULT -> var ]  (lvar(var))
+                   | case var of                                     (lvar(var))
+                      [ DEFAULT -> var ]                             (lvar(var))
                       C0 w0,0 ... w0,n -> var0
                       \vdots
-                      Cm wm,0 ... wm,n -> varm       (\forall{}i \forall{}j, wi,j \neq vari, lvar(vari))
+                      Cm wm,0 ... wm,n -> varm                       (\forall{}i \forall{}j, wi,j \neq vari, lvar(vari))
       \italic{userapp} := \italic{userfunc}
                        | \italic{userapp} {userarg}
-      \italic{userfunc} := var (gvar(var))
-      \italic{userarg} := var (lvar(var))
+      \italic{userfunc} := var                                       (gvar(var))
+      \italic{userarg} := var                                        (lvar(var))
       \italic{builtinapp} := \italic{builtinfunc}
                           | \italic{builtinapp} \italic{builtinarg}
-      \italic{builtinfunc} := var (bvar(var))
-      \italic{builtinarg} := var (representable(var) ∧ lvar(var))
-                          | \italic{partapp} (partapp :: a -> b)
-                          | \italic{coreexpr} (¬representable(coreexpr) ∧ ¬(coreexpr :: a -> b))
-      \italic{partapp} := \italic{userapp} | \italic{builtinapp}
-      \stoplambda
-
-      \todo{There can still be other casts around (which the code can handle,
-      e.g., ignore), which still need to be documented here}
+      \italic{builtinfunc} := var                                    (bvar(var))
+      \italic{builtinarg} := var                                     (representable(var) ∧ lvar(var))
+                          | \italic{partapp}                         (partapp :: a -> b)
+                          | \italic{coreexpr}                        (¬representable(coreexpr) ∧ ¬(coreexpr :: a -> b))
+      \italic{partapp} := \italic{userapp} 
+                       | \italic{builtinapp}
+      \stopbuffer
 
-      When looking at such a program from a hardware perspective, the top level
-      lambda's define the input ports. The variable reference in the body of
-      the recursive let expression is the output port. Most function
-      applications bound by the let expression define a component
-      instantiation, where the input and output ports are mapped to local
-      signals or arguments. Some of the others use a builtin construction (\eg
-      the \lam{case} expression) or call a builtin function (\eg \lam{+} or
-      \lam{map}). For these, a hardcoded \small{VHDL} translation is
-      available.
+      \placedefinition[][def:IntendedNormal]{Definition of the intended nnormal form using an \small{EBNF}-like syntax.}
+          {\defref{intended normal form definition}
+           \typebufferlam{IntendedNormal}}
+
+      When looking at such a program from a hardware perspective, the
+      top level lambda abstractions define the input ports. Lambda
+      abstractions cannot appear anywhere else. The variable reference
+      in the body of the recursive let expression is the output port.
+      Most function applications bound by the let expression define a
+      component instantiation, where the input and output ports are
+      mapped to local signals or arguments. Some of the others use a
+      builtin construction (\eg the \lam{case} expression) or call a
+      builtin function (\eg \lam{+} or \lam{map}). For these, a
+      hardcoded \small{VHDL} translation is available.
 
   \section[sec:normalization:transformation]{Transformation notation}
     To be able to concisely present transformations, we use a specific format
 
     This format desribes a transformation that applies to \lam{<original
     expresssion>} and transforms it into \lam{<transformed expression>}, assuming
-    that all conditions apply. In this format, there are a number of placeholders
+    that all conditions are satisfied. In this format, there are a number of placeholders
     in pointy brackets, most of which should be rather obvious in their meaning.
     Nevertheless, we will more precisely specify their meaning below:
 
       transformation applies, commonly to prevent a transformation from
       causing a loop with itself or another transformation.
 
-      Only if these conditions are \emph{all} true, the transformation
+      Only if these conditions are \emph{all} satisfied, the transformation
       applies.
       \stopdesc
 
       \startdesc{<transformed expression>}
       This is the expression template that is the result of the transformation. If, looking
       at the above three items, the transformation applies, the \lam{<original
-      expression>} is completely replaced with the \lam{<transformed expression>}.
+      expression>} is completely replaced by the \lam{<transformed expression>}.
       We call this a template, because it can contain placeholders, referring to
       any placeholder bound by the \lam{<original expression>} or the
       \lam{<context conditions>}. The resulting expression will have those
       \stopdesc
 
       \startdesc{<context additions>}
-      These are templates for new functions to add to the context. This is a way
-      to have a transformation create new top level functions.
+      These are templates for new functions to be added to the context.
+      This is a way to let a transformation create new top level
+      functions.
 
       Each addition has the form \lam{binder = template}. As above, any
       placeholder in the addition is replaced with the value bound to it, and any
       replaced with) a fresh binder.
       \stopdesc
 
-    As an example, we'll look at η-abstraction:
+    To understand this notation better, the step by step application of
+    the η-abstraction transformation to a simple \small{ALU} will be
+    shown. Consider η-abstraction, described using above notation as
+    follows:
 
     \starttrans
     E                 \lam{E :: a -> b}
     transformation does not apply infinitely (which are not necessarily part
     of the conventional definition of η-abstraction).
 
-    Consider the following function, which is a fairly obvious way to specify a
-    simple ALU (Note that \in{example}[ex:AddSubAlu] shows the normal form of this
-    function). The parentheses around the \lam{+} and \lam{-} operators are
-    commonly used in Haskell to show that the operators are used as normal
-    functions, instead of \emph{infix} operators (\eg, the operators appear
-    before their arguments, instead of in between).
+    Consider the following function, in Core notation, which is a fairly obvious way to specify a
+    simple \small{ALU} (Note that it is not yet in normal form, but
+    \in{example}[ex:AddSubAlu] shows the normal form of this function).
+    The parentheses around the \lam{+} and \lam{-} operators are
+    commonly used in Haskell to show that the operators are used as
+    normal functions, instead of \emph{infix} operators (\eg, the
+    operators appear before their arguments, instead of in between).
 
     \startlambda 
     alu :: Bit -> Word -> Word -> Word
     \stoplambda
     
     Here, the transformation does apply, binding \lam{E} to the entire
-    expression and \lam{x} to the fresh binder \lam{b}, resulting in the
-    replacement:
+    expression (which has type \lam{Word -> Word}) and binding \lam{x}
+    to the fresh binder \lam{b}, resulting in the replacement:
 
     \startlambda
     λb.(case opcode of
       High -> (-)) a b
     \stoplambda
 
-    Again, the transformation does not apply to this lambda abstraction, so we
+    The transformation does not apply to this lambda abstraction, so we
     look at its body. For brevity, we'll put the case expression on one line from
     now on.
 
       keep the transformation descriptions concise and powerful.
 
     \subsection{Definitions}
-      In the following sections, we will be using a number of functions and
-      notations, which we will define here.
-
-      \subsubsection{Concepts}
-        A \emph{global variable} is any variable (binder) that is bound at the
-        top level of a program, or an external module. A \emph{local variable} is any
-        other variable (\eg, variables local to a function, which can be bound by
-        lambda abstractions, let expressions and pattern matches of case
-        alternatives).  Note that this is a slightly different notion of global versus
-        local than what \small{GHC} uses internally.
-        \defref{global variable} \defref{local variable}
-
-        A \emph{hardware representable} (or just \emph{representable}) type or value
-        is (a value of) a type that we can generate a signal for in hardware. For
-        example, a bit, a vector of bits, a 32 bit unsigned word, etc. Values that are
-        not runtime representable notably include (but are not limited to): Types,
-        dictionaries, functions.
-        \defref{representable}
-
-        A \emph{builtin function} is a function supplied by the Cλash framework, whose
-        implementation is not valid Cλash. The implementation is of course valid
-        Haskell, for simulation, but it is not expressable in Cλash.
-        \defref{builtin function} \defref{user-defined function}
+      A \emph{global variable} is any variable (binder) that is bound at the
+      top level of a program, or an external module. A \emph{local variable} is any
+      other variable (\eg, variables local to a function, which can be bound by
+      lambda abstractions, let expressions and pattern matches of case
+      alternatives). This is a slightly different notion of global versus
+      local than what \small{GHC} uses internally, but for our purposes
+      the distinction \GHC makes is not useful.
+      \defref{global variable} \defref{local variable}
+
+      A \emph{hardware representable} (or just \emph{representable}) type or value
+      is (a value of) a type that we can generate a signal for in hardware. For
+      example, a bit, a vector of bits, a 32 bit unsigned word, etc. Values that are
+      not runtime representable notably include (but are not limited to): Types,
+      dictionaries, functions.
+      \defref{representable}
+
+      A \emph{builtin function} is a function supplied by the Cλash framework, whose
+      implementation is not valid Cλash. The implementation is of course valid
+      Haskell, for simulation, but it is not expressable in Cλash.
+      \defref{builtin function} \defref{user-defined function}
 
       For these functions, Cλash has a \emph{builtin hardware translation}, so calls
       to these functions can still be translated. These are functions like
       A \emph{user-defined} function is a function for which we do have a Cλash
       implementation available.
 
-      \subsubsection{Predicates}
+      \subsubsection[sec:normalization:predicates]{Predicates}
         Here, we define a number of predicates that can be used below to concisely
-        specify conditions.\refdef{global variable}
+        specify conditions.
 
         \emph{gvar(expr)} is true when \emph{expr} is a variable that references a
         global variable. It is false when it references a local variable.
 
-        \refdef{local variable}\emph{lvar(expr)} is the complement of \emph{gvar}; it is true when \emph{expr}
+        \emph{lvar(expr)} is the complement of \emph{gvar}; it is true when \emph{expr}
         references a local variable, false when it references a global variable.
 
-        \refdef{representable}\emph{representable(expr)} or \emph{representable(var)} is true when
-        \emph{expr} or \emph{var} is \emph{representable}.
+        \emph{representable(expr)} is true when \emph{expr} is \emph{representable}.
 
     \subsection[sec:normalization:uniq]{Binder uniqueness}
       A common problem in transformation systems, is binder uniqueness. When not
       \stoplambda
 
       This is obviously not what was supposed to happen! The root of this problem is
-      the reuse of binders: Identical binders can be bound in different scopes, such
-      that only the inner one is \quote{visible} in the inner expression. In the example
-      above, the \lam{c} binder was bound outside of the expression and in the inner
-      lambda expression. Inside that lambda expression, only the inner \lam{c} is
-      visible.
+      the reuse of binders: Identical binders can be bound in different,
+      but overlapping scopes. Any variable reference in those
+      overlapping scopes then refers to the variable bound in the inner
+      (smallest) scope. There is not way to refer to the variable in the
+      outer scope. This effect is usually referred to as
+      \emph{shadowing}: When a binder is bound in a scope where the
+      binder already had a value, the inner binding is said to
+      \emph{shadow} the outer binding. In the example above, the \lam{c}
+      binder was bound outside of the expression and in the inner lambda
+      expression. Inside that lambda expression, only the inner \lam{c}
+      can be accessed.
 
       There are a number of ways to solve this. \small{GHC} has isolated this
       problem to their binder substitution code, which performs \emph{deshadowing}
         This transformation removes let bindings that are never used.
         Occasionally, \GHC's desugarer introduces some unused let bindings.
 
-        This normalization pass should really be unneeded to get into intended normal form
-        (since unused bindings are not forbidden by the normal form), but in practice
-        the desugarer or simplifier emits some unused bindings that cannot be
-        normalized (e.g., calls to a \type{PatError}\todo{Check this name}). Also,
-        this transformation makes the resulting \small{VHDL} a lot shorter.
+        This normalization pass should really be not be necessary to get
+        into intended normal form (since the intended normal form
+        definition \refdef{intended normal form definition} does not
+        require that every binding is used), but in practice the
+        desugarer or simplifier emits some bindings that cannot be
+        normalized (e.g., calls to a
+        \hs{Control.Exception.Base.patError}) but are not used anywhere
+        either. To prevent the \VHDL generation from breaking on these
+        artifacts, this transformation removes them.
 
         \todo{Don't use old-style numerals in transformations}
         \starttrans
         \todo{Example}
 
       \subsubsection{Cast propagation / simplification}
-        This transform pushes casts down into the expression as far as possible.
-        Since its exact role and need is not clear yet, this transformation is
-        not yet specified.
+        This transform pushes casts down into the expression as far as
+        possible. This transformation has been added to make a few
+        specific corner cases work, but it is not clear yet if this
+        transformation handles cast expressions completely or in the
+        right way. See \in{section}[sec:normalization:castproblems].
 
-        \todo{Cast propagation}
+        \starttrans
+        (let binds in E) ▶ T
+        -------------------------
+        let binds in (E ▶ T)
+        \stoptrans
+
+        \starttrans
+        (case S of
+          p0 -> E0
+          \vdots
+          pn -> En
+        ) ▶ T
+        -------------------------
+        case S of
+          p0 -> E0 ▶ T
+          \vdots
+          pn -> En ▶ T
+        \stoptrans
 
       \subsubsection{Top level binding inlining}
+        \refdef{top level binding}
         This transform takes simple top level bindings generated by the
         \small{GHC} compiler. \small{GHC} sometimes generates very simple
         \quote{wrapper} bindings, which are bound to just a variable
-        reference, or a partial application to constants or other variable
-        references.
+        reference, or contain just a (partial) function appliation with
+        the type and dictionary arguments filled in (such as the
+        \lam{(+)} in the example below).
 
         Note that this transformation is completely optional. It is not
         required to get any function into intended normal form, but it does help making
         the resulting VHDL output easier to read (since it removes a bunch of
         components that are really boring).
 
-        This transform takes any top level binding generated by the compiler,
+        This transform takes any top level binding generated by \GHC,
         whose normalized form contains only a single let binding.
 
         \starttrans
 
         \starttrans
         E                 \lam{E :: a -> b}
-        --------------    \lam{E} is not the first argument of an application.
+        --------------    \lam{E} does not occur on a function position in an application
         λx.E x            \lam{E} is not a lambda abstraction.
-                          \lam{x} is a variable that does not occur free in \lam{E}.
         \stoptrans
 
         \startbuffer[from]
 
         \starttrans
         (case x of
-          p1 -> E1
+          p0 -> E0
           \vdots
           pn -> En) M
         -----------------
         case x of
-          p1 -> E1 M
+          p0 -> E0 M
           \vdots
           pn -> En M
         \stoptrans
         This transformation ensures that the return value of a function is always a
         simple local variable reference.
 
-        Currently implemented using lambda simplification, let simplification, and
-        top simplification. Should change into something like the following, which
-        works only on the result of a function instead of any subexpression. This is
-        achieved by the contexts, like \lam{x = E}, though this is strictly not
-        correct (you could read this as "if there is any function \lam{x} that binds
-        \lam{E}, any \lam{E} can be transformed, while we only mean the \lam{E} that
-        is bound by \lam{x}. This might need some extra notes or something).
-
-        Note that the return value is not simplified if its not representable.
-        Otherwise, this would cause a direct loop with the inlining of
-        unrepresentable bindings. If the return value is not
-        representable because it has a function type, η-abstraction should
-        make sure that this transformation will eventually apply. If the value
-        is not representable for other reasons, the function result itself is
-        not representable, meaning this function is not translatable anyway.
+        This transformation only applies to the entire body of a
+        function instead of any subexpression in a function. This is
+        achieved by the contexts, like \lam{x = E}, though this is
+        strictly not correct (you could read this as "if there is any
+        function \lam{x} that binds \lam{E}, any \lam{E} can be
+        transformed, while we only mean the \lam{E} that is bound by
+        \lam{x}).
+
+        Note that the return value is not simplified if its not
+        representable.  Otherwise, this would cause a direct loop with
+        the inlining of unrepresentable bindings. If the return value is
+        not representable because it has a function type, η-abstraction
+        should make sure that this transformation will eventually apply.
+        If the value is not representable for other reasons, the
+        function result itself is not representable, meaning this
+        function is not translatable anyway.
 
         \starttrans
         x = E                            \lam{E} is representable
           alts
         -----------------        \lam{E} is not a local variable reference
         letrec x = E in 
-          case E of
+          case x of
             alts
         \stoptrans
 
         \transexample{letflat}{Case normalisation}{from}{to}
 
 
-      \subsubsection{Case simplification}
-        This transformation ensures that all case expressions become normal form. This
-        means they will become one of:
+      \subsubsection{Case normalization}
+        This transformation ensures that all case expressions get a form
+        that is allowed by the intended normal form. This means they
+        will become one of: \refdef{intended normal form definition}
         \startitemize
-        \item An extractor case with a single alternative that picks a single field
+        \item An extractor case with a single alternative that picks a field
         from a datatype, \eg \lam{case x of (a, b) -> a}.
         \item A selector case with multiple alternatives and only wild binders, that
         makes a choice between expressions based on the constructor of another
         expression, \eg \lam{case x of Low -> a; High -> b}.
         \stopitemize
+
+        For an arbitrary case, that has \lam{n} alternatives, with
+        \lam{m} binders in each alternatives, this will result in \lam{m
+        * n} extractor case expression to get at each variable, \lam{n}
+        let bindings for each of the alternatives' value and a single
+        selector case to select the right value out of these.
+
+        Technically, the defintion of this transformation would require
+        that the constructor for every alternative has exactly the same
+        amount (\lam{m}) of arguments, but of course this transformation
+        also applies when this is not the case.
         
-        \defref{wild binder}
         \starttrans
         case E of
           C0 v0,0 ... v0,m -> E0
           \vdots
           Cn vn,0 ... vn,m -> En
         --------------------------------------------------- \forall i \forall j, 0 ≤ i ≤ n, 0 ≤ i < m (\lam{wi,j} is a wild (unused) binder)
-        letrec
-          v0,0 = case E of C0 v0,0 .. v0,m -> v0,0
+        letrec                                              The case expression is not an extractor case
+          v0,0 = case E of C0 x0,0 .. x0,m -> x0,0          The case expression is not a selector case
           \vdots
-          v0,m = case E of C0 v0,0 .. v0,m -> v0,m
+          v0,m = case E of C0 x0,0 .. x0,m -> x0,m
           \vdots
-          vn,m = case E of Cn vn,0 .. vn,m -> vn,m
-          x0 = E0
+          vn,m = case E of Cn xn,0 .. xn,m -> xn,m
+          y0 = E0
           \vdots
-          xn = En
+          yn = En
         in
           case E of
-            C0 w0,0 ... w0,m -> x0
+            C0 w0,0 ... w0,m -> y0
             \vdots
-            Cn wn,0 ... wn,m -> xn
+            Cn wn,0 ... wn,m -> yn
         \stoptrans
-        \todo{Check the subscripts of this transformation}
 
+        \refdef{wild binder}
         Note that this transformation applies to case expressions with any
-        scrutinee. If the scrutinee is a complex expression, this might result
-        in duplicate hardware. An extra condition to only apply this
-        transformation when the scrutinee is already simple (effectively
-        causing this transformation to be only applied after the scrutinee
-        simplification transformation) might be in order. 
-
-        \fxnote{This transformation specified like this is complicated and misses
-        conditions to prevent looping with itself. Perhaps it should be split here for
-        discussion?}
+        scrutinee. If the scrutinee is a complex expression, this might
+        result in duplication of work (hardware). An extra condition to
+        only apply this transformation when the scrutinee is already
+        simple (effectively causing this transformation to be only
+        applied after the scrutinee simplification transformation) might
+        be in order. 
 
         \startbuffer[from]
         case a of
         \stopbuffer
 
         \startbuffer[to]
-        letnonrec
+        letrec
           x0 = add b 1
           x1 = add b 2
         in
 
       \subsubsection[sec:transformation:caseremoval]{Case removal}
         This transform removes any case expression with a single alternative and
-        only wild binders.
+        only wild binders.\refdef{wild binder}
 
         These "useless" case expressions are usually leftovers from case simplification
         on extractor case (see the previous example).
         ~
         x Y0 ... Yi ... Yn                               \lam{Yi} is not representable
         ---------------------------------------------    \lam{Yi} is not a local variable reference
-        x' y0 ... yi-1 f0 ...  fm Yi+1 ... Yn            \lam{f0 ... fm} are all free local vars of \lam{Yi}
+        x' Y0 ... Yi-1 f0 ...  fm Yi+1 ... Yn            \lam{f0 ... fm} are all free local vars of \lam{Yi}
         ~                                                \lam{T0 ... Tn} are the types of \lam{Y0 ... Yn}
-        x' = λ(y0 :: T0) ... λ(yi-1 :: Ty-1). λf0 ... λfm. λ(yi+1 :: Ty+1) ...  λ(yn :: Tn).       
-              E y0 ... yi-1 Yi yi+1 ... yn   
+        x' = λ(y0 :: T0) ... λ(yi-1 :: Ty-1). 
+             λf0 ... λfm.
+             λ(yi+1 :: Ty+1) ...  λ(yn :: Tn).       
+               E y0 ... yi-1 Yi yi+1 ... yn   
         \stoptrans
 
         This is a bit of a complex transformation. It transforms an
         from the types of the \emph{actual} arguments (\lam{T0 ... Tn}). This
         means that any polymorphism in the arguments is removed, even when the
         corresponding explicit type lambda is not removed
-        yet.\refdef{type lambda}
+        yet.
 
         \todo{Examples. Perhaps reference the previous sections}
 
         transformation system as well. However, it is likely that there are
         other occurences of this problem.
 
-      \subsection{Casts}
+      \subsection[sec:normalization:castproblems]{Casts}
         We do not fully understand the use of cast expressions in Core, so
         there are probably expressions involving cast expressions that cannot
         be brought into intended normal form by this transformation system.
       \todo{Define β-reduction and η-reduction?}
 
       Note that the normal form of such a system consists of the set of nodes
-      (expressions) without outgoing edges, since those are the expression to which
+      (expressions) without outgoing edges, since those are the expressions to which
       no transformation applies anymore. We call this set of nodes the \emph{normal
       set}. The set of nodes containing expressions in intended normal
       form \refdef{intended normal form} is called the \emph{intended