More indent fixes to the Normalization chapter.
[matthijs/master-project/report.git] / Chapters / Prototype.tex
1 \chapter[chap:prototype]{Prototype}
2   An important step in this research is the creation of a prototype compiler.
3   Having this prototype allows us to apply the ideas from the previous chapter
4   to actual hardware descriptions and evaluate their usefulness. Having a
5   prototype also helps to find new techniques and test possible
6   interpretations.
7
8   Obviously the prototype was not created after all research
9   ideas were formed, but its implementation has been interleaved with the
10   research itself. Also, the prototype described here is the final version, it
11   has gone through a number of design iterations which we will not completely
12   describe here.
13
14   \section{Choice of language}
15     When implementing this prototype, the first question to ask is: What
16     (functional) language will we use to describe our hardware? (Note that
17     this does not concern the \emph{implementation language} of the compiler,
18     just the language \emph{translated by} the compiler).
19
20     On the highest level, we have two choices:
21
22     \startitemize
23       \item Create a new functional language from scratch. This has the
24       advantage of having a language that contains exactly those elements that
25       are convenient for describing hardware and can contain special
26       constructs that might.
27       \item Use an existing language and create a new backend for it. This has
28       the advantage that existing tools can be reused, which will speed up
29       development.
30     \stopitemize
31
32     Considering that we required a prototype which should be working quickly,
33     and that implementing parsers, semantic checkers and especially
34     typcheckers isn't exactly the core of this research (but it is lots and
35     lots of work!), using an existing language is the obvious choice. This
36     also has the advantage that a large set of language features is available
37     to experiment with and it is easy to find which features apply well and
38     which don't. A possible second prototype could use a custom language with
39     just the useful features (and possibly extra features that are specific to
40     the domain of hardware description as well).
41
42     The second choice is to pick one of the many existing languages. As
43     mentioned before, this language is Haskell.  This choice has not been the
44     result of a thorough comparison of languages, for the simple reason that
45     the requirements on the language were completely unclear at the start of
46     this language. The fact that Haskell is a language with a broad spectrum
47     of features, that it is commonly used in research projects and that the
48     primary compiler, GHC, provides a high level API to its internals, made
49     Haskell an obvious choice.
50
51     TODO: Was Haskell really a good choice? Perhaps say this somewhere else?
52
53     \subsection{Output language or format}
54         VHDL / Verilog / EDIF etc. Why VHDL?
55
56   \section{Prototype design}
57     As stated above, we will use the Glasgow Haskell Compiler (\small{GHC}) to
58     implement our prototype compiler. To understand the design of the
59     compiler, we will first dive into the \small{GHC} compiler a bit. It's
60     compilation consists of the following steps (slightly simplified):
61
62     \startuseMPgraphic{ghc-pipeline}
63       % Create objects
64       save inp, front, desugar, simpl, back, out;
65       newEmptyBox.inp(0,0);
66       newBox.front(btex Parser etex);
67       newBox.desugar(btex Desugarer etex);
68       newBox.simpl(btex Simplifier etex);
69       newBox.back(btex Backend etex);
70       newEmptyBox.out(0,0);
71
72       % Space the boxes evenly
73       inp.c - front.c = front.c - desugar.c = desugar.c - simpl.c 
74         = simpl.c - back.c = back.c - out.c = (0, 1.5cm);
75       out.c = origin;
76
77       % Draw lines between the boxes. We make these lines "deferred" and give
78       % them a name, so we can use ObjLabel to draw a label beside them.
79       ncline.inp(inp)(front) "name(haskell)";
80       ncline.front(front)(desugar) "name(ast)";
81       ncline.desugar(desugar)(simpl) "name(core)";
82       ncline.simpl(simpl)(back) "name(simplcore)";
83       ncline.back(back)(out) "name(native)";
84       ObjLabel.inp(btex Haskell source etex) "labpathname(haskell)", "labdir(rt)";
85       ObjLabel.front(btex Haskell AST etex) "labpathname(ast)", "labdir(rt)";
86       ObjLabel.desugar(btex Core etex) "labpathname(core)", "labdir(rt)";
87       ObjLabel.simpl(btex Simplified core etex) "labpathname(simplcore)", "labdir(rt)";
88       ObjLabel.back(btex Native code etex) "labpathname(native)", "labdir(rt)";
89
90       % Draw the objects (and deferred labels)
91       drawObj (inp, front, desugar, simpl, back, out);
92     \stopuseMPgraphic
93     \placefigure[right]{GHC compiler pipeline}{\useMPgraphic{ghc-pipeline}}
94
95     \startdesc{Frontend}
96       This step takes the Haskell source files and parses them into an
97       abstract syntax tree (\small{AST}). This \small{AST} can express the
98       complete Haskell language and is thus a very complex one (in contrast
99       with the Core \small{AST}, later on). All identifiers in this
100       \small{AST} are resolved by the renamer and all types are checked by the
101       typechecker.
102     \stopdesc
103     \startdesc{Desugaring}
104       This steps takes the full \small{AST} and translates it to the
105       \emph{Core} language. Core is a very small functional language with lazy
106       semantics, that can still express everything Haskell can express. Its
107       simpleness makes Core very suitable for further simplification and
108       translation. Core is the language we will be working on as well.
109     \stopdesc
110     \startdesc{Simplification}
111       Through a number of simplification steps (such as inlining, common
112       subexpression elimination, etc.) the Core program is simplified to make
113       it faster or easier to process further.
114     \stopdesc
115     \startdesc{Backend}
116       This step takes the simplified Core program and generates an actual
117       runnable program for it. This is a big and complicated step we will not
118       discuss it any further, since it is not required for our prototype.
119     \stopdesc
120
121     In this process, there a number of places where we can start our work.
122     Assuming that we don't want to deal with (or modify) parsing, typechecking
123     and other frontend business and that native code isn't really a useful
124     format anymore, we are left with the choice between the full Haskell
125     \small{AST}, or the smaller (simplified) core representation.
126
127     The advantage of taking the full \small{AST} is that the exact structure
128     of the source program is preserved. We can see exactly what the hardware
129     descriiption looks like and which syntax constructs were used. However,
130     the full \small{AST} is a very complicated datastructure. If we are to
131     handle everything it offers, we will quickly get a big compiler.
132
133     Using the core representation gives us a much more compact datastructure
134     (a core expression only uses 9 constructors). Note that this does not mean
135     that the core representation itself is smaller, on the contrary. Since the
136     core language has less constructs, a lot of things will take a larger
137     expression to express.
138
139     However, the fact that the core language is so much smaller, means it is a
140     lot easier to analyze and translate it into something else. For the same
141     reason, \small{GHC} runs its simplifications and optimizations on the core
142     representation as well.
143
144     However, we will use the normal core representation, not the simplified
145     core. Reasons for this are detailed below.
146     
147     The final prototype roughly consists of three steps:
148     
149     \startuseMPgraphic{ghc-pipeline}
150       % Create objects
151       save inp, front, norm, vhdl, out;
152       newEmptyBox.inp(0,0);
153       newBox.front(btex \small{GHC} frontend + desugarer etex);
154       newBox.norm(btex Normalization etex);
155       newBox.vhdl(btex \small{VHDL} generation etex);
156       newEmptyBox.out(0,0);
157
158       % Space the boxes evenly
159       inp.c - front.c = front.c - norm.c = norm.c - vhdl.c 
160         = vhdl.c - out.c = (0, 1.5cm);
161       out.c = origin;
162
163       % Draw lines between the boxes. We make these lines "deferred" and give
164       % them a name, so we can use ObjLabel to draw a label beside them.
165       ncline.inp(inp)(front) "name(haskell)";
166       ncline.front(front)(norm) "name(core)";
167       ncline.norm(norm)(vhdl) "name(normal)";
168       ncline.vhdl(vhdl)(out) "name(vhdl)";
169       ObjLabel.inp(btex Haskell source etex) "labpathname(haskell)", "labdir(rt)";
170       ObjLabel.front(btex Core etex) "labpathname(core)", "labdir(rt)";
171       ObjLabel.norm(btex Normalized core etex) "labpathname(normal)", "labdir(rt)";
172       ObjLabel.vhdl(btex \small{VHDL} description etex) "labpathname(vhdl)", "labdir(rt)";
173
174       % Draw the objects (and deferred labels)
175       drawObj (inp, front, norm, vhdl, out);
176     \stopuseMPgraphic
177     \placefigure[right]{GHC compiler pipeline}{\useMPgraphic{ghc-pipeline}}
178
179     \startdesc{Frontend}
180       This is exactly the frontend and desugarer from the \small{GHC}
181       pipeline, that translates Haskell sources to a core representation.
182     \stopdesc
183     \startdesc{Normalization}
184       This is a step that transforms the core representation into a normal
185       form. This normal form is still expressed in the core language, but has
186       to adhere to an extra set of constraints. This normal form is less
187       expressive than the full core language (e.g., it can have limited higher
188       order expressions, has a specific structure, etc.), but is also very
189       close to directly describing hardware.
190     \stopdesc
191     \startdesc{\small{VHDL} generation}
192       The last step takes the normal formed core representation and generates
193       \small{VHDL} for it. Since the normal form has a specific, hardware-like
194       structure, this final step is very straightforward.
195     \stopdesc
196     
197     The most interesting step in this process is the normalization step. That
198     is where more complicated functional constructs, which have no direct
199     hardware interpretation, are removed and translated into hardware
200     constructs. This step is described in a lot of detail at
201     \in{chapter}[chap:normalization].
202     
203   \section{The Core language}
204     Most of the prototype deals with handling the program in the Core
205     language. In this section we will show what this language looks like and
206     how it works.
207
208     The Core language is a functional language that describes
209     \emph{expressions}. Every identifier used in Core is called a
210     \emph{binder}, since it is bound to a value somewhere. On the highest
211     level, a Core program is a collection of functions, each of which bind a
212     binder (the function name) to an expression (the function value, which has
213     a function type).
214
215     The Core language itself does not prescribe any program structure, only
216     expression structure. In the \small{GHC} compiler, the Haskell module
217     structure is used for the resulting Core code as well. Since this is not
218     so relevant for understanding the Core language or the Normalization
219     process, we'll only look at the Core expression language here.
220
221     Each Core expression consists of one of these possible expressions.
222
223     \startdesc{Variable reference}
224 \startlambda
225 a
226 \stoplambda
227       This is a simple reference to a binder. It's written down as the
228       name of the binder that is being referred to, which should of course be
229       bound in a containing scope (including top level scope, so a reference
230       to a top level function is also a variable reference). Additionally,
231       constructors from algebraic datatypes also become variable references.
232
233       The value of this expression is the value bound to the given binder.
234
235       Each binder also carries around its type, but this is usually not shown
236       in the Core expressions. Occasionally, the type of an entire expression
237       or function is shown for clarity, but this is only informational. In
238       practice, the type of an expression is easily determined from the
239       structure of the expression and the types of the binders and occasional
240       cast expressions. This minimize the amount of bookkeeping needed to keep
241       the typing consistent.
242     \stopdesc
243     \startdesc{Literal}
244 \startlambda
245 10
246 \stoplambda
247       This is a simple literal. Only primitive types are supported, like
248       chars, strings, ints and doubles. The types of these literals are the
249       \quote{primitive} versions, like \lam{Char\#} and \lam{Word\#}, not the
250       normal Haskell versions (but there are builtin conversion functions).
251     \stopdesc
252     \startdesc{Application}
253 \startlambda
254 func arg
255 \stoplambda
256       This is simple function application. Each application consists of two
257       parts: The function part and the argument part. Applications are used
258       for normal function \quote{calls}, but also for applying type
259       abstractions and data constructors.
260       
261       The value of an application is the value of the function part, with the
262       first argument binder bound to the argument part.
263     \stopdesc
264     \startdesc{Lambda abstraction}
265 \startlambda
266 λbndr.body
267 \stoplambda
268       This is the basic lambda abstraction, as it occurs in labmda calculus.
269       It consists of a binder part and a body part.  A lambda abstraction
270       creates a function, that can be applied to an argument. 
271      
272       Note that the body of a lambda abstraction extends all the way to the
273       end of the expression, or the closing bracket surrounding the lambda. In
274       other words, the lambda abstraction \quote{operator} has the lowest
275       priority of all.
276
277       The value of an application is the value of the body part, with the
278       binder bound to the value the entire lambda abstraction is applied to.
279     \stopdesc
280     \startdesc{Non-recursive let expression}
281 \startlambda
282 let bndr = value in body
283 \stoplambda
284       A let expression allows you to bind a binder to some value, while
285       evaluating to some other value (where that binder is in scope). This
286       allows for sharing of subexpressions (you can use a binder twice) and
287       explicit \quote{naming} of arbitrary expressions. Note that the binder
288       is not in scope in the value bound to it, so it's not possible to make
289       recursive definitions with the normal form of the let expression (see
290       the recursive form below).
291
292       Even though this let expression is an extension on the basic lambda
293       calculus, it is easily translated to a lambda abstraction. The let
294       expression above would then become:
295
296 \startlambda
297 (λbndr.body) value
298 \stoplambda
299
300       This notion might be useful for verifying certain properties on
301       transformations, since a lot of verification work has been done on
302       lambda calculus already.
303
304       The value of a let expression is the value of the body part, with the
305       binder bound to the value. 
306     \stopdesc
307     \startdesc{Recursive let expression}
308 \startlambda
309 let 
310   bndr1 = value1
311   \vdots
312   bndrn = valuen
313 in 
314   body
315 \stoplambda
316
317       This is the recursive version of the let expression. In \small{GHC}'s
318       Core implementation, non-recursive and recursive lets are not so
319       distinct as we present them here, but this provides a clearer overview.
320       
321       The main difference with the normal let expression is that each of the
322       binders is in scope in each of the values, in addition to the body. This
323       allows for self-recursive definitions or mutually recursive definitions.
324
325       It should also be possible to express a recursive let using normal
326       lambda calculus, if we use the \emph{least fixed-point operator},
327       \lam{Y}.
328     \stopdesc
329     \startdesc{Case expression}
330 \startlambda
331   case scrut of bndr
332     DEFAULT -> defaultbody
333     C0 bndr0,0 ... bndr0,m -> body0
334     \vdots
335     Cn bndrn,0 ... bndrn,m -> bodyn
336 \stoplambda
337
338 TODO: Define WHNF
339
340     A case expression is the only way in Core to choose between values. A case
341     expression evaluates its scrutinee, which should have an algebraic
342     datatype, into weak head normal form (\small{WHNF}) and (optionally) binds
343     it to \lam{bndr}. It then chooses a body depending on the constructor of
344     its scrutinee. If none of the constructors match, the \lam{DEFAULT}
345     alternative is chosen. 
346     
347     Since we can only match the top level constructor, there can be no overlap
348     in the alternatives and thus order of alternatives is not relevant (though
349     the \lam{DEFAULT} alternative must appear first for implementation
350     efficiency).
351     
352     Any arguments to the constructor in the scrutinee are bound to each of the
353     binders after the constructor and are in scope only in the corresponding
354     body.
355
356     To support strictness, the scrutinee is always evaluated into WHNF, even
357     when there is only a \lam{DEFAULT} alternative. This allows a strict
358     function argument to be written like:
359
360 \startlambda
361 function (case argument of arg
362   DEFAULT -> arg)
363 \stoplambda
364
365     This seems to be the only use for the extra binder to which the scrutinee
366     is bound. When not using strictness annotations (which is rather pointless
367     in hardware descriptions), \small{GHC} seems to never generate any code
368     making use of this binder. The current prototype does not handle it
369     either, which probably means that code using it would break.
370
371     Note that these case statements are less powerful than the full Haskell
372     case statements. In particular, they do not support complex patterns like
373     in Haskell. Only the constructor of an expression can be matched, complex
374     patterns are implemented using multiple nested case expressions.
375
376     Case statements are also used for unpacking of algebraic datatypes, even
377     when there is only a single constructor. For examples, to add the elements
378     of a tuple, the following Core is generated:
379
380 \startlambda
381 sum = λtuple.case tuple of
382   (,) a b -> a + b
383 \stoplambda
384   
385     Here, there is only a single alternative (but no \lam{DEFAULT}
386     alternative, since the single alternative is already exhaustive). When
387     it's body is evaluated, the arguments to the tuple constructor \lam{(,)}
388     (\eg, the elements of the tuple) are bound to \lam{a} and \lam{b}.
389   \stopdesc
390   \startdesc{Cast expression}
391 \startlambda
392 body :: targettype
393 \stoplambda
394     A cast expression allows you to change the type of an expression to an
395     equivalent type. Note that this is not meant to do any actual work, like
396     conversion of data from one format to another, or force a complete type
397     change. Instead, it is meant to change between different representations
398     of the same type, \eg switch between types that are provably equal (but
399     look different).
400     
401     In our hardware descriptions, we typically see casts to change between a
402     Haskell newtype and its contained type, since those are effectively
403     different representations of the same type.
404
405     More complex are types that are proven to be equal by the typechecker,
406     but look different at first glance. To ensure that, once the typechecker
407     has proven equality, this information sticks around, explicit casts are
408     added. In our notation we only write the target type, but in reality a
409     cast expressions carries around a \emph{coercion}, which can be seen as a
410     proof of equality. TODO: Example
411
412     The value of a cast is the value of its body, unchanged. The type of this
413     value is equal to the target type, not the type of its body.
414
415     Note that this syntax is also used sometimes to indicate that a particular
416     expression has a particular type, even when no cast expression is
417     involved. This is then purely informational, since the only elements that
418     are explicitely typed in the Core language are the binder references and
419     cast expressions, the types of all other elements are determined at
420     runtime.
421   \stopdesc
422   \startdesc{Note}
423
424     The Core language in \small{GHC} allows adding \emph{notes}, which serve
425     as hints to the inliner or add custom (string) annotations to a core
426     expression. These shouldn't be generated normally, so these are not
427     handled in any way in the prototype.
428   \stopdesc
429   \startdesc{Type}
430 \startlambda
431 @type
432 \stoplambda
433     It is possibly to use a Core type as a Core expression. This is done to
434     allow for type abstractions and applications to be handled as normal
435     lambda abstractions and applications above. This means that a type
436     expression in Core can only ever occur in the argument position of an
437     application, and only if the type of the function that is applied to
438     expects a type as the first argument. This happens for all polymorphic
439     functions, for example, the \lam{fst} function:
440
441 \startlambda
442 fst :: \forall a. \forall b. (a, b) -> a
443 fst = λtup.case tup of (,) a b -> a
444
445 fstint :: (Int, Int) -> Int
446 fstint = λa.λb.fst @Int @Int a b
447 \stoplambda
448     
449     The type of \lam{fst} has two universally quantified type variables. When
450     \lam{fst} is applied in \lam{fstint}, it is first applied to two types.
451     (which are substitued for \lam{a} and \lam{b} in the type of \lam{fst}, so
452     the type of \lam{fst} actual type of arguments and result can be found:
453     \lam{fst @Int @Int :: (Int, Int) -> Int}).
454   \stopdesc
455
456   TODO: Core type system
457
458   \section[sec:prototype:statetype]{State annotations in Haskell}
459       Ideal: Type synonyms, since there is no additional code overhead for
460       packing and unpacking. Downside: there is no explicit conversion in Core
461       either, so type synonyms tend to get lost in expressions (they can be
462       preserved in binders, but this makes implementation harder, since that
463       statefulness of a value must be manually tracked).
464
465       Less ideal: Newtype. Requires explicit packing and unpacking of function
466       arguments. If you don't unpack substates, there is no overhead for
467       (un)packing substates. This will result in many nested State constructors
468       in a nested state type. \eg: 
469
470   \starttyping
471   State (State Bit, State (State Word, Bit), Word)
472   \stoptyping
473
474       Alternative: Provide different newtypes for input and output state. This
475       makes the code even more explicit, and typechecking can find even more
476       errors. However, this requires defining two type synomyms for each
477       stateful function instead of just one. \eg:
478   \starttyping
479   type AccumStateIn = StateIn Bit
480   type AccumStateOut = StateOut Bit
481   \stoptyping
482       This also increases the possibility of having different input and output
483       states. Checking for identical input and output state types is also
484       harder, since each element in the state must be unpacked and compared
485       separately.
486
487       Alternative: Provide a type for the entire result type of a stateful
488       function, not just the state part. \eg:
489
490   \starttyping
491   newtype Result state result = Result (state, result)
492   \stoptyping
493       
494       This makes it easy to say "Any stateful function must return a
495       \type{Result} type, without having to sort out result from state. However,
496       this either requires a second type for input state (similar to
497       \type{StateIn} / \type{StateOut} above), or requires the compiler to
498       select the right argument for input state by looking at types (which works
499       for complex states, but when that state has the same type as an argument,
500       things get ambiguous) or by selecting a fixed (\eg, the last) argument,
501       which might be limiting.
502
503       \subsubsection{Example}
504       As an example of the used approach, a simple averaging circuit, that lets
505       the accumulation of the inputs be done by a subcomponent.
506
507       \starttyping
508         newtype State s = State s
509
510         type AccumState = State Bit
511         accum :: Word -> AccumState -> (AccumState, Word)
512         accum i (State s) = (State (s + i), s + i)
513
514         type AvgState = (AccumState, Word)
515         avg :: Word -> AvgState -> (AvgState, Word)
516         avg i (State s) = (State s', o)
517           where
518             (accums, count) = s
519             -- Pass our input through the accumulator, which outputs a sum
520             (accums', sum) = accum i accums
521             -- Increment the count (which will be our new state)
522             count' = count + 1
523             -- Compute the average
524             o = sum / count'
525             s' = (accums', count')
526       \stoptyping
527
528       And the normalized, core-like versions:
529
530       \starttyping
531         accum i spacked = res
532           where
533             s = case spacked of (State s) -> s
534             s' = s + i
535             spacked' = State s'
536             o = s + i
537             res = (spacked', o)
538
539         avg i spacked = res
540           where
541             s = case spacked of (State s) -> s
542             accums = case s of (accums, \_) -> accums
543             count = case s of (\_, count) -> count
544             accumres = accum i accums
545             accums' = case accumres of (accums', \_) -> accums'
546             sum = case accumres of (\_, sum) -> sum
547             count' = count + 1
548             o = sum / count'
549             s' = (accums', count')
550             spacked' = State s'
551             res = (spacked', o)
552       \stoptyping
553
554
555
556       As noted above, any component of a function's state that is a substate,
557       \eg passed on as the state of another function, should have no influence
558       on the hardware generated for the calling function. Any state-specific
559       \small{VHDL} for this component can be generated entirely within the called
560       function. So,we can completely leave out substates from any function.
561       
562       From this observation, we might think to remove the substates from a
563       function's states alltogether, and leave only the state components which
564       are actual states of the current function. While doing this would not
565       remove any information needed to generate \small{VHDL} from the function, it would
566       cause the function definition to become invalid (since we won't have any
567       substate to pass to the functions anymore). We could solve the syntactic
568       problems by passing \type{undefined} for state variables, but that would
569       still break the code on the semantic level (\ie, the function would no
570       longer be semantically equivalent to the original input).
571
572       To keep the function definition correct until the very end of the process,
573       we will not deal with (sub)states until we get to the \small{VHDL} generation.
574       Here, we are translating from Core to \small{VHDL}, and we can simply not generate
575       \small{VHDL} for substates, effectively removing the substate components
576       alltogether.
577
578       There are a few important points when ignore substates.
579
580       First, we have to have some definition of "substate". Since any state
581       argument or return value that represents state must be of the \type{State}
582       type, we can simply look at its type. However, we must be careful to
583       ignore only {\em substates}, and not a function's own state.
584
585       In the example above, this means we should remove \type{accums'} from
586       \type{s'}, but not throw away \type{s'} entirely. We should, however,
587       remove \type{s'} from the output port of the function, since the state
588       will be handled by a \small{VHDL} procedure within the function.
589
590       When looking at substates, these can appear in two places: As part of an
591       argument and as part of a return value. As noted above, these substates
592       can only be used in very specific ways.
593
594       \desc{State variables can appear as an argument.} When generating \small{VHDL}, we
595       completely ignore the argument and generate no input port for it.
596
597       \desc{State variables can be extracted from other state variables.} When
598       extracting a state variable from another state variable, this always means
599       we're extracting a substate, which we can ignore. So, we simply generate no
600       \small{VHDL} for any extraction operation that has a state variable as a result.
601
602       \desc{State variables can be passed to functions.} When passing a
603       state variable to a function, this always means we're passing a substate
604       to a subcomponent. The entire argument can simply be ingored in the
605       resulting port map.
606
607       \desc{State variables can be returned from functions.} When returning a
608       state variable from a function (probably as a part of an algebraic
609       datatype), this always mean we're returning a substate from a
610       subcomponent. The entire state variable should be ignored in the resulting
611       port map. The type binder of the binder that the function call is bound
612       to should not include the state type either.
613
614       \startdesc{State variables can be inserted into other variables.} When inserting
615       a state variable into another variable (usually by constructing that new
616       variable using its constructor), we can identify two cases: 
617
618       \startitemize
619         \item The state is inserted into another state variable. In this case,
620         the inserted state is a substate, and can be safely left out of the
621         constructed variable.
622         \item The state is inserted into a non-state variable. This happens when
623         building up the return value of a function, where you put state and
624         retsult variables together in an algebraic type (usually a tuple). In
625         this case, we should leave the state variable out as well, since we
626         don't want it to be included as an output port.
627       \stopitemize
628
629       So, in both cases, we can simply leave out the state variable from the
630       resulting value. In the latter case, however, we should generate a state
631       proc instead, which assigns the state variable to the input state variable
632       at each clock tick.
633       \stopdesc
634       
635       \desc{State variables can appear as (part of) a function result.} When
636       generating \small{VHDL}, we can completely ignore any part of a function result
637       that has a state type. If the entire result is a state type, this will
638       mean the entity will not have an output port. Otherwise, the state
639       elements will be removed from the type of the output port.
640
641
642       Now, we know how to handle each use of a state variable separately. If we
643       look at the whole, we can conclude the following:
644
645       \startitemize
646       \item A state unpack operation should not generate any \small{VHDL}. The binder
647       to which the unpacked state is bound should still be declared, this signal
648       will become the register and will hold the current state.
649       \item A state pack operation should not generate any \small{VHDL}. The binder th
650       which the packed state is bound should not be declared. The binder that is
651       packed is the signal that will hold the new state.
652       \item Any values of a State type should not be translated to \small{VHDL}. In
653       particular, State elements should be removed from tuples (and other
654       datatypes) and arguments with a state type should not generate ports.
655       \item To make the state actually work, a simple \small{VHDL} proc should be
656       generated. This proc updates the state at every clockcycle, by assigning
657       the new state to the current state. This will be recognized by synthesis
658       tools as a register specification.
659       \stopitemize
660
661
662       When applying these rules to the example program (in normal form), we will
663       get the following result. All the parts that don't generate any value are
664       crossed out, leaving some very boring assignments here and there.
665       
666     
667   \starthaskell
668     avg i --spacked-- = res
669       where
670         s = --case spacked of (State s) -> s--
671         --accums = case s of (accums, \_) -> accums--
672         count = case s of (--\_,-- count) -> count
673         accumres = accum i --accums--
674         --accums' = case accumres of (accums', \_) -> accums'--
675         sum = case accumres of (--\_,-- sum) -> sum
676         count' = count + 1
677         o = sum / count'
678         s' = (--accums',-- count')
679         --spacked' = State s'--
680         res = (--spacked',-- o)
681   \stophaskell
682           
683       When we would really leave out the crossed out parts, we get a slightly
684       weird program: There is a variable \type{s} which has no value, and there
685       is a variable \type{s'} that is never used. Together, these two will form
686       the state proc of the function. \type{s} contains the "current" state,
687       \type{s'} is assigned the "next" state. So, at the end of each clock
688       cycle, \type{s'} should be assigned to \type{s}.
689
690       Note that the definition of \type{s'} is not removed, even though one
691       might think it as having a state type. Since the state type has a single
692       argument constructor \type{State}, some type that should be the resulting
693       state should always be explicitly packed with the State constructor,
694       allowing us to remove the packed version, but still generate \small{VHDL} for the
695       unpacked version (of course with any substates removed).
696       
697       As you can see, the definition of \type{s'} is still present, since it
698       does not have a state type (The State constructor. The \type{accums'} substate has been removed,
699       leaving us just with the state of \type{avg} itself.
700     \subsection{Initial state}
701       How to specify the initial state? Cannot be done inside a hardware
702       function, since the initial state is its own state argument for the first
703       call (unless you add an explicit, synchronous reset port).
704
705       External init state is natural for simulation.
706
707       External init state works for hardware generation as well.
708
709       Implementation issues: state splitting, linking input to output state,
710       checking usage constraints on state variables.
711
712         Implementation issues
713           \subsection[sec:prototype:separate]{Separate compilation}
714           - Simplified core?
715
716   \section{Haskell language coverage and constraints}
717     Recursion
718     Builtin types
719     Custom types (Sum types, product types)
720     Function types / higher order expressions