1 implementation module gen
11 import qualified Data.Map as Map
15 import Control.Applicative
17 import Control.Monad.State
18 import Control.Monad.Trans
19 from Text import class Text(concat), instance Text String
23 //Instruction is an instruction, with possible arguments and a possible comment
25 :: Instr = Instr String [Arg] String
27 :: Arg = L String | Lit Int
28 :: SSMProgram :== [Instr]
32 gen _ = toString [Label "Test"
33 ,Instr "ldc" [Lit 1] "Eerste instructie"
34 ,Instr "ldc" [Lit 2] "Tweede instructie"]
37 //Scrap this, we'll need shared state when generating
38 //i.e. to figure out the positions of vars relative to the
39 //SP/MP/whatever or in which register they are
40 //and to supply with fresh labels
42 //The generation monad
43 :: GenError = Error String
44 :: GenMap :== 'Map'.Map String LoadPlace
45 :: LoadPlace = LDA Int | LDC Int | LDH Int | LDL Int
47 :: Gen a :== StateT (GenMap) (Either GenError) a
52 class g a :: a -> Gen SSMProgram
55 g (VarExpr _ (VarDef k fs)) = pure <$> load k //note: pure is pure for list, i.e. []
57 load :: String -> Gen Instr
58 load k = genMap >>= \g-> case 'Map'.member k g of
59 False = liftT (Left $ Error $ concat ["PANIC: ", k, " not found in variable mapping"])
60 True = pure (loadP $ 'Map'.find k g)
62 loadP :: LoadPlace -> Instr
63 loadP pl = let (instr, arg) = dec pl in Instr instr [Lit arg] ""
65 dec (LDA i) = ("lda", i)
66 dec (LDC i) = ("ldc", i)
67 dec (LDH i) = ("ldh", i)
68 dec (LDL i) = ("ldl", i)
69 dec (LDR i) = ("ldr", i)
70 dec (LDS i) = ("lds", i)
72 class print a :: a -> [String]
74 instance print Instr where
75 print (Label l) = [l, ":", "\n"]
76 print (Instr i args com) = ["\t", i] ++ print args ++ [" ;", com, "\n"]
78 instance print [Arg] where
79 print args = (map toString args)
81 instance toString Arg where
83 toString (Lit int) = toString int
85 instance toString SSMProgram where
86 toString p = concat $ intersperse " " $ map (\i-> concat $ intersperse " " $ print i) p
88 instance MonadTrans (StateT GenMap) where
89 liftT m = StateT \s-> m >>= \a-> return (a, s)