3a43eb8b854487ca6b4c18dbd13af4c44b0f5566
[calu.git] / 3a_asm / DTFormat.hs
1 module DTFormat where
2
3 import Data.Word
4 import Text.Printf
5 import Text.Parsec
6 import Text.Parsec.String
7 import Text.Parsec.Combinator
8 import Text.Parsec.Expr
9 import Text.ParserCombinators.Parsec.Token
10 import Text.ParserCombinators.Parsec.Expr
11 import Control.Monad
12
13 data DT_State = NoState | InData | InText deriving (Show,Eq)
14
15 type Address = Word32
16 type Value = Word32
17 type Repeat = Word32
18 type ValueToParse = String
19 type Code = String
20 type Label = String
21 type Comment = String
22
23 data DTF =
24         DTF_Data Address Value Code Label Comment | -- 0;...
25         DTF_Instr Address Value Code Label Comment | -- 1;...
26         DTF_Comment Comment | -- 2;...
27         DTF_Label Label Comment Address | -- 3;...
28         -- types for intern processing
29         DTF_InstrToParse Address ValueToParse Code Label Comment |
30         DTF_SectionToDet Address Value Code Label Comment |
31         DTF_Org Address |
32         DTF_Define Label Value Comment |
33         DTF_Fill Repeat Value Label Code Comment |
34         DTF_State DT_State
35
36 instance Show (DTF) where
37         showsPrec n = showsDTF
38
39 showsDTF :: DTF -> ShowS
40 showsDTF (DTF_Data a v c l s) = (++) (datins "0" a v c l s)
41 showsDTF (DTF_Instr a v c l s) = (++) (datins "1" a v c l s)
42 showsDTF (DTF_Comment c) = (++) (printf "2;%s\n" c)
43 showsDTF (DTF_Label l c _) = (++) (printf "3;%s;%s\n" l c)
44 showsDTF (DTF_InstrToParse a v c l s) = (++) (printf "itp;%08x;%s;%s;%s;%s\n" a v c l s)
45 showsDTF (DTF_SectionToDet a v c l s) = (++) (datins "std" a v c l s)
46 showsDTF (DTF_Org a) = (++) (printf "org;%08x\n" a)
47 showsDTF (DTF_Define l a c) = (++) (printf "def;%s;%08x;%s\n" l a c)
48 showsDTF (DTF_Fill r v code l c) = (++) (printf "fill;%08x;%08x;%s;%s;%s\n" r v code l c)
49 showsDTF (DTF_State s) = (++) (printf "sta;%s\n" (show s))
50
51 datins :: String -> Address -> Value -> Code -> Label -> Comment -> String
52 datins = printf "%s;%08x;%08x;%s;%s;%s\n"
53
54
55 -- datastructure for managing labels and defines
56 type Dict = (Address,[DictElem])
57 type DictElem = (String,Word32)
58
59 get_elem :: String -> [DictElem] -> Word32
60 get_elem s dict = case (lookup s dict) of
61                 Nothing -> error ("unknown label or define: \"" ++ s ++ "\"")
62                 Just z -> z
63
64 add_elem :: [DictElem] -> (String,Word32) -> [DictElem]
65 add_elem dic (s,w)
66         | s == "" = dic -- ignore empty string
67         | already_in =  error ("Label or define \"" ++ s ++ "\" already exists")
68         | otherwise = (s,w):dic
69         where
70         already_in = case (lookup s dic) of
71                 Just _ -> True
72                 Nothing -> False
73
74 -- some common functions
75 parseMySpaces :: Parser String
76 parseMySpaces = do
77         ret <- many $ oneOf "\t "
78         return $ ret