-%
-%A function call starts by pushing the stack and frame pointer, and making space for the program counter (a) followed by evaluating the arguments in reverse order (b).
-%On executing \Cl{BCJumpSR}, the program counter is set and the interpreter jumps to the function (c).
-%When the function returns, the return value overwrites the old pointers and the arguments.
-%This occurs right after a \Cl{BCReturn} (d).
-%Putting the arguments on top of pointers and not reserving space for the return value uses little space and facilitates tail call optimization.
-%
-%\begin{figure}
-% \subfigure[\Cl{BCPushPtrs}]{\includegraphics[width=.24\linewidth]{memory1}}
-% \subfigure[Arguments]{\includegraphics[width=.24\linewidth]{memory2}}
-% \subfigure[\Cl{BCJumpSR}]{\includegraphics[width=.24\linewidth]{memory3}}
-% \subfigure[\Cl{BCReturn}]{\includegraphics[width=.24\linewidth]{memory4}}
-% \caption{The stack layout during function calls.}
-% \Description{A visual representation of the stack layout during a function call and a return.}
-%\end{figure}
-%
-%Calling a function and referencing function arguments are an extension to $\mathcal{E}$ as shown below.
-%Arguments may be at different places on the stack at different times (see Subsection~\ref{ssec:step}) and therefore the exact location always has to be determined from the context using \Cl{findarg}\footnote{%
-% \lstinline{findarg [l':r] l = if (l == l`) 0 (1 + findarg r l)}
-%}.
-%Compiling argument $a_{f^i}$, the $i$th argument in function $f$, consists of traversing all positions in the current context.
-%Arguments wider than one stack cell are fetched in reverse to preserve the order.
-%
-%\begin{compilationscheme}
-% \cschemeE{f(a_0, \ldots, a_n)}{r} & =
-% \text{\Cl{BCPushPtrs}};\\
-% {} & \mathbin{\phantom{=}} \cschemeE{a_n}{r}; \cschemeE{a_{\ldots}}{r}; \cschemeE{a_0}{r};\\
-% {} & \mathbin{\phantom{=}} \text{\Cl{BCJumpSR}}\enskip n\enskip f;\\
-% \cschemeE{a_{f^i}}{r} & =
-% \text{\Cl{BCArg} findarg}(r, f, i)\enskip \text{for all}\enskip i\in\{w\ldots v\};\\
-% {} & v = \Sigma^{i-1}_{j=0}\|a_{f^j}\|\\
-% {} & w = v + \|a_{f^i}\|\\
-%\end{compilationscheme}
-%
-%Translating the compilation schemes for functions to Clean is not as straightforward as other schemes due to the nature of shallow embedding.
-%The \Cl{fun} class has a single function with a single argument.
-%This argument is a Clean function that---when given a callable Clean function representing the mTask function---will produce \Cl{main} and a callable function.
-%To compile this, the argument must be called with a function representing a function call in mTask.
-%Listing~\ref{lst:fun_imp} shows the implementation for this as Clean code.
-%To uniquely identify the function, a fresh label is generated.
-%The function is then called with the \Cl{callFunction} helper function that generates the instructions that correspond to calling the function.
-%That is, it pushes the pointers, compiles the arguments, and writes the \Cl{JumpSR} instruction.
-%The resulting structure (\Cl{g In m}) contains a function representing the mTask function (\Cl{g}) and the \Cl{main} structure to continue with.
-%To get the actual function, \Cl{g} must be called with representations for the argument, i.e.\ using \Cl{findarg} for all arguments.
-%The arguments are added to the context and \Cl{liftFunction} is called with the label, the argument width and the compiler.
-%This function executes the compiler, decorates the instructions with a label and places them in the function dictionary together with the metadata such as the argument width.
-%After lifting the function, the context is cleared again and compilation continues with the rest of the program.
-%
-%\begin{lstlisting}[language=Clean,label={lst:fun_imp},caption={The backend implementation for functions.}]
-%instance fun (BCInterpret a) BCInterpret | type a where
-% fun def = {main=freshlabel >>= \funlabel->
-% let (g In m) = def \a->callFunction funlabel (byteWidth a) [a]
-% in addToCtx funlabel zero (argwidth def)
-% >>| liftFunction funlabel (argwidth def)
-% (g (findArgs funlabel zero (argwidth def))) Nothing
-% >>| clearCtx >>| m.main
-% }
-%
-%callFunction :: JumpLabel UInt8 [BCInterpret b] -> BCInterpret c | ...
-%liftFunction :: JumpLabel UInt8 (BCInterpret a) (Maybe UInt8) -> BCInterpret ()
-%\end{lstlisting}
-%
-%\subsection{Tasks}\label{ssec:scheme_tasks}
-%Task trees are created with the \Cl{BCMkTask} instruction that allocates a node and pushes it to the stack.
-%It pops arguments from the stack according to the given task type.
-%The following extension of $\mathcal{E}$ shows this compilation scheme (except for the step combinator, explained in Subsection~\ref{ssec:step}).
-%
-%\begin{compilationscheme}
-% \cschemeE{\text{\Cl{rtrn}}\enskip e}{r} & =
-% \cschemeE{e}{r};
-% \text{\Cl{BCMkTask BCStable}}_{\|e\|};\\
-% \cschemeE{\text{\Cl{unstable}}\enskip e}{r} & =
-% \cschemeE{e}{r};
-% \text{\Cl{BCMkTask BCUnstable}}_{\|e\|};\\
-% \cschemeE{\text{\Cl{readA}}\enskip e}{r} & =
-% \cschemeE{e}{r};
-% \text{\Cl{BCMkTask BCReadA}};\\
-% \cschemeE{\text{\Cl{writeA}}\enskip e_1\enskip e_2}{r} & =
-% \cschemeE{e_1}{r};
-% \cschemeE{e_2}{r};
-% \text{\Cl{BCMkTask BCWriteA}};\\
-% \cschemeE{\text{\Cl{readD}}\enskip e}{r} & =
-% \cschemeE{e}{r};
-% \text{\Cl{BCMkTask BCReadD}};\\
-% \cschemeE{\text{\Cl{writeD}}\enskip e_1\enskip e_2}{r} & =
-% \cschemeE{e_1}{r};
-% \cschemeE{e_2}{r};
-% \text{\Cl{BCMkTask BCWriteD}};\\
-% \cschemeE{\text{\Cl{delay}}\enskip e}{r} & =
-% \cschemeE{e}{r};
-% \text{\Cl{BCMkTask BCDelay}};\\
-% \cschemeE{\text{\Cl{rpeat}}\enskip e}{r} & =
-% \cschemeE{e}{r};
-% \text{\Cl{BCMkTask BCRepeat}};\\
-% \cschemeE{e_1\text{\Cl{.||.}}e_2}{r} & =
-% \cschemeE{e_1}{r};
-% \cschemeE{e_2}{r};
-% \text{\Cl{BCMkTask BCOr}};\\
-% \cschemeE{e_1\text{\Cl{.&&.}}e_2}{r} & =
-% \cschemeE{e_1}{r};
-% \cschemeE{e_2}{r};
-% \text{\Cl{BCMkTask BCAnd}};\\
-%\end{compilationscheme}
-%
-%This simply translates to Clean code by writing the correct \Cl{BCMkTask} instruction as exemplified in Listing~\ref{lst:imp_ret}.
-%
-%\begin{lstlisting}[language=Clean,caption={The backend implementation for \Cl{rtrn}.},label={lst:imp_ret}]
-%instance rtrn BCInterpret where rtrn m = m >>| tell` [BCMkTask (bcstable m)]
-%\end{lstlisting}
-%
-%\subsection{Step combinator}\label{ssec:step}
-%The \Cl{step} construct is a special type of task because the task value of the left-hand side may change over time.
-%Therefore, the continuation tasks on the right-hand side are \emph{observing} this task value and acting upon it.
-%In the compilation scheme, all continuations are first converted to a single function that has two arguments: the stability of the task and its value.
-%This function either returns a pointer to a task tree or fails (denoted by $\bot$).
-%It is special because in the generated function, the task value of a task can actually be inspected.
-%Furthermore, it is a lazy node in the task tree: the right-hand side may yield a new task tree after several rewrite steps (i.e.\ it is allowed to create infinite task trees using step combinators).
-%The function is generated using the $\mathcal{S}$ scheme that requires two arguments: the context $r$ and the width of the left-hand side so that it can determine the position of the stability which is added as an argument to the function.
-%The resulting function is basically a list of if-then-else constructions to check all predicates one by one.
-%Some optimization is possible here but has currently not been implemented.
-%
-%\begin{compilationscheme}
-% \cschemeE{t_1\text{\Cl{>>*.}}t_2}{r} & =
-% \cschemeE{a_{f^i}}{r}, \langle f, i\rangle\in r;
-% \text{\Cl{BCMkTask}}\enskip \text{\Cl{BCStable}}_{\|r\|};\\
-% {} & \mathbin{\phantom{=}} \cschemeE{t_1}{r};\\
-% {} & \mathbin{\phantom{=}} \text{\Cl{BCMkTask}}\enskip \text{\Cl{BCAnd}};\\
-% {} & \mathbin{\phantom{=}} \text{\Cl{BCMkTask}}\\
-% {} & \mathbin{\phantom{=}} \enskip (\text{\Cl{BCStep}}\enskip (\cschemeS{t_2}{(r + [\langle l_s, i\rangle])}{\|t_1\|}));\\
-%%
-% \cschemeS{[]}{r}{w} & =
-% \text{\Cl{BCPush}}\enskip \bot;\\
-% \cschemeS{\text{\Cl{IfValue}}\enskip f\enskip t:cs}{r}{w} & =
-% \text{\Cl{BCArg}} (\|r\| + w);
-% \text{\Cl{BCIsNoValue}};\\
-% {} & \mathbin{\phantom{=}} \cschemeE{f}{r};
-% \text{\Cl{BCAnd}};\\
-% {} & \mathbin{\phantom{=}} \text{\Cl{BCJmpF}}\enskip l_1;\\
-% {} & \mathbin{\phantom{=}} \cschemeE{t}{r};
-% \text{\Cl{BCJmp}}\enskip l_2;\\
-% {} & \mathbin{\phantom{=}} \text{\Cl{BCLabel}}\enskip l_1;
-% \cschemeS{cs}{r}{w};\\
-% {} & \mathbin{\phantom{=}} \text{\Cl{BCLabel}}\enskip l_2;\\
-% {} & \text{\emph{Where $l_1$ and $l_2$ are fresh labels}}\\
-% {} & \text{\emph{Similar for \Cl{IfStable} and \Cl{IfUnstable}}}\\
-% \cschemeS{\text{\Cl{IfNoValue}}\enskip t:cs}{r}{w} & =
-% \text{\Cl{BCArg}} (\|r\|+w);
-% \text{\Cl{BCIsNoValue}};\\
-% {} & \mathbin{\phantom{=}} \text{\Cl{BCJmpF}}\enskip l_1;\\
-% {} & \mathbin{\phantom{=}} \cschemeE{t}{r};
-% \text{\Cl{BCJmp}}\enskip l_2;\\
-% {} & \mathbin{\phantom{=}} \text{\Cl{BCLabel}}\enskip l_1;
-% \cschemeS{cs}{r}{w};\\
-% {} & \mathbin{\phantom{=}} \text{\Cl{BCLabel}}\enskip l_2;\\
-% {} & \text{\emph{Where $l_1$ and $l_2$ are fresh labels}}\\
-% \cschemeS{\text{\Cl{Always}}\enskip f:cs}{r}{w} & =
-% \cschemeE{f}{r};\\
-%\end{compilationscheme}
-%
-%First the context is evaluated.
-%The context contains arguments from functions and steps that need to be preserved after rewriting.
-%The evaluated context is combined with the left-hand side task value by means of a \Cl{.&&.} combinator to store it in the task tree so that it is available after a rewrite.
-%This means that the task tree is be transformed as follows:
-%
-%\begin{lstlisting}[language=Clean]
-%t1 >>= \v1->t2 >>= \v2->t3 >>= ...
-%//is transformed to
-%t1 >>= \v1->rtrn v1 .&&. t2 >>= \v2->rtrn (v1, v2) .&&. t3 >>= ...
-%\end{lstlisting}
-%
-%The translation to Clean is given in Listing~\ref{lst:imp_seq}.
-%
-%\begin{lstlisting}[language=Clean,caption={Backend implementation for the step class.},label={lst:imp_seq}]
-%instance step BCInterpret where
-% (>>*.) lhs cont
-% //Fetch a fresh label and fetch the context
-% = freshlabel >>= \funlab->gets (\s->s.bcs_context)
-% //Generate code for lhs
-% >>= \ctx->lhs
-% //Possibly add the context
-% >>| tell` (if (ctx =: []) []
-% //The context is just the arguments up till now in reverse
-% ( [BCArg (UInt8 i)\\i<-reverse (indexList ctx)]
-% ++ map BCMkTask (bcstable (UInt8 (length ctx)))
-% ++ [BCMkTask BCTAnd]
-% ))
-% //Increase the context
-% >>| addToCtx funlab zero lhswidth
-% //Lift the step function
-% >>| liftFunction funlab
-% //Width of the arguments is the width of the lhs plus the
-% //stability plus the context
-% (one + lhswidth + (UInt8 (length ctx)))
-% //Body label ctx width continuations
-% (contfun funlab (UInt8 (length ctx)))
-% //Return width (always 1, a task pointer)
-% (Just one)
-% >>| modify (\s->{s & bcs_context=ctx})
-% >>| tell` [BCMkTask $ instr rhswidth funlab]
-%
-%toContFun :: JumpLabel UInt8 -> BCInterpret a
-%toContFun steplabel contextwidth
-% = foldr tcf (tell` [BCPush fail]) cont
-%where
-% tcf (IfStable f t)
-% = If ((stability >>| tell` [BCIsStable]) &. f val)
-% (t val >>| tell` [])
-% ...
-% stability = tell` [BCArg $ lhswidth + contextwidth]
-% val = retrieveArgs steplabel zero lhswidth
-%\end{lstlisting}
-%
-%\subsection{Shared Data Sources}
-%The compilation scheme for SDS definitions is a trivial extension to $\mathcal{F}$ since there is no code generated as seen below.
-%
-%\begin{compilationscheme}
-% \cschemeF{\text{\Cl{sds}}\enskip x=i\enskip \text{\Cl{In}}\enskip m} & =
-% \cschemeF{m};\\
-% \cschemeF{\text{\Cl{liftsds}}\enskip x=i\enskip \text{\Cl{In}}\enskip m} & =
-% \cschemeF{m};\\
-%\end{compilationscheme}
-%
-%The SDS access tasks have a compilation scheme similar to other tasks (see~Subsection~\ref{ssec:scheme_tasks}).
-%The \Cl{getSds} task just pushes a task tree node with the SDS identifier embedded.
-%The \Cl{setSds} task evaluates the value, lifts that value to a task tree node and creates an SDS set node.
-%
-%\begin{compilationscheme}
-% \cschemeE{\text{\Cl{getSds}}\enskip s}{r} & =
-% \text{\Cl{BCMkTask}} (\text{\Cl{BCSdsGet}} s);\\
-% \cschemeE{\text{\Cl{setSds}}\enskip s\enskip e}{r} & =
-% \cschemeE{e}{r};
-% \text{\Cl{BCMkTask BCStable}}_{\|e\|};\\
-% {} & \mathbin{\phantom{=}} \text{\Cl{BCMkTask}} (\text{\Cl{BCSdsSet}} s);\\
-%\end{compilationscheme}
-%
-%While there is no code generated in the definition, the bytecode compiler is storing the SDS data in the \Cl{bcs_sdses} field in the compilation state.
-%The SDSs are typed as functions in the host language so an argument for this function must be created that represents the SDS on evaluation.
-%For this, an \Cl{BCInterpret} is created that emits this identifier.
-%When passing it to the function, the initial value of the SDS is returned.
-%This initial value is stored as a bytecode encoded value in the state and the compiler continues with the rest of the program.
-%
-%Compiling \Cl{getSds} is a matter of executing the \Cl{BCInterpret} representing the SDS, which yields the identifier that can be embedded in the instruction.
-%Setting the SDS is similar: the identifier is retrieved and the value is written to put in a task tree so that the resulting task can remember the value it has written.
-%Lifted SDSs are compiled in a very similar way.
-%The only difference is that there is no initial value but an iTasks SDS when executing the Clean function.
-%A lens on this SDS converting \Cl{a} from the \Cl{Shared a} to a \Cl{String255}---a bytecode encoded version---is stored in the state.
-%The encoding and decoding itself is unsafe when used directly but the type system of the language and the abstractions make it safe.
-%Upon sending the mTask task to the device, the initial values of the lifted SDSs are fetched to complete the SDS specification.
-%
-%\begin{lstlisting}[language=Clean,caption={Backend implementation for the SDS classes.},label={lst:comp_sds}]
-%:: Sds a = Sds Int
-%instance sds BCInterpret where
-% sds def = {main = freshsds >>= \sdsi->
-% let sds = modify (\s->{s & bcs_sdses=put sdsi
-% (Left (toByteCode t)) s.bcs_sdses})
-% >>| pure (Sds sdsi)
-% (t In e) = def sds
-% in e.main}
-% getSds f = f >>= \(Sds i)-> tell` [BCMkTask (BCSdsGet (fromInt i))]
-% setSds f v = f >>= \(Sds i)->v >>| tell`
-% ( map BCMkTask (bcstable (byteWidth v))
-% ++ [BCMkTask (BCSdsSet (fromInt i))])\end{lstlisting}
-%
-%\section{Run time system}
-%
-%The RTS is designed to run on systems with as little as 2kB of RAM.
-%Aggressive memory management is therefore vital.
-%Not all firmwares for MCUs support heaps and---when they do---allocation often leaves holes when not used in a Last In First Out strategy.
-%Therefore the RTS uses a chunk of memory in the global data segment with its own memory manager tailored to the needs of mTask.
-%The size of this block can be changed in the configuration of the RTS if necessary.
-%On an Arduino {UNO} ---equipped with 2kB of RAM--- this size can be about 1500 bytes.
-%
-%In memory, task data grows from the bottom up and an interpreter stack is located directly on top of it growing in the same direction.
-%As a consequence, the stack moves when a new task is received.
-%This never happens within execution because communication is always processed before execution.
-%Values in the interpreter are always stored on the stack, even tuples.
-%Task trees grow from the top down as in a heap.
-%This approach allows for flexible ratios, i.e.\ many tasks and small trees or few tasks and big trees.
-%
-%The event loop of the RTS is executed repeatedly and consists of three distinct phases.
-%
-%%TODO evt subsubsections verwijderen
-%\subsubsection{Communication}
-%In the first phase, the communication channels are processed.
-%The messages announcing SDS updates are applied immediately, the initialization of new tasks is delayed until the next phase.
-%
-%\subsubsection{Execution}
-%The second phase consists of executing tasks.
-%The RTS executes all tasks in a round robin fashion.
-%If a task is not initialized yet, the bytecode of the main function is interpreted to produce the initial task tree.
-%The rewriting engine uses the interpreter when needed, e.g.\ to calculate the step continuations.
-%The rewriter and the interpreter use the same stack to store intermediate values.
-%Rewriting steps are small so that interleaving results in seemingly parallel execution.
-%In this phase new task tree nodes may be allocated.
-%Both rewriting and initialization are atomic operations in the sense that no processing on SDSs is done other than SDS operations from the task itself.
-%The host is notified if a task value is changed after a rewrite step.
-%
-%\subsubsection{Memory management}
-%The third and final phase is memory management.
-%Stable tasks, and unreachable task tree nodes are removed.
-%If a task is to be removed, tasks with higher memory addresses are moved down.
-%For task trees---stored in the heap---the RTS already marks tasks and task trees as trash during rewriting so the heap can be compacted in a single pass.
-%This is possible because there is no sharing or cycles in task trees and nodes contain pointers pointers to their parent.
-%\subsection{Memory management}
-%\subsection{Interpreter}
-%\subsection{Rewrite engine}
-%\section{Task rewriting}\label{sec:rewrite}
-%Tasks are rewritten every event loop iteration and one rewrite cycle is generally very fast.
-%This results in seemingly parallel execution of the tasks because the rewrite steps are interleaved.
-%Rewriting is a destructive process that actually modifies the task tree nodes in memory and marks nodes that become garbage.
-%The task value is stored on the stack and therefore only available during rewriting.
-%
-%\subsection{Basic tasks}
-%The \Cl{rtrn} and \Cl{unstable} tasks always rewrite to themselves and have no side effects.
-%The GPIO interaction tasks do have side effects.
-%The \Cl{readA} and \Cl{readD} tasks will query the given pin every rewrite cycle and emit it as an unstable task value.
-%The \Cl{writeA} and \Cl{writeD} tasks write the given value to the given pin and immediately rewrite to a stable task of the written value.
-%
-%\subsection{Delay and repetition}
-%The \Cl{delay} task stabilizes once a certain amount of time has been passed by storing the finish time on initialization.
-%In every rewrite step it checks whether the current time is bigger than the finish time and if so, it rewrites to a \Cl{rtrn} task containing the number of milliseconds that it overshot the target.
-%The \Cl{rpeat} task combinator rewrites the argument until it becomes stable.
-%Rewriting is a destructive process and therefore the original task tree must be saved.
-%As a consequence, on installation, the argument is cloned and the task rewrites the clone.
-%
-%\subsection{Sequential combination}
-%First the left-hand side of the step task is rewritten.
-%The resulting value is passed to the continuation function.
-%If the continuation function returns a pointer to a task tree, the task tree rewrites to that task tree and marks the original left-hand side as trash.
-%If the function returns $\bot$, the step is kept unchanged.
-%The step itself never fields a value.
-%
-%\subsection{Parallel combination}\label{ssec:parallelExecution}
-%There are two parallel task combinators available.
-%A \Cl{.&&.} task only becomes stable when both sides are stable.
-%A \Cl{.||.} task becomes stable when one of the sides is stable.
-%The combinators first rewrite both sides and then merge the task values according to the semantics given in Listing~\ref{lst:parallel_combinators}.
-%
-%\begin{lstlisting}[language=Clean,caption={Task value semantics for the parallel combinators.},label={lst:parallel_combinators}]
-%(.&&.) :: (TaskValue a) (TaskValue b) -> TaskValue (a, b)
-%(.&&.) (Value lhs stab1) (Value rhs stab2) = Value (lhs, rhs) (stab1 && stab2)
-%(.&&.) _ _ = NoValue
-%
-%(.||.) :: (TaskValue a) (TaskValue a) -> TaskValue a
-%(.||.) lhs=:(Value _ True) _ = lhs
-%(.||.) (Value lhs _) rhs=:(Value _ True) = rhs
-%(.||.) NoValue rhs = rhs
-%(.||.) lhs _ = lhs\end{lstlisting}
-%
-%\subsection{Shared Data Source tasks}
-%The \Cl{BCSdsGet} node always rewrites to itself.
-%It will read the actual SDS embedded and emit the value as an unstable task value.
-%
-%Setting an SDS is a bit more involved because after writing, it emits the value written as a stable task value.
-%The \Cl{BCSdsSet} node contains the identifier for the SDS and a task tree that, when rewritten, emits the value to be set as a stable task value.
-%The naive approach would be to just rewrite the \Cl{BCSdsSet} to a node similar to the \Cl{BCSdsGet} but only with a stable value.
-%However, after writing the SDS, its value might have changed due to other tasks writing it, and then the \Cl{setSDS}'s stable value may change.
-%Therefore, the \Cl{BCSdsSet} node is rewritten to the argument task tree which always represents constant stable value.
-%In future rewrites, the constant value node emits the value that was originally written.
-%
-%The client only knows whether an SDS is a lifted SDS, not to which iTasks SDS it is connected.
-%If the SDS is modified on the device, it sends an update to the server.
-%
-%\section{Conclusion}
+
+Translating the compilation schemes for functions to \gls{CLEAN} is not as straightforward as other schemes due to the nature of shallow embedding in combination with the use of state.
+The \cleaninline{fun} class has a single function with a single argument.
+This argument is a \gls{CLEAN} function that---when given a callable \gls{CLEAN} function representing the \gls{MTASK} function---produces the \cleaninline{main} expression and a callable function.
+To compile this, the argument must be called with a function representing a function call in \gls{MTASK}.
+\Cref{lst:fun_imp} shows the implementation for this as \gls{CLEAN} code.
+To uniquely identify the function, a fresh label is generated.
+The function is then called with the \cleaninline{callFunction} helper function that generates the instructions that correspond to calling the function.
+That is, it pushes the pointers, compiles the arguments, and writes the \cleaninline{JumpSR} instruction.
+The resulting structure (\cleaninline{g In m}) contains a function representing the mTask function (\cleaninline{g}) and the \cleaninline{main} structure to continue with.
+To get the actual function, \cleaninline{g} must be called with representations for the argument, i.e.\ using \cleaninline{findarg} for all arguments.
+The arguments are added to the context using \cleaninline{infun} and \cleaninline{liftFunction} is called with the label, the argument width and the compiler.
+This function executes the compiler, decorates the instructions with a label and places them in the function dictionary together with the metadata such as the argument width.
+After lifting the function, the context is cleared again and compilation continues with the rest of the program.
+
+\begin{lstClean}[label={lst:fun_imp},caption={The interpretation implementation for functions.}]
+instance fun (BCInterpret a) BCInterpret | type a where
+ fun def = {main=freshlabel >>= \funlabel->
+ let (g In m) = def \a->callFunction funlabel (toByteWidth a) [a]
+ argwidth = toByteWidth (argOf g)
+ in addToCtx funlabel zero argwidth
+ >>| infun funlabel
+ (liftFunction funlabel argwidth
+ (g (retrieveArgs funlabel zero argwidth)
+ ) ?None)
+ >>| clearCtx >>| m.main
+ }
+
+argOf :: ((m a) -> b) a -> UInt8 | toByteWidth a
+callFunction :: JumpLabel UInt8 [BCInterpret b] -> BCInterpret c | ...
+liftFunction :: JumpLabel UInt8 (BCInterpret a) (?UInt8) -> BCInterpret ()
+infun :: JumpLabel (BCInterpret a) -> BCInterpret a
+\end{lstClean}
+
+\subsection{Tasks}\label{ssec:scheme_tasks}
+Task trees are created with the \cleaninline{BCMkTask} instruction that allocates a node and pushes a pointer to it on the stack.
+It pops arguments from the stack according to the given task type.
+The following extension of $\mathcal{E}$ shows this compilation scheme (except for the step combinator, explained in \cref{ssec:step}).
+
+\begingroup
+\allowdisplaybreaks%
+\begin{align*}
+ \cschemeE{\text{\cleaninline{rtrn}}~e}{r} & =
+ \cschemeE{e}{r};
+ \text{\cleaninline{BCMkTask BCStable}}_{\stacksize{e}};\\
+ \cschemeE{\text{\cleaninline{unstable}}~e}{r} & =
+ \cschemeE{e}{r};
+ \text{\cleaninline{BCMkTask BCUnstable}}_{\stacksize{e}};\\
+ \cschemeE{\text{\cleaninline{readA}}~e}{r} & =
+ \cschemeE{e}{r};
+ \text{\cleaninline{BCMkTask BCReadA}};\\
+ \cschemeE{\text{\cleaninline{writeA}}~e_1~e_2}{r} & =
+ \cschemeE{e_1}{r};
+ \cschemeE{e_2}{r};
+ \text{\cleaninline{BCMkTask BCWriteA}};\\
+ \cschemeE{\text{\cleaninline{readD}}~e}{r} & =
+ \cschemeE{e}{r};
+ \text{\cleaninline{BCMkTask BCReadD}};\\
+ \cschemeE{\text{\cleaninline{writeD}}~e_1~e_2}{r} & =
+ \cschemeE{e_1}{r};
+ \cschemeE{e_2}{r};
+ \text{\cleaninline{BCMkTask BCWriteD}};\\
+ \cschemeE{\text{\cleaninline{delay}}~e}{r} & =
+ \cschemeE{e}{r};
+ \text{\cleaninline{BCMkTask BCDelay}};\\
+ \cschemeE{\text{\cleaninline{rpeat}}~e}{r} & =
+ \cschemeE{e}{r};
+ \text{\cleaninline{BCMkTask BCRepeat}};\\
+ \cschemeE{e_1\text{\cleaninline{.\|\|.}}e_2}{r} & =
+ \cschemeE{e_1}{r};
+ \cschemeE{e_2}{r};
+ \text{\cleaninline{BCMkTask BCOr}};\\
+ \cschemeE{e_1\text{\cleaninline{.&&.}}e_2}{r} & =
+ \cschemeE{e_1}{r};
+ \cschemeE{e_2}{r};
+ \text{\cleaninline{BCMkTask BCAnd}};\\
+\end{align*}
+\endgroup%
+
+This compilation scheme translates to Clean code by first writing the arguments and then the correct \cleaninline{BCMkTask} instruction.
+This is shown for the \cleaninline{.&&.} task in \cref{lst:imp_ret}.
+
+\begin{lstClean}[caption={The byte code interpretation implementation for \cleaninline{rtrn}.},label={lst:imp_ret}]
+instance .&&. BCInterpret where
+ (.&&.) l r = l >>| r >>| tell` [BCMkTask BCTAnd]
+\end{lstClean}
+
+\subsection{Sequential combinator}\label{ssec:step}
+The \cleaninline{step} construct is a special type of task because the task value of the left-hand side changes over time.
+Therefore, the task continuations on the right-hand side are \emph{observing} this task value and acting upon it.
+In the compilation scheme, all continuations are first converted to a single function that has two arguments: the stability of the task and its value.
+This function either returns a pointer to a task tree or fails (denoted by $\bot$).
+It is special because in the generated function, the task value of a task is inspected.
+Furthermore, it is a lazy node in the task tree: the right-hand side may yield a new task tree after several rewrite steps, i.e.\ it is allowed to create infinite task trees using step combinators.
+The function is generated using the $\mathcal{S}$ scheme that requires two arguments: the context $r$ and the width of the left-hand side so that it can determine the position of the stability which is added as an argument to the function.
+The resulting function is basically a list of if-then-else constructions to check all predicates one by one.
+Some optimisation is possible here but has currently not been implemented.
+
+\begin{align*}
+ \cschemeE{t_1\text{\cleaninline{>>*.}}e_2}{r} & =
+ \cschemeE{a_{f^i}}{r}, \langle f, i\rangle\in r;
+ \text{\cleaninline{BCMkTask}}~\text{\cleaninline{BCStable}}_{\stacksize{r}}; \cschemeE{t_1}{r};\\
+ {} & \mathbin{\phantom{=}} \text{\cleaninline{BCMkTask}}~\text{\cleaninline{BCAnd}}; \text{\cleaninline{BCMkTask}}~(\text{\cleaninline{BCStep}}~(\cschemeS{e_2}{(r + [\langle l_s, i\rangle])}{\stacksize{t_1}}));\\
+\end{align*}
+
+\begin{align*}
+ \cschemeS{[]}{r}{w} & =
+ \text{\cleaninline{BCPush}}~\bot;\\
+ \cschemeS{\text{\cleaninline{IfValue}}~f~t:cs}{r}{w} & =
+ \text{\cleaninline{BCArg}} (\stacksize{r} + w);
+ \text{\cleaninline{BCIsNoValue}};\\
+ {} & \mathbin{\phantom{=}} \cschemeE{f}{r};
+ \text{\cleaninline{BCAnd}};\\
+ {} & \mathbin{\phantom{=}} \text{\cleaninline{BCJmpF}}~l_1;\\
+ {} & \mathbin{\phantom{=}} \cschemeE{t}{r};
+ \text{\cleaninline{BCJmp}}~l_2;\\
+ {} & \mathbin{\phantom{=}} \text{\cleaninline{BCLabel}}~l_1;
+ \cschemeS{cs}{r}{w};\\
+ {} & \mathbin{\phantom{=}} \text{\cleaninline{BCLabel}}~l_2;\\
+ {} & \text{\emph{Where $l_1$ and $l_2$ are fresh labels}}\\
+ {} & \text{\emph{Similar for \cleaninline{IfStable} and \cleaninline{IfUnstable}}}\\
+\end{align*}
+
+The step combinator has a task as the left-hand side and a list of continuations at the right-hand side.
+First the context is evaluated ($\cschemeE{a_{f^i}}{r}$).
+The context contains arguments from functions and steps that need to be preserved after rewriting.
+The evaluated context is combined with the left-hand side task value by means of a \cleaninline{.&&.} combinator to store it in the task tree so that it is available after a rewrite step.
+This means that the task tree is transformed as seen in \cref{lst:context_tree}.
+In this figure, the expression \cleaninline{t1 >>=. \\v1->t2 >>=. \\v2->...} is shown\footnote{%
+ \cleaninline{t >>=. e} is a shorthand combinator for \cleaninline{t >>* [OnStable (\\_->true) e].}}.
+Then, the right-hand side list of continuations is converted to an expression using $\mathcal{S}$.
+
+\begin{figure}
+ \begin{subfigure}{.5\textwidth}
+ \includestandalone{contexttree1}
+ \caption{Without the embedded context.}
+ \end{subfigure}%
+ \begin{subfigure}{.5\textwidth}
+ \includestandalone{contexttree2}
+ \caption{With the embedded context.}
+ \end{subfigure}
+ \caption{Context embedded in a virtual task tree.}%
+ \label{lst:context_tree}
+\end{figure}
+
+The translation to \gls{CLEAN} is given in \cref{lst:imp_seq}.
+
+\begin{lstClean}[caption={Byte code compilation interpretation implementation for the step class.},label={lst:imp_seq}]
+instance step BCInterpret where
+ (>>*.) lhs cont
+ //Fetch a fresh label and fetch the context
+ = freshlabel >>= \funlab->gets (\s->s.bcs_context)
+ //Generate code for lhs
+ >>= \ctx->lhs
+ //Possibly add the context
+ >>| tell` (if (ctx =: []) []
+ //The context is just the arguments up till now in reverse
+ ( [BCArg (UInt8 i)\\i<-reverse (indexList ctx)]
+ ++ map BCMkTask (bcstable (UInt8 (length ctx)))
+ ++ [BCMkTask BCTAnd]
+ ))
+ //Increase the context
+ >>| addToCtx funlab zero lhswidth
+ //Lift the step function
+ >>| liftFunction funlab
+ //Width of the arguments is the width of the lhs plus the
+ //stability plus the context
+ (one + lhswidth + (UInt8 (length ctx)))
+ //Body label ctx width continuations
+ (contfun funlab (UInt8 (length ctx)))
+ //Return width (always 1, a task pointer)
+ (Just one)
+ >>| modify (\s->{s & bcs_context=ctx})
+ >>| tell` [BCMkTask (instr rhswidth funlab)][+\pagebreak+]
+toContFun :: JumpLabel UInt8 -> BCInterpret a
+toContFun steplabel contextwidth
+ = foldr tcf (tell` [BCPush fail]) cont
+where
+ tcf (IfStable f t)
+ = If ((stability >>| tell` [BCIsStable]) &. f val)
+ (t val >>| tell` [])
+ ...
+ stability = tell` [BCArg (lhswidth + contextwidth)]
+ val = retrieveArgs steplabel zero lhswidth
+\end{lstClean}
+
+\subsection{Shared data sources}\label{lst:imp_sds}
+The compilation scheme for \gls{SDS} definitions is a trivial extension to $\mathcal{F}$.
+While there is no code generated in the definition, the byte code compiler is storing all \gls{SDS} data in the \cleaninline{bcs_sdses} field in the compilation state.
+Regular \glspl{SDS} are stored as \cleaninline{Right String255} values.
+The \glspl{SDS} are typed as functions in the host language, so an argument for this function must be created that represents the \gls{SDS} on evaluation.
+For this, an \cleaninline{BCInterpret} is created that emits this identifier.
+When passing it to the function, the initial value of the \gls{SDS} is returned.
+In the case of a local \gls{SDS}, this initial value is stored as a byte code encoded value in the state and the compiler continues with the rest of the program.
+The \gls{SDS} access tasks have a compilation scheme similar to other tasks (see \cref{ssec:scheme_tasks}).
+The \cleaninline{getSds} task just pushes a task tree node with the \gls{SDS} identifier embedded.
+The \cleaninline{setSds} task evaluates the value, lifts that value to a task tree node and creates \pgls{SDS} set node.
+
+\begin{align*}
+ \cschemeF{\text{\cleaninline{sds}}~x=i~\text{\cleaninline{In}}~m} & =
+ \cschemeF{m};\\
+ \\
+ \cschemeE{\text{\cleaninline{getSds}}~s}{r} & =
+ \text{\cleaninline{BCMkTask}}~(\text{\cleaninline{BCSdsGet}}~s);\\
+ \cschemeE{\text{\cleaninline{setSds}}~s~e}{r} & =
+ \cschemeE{e}{r};
+ \text{\cleaninline{BCMkTask BCStable}}_{\stacksize{e}};\\
+ {} & \mathbin{\phantom{=}} \text{\cleaninline{BCMkTask}}~(\text{\cleaninline{BCSdsSet}}~s);\\
+\end{align*}
+
+\Cref{lst:comp_sds} shows the implementation of the \cleaninline{sds} type class.
+First, the initial \gls{SDS} value is extracted from the expression by bootstrapping the fixed point with a dummy value.
+This is safe because the expression on the right-hand side of the \cleaninline{In} is never evaluated.
+Then, using \cleaninline{addSdsIfNotExist}, the identifier for this particular \gls{SDS} is either retrieved from the compiler state or generated freshly.
+This identifier is then used to provide a reference to the \cleaninline{def} definition to evaluate the main expression.
+Compiling \cleaninline{getSds} is a matter of executing the \cleaninline{BCInterpret} representing the \gls{SDS}, which yields the identifier that can be embedded in the instruction.
+Setting the \gls{SDS} is similar: the identifier is retrieved, and the value is written to put in a task tree so that the resulting task can remember the value it has written.
+
+% VimTeX: SynIgnore on
+\begin{lstClean}[caption={Backend implementation for the \gls{SDS} classes.},label={lst:comp_sds}]
+:: Sds a = Sds Int
+instance sds BCInterpret where
+ sds def = {main =
+ let (t In e) = def (abort "sds: expression too strict")
+ in addSdsIfNotExist (Left $ String255 (toByteCode{|*|} t))
+ >>= \sdsi-> let (t In e) = def (pure (Sds sdsi))
+ in e.main
+ }
+ getSds f = f >>= \(Sds i)-> tell` [BCMkTask (BCSdsGet (fromInt i))]
+ setSds f v = f >>= \(Sds i)->v >>| tell`
+ ( map BCMkTask (bcstable (byteWidth v))
+ ++ [BCMkTask (BCSdsSet (fromInt i))])
+\end{lstClean}
+% VimTeX: SynIgnore off
+
+Lowered \glspl{SDS} are stored in the compiler state as \cleaninline{Right MTLens} values.
+The compilation of the code and the serialisation of the data throws away all typing information.
+The \cleaninline{MTLens} is a type synonym for \pgls{SDS} that represents the typeless serialised value of the underlying \gls{SDS}.
+This is done so that the \cleaninline{withDevice} task can write the received \gls{SDS} updates to the according \gls{SDS} while the \gls{SDS} is not in scope.
+The \gls{ITASK} notification mechanism then takes care of the rest.
+Such \pgls{SDS} is created by using the \cleaninline{mapReadWriteError} which, given a pair of read and write functions with error handling, produces \pgls{SDS} with the lens embedded.
+The read function transforms converts the typed value to a typeless serialised value.
+The write function will, given a new serialised value and the old typed value, produce a new typed value.
+It tries to decode the serialised value, if that succeeds, it is written to the underlying \gls{SDS}, an error is thrown otherwise.
+\Cref{lst:mtask_itasksds_lens} shows the implementation for this.
+
+% VimTeX: SynIgnore on
+\begin{lstClean}[label={lst:mtask_itasksds_lens},caption={Lens applied to lowered \gls{ITASK} \glspl{SDS} in \gls{MTASK}.}]
+lens :: (Shared sds a) -> MTLens | type a & RWShared sds
+lens sds = mapReadWriteError
+ ( \r-> Ok (fromString (toByteCode{|*|} r)
+ , \w r-> ?Just <$> iTasksDecode (toString w)
+ ) ?None sds
+\end{lstClean}
+% VimTeX: SynIgnore off
+
+\Cref{lst:mtask_itasksds_lift} shows the code for the implementation of \cleaninline{lowerSds} that uses the \cleaninline{lens} function shown earlier.
+It is very similar to the \cleaninline{sds} constructor in \cref{lst:comp_sds}, only now a \cleaninline{Right} value is inserted in the \gls{SDS} administration.
+
+% VimTeX: SynIgnore on
+\begin{lstClean}[label={lst:mtask_itasksds_lift},caption={The implementation for lowering \glspl{SDS} in \gls{MTASK}.}]
+instance lowerSds BCInterpret where
+ lowerSds def = {main =
+ let (t In _) = def (abort "lowerSds: expression too strict")
+ in addSdsIfNotExist (Right $ lens t)
+ >>= \sdsi->let (_ In e) = def (pure (Sds sdsi)) in e.main
+ }\end{lstClean}
+% VimTeX: SynIgnore off
+
+\section{Run-time system}\label{sec:compiler_rts}
+The \gls{RTS} is a customisable domain-specific \gls{OS} that takes care of the execution of tasks.
+Furthermore, it also takes care of low-level mechanisms such as the communication, multitasking, and memory management.
+Once a device is programmed with the \gls{MTASK} \gls{RTS}, it can continuously receive new tasks without the need for reprogramming.
+The \gls{OS} is written in portable \ccpp{} and only contains a small device-specific portion.
+In order to keep the abstraction level high and the hardware requirements low, much of the high-level functionality of the \gls{MTASK} language is implemented not in terms of lower-level constructs from \gls{MTASK} language but in terms of \ccpp{} code.
+
+Most microcontrollers software consists of a cyclic executive instead of an \gls{OS}, this one loop function is continuously executed and all work is performed there.
+In the \gls{RTS} of the \gls{MTASK} system, there is also such an event loop function.
+It is a function with a relatively short execution time that gets called repeatedly.
+The event loop consists of three distinct phases.
+After doing the three phases, the devices goes to sleep for as long as possible (see \cref{chp:green_computing_mtask} for more details on task scheduling).
+
+\subsection{Communication phase}
+In the first phase, the communication channels are processed.
+The exact communication method is a customisable device-specific option baked into the \gls{RTS}.
+The interface is kept deliberately simple and consists of two layers: a link interface and a communication interface.
+Besides opening, closing and cleaning up, the link interface has three functions that are shown in \cref{lst:link_interface}.
+Consequently, implementing this link interface is very simple, but it is still possible to implement more advanced link features such as buffering.
+There are implementations for this interface for serial or \gls{WIFI} connections using \gls{ARDUINO}, and \gls{TCP} connections for Linux.
+
+\begin{lstArduino}[caption={Link interface of the \gls{MTASK} \gls{RTS}.},label={lst:link_interface}]
+bool link_input_available(void);
+uint8_t link_read_byte(void);
+void link_write_byte(uint8_t b);
+\end{lstArduino}
+
+The communication interface abstracts away from this link interface and is typed instead.
+It contains only two functions as seen in \cref{lst:comm_interface}.
+There are implementations for direct communication, or communication using an \gls{MQTT} broker.
+Both use the automatic serialisation and deserialisation shown in \cref{sec:ccodegen}.
+
+\begin{lstArduino}[caption={Communication interface of the \gls{MTASK} \gls{RTS}.},label={lst:comm_interface}]
+struct MTMessageTo receive_message(void);
+void send_message(struct MTMessageFro msg);
+\end{lstArduino}
+
+Processing the received messages from the communication channels happens synchronously and the channels are exhausted completely before moving on to the next phase.
+There are several possible messages that can be received from the server:
+
+\begin{description}
+ \item[SpecRequest]
+ is a message instructing the device to send its specification.
+ It is received immediately after connecting.
+ The \gls{RTS} responds with a \texttt{Spec} answer containing the specification.
+ \item[TaskPrep]
+ tells the device a task is on its way.
+ Especially on faster connections, it may be the case that the communication buffers overflow because a big message is sent while the \gls{RTS} is busy executing tasks.
+ This message allows the \gls{RTS} to postpone execution for a while, until the larger task has been received.
+ The server sends the task only after the device acknowledged the preparation by sending a \texttt{TaskPrepAck} message.
+ \item[Task]
+ contains a new task, its peripheral configuration, the \glspl{SDS}, and the byte code.
+ The new task is immediately copied to the task storage but is only initialised during the next phase.
+ The device acknowledges the task by sending a \texttt{TaskAck} message.
+ \item[SdsUpdate]
+ notifies the device of the new value for a lowered \gls{SDS}.
+ The old value of the lowered \gls{SDS} is immediately replaced with the new one.
+ There is no acknowledgement required.
+ \item[TaskDel]
+ instructs the device to delete a running task.
+ Tasks are automatically deleted when they become stable.
+ However, a task may also be deleted when the surrounding task on the server is deleted, for example when the task is on the left-hand side of a step combinator and the condition to step holds.
+ The device acknowledges the deletion by sending a \texttt{TaskDelAck}.
+ \item[Shutdown]
+ tells the device to reset.
+\end{description}
+
+\subsection{Execution phase}
+The second phase performs one execution step for all tasks that wish for it.
+Tasks are ordered in a priority queue ordered by the time a task needs to execute, the \gls{RTS} selects all tasks that can be scheduled, see \cref{sec:scheduling} for more details.
+Execution of a task is always an interplay between the interpreter and the rewriter.
+The rewriter scans the current task tree and tries to rewrite it using small-step reduction.
+Expressions in the tree are always strictly evaluated by the interpreter.
+
+When a new task is received, the main expression is evaluated to produce a task tree.
+A task tree is a tree structure in which each node represents a task combinator and the leaves are basic tasks.
+If a task is not initialised yet, i.e.\ the pointer to the current task tree is still null, the byte code of the main function is interpreted.
+The main expression of \gls{MTASK} programs sent to the device fore execution always produces a task tree.
+Execution of a task consists of continuously rewriting the task until its value is stable.
+
+Rewriting is a destructive process, i.e.\ the rewriting is done in place.
+The rewriting engine uses the interpreter when needed, e.g.\ to calculate the step continuations.
+The rewriter and the interpreter use the same stack to store intermediate values.
+Rewriting steps are small so that interleaving results in seemingly parallel execution.
+In this phase new task tree nodes may be allocated.
+Both rewriting and initialization are atomic operations in the sense that no processing on \glspl{SDS} is done other than \gls{SDS} operations from the task itself.
+The host is notified if a task value is changed after a rewrite step by sending a \texttt{TaskReturn} message.
+
+Take for example a blink task for which the code is shown in \cref{lst:blink_code}.
+
+\begin{lstClean}[caption={Code for a blink program.},label={lst:blink_code}]
+declarePin D13 PMOutput \ledPin->
+fun \blink=(\st->delay (lit 500) >>|. writeD ledPin st >>=. blink o Not)
+In {main = blink true}
+\end{lstClean}
+
+On receiving this task, the task tree is still null and the initial expression \cleaninline{blink true} is evaluated by the interpreter.
+This results in the task tree shown in \cref{fig:blink_tree1}.
+Rewriting always starts at the top of the tree and traverses to the leaves, the basic tasks that do the actual work.
+The first basic task encountered is the \cleaninline{delay} task, that yields no value until the time, \qty{500}{\ms} in this case, has passed.
+When the \cleaninline{delay} task yielded a stable value after a number of rewrites, the task continues with the right-hand side of the \cleaninline{>>\|.} combinator by evaluating the expression (see \cref{fig:blink_tree2})\footnotemark.
+\footnotetext{\cleaninline{t1 >>\|. t2} is a shorthand for \cleaninline{t1 >>*. [IfStable id \\_->t2]}.}
+This combinator has a \cleaninline{writeD} task at the left-hand side that becomes stable after one rewrite step in which it writes the value to the given pin.
+When \cleaninline{writeD} becomes stable, the written value is the task value that is observed by the right-hand side of the \cleaninline{>>=.} combinator.
+Then the interpreter is used again to evaluate the expression, now that the argument of the function is known.
+The result of the call to the function is again a task tree, but now with different arguments to the tasks, e.g.\ the state in \cleaninline{writeD} is inversed.
+
+\begin{figure}
+ \centering
+ \begin{subfigure}[t]{.5\textwidth}
+ \includestandalone{blinktree1}
+ \caption{Initial task tree}%
+ \label{fig:blink_tree1}
+ \end{subfigure}%
+ \begin{subfigure}[t]{.5\textwidth}
+ \includestandalone{blinktree2}
+ \caption{Task tree after the delay passed}%
+ \label{fig:blink_tree2}
+ \end{subfigure}
+ \caption{The task trees during reduction for a blink task in \gls{MTASK}.}%
+ \label{fig:blink_tree}
+\end{figure}
+
+\subsection{Memory management}
+The third and final phase is memory management.
+The \gls{MTASK} \gls{RTS} is designed to run on systems with as little as \qty{2}{\kibi\byte} of \gls{RAM}.
+Aggressive memory management is therefore vital.
+Not all firmwares for microprocessors support heaps and---when they do---allocation often leaves holes when not used in a \emph{last in first out} strategy.
+The \gls{RTS} uses a chunk of memory in the global data segment with its own memory manager tailored to the needs of \gls{MTASK}.
+The size of this block can be changed in the configuration of the \gls{RTS} if necessary.
+On an \gls{ARDUINO} UNO---equipped with \qty{2}{\kibi\byte} of \gls{RAM}---the maximum viable size is about \qty{1500}{\byte}.
+The self-managed memory uses a similar layout as the memory layout for \gls{C} programs only the heap and the stack are switched (see \cref{fig:memory_layout}).
+
+\begin{figure}
+ \centering
+ \includestandalone{memorylayout}
+ \caption{Memory layout in the \gls{MTASK} \gls{RTS}.}\label{fig:memory_layout}
+\end{figure}
+
+A task is stored below the stack and it consists of the task id, a pointer to the task tree in the heap (null if not initialised yet), the current task value, the configuration of \glspl{SDS}, the configuration of peripherals, the byte code and some scheduling information.
+
+In memory, task data grows from the bottom up and the interpreter stack is located directly on top of it growing in the same direction.
+As a consequence, the stack moves when a new task is received.
+This never happens within execution because communication is always processed before execution.
+Values in the interpreter are always stored on the stack.
+Compound data types are stored unboxed and flattened.
+Task trees grow from the top down as in a heap.
+This approach allows for flexible ratios, i.e.\ many tasks and small trees or few tasks and big trees.
+
+Stable tasks, and unreachable task tree nodes are removed.
+If a task is to be removed, tasks with higher memory addresses are moved down.
+For task trees---stored in the heap---the \gls{RTS} already marks tasks and task trees as trash during rewriting, so the heap can be compacted in a single pass.
+This is possible because there is no sharing or cycles in task trees and nodes contain pointers to their parent.
+
+
+\section{C code generation for communication}\label{sec:ccodegen}
+All communication between the \gls{ITASK} server and the \gls{MTASK} server is type parametrised and automated.
+From the structural representation of the type, a \gls{CLEAN} parser and printer is constructed using generic programming.
+Furthermore, a \ccpp{} parser and printer is generated for use on the \gls{MTASK} device.
+The technique for generating the \ccpp{} parser and printer is very similar to template metaprogramming and requires a rich generic programming library or compiler support that includes a lot of metadata in the record and constructor nodes.
+Using generic programming in the \gls{MTASK} system, both serialisation and deserialisation on the microcontroller and the server is automatically generated.
+
+\subsection{Server}
+On the server, off-the-shelve generic programming techniques are used to make the serialisation and deserialisation functions (see \cref{lst:ser_deser_server}).
+Serialisation is a simple conversion from a value of the type to a string.
+Deserialisation is a bit different in order to support streaming\footnotemark.
+\footnotetext{%
+ Here the \cleaninline{*!} variant of the generic interface is chosen that has less uniqueness constraints for the compiler-generated adaptors \citep{alimarine_generic_2005,hinze_derivable_2001}.%
+}
+Given a list of available characters, a tuple is always returned.
+The right-hand side of the tuple contains the remaining characters, the unparsed input.
+The left-hand side contains either an error or a maybe value.
+If the value is a \cleaninline{?None}, there was no full value to parse.
+If the value is a \cleaninline{?Just}, the data field contains a value of the requested type.
+
+\begin{lstClean}[caption={Serialisation and deserialisation functions in \gls{CLEAN}.},label={lst:ser_deser_server}]
+generic toByteCode a :: a -> String
+generic fromByteCode a *! :: [Char] -> (Either String (? a), [Char])
+\end{lstClean}
+
+\subsection{Client}
+The \gls{RTS} of the \gls{MTASK} system runs on resource-constrained microcontrollers and is implemented in portable \ccpp{}.
+In order to achieve more interoperation safety, the communication between the server and the client is automated, i.e.\ the serialisation and deserialisation code in the \gls{RTS} is generated.
+The technique used for this is very similar to the technique shown in \cref{chp:first-class_datatypes}.
+However, instead of using template metaprogramming, a feature \gls{CLEAN} lacks, generic programming is used also as a two-stage rocket.
+In contrast to many other generic programming systems, \gls{CLEAN} allows for access to much of the metadata of the compiler.
+For example, \cleaninline{Cons}, \cleaninline{Object}, \cleaninline{Field}, and \cleaninline{Record} generic constructors are enriched with their arity, names, types, \etc.
+Furthermore, constructors can access the metadata of the objects and fields of their parent records.
+Using this metadata, generic functions are created that generate \ccpp{} type definitions, parsers and printers for any first-order \gls{CLEAN} type.
+The exact details of this technique can be found in the future in a paper that is in preparation.
+
+\Glspl{ADT} are converted to tagged unions, newtypes to typedefs, records to structs, and arrays to dynamic size-parametrised allocated arrays.
+For example, the \gls{CLEAN} types in \cref{lst:ser_clean} are translated to the \ccpp{} types seen in \cref{lst:ser_c}
+
+\begin{lstClean}[caption={Simple \glspl{ADT} in \gls{CLEAN}.},label={lst:ser_clean}]
+:: T a = A a | B NT {#Char}
+:: NT =: NT Real
+\end{lstClean}
+
+\begin{lstArduino}[caption={Generated \ccpp{} type definitions for the simple \glspl{ADT}.},label={lst:ser_c}]
+typedef double Real;
+typedef char Char;
+
+typedef Real NT;
+enum T_c {A_c, B_c};
+
+struct Char_HshArray { uint32_t size; Char *elements; };
+struct T {
+ enum T_c cons;
+ struct { void *A;
+ struct { NT f0; struct Char_HshArray f1; } B;
+ } data;
+};
+\end{lstArduino}
+
+For each of these generated types, two functions are created, a typed printer, and a typed parser (see \cref{lst:ser_pp}).
+The parser functions are parametrised by a read function, an allocation function and parse functions for all type variables.
+This allows for the use of these functions in environments where the communication is parametrised and the memory management is self-managed such as in the \gls{MTASK} \gls{RTS}.
+
+\begin{lstArduino}[caption={Printer and parser for the \glspl{ADT} in \ccpp{}.},label={lst:ser_pp}]
+struct T parse_T(uint8_t (*get)(), void *(*alloc)(size_t),
+ void *(*parse_0)(uint8_t (*)(), void *(*)(size_t)));
+
+void print_T(void (*put)(uint8_t), struct T r,
+ void (*print_0)(void (*)(uint8_t), void *));
+\end{lstArduino}
+
+\section{Conclusion}
+This chapter showed the implementation of the \gls{MTASK} byte code compiler, the \gls{RTS}, and the internals of their communication.
+It is not straightforward to execute \gls{MTASK} tasks on resources-constrained \gls{IOT} edge devices.
+To achieve this, the terms in the \gls{DSL} are compiled to compact domain-specific byte code.
+This byte code is sent for interpretation to the light-weight \gls{RTS} of the edge device.
+The \gls{RTS} first evaluates the main expression in the interpreter.
+The result of this evaluation, a run time representation of the task, is a task tree.
+This task tree is rewritten according to small-step reduction rules until a stable value is observed.
+Rewriting multiple tasks at the same time is achieved by interleaving the rewrite steps, resulting in seemingly parallel execution of the tasks.
+All communication, including the serialisation and deserialisation, between the server and the \gls{RTS} is automated.
+From the structural representation of the types, printers and parsers are generated for the server and the client.