da88848ae305d50a123bbb3edf5664537e851e98
[ghc-hetmet.git] / ghc / compiler / coreSyn / MkExternalCore.lhs
1 %
2 % (c) The University of Glasgow 2001
3 %
4 \begin{code}
5
6 module MkExternalCore (
7         emitExternalCore
8 ) where
9
10 #include "HsVersions.h"
11
12 import qualified ExternalCore as C
13 import Char
14 import Module
15 import CoreSyn
16 import HscTypes 
17 import TyCon
18 import Class
19 import TypeRep
20 import Type
21 import PprExternalCore  -- Instances
22 import DataCon  ( DataCon, dataConTyVars, dataConRepArgTys, 
23                   dataConName, dataConTyCon, dataConWrapId_maybe )
24 import CoreSyn
25 import Var
26 import IdInfo
27 import Id       ( idUnfolding )
28 import Kind
29 import CoreTidy ( tidyExpr )
30 import VarEnv   ( emptyTidyEnv )
31 import Literal
32 import Name
33 import Outputable
34 import ForeignCall
35 import CmdLineOpts
36 import Maybes   ( mapCatMaybes )
37 import IO
38 import FastString
39
40 emitExternalCore :: DynFlags -> ModGuts -> IO ()
41 emitExternalCore dflags mod_impl
42  | opt_EmitExternalCore 
43  = (do handle <- openFile corename WriteMode
44        hPutStrLn handle (show (mkExternalCore mod_impl))      
45        hClose handle)
46    `catch` (\err -> pprPanic "Failed to open or write external core output file" 
47                              (text corename))
48    where corename = extCoreName dflags
49 emitExternalCore _ _
50  | otherwise
51  = return ()
52
53
54 mkExternalCore :: ModGuts -> C.Module
55 -- The ModGuts has been tidied, but the implicit bindings have
56 -- not been injected, so we have to add them manually here
57 -- We don't include the strange data-con *workers* because they are
58 -- implicit in the data type declaration itself
59 mkExternalCore (ModGuts {mg_module=this_mod, mg_types = type_env, mg_binds = binds})
60   = C.Module mname tdefs (map make_vdef all_binds)
61   where
62     mname  = make_mid this_mod
63     tdefs  = foldr collect_tdefs [] tycons
64
65     all_binds  = implicit_con_wrappers ++ other_implicit_binds ++ binds
66                 -- Put the constructor wrappers first, because
67                 -- other implicit bindings (notably the fromT functions arising 
68                 -- from generics) use the constructor wrappers.
69
70     tycons = map classTyCon (typeEnvClasses type_env) ++ typeEnvTyCons type_env
71
72     implicit_con_wrappers = map get_defn (concatMap implicit_con_ids   (typeEnvElts type_env))
73     other_implicit_binds  = map get_defn (concatMap other_implicit_ids (typeEnvElts type_env))
74
75 implicit_con_ids :: TyThing -> [Id]
76 implicit_con_ids (ATyCon tc) | isAlgTyCon tc = mapCatMaybes dataConWrapId_maybe (tyConDataCons tc)
77 implicit_con_ids other                       = []
78
79 other_implicit_ids :: TyThing -> [Id]
80 other_implicit_ids (ATyCon tc) = tyConSelIds tc
81 other_implicit_ids (AClass cl) = classSelIds cl
82 other_implicit_ids other       = []
83
84 get_defn :: Id -> CoreBind
85 get_defn id = NonRec id rhs
86             where
87               rhs  = tidyExpr emptyTidyEnv body 
88               body = unfoldingTemplate (idUnfolding id)
89         -- Don't forget to tidy the body !  Otherwise you get silly things like
90         --      \ tpl -> case tpl of tpl -> (tpl,tpl) -> tpl
91         -- Maybe we should inject these bindings during CoreTidy?
92
93 collect_tdefs :: TyCon -> [C.Tdef] -> [C.Tdef]
94 collect_tdefs tcon tdefs 
95   | isAlgTyCon tcon = tdef: tdefs
96   where
97     tdef | isNewTyCon tcon = 
98                 C.Newtype (make_con_qid (tyConName tcon)) (map make_tbind tyvars) repclause 
99          | null (tyConDataCons tcon) = error "MkExternalCore died: can't handle datatype declarations with no data constructors"
100          | otherwise = 
101                 C.Data (make_con_qid (tyConName tcon)) (map make_tbind tyvars) (map make_cdef (tyConDataCons tcon)) 
102          where repclause | isRecursiveTyCon tcon = Nothing
103                          | otherwise = Just (make_ty rep)
104                                            where (_, rep) = newTyConRep tcon
105     tyvars = tyConTyVars tcon
106
107 collect_tdefs _ tdefs = tdefs
108
109
110 make_cdef :: DataCon -> C.Cdef
111 make_cdef dcon =  C.Constr dcon_name existentials tys
112   where 
113     dcon_name    = make_var_id (dataConName dcon)
114     existentials = map make_tbind ex_tyvars
115     ex_tyvars    = drop (tyConArity (dataConTyCon dcon)) (dataConTyVars dcon)
116     tys          = map make_ty (dataConRepArgTys dcon)
117
118 make_tbind :: TyVar -> C.Tbind
119 make_tbind tv = (make_var_id (tyVarName tv), make_kind (tyVarKind tv))
120     
121 make_vbind :: Var -> C.Vbind
122 make_vbind v = (make_var_id  (Var.varName v), make_ty (idType v))
123
124 make_vdef :: CoreBind -> C.Vdefg
125 make_vdef b = 
126   case b of
127     NonRec v e -> C.Nonrec (f (v,e))
128     Rec ves -> C.Rec (map f ves)
129   where f (v,e) = (make_var_id (Var.varName v), make_ty (idType v),make_exp e)
130         -- Top level bindings are unqualified now
131
132 make_exp :: CoreExpr -> C.Exp
133 make_exp (Var v) =  
134   case globalIdDetails v of
135      -- a DataConId represents the Id of a worker, which is a varName. -- sof 4/02
136 --    DataConId _ -> C.Dcon (make_con_qid (Var.varName v))
137     FCallId (CCall (CCallSpec (StaticTarget nm) _ _)) -> C.External (unpackFS nm) (make_ty (idType v))
138     FCallId _ -> error "MkExternalCore died: can't handle non-static-C foreign call"
139     _ -> C.Var (make_var_qid (Var.varName v))
140 make_exp (Lit (l@(MachLabel s _))) = error "MkExternalCore died: can't handle \"foreign label\" declarations"
141 make_exp (Lit l) = C.Lit (make_lit l)
142 make_exp (App e (Type t)) = C.Appt (make_exp e) (make_ty t)
143 make_exp (App e1 e2) = C.App (make_exp e1) (make_exp e2)
144 make_exp (Lam v e) | isTyVar v = C.Lam (C.Tb (make_tbind v)) (make_exp e)
145 make_exp (Lam v e) | otherwise = C.Lam (C.Vb (make_vbind v)) (make_exp e)
146 make_exp (Let b e) = C.Let (make_vdef b) (make_exp e)
147 -- gaw 2004
148 make_exp (Case e v ty alts) = C.Case (make_exp e) (make_vbind v) (make_ty ty) (map make_alt alts)
149 make_exp (Note (SCC cc) e) = C.Note "SCC"  (make_exp e) -- temporary
150 make_exp (Note (Coerce t_to t_from) e) = C.Coerce (make_ty t_to) (make_exp e)
151 make_exp (Note InlineCall e) = C.Note "InlineCall" (make_exp e)
152 make_exp (Note (CoreNote s) e) = C.Note s (make_exp e)  -- hdaume: core annotations
153 make_exp (Note InlineMe e) = C.Note "InlineMe" (make_exp e)
154 make_exp _ = error "MkExternalCore died: make_exp"
155
156 make_alt :: CoreAlt -> C.Alt
157 make_alt (DataAlt dcon, vs, e) = 
158     C.Acon (make_con_qid (dataConName dcon))
159            (map make_tbind tbs)
160            (map make_vbind vbs)
161            (make_exp e)    
162         where (tbs,vbs) = span isTyVar vs
163 make_alt (LitAlt l,_,e) = C.Alit (make_lit l) (make_exp e)
164 make_alt (DEFAULT,[],e) = C.Adefault (make_exp e)
165
166 make_lit :: Literal -> C.Lit
167 make_lit l = 
168   case l of
169     MachChar i -> C.Lchar i t
170     MachStr s -> C.Lstring (unpackFS s) t
171     MachNullAddr -> C.Lint 0 t
172     MachInt i -> C.Lint i t
173     MachInt64 i -> C.Lint i t
174     MachWord i -> C.Lint i t
175     MachWord64 i -> C.Lint i t
176     MachFloat r -> C.Lrational r t
177     MachDouble r -> C.Lrational r t
178     _ -> error "MkExternalCore died: make_lit"
179   where 
180     t = make_ty (literalType l)
181
182 make_ty :: Type -> C.Ty
183 make_ty (TyVarTy tv)             = C.Tvar (make_var_id (tyVarName tv))
184 make_ty (AppTy t1 t2)            = C.Tapp (make_ty t1) (make_ty t2)
185 make_ty (FunTy t1 t2)            = make_ty (TyConApp funTyCon [t1,t2])
186 make_ty (ForAllTy tv t)          = C.Tforall (make_tbind tv) (make_ty t)
187 make_ty (TyConApp tc ts)         = foldl C.Tapp (C.Tcon (make_con_qid (tyConName tc))) 
188                                          (map make_ty ts)
189 -- Newtypes are treated just like any other type constructor; not expanded
190 -- Reason: predTypeRep does substitution and, while substitution deals
191 --         correctly with name capture, it's only correct if you see the uniques!
192 --         If you just see occurrence names, name capture may occur.
193 -- Example: newtype A a = A (forall b. b -> a)
194 --          test :: forall q b. q -> A b
195 --          test _ = undefined
196 --      Here the 'a' gets substituted by 'b', which is captured.
197 -- Another solution would be to expand newtypes before tidying; but that would
198 -- expose the representation in interface files, which definitely isn't right.
199 -- Maybe CoreTidy should know whether to expand newtypes or not?
200
201 make_ty (PredTy p)      = make_ty (predTypeRep p)
202 make_ty (NoteTy _ t)    = make_ty t
203
204
205
206 make_kind :: Kind -> C.Kind
207 make_kind (FunKind k1 k2)  = C.Karrow (make_kind k1) (make_kind k2)
208 make_kind LiftedTypeKind   = C.Klifted
209 make_kind UnliftedTypeKind = C.Kunlifted
210 make_kind OpenTypeKind     = C.Kopen
211 make_kind _ = error "MkExternalCore died: make_kind"
212
213 {- Id generation. -}
214
215 {- Use encoded strings.
216    Also, adjust casing to work around some badly-chosen internal names. -}
217 make_id :: Bool -> Name -> C.Id
218 make_id is_var nm = (occNameString . nameOccName) nm
219
220 {-      SIMON thinks this stuff isn't necessary
221 make_id is_var nm = 
222   case n of
223     'Z':cs | is_var -> 'z':cs 
224     'z':cs | not is_var -> 'Z':cs 
225     c:cs | isUpper c && is_var -> 'z':'d':n
226     c:cs | isLower c && (not is_var) -> 'Z':'d':n
227     _ -> n
228   where n = (occNameString . nameOccName) nm
229 -}
230
231 make_var_id :: Name -> C.Id
232 make_var_id = make_id True
233
234 make_mid :: Module -> C.Id
235 make_mid = moduleNameString . moduleName
236
237 make_qid :: Bool -> Name -> C.Qual C.Id
238 make_qid is_var n = (mname,make_id is_var n)
239     where mname = 
240            case nameModule_maybe n of
241             Just m -> make_mid m
242             Nothing -> "" 
243
244 make_var_qid :: Name -> C.Qual C.Id
245 make_var_qid = make_qid True
246
247 make_con_qid :: Name -> C.Qual C.Id
248 make_con_qid = make_qid False
249
250 \end{code}
251
252
253
254