2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
5 This module converts Template Haskell syntax into HsSyn
9 module Convert( convertToHsExpr, convertToHsDecls ) where
11 #include "HsVersions.h"
13 import Language.Haskell.THSyntax as Meta
16 ( HsExpr(..), HsLit(..), ArithSeqInfo(..),
17 HsStmtContext(..), TyClDecl(..),
18 Match(..), GRHSs(..), GRHS(..), HsPred(..),
19 HsDecl(..), TyClDecl(..), InstDecl(..), ConDecl(..),
20 Stmt(..), HsBinds(..), MonoBinds(..), Sig(..),
21 Pat(..), HsConDetails(..), HsOverLit, BangType(..),
22 placeHolderType, HsType(..), HsTupCon(..),
23 HsTyVarBndr(..), HsContext,
24 mkSimpleMatch, mkHsForAllTy
27 import RdrName ( RdrName, mkRdrUnqual, mkRdrQual, mkOrig )
28 import Module ( mkModuleName )
29 import RdrHsSyn ( mkHsIntegral, mkHsFractional, mkClassDecl, mkTyData )
31 import SrcLoc ( SrcLoc, generatedSrcLoc )
32 import TyCon ( DataConDetails(..) )
34 import BasicTypes( Boxity(..), RecFlag(Recursive),
35 NewOrData(..), StrictnessMark(..) )
36 import ForeignCall ( Safety(..), CCallConv(..), CCallTarget(..) )
37 import HsDecls ( CImportSpec(..), ForeignImport(..), ForeignDecl(..) )
38 import FastString( FastString, mkFastString, nilFS )
39 import Char ( ord, isAscii, isAlphaNum, isAlpha )
40 import List ( partition )
41 import ErrUtils (Message)
45 -------------------------------------------------------------------
46 convertToHsDecls :: [Meta.Dec] -> [Either (HsDecl RdrName) Message]
47 convertToHsDecls ds = map cvt_top ds
50 cvt_top :: Meta.Dec -> Either (HsDecl RdrName) Message
51 cvt_top d@(Val _ _ _) = Left $ ValD (cvtd d)
52 cvt_top d@(Fun _ _) = Left $ ValD (cvtd d)
54 cvt_top (TySyn tc tvs rhs)
55 = Left $ TyClD (TySynonym (tconName tc) (cvt_tvs tvs) (cvtType rhs) loc0)
57 cvt_top (Data tc tvs constrs derivs)
58 = Left $ TyClD (mkTyData DataType
59 (noContext, tconName tc, cvt_tvs tvs)
60 (DataCons (map mk_con constrs))
61 (mk_derivs derivs) loc0)
64 = ConDecl (cName c) noExistentials noContext
65 (PrefixCon (map mk_arg tys)) loc0
67 mk_arg ty = BangType NotMarkedStrict (cvtType ty)
69 mk_derivs [] = Nothing
70 mk_derivs cs = Just [HsClassP (tconName c) [] | c <- cs]
72 cvt_top (Class ctxt cl tvs decs)
73 = Left $ TyClD (mkClassDecl (cvt_context ctxt, tconName cl, cvt_tvs tvs)
75 sigs (Just binds) loc0)
77 (binds,sigs) = cvtBindsAndSigs decs
79 cvt_top (Instance tys ty decs)
80 = Left $ InstD (InstDecl inst_ty binds sigs Nothing loc0)
82 (binds, sigs) = cvtBindsAndSigs decs
83 inst_ty = HsForAllTy Nothing
85 (HsPredTy (cvt_pred ty))
87 cvt_top (Proto nm typ) = Left $ SigD (Sig (vName nm) (cvtType typ) loc0)
89 cvt_top (Foreign (Import callconv safety from nm typ))
91 Just (c_header, cis) ->
92 let i = CImport callconv' safety' c_header nilFS cis
93 in Left $ ForD (ForeignImport (vName nm) (cvtType typ) i False loc0)
94 Nothing -> Right $ text (show from)
95 <+> ptext SLIT("is not a valid ccall impent")
96 where callconv' = case callconv of
98 StdCall -> StdCallConv
99 safety' = case safety of
101 Safe -> PlaySafe False
102 Threadsafe -> PlaySafe True
103 parsed = parse_ccall_impent nm from
105 parse_ccall_impent :: String -> String -> Maybe (FastString, CImportSpec)
106 parse_ccall_impent nm s
107 = case lex_ccall_impent s of
108 Just ["dynamic"] -> Just (nilFS, CFunction DynamicTarget)
109 Just ["wrapper"] -> Just (nilFS, CWrapper)
110 Just ("static":ts) -> parse_ccall_impent_static nm ts
111 Just ts -> parse_ccall_impent_static nm ts
114 parse_ccall_impent_static :: String
116 -> Maybe (FastString, CImportSpec)
117 parse_ccall_impent_static nm ts
118 = let ts' = case ts of
119 [ "&", cid] -> [ cid]
120 [fname, "&" ] -> [fname ]
121 [fname, "&", cid] -> [fname, cid]
124 [ cid] | is_cid cid -> Just (nilFS, mk_cid cid)
125 [fname, cid] | is_cid cid -> Just (mkFastString fname, mk_cid cid)
126 [ ] -> Just (nilFS, mk_cid nm)
127 [fname ] -> Just (mkFastString fname, mk_cid nm)
129 where is_cid :: String -> Bool
130 is_cid x = all (/= '.') x && (isAlpha (head x) || head x == '_')
131 mk_cid :: String -> CImportSpec
132 mk_cid = CFunction . StaticTarget . mkFastString
134 lex_ccall_impent :: String -> Maybe [String]
135 lex_ccall_impent "" = Just []
136 lex_ccall_impent ('&':xs) = fmap ("&":) $ lex_ccall_impent xs
137 lex_ccall_impent (' ':xs) = lex_ccall_impent xs
138 lex_ccall_impent ('\t':xs) = lex_ccall_impent xs
139 lex_ccall_impent xs = case span is_valid xs of
141 (t, xs') -> fmap (t:) $ lex_ccall_impent xs'
142 where is_valid :: Char -> Bool
143 is_valid c = isAscii c && (isAlphaNum c || c `elem` "._")
149 -------------------------------------------------------------------
150 convertToHsExpr :: Meta.Exp -> HsExpr RdrName
151 convertToHsExpr = cvt
153 cvt (Var s) = HsVar (vName s)
154 cvt (Con s) = HsVar (cName s)
156 | overloadedLit l = HsOverLit (cvtOverLit l)
157 | otherwise = HsLit (cvtLit l)
159 cvt (App x y) = HsApp (cvt x) (cvt y)
160 cvt (Lam ps e) = HsLam (mkSimpleMatch (map cvtp ps) (cvt e) void loc0)
161 cvt (Tup [e]) = cvt e
162 cvt (Tup es) = ExplicitTuple(map cvt es) Boxed
163 cvt (Cond x y z) = HsIf (cvt x) (cvt y) (cvt z) loc0
164 cvt (Let ds e) = HsLet (cvtdecs ds) (cvt e)
165 cvt (Case e ms) = HsCase (cvt e) (map cvtm ms) loc0
166 cvt (Do ss) = HsDo DoExpr (cvtstmts ss) [] void loc0
167 cvt (Comp ss) = HsDo ListComp (cvtstmts ss) [] void loc0
168 cvt (ArithSeq dd) = ArithSeqIn (cvtdd dd)
169 cvt (ListExp xs) = ExplicitList void (map cvt xs)
170 cvt (Infix (Just x) s (Just y))
171 = HsPar (OpApp (cvt x) (cvt s) undefined (cvt y))
172 cvt (Infix Nothing s (Just y)) = SectionR (cvt s) (cvt y)
173 cvt (Infix (Just x) s Nothing ) = SectionL (cvt x) (cvt s)
174 cvt (Infix Nothing s Nothing ) = cvt s -- Can I indicate this is an infix thing?
175 cvt (SigExp e t) = ExprWithTySig (cvt e) (cvtType t)
177 cvtdecs :: [Meta.Dec] -> HsBinds RdrName
178 cvtdecs [] = EmptyBinds
179 cvtdecs ds = MonoBind binds sigs Recursive
181 (binds, sigs) = cvtBindsAndSigs ds
184 = (cvtds non_sigs, map cvtSig sigs)
186 (sigs, non_sigs) = partition sigP ds
188 cvtSig (Proto nm typ) = Sig (vName nm) (cvtType typ) loc0
190 cvtds :: [Meta.Dec] -> MonoBinds RdrName
191 cvtds [] = EmptyMonoBinds
192 cvtds (d:ds) = AndMonoBinds (cvtd d) (cvtds ds)
194 cvtd :: Meta.Dec -> MonoBinds RdrName
195 -- Used only for declarations in a 'let/where' clause,
196 -- not for top level decls
197 cvtd (Val (Pvar s) body ds) = FunMonoBind (vName s) False
198 [cvtclause (Clause [] body ds)] loc0
199 cvtd (Fun nm cls) = FunMonoBind (vName nm) False (map cvtclause cls) loc0
200 cvtd (Val p body ds) = PatMonoBind (cvtp p) (GRHSs (cvtguard body)
203 cvtd x = panic "Illegal kind of declaration in where clause"
206 cvtclause :: Meta.Clause (Meta.Pat) (Meta.Exp) (Meta.Dec) -> Hs.Match RdrName
207 cvtclause (Clause ps body wheres)
208 = Match (map cvtp ps) Nothing (GRHSs (cvtguard body) (cvtdecs wheres) void)
212 cvtdd :: Meta.DDt -> ArithSeqInfo RdrName
213 cvtdd (Meta.From x) = (Hs.From (cvt x))
214 cvtdd (Meta.FromThen x y) = (Hs.FromThen (cvt x) (cvt y))
215 cvtdd (Meta.FromTo x y) = (Hs.FromTo (cvt x) (cvt y))
216 cvtdd (Meta.FromThenTo x y z) = (Hs.FromThenTo (cvt x) (cvt y) (cvt z))
219 cvtstmts :: [Meta.Stm] -> [Hs.Stmt RdrName]
220 cvtstmts [] = [] -- this is probably an error as every [stmt] should end with ResultStmt
221 cvtstmts [NoBindSt e] = [ResultStmt (cvt e) loc0] -- when its the last element use ResultStmt
222 cvtstmts (NoBindSt e : ss) = ExprStmt (cvt e) void loc0 : cvtstmts ss
223 cvtstmts (BindSt p e : ss) = BindStmt (cvtp p) (cvt e) loc0 : cvtstmts ss
224 cvtstmts (LetSt ds : ss) = LetStmt (cvtdecs ds) : cvtstmts ss
225 cvtstmts (ParSt dss : ss) = ParStmt(map cvtstmts dss) : cvtstmts ss
228 cvtm :: Meta.Mat -> Hs.Match RdrName
229 cvtm (Mat p body wheres)
230 = Match [cvtp p] Nothing (GRHSs (cvtguard body) (cvtdecs wheres) void)
232 cvtguard :: Meta.Rhs -> [GRHS RdrName]
233 cvtguard (Guarded pairs) = map cvtpair pairs
234 cvtguard (Normal e) = [GRHS [ ResultStmt (cvt e) loc0 ] loc0]
236 cvtpair :: (Meta.Exp,Meta.Exp) -> GRHS RdrName
237 cvtpair (x,y) = GRHS [BindStmt truePat (cvt x) loc0,
238 ResultStmt (cvt y) loc0] loc0
240 cvtOverLit :: Lit -> HsOverLit
241 cvtOverLit (Integer i) = mkHsIntegral i
242 cvtOverLit (Rational r) = mkHsFractional r
243 -- An Integer is like an an (overloaded) '3' in a Haskell source program
244 -- Similarly 3.5 for fractionals
246 cvtLit :: Lit -> HsLit
247 cvtLit (Char c) = HsChar (ord c)
248 cvtLit (String s) = HsString (mkFastString s)
250 cvtp :: Meta.Pat -> Hs.Pat RdrName
252 | overloadedLit l = NPatIn (cvtOverLit l) Nothing -- Not right for negative
253 -- patterns; need to think
255 | otherwise = LitPat (cvtLit l)
256 cvtp (Pvar s) = VarPat(vName s)
257 cvtp (Ptup [p]) = cvtp p
258 cvtp (Ptup ps) = TuplePat (map cvtp ps) Boxed
259 cvtp (Pcon s ps) = ConPatIn (cName s) (PrefixCon (map cvtp ps))
260 cvtp (Ptilde p) = LazyPat (cvtp p)
261 cvtp (Paspat s p) = AsPat (vName s) (cvtp p)
262 cvtp Pwild = WildPat void
264 -----------------------------------------------------------
265 -- Types and type variables
267 cvt_tvs :: [String] -> [HsTyVarBndr RdrName]
268 cvt_tvs tvs = map (UserTyVar . tName) tvs
270 cvt_context :: Cxt -> HsContext RdrName
271 cvt_context tys = map cvt_pred tys
273 cvt_pred :: Typ -> HsPred RdrName
274 cvt_pred ty = case split_ty_app ty of
275 (Tcon (TconName tc), tys) -> HsClassP (tconName tc) (map cvtType tys)
276 other -> panic "Malformed predicate"
278 cvtType :: Meta.Typ -> HsType RdrName
279 cvtType ty = trans (root ty [])
280 where root (Tapp a b) zs = root a (cvtType b : zs)
283 trans (Tcon (Tuple n),args) | length args == n
284 = HsTupleTy (HsTupCon Boxed n) args
285 trans (Tcon Arrow, [x,y]) = HsFunTy x y
286 trans (Tcon List, [x]) = HsListTy x
288 trans (Tvar nm, args) = foldl HsAppTy (HsTyVar (tName nm)) args
289 trans (Tcon tc, args) = foldl HsAppTy (HsTyVar (tc_name tc)) args
291 trans (TForall tvs cxt ty, []) = mkHsForAllTy (Just (cvt_tvs tvs))
295 tc_name (TconName nm) = tconName nm
296 tc_name Arrow = tconName "->"
297 tc_name List = tconName "[]"
298 tc_name (Tuple 0) = tconName "()"
299 tc_name (Tuple n) = tconName ("(" ++ replicate (n-1) ',' ++ ")")
301 split_ty_app :: Typ -> (Typ, [Typ])
302 split_ty_app ty = go ty []
304 go (Tapp f a) as = go f (a:as)
307 -----------------------------------------------------------
309 sigP (Proto _ _) = True
313 -----------------------------------------------------------
314 -- some useful things
316 truePat = ConPatIn (cName "True") (PrefixCon [])
317 falsePat = ConPatIn (cName "False") (PrefixCon [])
319 overloadedLit :: Lit -> Bool
320 -- True for literals that Haskell treats as overloaded
321 overloadedLit (Integer l) = True
322 overloadedLit (Rational l) = True
323 overloadedLit l = False
326 void = placeHolderType
329 loc0 = generatedSrcLoc
332 vName :: String -> RdrName
333 vName = mkName varName
335 -- Constructor function names; this is Haskell source, hence srcDataName
336 cName :: String -> RdrName
337 cName = mkName srcDataName
339 -- Type variable names
340 tName :: String -> RdrName
341 tName = mkName tvName
343 -- Type Constructor names
344 tconName = mkName tcName
346 mkName :: NameSpace -> String -> RdrName
347 -- Parse the string to see if it has a "." or ":" in it
348 -- so we know whether to generate a qualified or original name
349 -- It's a bit tricky because we need to parse
350 -- Foo.Baz.x as Qual Foo.Baz x
351 -- So we parse it from back to front
354 = split [] (reverse str)
356 split occ [] = mkRdrUnqual (mk_occ occ)
357 split occ (c:d:rev) -- 'd' is the last char before the separator
358 | is_sep c -- E.g. Fo.x d='o'
359 && isAlphaNum d -- Fo.+: d='+' perhaps
360 = mk_qual (reverse (d:rev)) c occ
361 split occ (c:rev) = split (c:occ) rev
363 mk_qual mod '.' occ = mkRdrQual (mk_mod mod) (mk_occ occ)
364 mk_qual mod ':' occ = mkOrig (mk_mod mod) (mk_occ occ)
366 mk_occ occ = mkOccFS ns (mkFastString occ)
367 mk_mod mod = mkModuleName mod