update a lot, try to type shares
[mTask.git] / mTaskInterpret.icl
index dca53d4..5acd1da 100644 (file)
@@ -1,11 +1,13 @@
 implementation module mTaskInterpret
 
-//import iTasks
-import gdynamic, gCons, GenEq, StdMisc, StdArray, GenBimap
+import Generics.gCons
+
+import GenEq, StdMisc, StdArray, GenBimap
 import GenPrint
 import StdEnum
 import mTask
 
+import StdInt
 import StdFile
 import StdString
 
@@ -17,206 +19,244 @@ import Data.Monoid
 import Data.Functor
 import StdList
 from Data.Func import $
-from Text import class Text(concat,join,toUpperCase), instance Text String
+from Text import class Text(concat,toUpperCase), instance Text String
+import qualified Text
+import Text.JSON
+
+import Control.Monad.RWST
+import Control.Monad.Identity
+import Control.Monad
+import Control.Applicative
+import Data.Functor
+import Data.Either
 
+import Data.Array
 import qualified Data.Map as DM
+import qualified Data.List as DL
 import Text.Encodings.Base64
 
 encode :: MTaskMSGSend -> String
+encode (MTTask to data) = "t" +++ tob +++ to16bit (size data) +++ data +++ "\n"
+       where 
+               tob = case to of
+                       OneShot = to16bit 0
+                       OnInterval i = to16bit i
+                       OnInterrupt _ = abort "Interrupts not implemented yet"
+encode (MTTaskDel i) = "d" +++ to16bit i +++ "\n"
 encode (MTSds i v) = "s" +++ to16bit i +++ v +++ "\n"
-encode (MTTask to data) = "t" +++ to16bit to +++ to16bit (size data) +++ data +++ "\n"
 encode (MTUpd i v) = "u" +++ to16bit i +++ v +++ "\n"
 
-import StdDebug
 decode :: String -> MTaskMSGRecv
 decode x
 | size x == 0 = MTEmpty
 = case x.[0] of
+       't' = MTTaskAck (from16bit (x % (1,3)))
+       'd' = MTTaskDelAck (from16bit (x % (1,3)))
+       'm' = MTMessage x
+       's' = MTSDSAck (from16bit (x % (1,3)))
+       'a' = MTSDSDelAck (from16bit (x % (1,3)))
+       'p' = MTPub (from16bit (x % (1,3))) (x % (3,5))
        '\0' = MTEmpty
        '\n' = MTEmpty
-       'm' = MTMessage x
-       't' = MTTaskAdded (from16bit (x % (1,3)))
-       'u' = MTPub (from16bit (x % (1,3))) (x % (3,5))
        _ = MTMessage x//abort ("Didn't understand message: " +++ join " " [toString (toInt c)\\c<-: x] +++ "\n")
 
 safePrint :== toString o toJSON
 
+instance toString MTaskInterval where
+       toString OneShot = "One shot"
+       toString (OnInterrupt i) = "Interrupt: " +++ toString i
+       toString (OnInterval i) = "Every " +++ toString i +++ "ms"
+
 instance toString MTaskMSGSend where
        toString (MTSds i v) = "Sds id: " +++ toString i
                +++ " value " +++ safePrint v
        toString (MTTask to data) = "Task timeout: " +++ toString to
                +++ " data " +++ safePrint data
+       toString (MTTaskDel i) = "Task delete request: " +++ toString i
        toString (MTUpd i v) = "Update id: " +++ toString i
                +++ " value " +++ safePrint v
 
 instance toString MTaskMSGRecv where
+       toString (MTTaskAck i) = "Task added with id: " +++ toString i
+       toString (MTTaskDelAck i) = "Task deleted with id: " +++ toString i
+       toString (MTSDSAck i) = "SDS added with id: " +++ toString i
+       toString (MTSDSDelAck i) = "SDS deleted with id: " +++ toString i
        toString (MTPub i v) = "Publish id: " +++ toString i
                +++ " value " +++ safePrint v
-       toString (MTTaskAdded i) = "Task added with id: " +++ toString i
+       toString (MTMessage m) = m
        toString MTEmpty = "Empty message"
 
-bclength :: BC -> Int
-bclength (BCPush _) = 3
-bclength (BCLab _) = 2
-bclength (BCSdsStore _) = 3
-bclength (BCSdsFetch _) = 3
-bclength (BCSdsPublish _) = 3
-bclength (BCAnalogRead _) = 2
-bclength (BCAnalogWrite _) = 2
-bclength (BCDigitalRead _) = 2
-bclength (BCDigitalWrite _) = 2
-bclength (BCJmp i) = 2
-bclength (BCJmpT i) = 2
-bclength (BCJmpF i) = 2
-bclength _ = 1
-
-toByteVal :: BC -> [Char]
-toByteVal b
-# bt = toChar $ consIndex{|*|} b
-= [bt:case b of
+toByteVal :: BC -> String
+toByteVal b = {toChar $ consIndex{|*|} b} +++
+       case b of
                (BCPush i) = i
-               (BCLab i) = [toChar i]
-               (BCSdsStore i) = [c\\c<-:to16bit i]
-               (BCSdsFetch i) = [c\\c<-:to16bit i]
-               (BCSdsPublish i) = [c\\c<-:to16bit i]
-               (BCAnalogRead i) = [toChar i]
-               (BCAnalogWrite i) = [toChar i]
-               (BCDigitalRead i) = [toChar i]
-               (BCDigitalWrite i) = [toChar i]
-               (BCJmp i) = [toChar i]
-               (BCJmpT i) = [toChar i]
-               (BCJmpF i) = [toChar i]
-               _ = []]
-
-instance Semigroup (ByteCode a p) where
-       mappend m n = BC \s->let (b1, (b2, t)) = runBC m <$> runBC m s in (b1 ++ b2, t)
-
-instance Monoid (ByteCode a p) where
-       mempty = retrn []
-
-(<++>) infixl 2 :: (ByteCode a p) (ByteCode b q) -> ByteCode c r
-(<++>) m n = BC \s->let (b1, (b2, t)) = runBC n <$> runBC m s in (b1 ++ b2, t)
-
-(<+->) infixr 1
-(<+->) m n :== m <++> retrn n
-
-runBC (BC m) = m
-
-retrn :: ([BC] -> ByteCode a p)
-retrn = BC o tuple
-fmp :: ([BC] -> [BC]) (ByteCode a p) -> ByteCode a q
-fmp f b = BC \s->let (bc, s`) = runBC b s in (f bc, s`)
-
-instance toByteCode Bool where
-       toByteCode True = [toChar 0, toChar 1]
-       toByteCode False = [toChar 0, toChar 0]
-instance toByteCode Int where toByteCode n = map toChar [n/256,n rem 256]
+               (BCLab i) = {toChar i}
+               (BCSdsStore i) = to16bit i
+               (BCSdsFetch i) = to16bit i
+               (BCSdsPublish i) = to16bit i
+               (BCAnalogRead i) = {toChar i}
+               (BCAnalogWrite i) = {toChar i}
+               (BCDigitalRead i) = {toChar i}
+               (BCDigitalWrite i) = {toChar i}
+               (BCJmp i) = {toChar i}
+               (BCJmpT i) = {toChar i}
+               (BCJmpF i) = {toChar i}
+               _ = ""
+
+//(>>) infixl 2 :: (ByteCode a p) (ByteCode b q) -> ByteCode b q
+//(>>) m n = BC \s->(let (_, s1) = runBC m s in
+//     let (a, s2) = runBC n s1
+//     in (a, {s2 & bytecode=(s2.BCState.bytecode ++ s1.BCState.bytecode)}))
+//
+//(<+->) infixr 1
+//(<+->) m n :== m >> tell n
+//
+//runBC (BC m) = m
+//
+//tell :: [BC] -> ByteCode a p | mTaskType a
+//tell b = BC \s->(zero, {s & bytecode=b++s.bytecode})
+//
+//fmp :: (a -> BC) (ByteCode a p) -> ByteCode a q
+//fmp f b = BC \s->let (a, s`) = runBC b s in (a, {s` & code=[f a:s`.code]})
+
+instance toByteCode Bool where toByteCode b = if b "\x01" "\x00"
+instance toByteCode Int where toByteCode n = {toChar $ n/256,toChar $ n rem 256}
 instance toByteCode Long where toByteCode (L n) = toByteCode n
-instance toByteCode Char where toByteCode c = [c]
-instance toByteCode String where toByteCode s = undef
-instance toByteCode Button where toByteCode s = [toChar $ consIndex{|*|} s]
+instance toByteCode Char where toByteCode s = toString s
+instance toByteCode String where toByteCode s = abort $ "Undef on toBytecode String" +++ s
+instance toByteCode Button where toByteCode s = {toChar $ consIndex{|*|} s}
+instance toByteCode UserLED where toByteCode s = {toChar $ consIndex{|*|} s}
+instance toByteCode MTaskInterval where
+       toByteCode OneShot = toByteCode 0
+       //Intervals have the first bit 0 and the rest is a 15 bit unsigned int
+       toByteCode (OnInterval i) = {toChar $ i/256 bitand 127, toChar $ i rem 256}
+       //Intervals have the first bit 1 and the rest is a 15 bit unsigned int
+       toByteCode (OnInterrupt i) = {toChar $ i/256 bitor 127, toChar $ i rem 256}
+
+instance fromByteCode Bool where fromByteCode s = s == "\x01"
+instance fromByteCode Int where fromByteCode s = (toInt s.[0])*256 + toInt s.[1]
+instance fromByteCode Long where fromByteCode s = L $ fromByteCode s
+instance fromByteCode Char where fromByteCode s = toChar s.[0]
+instance fromByteCode String where fromByteCode s = abort $ "Undef on fromBytecode String" +++ s
+instance fromByteCode Button where fromByteCode s = conses{|*|} !! toInt s.[0]
+instance fromByteCode UserLED where fromByteCode s = conses{|*|} !! toInt s.[0]
+instance fromByteCode MTaskInterval
+       where
+               fromByteCode s
+               //Interval
+               | (toInt s.[0]) bitand 128 == 0 = case fromByteCode s of
+                       0 = OneShot
+                       i = OnInterval i
+               = OnInterrupt $ fromByteCode s bitand 127
 
 instance toChar Pin where
        toChar (Digital p) = toChar $ consIndex{|*|} p
        toChar (Analog p) = toChar $ consIndex{|*|} p
 
-derive gPrint BC, AnalogPin, Pin, DigitalPin
-derive consIndex BC, Pin, Button
-derive consName BC, Pin, Button
+derive gPrint BC
+derive class gCons BC
+
+op2 :: (ByteCode a p1) (ByteCode a p2) BC -> ByteCode b Expr
+op2 (BC x) (BC y) bc = BC $ x >>| y >>| tell [bc]
+
+op :: (ByteCode a p) BC -> ByteCode a Expr
+op (BC x) bc = BC $ x >>| tell [bc]
+
+tell` x = BC $ tell x
+
+instance zero Bool where zero = False
 
 instance arith ByteCode where
-       lit x = retrn [BCPush $ toByteCode x]
-       (+.) x y = x <++> y <+-> [BCAdd]
-       (-.) x y = x <++> y <+-> [BCSub]
-       (*.) x y = x <++> y <+-> [BCMul]
-       (/.) x y = x <++> y <+-> [BCDiv]
+       lit x = tell` [BCPush $ toByteCode x]
+       (+.) x y = op2 x y BCAdd
+       (-.) x y = op2 x y BCSub
+       (*.) x y = op2 x y BCMul
+       (/.) x y = op2 x y BCDiv
 
 instance boolExpr ByteCode where
-       (&.) x y = x <++> y <+-> [BCAnd]
-       (|.) x y = x <++> y <+-> [BCOr]
-       Not x = x <+-> [BCNot]
-       (==.) x y = x <++> y <+-> [BCEq]
-       (!=.) x y = x <++> y <+-> [BCNeq]
-       (<.) x y = x <++> y <+-> [ BCLes]
-       (>.)  x y = x <++> y <+-> [BCGre]
-       (<=.) x y = x <++> y <+-> [BCLeq]
-       (>=.) x y = x <++> y <+-> [BCGeq]
+       (&.) x y =  op2 x y BCAnd
+       (|.) x y =  op2 x y BCOr
+       Not x = op x BCNot
+       (==.) x y = op2 x y BCEq
+       (!=.) x y = op2 x y BCNeq
+       (<.)  x y = op2 x y  BCLes
+       (>.)  x y = op2 x y BCGre
+       (<=.) x y = op2 x y BCLeq
+       (>=.) x y = op2 x y BCGeq
 
 instance analogIO ByteCode where
-       analogRead p = retrn [BCAnalogRead $ pin p]
-       analogWrite p b = b <+-> [BCAnalogWrite $ pin p]
+       analogRead p = tell` [BCAnalogRead $ pin p]
+       analogWrite p b = op b (BCAnalogWrite $ pin p)
 
 instance digitalIO ByteCode where
-       digitalRead p = retrn [BCDigitalRead $ pin p]
-       digitalWrite p b = b <+-> [BCDigitalWrite $ pin p]
+       digitalRead p = tell` [BCDigitalRead $ pin p]
+       digitalWrite p b = op b (BCDigitalWrite $ pin p)
 
-//instance If ByteCode Stmt Stmt Stmt where If b t e = BCIfStmt b t e
-//instance If ByteCode e Stmt Stmt where If b t e = BCIfStmt b t e
-//instance If ByteCode Stmt e Stmt where If b t e = BCIfStmt b t e
+instance If ByteCode Stmt Stmt Stmt where If b t e = BCIfStmt b t e
+instance If ByteCode e Stmt Stmt where If b t e = BCIfStmt b t e
+instance If ByteCode Stmt e Stmt where If b t e = BCIfStmt b t e
 instance If ByteCode x y Stmt where If b t e = BCIfStmt b t e
 instance IF ByteCode where
        IF b t e = BCIfStmt b t e
-       (?) b t = BCIfStmt b t $ retrn []
-BCIfStmt b t e = 
-       withLabel \else->withLabel \endif->
-       b <++> retrn [BCJmpF else] <++> t
-       <++> retrn [BCJmp endif,BCLab else] <++> e <++> retrn [BCLab endif]
+       (?) b t = BCIfStmt b t $ tell` mempty
+BCIfStmt (BC b) (BC t) (BC e) = BC $
+       freshl >>= \else->freshl >>= \endif->
+       b >>| tell [BCJmpF else] >>|
+       t >>| tell [BCJmp endif, BCLab else] >>|
+       e >>| tell [BCLab endif]
 
-instance noOp ByteCode where noOp = retrn [BCNop]
+freshl = get >>= \st=:{freshl=[fr:frs]}->put {st & freshl=frs} >>| pure fr
+freshs = get >>= \st=:{freshs=[fr:frs]}->put {st & freshs=frs} >>| pure fr
 
-withLabel :: (Int -> (ByteCode b q)) -> ByteCode b q
-withLabel f = BC \s->let [fresh:fs] = s.freshl
-       in runBC (f fresh) {s & freshl=fs}
+instance noOp ByteCode where noOp = tell` [BCNop]
 
-withSDS :: (Int -> (ByteCode b q)) -> ByteCode b q
-withSDS f = BC \s->let [fresh:fs] = s.freshs
-       in runBC (f fresh) {s & freshs=fs}
-
-setSDS :: Int v -> ByteCode b q | toByteCode v
-setSDS ident val = BC \s->([], {s & sdss = [(ident, toByteCode val):s.sdss]})
+unBC (BC x) = x
 
 instance sds ByteCode where
-       sds f = {main = withSDS \sds->
-                       let (v In body) = f $ retrn [BCSdsFetch sds]
-                       in setSDS sds v <++> unMain body
-               }
+       sds f = {main = BC $ freshs 
+                               >>= \sds->pure (f (tell` [BCSdsFetch sds]))
+                               >>= \(v In bdy)->modify (addSDS sds (toByteCode v)) >>| unBC (unMain bdy)}
+               where
+                       addSDS i v s = {s & sdss=[{sdsi=i,sdspub=False,sdsval=v}:s.sdss]}
+
        con f = undef
-       pub x = fmp makePub x
-//     pub _ = undef
+       pub (BC x) = BC $ censor (\[BCSdsFetch s]->[BCSdsPublish s])
+                       (listen x >>= \(_, [BCSdsFetch s])->modify (publish s)) >>| tell mempty
+               where
+                       publish i st = {st & sdss=[if (i == s.sdsi) {s & sdspub=True} s \\s<-st.sdss]}
 
 instance assign ByteCode where
-       (=.) v e = e <++> fmp makeStore v
-
-makePub [] = []
-makePub [x:xs] = case x of
-       BCSdsFetch i = [BCSdsPublish i:xs]
-       y = [y:xs]
-
-makeStore [] = []
-makeStore [x:xs] = case x of
-       BCSdsFetch i = [BCSdsStore i:xs]
-       y = [y:xs]
+       (=.) (BC v) (BC e) = BC $ e >>| censor makeStore v
+               where 
+                       //This is going to include pins as well, as variables
+                       makeStore [BCSdsFetch i] = [BCSdsStore i]
 
 instance seq ByteCode where
        (>>=.) _ _ = abort "undef on >>=."
-       (:.) x y = x <++> y
+       (:.) (BC x) (BC y) = BC $ x >>| y
 
 instance serial ByteCode where
-       serialAvailable = retrn [BCSerialAvail]
-       serialPrint s = retrn [BCSerialPrint]
-       serialPrintln s = retrn [BCSerialPrintln]
-       serialRead = retrn [BCSerialRead]
-       serialParseInt = retrn [BCSerialParseInt]
+       serialAvailable = tell` [BCSerialAvail]
+       serialPrint s = tell` [BCSerialPrint]
+       serialPrintln s = tell` [BCSerialPrintln]
+       serialRead = tell` [BCSerialRead]
+       serialParseInt = tell` [BCSerialParseInt]
+
+instance userLed ByteCode where
+       ledOn  (BC l) = BC $ l >>| tell [BCLedOn]
+       ledOff (BC l) = BC $ l >>| tell [BCLedOff]
+
+func :: (a -> BC) [BC] -> [BC] | mTaskType a
+func f b = abort ('Text'.join "\n" (map printToString b))
 
 instance zero BCState where
        zero = {freshl=[1..], freshs=[1..], sdss=[]}
 
-
-toRealByteCode :: (ByteCode a b) -> (String, BCState)
-toRealByteCode x
-# (bc, st) = runBC x zero
+toRealByteCode :: (ByteCode a b) BCState -> (String, BCState)
+toRealByteCode x s
+# (s, bc) = runBC x s
 # (bc, gtmap) = computeGotos bc 1
-= (concat $ map (toString o toByteVal) (map (implGotos gtmap) bc), st)
+= (concat $ map (toString o toByteVal) (map (implGotos gtmap) bc), s)
 
 implGotos map (BCJmp t) = BCJmp $ fromJust ('DM'.get t map)
 implGotos map (BCJmpT t) = BCJmpT $ fromJust ('DM'.get t map)
@@ -226,43 +266,41 @@ implGotos _ i = i
 computeGotos :: [BC] Int -> ([BC], 'DM'.Map Int Int)
 computeGotos [] _ = ([], 'DM'.newMap)
 computeGotos [BCLab l:xs] i = appSnd ('DM'.put l i) (computeGotos xs i)
-computeGotos [x:xs] i = appFst (\bc->[x:bc]) (computeGotos xs (i+(bclength x)))
+computeGotos [x:xs] i = appFst (\bc->[x:bc])
+       (computeGotos xs $ i + 1 + consNum{|*|} x)
 
 readable :: BC -> String
-readable (BCPush d) = "BCPush " +++ concat (map safe d)
+readable (BCPush d) = "BCPush " +++ concat [safe c\\c<-:d]
        where
-               safe c
-               | isControl c = "\\d" +++ toString (toInt c)
-               = toString c
+               safe c = if (isControl c) ("\\d" +++ toString (toInt c)) (toString c)
 readable b = printToString b
 
-toReadableByteCode :: (ByteCode a b) -> (String, BCState)
-toReadableByteCode x
-# (bc, st) = runBC x zero
+runBC :: (ByteCode a b) -> (BCState -> (BCState, [BC]))
+runBC (BC x) = execRWS x ()
+
+toReadableByteCode :: (ByteCode a b) BCState -> (String, BCState)
+toReadableByteCode x s
+# (s, bc) = runBC x s
 # (bc, gtmap) = computeGotos bc 0
-= (join "\n" $ map readable (map (implGotos gtmap) bc), st)
+= ('Text'.join "\n" $ map readable (map (implGotos gtmap) bc), s)
 
-//Start :: String
-//Start = toReadableByteCode bc
-//     where
-//             bc :: ByteCode Int Expr
-//             bc = (lit 36 +. lit 42) +. lit 44
-toMessages :: Int (String, BCState) -> ([MTaskMSGSend], BCState)
-toMessages interval (bytes, st=:{sdss}) = ([MTSds i (toString b)\\(i,b)<-sdss] ++ [MTTask interval bytes], st)
+toMessages :: MTaskInterval (String, BCState) -> ([MTaskMSGSend], BCState)
+toMessages interval (bytes, st=:{sdss}) = (
+       [MTSds s.sdsi (toByteCode s.sdsval)\\s<-sdss] ++
+       [MTTask interval bytes], st)
 
 toSDSUpdate :: Int Int -> [MTaskMSGSend]
 toSDSUpdate i v = [MTUpd i (to16bit v)]
 
-Start = toMessages 500 $ toRealByteCode (unMain bc)
-//Start = fst $ toReadableByteCode $ unMain bc
+//Start = toMessages (OnInterval 500) $ toRealByteCode (unMain bc) zero
+Start = let (bcs, st) = toReadableByteCode (unMain bc) zero
+               in (bcs, st.sdss)
        where
+//             bc = {main = ledOn (lit LED1)}
                bc = sds \x=5 In 
                        sds \y=4 In
                        {main = If (y ==. lit 0) (pub x) (x =. x *. y :. y =. y -. lit 1)}
 
-//pub :: (ByteCode a b) -> ByteCode a b
-//pub x = fmp makePub x
-
 to16bit :: Int -> String
 to16bit i = toString (toChar (i/256)) +++ toString (toChar (i rem 256))