Add an error message.
[matthijs/master-project/cλash.git] / Translator.hs
1 module Main(main) where
2 import GHC
3 import CoreSyn
4 import qualified CoreUtils
5 import qualified Var
6 import qualified Type
7 import qualified TyCon
8 import qualified DataCon
9 import qualified Maybe
10 import Name
11 import Data.Generics
12 import NameEnv ( lookupNameEnv )
13 import HscTypes ( cm_binds, cm_types )
14 import MonadUtils ( liftIO )
15 import Outputable ( showSDoc, ppr )
16 import GHC.Paths ( libdir )
17 import DynFlags ( defaultDynFlags )
18 import List ( find )
19
20 main = 
21                 do
22                         defaultErrorHandler defaultDynFlags $ do
23                                 runGhc (Just libdir) $ do
24                                         dflags <- getSessionDynFlags
25                                         setSessionDynFlags dflags
26                                         --target <- guessTarget "adder.hs" Nothing
27                                         --liftIO (print (showSDoc (ppr (target))))
28                                         --liftIO $ printTarget target
29                                         --setTargets [target]
30                                         --load LoadAllTargets
31                                         --core <- GHC.compileToCoreSimplified "Adders.hs"
32                                         core <- GHC.compileToCoreSimplified "Adders.hs"
33                                         liftIO $ printBinds (cm_binds core)
34                                         let bind = findBind "no_carry_adder" (cm_binds core)
35                                         let NonRec var expr = bind
36                                         liftIO $ putStr $ showSDoc $ ppr expr
37                                         liftIO $ putStr "\n\n"
38                                         liftIO $ putStr $ getEntity bind
39                                         liftIO $ putStr $ getArchitecture bind
40                                         return expr
41
42 printTarget (Target (TargetFile file (Just x)) obj Nothing) =
43         print $ show file
44
45 printBinds [] = putStr "done\n\n"
46 printBinds (b:bs) = do
47         printBind b
48         putStr "\n"
49         printBinds bs
50
51 printBind (NonRec b expr) = do
52         putStr "NonRec: "
53         printBind' (b, expr)
54
55 printBind (Rec binds) = do
56         putStr "Rec: \n"        
57         foldl1 (>>) (map printBind' binds)
58
59 printBind' (b, expr) = do
60         putStr $ getOccString b
61         --putStr $ showSDoc $ ppr expr
62         putStr "\n"
63
64 findBind :: String -> [CoreBind] -> CoreBind
65 findBind lookfor =
66         -- This ignores Recs and compares the name of the bind with lookfor,
67         -- disregarding any namespaces in OccName and extra attributes in Name and
68         -- Var.
69         Maybe.fromJust . find (\b -> case b of 
70                 Rec l -> False
71                 NonRec var _ -> lookfor == (occNameString $ nameOccName $ getName var)
72         )
73
74 -- Generate a port (or multiple for tuple types) in the given direction for
75 -- each type given.
76 getPortsForTys :: String -> String -> Int -> [Type] -> String
77 getPortsForTys dir prefix num [] = ""
78 getPortsForTys dir prefix num (t:ts) = 
79         (getPortsForTy dir (prefix ++ show num) t) ++ getPortsForTys dir prefix (num + 1) ts
80
81 getPortsForFunTy ty =
82                 -- All of a function's arguments become IN ports, the result becomes on
83                 -- (or more) OUT ports.
84                 -- Drop the first ;\n
85                 drop 2 (getPortsForTys "in" "portin" 0 args) ++ (getPortsForTy "out" "portout" res) ++ "\n"
86         where
87                 (args, res) = Type.splitFunTys ty
88
89 getPortsForTy   :: String -> String -> Type -> String
90 getPortsForTy dir name ty =
91         if (TyCon.isTupleTyCon tycon) then
92                 -- Expand tuples we find
93                 getPortsForTys dir name 0 args
94         else -- Assume it's a type constructor application, ie simple data type
95                 let 
96                         vhdlTy = showSDoc $ ppr $ TyCon.tyConName tycon;
97                 in
98                         ";\n\t" ++ name ++ " : " ++ dir ++ " " ++ vhdlTy
99         where
100                 (tycon, args) = Type.splitTyConApp ty 
101
102 getEntity (NonRec var expr) =
103                 "entity " ++ name ++ " is\n"
104                 ++ "port (\n"
105                 ++ getPortsForFunTy ty
106           ++ ");\n"
107                 ++ "end " ++ name ++ ";\n\n"
108         where
109                 name = (getOccString var)
110                 ty = CoreUtils.exprType expr
111
112 -- Accepts a port name and an argument to map to it.
113 -- Returns the appropriate line for in the port map
114 getPortMapEntry binds portname (Var id) = 
115         "\t" ++ portname ++ " => " ++ signalname ++ "\n"
116         where
117                 Port signalname = Maybe.fromMaybe
118                         (error $ "Argument " ++ getOccString id ++ "is unknown")
119                         (lookup id binds)
120
121 getPortMapEntry binds _ a = error $ "Unsupported argument: " ++ (showSDoc $ ppr a)
122
123 getInstantiations ::
124         PortNameMap                  -- The arguments that need to be applied to the
125                                                                                                                          -- expression. Should always be the Args
126                                                                                                                          -- constructor.
127         -> PortNameMap               -- The output ports that the expression should generate.
128         -> [(CoreBndr, PortNameMap)] -- A list of bindings in effect
129         -> CoreSyn.CoreExpr          -- The expression to generate an architecture for
130         -> String                    -- The resulting VHDL code
131
132 -- A lambda expression binds the first argument (a) to the binder b.
133 getInstantiations (Args (a:as)) outs binds (Lam b expr) =
134         getInstantiations (Args as) outs ((b, a):binds) expr
135
136 -- A case expression that checks a single variable and has a single
137 -- alternative, can be used to take tuples apart
138 getInstantiations args outs binds (Case (Var v) b _ [res]) =
139         case altcon of
140                 DataAlt datacon ->
141                         if (DataCon.isTupleCon datacon) then
142                                 getInstantiations args outs binds' expr
143                         else
144                                 error "Data constructors other than tuples not supported"
145                 otherwise ->
146                         error "Case binders other than tuples not supported"
147         where
148                 binds' = (zip bind_vars tuple_ports) ++ binds
149                 (altcon, bind_vars, expr) = res
150                 -- Find the portnamemaps for each of the tuple's elements
151                 Tuple tuple_ports = Maybe.fromMaybe 
152                         (error $ "Case expression uses unknown scrutinee " ++ getOccString v)
153                         (lookup v binds)
154
155 -- An application is an instantiation of a component
156 getInstantiations args outs binds app@(App expr arg) =
157         --indent ++ "F:\n" ++ (getInstantiations (' ':indent) expr) ++ "\n" ++ indent ++ "A:\n" ++ (getInstantiations (' ':indent) arg) ++ "\n"
158         "app : " ++ (getOccString f) ++ "\n"
159         ++ "port map (\n"
160         -- Map input ports of f
161         ++ concat (zipWith (getPortMapEntry binds) ["portin0", "portin1"] args)
162         -- Map output ports of f
163         ++ mapOutputPorts (Port "portout") outs
164         ++ ");\n"
165         where
166                 ((Var f), args) = collectArgs app
167
168 getInstantiations args outs binds expr = 
169         error $ "Unsupported expression" ++ (showSDoc $ ppr $ expr)
170
171 -- Map the output port of a component to the output port of the containing
172 -- entity.
173 mapOutputPorts (Port port) (Port signal) =
174         "\t" ++ port ++ " => " ++ signal ++ "\n"
175
176 -- Map matching output ports in the tuple
177 mapOutputPorts (Tuple ports) (Tuple signals) =
178         concat (zipWith mapOutputPorts ports signals)
179
180 getArchitecture (NonRec var expr) =
181         "architecture structural of " ++ name ++ " is\n"
182         ++ "begin\n"
183         ++ getInstantiations (Args inportnames) outport [] expr
184         ++ "end structural\n"
185         where
186                 name = (getOccString var)
187                 ty = CoreUtils.exprType expr
188                 (fargs, res) = Type.splitFunTys ty
189                 --state = if length fargs == 1 then () else (last fargs)
190                 ports = if length fargs == 1 then fargs else (init fargs)
191                 inportnames = case ports of
192                         [port] -> [getPortNameMapForTy "portin" port]
193                         ps     -> getPortNameMapForTys "portin" 0 ps
194                 outport = getPortNameMapForTy "portout" res
195
196 data PortNameMap =
197         Args [PortNameMap] -- Each of the submaps represent an argument to the
198                            -- function. Should only occur at top level.
199         | Tuple [PortNameMap]
200         | Port  String
201
202 -- Generate a port name map (or multiple for tuple types) in the given direction for
203 -- each type given.
204 getPortNameMapForTys :: String -> Int -> [Type] -> [PortNameMap]
205 getPortNameMapForTys prefix num [] = [] 
206 getPortNameMapForTys prefix num (t:ts) =
207         (getPortNameMapForTy (prefix ++ show num) t) : getPortNameMapForTys prefix (num + 1) ts
208
209 getPortNameMapForTy     :: String -> Type -> PortNameMap
210 getPortNameMapForTy name ty =
211         if (TyCon.isTupleTyCon tycon) then
212                 -- Expand tuples we find
213                 Tuple (getPortNameMapForTys name 0 args)
214         else -- Assume it's a type constructor application, ie simple data type
215                 -- TODO: Add type?
216                 Port name
217         where
218                 (tycon, args) = Type.splitTyConApp ty