ApiAnnotations : AST version of nested forall loses forall annotation
[ghc.git] / compiler / hsSyn / Convert.hs
1 {-
2 (c) The University of Glasgow 2006
3 (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4
5
6 This module converts Template Haskell syntax into HsSyn
7 -}
8
9 {-# LANGUAGE CPP #-}
10
11 module Convert( convertToHsExpr, convertToPat, convertToHsDecls,
12 convertToHsType,
13 thRdrNameGuesses ) where
14
15 import HsSyn as Hs
16 import HsTypes ( mkHsForAllTy )
17 import qualified Class
18 import RdrName
19 import qualified Name
20 import Module
21 import RdrHsSyn
22 import qualified OccName
23 import OccName
24 import SrcLoc
25 import Type
26 import qualified Coercion ( Role(..) )
27 import TysWiredIn
28 import TysPrim (eqPrimTyCon)
29 import BasicTypes as Hs
30 import ForeignCall
31 import Unique
32 import ErrUtils
33 import Bag
34 import Lexeme
35 import Util
36 import FastString
37 import Outputable
38
39 import qualified Data.ByteString as BS
40 import Control.Monad( unless, liftM, ap )
41 #if __GLASGOW_HASKELL__ < 709
42 import Control.Applicative (Applicative(..))
43 #endif
44
45 import Data.Char ( chr )
46 import Data.Word ( Word8 )
47 import Data.Maybe( catMaybes )
48 import Language.Haskell.TH as TH hiding (sigP)
49 import Language.Haskell.TH.Syntax as TH
50
51 -------------------------------------------------------------------
52 -- The external interface
53
54 convertToHsDecls :: SrcSpan -> [TH.Dec] -> Either MsgDoc [LHsDecl RdrName]
55 convertToHsDecls loc ds = initCvt loc (fmap catMaybes (mapM cvt_dec ds))
56 where
57 cvt_dec d = wrapMsg "declaration" d (cvtDec d)
58
59 convertToHsExpr :: SrcSpan -> TH.Exp -> Either MsgDoc (LHsExpr RdrName)
60 convertToHsExpr loc e
61 = initCvt loc $ wrapMsg "expression" e $ cvtl e
62
63 convertToPat :: SrcSpan -> TH.Pat -> Either MsgDoc (LPat RdrName)
64 convertToPat loc p
65 = initCvt loc $ wrapMsg "pattern" p $ cvtPat p
66
67 convertToHsType :: SrcSpan -> TH.Type -> Either MsgDoc (LHsType RdrName)
68 convertToHsType loc t
69 = initCvt loc $ wrapMsg "type" t $ cvtType t
70
71 -------------------------------------------------------------------
72 newtype CvtM a = CvtM { unCvtM :: SrcSpan -> Either MsgDoc (SrcSpan, a) }
73 -- Push down the source location;
74 -- Can fail, with a single error message
75
76 -- NB: If the conversion succeeds with (Right x), there should
77 -- be no exception values hiding in x
78 -- Reason: so a (head []) in TH code doesn't subsequently
79 -- make GHC crash when it tries to walk the generated tree
80
81 -- Use the loc everywhere, for lack of anything better
82 -- In particular, we want it on binding locations, so that variables bound in
83 -- the spliced-in declarations get a location that at least relates to the splice point
84
85 instance Functor CvtM where
86 fmap = liftM
87
88 instance Applicative CvtM where
89 pure = return
90 (<*>) = ap
91
92 instance Monad CvtM where
93 return x = CvtM $ \loc -> Right (loc,x)
94 (CvtM m) >>= k = CvtM $ \loc -> case m loc of
95 Left err -> Left err
96 Right (loc',v) -> unCvtM (k v) loc'
97
98 initCvt :: SrcSpan -> CvtM a -> Either MsgDoc a
99 initCvt loc (CvtM m) = fmap snd (m loc)
100
101 force :: a -> CvtM ()
102 force a = a `seq` return ()
103
104 failWith :: MsgDoc -> CvtM a
105 failWith m = CvtM (\_ -> Left m)
106
107 getL :: CvtM SrcSpan
108 getL = CvtM (\loc -> Right (loc,loc))
109
110 setL :: SrcSpan -> CvtM ()
111 setL loc = CvtM (\_ -> Right (loc, ()))
112
113 returnL :: a -> CvtM (Located a)
114 returnL x = CvtM (\loc -> Right (loc, L loc x))
115
116 returnJustL :: a -> CvtM (Maybe (Located a))
117 returnJustL = fmap Just . returnL
118
119 wrapParL :: (Located a -> a) -> a -> CvtM a
120 wrapParL add_par x = CvtM (\loc -> Right (loc, add_par (L loc x)))
121
122 wrapMsg :: (Show a, TH.Ppr a) => String -> a -> CvtM b -> CvtM b
123 -- E.g wrapMsg "declaration" dec thing
124 wrapMsg what item (CvtM m)
125 = CvtM (\loc -> case m loc of
126 Left err -> Left (err $$ getPprStyle msg)
127 Right v -> Right v)
128 where
129 -- Show the item in pretty syntax normally,
130 -- but with all its constructors if you say -dppr-debug
131 msg sty = hang (ptext (sLit "When splicing a TH") <+> text what <> colon)
132 2 (if debugStyle sty
133 then text (show item)
134 else text (pprint item))
135
136 wrapL :: CvtM a -> CvtM (Located a)
137 wrapL (CvtM m) = CvtM (\loc -> case m loc of
138 Left err -> Left err
139 Right (loc',v) -> Right (loc',L loc v))
140
141 -------------------------------------------------------------------
142 cvtDecs :: [TH.Dec] -> CvtM [LHsDecl RdrName]
143 cvtDecs = fmap catMaybes . mapM cvtDec
144
145 cvtDec :: TH.Dec -> CvtM (Maybe (LHsDecl RdrName))
146 cvtDec (TH.ValD pat body ds)
147 | TH.VarP s <- pat
148 = do { s' <- vNameL s
149 ; cl' <- cvtClause (Clause [] body ds)
150 ; returnJustL $ Hs.ValD $ mkFunBind s' [cl'] }
151
152 | otherwise
153 = do { pat' <- cvtPat pat
154 ; body' <- cvtGuard body
155 ; ds' <- cvtLocalDecs (ptext (sLit "a where clause")) ds
156 ; returnJustL $ Hs.ValD $
157 PatBind { pat_lhs = pat', pat_rhs = GRHSs body' ds'
158 , pat_rhs_ty = placeHolderType, bind_fvs = placeHolderNames
159 , pat_ticks = ([],[]) } }
160
161 cvtDec (TH.FunD nm cls)
162 | null cls
163 = failWith (ptext (sLit "Function binding for")
164 <+> quotes (text (TH.pprint nm))
165 <+> ptext (sLit "has no equations"))
166 | otherwise
167 = do { nm' <- vNameL nm
168 ; cls' <- mapM cvtClause cls
169 ; returnJustL $ Hs.ValD $ mkFunBind nm' cls' }
170
171 cvtDec (TH.SigD nm typ)
172 = do { nm' <- vNameL nm
173 ; ty' <- cvtType typ
174 ; returnJustL $ Hs.SigD (TypeSig [nm'] ty' PlaceHolder) }
175
176 cvtDec (TH.InfixD fx nm)
177 -- fixity signatures are allowed for variables, constructors, and types
178 -- the renamer automatically looks for types during renaming, even when
179 -- the RdrName says it's a variable or a constructor. So, just assume
180 -- it's a variable or constructor and proceed.
181 = do { nm' <- vcNameL nm
182 ; returnJustL (Hs.SigD (FixSig (FixitySig [nm'] (cvtFixity fx)))) }
183
184 cvtDec (PragmaD prag)
185 = cvtPragmaD prag
186
187 cvtDec (TySynD tc tvs rhs)
188 = do { (_, tc', tvs') <- cvt_tycl_hdr [] tc tvs
189 ; rhs' <- cvtType rhs
190 ; returnJustL $ TyClD $
191 SynDecl { tcdLName = tc'
192 , tcdTyVars = tvs', tcdFVs = placeHolderNames
193 , tcdRhs = rhs' } }
194
195 cvtDec (DataD ctxt tc tvs constrs derivs)
196 = do { (ctxt', tc', tvs') <- cvt_tycl_hdr ctxt tc tvs
197 ; cons' <- mapM cvtConstr constrs
198 ; derivs' <- cvtDerivs derivs
199 ; let defn = HsDataDefn { dd_ND = DataType, dd_cType = Nothing
200 , dd_ctxt = ctxt'
201 , dd_kindSig = Nothing
202 , dd_cons = cons', dd_derivs = derivs' }
203 ; returnJustL $ TyClD (DataDecl { tcdLName = tc', tcdTyVars = tvs'
204 , tcdDataDefn = defn
205 , tcdFVs = placeHolderNames }) }
206
207 cvtDec (NewtypeD ctxt tc tvs constr derivs)
208 = do { (ctxt', tc', tvs') <- cvt_tycl_hdr ctxt tc tvs
209 ; con' <- cvtConstr constr
210 ; derivs' <- cvtDerivs derivs
211 ; let defn = HsDataDefn { dd_ND = NewType, dd_cType = Nothing
212 , dd_ctxt = ctxt'
213 , dd_kindSig = Nothing
214 , dd_cons = [con']
215 , dd_derivs = derivs' }
216 ; returnJustL $ TyClD (DataDecl { tcdLName = tc', tcdTyVars = tvs'
217 , tcdDataDefn = defn
218 , tcdFVs = placeHolderNames }) }
219
220 cvtDec (ClassD ctxt cl tvs fds decs)
221 = do { (cxt', tc', tvs') <- cvt_tycl_hdr ctxt cl tvs
222 ; fds' <- mapM cvt_fundep fds
223 ; (binds', sigs', fams', ats', adts') <- cvt_ci_decs (ptext (sLit "a class declaration")) decs
224 ; unless (null adts')
225 (failWith $ (ptext (sLit "Default data instance declarations are not allowed:"))
226 $$ (Outputable.ppr adts'))
227 ; at_defs <- mapM cvt_at_def ats'
228 ; returnJustL $ TyClD $
229 ClassDecl { tcdCtxt = cxt', tcdLName = tc', tcdTyVars = tvs'
230 , tcdFDs = fds', tcdSigs = sigs', tcdMeths = binds'
231 , tcdATs = fams', tcdATDefs = at_defs, tcdDocs = []
232 , tcdFVs = placeHolderNames }
233 -- no docs in TH ^^
234 }
235 where
236 cvt_at_def :: LTyFamInstDecl RdrName -> CvtM (LTyFamDefltEqn RdrName)
237 -- Very similar to what happens in RdrHsSyn.mkClassDecl
238 cvt_at_def decl = case RdrHsSyn.mkATDefault decl of
239 Right def -> return def
240 Left (_, msg) -> failWith msg
241
242 cvtDec (InstanceD ctxt ty decs)
243 = do { let doc = ptext (sLit "an instance declaration")
244 ; (binds', sigs', fams', ats', adts') <- cvt_ci_decs doc decs
245 ; unless (null fams') (failWith (mkBadDecMsg doc fams'))
246 ; ctxt' <- cvtContext ctxt
247 ; L loc ty' <- cvtType ty
248 ; let inst_ty' = L loc $ mkHsForAllTy Implicit [] ctxt' $ L loc ty'
249 ; returnJustL $ InstD $ ClsInstD $
250 ClsInstDecl inst_ty' binds' sigs' ats' adts' Nothing }
251
252 cvtDec (ForeignD ford)
253 = do { ford' <- cvtForD ford
254 ; returnJustL $ ForD ford' }
255
256 cvtDec (FamilyD flav tc tvs kind)
257 = do { (_, tc', tvs') <- cvt_tycl_hdr [] tc tvs
258 ; kind' <- cvtMaybeKind kind
259 ; returnJustL $ TyClD $ FamDecl $
260 FamilyDecl (cvtFamFlavour flav) tc' tvs' kind' }
261 where
262 cvtFamFlavour TypeFam = OpenTypeFamily
263 cvtFamFlavour DataFam = DataFamily
264
265 cvtDec (DataInstD ctxt tc tys constrs derivs)
266 = do { (ctxt', tc', typats') <- cvt_tyinst_hdr ctxt tc tys
267 ; cons' <- mapM cvtConstr constrs
268 ; derivs' <- cvtDerivs derivs
269 ; let defn = HsDataDefn { dd_ND = DataType, dd_cType = Nothing
270 , dd_ctxt = ctxt'
271 , dd_kindSig = Nothing
272 , dd_cons = cons', dd_derivs = derivs' }
273
274 ; returnJustL $ InstD $ DataFamInstD
275 { dfid_inst = DataFamInstDecl { dfid_tycon = tc', dfid_pats = typats'
276 , dfid_defn = defn
277 , dfid_fvs = placeHolderNames } }}
278
279 cvtDec (NewtypeInstD ctxt tc tys constr derivs)
280 = do { (ctxt', tc', typats') <- cvt_tyinst_hdr ctxt tc tys
281 ; con' <- cvtConstr constr
282 ; derivs' <- cvtDerivs derivs
283 ; let defn = HsDataDefn { dd_ND = NewType, dd_cType = Nothing
284 , dd_ctxt = ctxt'
285 , dd_kindSig = Nothing
286 , dd_cons = [con'], dd_derivs = derivs' }
287 ; returnJustL $ InstD $ DataFamInstD
288 { dfid_inst = DataFamInstDecl { dfid_tycon = tc', dfid_pats = typats'
289 , dfid_defn = defn
290 , dfid_fvs = placeHolderNames } }}
291
292 cvtDec (TySynInstD tc eqn)
293 = do { tc' <- tconNameL tc
294 ; eqn' <- cvtTySynEqn tc' eqn
295 ; returnJustL $ InstD $ TyFamInstD
296 { tfid_inst = TyFamInstDecl { tfid_eqn = eqn'
297 , tfid_fvs = placeHolderNames } } }
298
299 cvtDec (ClosedTypeFamilyD tc tyvars mkind eqns)
300 = do { (_, tc', tvs') <- cvt_tycl_hdr [] tc tyvars
301 ; mkind' <- cvtMaybeKind mkind
302 ; eqns' <- mapM (cvtTySynEqn tc') eqns
303 ; returnJustL $ TyClD $ FamDecl $
304 FamilyDecl (ClosedTypeFamily (Just eqns')) tc' tvs' mkind' }
305
306 cvtDec (TH.RoleAnnotD tc roles)
307 = do { tc' <- tconNameL tc
308 ; let roles' = map (noLoc . cvtRole) roles
309 ; returnJustL $ Hs.RoleAnnotD (RoleAnnotDecl tc' roles') }
310
311 cvtDec (TH.StandaloneDerivD cxt ty)
312 = do { cxt' <- cvtContext cxt
313 ; L loc ty' <- cvtType ty
314 ; let inst_ty' = L loc $ mkHsForAllTy Implicit [] cxt' $ L loc ty'
315 ; returnJustL $ DerivD $
316 DerivDecl { deriv_type = inst_ty', deriv_overlap_mode = Nothing } }
317
318 cvtDec (TH.DefaultSigD nm typ)
319 = do { nm' <- vNameL nm
320 ; ty' <- cvtType typ
321 ; returnJustL $ Hs.SigD $ GenericSig [nm'] ty' }
322 ----------------
323 cvtTySynEqn :: Located RdrName -> TySynEqn -> CvtM (LTyFamInstEqn RdrName)
324 cvtTySynEqn tc (TySynEqn lhs rhs)
325 = do { lhs' <- mapM cvtType lhs
326 ; rhs' <- cvtType rhs
327 ; returnL $ TyFamEqn { tfe_tycon = tc
328 , tfe_pats = mkHsWithBndrs lhs'
329 , tfe_rhs = rhs' } }
330
331 ----------------
332 cvt_ci_decs :: MsgDoc -> [TH.Dec]
333 -> CvtM (LHsBinds RdrName,
334 [LSig RdrName],
335 [LFamilyDecl RdrName],
336 [LTyFamInstDecl RdrName],
337 [LDataFamInstDecl RdrName])
338 -- Convert the declarations inside a class or instance decl
339 -- ie signatures, bindings, and associated types
340 cvt_ci_decs doc decs
341 = do { decs' <- cvtDecs decs
342 ; let (ats', bind_sig_decs') = partitionWith is_tyfam_inst decs'
343 ; let (adts', no_ats') = partitionWith is_datafam_inst bind_sig_decs'
344 ; let (sigs', prob_binds') = partitionWith is_sig no_ats'
345 ; let (binds', prob_fams') = partitionWith is_bind prob_binds'
346 ; let (fams', bads) = partitionWith is_fam_decl prob_fams'
347 ; unless (null bads) (failWith (mkBadDecMsg doc bads))
348 --We use FromSource as the origin of the bind
349 -- because the TH declaration is user-written
350 ; return (listToBag binds', sigs', fams', ats', adts') }
351
352 ----------------
353 cvt_tycl_hdr :: TH.Cxt -> TH.Name -> [TH.TyVarBndr]
354 -> CvtM ( LHsContext RdrName
355 , Located RdrName
356 , LHsTyVarBndrs RdrName)
357 cvt_tycl_hdr cxt tc tvs
358 = do { cxt' <- cvtContext cxt
359 ; tc' <- tconNameL tc
360 ; tvs' <- cvtTvs tvs
361 ; return (cxt', tc', tvs')
362 }
363
364 cvt_tyinst_hdr :: TH.Cxt -> TH.Name -> [TH.Type]
365 -> CvtM ( LHsContext RdrName
366 , Located RdrName
367 , HsWithBndrs RdrName [LHsType RdrName])
368 cvt_tyinst_hdr cxt tc tys
369 = do { cxt' <- cvtContext cxt
370 ; tc' <- tconNameL tc
371 ; tys' <- mapM cvtType tys
372 ; return (cxt', tc', mkHsWithBndrs tys') }
373
374 -------------------------------------------------------------------
375 -- Partitioning declarations
376 -------------------------------------------------------------------
377
378 is_fam_decl :: LHsDecl RdrName -> Either (LFamilyDecl RdrName) (LHsDecl RdrName)
379 is_fam_decl (L loc (TyClD (FamDecl { tcdFam = d }))) = Left (L loc d)
380 is_fam_decl decl = Right decl
381
382 is_tyfam_inst :: LHsDecl RdrName -> Either (LTyFamInstDecl RdrName) (LHsDecl RdrName)
383 is_tyfam_inst (L loc (Hs.InstD (TyFamInstD { tfid_inst = d }))) = Left (L loc d)
384 is_tyfam_inst decl = Right decl
385
386 is_datafam_inst :: LHsDecl RdrName -> Either (LDataFamInstDecl RdrName) (LHsDecl RdrName)
387 is_datafam_inst (L loc (Hs.InstD (DataFamInstD { dfid_inst = d }))) = Left (L loc d)
388 is_datafam_inst decl = Right decl
389
390 is_sig :: LHsDecl RdrName -> Either (LSig RdrName) (LHsDecl RdrName)
391 is_sig (L loc (Hs.SigD sig)) = Left (L loc sig)
392 is_sig decl = Right decl
393
394 is_bind :: LHsDecl RdrName -> Either (LHsBind RdrName) (LHsDecl RdrName)
395 is_bind (L loc (Hs.ValD bind)) = Left (L loc bind)
396 is_bind decl = Right decl
397
398 mkBadDecMsg :: Outputable a => MsgDoc -> [a] -> MsgDoc
399 mkBadDecMsg doc bads
400 = sep [ ptext (sLit "Illegal declaration(s) in") <+> doc <> colon
401 , nest 2 (vcat (map Outputable.ppr bads)) ]
402
403 ---------------------------------------------------
404 -- Data types
405 -- Can't handle GADTs yet
406 ---------------------------------------------------
407
408 cvtConstr :: TH.Con -> CvtM (LConDecl RdrName)
409
410 cvtConstr (NormalC c strtys)
411 = do { c' <- cNameL c
412 ; cxt' <- returnL []
413 ; tys' <- mapM cvt_arg strtys
414 ; returnL $ mkSimpleConDecl c' noExistentials cxt' (PrefixCon tys') }
415
416 cvtConstr (RecC c varstrtys)
417 = do { c' <- cNameL c
418 ; cxt' <- returnL []
419 ; args' <- mapM cvt_id_arg varstrtys
420 ; returnL $ mkSimpleConDecl c' noExistentials cxt'
421 (RecCon (noLoc args')) }
422
423 cvtConstr (InfixC st1 c st2)
424 = do { c' <- cNameL c
425 ; cxt' <- returnL []
426 ; st1' <- cvt_arg st1
427 ; st2' <- cvt_arg st2
428 ; returnL $ mkSimpleConDecl c' noExistentials cxt' (InfixCon st1' st2') }
429
430 cvtConstr (ForallC tvs ctxt con)
431 = do { tvs' <- cvtTvs tvs
432 ; L loc ctxt' <- cvtContext ctxt
433 ; L _ con' <- cvtConstr con
434 ; returnL $ con' { con_qvars = mkHsQTvs (hsQTvBndrs tvs' ++ hsQTvBndrs (con_qvars con'))
435 , con_cxt = L loc (ctxt' ++ (unLoc $ con_cxt con')) } }
436
437 cvt_arg :: (TH.Strict, TH.Type) -> CvtM (LHsType RdrName)
438 cvt_arg (NotStrict, ty) = cvtType ty
439 cvt_arg (IsStrict, ty)
440 = do { ty' <- cvtType ty
441 ; returnL $ HsBangTy (HsSrcBang Nothing Nothing True) ty' }
442 cvt_arg (Unpacked, ty)
443 = do { ty' <- cvtType ty
444 ; returnL $ HsBangTy (HsSrcBang Nothing (Just True) True) ty' }
445
446 cvt_id_arg :: (TH.Name, TH.Strict, TH.Type) -> CvtM (LConDeclField RdrName)
447 cvt_id_arg (i, str, ty)
448 = do { i' <- vNameL i
449 ; ty' <- cvt_arg (str,ty)
450 ; return $ noLoc (ConDeclField { cd_fld_names = [i']
451 , cd_fld_type = ty'
452 , cd_fld_doc = Nothing}) }
453
454 cvtDerivs :: [TH.Name] -> CvtM (Maybe (Located [LHsType RdrName]))
455 cvtDerivs [] = return Nothing
456 cvtDerivs cs = do { cs' <- mapM cvt_one cs
457 ; return (Just (noLoc cs')) }
458 where
459 cvt_one c = do { c' <- tconName c
460 ; returnL $ HsTyVar c' }
461
462 cvt_fundep :: FunDep -> CvtM (Located (Class.FunDep (Located RdrName)))
463 cvt_fundep (FunDep xs ys) = do { xs' <- mapM tName xs
464 ; ys' <- mapM tName ys
465 ; returnL (map noLoc xs', map noLoc ys') }
466
467 noExistentials :: [LHsTyVarBndr RdrName]
468 noExistentials = []
469
470 ------------------------------------------
471 -- Foreign declarations
472 ------------------------------------------
473
474 cvtForD :: Foreign -> CvtM (ForeignDecl RdrName)
475 cvtForD (ImportF callconv safety from nm ty)
476 | Just impspec <- parseCImport (noLoc (cvt_conv callconv)) (noLoc safety')
477 (mkFastString (TH.nameBase nm))
478 from (noLoc from)
479 = do { nm' <- vNameL nm
480 ; ty' <- cvtType ty
481 ; return (ForeignImport nm' ty' noForeignImportCoercionYet impspec)
482 }
483 | otherwise
484 = failWith $ text (show from) <+> ptext (sLit "is not a valid ccall impent")
485 where
486 safety' = case safety of
487 Unsafe -> PlayRisky
488 Safe -> PlaySafe
489 Interruptible -> PlayInterruptible
490
491 cvtForD (ExportF callconv as nm ty)
492 = do { nm' <- vNameL nm
493 ; ty' <- cvtType ty
494 ; let e = CExport (noLoc (CExportStatic (mkFastString as)
495 (cvt_conv callconv)))
496 (noLoc as)
497 ; return $ ForeignExport nm' ty' noForeignExportCoercionYet e }
498
499 cvt_conv :: TH.Callconv -> CCallConv
500 cvt_conv TH.CCall = CCallConv
501 cvt_conv TH.StdCall = StdCallConv
502 cvt_conv TH.CApi = CApiConv
503 cvt_conv TH.Prim = PrimCallConv
504 cvt_conv TH.JavaScript = JavaScriptCallConv
505
506 ------------------------------------------
507 -- Pragmas
508 ------------------------------------------
509
510 cvtPragmaD :: Pragma -> CvtM (Maybe (LHsDecl RdrName))
511 cvtPragmaD (InlineP nm inline rm phases)
512 = do { nm' <- vNameL nm
513 ; let dflt = dfltActivation inline
514 ; let ip = InlinePragma { inl_src = "{-# INLINE"
515 , inl_inline = cvtInline inline
516 , inl_rule = cvtRuleMatch rm
517 , inl_act = cvtPhases phases dflt
518 , inl_sat = Nothing }
519 ; returnJustL $ Hs.SigD $ InlineSig nm' ip }
520
521 cvtPragmaD (SpecialiseP nm ty inline phases)
522 = do { nm' <- vNameL nm
523 ; ty' <- cvtType ty
524 ; let (inline', dflt) = case inline of
525 Just inline1 -> (cvtInline inline1, dfltActivation inline1)
526 Nothing -> (EmptyInlineSpec, AlwaysActive)
527 ; let ip = InlinePragma { inl_src = "{-# INLINE"
528 , inl_inline = inline'
529 , inl_rule = Hs.FunLike
530 , inl_act = cvtPhases phases dflt
531 , inl_sat = Nothing }
532 ; returnJustL $ Hs.SigD $ SpecSig nm' [ty'] ip }
533
534 cvtPragmaD (SpecialiseInstP ty)
535 = do { ty' <- cvtType ty
536 ; returnJustL $ Hs.SigD $ SpecInstSig "{-# SPECIALISE" ty' }
537
538 cvtPragmaD (RuleP nm bndrs lhs rhs phases)
539 = do { let nm' = mkFastString nm
540 ; let act = cvtPhases phases AlwaysActive
541 ; bndrs' <- mapM cvtRuleBndr bndrs
542 ; lhs' <- cvtl lhs
543 ; rhs' <- cvtl rhs
544 ; returnJustL $ Hs.RuleD
545 $ HsRules "{-# RULES" [noLoc $ HsRule (noLoc nm') act bndrs'
546 lhs' placeHolderNames
547 rhs' placeHolderNames]
548 }
549
550 cvtPragmaD (AnnP target exp)
551 = do { exp' <- cvtl exp
552 ; target' <- case target of
553 ModuleAnnotation -> return ModuleAnnProvenance
554 TypeAnnotation n -> do
555 n' <- tconName n
556 return (TypeAnnProvenance (noLoc n'))
557 ValueAnnotation n -> do
558 n' <- vcName n
559 return (ValueAnnProvenance (noLoc n'))
560 ; returnJustL $ Hs.AnnD $ HsAnnotation "{-# ANN" target' exp'
561 }
562
563 cvtPragmaD (LineP line file)
564 = do { setL (srcLocSpan (mkSrcLoc (fsLit file) line 1))
565 ; return Nothing
566 }
567
568 dfltActivation :: TH.Inline -> Activation
569 dfltActivation TH.NoInline = NeverActive
570 dfltActivation _ = AlwaysActive
571
572 cvtInline :: TH.Inline -> Hs.InlineSpec
573 cvtInline TH.NoInline = Hs.NoInline
574 cvtInline TH.Inline = Hs.Inline
575 cvtInline TH.Inlinable = Hs.Inlinable
576
577 cvtRuleMatch :: TH.RuleMatch -> RuleMatchInfo
578 cvtRuleMatch TH.ConLike = Hs.ConLike
579 cvtRuleMatch TH.FunLike = Hs.FunLike
580
581 cvtPhases :: TH.Phases -> Activation -> Activation
582 cvtPhases AllPhases dflt = dflt
583 cvtPhases (FromPhase i) _ = ActiveAfter i
584 cvtPhases (BeforePhase i) _ = ActiveBefore i
585
586 cvtRuleBndr :: TH.RuleBndr -> CvtM (Hs.LRuleBndr RdrName)
587 cvtRuleBndr (RuleVar n)
588 = do { n' <- vNameL n
589 ; return $ noLoc $ Hs.RuleBndr n' }
590 cvtRuleBndr (TypedRuleVar n ty)
591 = do { n' <- vNameL n
592 ; ty' <- cvtType ty
593 ; return $ noLoc $ Hs.RuleBndrSig n' $ mkHsWithBndrs ty' }
594
595 ---------------------------------------------------
596 -- Declarations
597 ---------------------------------------------------
598
599 cvtLocalDecs :: MsgDoc -> [TH.Dec] -> CvtM (HsLocalBinds RdrName)
600 cvtLocalDecs doc ds
601 | null ds
602 = return EmptyLocalBinds
603 | otherwise
604 = do { ds' <- cvtDecs ds
605 ; let (binds, prob_sigs) = partitionWith is_bind ds'
606 ; let (sigs, bads) = partitionWith is_sig prob_sigs
607 ; unless (null bads) (failWith (mkBadDecMsg doc bads))
608 ; return (HsValBinds (ValBindsIn (listToBag binds) sigs)) }
609
610 cvtClause :: TH.Clause -> CvtM (Hs.LMatch RdrName (LHsExpr RdrName))
611 cvtClause (Clause ps body wheres)
612 = do { ps' <- cvtPats ps
613 ; g' <- cvtGuard body
614 ; ds' <- cvtLocalDecs (ptext (sLit "a where clause")) wheres
615 ; returnL $ Hs.Match Nothing ps' Nothing (GRHSs g' ds') }
616
617
618 -------------------------------------------------------------------
619 -- Expressions
620 -------------------------------------------------------------------
621
622 cvtl :: TH.Exp -> CvtM (LHsExpr RdrName)
623 cvtl e = wrapL (cvt e)
624 where
625 cvt (VarE s) = do { s' <- vName s; return $ HsVar s' }
626 cvt (ConE s) = do { s' <- cName s; return $ HsVar s' }
627 cvt (LitE l)
628 | overloadedLit l = do { l' <- cvtOverLit l; return $ HsOverLit l' }
629 | otherwise = do { l' <- cvtLit l; return $ HsLit l' }
630
631 cvt (AppE x y) = do { x' <- cvtl x; y' <- cvtl y; return $ HsApp x' y' }
632 cvt (LamE ps e) = do { ps' <- cvtPats ps; e' <- cvtl e
633 ; return $ HsLam (mkMatchGroup FromSource [mkSimpleMatch ps' e']) }
634 cvt (LamCaseE ms) = do { ms' <- mapM cvtMatch ms
635 ; return $ HsLamCase placeHolderType
636 (mkMatchGroup FromSource ms')
637 }
638 cvt (TupE [e]) = do { e' <- cvtl e; return $ HsPar e' }
639 -- Note [Dropping constructors]
640 -- Singleton tuples treated like nothing (just parens)
641 cvt (TupE es) = do { es' <- mapM cvtl es
642 ; return $ ExplicitTuple (map (noLoc . Present) es')
643 Boxed }
644 cvt (UnboxedTupE es) = do { es' <- mapM cvtl es
645 ; return $ ExplicitTuple
646 (map (noLoc . Present) es') Unboxed }
647 cvt (CondE x y z) = do { x' <- cvtl x; y' <- cvtl y; z' <- cvtl z;
648 ; return $ HsIf (Just noSyntaxExpr) x' y' z' }
649 cvt (MultiIfE alts)
650 | null alts = failWith (ptext (sLit "Multi-way if-expression with no alternatives"))
651 | otherwise = do { alts' <- mapM cvtpair alts
652 ; return $ HsMultiIf placeHolderType alts' }
653 cvt (LetE ds e) = do { ds' <- cvtLocalDecs (ptext (sLit "a let expression")) ds
654 ; e' <- cvtl e; return $ HsLet ds' e' }
655 cvt (CaseE e ms) = do { e' <- cvtl e; ms' <- mapM cvtMatch ms
656 ; return $ HsCase e' (mkMatchGroup FromSource ms') }
657 cvt (DoE ss) = cvtHsDo DoExpr ss
658 cvt (CompE ss) = cvtHsDo ListComp ss
659 cvt (ArithSeqE dd) = do { dd' <- cvtDD dd; return $ ArithSeq noPostTcExpr Nothing dd' }
660 cvt (ListE xs)
661 | Just s <- allCharLs xs = do { l' <- cvtLit (StringL s); return (HsLit l') }
662 -- Note [Converting strings]
663 | otherwise = do { xs' <- mapM cvtl xs
664 ; return $ ExplicitList placeHolderType Nothing xs'
665 }
666
667 -- Infix expressions
668 cvt (InfixE (Just x) s (Just y)) = do { x' <- cvtl x; s' <- cvtl s; y' <- cvtl y
669 ; wrapParL HsPar $
670 OpApp (mkLHsPar x') s' undefined (mkLHsPar y') }
671 -- Parenthesise both arguments and result,
672 -- to ensure this operator application does
673 -- does not get re-associated
674 -- See Note [Operator association]
675 cvt (InfixE Nothing s (Just y)) = do { s' <- cvtl s; y' <- cvtl y
676 ; wrapParL HsPar $ SectionR s' y' }
677 -- See Note [Sections in HsSyn] in HsExpr
678 cvt (InfixE (Just x) s Nothing ) = do { x' <- cvtl x; s' <- cvtl s
679 ; wrapParL HsPar $ SectionL x' s' }
680
681 cvt (InfixE Nothing s Nothing ) = do { s' <- cvtl s; return $ HsPar s' }
682 -- Can I indicate this is an infix thing?
683 -- Note [Dropping constructors]
684
685 cvt (UInfixE x s y) = do { x' <- cvtl x
686 ; let x'' = case x' of
687 L _ (OpApp {}) -> x'
688 _ -> mkLHsPar x'
689 ; cvtOpApp x'' s y } -- Note [Converting UInfix]
690
691 cvt (ParensE e) = do { e' <- cvtl e; return $ HsPar e' }
692 cvt (SigE e t) = do { e' <- cvtl e; t' <- cvtType t
693 ; return $ ExprWithTySig e' t' PlaceHolder }
694 cvt (RecConE c flds) = do { c' <- cNameL c
695 ; flds' <- mapM cvtFld flds
696 ; return $ RecordCon c' noPostTcExpr (HsRecFields flds' Nothing)}
697 cvt (RecUpdE e flds) = do { e' <- cvtl e
698 ; flds' <- mapM cvtFld flds
699 ; return $ RecordUpd e' (HsRecFields flds' Nothing) [] [] [] }
700 cvt (StaticE e) = fmap HsStatic $ cvtl e
701
702 {- Note [Dropping constructors]
703 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
704 When we drop constructors from the input (for instance, when we encounter @TupE [e]@)
705 we must insert parentheses around the argument. Otherwise, @UInfix@ constructors in @e@
706 could meet @UInfix@ constructors containing the @TupE [e]@. For example:
707
708 UInfixE x * (TupE [UInfixE y + z])
709
710 If we drop the singleton tuple but don't insert parentheses, the @UInfixE@s would meet
711 and the above expression would be reassociated to
712
713 OpApp (OpApp x * y) + z
714
715 which we don't want.
716 -}
717
718 cvtFld :: (TH.Name, TH.Exp) -> CvtM (LHsRecField RdrName (LHsExpr RdrName))
719 cvtFld (v,e)
720 = do { v' <- vNameL v; e' <- cvtl e
721 ; return (noLoc $ HsRecField { hsRecFieldId = v', hsRecFieldArg = e'
722 , hsRecPun = False}) }
723
724 cvtDD :: Range -> CvtM (ArithSeqInfo RdrName)
725 cvtDD (FromR x) = do { x' <- cvtl x; return $ From x' }
726 cvtDD (FromThenR x y) = do { x' <- cvtl x; y' <- cvtl y; return $ FromThen x' y' }
727 cvtDD (FromToR x y) = do { x' <- cvtl x; y' <- cvtl y; return $ FromTo x' y' }
728 cvtDD (FromThenToR x y z) = do { x' <- cvtl x; y' <- cvtl y; z' <- cvtl z; return $ FromThenTo x' y' z' }
729
730 {- Note [Operator assocation]
731 We must be quite careful about adding parens:
732 * Infix (UInfix ...) op arg Needs parens round the first arg
733 * Infix (Infix ...) op arg Needs parens round the first arg
734 * UInfix (UInfix ...) op arg No parens for first arg
735 * UInfix (Infix ...) op arg Needs parens round first arg
736
737
738 Note [Converting UInfix]
739 ~~~~~~~~~~~~~~~~~~~~~~~~
740 When converting @UInfixE@ and @UInfixP@ values, we want to readjust
741 the trees to reflect the fixities of the underlying operators:
742
743 UInfixE x * (UInfixE y + z) ---> (x * y) + z
744
745 This is done by the renamer (see @mkOppAppRn@ and @mkConOppPatRn@ in
746 RnTypes), which expects that the input will be completely left-biased.
747 So we left-bias the trees of @UInfixP@ and @UInfixE@ that we come across.
748
749 Sample input:
750
751 UInfixE
752 (UInfixE x op1 y)
753 op2
754 (UInfixE z op3 w)
755
756 Sample output:
757
758 OpApp
759 (OpApp
760 (OpApp x op1 y)
761 op2
762 z)
763 op3
764 w
765
766 The functions @cvtOpApp@ and @cvtOpAppP@ are responsible for this
767 left-biasing.
768 -}
769
770 {- | @cvtOpApp x op y@ converts @op@ and @y@ and produces the operator application @x `op` y@.
771 The produced tree of infix expressions will be left-biased, provided @x@ is.
772
773 We can see that @cvtOpApp@ is correct as follows. The inductive hypothesis
774 is that @cvtOpApp x op y@ is left-biased, provided @x@ is. It is clear that
775 this holds for both branches (of @cvtOpApp@), provided we assume it holds for
776 the recursive calls to @cvtOpApp@.
777
778 When we call @cvtOpApp@ from @cvtl@, the first argument will always be left-biased
779 since we have already run @cvtl@ on it.
780 -}
781 cvtOpApp :: LHsExpr RdrName -> TH.Exp -> TH.Exp -> CvtM (HsExpr RdrName)
782 cvtOpApp x op1 (UInfixE y op2 z)
783 = do { l <- wrapL $ cvtOpApp x op1 y
784 ; cvtOpApp l op2 z }
785 cvtOpApp x op y
786 = do { op' <- cvtl op
787 ; y' <- cvtl y
788 ; return (OpApp x op' undefined y') }
789
790 -------------------------------------
791 -- Do notation and statements
792 -------------------------------------
793
794 cvtHsDo :: HsStmtContext Name.Name -> [TH.Stmt] -> CvtM (HsExpr RdrName)
795 cvtHsDo do_or_lc stmts
796 | null stmts = failWith (ptext (sLit "Empty stmt list in do-block"))
797 | otherwise
798 = do { stmts' <- cvtStmts stmts
799 ; let Just (stmts'', last') = snocView stmts'
800
801 ; last'' <- case last' of
802 L loc (BodyStmt body _ _ _) -> return (L loc (mkLastStmt body))
803 _ -> failWith (bad_last last')
804
805 ; return $ HsDo do_or_lc (stmts'' ++ [last'']) placeHolderType }
806 where
807 bad_last stmt = vcat [ ptext (sLit "Illegal last statement of") <+> pprAStmtContext do_or_lc <> colon
808 , nest 2 $ Outputable.ppr stmt
809 , ptext (sLit "(It should be an expression.)") ]
810
811 cvtStmts :: [TH.Stmt] -> CvtM [Hs.LStmt RdrName (LHsExpr RdrName)]
812 cvtStmts = mapM cvtStmt
813
814 cvtStmt :: TH.Stmt -> CvtM (Hs.LStmt RdrName (LHsExpr RdrName))
815 cvtStmt (NoBindS e) = do { e' <- cvtl e; returnL $ mkBodyStmt e' }
816 cvtStmt (TH.BindS p e) = do { p' <- cvtPat p; e' <- cvtl e; returnL $ mkBindStmt p' e' }
817 cvtStmt (TH.LetS ds) = do { ds' <- cvtLocalDecs (ptext (sLit "a let binding")) ds
818 ; returnL $ LetStmt ds' }
819 cvtStmt (TH.ParS dss) = do { dss' <- mapM cvt_one dss; returnL $ ParStmt dss' noSyntaxExpr noSyntaxExpr }
820 where
821 cvt_one ds = do { ds' <- cvtStmts ds; return (ParStmtBlock ds' undefined noSyntaxExpr) }
822
823 cvtMatch :: TH.Match -> CvtM (Hs.LMatch RdrName (LHsExpr RdrName))
824 cvtMatch (TH.Match p body decs)
825 = do { p' <- cvtPat p
826 ; g' <- cvtGuard body
827 ; decs' <- cvtLocalDecs (ptext (sLit "a where clause")) decs
828 ; returnL $ Hs.Match Nothing [p'] Nothing (GRHSs g' decs') }
829
830 cvtGuard :: TH.Body -> CvtM [LGRHS RdrName (LHsExpr RdrName)]
831 cvtGuard (GuardedB pairs) = mapM cvtpair pairs
832 cvtGuard (NormalB e) = do { e' <- cvtl e; g' <- returnL $ GRHS [] e'; return [g'] }
833
834 cvtpair :: (TH.Guard, TH.Exp) -> CvtM (LGRHS RdrName (LHsExpr RdrName))
835 cvtpair (NormalG ge,rhs) = do { ge' <- cvtl ge; rhs' <- cvtl rhs
836 ; g' <- returnL $ mkBodyStmt ge'
837 ; returnL $ GRHS [g'] rhs' }
838 cvtpair (PatG gs,rhs) = do { gs' <- cvtStmts gs; rhs' <- cvtl rhs
839 ; returnL $ GRHS gs' rhs' }
840
841 cvtOverLit :: Lit -> CvtM (HsOverLit RdrName)
842 cvtOverLit (IntegerL i)
843 = do { force i; return $ mkHsIntegral (show i) i placeHolderType}
844 cvtOverLit (RationalL r)
845 = do { force r; return $ mkHsFractional (cvtFractionalLit r) placeHolderType}
846 cvtOverLit (StringL s)
847 = do { let { s' = mkFastString s }
848 ; force s'
849 ; return $ mkHsIsString s s' placeHolderType
850 }
851 cvtOverLit _ = panic "Convert.cvtOverLit: Unexpected overloaded literal"
852 -- An Integer is like an (overloaded) '3' in a Haskell source program
853 -- Similarly 3.5 for fractionals
854
855 {- Note [Converting strings]
856 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
857 If we get (ListE [CharL 'x', CharL 'y']) we'd like to convert to
858 a string literal for "xy". Of course, we might hope to get
859 (LitE (StringL "xy")), but not always, and allCharLs fails quickly
860 if it isn't a literal string
861 -}
862
863 allCharLs :: [TH.Exp] -> Maybe String
864 -- Note [Converting strings]
865 -- NB: only fire up this setup for a non-empty list, else
866 -- there's a danger of returning "" for [] :: [Int]!
867 allCharLs xs
868 = case xs of
869 LitE (CharL c) : ys -> go [c] ys
870 _ -> Nothing
871 where
872 go cs [] = Just (reverse cs)
873 go cs (LitE (CharL c) : ys) = go (c:cs) ys
874 go _ _ = Nothing
875
876 cvtLit :: Lit -> CvtM HsLit
877 cvtLit (IntPrimL i) = do { force i; return $ HsIntPrim (show i) i }
878 cvtLit (WordPrimL w) = do { force w; return $ HsWordPrim (show w) w }
879 cvtLit (FloatPrimL f) = do { force f; return $ HsFloatPrim (cvtFractionalLit f) }
880 cvtLit (DoublePrimL f) = do { force f; return $ HsDoublePrim (cvtFractionalLit f) }
881 cvtLit (CharL c) = do { force c; return $ HsChar (show c) c }
882 cvtLit (StringL s) = do { let { s' = mkFastString s }
883 ; force s'
884 ; return $ HsString s s' }
885 cvtLit (StringPrimL s) = do { let { s' = BS.pack s }
886 ; force s'
887 ; return $ HsStringPrim (w8ToString s) s' }
888 cvtLit _ = panic "Convert.cvtLit: Unexpected literal"
889 -- cvtLit should not be called on IntegerL, RationalL
890 -- That precondition is established right here in
891 -- Convert.hs, hence panic
892
893 w8ToString :: [Word8] -> String
894 w8ToString ws = map (\w -> chr (fromIntegral w)) ws
895
896 cvtPats :: [TH.Pat] -> CvtM [Hs.LPat RdrName]
897 cvtPats pats = mapM cvtPat pats
898
899 cvtPat :: TH.Pat -> CvtM (Hs.LPat RdrName)
900 cvtPat pat = wrapL (cvtp pat)
901
902 cvtp :: TH.Pat -> CvtM (Hs.Pat RdrName)
903 cvtp (TH.LitP l)
904 | overloadedLit l = do { l' <- cvtOverLit l
905 ; return (mkNPat (noLoc l') Nothing) }
906 -- Not right for negative patterns;
907 -- need to think about that!
908 | otherwise = do { l' <- cvtLit l; return $ Hs.LitPat l' }
909 cvtp (TH.VarP s) = do { s' <- vName s; return $ Hs.VarPat s' }
910 cvtp (TupP [p]) = do { p' <- cvtPat p; return $ ParPat p' } -- Note [Dropping constructors]
911 cvtp (TupP ps) = do { ps' <- cvtPats ps; return $ TuplePat ps' Boxed [] }
912 cvtp (UnboxedTupP ps) = do { ps' <- cvtPats ps; return $ TuplePat ps' Unboxed [] }
913 cvtp (ConP s ps) = do { s' <- cNameL s; ps' <- cvtPats ps
914 ; return $ ConPatIn s' (PrefixCon ps') }
915 cvtp (InfixP p1 s p2) = do { s' <- cNameL s; p1' <- cvtPat p1; p2' <- cvtPat p2
916 ; wrapParL ParPat $
917 ConPatIn s' (InfixCon (mkParPat p1') (mkParPat p2')) }
918 -- See Note [Operator association]
919 cvtp (UInfixP p1 s p2) = do { p1' <- cvtPat p1; cvtOpAppP p1' s p2 } -- Note [Converting UInfix]
920 cvtp (ParensP p) = do { p' <- cvtPat p; return $ ParPat p' }
921 cvtp (TildeP p) = do { p' <- cvtPat p; return $ LazyPat p' }
922 cvtp (BangP p) = do { p' <- cvtPat p; return $ BangPat p' }
923 cvtp (TH.AsP s p) = do { s' <- vNameL s; p' <- cvtPat p; return $ AsPat s' p' }
924 cvtp TH.WildP = return $ WildPat placeHolderType
925 cvtp (RecP c fs) = do { c' <- cNameL c; fs' <- mapM cvtPatFld fs
926 ; return $ ConPatIn c'
927 $ Hs.RecCon (HsRecFields fs' Nothing) }
928 cvtp (ListP ps) = do { ps' <- cvtPats ps
929 ; return $ ListPat ps' placeHolderType Nothing }
930 cvtp (SigP p t) = do { p' <- cvtPat p; t' <- cvtType t
931 ; return $ SigPatIn p' (mkHsWithBndrs t') }
932 cvtp (ViewP e p) = do { e' <- cvtl e; p' <- cvtPat p
933 ; return $ ViewPat e' p' placeHolderType }
934
935 cvtPatFld :: (TH.Name, TH.Pat) -> CvtM (LHsRecField RdrName (LPat RdrName))
936 cvtPatFld (s,p)
937 = do { s' <- vNameL s; p' <- cvtPat p
938 ; return (noLoc $ HsRecField { hsRecFieldId = s', hsRecFieldArg = p'
939 , hsRecPun = False}) }
940
941 {- | @cvtOpAppP x op y@ converts @op@ and @y@ and produces the operator application @x `op` y@.
942 The produced tree of infix patterns will be left-biased, provided @x@ is.
943
944 See the @cvtOpApp@ documentation for how this function works.
945 -}
946 cvtOpAppP :: Hs.LPat RdrName -> TH.Name -> TH.Pat -> CvtM (Hs.Pat RdrName)
947 cvtOpAppP x op1 (UInfixP y op2 z)
948 = do { l <- wrapL $ cvtOpAppP x op1 y
949 ; cvtOpAppP l op2 z }
950 cvtOpAppP x op y
951 = do { op' <- cNameL op
952 ; y' <- cvtPat y
953 ; return (ConPatIn op' (InfixCon x y')) }
954
955 -----------------------------------------------------------
956 -- Types and type variables
957
958 cvtTvs :: [TH.TyVarBndr] -> CvtM (LHsTyVarBndrs RdrName)
959 cvtTvs tvs = do { tvs' <- mapM cvt_tv tvs; return (mkHsQTvs tvs') }
960
961 cvt_tv :: TH.TyVarBndr -> CvtM (LHsTyVarBndr RdrName)
962 cvt_tv (TH.PlainTV nm)
963 = do { nm' <- tName nm
964 ; returnL $ UserTyVar nm' }
965 cvt_tv (TH.KindedTV nm ki)
966 = do { nm' <- tName nm
967 ; ki' <- cvtKind ki
968 ; returnL $ KindedTyVar (noLoc nm') ki' }
969
970 cvtRole :: TH.Role -> Maybe Coercion.Role
971 cvtRole TH.NominalR = Just Coercion.Nominal
972 cvtRole TH.RepresentationalR = Just Coercion.Representational
973 cvtRole TH.PhantomR = Just Coercion.Phantom
974 cvtRole TH.InferR = Nothing
975
976 cvtContext :: TH.Cxt -> CvtM (LHsContext RdrName)
977 cvtContext tys = do { preds' <- mapM cvtPred tys; returnL preds' }
978
979 cvtPred :: TH.Pred -> CvtM (LHsType RdrName)
980 cvtPred = cvtType
981
982 cvtType :: TH.Type -> CvtM (LHsType RdrName)
983 cvtType = cvtTypeKind "type"
984
985 cvtTypeKind :: String -> TH.Type -> CvtM (LHsType RdrName)
986 cvtTypeKind ty_str ty
987 = do { (head_ty, tys') <- split_ty_app ty
988 ; case head_ty of
989 TupleT n
990 | length tys' == n -- Saturated
991 -> if n==1 then return (head tys') -- Singleton tuples treated
992 -- like nothing (ie just parens)
993 else returnL (HsTupleTy HsBoxedOrConstraintTuple tys')
994 | n == 1
995 -> failWith (ptext (sLit ("Illegal 1-tuple " ++ ty_str ++ " constructor")))
996 | otherwise
997 -> mk_apps (HsTyVar (getRdrName (tupleTyCon Boxed n))) tys'
998 UnboxedTupleT n
999 | length tys' == n -- Saturated
1000 -> if n==1 then return (head tys') -- Singleton tuples treated
1001 -- like nothing (ie just parens)
1002 else returnL (HsTupleTy HsUnboxedTuple tys')
1003 | otherwise
1004 -> mk_apps (HsTyVar (getRdrName (tupleTyCon Unboxed n))) tys'
1005 ArrowT
1006 | [x',y'] <- tys' -> returnL (HsFunTy x' y')
1007 | otherwise -> mk_apps (HsTyVar (getRdrName funTyCon)) tys'
1008 ListT
1009 | [x'] <- tys' -> returnL (HsListTy x')
1010 | otherwise -> mk_apps (HsTyVar (getRdrName listTyCon)) tys'
1011 VarT nm -> do { nm' <- tName nm; mk_apps (HsTyVar nm') tys' }
1012 ConT nm -> do { nm' <- tconName nm; mk_apps (HsTyVar nm') tys' }
1013
1014 ForallT tvs cxt ty
1015 | null tys'
1016 -> do { tvs' <- cvtTvs tvs
1017 ; cxt' <- cvtContext cxt
1018 ; ty' <- cvtType ty
1019 ; returnL $ mkExplicitHsForAllTy (hsQTvBndrs tvs') cxt' ty'
1020 }
1021
1022 SigT ty ki
1023 -> do { ty' <- cvtType ty
1024 ; ki' <- cvtKind ki
1025 ; mk_apps (HsKindSig ty' ki') tys'
1026 }
1027
1028 LitT lit
1029 -> returnL (HsTyLit (cvtTyLit lit))
1030
1031 PromotedT nm -> do { nm' <- cName nm; mk_apps (HsTyVar nm') tys' }
1032 -- Promoted data constructor; hence cName
1033
1034 PromotedTupleT n
1035 | n == 1
1036 -> failWith (ptext (sLit ("Illegal promoted 1-tuple " ++ ty_str)))
1037 | m == n -- Saturated
1038 -> do { let kis = replicate m placeHolderKind
1039 ; returnL (HsExplicitTupleTy kis tys')
1040 }
1041 where
1042 m = length tys'
1043
1044 PromotedNilT
1045 -> returnL (HsExplicitListTy placeHolderKind [])
1046
1047 PromotedConsT -- See Note [Representing concrete syntax in types]
1048 -- in Language.Haskell.TH.Syntax
1049 | [ty1, L _ (HsExplicitListTy _ tys2)] <- tys'
1050 -> returnL (HsExplicitListTy placeHolderKind (ty1:tys2))
1051 | otherwise
1052 -> mk_apps (HsTyVar (getRdrName consDataCon)) tys'
1053
1054 StarT
1055 -> returnL (HsTyVar (getRdrName liftedTypeKindTyCon))
1056
1057 ConstraintT
1058 -> returnL (HsTyVar (getRdrName constraintKindTyCon))
1059
1060 EqualityT
1061 | [x',y'] <- tys' -> returnL (HsEqTy x' y')
1062 | otherwise -> mk_apps (HsTyVar (getRdrName eqPrimTyCon)) tys'
1063
1064 _ -> failWith (ptext (sLit ("Malformed " ++ ty_str)) <+> text (show ty))
1065 }
1066
1067 mk_apps :: HsType RdrName -> [LHsType RdrName] -> CvtM (LHsType RdrName)
1068 mk_apps head_ty [] = returnL head_ty
1069 mk_apps head_ty (ty:tys) = do { head_ty' <- returnL head_ty
1070 ; mk_apps (HsAppTy head_ty' ty) tys }
1071
1072 split_ty_app :: TH.Type -> CvtM (TH.Type, [LHsType RdrName])
1073 split_ty_app ty = go ty []
1074 where
1075 go (AppT f a) as' = do { a' <- cvtType a; go f (a':as') }
1076 go f as = return (f,as)
1077
1078 cvtTyLit :: TH.TyLit -> HsTyLit
1079 cvtTyLit (NumTyLit i) = HsNumTy (show i) i
1080 cvtTyLit (StrTyLit s) = HsStrTy s (fsLit s)
1081
1082 cvtKind :: TH.Kind -> CvtM (LHsKind RdrName)
1083 cvtKind = cvtTypeKind "kind"
1084
1085 cvtMaybeKind :: Maybe TH.Kind -> CvtM (Maybe (LHsKind RdrName))
1086 cvtMaybeKind Nothing = return Nothing
1087 cvtMaybeKind (Just ki) = do { ki' <- cvtKind ki
1088 ; return (Just ki') }
1089
1090 -----------------------------------------------------------
1091 cvtFixity :: TH.Fixity -> Hs.Fixity
1092 cvtFixity (TH.Fixity prec dir) = Hs.Fixity prec (cvt_dir dir)
1093 where
1094 cvt_dir TH.InfixL = Hs.InfixL
1095 cvt_dir TH.InfixR = Hs.InfixR
1096 cvt_dir TH.InfixN = Hs.InfixN
1097
1098 -----------------------------------------------------------
1099
1100
1101 -----------------------------------------------------------
1102 -- some useful things
1103
1104 overloadedLit :: Lit -> Bool
1105 -- True for literals that Haskell treats as overloaded
1106 overloadedLit (IntegerL _) = True
1107 overloadedLit (RationalL _) = True
1108 overloadedLit _ = False
1109
1110 cvtFractionalLit :: Rational -> FractionalLit
1111 cvtFractionalLit r = FL { fl_text = show (fromRational r :: Double), fl_value = r }
1112
1113 --------------------------------------------------------------------
1114 -- Turning Name back into RdrName
1115 --------------------------------------------------------------------
1116
1117 -- variable names
1118 vNameL, cNameL, vcNameL, tconNameL :: TH.Name -> CvtM (Located RdrName)
1119 vName, cName, vcName, tName, tconName :: TH.Name -> CvtM RdrName
1120
1121 -- Variable names
1122 vNameL n = wrapL (vName n)
1123 vName n = cvtName OccName.varName n
1124
1125 -- Constructor function names; this is Haskell source, hence srcDataName
1126 cNameL n = wrapL (cName n)
1127 cName n = cvtName OccName.dataName n
1128
1129 -- Variable *or* constructor names; check by looking at the first char
1130 vcNameL n = wrapL (vcName n)
1131 vcName n = if isVarName n then vName n else cName n
1132
1133 -- Type variable names
1134 tName n = cvtName OccName.tvName n
1135
1136 -- Type Constructor names
1137 tconNameL n = wrapL (tconName n)
1138 tconName n = cvtName OccName.tcClsName n
1139
1140 cvtName :: OccName.NameSpace -> TH.Name -> CvtM RdrName
1141 cvtName ctxt_ns (TH.Name occ flavour)
1142 | not (okOcc ctxt_ns occ_str) = failWith (badOcc ctxt_ns occ_str)
1143 | otherwise
1144 = do { loc <- getL
1145 ; let rdr_name = thRdrName loc ctxt_ns occ_str flavour
1146 ; force rdr_name
1147 ; return rdr_name }
1148 where
1149 occ_str = TH.occString occ
1150
1151 okOcc :: OccName.NameSpace -> String -> Bool
1152 okOcc ns str
1153 | OccName.isVarNameSpace ns = okVarOcc str
1154 | OccName.isDataConNameSpace ns = okConOcc str
1155 | otherwise = okTcOcc str
1156
1157 -- Determine the name space of a name in a type
1158 --
1159 isVarName :: TH.Name -> Bool
1160 isVarName (TH.Name occ _)
1161 = case TH.occString occ of
1162 "" -> False
1163 (c:_) -> startsVarId c || startsVarSym c
1164
1165 badOcc :: OccName.NameSpace -> String -> SDoc
1166 badOcc ctxt_ns occ
1167 = ptext (sLit "Illegal") <+> pprNameSpace ctxt_ns
1168 <+> ptext (sLit "name:") <+> quotes (text occ)
1169
1170 thRdrName :: SrcSpan -> OccName.NameSpace -> String -> TH.NameFlavour -> RdrName
1171 -- This turns a TH Name into a RdrName; used for both binders and occurrences
1172 -- See Note [Binders in Template Haskell]
1173 -- The passed-in name space tells what the context is expecting;
1174 -- use it unless the TH name knows what name-space it comes
1175 -- from, in which case use the latter
1176 --
1177 -- We pass in a SrcSpan (gotten from the monad) because this function
1178 -- is used for *binders* and if we make an Exact Name we want it
1179 -- to have a binding site inside it. (cf Trac #5434)
1180 --
1181 -- ToDo: we may generate silly RdrNames, by passing a name space
1182 -- that doesn't match the string, like VarName ":+",
1183 -- which will give confusing error messages later
1184 --
1185 -- The strict applications ensure that any buried exceptions get forced
1186 thRdrName loc ctxt_ns th_occ th_name
1187 = case th_name of
1188 TH.NameG th_ns pkg mod -> thOrigRdrName th_occ th_ns pkg mod
1189 TH.NameQ mod -> (mkRdrQual $! mk_mod mod) $! occ
1190 TH.NameL uniq -> nameRdrName $! (((Name.mkInternalName $! mk_uniq uniq) $! occ) loc)
1191 TH.NameU uniq -> nameRdrName $! (((Name.mkSystemNameAt $! mk_uniq uniq) $! occ) loc)
1192 TH.NameS | Just name <- isBuiltInOcc_maybe occ -> nameRdrName $! name
1193 | otherwise -> mkRdrUnqual $! occ
1194 -- We check for built-in syntax here, because the TH
1195 -- user might have written a (NameS "(,,)"), for example
1196 where
1197 occ :: OccName.OccName
1198 occ = mk_occ ctxt_ns th_occ
1199
1200 thOrigRdrName :: String -> TH.NameSpace -> PkgName -> ModName -> RdrName
1201 thOrigRdrName occ th_ns pkg mod = (mkOrig $! (mkModule (mk_pkg pkg) (mk_mod mod))) $! (mk_occ (mk_ghc_ns th_ns) occ)
1202
1203 thRdrNameGuesses :: TH.Name -> [RdrName]
1204 thRdrNameGuesses (TH.Name occ flavour)
1205 -- This special case for NameG ensures that we don't generate duplicates in the output list
1206 | TH.NameG th_ns pkg mod <- flavour = [ thOrigRdrName occ_str th_ns pkg mod]
1207 | otherwise = [ thRdrName noSrcSpan gns occ_str flavour
1208 | gns <- guessed_nss]
1209 where
1210 -- guessed_ns are the name spaces guessed from looking at the TH name
1211 guessed_nss | isLexCon (mkFastString occ_str) = [OccName.tcName, OccName.dataName]
1212 | otherwise = [OccName.varName, OccName.tvName]
1213 occ_str = TH.occString occ
1214
1215 -- The packing and unpacking is rather turgid :-(
1216 mk_occ :: OccName.NameSpace -> String -> OccName.OccName
1217 mk_occ ns occ = OccName.mkOccName ns occ
1218
1219 mk_ghc_ns :: TH.NameSpace -> OccName.NameSpace
1220 mk_ghc_ns TH.DataName = OccName.dataName
1221 mk_ghc_ns TH.TcClsName = OccName.tcClsName
1222 mk_ghc_ns TH.VarName = OccName.varName
1223
1224 mk_mod :: TH.ModName -> ModuleName
1225 mk_mod mod = mkModuleName (TH.modString mod)
1226
1227 mk_pkg :: TH.PkgName -> PackageKey
1228 mk_pkg pkg = stringToPackageKey (TH.pkgString pkg)
1229
1230 mk_uniq :: Int -> Unique
1231 mk_uniq u = mkUniqueGrimily u
1232
1233 {-
1234 Note [Binders in Template Haskell]
1235 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1236 Consider this TH term construction:
1237 do { x1 <- TH.newName "x" -- newName :: String -> Q TH.Name
1238 ; x2 <- TH.newName "x" -- Builds a NameU
1239 ; x3 <- TH.newName "x"
1240
1241 ; let x = mkName "x" -- mkName :: String -> TH.Name
1242 -- Builds a NameS
1243
1244 ; return (LamE (..pattern [x1,x2]..) $
1245 LamE (VarPat x3) $
1246 ..tuple (x1,x2,x3,x)) }
1247
1248 It represents the term \[x1,x2]. \x3. (x1,x2,x3,x)
1249
1250 a) We don't want to complain about "x" being bound twice in
1251 the pattern [x1,x2]
1252 b) We don't want x3 to shadow the x1,x2
1253 c) We *do* want 'x' (dynamically bound with mkName) to bind
1254 to the innermost binding of "x", namely x3.
1255 d) When pretty printing, we want to print a unique with x1,x2
1256 etc, else they'll all print as "x" which isn't very helpful
1257
1258 When we convert all this to HsSyn, the TH.Names are converted with
1259 thRdrName. To achieve (b) we want the binders to be Exact RdrNames.
1260 Achieving (a) is a bit awkward, because
1261 - We must check for duplicate and shadowed names on Names,
1262 not RdrNames, *after* renaming.
1263 See Note [Collect binders only after renaming] in HsUtils
1264
1265 - But to achieve (a) we must distinguish between the Exact
1266 RdrNames arising from TH and the Unqual RdrNames that would
1267 come from a user writing \[x,x] -> blah
1268
1269 So in Convert.thRdrName we translate
1270 TH Name RdrName
1271 --------------------------------------------------------
1272 NameU (arising from newName) --> Exact (Name{ System })
1273 NameS (arising from mkName) --> Unqual
1274
1275 Notice that the NameUs generate *System* Names. Then, when
1276 figuring out shadowing and duplicates, we can filter out
1277 System Names.
1278
1279 This use of System Names fits with other uses of System Names, eg for
1280 temporary variables "a". Since there are lots of things called "a" we
1281 usually want to print the name with the unique, and that is indeed
1282 the way System Names are printed.
1283
1284 There's a small complication of course; see Note [Looking up Exact
1285 RdrNames] in RnEnv.
1286 -}