eae4b932657cf8c6ee906dd5bfd5c1ba08ad7916
[ghc-hetmet.git] / compiler / coreSyn / MkExternalCore.lhs
1
2 % (c) The University of Glasgow 2001-2006
3 %
4 \begin{code}
5 module MkExternalCore (
6         emitExternalCore
7 ) where
8
9 #include "HsVersions.h"
10
11 import qualified ExternalCore as C
12 import Module
13 import CoreSyn
14 import HscTypes 
15 import TyCon
16 import TypeRep
17 import Type
18 import PprExternalCore () -- Instances
19 import DataCon
20 import Coercion
21 import Var
22 import IdInfo
23 import Literal
24 import Name
25 import Outputable
26 import Encoding
27 import ForeignCall
28 import DynFlags
29 import FastString
30
31 import Data.Char
32 import System.IO
33
34 emitExternalCore :: DynFlags -> CgGuts -> IO ()
35 emitExternalCore dflags cg_guts
36  | dopt Opt_EmitExternalCore dflags
37  = (do handle <- openFile corename WriteMode
38        hPutStrLn handle (show (mkExternalCore cg_guts))      
39        hClose handle)
40    `catch` (\_ -> pprPanic "Failed to open or write external core output file"
41                            (text corename))
42    where corename = extCoreName dflags
43 emitExternalCore _ _
44  | otherwise
45  = return ()
46
47 -- Reinventing the Reader monad; whee.
48 newtype CoreM a = CoreM (CoreState -> (CoreState, a))
49 type CoreState = Module
50 instance Monad CoreM where
51   (CoreM m) >>= f = CoreM (\ s -> case m s of
52                                     (s',r) -> case f r of
53                                                 CoreM f' -> f' s')
54   return x = CoreM (\ s -> (s, x))
55 runCoreM :: CoreM a -> CoreState -> a
56 runCoreM (CoreM f) s = snd $ f s
57 ask :: CoreM CoreState
58 ask = CoreM (\ s -> (s,s))
59
60 mkExternalCore :: CgGuts -> C.Module
61 -- The ModGuts has been tidied, but the implicit bindings have
62 -- not been injected, so we have to add them manually here
63 -- We don't include the strange data-con *workers* because they are
64 -- implicit in the data type declaration itself
65 mkExternalCore (CgGuts {cg_module=this_mod, cg_tycons = tycons, 
66                         cg_binds = binds})
67 {- Note that modules can be mutually recursive, but even so, we
68    print out dependency information within each module. -}
69   = C.Module mname tdefs (runCoreM (mapM (make_vdef True) binds) this_mod)
70   where
71     mname  = make_mid this_mod
72     tdefs  = foldr collect_tdefs [] tycons
73
74 collect_tdefs :: TyCon -> [C.Tdef] -> [C.Tdef]
75 collect_tdefs tcon tdefs 
76   | isAlgTyCon tcon = tdef: tdefs
77   where
78     tdef | isNewTyCon tcon = 
79                 C.Newtype (qtc tcon) 
80                   (case newTyConCo_maybe tcon of
81                      Just co -> qtc co
82                      Nothing       -> pprPanic ("MkExternalCore: newtype tcon\
83                                        should have a coercion: ") (ppr tcon))
84                   (map make_tbind tyvars) 
85                   (make_ty (snd (newTyConRhs tcon)))
86          | otherwise = 
87                 C.Data (qtc tcon) (map make_tbind tyvars) 
88                    (map make_cdef (tyConDataCons tcon)) 
89     tyvars = tyConTyVars tcon
90
91 collect_tdefs _ tdefs = tdefs
92
93 qtc :: TyCon -> C.Qual C.Tcon
94 qtc = make_con_qid . tyConName
95
96
97 make_cdef :: DataCon -> C.Cdef
98 make_cdef dcon =  C.Constr dcon_name existentials tys
99   where 
100     dcon_name    = make_qid False False (dataConName dcon)
101     existentials = map make_tbind ex_tyvars
102     ex_tyvars    = dataConExTyVars dcon
103     tys          = map make_ty (dataConRepArgTys dcon)
104
105 make_tbind :: TyVar -> C.Tbind
106 make_tbind tv = (make_var_id (tyVarName tv), make_kind (tyVarKind tv))
107     
108 make_vbind :: Var -> C.Vbind
109 make_vbind v = (make_var_id  (Var.varName v), make_ty (varType v))
110
111 make_vdef :: Bool -> CoreBind -> CoreM C.Vdefg
112 make_vdef topLevel b = 
113   case b of
114     NonRec v e -> f (v,e)     >>= (return . C.Nonrec)
115     Rec ves    -> mapM f ves  >>= (return . C.Rec)
116   where
117   f :: (CoreBndr,CoreExpr) -> CoreM C.Vdef
118   f (v,e) = do
119           localN <- isALocal vName
120           let local = not topLevel || localN
121           rhs <- make_exp e
122           -- use local flag to determine where to add the module name
123           return (local, make_qid local True vName, make_ty (varType v),rhs)
124         where vName = Var.varName v
125
126 make_exp :: CoreExpr -> CoreM C.Exp
127 make_exp (Var v) = do
128   let vName = Var.varName v
129   isLocal <- isALocal vName
130   return $
131      case idDetails v of
132        FCallId (CCall (CCallSpec (StaticTarget nm _) callconv _)) 
133            -> C.External (unpackFS nm) (showSDoc (ppr callconv)) (make_ty (varType v))
134        FCallId (CCall (CCallSpec DynamicTarget     callconv _)) 
135            -> C.DynExternal            (showSDoc (ppr callconv)) (make_ty (varType v))
136        -- Constructors are always exported, so make sure to declare them
137        -- with qualified names
138        DataConWorkId _ -> C.Var (make_var_qid False vName)
139        DataConWrapId _ -> C.Var (make_var_qid False vName)
140        _ -> C.Var (make_var_qid isLocal vName)
141 make_exp (Lit (MachLabel s _ _)) = return $ C.Label (unpackFS s)
142 make_exp (Lit l) = return $ C.Lit (make_lit l)
143 make_exp (App e (Type t)) = make_exp e >>= (\ b -> return $ C.Appt b (make_ty t))
144 make_exp (App e1 e2) = do
145    rator <- make_exp e1
146    rand <- make_exp e2
147    return $ C.App rator rand
148 make_exp (Lam v e) | isTyVar v = make_exp e >>= (\ b -> 
149                                     return $ C.Lam (C.Tb (make_tbind v)) b)
150 make_exp (Lam v e) | otherwise = make_exp e >>= (\ b -> 
151                                     return $ C.Lam (C.Vb (make_vbind v)) b)
152 make_exp (Cast e co) = make_exp e >>= (\ b -> return $ C.Cast b (make_ty co))
153 make_exp (Let b e) = do
154   vd   <- make_vdef False b
155   body <- make_exp e
156   return $ C.Let vd body
157 make_exp (Case e v ty alts) = do
158   scrut <- make_exp e
159   newAlts  <- mapM make_alt alts
160   return $ C.Case scrut (make_vbind v) (make_ty ty) newAlts
161 make_exp (Note (SCC _) e) = make_exp e >>= (return . C.Note "SCC") -- temporary
162 make_exp (Note (CoreNote s) e) = make_exp e >>= (return . C.Note s)  -- hdaume: core annotations
163 make_exp _ = error "MkExternalCore died: make_exp"
164
165 make_alt :: CoreAlt -> CoreM C.Alt
166 make_alt (DataAlt dcon, vs, e) = do
167     newE <- make_exp e
168     return $ C.Acon (make_con_qid (dataConName dcon))
169            (map make_tbind tbs)
170            (map make_vbind vbs)
171            newE
172         where (tbs,vbs) = span isTyVar vs
173 make_alt (LitAlt l,_,e)   = make_exp e >>= (return . (C.Alit (make_lit l)))
174 make_alt (DEFAULT,[],e)   = make_exp e >>= (return . C.Adefault)
175 -- This should never happen, as the DEFAULT alternative binds no variables,
176 -- but we might as well check for it:
177 make_alt a@(DEFAULT,_ ,_) = pprPanic ("MkExternalCore: make_alt: DEFAULT "
178              ++ "alternative had a non-empty var list") (ppr a)
179
180
181 make_lit :: Literal -> C.Lit
182 make_lit l = 
183   case l of
184     -- Note that we need to check whether the character is "big".
185     -- External Core only allows character literals up to '\xff'.
186     MachChar i | i <= chr 0xff -> C.Lchar i t
187     -- For a character bigger than 0xff, we represent it in ext-core
188     -- as an int lit with a char type.
189     MachChar i             -> C.Lint (fromIntegral $ ord i) t 
190     MachStr s -> C.Lstring (unpackFS s) t
191     MachNullAddr -> C.Lint 0 t
192     MachInt i -> C.Lint i t
193     MachInt64 i -> C.Lint i t
194     MachWord i -> C.Lint i t
195     MachWord64 i -> C.Lint i t
196     MachFloat r -> C.Lrational r t
197     MachDouble r -> C.Lrational r t
198     _ -> error "MkExternalCore died: make_lit"
199   where 
200     t = make_ty (literalType l)
201
202 -- Expand type synonyms, then convert.
203 make_ty :: Type -> C.Ty                 -- Be sure to expand types recursively!
204                                         -- example: FilePath ~> String ~> [Char]
205 make_ty t | Just expanded <- tcView t = make_ty expanded
206 make_ty t = make_ty' t
207  
208 -- note calls to make_ty so as to expand types recursively
209 make_ty' :: Type -> C.Ty
210 make_ty' (TyVarTy tv)            = C.Tvar (make_var_id (tyVarName tv))
211 make_ty' (AppTy t1 t2)           = C.Tapp (make_ty t1) (make_ty t2)
212 make_ty' (FunTy t1 t2)           = make_ty (TyConApp funTyCon [t1,t2])
213 make_ty' (ForAllTy tv t)         = C.Tforall (make_tbind tv) (make_ty t)
214 make_ty' (TyConApp tc ts)        = make_tyConApp tc ts
215
216 -- Newtypes are treated just like any other type constructor; not expanded
217 -- Reason: predTypeRep does substitution and, while substitution deals
218 --         correctly with name capture, it's only correct if you see the uniques!
219 --         If you just see occurrence names, name capture may occur.
220 -- Example: newtype A a = A (forall b. b -> a)
221 --          test :: forall q b. q -> A b
222 --          test _ = undefined
223 --      Here the 'a' gets substituted by 'b', which is captured.
224 -- Another solution would be to expand newtypes before tidying; but that would
225 -- expose the representation in interface files, which definitely isn't right.
226 -- Maybe CoreTidy should know whether to expand newtypes or not?
227
228 make_ty' (PredTy p)     = make_ty (predTypeRep p)
229
230 make_tyConApp :: TyCon -> [Type] -> C.Ty
231 make_tyConApp tc [t1, t2] | tc == transCoercionTyCon =
232   C.TransCoercion (make_ty t1) (make_ty t2)
233 make_tyConApp tc [t]      | tc == symCoercionTyCon =
234   C.SymCoercion (make_ty t)
235 make_tyConApp tc [t1, t2] | tc == unsafeCoercionTyCon =
236   C.UnsafeCoercion (make_ty t1) (make_ty t2)
237 make_tyConApp tc [t]      | tc == leftCoercionTyCon =
238   C.LeftCoercion (make_ty t)
239 make_tyConApp tc [t]      | tc == rightCoercionTyCon =
240   C.RightCoercion (make_ty t)
241 make_tyConApp tc [t1, t2] | tc == instCoercionTyCon =
242   C.InstCoercion (make_ty t1) (make_ty t2)
243 -- this fails silently if we have an application
244 -- of a wired-in coercion tycon to the wrong number of args.
245 -- Not great...
246 make_tyConApp tc ts =
247   foldl C.Tapp (C.Tcon (qtc tc)) 
248             (map make_ty ts)
249
250
251 make_kind :: Kind -> C.Kind
252 make_kind (PredTy p) | isEqPred p = C.Keq (make_ty t1) (make_ty t2)
253     where (t1, t2) = getEqPredTys p
254 make_kind (FunTy k1 k2)  = C.Karrow (make_kind k1) (make_kind k2)
255 make_kind k
256   | isLiftedTypeKind k   = C.Klifted
257   | isUnliftedTypeKind k = C.Kunlifted
258   | isOpenTypeKind k     = C.Kopen
259 make_kind _ = error "MkExternalCore died: make_kind"
260
261 {- Id generation. -}
262
263 make_id :: Bool -> Name -> C.Id
264 -- include uniques for internal names in order to avoid name shadowing
265 make_id _is_var nm = ((occNameString . nameOccName) nm)
266   ++ (if isInternalName nm then (show . nameUnique) nm else "")
267
268 make_var_id :: Name -> C.Id
269 make_var_id = make_id True
270
271 -- It's important to encode the module name here, because in External Core,
272 -- base:GHC.Base => base:GHCziBase
273 -- We don't do this in pprExternalCore because we
274 -- *do* want to keep the package name (we don't want baseZCGHCziBase,
275 -- because that would just be ugly.)
276 -- SIGH.
277 -- We encode the package name as well.
278 make_mid :: Module -> C.Id
279 -- Super ugly code, but I can't find anything else that does quite what I
280 -- want (encodes the hierarchical module name without encoding the colon
281 -- that separates the package name from it.)
282 make_mid m = showSDoc $
283               (text $ zEncodeString $ packageIdString $ modulePackageId m)
284               <> text ":"
285               <> (pprEncoded $ pprModuleName $ moduleName m)
286      where pprEncoded = pprCode CStyle
287                
288 make_qid :: Bool -> Bool -> Name -> C.Qual C.Id
289 make_qid force_unqual is_var n = (mname,make_id is_var n)
290     where mname = 
291            case nameModule_maybe n of
292             Just m | not force_unqual -> make_mid m
293             _ -> "" 
294
295 make_var_qid :: Bool -> Name -> C.Qual C.Id
296 make_var_qid force_unqual = make_qid force_unqual True
297
298 make_con_qid :: Name -> C.Qual C.Id
299 make_con_qid = make_qid False False
300
301 -------
302 isALocal :: Name -> CoreM Bool
303 isALocal vName = do
304   modName <- ask
305   return $ case nameModule_maybe vName of
306              -- Not sure whether isInternalName corresponds to "local"ness
307              -- in the External Core sense; need to re-read the spec.
308              Just m | m == modName -> isInternalName vName
309              _                     -> False
310 \end{code}
311
312
313
314