Merge branch 'master' of git.martlubbers.net:msc-thesis1617
[msc-thesis1617.git] / mtaskext.examples.tex
1 As an example for the bytecode compilation the following listing shows the
2 thermostat example given in Listing~\ref{lst:exmtask} compiled to bytecode.
3 The left column indicates the position in the program memory. The \CI{endif}
4 label is resolved to an address outside of the program space. This is not a
5 problem since this is included in the stopping condition of the interpreter.
6 When the program counter exceeds the length of the program, the task
7 terminates.
8
9 \begin{lstlisting}[language=Clean,caption={Thermostat bytecode},language=c]
10 0-1 : BCAnalogRead (Analog A0)
11 2-5 : BCPush (Int 50)
12 6 : BCGre
13 7-8 : BCJmpF 17 //Jump to else
14 9-11: BCPush (Bool 1)
15 12-13: BCDigitalWrite (Digital D0)
16 14-15: BCJmp 21 //Jump to endif
17 16-18: BCPush (Bool 0) //Else label
18 19 : BCDigitalWrite (Digital D0)
19 20 : //Endif label
20 \end{lstlisting}
21
22 The factorial function can be expressed as an \gls{mTask}-\gls{Task} and uses
23 the \CI{sds} and the \CI{return} functionality. Typically this \gls{Task} is
24 called with the \CI{OnInterval} scheduling strategy and will calculate the
25 factorial after which is will return. The following listings shows the actual
26 \gls{mTask} and the generated messages followed by the actual bytecode in a
27 readable form.
28
29 \begin{lstlisting}[language=Clean,caption={Factorial as an \gls{mTask}-\gls{Task}}]
30 factorial :: Int -> Main (ByteCode () Stmt)
31 factorial i = sds \y=i In
32 namedsds \x=1 Named "result" In
33 {main =
34 IF (y <=. lit 1) (
35 pub x :. retrn
36 ) (
37 x =. x *. y :. y =. y -. lit 1
38 )}
39
40 //Generating the actual messages with:
41 Start = fst $ toMessages (OnInterval 500) (factorial 5) zero
42
43 //The output will be
44 //[MTSds 2 (BCValue 5), MTSds 1 (BCValue 1), MTTask (OnInterval 500) ...]
45 \end{lstlisting}
46
47 \begin{lstlisting}[language=Clean,label={lst:actualbc},%
48 caption={The resulting bytecode for the factorial function},language=C]
49 0-2 : BCSdsFetch 1
50 3-6 : BCPush (Int 1)
51 7 : BCLeq
52 8-9 : BCJmpF 16 //Jump to else
53 10-12: BCSdsPublish 2 ("result")
54 13 : BCReturn
55 14-15: BCJmp 37 //Jump to endif
56 16-18: BCSdsFetch 2 ("result") //Else label
57 19-21: BCSdsFetch 1
58 22 : BCMul
59 23-25: BCSdsStore 2 ("result")
60 26-28: BCSdsFetch 1
61 29-32: BCPush (Int 1)
62 33 : BCSub
63 34-36: BCSdsStore 1
64 37 : //Endif label
65 \end{lstlisting}