3a_asm: changed data structure again to calculate relative addresses
[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 Control.Monad
9
10 data DT_State = NoState | InData | InText deriving (Show,Eq)
11
12 type Address = Word32
13 type Value = Word32
14 type ValueToParse = String
15 type Code = String
16 type Label = String
17 type Comment = String
18
19 data DTF =
20         DTF_Data Address Value Code Label Comment | -- 0;...
21         DTF_Instr Address Value Code Label Comment | -- 1;...
22         DTF_Comment Comment | -- 2;...
23         DTF_Label Label Comment Address | -- 3;...
24         -- types for intern processing
25         DTF_InstrToParse Address ValueToParse Code Label Comment |
26         DTF_SectionToDet Address Value Code Label Comment |
27         DTF_Org Address |
28         DTF_State DT_State
29
30 instance Show (DTF) where
31         showsPrec n = showsDTF
32
33 showsDTF :: DTF -> ShowS
34 showsDTF (DTF_Data a v c l s) = (++) (datins "0" a v c l s)
35 showsDTF (DTF_Instr a v c l s) = (++) (datins "1" a v c l s)
36 showsDTF (DTF_Comment c) = (++) (printf "2;%s\n" c)
37 showsDTF (DTF_Label l c _) = (++) (printf "3;%s;%s\n" l c)
38 showsDTF (DTF_InstrToParse a v c l s) = (++) (printf "itp;%08x;%s;%s;%s;%s\n" a v c l s)
39 showsDTF (DTF_SectionToDet a v c l s) = (++) (datins "std" a v c l s)
40 showsDTF (DTF_Org a) = (++) (printf "org;%08x\n" a)
41 showsDTF (DTF_State s) = (++) (printf "sta;%s\n" (show s))
42
43 datins :: String -> Address -> Value -> Code -> Label -> Comment -> String
44 datins = printf "%s;%08x;%08x;%s;%s;%s\n"
45
46
47 -- datastructure for managing labels and defines
48 type Dict = (Address,[DictElem])
49 type DictElem = (String,Word32)
50
51 get_elem :: String -> [DictElem] -> Word32
52 get_elem s dict = case (lookup s dict) of
53                 Nothing -> error ("unknown label or define: \"" ++ s ++ "\"")
54                 Just z -> z
55
56 add_elem :: [DictElem] -> (String,Word32) -> [DictElem]
57 add_elem dic (s,w)
58         | s == "" = dic -- ignore empty string
59         | already_in =  error ("Label or define \"" ++ s ++ "\" already exists")
60         | otherwise = (s,w):dic
61         where
62         already_in = case (lookup s dic) of
63                 Just _ -> True
64                 Nothing -> False
65
66 -- some common functions
67 parseMySpaces :: Parser String
68 parseMySpaces = do
69         ret <- many $ oneOf "\t "
70         return $ ret