d33198b3ba0a19dbb083fe4c70d9645de772207c
[phd-thesis.git] / top / imp.tex
1 \documentclass[../thesis.tex]{subfiles}
2
3 \input{subfilepreamble}
4
5 \begin{document}
6 \input{subfileprefix}
7 \chapter{Implementation}%
8 \label{chp:implementation}
9 \begin{chapterabstract}
10 This chapter shows the implementation of the \gls{MTASK} system.
11 It is threefold: first it shows the implementation of the byte code compiler for \gls{MTASK}'s \gls{TOP} language, then is details of the implementation of \gls{MTASK}'s \gls{TOP} engine that executes the \gls{MTASK} tasks on the microcontroller, and finally it shows how the integration of \gls{MTASK} tasks and \glspl{SDS} is implemented both on the server and on the device.
12 \end{chapterabstract}
13
14 Microcontrollers usually have flash-based program memory which wears out fairly quick.
15 For example, the atmega328p in the \gls{ARDUINO} UNO is rated for 10000 write cycles.
16 While this sounds like a lot, if new tasks are sent to the device every minute or so, a lifetime of not even seven days is guaranteed.
17 Hence, for dynamic applications, generating code at run-time for interpretation on the device is necessary.
18 This byte code is then interpreted on MCUs with very little memory and processing power and thus save precious write cycles of the program memory.
19 precious write cycles of the program memory.
20
21 In order to provide the device with the tools to interpret the byte code, it is programmed with a \gls{RTS}, a customisable domain-specific \gls{OS} that takes care of the execution of tasks but also low-level mechanisms such as the communication, multi tasking, and memory management.
22 Once the device is programmed with the \gls{MTASK} \gls{RTS}, it can continuously receive new tasks.
23
24 \subsection{Instruction set}
25 The instruction set is a fairly standard stack machine instruction set extended with special \gls{TOP} instructions.
26 \Cref{lst:instruction_type} shows the \gls{CLEAN} type representing the instruction set of which \cref{tbl:instr_task} gives detailed semantics.
27 Type synonyms are used to provide insight on the arguments of the instructions.
28 One notable instruction is the \cleaninline{MkTask} instruction, it allocates and initialises a task tree node and pushes a pointer to it on the stack.
29
30 \begin{lstClean}[caption={The type housing the instruction set.},label={lst:instruction_type}]
31 :: ArgWidth :== UInt8 :: ReturnWidth :== UInt8
32 :: Depth :== UInt8 :: Num :== UInt8
33 :: SdsId :== UInt8 :: JumpLabel =: JL UInt16
34
35 //** Datatype housing all instructions
36 :: BCInstr
37 //Return instructions
38 //Jumps
39 = BCJumpF JumpLabel | BCJump JumpLabel | BCLabel JumpLabel | BCJumpSR ArgWidth JumpLabel
40 | BCReturn ReturnWidth ArgWidth | BCTailcall ArgWidth ArgWidth JumpLabel
41 //Arguments
42 | BCArgs ArgWidth ArgWidth
43 //Task node creation and refinement
44 | BCMkTask BCTaskType | BCTuneRateMs | BCTuneRateSec
45 //Task value ops
46 | BCIsStable | BCIsUnstable | BCIsNoValue | BCIsValue
47 //Stack ops
48 | BCPush String255 | BCPop Num | BCRot Depth Num | BCDup | BCPushPtrs
49 //Casting
50 | BCItoR | BCItoL | BCRtoI | ...
51 // arith
52 | BCAddI | BCSubI | ...
53 ...
54
55 //** Datatype housing all task types
56 :: BCTaskType
57 = BCStableNode ArgWidth | ArgWidth
58 // Pin io
59 | BCReadD | BCWriteD | BCReadA | BCWriteA | BCPinMode
60 // Interrupts
61 | BCInterrupt
62 // Repeat
63 | BCRepeat
64 // Delay
65 | BCDelay | BCDelayUntil //* Only for internal use
66 // Parallel
67 | BCTAnd | BCTOr
68 //Step
69 | BCStep ArgWidth JumpLabel
70 //Sds ops
71 | BCSdsGet SdsId | BCSdsSet SdsId | BCSdsUpd SdsId JumpLabel
72 // Rate limiter
73 | BCRateLimit
74 ////Peripherals
75 //DHT
76 | BCDHTTemp UInt8 | BCDHTHumid UInt8
77 ...
78 \end{lstClean}
79
80 \subsection{Compiler}
81 The bytecode compiler interpretation for the \gls{MTASK} language is implemented as a monad stack containing a writer monad and a state monad.
82 The writer monad is used to generate code snippets locally without having to store them in the monadic values.
83 The state monad accumulates the code, and stores the stateful data the compiler requires.
84 \Cref{lst:compiler_state} shows the data type for the state, storing:
85 function the compiler currently is in;
86 code of the main expression;
87 context (see \todo{insert ref to compilation rules step here});
88 code for the functions;
89 next fresh label;
90 a list of all the used \glspl{SDS}, either local \glspl{SDS} containing the initial value (\cleaninline{Left}) or lifted \glspl{SDS} (see \cref{sec:liftsds}) containing a reference to the associated \gls{ITASK} \gls{SDS};
91 and finally there is a list of peripherals used.
92
93 \begin{lstClean}[label={lst:compiler_state},caption={\Gls{MTASK}'s byte code compiler type}]
94 :: BCInterpret a :== StateT BCState (WriterT [BCInstr] Identity) a
95 :: BCState =
96 { bcs_infun :: JumpLabel
97 , bcs_mainexpr :: [BCInstr]
98 , bcs_context :: [BCInstr]
99 , bcs_functions :: Map JumpLabel BCFunction
100 , bcs_freshlabel :: JumpLabel
101 , bcs_sdses :: [Either String255 MTLens]
102 , bcs_hardware :: [BCPeripheral]
103 }
104 :: BCFunction =
105 { bcf_instructions :: [BCInstr]
106 , bcf_argwidth :: UInt8
107 , bcf_returnwidth :: UInt8
108 }
109 \end{lstClean}
110
111 Executing the compiler is done by providing an initial state.
112 After compilation, several post-processing steps are applied to make the code suitable for the microprocessor.
113 First, in all tail call \cleaninline{BCReturn}'s are replaced by \cleaninline{BCTailCall} to implement tail call elimination.
114 Furthermore, all byte code is concatenated, resulting in one big program.
115 Many instructions have commonly used arguments so shorthands are introduced to reduce the program size.
116 For example, the \cleaninline{BCArg} instruction is often called with argument \qtyrange{0}{2} and can be replaced by the \cleaninline{BCArg0}--\cleaninline{BCArg2} shorthands.
117 Furthermore, redundant instructions (e.g.\ pop directly after push) are removed as well in order not to burden the code generation with these intricacies.
118 Finally the labels are resolved to represent actual program addresses instead of freshly generated identifiers.
119 After the byte code is ready, the lifted \glspl{SDS} are resolved to provide an initial value for them.
120 The result---byte code, \gls{SDS} specification and perpipheral specifications---are the result of the process, ready to be sent to the device.
121
122 \section{Compilation rules}
123 This section describes the compilation rules, the translation from abstract syntax to byte code.
124 The compilation scheme consists of three schemes\slash{}functions.
125 When something is surrounded by double vertical bars, e.g.\ $\stacksize{a_i}$, it denotes the number of stack cells required to store it.
126
127 Some schemes have a \emph{context} $r$ as an argument which contains information about the location of the arguments in scope.
128 More information is given in the schemes requiring such arguments.
129
130 \newcommand{\cschemeE}[2]{\mathcal{E}\llbracket#1\rrbracket~#2}
131 \newcommand{\cschemeF}[1]{\mathcal{F}\llbracket#1\rrbracket}
132 \newcommand{\cschemeS}[3]{\mathcal{S}\llbracket#1\rrbracket~#2~#3}
133 \begin{table}
134 \centering
135 \begin{tabularx}{\linewidth}{l X}
136 \toprule
137 Scheme & Description\\
138 \midrule
139 $\cschemeE{e}{r}$ & Produces the value of expression $e$ given the context $r$ and pushes it on the stack.
140 The result can be a basic value or a pointer to a task.\\
141 $\cschemeF{e}$ & Generates the bytecode for functions.\\
142 $\cschemeS{e}{r}{w} $ & Generates the function for the step continuation given the context $r$ and the width $w$ of the left-hand side task value.\\
143 \bottomrule
144 \end{tabularx}
145 \end{table}
146
147 \subsection{Expressions}
148 Almost all expression constructions are compiled using $\mathcal{E}$.
149 The argument of $\mathcal{E}$ is the context (see \cref{ssec:functions}).
150 Values are always placed on the stack; tuples and other compound data types are unpacked.
151 Function calls, function arguments and tasks are also compiled using $\mathcal{E}$ but their compilations is explained later.
152
153 \begin{align*}
154 \cschemeE{\text{\cleaninline{lit}}~e}{r} & = \text{\cleaninline{BCPush (bytecode e)}};\\
155 \cschemeE{e_1\mathbin{\text{\cleaninline{+.}}}e_2}{r} & = \cschemeE{e_1}{r};
156 \cschemeE{e_2}{r};
157 \text{\cleaninline{BCAdd}};\\
158 {} & \text{\emph{Similar for other binary operators}}\\
159 \cschemeE{\text{\cleaninline{Not}}~e}{r} & =
160 \cschemeE{e}{r};
161 \text{\cleaninline{BCNot}};\\
162 {} & \text{\emph{Similar for other unary operators}}\\
163 \cschemeE{\text{\cleaninline{If}}~e_1~e_2~e_3}{r} & =
164 \cschemeE{e_1}{r};
165 \text{\cleaninline{BCJmpF}}\enskip l_{else}; \mathbin{\phantom{=}} \cschemeE{e_2}{r}; \text{\cleaninline{BCJmp}}\enskip l_{endif};\\
166 {} & \mathbin{\phantom{=}} \text{\cleaninline{BCLabel}}\enskip l_{else}; \cschemeE{e_3}{r}; \mathbin{\phantom{=}} \text{\cleaninline{BCLabel}}\enskip l_{endif};\\
167 {} & \text{\emph{Where $l_{else}$ and $l_{endif}$ are fresh labels}}\\
168 \cschemeE{\text{\cleaninline{tupl}}~e_1~e_2}{r} & =
169 \cschemeE{e_1}{r};
170 \cschemeE{e_2}{r};\\
171 {} & \text{\emph{Similar for other unboxed compound data types}}\\
172 \cschemeE{\text{\cleaninline{first}}~e}{r} & =
173 \cschemeE{e}{r};
174 \text{\cleaninline{BCPop}}\enskip w;\\
175 {} & \text{\emph{Where $w$ is the width of the left value and}}\\
176 {} & \text{\emph{similar for other unboxed compound data types}}\\
177 \cschemeE{\text{\cleaninline{second}}\enskip e}{r} & =
178 \cschemeE{e}{r};
179 \text{\cleaninline{BCRot}}\enskip w_1\enskip (w_1+w_2);
180 \text{\cleaninline{BCPop}}\enskip w_2;\\
181 {} & \text{\emph{Where $w_1$ is the width of the left and, $w_2$ of the right value}}\\
182 {} & \text{\emph{similar for other unboxed compound data types}}\\
183 \end{align*}
184
185 Translating $\mathcal{E}$ to \gls{CLEAN} code is very straightforward, it basically means executing the monad.
186 Almost always, the type of the interpretation is not used, i.e.\ it is a phantom type.
187 To still have the functions return the correct type, the \cleaninline{tell`}\footnote{\cleaninline{tell` :: [BCInstr] -> BCInterpret a}} helper is used.
188 This function is similar to the writer monad's \cleaninline{tell} function but is casted to the correct type.
189 \Cref{lst:imp_arith} shows the implementation for the arithmetic and conditional expressions.
190 Note that $r$, the context, is not an explicit argument but stored in the state.
191
192 \begin{lstClean}[caption={Interpretation implementation for the arithmetic and conditional classes.},label={lst:imp_arith}]
193 instance expr BCInterpret where
194 lit t = tell` [BCPush (toByteCode{|*|} t)]
195 (+.) a b = a >>| b >>| tell` [BCAdd]
196 ...
197 If c t e = freshlabel >>= \elselabel->freshlabel >>= \endiflabel->
198 c >>| tell` [BCJumpF elselabel] >>|
199 t >>| tell` [BCJump endiflabel,BCLabel elselabel] >>|
200 e >>| tell` [BCLabel endiflabel]
201 \end{lstClean}
202
203 \subsection{Functions}
204 Compiling functions occurs in $\mathcal{F}$, which generates bytecode for the complete program by iterating over the functions and ending with the main expression.
205 When compiling the body of the function, the arguments of the function are added to the context so that the addresses can be determined when referencing arguments.
206 The main expression is a special case of $\mathcal{F}$ since it neither has arguments nor something to continue.
207 Therefore, it is just compiled using $\mathcal{E}$.
208
209 \begin{align*}
210 \cschemeF{main=m} & =
211 \cschemeE{m}{[]};\\
212 \cschemeF{f~a_0 \ldots a_n = b~\text{\cleaninline{In}}~m} & =
213 \text{\cleaninline{BCLabel}}~f; \cschemeE{b}{[\langle f, i\rangle, i\in \{(\Sigma^n_{i=0}\stacksize{a_i})..0\}]};\\
214 {} & \mathbin{\phantom{=}} \text{\cleaninline{BCReturn}}~\stacksize{b}~n; \cschemeF{m};\\
215 \end{align*}
216
217 A function call starts by pushing the stack and frame pointer, and making space for the program counter (\cref{lst:funcall_pushptrs}) followed by evaluating the arguments in reverse order (\cref{lst:funcall_args}).
218 On executing \cleaninline{BCJumpSR}, the program counter is set and the interpreter jumps to the function (\cref{lst:funcall_jumpsr}).
219 When the function returns, the return value overwrites the old pointers and the arguments.
220 This occurs right after a \cleaninline{BCReturn} (\cref{lst:funcall_ret}).
221 Putting the arguments on top of pointers and not reserving space for the return value uses little space and facilitates tail call optimization.
222
223 \begin{figure}
224 \begin{subfigure}{.24\linewidth}
225 \centering
226 \includestandalone{memory1}
227 \caption{\cleaninline{BCPushPtrs}}\label{lst:funcall_pushptrs}
228 \end{subfigure}
229 \begin{subfigure}{.24\linewidth}
230 \centering
231 \includestandalone{memory2}
232 \caption{Arguments}\label{lst:funcall_args}
233 \end{subfigure}
234 \begin{subfigure}{.24\linewidth}
235 \centering
236 \includestandalone{memory3}
237 \caption{\cleaninline{BCJumpSR}}\label{lst:funcall_jumpsr}
238 \end{subfigure}
239 \begin{subfigure}{.24\linewidth}
240 \centering
241 \includestandalone{memory4}
242 \caption{\cleaninline{BCReturn}}\label{lst:funcall_ret}
243 \end{subfigure}
244 \caption{The stack layout during function calls.}%
245 \end{figure}
246
247 Calling a function and referencing function arguments are an extension to $\mathcal{E}$ as shown below.
248 Arguments may be at different places on the stack at different times (see \cref{ssec:step}) and therefore the exact location always has to be determined from the context using \cleaninline{findarg}\footnote{\cleaninline{findarg [l`:r] l = if (l == l`) 0 (1 + findarg r l)}}.
249 Compiling argument $a_{f^i}$, the $i$th argument in function $f$, consists of traversing all positions in the current context.
250 Arguments wider than one stack cell are fetched in reverse to preserve the order.
251
252 \begin{align*}
253 \cschemeE{f(a_0, \ldots, a_n)}{r} & =
254 \text{\cleaninline{BCPushPtrs}}; \cschemeE{a_n}{r}; \cschemeE{a_{\ldots}}{r}; \cschemeE{a_0}{r}; \text{\cleaninline{BCJumpSR}}~n~f;\\
255 \cschemeE{a_{f^i}}{r} & =
256 \text{\cleaninline{BCArg}~findarg}(r, f, i)~\text{for all}~i\in\{w\ldots v\};\\
257 {} & v = \Sigma^{i-1}_{j=0}\stacksize{a_{f^j}}~\text{ and }~ w = v + \stacksize{a_{f^i}}\\
258 \end{align*}
259
260 Translating the compilation schemes for functions to Clean is not as straightforward as other schemes due to the nature of shallow embedding.\todo{deze \P{} moet ge\-\"up\-da\-ted worden}
261 The \cleaninline{fun} class has a single function with a single argument.
262 This argument is a Clean function that---when given a callable Clean function representing the mTask function---will produce \cleaninline{main} and a callable function.
263 To compile this, the argument must be called with a function representing a function call in mTask.
264 \Cref{lst:fun_imp} shows the implementation for this as Clean code.
265 To uniquely identify the function, a fresh label is generated.
266 The function is then called with the \cleaninline{callFunction} helper function that generates the instructions that correspond to calling the function.
267 That is, it pushes the pointers, compiles the arguments, and writes the \cleaninline{JumpSR} instruction.
268 The resulting structure (\cleaninline{g In m}) contains a function representing the mTask function (\cleaninline{g}) and the \cleaninline{main} structure to continue with.
269 To get the actual function, \cleaninline{g} must be called with representations for the argument, i.e.\ using \cleaninline{findarg} for all arguments.
270 The arguments are added to the context and \cleaninline{liftFunction} is called with the label, the argument width and the compiler.
271 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.
272 After lifting the function, the context is cleared again and compilation continues with the rest of the program.
273
274 \begin{lstClean}[label={lst:fun_imp},caption={The backend implementation for functions.}]
275 instance fun (BCInterpret a) BCInterpret | type a where
276 fun def = {main=freshlabel >>= \funlabel->
277 let (g In m) = def \a->callFunction funlabel (toByteWidth a) [a]
278 argwidth = toByteWidth (argOf g)
279 in addToCtx funlabel zero argwidth
280 >>| infun funlabel
281 (liftFunction funlabel argwidth
282 (g (retrieveArgs funlabel zero argwidth)
283 ) ?None)
284 >>| clearCtx >>| m.main
285 }
286
287 argOf :: ((m a) -> b) a -> UInt8 | toByteWidth a
288 callFunction :: JumpLabel UInt8 [BCInterpret b] -> BCInterpret c | ...
289 liftFunction :: JumpLabel UInt8 (BCInterpret a) (?UInt8) -> BCInterpret ()
290 \end{lstClean}
291
292 \subsection{Tasks}
293 Task trees are created with the \cleaninline{BCMkTask} instruction that allocates a node and pushes it to the stack.
294 It pops arguments from the stack according to the given task type.
295 The following extension of $\mathcal{E}$ shows this compilation scheme (except for the step combinator, explained in \cref{ssec:step}).
296
297 \begin{align*}
298 \cschemeE{\text{\cleaninline{rtrn}}~e}{r} & =
299 \cschemeE{e}{r};
300 \text{\cleaninline{BCMkTask BCStable}}_{\stacksize{e}};\\
301 \cschemeE{\text{\cleaninline{unstable}}~e}{r} & =
302 \cschemeE{e}{r};
303 \text{\cleaninline{BCMkTask BCUnstable}}_{\stacksize{e}};\\
304 \cschemeE{\text{\cleaninline{readA}}~e}{r} & =
305 \cschemeE{e}{r};
306 \text{\cleaninline{BCMkTask BCReadA}};\\
307 \cschemeE{\text{\cleaninline{writeA}}~e_1~e_2}{r} & =
308 \cschemeE{e_1}{r};
309 \cschemeE{e_2}{r};
310 \text{\cleaninline{BCMkTask BCWriteA}};\\
311 \cschemeE{\text{\cleaninline{readD}}~e}{r} & =
312 \cschemeE{e}{r};
313 \text{\cleaninline{BCMkTask BCReadD}};\\
314 \cschemeE{\text{\cleaninline{writeD}}~e_1~e_2}{r} & =
315 \cschemeE{e_1}{r};
316 \cschemeE{e_2}{r};
317 \text{\cleaninline{BCMkTask BCWriteD}};\\
318 \cschemeE{\text{\cleaninline{delay}}~e}{r} & =
319 \cschemeE{e}{r};
320 \text{\cleaninline{BCMkTask BCDelay}};\\
321 \cschemeE{\text{\cleaninline{rpeat}}~e}{r} & =
322 \cschemeE{e}{r};
323 \text{\cleaninline{BCMkTask BCRepeat}};\\
324 \cschemeE{e_1\text{\cleaninline{.\|\|.}}e_2}{r} & =
325 \cschemeE{e_1}{r};
326 \cschemeE{e_2}{r};
327 \text{\cleaninline{BCMkTask BCOr}};\\
328 \cschemeE{e_1\text{\cleaninline{.&&.}}e_2}{r} & =
329 \cschemeE{e_1}{r};
330 \cschemeE{e_2}{r};
331 \text{\cleaninline{BCMkTask BCAnd}};\\
332 \end{align*}
333
334 This simply translates to Clean code by writing the correct \cleaninline{BCMkTask} instruction as exemplified in \cref{lst:imp_ret}.
335
336 \begin{lstClean}[caption={The backend implementation for \cleaninline{rtrn}.},label={lst:imp_ret}]
337 instance rtrn BCInterpret
338 where
339 rtrn m = m >>| tell` [BCMkTask (bcstable m)]
340 \end{lstClean}
341
342 \subsection{Step combinator}\label{ssec:step}
343 The \cleaninline{step} construct is a special type of task because the task value of the left-hand side may change over time.
344 Therefore, the continuation tasks on the right-hand side are \emph{observing} this task value and acting upon it.
345 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.
346 This function either returns a pointer to a task tree or fails (denoted by $\bot$).
347 It is special because in the generated function, the task value of a task can actually be inspected.
348 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).
349 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.
350 The resulting function is basically a list of if-then-else constructions to check all predicates one by one.
351 Some optimization is possible here but has currently not been implemented.
352
353 \begin{align*}
354 \cschemeE{t_1\text{\cleaninline{>>*.}}t_2}{r} & =
355 \cschemeE{a_{f^i}}{r}, \langle f, i\rangle\in r;
356 \text{\cleaninline{BCMkTask}}~\text{\cleaninline{BCStable}}_{\stacksize{r}}; \cschemeE{t_1}{r};\\
357 {} & \mathbin{\phantom{=}} \text{\cleaninline{BCMkTask}}~\text{\cleaninline{BCAnd}}; \text{\cleaninline{BCMkTask}}~(\text{\cleaninline{BCStep}}~(\cschemeS{t_2}{(r + [\langle l_s, i\rangle])}{\stacksize{t_1}}));\\
358 \end{align*}
359
360 \begin{align*}
361 \cschemeS{[]}{r}{w} & =
362 \text{\cleaninline{BCPush}}~\bot;\\
363 \cschemeS{\text{\cleaninline{IfValue}}~f~t:cs}{r}{w} & =
364 \text{\cleaninline{BCArg}} (\stacksize{r} + w);
365 \text{\cleaninline{BCIsNoValue}};\\
366 {} & \mathbin{\phantom{=}} \cschemeE{f}{r};
367 \text{\cleaninline{BCAnd}};\\
368 {} & \mathbin{\phantom{=}} \text{\cleaninline{BCJmpF}}~l_1;\\
369 {} & \mathbin{\phantom{=}} \cschemeE{t}{r};
370 \text{\cleaninline{BCJmp}}~l_2;\\
371 {} & \mathbin{\phantom{=}} \text{\cleaninline{BCLabel}}~l_1;
372 \cschemeS{cs}{r}{w};\\
373 {} & \mathbin{\phantom{=}} \text{\cleaninline{BCLabel}}~l_2;\\
374 {} & \text{\emph{Where $l_1$ and $l_2$ are fresh labels}}\\
375 {} & \text{\emph{Similar for \cleaninline{IfStable} and \cleaninline{IfUnstable}}}\\
376 \end{align*}
377
378 First the context is evaluated.
379 The context contains arguments from functions and steps that need to be preserved after rewriting.
380 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.
381 This means that the task tree is be transformed as follows:
382
383 \begin{lstClean}
384 t1 >>= \v1->t2 >>= \v2->t3 >>= ...
385 //is transformed to
386 t1 >>= \v1->rtrn v1 .&&. t2 >>= \v2->rtrn (v1, v2) .&&. t3 >>= ...
387 \end{lstClean}
388
389 The translation to \gls{CLEAN} is given in \cref{lst:imp_seq}.
390
391 \begin{lstClean}[caption={Backend implementation for the step class.},label={lst:imp_seq}]
392 instance step BCInterpret where
393 (>>*.) lhs cont
394 //Fetch a fresh label and fetch the context
395 = freshlabel >>= \funlab->gets (\s->s.bcs_context)
396 //Generate code for lhs
397 >>= \ctx->lhs
398 //Possibly add the context
399 >>| tell` (if (ctx =: []) []
400 //The context is just the arguments up till now in reverse
401 ( [BCArg (UInt8 i)\\i<-reverse (indexList ctx)]
402 ++ map BCMkTask (bcstable (UInt8 (length ctx)))
403 ++ [BCMkTask BCTAnd]
404 ))
405 //Increase the context
406 >>| addToCtx funlab zero lhswidth
407 //Lift the step function
408 >>| liftFunction funlab
409 //Width of the arguments is the width of the lhs plus the
410 //stability plus the context
411 (one + lhswidth + (UInt8 (length ctx)))
412 //Body label ctx width continuations
413 (contfun funlab (UInt8 (length ctx)))
414 //Return width (always 1, a task pointer)
415 (Just one)
416 >>| modify (\s->{s & bcs_context=ctx})
417 >>| tell` [BCMkTask (instr rhswidth funlab)]
418
419 toContFun :: JumpLabel UInt8 -> BCInterpret a
420 toContFun steplabel contextwidth
421 = foldr tcf (tell` [BCPush fail]) cont
422 where
423 tcf (IfStable f t)
424 = If ((stability >>| tell` [BCIsStable]) &. f val)
425 (t val >>| tell` [])
426 ...
427 stability = tell` [BCArg (lhswidth + contextwidth)]
428 val = retrieveArgs steplabel zero lhswidth
429 \end{lstClean}
430
431 \subsection{\texorpdfstring{\Glspl{SDS}}{Shared data sources}}
432 The compilation scheme for \gls{SDS} definitions is a trivial extension to $\mathcal{F}$ since there is no code generated as seen below.
433
434 \begin{align*}
435 \cschemeF{\text{\cleaninline{sds}}~x=i~\text{\cleaninline{In}}~m} & =
436 \cschemeF{m};\\
437 \end{align*}
438
439 The \gls{SDS} access tasks have a compilation scheme similar to other tasks (see \cref{ssec:scheme_tasks}).
440 The \cleaninline{getSds} task just pushes a task tree node with the \gls{SDS} identifier embedded.
441 The \cleaninline{setSds} task evaluates the value, lifts that value to a task tree node and creates an \gls{SDS} set node.
442
443 \begin{align*}
444 \cschemeE{\text{\cleaninline{getSds}}~s}{r} & =
445 \text{\cleaninline{BCMkTask}} (\text{\cleaninline{BCSdsGet}} s);\\
446 \cschemeE{\text{\cleaninline{setSds}}~s~e}{r} & =
447 \cschemeE{e}{r};
448 \text{\cleaninline{BCMkTask BCStable}}_{\stacksize{e}};\\
449 {} & \mathbin{\phantom{=}} \text{\cleaninline{BCMkTask}} (\text{\cleaninline{BCSdsSet}} s);\\
450 \end{align*}
451
452 While there is no code generated in the definition, the byte code compiler is storing the \gls{SDS} data in the \cleaninline{bcs_sdses} field in the compilation state.
453 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.
454 For this, an \cleaninline{BCInterpret} is created that emits this identifier.
455 When passing it to the function, the initial value of the \gls{SDS} is returned.
456 This initial value is stored as a byte code encoded value in the state and the compiler continues with the rest of the program.
457
458 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.
459 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.
460 Lifted SDSs are compiled in a very similar way.\todo{deze \P{} moet naar integration?}
461 The only difference is that there is no initial value but an iTasks SDS when executing the Clean function.
462 A lens on this SDS converting \cleaninline{a} from the \cleaninline{Shared a} to a \cleaninline{String255}---a bytecode encoded version---is stored in the state.
463 The encoding and decoding itself is unsafe when used directly but the type system of the language and the abstractions make it safe.
464 Upon sending the mTask task to the device, the initial values of the lifted SDSs are fetched to complete the SDS specification.
465
466 % VimTeX: SynIgnore on
467 \begin{lstClean}[caption={Backend implementation for the SDS classes.},label={lst:comp_sds}]
468 :: Sds a = Sds Int
469 instance sds BCInterpret where
470 sds def = {main = freshsds >>= \sdsi->
471 let sds = modify (\s->{s & bcs_sdses=put sdsi
472 (Left (toByteCode t)) s.bcs_sdses})
473 >>| pure (Sds sdsi)
474 (t In e) = def sds
475 in e.main}
476 getSds f = f >>= \(Sds i)-> tell` [BCMkTask (BCSdsGet (fromInt i))]
477 setSds f v = f >>= \(Sds i)->v >>| tell`
478 ( map BCMkTask (bcstable (byteWidth v))
479 ++ [BCMkTask (BCSdsSet (fromInt i))])
480 \end{lstClean}
481 % VimTeX: SynIgnore off
482
483
484 \section{\texorpdfstring{\Gls{RTS}}{Run time system}}
485
486 The \gls{RTS} is designed to run on systems with as little as \qty{2}{\kibi\byte} of \gls{RAM}.
487 Aggressive memory management is therefore vital.
488 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.
489 Therefore 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}.
490 The size of this block can be changed in the configuration of the \gls{RTS} if necessary.
491 On an \gls{ARDUINO} UNO ---equipped with \qty{2}{\kibi\byte} of \gls{RAM}--- this size is about \qty{1500}{\byte}.
492
493 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.
494 As a consequence, the stack moves when a new task is received.
495 This never happens within execution because communication is always processed before execution.
496 Values in the interpreter are always stored on the stack, even tuples.
497 Task trees grow from the top down as in a heap.
498 This approach allows for flexible ratios, i.e.\ many tasks and small trees or few tasks and big trees.
499
500 The event loop of the \gls{RTS} is executed repeatedly and consists of three distinct phases.
501 \todo{plaa\-tje van me\-mo\-ry hier}
502 \todo{pseu\-do\-code hier van de ex\-e\-cu\-tie}
503
504 %TODO evt subsubsections verwijderen
505 \subsection{Communication}
506 In the first phase, the communication channels are processed.
507 The messages announcing \gls{SDS} updates are applied immediately, the initialization of new tasks is delayed until the next phase.
508
509 \subsection{Execution}
510 The second phase consists of executing tasks.
511 The \gls{RTS} executes all tasks in a round robin fashion.
512 If a task is not initialized yet, the bytecode of the main function is interpreted to produce the initial task tree.
513 The rewriting engine uses the interpreter when needed, e.g.\ to calculate the step continuations.
514 The rewriter and the interpreter use the same stack to store intermediate values.
515 Rewriting steps are small so that interleaving results in seemingly parallel execution.
516 In this phase new task tree nodes may be allocated.
517 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.
518 The host is notified if a task value is changed after a rewrite step.
519
520 \subsection{Memory management}
521 The third and final phase is memory management.
522 Stable tasks, and unreachable task tree nodes are removed.
523 If a task is to be removed, tasks with higher memory addresses are moved down.
524 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.
525 This is possible because there is no sharing or cycles in task trees and nodes contain pointers pointers to their parent.
526
527 \input{subfilepostamble}
528 \end{document}