Revert "trees that grow" work
[ghc.git] / compiler / deSugar / DsMeta.hs
1 {-# LANGUAGE CPP, TypeFamilies #-}
2 {-# LANGUAGE FlexibleContexts #-}
3
4 -----------------------------------------------------------------------------
5 --
6 -- (c) The University of Glasgow 2006
7 --
8 -- The purpose of this module is to transform an HsExpr into a CoreExpr which
9 -- when evaluated, returns a (Meta.Q Meta.Exp) computation analogous to the
10 -- input HsExpr. We do this in the DsM monad, which supplies access to
11 -- CoreExpr's of the "smart constructors" of the Meta.Exp datatype.
12 --
13 -- It also defines a bunch of knownKeyNames, in the same way as is done
14 -- in prelude/PrelNames. It's much more convenient to do it here, because
15 -- otherwise we have to recompile PrelNames whenever we add a Name, which is
16 -- a Royal Pain (triggers other recompilation).
17 -----------------------------------------------------------------------------
18
19 module DsMeta( dsBracket ) where
20
21 #include "HsVersions.h"
22
23 import GhcPrelude
24
25 import {-# SOURCE #-} DsExpr ( dsExpr )
26
27 import MatchLit
28 import DsMonad
29
30 import qualified Language.Haskell.TH as TH
31
32 import HsSyn
33 import Class
34 import PrelNames
35 -- To avoid clashes with DsMeta.varName we must make a local alias for
36 -- OccName.varName we do this by removing varName from the import of
37 -- OccName above, making a qualified instance of OccName and using
38 -- OccNameAlias.varName where varName ws previously used in this file.
39 import qualified OccName( isDataOcc, isVarOcc, isTcOcc )
40
41 import Module
42 import Id
43 import Name hiding( isVarOcc, isTcOcc, varName, tcName )
44 import THNames
45 import NameEnv
46 import NameSet
47 import TcType
48 import TyCon
49 import TysWiredIn
50 import CoreSyn
51 import MkCore
52 import CoreUtils
53 import SrcLoc
54 import Unique
55 import BasicTypes
56 import Outputable
57 import Bag
58 import DynFlags
59 import FastString
60 import ForeignCall
61 import Util
62 import Maybes
63 import MonadUtils
64
65 import Data.ByteString ( unpack )
66 import Control.Monad
67 import Data.List
68
69 -----------------------------------------------------------------------------
70 dsBracket :: HsBracket GhcRn -> [PendingTcSplice] -> DsM CoreExpr
71 -- Returns a CoreExpr of type TH.ExpQ
72 -- The quoted thing is parameterised over Name, even though it has
73 -- been type checked. We don't want all those type decorations!
74
75 dsBracket brack splices
76 = dsExtendMetaEnv new_bit (do_brack brack)
77 where
78 new_bit = mkNameEnv [(n, DsSplice (unLoc e)) | PendingTcSplice n e <- splices]
79
80 do_brack (VarBr _ n) = do { MkC e1 <- lookupOcc n ; return e1 }
81 do_brack (ExpBr e) = do { MkC e1 <- repLE e ; return e1 }
82 do_brack (PatBr p) = do { MkC p1 <- repTopP p ; return p1 }
83 do_brack (TypBr t) = do { MkC t1 <- repLTy t ; return t1 }
84 do_brack (DecBrG gp) = do { MkC ds1 <- repTopDs gp ; return ds1 }
85 do_brack (DecBrL _) = panic "dsBracket: unexpected DecBrL"
86 do_brack (TExpBr e) = do { MkC e1 <- repLE e ; return e1 }
87
88 {- -------------- Examples --------------------
89
90 [| \x -> x |]
91 ====>
92 gensym (unpackString "x"#) `bindQ` \ x1::String ->
93 lam (pvar x1) (var x1)
94
95
96 [| \x -> $(f [| x |]) |]
97 ====>
98 gensym (unpackString "x"#) `bindQ` \ x1::String ->
99 lam (pvar x1) (f (var x1))
100 -}
101
102
103 -------------------------------------------------------
104 -- Declarations
105 -------------------------------------------------------
106
107 repTopP :: LPat GhcRn -> DsM (Core TH.PatQ)
108 repTopP pat = do { ss <- mkGenSyms (collectPatBinders pat)
109 ; pat' <- addBinds ss (repLP pat)
110 ; wrapGenSyms ss pat' }
111
112 repTopDs :: HsGroup GhcRn -> DsM (Core (TH.Q [TH.Dec]))
113 repTopDs group@(HsGroup { hs_valds = valds
114 , hs_splcds = splcds
115 , hs_tyclds = tyclds
116 , hs_derivds = derivds
117 , hs_fixds = fixds
118 , hs_defds = defds
119 , hs_fords = fords
120 , hs_warnds = warnds
121 , hs_annds = annds
122 , hs_ruleds = ruleds
123 , hs_vects = vects
124 , hs_docs = docs })
125 = do { let { bndrs = hsSigTvBinders valds
126 ++ hsGroupBinders group
127 ++ hsPatSynSelectors valds
128 ; instds = tyclds >>= group_instds } ;
129 ss <- mkGenSyms bndrs ;
130
131 -- Bind all the names mainly to avoid repeated use of explicit strings.
132 -- Thus we get
133 -- do { t :: String <- genSym "T" ;
134 -- return (Data t [] ...more t's... }
135 -- The other important reason is that the output must mention
136 -- only "T", not "Foo:T" where Foo is the current module
137
138 decls <- addBinds ss (
139 do { val_ds <- rep_val_binds valds
140 ; _ <- mapM no_splice splcds
141 ; tycl_ds <- mapM repTyClD (tyClGroupTyClDecls tyclds)
142 ; role_ds <- mapM repRoleD (concatMap group_roles tyclds)
143 ; inst_ds <- mapM repInstD instds
144 ; deriv_ds <- mapM repStandaloneDerivD derivds
145 ; fix_ds <- mapM repFixD fixds
146 ; _ <- mapM no_default_decl defds
147 ; for_ds <- mapM repForD fords
148 ; _ <- mapM no_warn (concatMap (wd_warnings . unLoc)
149 warnds)
150 ; ann_ds <- mapM repAnnD annds
151 ; rule_ds <- mapM repRuleD (concatMap (rds_rules . unLoc)
152 ruleds)
153 ; _ <- mapM no_vect vects
154 ; _ <- mapM no_doc docs
155
156 -- more needed
157 ; return (de_loc $ sort_by_loc $
158 val_ds ++ catMaybes tycl_ds ++ role_ds
159 ++ (concat fix_ds)
160 ++ inst_ds ++ rule_ds ++ for_ds
161 ++ ann_ds ++ deriv_ds) }) ;
162
163 decl_ty <- lookupType decQTyConName ;
164 let { core_list = coreList' decl_ty decls } ;
165
166 dec_ty <- lookupType decTyConName ;
167 q_decs <- repSequenceQ dec_ty core_list ;
168
169 wrapGenSyms ss q_decs
170 }
171 where
172 no_splice (L loc _)
173 = notHandledL loc "Splices within declaration brackets" empty
174 no_default_decl (L loc decl)
175 = notHandledL loc "Default declarations" (ppr decl)
176 no_warn (L loc (Warning thing _))
177 = notHandledL loc "WARNING and DEPRECATION pragmas" $
178 text "Pragma for declaration of" <+> ppr thing
179 no_vect (L loc decl)
180 = notHandledL loc "Vectorisation pragmas" (ppr decl)
181 no_doc (L loc _)
182 = notHandledL loc "Haddock documentation" empty
183
184 hsSigTvBinders :: HsValBinds GhcRn -> [Name]
185 -- See Note [Scoped type variables in bindings]
186 hsSigTvBinders binds
187 = concatMap get_scoped_tvs sigs
188 where
189 get_scoped_tvs :: LSig GhcRn -> [Name]
190 -- Both implicit and explicit quantified variables
191 -- We need the implicit ones for f :: forall (a::k). blah
192 -- here 'k' scopes too
193 get_scoped_tvs (L _ (TypeSig _ sig))
194 | HsIB { hsib_vars = implicit_vars
195 , hsib_body = hs_ty } <- hswc_body sig
196 , (explicit_vars, _) <- splitLHsForAllTy hs_ty
197 = implicit_vars ++ map hsLTyVarName explicit_vars
198 get_scoped_tvs _ = []
199
200 sigs = case binds of
201 ValBindsIn _ sigs -> sigs
202 ValBindsOut _ sigs -> sigs
203
204 {- Notes
205
206 Note [Scoped type variables in bindings]
207 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
208 Consider
209 f :: forall a. a -> a
210 f x = x::a
211 Here the 'forall a' brings 'a' into scope over the binding group.
212 To achieve this we
213
214 a) Gensym a binding for 'a' at the same time as we do one for 'f'
215 collecting the relevant binders with hsSigTvBinders
216
217 b) When processing the 'forall', don't gensym
218
219 The relevant places are signposted with references to this Note
220
221 Note [Binders and occurrences]
222 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
223 When we desugar [d| data T = MkT |]
224 we want to get
225 Data "T" [] [Con "MkT" []] []
226 and *not*
227 Data "Foo:T" [] [Con "Foo:MkT" []] []
228 That is, the new data decl should fit into whatever new module it is
229 asked to fit in. We do *not* clone, though; no need for this:
230 Data "T79" ....
231
232 But if we see this:
233 data T = MkT
234 foo = reifyDecl T
235
236 then we must desugar to
237 foo = Data "Foo:T" [] [Con "Foo:MkT" []] []
238
239 So in repTopDs we bring the binders into scope with mkGenSyms and addBinds.
240 And we use lookupOcc, rather than lookupBinder
241 in repTyClD and repC.
242
243 Note [Don't quantify implicit type variables in quotes]
244 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
245 If you're not careful, it's suprisingly easy to take this quoted declaration:
246
247 [d| idProxy :: forall proxy (b :: k). proxy b -> proxy b
248 idProxy x = x
249 |]
250
251 and have Template Haskell turn it into this:
252
253 idProxy :: forall k proxy (b :: k). proxy b -> proxy b
254 idProxy x = x
255
256 Notice that we explicitly quantified the variable `k`! This is quite bad, as the
257 latter declaration requires -XTypeInType, while the former does not. Not to
258 mention that the latter declaration isn't even what the user wrote in the
259 first place.
260
261 Usually, the culprit behind these bugs is taking implicitly quantified type
262 variables (often from the hsib_vars field of HsImplicitBinders) and putting
263 them into a `ForallT` or `ForallC`. Doing so caused #13018 and #13123.
264 -}
265
266 -- represent associated family instances
267 --
268 repTyClD :: LTyClDecl GhcRn -> DsM (Maybe (SrcSpan, Core TH.DecQ))
269
270 repTyClD (L loc (FamDecl { tcdFam = fam })) = liftM Just $ repFamilyDecl (L loc fam)
271
272 repTyClD (L loc (SynDecl { tcdLName = tc, tcdTyVars = tvs, tcdRhs = rhs }))
273 = do { tc1 <- lookupLOcc tc -- See note [Binders and occurrences]
274 ; dec <- addTyClTyVarBinds tvs $ \bndrs ->
275 repSynDecl tc1 bndrs rhs
276 ; return (Just (loc, dec)) }
277
278 repTyClD (L loc (DataDecl { tcdLName = tc, tcdTyVars = tvs, tcdDataDefn = defn }))
279 = do { tc1 <- lookupLOcc tc -- See note [Binders and occurrences]
280 ; dec <- addTyClTyVarBinds tvs $ \bndrs ->
281 repDataDefn tc1 bndrs Nothing defn
282 ; return (Just (loc, dec)) }
283
284 repTyClD (L loc (ClassDecl { tcdCtxt = cxt, tcdLName = cls,
285 tcdTyVars = tvs, tcdFDs = fds,
286 tcdSigs = sigs, tcdMeths = meth_binds,
287 tcdATs = ats, tcdATDefs = atds }))
288 = do { cls1 <- lookupLOcc cls -- See note [Binders and occurrences]
289 ; dec <- addTyVarBinds tvs $ \bndrs ->
290 do { cxt1 <- repLContext cxt
291 ; sigs1 <- rep_sigs sigs
292 ; binds1 <- rep_binds meth_binds
293 ; fds1 <- repLFunDeps fds
294 ; ats1 <- repFamilyDecls ats
295 ; atds1 <- repAssocTyFamDefaults atds
296 ; decls1 <- coreList decQTyConName (ats1 ++ atds1 ++ sigs1 ++ binds1)
297 ; repClass cxt1 cls1 bndrs fds1 decls1
298 }
299 ; return $ Just (loc, dec)
300 }
301
302 -------------------------
303 repRoleD :: LRoleAnnotDecl GhcRn -> DsM (SrcSpan, Core TH.DecQ)
304 repRoleD (L loc (RoleAnnotDecl tycon roles))
305 = do { tycon1 <- lookupLOcc tycon
306 ; roles1 <- mapM repRole roles
307 ; roles2 <- coreList roleTyConName roles1
308 ; dec <- repRoleAnnotD tycon1 roles2
309 ; return (loc, dec) }
310
311 -------------------------
312 repDataDefn :: Core TH.Name -> Core [TH.TyVarBndrQ]
313 -> Maybe (Core [TH.TypeQ])
314 -> HsDataDefn GhcRn
315 -> DsM (Core TH.DecQ)
316 repDataDefn tc bndrs opt_tys
317 (HsDataDefn { dd_ND = new_or_data, dd_ctxt = cxt, dd_kindSig = ksig
318 , dd_cons = cons, dd_derivs = mb_derivs })
319 = do { cxt1 <- repLContext cxt
320 ; derivs1 <- repDerivs mb_derivs
321 ; case (new_or_data, cons) of
322 (NewType, [con]) -> do { con' <- repC con
323 ; ksig' <- repMaybeLTy ksig
324 ; repNewtype cxt1 tc bndrs opt_tys ksig' con'
325 derivs1 }
326 (NewType, _) -> failWithDs (text "Multiple constructors for newtype:"
327 <+> pprQuotedList
328 (getConNames $ unLoc $ head cons))
329 (DataType, _) -> do { ksig' <- repMaybeLTy ksig
330 ; consL <- mapM repC cons
331 ; cons1 <- coreList conQTyConName consL
332 ; repData cxt1 tc bndrs opt_tys ksig' cons1
333 derivs1 }
334 }
335
336 repSynDecl :: Core TH.Name -> Core [TH.TyVarBndrQ]
337 -> LHsType GhcRn
338 -> DsM (Core TH.DecQ)
339 repSynDecl tc bndrs ty
340 = do { ty1 <- repLTy ty
341 ; repTySyn tc bndrs ty1 }
342
343 repFamilyDecl :: LFamilyDecl GhcRn -> DsM (SrcSpan, Core TH.DecQ)
344 repFamilyDecl decl@(L loc (FamilyDecl { fdInfo = info,
345 fdLName = tc,
346 fdTyVars = tvs,
347 fdResultSig = L _ resultSig,
348 fdInjectivityAnn = injectivity }))
349 = do { tc1 <- lookupLOcc tc -- See note [Binders and occurrences]
350 ; let mkHsQTvs :: [LHsTyVarBndr GhcRn] -> LHsQTyVars GhcRn
351 mkHsQTvs tvs = HsQTvs { hsq_implicit = [], hsq_explicit = tvs
352 , hsq_dependent = emptyNameSet }
353 resTyVar = case resultSig of
354 TyVarSig bndr -> mkHsQTvs [bndr]
355 _ -> mkHsQTvs []
356 ; dec <- addTyClTyVarBinds tvs $ \bndrs ->
357 addTyClTyVarBinds resTyVar $ \_ ->
358 case info of
359 ClosedTypeFamily Nothing ->
360 notHandled "abstract closed type family" (ppr decl)
361 ClosedTypeFamily (Just eqns) ->
362 do { eqns1 <- mapM (repTyFamEqn . unLoc) eqns
363 ; eqns2 <- coreList tySynEqnQTyConName eqns1
364 ; result <- repFamilyResultSig resultSig
365 ; inj <- repInjectivityAnn injectivity
366 ; repClosedFamilyD tc1 bndrs result inj eqns2 }
367 OpenTypeFamily ->
368 do { result <- repFamilyResultSig resultSig
369 ; inj <- repInjectivityAnn injectivity
370 ; repOpenFamilyD tc1 bndrs result inj }
371 DataFamily ->
372 do { kind <- repFamilyResultSigToMaybeKind resultSig
373 ; repDataFamilyD tc1 bndrs kind }
374 ; return (loc, dec)
375 }
376
377 -- | Represent result signature of a type family
378 repFamilyResultSig :: FamilyResultSig GhcRn -> DsM (Core TH.FamilyResultSigQ)
379 repFamilyResultSig NoSig = repNoSig
380 repFamilyResultSig (KindSig ki) = do { ki' <- repLTy ki
381 ; repKindSig ki' }
382 repFamilyResultSig (TyVarSig bndr) = do { bndr' <- repTyVarBndr bndr
383 ; repTyVarSig bndr' }
384
385 -- | Represent result signature using a Maybe Kind. Used with data families,
386 -- where the result signature can be either missing or a kind but never a named
387 -- result variable.
388 repFamilyResultSigToMaybeKind :: FamilyResultSig GhcRn
389 -> DsM (Core (Maybe TH.KindQ))
390 repFamilyResultSigToMaybeKind NoSig =
391 do { coreNothing kindQTyConName }
392 repFamilyResultSigToMaybeKind (KindSig ki) =
393 do { ki' <- repLTy ki
394 ; coreJust kindQTyConName ki' }
395 repFamilyResultSigToMaybeKind _ = panic "repFamilyResultSigToMaybeKind"
396
397 -- | Represent injectivity annotation of a type family
398 repInjectivityAnn :: Maybe (LInjectivityAnn GhcRn)
399 -> DsM (Core (Maybe TH.InjectivityAnn))
400 repInjectivityAnn Nothing =
401 do { coreNothing injAnnTyConName }
402 repInjectivityAnn (Just (L _ (InjectivityAnn lhs rhs))) =
403 do { lhs' <- lookupBinder (unLoc lhs)
404 ; rhs1 <- mapM (lookupBinder . unLoc) rhs
405 ; rhs2 <- coreList nameTyConName rhs1
406 ; injAnn <- rep2 injectivityAnnName [unC lhs', unC rhs2]
407 ; coreJust injAnnTyConName injAnn }
408
409 repFamilyDecls :: [LFamilyDecl GhcRn] -> DsM [Core TH.DecQ]
410 repFamilyDecls fds = liftM de_loc (mapM repFamilyDecl fds)
411
412 repAssocTyFamDefaults :: [LTyFamDefltEqn GhcRn] -> DsM [Core TH.DecQ]
413 repAssocTyFamDefaults = mapM rep_deflt
414 where
415 -- very like repTyFamEqn, but different in the details
416 rep_deflt :: LTyFamDefltEqn GhcRn -> DsM (Core TH.DecQ)
417 rep_deflt (L _ (FamEqn { feqn_tycon = tc
418 , feqn_pats = bndrs
419 , feqn_rhs = rhs }))
420 = addTyClTyVarBinds bndrs $ \ _ ->
421 do { tc1 <- lookupLOcc tc
422 ; tys1 <- repLTys (hsLTyVarBndrsToTypes bndrs)
423 ; tys2 <- coreList typeQTyConName tys1
424 ; rhs1 <- repLTy rhs
425 ; eqn1 <- repTySynEqn tys2 rhs1
426 ; repTySynInst tc1 eqn1 }
427
428 -------------------------
429 -- represent fundeps
430 --
431 repLFunDeps :: [Located (FunDep (Located Name))] -> DsM (Core [TH.FunDep])
432 repLFunDeps fds = repList funDepTyConName repLFunDep fds
433
434 repLFunDep :: Located (FunDep (Located Name)) -> DsM (Core TH.FunDep)
435 repLFunDep (L _ (xs, ys))
436 = do xs' <- repList nameTyConName (lookupBinder . unLoc) xs
437 ys' <- repList nameTyConName (lookupBinder . unLoc) ys
438 repFunDep xs' ys'
439
440 -- Represent instance declarations
441 --
442 repInstD :: LInstDecl GhcRn -> DsM (SrcSpan, Core TH.DecQ)
443 repInstD (L loc (TyFamInstD { tfid_inst = fi_decl }))
444 = do { dec <- repTyFamInstD fi_decl
445 ; return (loc, dec) }
446 repInstD (L loc (DataFamInstD { dfid_inst = fi_decl }))
447 = do { dec <- repDataFamInstD fi_decl
448 ; return (loc, dec) }
449 repInstD (L loc (ClsInstD { cid_inst = cls_decl }))
450 = do { dec <- repClsInstD cls_decl
451 ; return (loc, dec) }
452
453 repClsInstD :: ClsInstDecl GhcRn -> DsM (Core TH.DecQ)
454 repClsInstD (ClsInstDecl { cid_poly_ty = ty, cid_binds = binds
455 , cid_sigs = prags, cid_tyfam_insts = ats
456 , cid_datafam_insts = adts
457 , cid_overlap_mode = overlap
458 })
459 = addSimpleTyVarBinds tvs $
460 -- We must bring the type variables into scope, so their
461 -- occurrences don't fail, even though the binders don't
462 -- appear in the resulting data structure
463 --
464 -- But we do NOT bring the binders of 'binds' into scope
465 -- because they are properly regarded as occurrences
466 -- For example, the method names should be bound to
467 -- the selector Ids, not to fresh names (Trac #5410)
468 --
469 do { cxt1 <- repLContext cxt
470 ; inst_ty1 <- repLTy inst_ty
471 ; binds1 <- rep_binds binds
472 ; prags1 <- rep_sigs prags
473 ; ats1 <- mapM (repTyFamInstD . unLoc) ats
474 ; adts1 <- mapM (repDataFamInstD . unLoc) adts
475 ; decls <- coreList decQTyConName (ats1 ++ adts1 ++ binds1 ++ prags1)
476 ; rOver <- repOverlap (fmap unLoc overlap)
477 ; repInst rOver cxt1 inst_ty1 decls }
478 where
479 (tvs, cxt, inst_ty) = splitLHsInstDeclTy ty
480
481 repStandaloneDerivD :: LDerivDecl GhcRn -> DsM (SrcSpan, Core TH.DecQ)
482 repStandaloneDerivD (L loc (DerivDecl { deriv_strategy = strat
483 , deriv_type = ty }))
484 = do { dec <- addSimpleTyVarBinds tvs $
485 do { cxt' <- repLContext cxt
486 ; strat' <- repDerivStrategy strat
487 ; inst_ty' <- repLTy inst_ty
488 ; repDeriv strat' cxt' inst_ty' }
489 ; return (loc, dec) }
490 where
491 (tvs, cxt, inst_ty) = splitLHsInstDeclTy ty
492
493 repTyFamInstD :: TyFamInstDecl GhcRn -> DsM (Core TH.DecQ)
494 repTyFamInstD decl@(TyFamInstDecl { tfid_eqn = eqn })
495 = do { let tc_name = tyFamInstDeclLName decl
496 ; tc <- lookupLOcc tc_name -- See note [Binders and occurrences]
497 ; eqn1 <- repTyFamEqn eqn
498 ; repTySynInst tc eqn1 }
499
500 repTyFamEqn :: TyFamInstEqn GhcRn -> DsM (Core TH.TySynEqnQ)
501 repTyFamEqn (HsIB { hsib_vars = var_names
502 , hsib_body = FamEqn { feqn_pats = tys
503 , feqn_rhs = rhs }})
504 = do { let hs_tvs = HsQTvs { hsq_implicit = var_names
505 , hsq_explicit = []
506 , hsq_dependent = emptyNameSet } -- Yuk
507 ; addTyClTyVarBinds hs_tvs $ \ _ ->
508 do { tys1 <- repLTys tys
509 ; tys2 <- coreList typeQTyConName tys1
510 ; rhs1 <- repLTy rhs
511 ; repTySynEqn tys2 rhs1 } }
512
513 repDataFamInstD :: DataFamInstDecl GhcRn -> DsM (Core TH.DecQ)
514 repDataFamInstD (DataFamInstDecl { dfid_eqn =
515 (HsIB { hsib_vars = var_names
516 , hsib_body = FamEqn { feqn_tycon = tc_name
517 , feqn_pats = tys
518 , feqn_rhs = defn }})})
519 = do { tc <- lookupLOcc tc_name -- See note [Binders and occurrences]
520 ; let hs_tvs = HsQTvs { hsq_implicit = var_names
521 , hsq_explicit = []
522 , hsq_dependent = emptyNameSet } -- Yuk
523 ; addTyClTyVarBinds hs_tvs $ \ bndrs ->
524 do { tys1 <- repList typeQTyConName repLTy tys
525 ; repDataDefn tc bndrs (Just tys1) defn } }
526
527 repForD :: Located (ForeignDecl GhcRn) -> DsM (SrcSpan, Core TH.DecQ)
528 repForD (L loc (ForeignImport { fd_name = name, fd_sig_ty = typ
529 , fd_fi = CImport (L _ cc) (L _ s) mch cis _ }))
530 = do MkC name' <- lookupLOcc name
531 MkC typ' <- repHsSigType typ
532 MkC cc' <- repCCallConv cc
533 MkC s' <- repSafety s
534 cis' <- conv_cimportspec cis
535 MkC str <- coreStringLit (static ++ chStr ++ cis')
536 dec <- rep2 forImpDName [cc', s', str, name', typ']
537 return (loc, dec)
538 where
539 conv_cimportspec (CLabel cls) = notHandled "Foreign label" (doubleQuotes (ppr cls))
540 conv_cimportspec (CFunction DynamicTarget) = return "dynamic"
541 conv_cimportspec (CFunction (StaticTarget _ fs _ True))
542 = return (unpackFS fs)
543 conv_cimportspec (CFunction (StaticTarget _ _ _ False))
544 = panic "conv_cimportspec: values not supported yet"
545 conv_cimportspec CWrapper = return "wrapper"
546 -- these calling conventions do not support headers and the static keyword
547 raw_cconv = cc == PrimCallConv || cc == JavaScriptCallConv
548 static = case cis of
549 CFunction (StaticTarget _ _ _ _) | not raw_cconv -> "static "
550 _ -> ""
551 chStr = case mch of
552 Just (Header _ h) | not raw_cconv -> unpackFS h ++ " "
553 _ -> ""
554 repForD decl = notHandled "Foreign declaration" (ppr decl)
555
556 repCCallConv :: CCallConv -> DsM (Core TH.Callconv)
557 repCCallConv CCallConv = rep2 cCallName []
558 repCCallConv StdCallConv = rep2 stdCallName []
559 repCCallConv CApiConv = rep2 cApiCallName []
560 repCCallConv PrimCallConv = rep2 primCallName []
561 repCCallConv JavaScriptCallConv = rep2 javaScriptCallName []
562
563 repSafety :: Safety -> DsM (Core TH.Safety)
564 repSafety PlayRisky = rep2 unsafeName []
565 repSafety PlayInterruptible = rep2 interruptibleName []
566 repSafety PlaySafe = rep2 safeName []
567
568 repFixD :: LFixitySig GhcRn -> DsM [(SrcSpan, Core TH.DecQ)]
569 repFixD (L loc (FixitySig names (Fixity _ prec dir)))
570 = do { MkC prec' <- coreIntLit prec
571 ; let rep_fn = case dir of
572 InfixL -> infixLDName
573 InfixR -> infixRDName
574 InfixN -> infixNDName
575 ; let do_one name
576 = do { MkC name' <- lookupLOcc name
577 ; dec <- rep2 rep_fn [prec', name']
578 ; return (loc,dec) }
579 ; mapM do_one names }
580
581 repRuleD :: LRuleDecl GhcRn -> DsM (SrcSpan, Core TH.DecQ)
582 repRuleD (L loc (HsRule n act bndrs lhs _ rhs _))
583 = do { let bndr_names = concatMap ruleBndrNames bndrs
584 ; ss <- mkGenSyms bndr_names
585 ; rule1 <- addBinds ss $
586 do { bndrs' <- repList ruleBndrQTyConName repRuleBndr bndrs
587 ; n' <- coreStringLit $ unpackFS $ snd $ unLoc n
588 ; act' <- repPhases act
589 ; lhs' <- repLE lhs
590 ; rhs' <- repLE rhs
591 ; repPragRule n' bndrs' lhs' rhs' act' }
592 ; rule2 <- wrapGenSyms ss rule1
593 ; return (loc, rule2) }
594
595 ruleBndrNames :: LRuleBndr GhcRn -> [Name]
596 ruleBndrNames (L _ (RuleBndr n)) = [unLoc n]
597 ruleBndrNames (L _ (RuleBndrSig n sig))
598 | HsWC { hswc_body = HsIB { hsib_vars = vars }} <- sig
599 = unLoc n : vars
600
601 repRuleBndr :: LRuleBndr GhcRn -> DsM (Core TH.RuleBndrQ)
602 repRuleBndr (L _ (RuleBndr n))
603 = do { MkC n' <- lookupLBinder n
604 ; rep2 ruleVarName [n'] }
605 repRuleBndr (L _ (RuleBndrSig n sig))
606 = do { MkC n' <- lookupLBinder n
607 ; MkC ty' <- repLTy (hsSigWcType sig)
608 ; rep2 typedRuleVarName [n', ty'] }
609
610 repAnnD :: LAnnDecl GhcRn -> DsM (SrcSpan, Core TH.DecQ)
611 repAnnD (L loc (HsAnnotation _ ann_prov (L _ exp)))
612 = do { target <- repAnnProv ann_prov
613 ; exp' <- repE exp
614 ; dec <- repPragAnn target exp'
615 ; return (loc, dec) }
616
617 repAnnProv :: AnnProvenance Name -> DsM (Core TH.AnnTarget)
618 repAnnProv (ValueAnnProvenance (L _ n))
619 = do { MkC n' <- globalVar n -- ANNs are allowed only at top-level
620 ; rep2 valueAnnotationName [ n' ] }
621 repAnnProv (TypeAnnProvenance (L _ n))
622 = do { MkC n' <- globalVar n
623 ; rep2 typeAnnotationName [ n' ] }
624 repAnnProv ModuleAnnProvenance
625 = rep2 moduleAnnotationName []
626
627 -------------------------------------------------------
628 -- Constructors
629 -------------------------------------------------------
630
631 repC :: LConDecl GhcRn -> DsM (Core TH.ConQ)
632 repC (L _ (ConDeclH98 { con_name = con
633 , con_qvars = Nothing, con_cxt = Nothing
634 , con_details = details }))
635 = repDataCon con details
636
637 repC (L _ (ConDeclH98 { con_name = con
638 , con_qvars = mcon_tvs, con_cxt = mcxt
639 , con_details = details }))
640 = do { let con_tvs = fromMaybe emptyLHsQTvs mcon_tvs
641 ctxt = unLoc $ fromMaybe (noLoc []) mcxt
642 ; addTyVarBinds con_tvs $ \ ex_bndrs ->
643 do { c' <- repDataCon con details
644 ; ctxt' <- repContext ctxt
645 ; if isEmptyLHsQTvs con_tvs && null ctxt
646 then return c'
647 else rep2 forallCName ([unC ex_bndrs, unC ctxt', unC c'])
648 }
649 }
650
651 repC (L _ (ConDeclGADT { con_names = cons
652 , con_type = res_ty@(HsIB { hsib_vars = imp_tvs })}))
653 | (details, res_ty', L _ [] , []) <- gadtDetails
654 , [] <- imp_tvs
655 -- no implicit or explicit variables, no context = no need for a forall
656 = do { let doc = text "In the constructor for " <+> ppr (head cons)
657 ; (hs_details, gadt_res_ty) <-
658 updateGadtResult failWithDs doc details res_ty'
659 ; repGadtDataCons cons hs_details gadt_res_ty }
660
661 | (details,res_ty',ctxt, exp_tvs) <- gadtDetails
662 = do { let doc = text "In the constructor for " <+> ppr (head cons)
663 con_tvs = HsQTvs { hsq_implicit = imp_tvs
664 , hsq_explicit = exp_tvs
665 , hsq_dependent = emptyNameSet }
666 -- NB: Don't put imp_tvs into the hsq_explicit field above
667 -- See Note [Don't quantify implicit type variables in quotes]
668 ; addTyVarBinds con_tvs $ \ ex_bndrs -> do
669 { (hs_details, gadt_res_ty) <-
670 updateGadtResult failWithDs doc details res_ty'
671 ; c' <- repGadtDataCons cons hs_details gadt_res_ty
672 ; ctxt' <- repContext (unLoc ctxt)
673 ; if null exp_tvs && null (unLoc ctxt)
674 then return c'
675 else rep2 forallCName ([unC ex_bndrs, unC ctxt', unC c']) } }
676 where
677 gadtDetails = gadtDeclDetails res_ty
678
679 repSrcUnpackedness :: SrcUnpackedness -> DsM (Core TH.SourceUnpackednessQ)
680 repSrcUnpackedness SrcUnpack = rep2 sourceUnpackName []
681 repSrcUnpackedness SrcNoUnpack = rep2 sourceNoUnpackName []
682 repSrcUnpackedness NoSrcUnpack = rep2 noSourceUnpackednessName []
683
684 repSrcStrictness :: SrcStrictness -> DsM (Core TH.SourceStrictnessQ)
685 repSrcStrictness SrcLazy = rep2 sourceLazyName []
686 repSrcStrictness SrcStrict = rep2 sourceStrictName []
687 repSrcStrictness NoSrcStrict = rep2 noSourceStrictnessName []
688
689 repBangTy :: LBangType GhcRn -> DsM (Core (TH.BangTypeQ))
690 repBangTy ty = do
691 MkC u <- repSrcUnpackedness su'
692 MkC s <- repSrcStrictness ss'
693 MkC b <- rep2 bangName [u, s]
694 MkC t <- repLTy ty'
695 rep2 bangTypeName [b, t]
696 where
697 (su', ss', ty') = case ty of
698 L _ (HsBangTy (HsSrcBang _ su ss) ty) -> (su, ss, ty)
699 _ -> (NoSrcUnpack, NoSrcStrict, ty)
700
701 -------------------------------------------------------
702 -- Deriving clauses
703 -------------------------------------------------------
704
705 repDerivs :: HsDeriving GhcRn -> DsM (Core [TH.DerivClauseQ])
706 repDerivs (L _ clauses) = repList derivClauseQTyConName repDerivClause clauses
707
708 repDerivClause :: LHsDerivingClause GhcRn
709 -> DsM (Core TH.DerivClauseQ)
710 repDerivClause (L _ (HsDerivingClause { deriv_clause_strategy = dcs
711 , deriv_clause_tys = L _ dct }))
712 = do MkC dcs' <- repDerivStrategy dcs
713 MkC dct' <- repList typeQTyConName (rep_deriv_ty . hsSigType) dct
714 rep2 derivClauseName [dcs',dct']
715 where
716 rep_deriv_ty :: LHsType GhcRn -> DsM (Core TH.TypeQ)
717 rep_deriv_ty (L _ ty) = repTy ty
718
719 -------------------------------------------------------
720 -- Signatures in a class decl, or a group of bindings
721 -------------------------------------------------------
722
723 rep_sigs :: [LSig GhcRn] -> DsM [Core TH.DecQ]
724 rep_sigs sigs = do locs_cores <- rep_sigs' sigs
725 return $ de_loc $ sort_by_loc locs_cores
726
727 rep_sigs' :: [LSig GhcRn] -> DsM [(SrcSpan, Core TH.DecQ)]
728 -- We silently ignore ones we don't recognise
729 rep_sigs' = concatMapM rep_sig
730
731 rep_sig :: LSig GhcRn -> DsM [(SrcSpan, Core TH.DecQ)]
732 rep_sig (L loc (TypeSig nms ty)) = mapM (rep_wc_ty_sig sigDName loc ty) nms
733 rep_sig (L loc (PatSynSig nms ty)) = mapM (rep_patsyn_ty_sig loc ty) nms
734 rep_sig (L loc (ClassOpSig is_deflt nms ty))
735 | is_deflt = mapM (rep_ty_sig defaultSigDName loc ty) nms
736 | otherwise = mapM (rep_ty_sig sigDName loc ty) nms
737 rep_sig d@(L _ (IdSig {})) = pprPanic "rep_sig IdSig" (ppr d)
738 rep_sig (L _ (FixSig {})) = return [] -- fixity sigs at top level
739 rep_sig (L loc (InlineSig nm ispec)) = rep_inline nm ispec loc
740 rep_sig (L loc (SpecSig nm tys ispec))
741 = concatMapM (\t -> rep_specialise nm t ispec loc) tys
742 rep_sig (L loc (SpecInstSig _ ty)) = rep_specialiseInst ty loc
743 rep_sig (L _ (MinimalSig {})) = notHandled "MINIMAL pragmas" empty
744 rep_sig (L _ (SCCFunSig {})) = notHandled "SCC pragmas" empty
745 rep_sig (L loc (CompleteMatchSig _st cls mty)) = rep_complete_sig cls mty loc
746
747
748 rep_ty_sig :: Name -> SrcSpan -> LHsSigType GhcRn -> Located Name
749 -> DsM (SrcSpan, Core TH.DecQ)
750 rep_ty_sig mk_sig loc sig_ty nm
751 = do { nm1 <- lookupLOcc nm
752 ; ty1 <- repHsSigType sig_ty
753 ; sig <- repProto mk_sig nm1 ty1
754 ; return (loc, sig) }
755
756 rep_patsyn_ty_sig :: SrcSpan -> LHsSigType GhcRn -> Located Name
757 -> DsM (SrcSpan, Core TH.DecQ)
758 -- represents a pattern synonym type signature;
759 -- see Note [Pattern synonym type signatures and Template Haskell] in Convert
760 rep_patsyn_ty_sig loc sig_ty nm
761 = do { nm1 <- lookupLOcc nm
762 ; ty1 <- repHsPatSynSigType sig_ty
763 ; sig <- repProto patSynSigDName nm1 ty1
764 ; return (loc, sig) }
765
766 rep_wc_ty_sig :: Name -> SrcSpan -> LHsSigWcType GhcRn -> Located Name
767 -> DsM (SrcSpan, Core TH.DecQ)
768 -- We must special-case the top-level explicit for-all of a TypeSig
769 -- See Note [Scoped type variables in bindings]
770 rep_wc_ty_sig mk_sig loc sig_ty nm
771 | HsIB { hsib_body = hs_ty } <- hswc_body sig_ty
772 , (explicit_tvs, ctxt, ty) <- splitLHsSigmaTy hs_ty
773 = do { nm1 <- lookupLOcc nm
774 ; let rep_in_scope_tv tv = do { name <- lookupBinder (hsLTyVarName tv)
775 ; repTyVarBndrWithKind tv name }
776 ; th_explicit_tvs <- repList tyVarBndrQTyConName rep_in_scope_tv
777 explicit_tvs
778 -- NB: Don't pass any implicit type variables to repList above
779 -- See Note [Don't quantify implicit type variables in quotes]
780
781 ; th_ctxt <- repLContext ctxt
782 ; th_ty <- repLTy ty
783 ; ty1 <- if null explicit_tvs && null (unLoc ctxt)
784 then return th_ty
785 else repTForall th_explicit_tvs th_ctxt th_ty
786 ; sig <- repProto mk_sig nm1 ty1
787 ; return (loc, sig) }
788
789 rep_inline :: Located Name
790 -> InlinePragma -- Never defaultInlinePragma
791 -> SrcSpan
792 -> DsM [(SrcSpan, Core TH.DecQ)]
793 rep_inline nm ispec loc
794 = do { nm1 <- lookupLOcc nm
795 ; inline <- repInline $ inl_inline ispec
796 ; rm <- repRuleMatch $ inl_rule ispec
797 ; phases <- repPhases $ inl_act ispec
798 ; pragma <- repPragInl nm1 inline rm phases
799 ; return [(loc, pragma)]
800 }
801
802 rep_specialise :: Located Name -> LHsSigType GhcRn -> InlinePragma
803 -> SrcSpan
804 -> DsM [(SrcSpan, Core TH.DecQ)]
805 rep_specialise nm ty ispec loc
806 = do { nm1 <- lookupLOcc nm
807 ; ty1 <- repHsSigType ty
808 ; phases <- repPhases $ inl_act ispec
809 ; let inline = inl_inline ispec
810 ; pragma <- if noUserInlineSpec inline
811 then -- SPECIALISE
812 repPragSpec nm1 ty1 phases
813 else -- SPECIALISE INLINE
814 do { inline1 <- repInline inline
815 ; repPragSpecInl nm1 ty1 inline1 phases }
816 ; return [(loc, pragma)]
817 }
818
819 rep_specialiseInst :: LHsSigType GhcRn -> SrcSpan
820 -> DsM [(SrcSpan, Core TH.DecQ)]
821 rep_specialiseInst ty loc
822 = do { ty1 <- repHsSigType ty
823 ; pragma <- repPragSpecInst ty1
824 ; return [(loc, pragma)] }
825
826 repInline :: InlineSpec -> DsM (Core TH.Inline)
827 repInline NoInline = dataCon noInlineDataConName
828 repInline Inline = dataCon inlineDataConName
829 repInline Inlinable = dataCon inlinableDataConName
830 repInline spec = notHandled "repInline" (ppr spec)
831
832 repRuleMatch :: RuleMatchInfo -> DsM (Core TH.RuleMatch)
833 repRuleMatch ConLike = dataCon conLikeDataConName
834 repRuleMatch FunLike = dataCon funLikeDataConName
835
836 repPhases :: Activation -> DsM (Core TH.Phases)
837 repPhases (ActiveBefore _ i) = do { MkC arg <- coreIntLit i
838 ; dataCon' beforePhaseDataConName [arg] }
839 repPhases (ActiveAfter _ i) = do { MkC arg <- coreIntLit i
840 ; dataCon' fromPhaseDataConName [arg] }
841 repPhases _ = dataCon allPhasesDataConName
842
843 rep_complete_sig :: Located [Located Name]
844 -> Maybe (Located Name)
845 -> SrcSpan
846 -> DsM [(SrcSpan, Core TH.DecQ)]
847 rep_complete_sig (L _ cls) mty loc
848 = do { mty' <- rep_maybe_name mty
849 ; cls' <- repList nameTyConName lookupLOcc cls
850 ; sig <- repPragComplete cls' mty'
851 ; return [(loc, sig)] }
852 where
853 rep_maybe_name Nothing = coreNothing nameTyConName
854 rep_maybe_name (Just n) = do
855 cn <- lookupLOcc n
856 coreJust nameTyConName cn
857
858 -------------------------------------------------------
859 -- Types
860 -------------------------------------------------------
861
862 addSimpleTyVarBinds :: [Name] -- the binders to be added
863 -> DsM (Core (TH.Q a)) -- action in the ext env
864 -> DsM (Core (TH.Q a))
865 addSimpleTyVarBinds names thing_inside
866 = do { fresh_names <- mkGenSyms names
867 ; term <- addBinds fresh_names thing_inside
868 ; wrapGenSyms fresh_names term }
869
870 addTyVarBinds :: LHsQTyVars GhcRn -- the binders to be added
871 -> (Core [TH.TyVarBndrQ] -> DsM (Core (TH.Q a))) -- action in the ext env
872 -> DsM (Core (TH.Q a))
873 -- gensym a list of type variables and enter them into the meta environment;
874 -- the computations passed as the second argument is executed in that extended
875 -- meta environment and gets the *new* names on Core-level as an argument
876
877 addTyVarBinds (HsQTvs { hsq_implicit = imp_tvs, hsq_explicit = exp_tvs }) m
878 = do { fresh_imp_names <- mkGenSyms imp_tvs
879 ; fresh_exp_names <- mkGenSyms (map hsLTyVarName exp_tvs)
880 ; let fresh_names = fresh_imp_names ++ fresh_exp_names
881 ; term <- addBinds fresh_names $
882 do { kbs <- repList tyVarBndrQTyConName mk_tv_bndr
883 (exp_tvs `zip` fresh_exp_names)
884 ; m kbs }
885 ; wrapGenSyms fresh_names term }
886 where
887 mk_tv_bndr (tv, (_,v)) = repTyVarBndrWithKind tv (coreVar v)
888
889 addTyClTyVarBinds :: LHsQTyVars GhcRn
890 -> (Core [TH.TyVarBndrQ] -> DsM (Core (TH.Q a)))
891 -> DsM (Core (TH.Q a))
892
893 -- Used for data/newtype declarations, and family instances,
894 -- so that the nested type variables work right
895 -- instance C (T a) where
896 -- type W (T a) = blah
897 -- The 'a' in the type instance is the one bound by the instance decl
898 addTyClTyVarBinds tvs m
899 = do { let tv_names = hsAllLTyVarNames tvs
900 ; env <- dsGetMetaEnv
901 ; freshNames <- mkGenSyms (filterOut (`elemNameEnv` env) tv_names)
902 -- Make fresh names for the ones that are not already in scope
903 -- This makes things work for family declarations
904
905 ; term <- addBinds freshNames $
906 do { kbs <- repList tyVarBndrQTyConName mk_tv_bndr
907 (hsQTvExplicit tvs)
908 ; m kbs }
909
910 ; wrapGenSyms freshNames term }
911 where
912 mk_tv_bndr :: LHsTyVarBndr GhcRn -> DsM (Core TH.TyVarBndrQ)
913 mk_tv_bndr tv = do { v <- lookupBinder (hsLTyVarName tv)
914 ; repTyVarBndrWithKind tv v }
915
916 -- Produce kinded binder constructors from the Haskell tyvar binders
917 --
918 repTyVarBndrWithKind :: LHsTyVarBndr GhcRn
919 -> Core TH.Name -> DsM (Core TH.TyVarBndrQ)
920 repTyVarBndrWithKind (L _ (UserTyVar _)) nm
921 = repPlainTV nm
922 repTyVarBndrWithKind (L _ (KindedTyVar _ ki)) nm
923 = repLTy ki >>= repKindedTV nm
924
925 -- | Represent a type variable binder
926 repTyVarBndr :: LHsTyVarBndr GhcRn -> DsM (Core TH.TyVarBndrQ)
927 repTyVarBndr (L _ (UserTyVar (L _ nm)) )= do { nm' <- lookupBinder nm
928 ; repPlainTV nm' }
929 repTyVarBndr (L _ (KindedTyVar (L _ nm) ki)) = do { nm' <- lookupBinder nm
930 ; ki' <- repLTy ki
931 ; repKindedTV nm' ki' }
932
933 -- represent a type context
934 --
935 repLContext :: LHsContext GhcRn -> DsM (Core TH.CxtQ)
936 repLContext (L _ ctxt) = repContext ctxt
937
938 repContext :: HsContext GhcRn -> DsM (Core TH.CxtQ)
939 repContext ctxt = do preds <- repList typeQTyConName repLTy ctxt
940 repCtxt preds
941
942 repHsSigType :: LHsSigType GhcRn -> DsM (Core TH.TypeQ)
943 repHsSigType (HsIB { hsib_vars = implicit_tvs
944 , hsib_body = body })
945 | (explicit_tvs, ctxt, ty) <- splitLHsSigmaTy body
946 = addTyVarBinds (HsQTvs { hsq_implicit = implicit_tvs
947 , hsq_explicit = explicit_tvs
948 , hsq_dependent = emptyNameSet })
949 -- NB: Don't pass implicit_tvs to the hsq_explicit field above
950 -- See Note [Don't quantify implicit type variables in quotes]
951 $ \ th_explicit_tvs ->
952 do { th_ctxt <- repLContext ctxt
953 ; th_ty <- repLTy ty
954 ; if null explicit_tvs && null (unLoc ctxt)
955 then return th_ty
956 else repTForall th_explicit_tvs th_ctxt th_ty }
957
958 repHsPatSynSigType :: LHsSigType GhcRn -> DsM (Core TH.TypeQ)
959 repHsPatSynSigType (HsIB { hsib_vars = implicit_tvs
960 , hsib_body = body })
961 = addTyVarBinds (newTvs implicit_tvs univs) $ \th_univs ->
962 addTyVarBinds (newTvs [] exis) $ \th_exis ->
963 do { th_reqs <- repLContext reqs
964 ; th_provs <- repLContext provs
965 ; th_ty <- repLTy ty
966 ; repTForall th_univs th_reqs =<< (repTForall th_exis th_provs th_ty) }
967 where
968 newTvs impl_tvs expl_tvs = HsQTvs
969 { hsq_implicit = impl_tvs
970 , hsq_explicit = expl_tvs
971 , hsq_dependent = emptyNameSet }
972 -- NB: Don't pass impl_tvs to the hsq_explicit field above
973 -- See Note [Don't quantify implicit type variables in quotes]
974
975 (univs, reqs, exis, provs, ty) = splitLHsPatSynTy body
976
977 repHsSigWcType :: LHsSigWcType GhcRn -> DsM (Core TH.TypeQ)
978 repHsSigWcType (HsWC { hswc_body = sig1 })
979 = repHsSigType sig1
980
981 -- yield the representation of a list of types
982 repLTys :: [LHsType GhcRn] -> DsM [Core TH.TypeQ]
983 repLTys tys = mapM repLTy tys
984
985 -- represent a type
986 repLTy :: LHsType GhcRn -> DsM (Core TH.TypeQ)
987 repLTy (L _ ty) = repTy ty
988
989 repForall :: HsType GhcRn -> DsM (Core TH.TypeQ)
990 -- Arg of repForall is always HsForAllTy or HsQualTy
991 repForall ty
992 | (tvs, ctxt, tau) <- splitLHsSigmaTy (noLoc ty)
993 = addTyVarBinds (HsQTvs { hsq_implicit = [], hsq_explicit = tvs
994 , hsq_dependent = emptyNameSet }) $ \bndrs ->
995 do { ctxt1 <- repLContext ctxt
996 ; ty1 <- repLTy tau
997 ; repTForall bndrs ctxt1 ty1 }
998
999 repTy :: HsType GhcRn -> DsM (Core TH.TypeQ)
1000 repTy ty@(HsForAllTy {}) = repForall ty
1001 repTy ty@(HsQualTy {}) = repForall ty
1002
1003 repTy (HsTyVar _ (L _ n))
1004 | isLiftedTypeKindTyConName n = repTStar
1005 | n `hasKey` constraintKindTyConKey = repTConstraint
1006 | isTvOcc occ = do tv1 <- lookupOcc n
1007 repTvar tv1
1008 | isDataOcc occ = do tc1 <- lookupOcc n
1009 repPromotedDataCon tc1
1010 | n == eqTyConName = repTequality
1011 | otherwise = do tc1 <- lookupOcc n
1012 repNamedTyCon tc1
1013 where
1014 occ = nameOccName n
1015
1016 repTy (HsAppTy f a) = do
1017 f1 <- repLTy f
1018 a1 <- repLTy a
1019 repTapp f1 a1
1020 repTy (HsFunTy f a) = do
1021 f1 <- repLTy f
1022 a1 <- repLTy a
1023 tcon <- repArrowTyCon
1024 repTapps tcon [f1, a1]
1025 repTy (HsListTy t) = do
1026 t1 <- repLTy t
1027 tcon <- repListTyCon
1028 repTapp tcon t1
1029 repTy (HsPArrTy t) = do
1030 t1 <- repLTy t
1031 tcon <- repTy (HsTyVar NotPromoted
1032 (noLoc (tyConName parrTyCon)))
1033 repTapp tcon t1
1034 repTy (HsTupleTy HsUnboxedTuple tys) = do
1035 tys1 <- repLTys tys
1036 tcon <- repUnboxedTupleTyCon (length tys)
1037 repTapps tcon tys1
1038 repTy (HsTupleTy _ tys) = do tys1 <- repLTys tys
1039 tcon <- repTupleTyCon (length tys)
1040 repTapps tcon tys1
1041 repTy (HsSumTy tys) = do tys1 <- repLTys tys
1042 tcon <- repUnboxedSumTyCon (length tys)
1043 repTapps tcon tys1
1044 repTy (HsOpTy ty1 n ty2) = repLTy ((nlHsTyVar (unLoc n) `nlHsAppTy` ty1)
1045 `nlHsAppTy` ty2)
1046 repTy (HsParTy t) = repLTy t
1047 repTy (HsEqTy t1 t2) = do
1048 t1' <- repLTy t1
1049 t2' <- repLTy t2
1050 eq <- repTequality
1051 repTapps eq [t1', t2']
1052 repTy (HsKindSig t k) = do
1053 t1 <- repLTy t
1054 k1 <- repLTy k
1055 repTSig t1 k1
1056 repTy (HsSpliceTy splice _) = repSplice splice
1057 repTy (HsExplicitListTy _ _ tys) = do
1058 tys1 <- repLTys tys
1059 repTPromotedList tys1
1060 repTy (HsExplicitTupleTy _ tys) = do
1061 tys1 <- repLTys tys
1062 tcon <- repPromotedTupleTyCon (length tys)
1063 repTapps tcon tys1
1064 repTy (HsTyLit lit) = do
1065 lit' <- repTyLit lit
1066 repTLit lit'
1067 repTy (HsWildCardTy (AnonWildCard _)) = repTWildCard
1068
1069 repTy ty = notHandled "Exotic form of type" (ppr ty)
1070
1071 repTyLit :: HsTyLit -> DsM (Core TH.TyLitQ)
1072 repTyLit (HsNumTy _ i) = do iExpr <- mkIntegerExpr i
1073 rep2 numTyLitName [iExpr]
1074 repTyLit (HsStrTy _ s) = do { s' <- mkStringExprFS s
1075 ; rep2 strTyLitName [s']
1076 }
1077
1078 -- | Represent a type wrapped in a Maybe
1079 repMaybeLTy :: Maybe (LHsKind GhcRn)
1080 -> DsM (Core (Maybe TH.TypeQ))
1081 repMaybeLTy Nothing =
1082 do { coreNothing kindQTyConName }
1083 repMaybeLTy (Just ki) =
1084 do { ki' <- repLTy ki
1085 ; coreJust kindQTyConName ki' }
1086
1087 repRole :: Located (Maybe Role) -> DsM (Core TH.Role)
1088 repRole (L _ (Just Nominal)) = rep2 nominalRName []
1089 repRole (L _ (Just Representational)) = rep2 representationalRName []
1090 repRole (L _ (Just Phantom)) = rep2 phantomRName []
1091 repRole (L _ Nothing) = rep2 inferRName []
1092
1093 -----------------------------------------------------------------------------
1094 -- Splices
1095 -----------------------------------------------------------------------------
1096
1097 repSplice :: HsSplice GhcRn -> DsM (Core a)
1098 -- See Note [How brackets and nested splices are handled] in TcSplice
1099 -- We return a CoreExpr of any old type; the context should know
1100 repSplice (HsTypedSplice _ n _) = rep_splice n
1101 repSplice (HsUntypedSplice _ n _) = rep_splice n
1102 repSplice (HsQuasiQuote n _ _ _) = rep_splice n
1103 repSplice e@(HsSpliced _ _) = pprPanic "repSplice" (ppr e)
1104
1105 rep_splice :: Name -> DsM (Core a)
1106 rep_splice splice_name
1107 = do { mb_val <- dsLookupMetaEnv splice_name
1108 ; case mb_val of
1109 Just (DsSplice e) -> do { e' <- dsExpr e
1110 ; return (MkC e') }
1111 _ -> pprPanic "HsSplice" (ppr splice_name) }
1112 -- Should not happen; statically checked
1113
1114 -----------------------------------------------------------------------------
1115 -- Expressions
1116 -----------------------------------------------------------------------------
1117
1118 repLEs :: [LHsExpr GhcRn] -> DsM (Core [TH.ExpQ])
1119 repLEs es = repList expQTyConName repLE es
1120
1121 -- FIXME: some of these panics should be converted into proper error messages
1122 -- unless we can make sure that constructs, which are plainly not
1123 -- supported in TH already lead to error messages at an earlier stage
1124 repLE :: LHsExpr GhcRn -> DsM (Core TH.ExpQ)
1125 repLE (L loc e) = putSrcSpanDs loc (repE e)
1126
1127 repE :: HsExpr GhcRn -> DsM (Core TH.ExpQ)
1128 repE (HsVar (L _ x)) =
1129 do { mb_val <- dsLookupMetaEnv x
1130 ; case mb_val of
1131 Nothing -> do { str <- globalVar x
1132 ; repVarOrCon x str }
1133 Just (DsBound y) -> repVarOrCon x (coreVar y)
1134 Just (DsSplice e) -> do { e' <- dsExpr e
1135 ; return (MkC e') } }
1136 repE e@(HsIPVar _) = notHandled "Implicit parameters" (ppr e)
1137 repE (HsOverLabel _ s) = repOverLabel s
1138
1139 repE e@(HsRecFld f) = case f of
1140 Unambiguous _ x -> repE (HsVar (noLoc x))
1141 Ambiguous{} -> notHandled "Ambiguous record selectors" (ppr e)
1142
1143 -- Remember, we're desugaring renamer output here, so
1144 -- HsOverlit can definitely occur
1145 repE (HsOverLit l) = do { a <- repOverloadedLiteral l; repLit a }
1146 repE (HsLit l) = do { a <- repLiteral l; repLit a }
1147 repE (HsLam (MG { mg_alts = L _ [m] })) = repLambda m
1148 repE (HsLamCase (MG { mg_alts = L _ ms }))
1149 = do { ms' <- mapM repMatchTup ms
1150 ; core_ms <- coreList matchQTyConName ms'
1151 ; repLamCase core_ms }
1152 repE (HsApp x y) = do {a <- repLE x; b <- repLE y; repApp a b}
1153 repE (HsAppType e t) = do { a <- repLE e
1154 ; s <- repLTy (hswc_body t)
1155 ; repAppType a s }
1156
1157 repE (OpApp e1 op _ e2) =
1158 do { arg1 <- repLE e1;
1159 arg2 <- repLE e2;
1160 the_op <- repLE op ;
1161 repInfixApp arg1 the_op arg2 }
1162 repE (NegApp x _) = do
1163 a <- repLE x
1164 negateVar <- lookupOcc negateName >>= repVar
1165 negateVar `repApp` a
1166 repE (HsPar x) = repLE x
1167 repE (SectionL x y) = do { a <- repLE x; b <- repLE y; repSectionL a b }
1168 repE (SectionR x y) = do { a <- repLE x; b <- repLE y; repSectionR a b }
1169 repE (HsCase e (MG { mg_alts = L _ ms }))
1170 = do { arg <- repLE e
1171 ; ms2 <- mapM repMatchTup ms
1172 ; core_ms2 <- coreList matchQTyConName ms2
1173 ; repCaseE arg core_ms2 }
1174 repE (HsIf _ x y z) = do
1175 a <- repLE x
1176 b <- repLE y
1177 c <- repLE z
1178 repCond a b c
1179 repE (HsMultiIf _ alts)
1180 = do { (binds, alts') <- liftM unzip $ mapM repLGRHS alts
1181 ; expr' <- repMultiIf (nonEmptyCoreList alts')
1182 ; wrapGenSyms (concat binds) expr' }
1183 repE (HsLet (L _ bs) e) = do { (ss,ds) <- repBinds bs
1184 ; e2 <- addBinds ss (repLE e)
1185 ; z <- repLetE ds e2
1186 ; wrapGenSyms ss z }
1187
1188 -- FIXME: I haven't got the types here right yet
1189 repE e@(HsDo ctxt (L _ sts) _)
1190 | case ctxt of { DoExpr -> True; GhciStmtCtxt -> True; _ -> False }
1191 = do { (ss,zs) <- repLSts sts;
1192 e' <- repDoE (nonEmptyCoreList zs);
1193 wrapGenSyms ss e' }
1194
1195 | ListComp <- ctxt
1196 = do { (ss,zs) <- repLSts sts;
1197 e' <- repComp (nonEmptyCoreList zs);
1198 wrapGenSyms ss e' }
1199
1200 | otherwise
1201 = notHandled "mdo, monad comprehension and [: :]" (ppr e)
1202
1203 repE (ExplicitList _ _ es) = do { xs <- repLEs es; repListExp xs }
1204 repE e@(ExplicitPArr _ _) = notHandled "Parallel arrays" (ppr e)
1205 repE e@(ExplicitTuple es boxed)
1206 | not (all tupArgPresent es) = notHandled "Tuple sections" (ppr e)
1207 | isBoxed boxed = do { xs <- repLEs [e | L _ (Present e) <- es]; repTup xs }
1208 | otherwise = do { xs <- repLEs [e | L _ (Present e) <- es]
1209 ; repUnboxedTup xs }
1210
1211 repE (ExplicitSum alt arity e _)
1212 = do { e1 <- repLE e
1213 ; repUnboxedSum e1 alt arity }
1214
1215 repE (RecordCon { rcon_con_name = c, rcon_flds = flds })
1216 = do { x <- lookupLOcc c;
1217 fs <- repFields flds;
1218 repRecCon x fs }
1219 repE (RecordUpd { rupd_expr = e, rupd_flds = flds })
1220 = do { x <- repLE e;
1221 fs <- repUpdFields flds;
1222 repRecUpd x fs }
1223
1224 repE (ExprWithTySig e ty)
1225 = do { e1 <- repLE e
1226 ; t1 <- repHsSigWcType ty
1227 ; repSigExp e1 t1 }
1228
1229 repE (ArithSeq _ _ aseq) =
1230 case aseq of
1231 From e -> do { ds1 <- repLE e; repFrom ds1 }
1232 FromThen e1 e2 -> do
1233 ds1 <- repLE e1
1234 ds2 <- repLE e2
1235 repFromThen ds1 ds2
1236 FromTo e1 e2 -> do
1237 ds1 <- repLE e1
1238 ds2 <- repLE e2
1239 repFromTo ds1 ds2
1240 FromThenTo e1 e2 e3 -> do
1241 ds1 <- repLE e1
1242 ds2 <- repLE e2
1243 ds3 <- repLE e3
1244 repFromThenTo ds1 ds2 ds3
1245
1246 repE (HsSpliceE splice) = repSplice splice
1247 repE (HsStatic _ e) = repLE e >>= rep2 staticEName . (:[]) . unC
1248 repE (HsUnboundVar uv) = do
1249 occ <- occNameLit (unboundVarOcc uv)
1250 sname <- repNameS occ
1251 repUnboundVar sname
1252
1253 repE e@(PArrSeq {}) = notHandled "Parallel arrays" (ppr e)
1254 repE e@(HsCoreAnn {}) = notHandled "Core annotations" (ppr e)
1255 repE e@(HsSCC {}) = notHandled "Cost centres" (ppr e)
1256 repE e@(HsTickPragma {}) = notHandled "Tick Pragma" (ppr e)
1257 repE e@(HsTcBracketOut {}) = notHandled "TH brackets" (ppr e)
1258 repE e = notHandled "Expression form" (ppr e)
1259
1260 -----------------------------------------------------------------------------
1261 -- Building representations of auxillary structures like Match, Clause, Stmt,
1262
1263 repMatchTup :: LMatch GhcRn (LHsExpr GhcRn) -> DsM (Core TH.MatchQ)
1264 repMatchTup (L _ (Match { m_pats = [p], m_grhss = GRHSs guards (L _ wheres) })) =
1265 do { ss1 <- mkGenSyms (collectPatBinders p)
1266 ; addBinds ss1 $ do {
1267 ; p1 <- repLP p
1268 ; (ss2,ds) <- repBinds wheres
1269 ; addBinds ss2 $ do {
1270 ; gs <- repGuards guards
1271 ; match <- repMatch p1 gs ds
1272 ; wrapGenSyms (ss1++ss2) match }}}
1273 repMatchTup _ = panic "repMatchTup: case alt with more than one arg"
1274
1275 repClauseTup :: LMatch GhcRn (LHsExpr GhcRn) -> DsM (Core TH.ClauseQ)
1276 repClauseTup (L _ (Match { m_pats = ps, m_grhss = GRHSs guards (L _ wheres) })) =
1277 do { ss1 <- mkGenSyms (collectPatsBinders ps)
1278 ; addBinds ss1 $ do {
1279 ps1 <- repLPs ps
1280 ; (ss2,ds) <- repBinds wheres
1281 ; addBinds ss2 $ do {
1282 gs <- repGuards guards
1283 ; clause <- repClause ps1 gs ds
1284 ; wrapGenSyms (ss1++ss2) clause }}}
1285
1286 repGuards :: [LGRHS GhcRn (LHsExpr GhcRn)] -> DsM (Core TH.BodyQ)
1287 repGuards [L _ (GRHS [] e)]
1288 = do {a <- repLE e; repNormal a }
1289 repGuards other
1290 = do { zs <- mapM repLGRHS other
1291 ; let (xs, ys) = unzip zs
1292 ; gd <- repGuarded (nonEmptyCoreList ys)
1293 ; wrapGenSyms (concat xs) gd }
1294
1295 repLGRHS :: LGRHS GhcRn (LHsExpr GhcRn)
1296 -> DsM ([GenSymBind], (Core (TH.Q (TH.Guard, TH.Exp))))
1297 repLGRHS (L _ (GRHS [L _ (BodyStmt e1 _ _ _)] e2))
1298 = do { guarded <- repLNormalGE e1 e2
1299 ; return ([], guarded) }
1300 repLGRHS (L _ (GRHS ss rhs))
1301 = do { (gs, ss') <- repLSts ss
1302 ; rhs' <- addBinds gs $ repLE rhs
1303 ; guarded <- repPatGE (nonEmptyCoreList ss') rhs'
1304 ; return (gs, guarded) }
1305
1306 repFields :: HsRecordBinds GhcRn -> DsM (Core [TH.Q TH.FieldExp])
1307 repFields (HsRecFields { rec_flds = flds })
1308 = repList fieldExpQTyConName rep_fld flds
1309 where
1310 rep_fld :: LHsRecField GhcRn (LHsExpr GhcRn)
1311 -> DsM (Core (TH.Q TH.FieldExp))
1312 rep_fld (L _ fld) = do { fn <- lookupLOcc (hsRecFieldSel fld)
1313 ; e <- repLE (hsRecFieldArg fld)
1314 ; repFieldExp fn e }
1315
1316 repUpdFields :: [LHsRecUpdField GhcRn] -> DsM (Core [TH.Q TH.FieldExp])
1317 repUpdFields = repList fieldExpQTyConName rep_fld
1318 where
1319 rep_fld :: LHsRecUpdField GhcRn -> DsM (Core (TH.Q TH.FieldExp))
1320 rep_fld (L l fld) = case unLoc (hsRecFieldLbl fld) of
1321 Unambiguous _ sel_name -> do { fn <- lookupLOcc (L l sel_name)
1322 ; e <- repLE (hsRecFieldArg fld)
1323 ; repFieldExp fn e }
1324 _ -> notHandled "Ambiguous record updates" (ppr fld)
1325
1326
1327
1328 -----------------------------------------------------------------------------
1329 -- Representing Stmt's is tricky, especially if bound variables
1330 -- shadow each other. Consider: [| do { x <- f 1; x <- f x; g x } |]
1331 -- First gensym new names for every variable in any of the patterns.
1332 -- both static (x'1 and x'2), and dynamic ((gensym "x") and (gensym "y"))
1333 -- if variables didn't shaddow, the static gensym wouldn't be necessary
1334 -- and we could reuse the original names (x and x).
1335 --
1336 -- do { x'1 <- gensym "x"
1337 -- ; x'2 <- gensym "x"
1338 -- ; doE [ BindSt (pvar x'1) [| f 1 |]
1339 -- , BindSt (pvar x'2) [| f x |]
1340 -- , NoBindSt [| g x |]
1341 -- ]
1342 -- }
1343
1344 -- The strategy is to translate a whole list of do-bindings by building a
1345 -- bigger environment, and a bigger set of meta bindings
1346 -- (like: x'1 <- gensym "x" ) and then combining these with the translations
1347 -- of the expressions within the Do
1348
1349 -----------------------------------------------------------------------------
1350 -- The helper function repSts computes the translation of each sub expression
1351 -- and a bunch of prefix bindings denoting the dynamic renaming.
1352
1353 repLSts :: [LStmt GhcRn (LHsExpr GhcRn)] -> DsM ([GenSymBind], [Core TH.StmtQ])
1354 repLSts stmts = repSts (map unLoc stmts)
1355
1356 repSts :: [Stmt GhcRn (LHsExpr GhcRn)] -> DsM ([GenSymBind], [Core TH.StmtQ])
1357 repSts (BindStmt p e _ _ _ : ss) =
1358 do { e2 <- repLE e
1359 ; ss1 <- mkGenSyms (collectPatBinders p)
1360 ; addBinds ss1 $ do {
1361 ; p1 <- repLP p;
1362 ; (ss2,zs) <- repSts ss
1363 ; z <- repBindSt p1 e2
1364 ; return (ss1++ss2, z : zs) }}
1365 repSts (LetStmt (L _ bs) : ss) =
1366 do { (ss1,ds) <- repBinds bs
1367 ; z <- repLetSt ds
1368 ; (ss2,zs) <- addBinds ss1 (repSts ss)
1369 ; return (ss1++ss2, z : zs) }
1370 repSts (BodyStmt e _ _ _ : ss) =
1371 do { e2 <- repLE e
1372 ; z <- repNoBindSt e2
1373 ; (ss2,zs) <- repSts ss
1374 ; return (ss2, z : zs) }
1375 repSts (ParStmt stmt_blocks _ _ _ : ss) =
1376 do { (ss_s, stmt_blocks1) <- mapAndUnzipM rep_stmt_block stmt_blocks
1377 ; let stmt_blocks2 = nonEmptyCoreList stmt_blocks1
1378 ss1 = concat ss_s
1379 ; z <- repParSt stmt_blocks2
1380 ; (ss2, zs) <- addBinds ss1 (repSts ss)
1381 ; return (ss1++ss2, z : zs) }
1382 where
1383 rep_stmt_block :: ParStmtBlock GhcRn GhcRn
1384 -> DsM ([GenSymBind], Core [TH.StmtQ])
1385 rep_stmt_block (ParStmtBlock stmts _ _) =
1386 do { (ss1, zs) <- repSts (map unLoc stmts)
1387 ; zs1 <- coreList stmtQTyConName zs
1388 ; return (ss1, zs1) }
1389 repSts [LastStmt e _ _]
1390 = do { e2 <- repLE e
1391 ; z <- repNoBindSt e2
1392 ; return ([], [z]) }
1393 repSts [] = return ([],[])
1394 repSts other = notHandled "Exotic statement" (ppr other)
1395
1396
1397 -----------------------------------------------------------
1398 -- Bindings
1399 -----------------------------------------------------------
1400
1401 repBinds :: HsLocalBinds GhcRn -> DsM ([GenSymBind], Core [TH.DecQ])
1402 repBinds EmptyLocalBinds
1403 = do { core_list <- coreList decQTyConName []
1404 ; return ([], core_list) }
1405
1406 repBinds b@(HsIPBinds _) = notHandled "Implicit parameters" (ppr b)
1407
1408 repBinds (HsValBinds decs)
1409 = do { let { bndrs = hsSigTvBinders decs ++ collectHsValBinders decs }
1410 -- No need to worry about detailed scopes within
1411 -- the binding group, because we are talking Names
1412 -- here, so we can safely treat it as a mutually
1413 -- recursive group
1414 -- For hsSigTvBinders see Note [Scoped type variables in bindings]
1415 ; ss <- mkGenSyms bndrs
1416 ; prs <- addBinds ss (rep_val_binds decs)
1417 ; core_list <- coreList decQTyConName
1418 (de_loc (sort_by_loc prs))
1419 ; return (ss, core_list) }
1420
1421 rep_val_binds :: HsValBinds GhcRn -> DsM [(SrcSpan, Core TH.DecQ)]
1422 -- Assumes: all the binders of the binding are already in the meta-env
1423 rep_val_binds (ValBindsOut binds sigs)
1424 = do { core1 <- rep_binds' (unionManyBags (map snd binds))
1425 ; core2 <- rep_sigs' sigs
1426 ; return (core1 ++ core2) }
1427 rep_val_binds (ValBindsIn _ _)
1428 = panic "rep_val_binds: ValBindsIn"
1429
1430 rep_binds :: LHsBinds GhcRn -> DsM [Core TH.DecQ]
1431 rep_binds binds = do { binds_w_locs <- rep_binds' binds
1432 ; return (de_loc (sort_by_loc binds_w_locs)) }
1433
1434 rep_binds' :: LHsBinds GhcRn -> DsM [(SrcSpan, Core TH.DecQ)]
1435 rep_binds' = mapM rep_bind . bagToList
1436
1437 rep_bind :: LHsBind GhcRn -> DsM (SrcSpan, Core TH.DecQ)
1438 -- Assumes: all the binders of the binding are already in the meta-env
1439
1440 -- Note GHC treats declarations of a variable (not a pattern)
1441 -- e.g. x = g 5 as a Fun MonoBinds. This is indicated by a single match
1442 -- with an empty list of patterns
1443 rep_bind (L loc (FunBind
1444 { fun_id = fn,
1445 fun_matches = MG { mg_alts
1446 = L _ [L _ (Match { m_pats = []
1447 , m_grhss = GRHSs guards (L _ wheres) })] } }))
1448 = do { (ss,wherecore) <- repBinds wheres
1449 ; guardcore <- addBinds ss (repGuards guards)
1450 ; fn' <- lookupLBinder fn
1451 ; p <- repPvar fn'
1452 ; ans <- repVal p guardcore wherecore
1453 ; ans' <- wrapGenSyms ss ans
1454 ; return (loc, ans') }
1455
1456 rep_bind (L loc (FunBind { fun_id = fn
1457 , fun_matches = MG { mg_alts = L _ ms } }))
1458 = do { ms1 <- mapM repClauseTup ms
1459 ; fn' <- lookupLBinder fn
1460 ; ans <- repFun fn' (nonEmptyCoreList ms1)
1461 ; return (loc, ans) }
1462
1463 rep_bind (L loc (PatBind { pat_lhs = pat
1464 , pat_rhs = GRHSs guards (L _ wheres) }))
1465 = do { patcore <- repLP pat
1466 ; (ss,wherecore) <- repBinds wheres
1467 ; guardcore <- addBinds ss (repGuards guards)
1468 ; ans <- repVal patcore guardcore wherecore
1469 ; ans' <- wrapGenSyms ss ans
1470 ; return (loc, ans') }
1471
1472 rep_bind (L _ (VarBind { var_id = v, var_rhs = e}))
1473 = do { v' <- lookupBinder v
1474 ; e2 <- repLE e
1475 ; x <- repNormal e2
1476 ; patcore <- repPvar v'
1477 ; empty_decls <- coreList decQTyConName []
1478 ; ans <- repVal patcore x empty_decls
1479 ; return (srcLocSpan (getSrcLoc v), ans) }
1480
1481 rep_bind (L _ (AbsBinds {})) = panic "rep_bind: AbsBinds"
1482 rep_bind (L loc (PatSynBind (PSB { psb_id = syn
1483 , psb_fvs = _fvs
1484 , psb_args = args
1485 , psb_def = pat
1486 , psb_dir = dir })))
1487 = do { syn' <- lookupLBinder syn
1488 ; dir' <- repPatSynDir dir
1489 ; ss <- mkGenArgSyms args
1490 ; patSynD' <- addBinds ss (
1491 do { args' <- repPatSynArgs args
1492 ; pat' <- repLP pat
1493 ; repPatSynD syn' args' dir' pat' })
1494 ; patSynD'' <- wrapGenArgSyms args ss patSynD'
1495 ; return (loc, patSynD'') }
1496 where
1497 mkGenArgSyms :: HsPatSynDetails (Located Name) -> DsM [GenSymBind]
1498 -- for Record Pattern Synonyms we want to conflate the selector
1499 -- and the pattern-only names in order to provide a nicer TH
1500 -- API. Whereas inside GHC, record pattern synonym selectors and
1501 -- their pattern-only bound right hand sides have different names,
1502 -- we want to treat them the same in TH. This is the reason why we
1503 -- need an adjusted mkGenArgSyms in the `RecordPatSyn` case below.
1504 mkGenArgSyms (PrefixPatSyn args) = mkGenSyms (map unLoc args)
1505 mkGenArgSyms (InfixPatSyn arg1 arg2) = mkGenSyms [unLoc arg1, unLoc arg2]
1506 mkGenArgSyms (RecordPatSyn fields)
1507 = do { let pats = map (unLoc . recordPatSynPatVar) fields
1508 sels = map (unLoc . recordPatSynSelectorId) fields
1509 ; ss <- mkGenSyms sels
1510 ; return $ replaceNames (zip sels pats) ss }
1511
1512 replaceNames selsPats genSyms
1513 = [ (pat, id) | (sel, id) <- genSyms, (sel', pat) <- selsPats
1514 , sel == sel' ]
1515
1516 wrapGenArgSyms :: HsPatSynDetails (Located Name)
1517 -> [GenSymBind] -> Core TH.DecQ -> DsM (Core TH.DecQ)
1518 wrapGenArgSyms (RecordPatSyn _) _ dec = return dec
1519 wrapGenArgSyms _ ss dec = wrapGenSyms ss dec
1520
1521 repPatSynD :: Core TH.Name
1522 -> Core TH.PatSynArgsQ
1523 -> Core TH.PatSynDirQ
1524 -> Core TH.PatQ
1525 -> DsM (Core TH.DecQ)
1526 repPatSynD (MkC syn) (MkC args) (MkC dir) (MkC pat)
1527 = rep2 patSynDName [syn, args, dir, pat]
1528
1529 repPatSynArgs :: HsPatSynDetails (Located Name) -> DsM (Core TH.PatSynArgsQ)
1530 repPatSynArgs (PrefixPatSyn args)
1531 = do { args' <- repList nameTyConName lookupLOcc args
1532 ; repPrefixPatSynArgs args' }
1533 repPatSynArgs (InfixPatSyn arg1 arg2)
1534 = do { arg1' <- lookupLOcc arg1
1535 ; arg2' <- lookupLOcc arg2
1536 ; repInfixPatSynArgs arg1' arg2' }
1537 repPatSynArgs (RecordPatSyn fields)
1538 = do { sels' <- repList nameTyConName lookupLOcc sels
1539 ; repRecordPatSynArgs sels' }
1540 where sels = map recordPatSynSelectorId fields
1541
1542 repPrefixPatSynArgs :: Core [TH.Name] -> DsM (Core TH.PatSynArgsQ)
1543 repPrefixPatSynArgs (MkC nms) = rep2 prefixPatSynName [nms]
1544
1545 repInfixPatSynArgs :: Core TH.Name -> Core TH.Name -> DsM (Core TH.PatSynArgsQ)
1546 repInfixPatSynArgs (MkC nm1) (MkC nm2) = rep2 infixPatSynName [nm1, nm2]
1547
1548 repRecordPatSynArgs :: Core [TH.Name]
1549 -> DsM (Core TH.PatSynArgsQ)
1550 repRecordPatSynArgs (MkC sels) = rep2 recordPatSynName [sels]
1551
1552 repPatSynDir :: HsPatSynDir GhcRn -> DsM (Core TH.PatSynDirQ)
1553 repPatSynDir Unidirectional = rep2 unidirPatSynName []
1554 repPatSynDir ImplicitBidirectional = rep2 implBidirPatSynName []
1555 repPatSynDir (ExplicitBidirectional (MG { mg_alts = L _ clauses }))
1556 = do { clauses' <- mapM repClauseTup clauses
1557 ; repExplBidirPatSynDir (nonEmptyCoreList clauses') }
1558
1559 repExplBidirPatSynDir :: Core [TH.ClauseQ] -> DsM (Core TH.PatSynDirQ)
1560 repExplBidirPatSynDir (MkC cls) = rep2 explBidirPatSynName [cls]
1561
1562
1563 -----------------------------------------------------------------------------
1564 -- Since everything in a Bind is mutually recursive we need rename all
1565 -- all the variables simultaneously. For example:
1566 -- [| AndMonoBinds (f x = x + g 2) (g x = f 1 + 2) |] would translate to
1567 -- do { f'1 <- gensym "f"
1568 -- ; g'2 <- gensym "g"
1569 -- ; [ do { x'3 <- gensym "x"; fun f'1 [pvar x'3] [| x + g2 |]},
1570 -- do { x'4 <- gensym "x"; fun g'2 [pvar x'4] [| f 1 + 2 |]}
1571 -- ]}
1572 -- This requires collecting the bindings (f'1 <- gensym "f"), and the
1573 -- environment ( f |-> f'1 ) from each binding, and then unioning them
1574 -- together. As we do this we collect GenSymBinds's which represent the renamed
1575 -- variables bound by the Bindings. In order not to lose track of these
1576 -- representations we build a shadow datatype MB with the same structure as
1577 -- MonoBinds, but which has slots for the representations
1578
1579
1580 -----------------------------------------------------------------------------
1581 -- GHC allows a more general form of lambda abstraction than specified
1582 -- by Haskell 98. In particular it allows guarded lambda's like :
1583 -- (\ x | even x -> 0 | odd x -> 1) at the moment we can't represent this in
1584 -- Haskell Template's Meta.Exp type so we punt if it isn't a simple thing like
1585 -- (\ p1 .. pn -> exp) by causing an error.
1586
1587 repLambda :: LMatch GhcRn (LHsExpr GhcRn) -> DsM (Core TH.ExpQ)
1588 repLambda (L _ (Match { m_pats = ps
1589 , m_grhss = GRHSs [L _ (GRHS [] e)] (L _ EmptyLocalBinds) } ))
1590 = do { let bndrs = collectPatsBinders ps ;
1591 ; ss <- mkGenSyms bndrs
1592 ; lam <- addBinds ss (
1593 do { xs <- repLPs ps; body <- repLE e; repLam xs body })
1594 ; wrapGenSyms ss lam }
1595
1596 repLambda (L _ m) = notHandled "Guarded labmdas" (pprMatch m)
1597
1598
1599 -----------------------------------------------------------------------------
1600 -- Patterns
1601 -- repP deals with patterns. It assumes that we have already
1602 -- walked over the pattern(s) once to collect the binders, and
1603 -- have extended the environment. So every pattern-bound
1604 -- variable should already appear in the environment.
1605
1606 -- Process a list of patterns
1607 repLPs :: [LPat GhcRn] -> DsM (Core [TH.PatQ])
1608 repLPs ps = repList patQTyConName repLP ps
1609
1610 repLP :: LPat GhcRn -> DsM (Core TH.PatQ)
1611 repLP (L _ p) = repP p
1612
1613 repP :: Pat GhcRn -> DsM (Core TH.PatQ)
1614 repP (WildPat _) = repPwild
1615 repP (LitPat l) = do { l2 <- repLiteral l; repPlit l2 }
1616 repP (VarPat (L _ x)) = do { x' <- lookupBinder x; repPvar x' }
1617 repP (LazyPat p) = do { p1 <- repLP p; repPtilde p1 }
1618 repP (BangPat p) = do { p1 <- repLP p; repPbang p1 }
1619 repP (AsPat x p) = do { x' <- lookupLBinder x; p1 <- repLP p; repPaspat x' p1 }
1620 repP (ParPat p) = repLP p
1621 repP (ListPat ps _ Nothing) = do { qs <- repLPs ps; repPlist qs }
1622 repP (ListPat ps ty1 (Just (_,e))) = do { p <- repP (ListPat ps ty1 Nothing); e' <- repE (syn_expr e); repPview e' p}
1623 repP (TuplePat ps boxed _)
1624 | isBoxed boxed = do { qs <- repLPs ps; repPtup qs }
1625 | otherwise = do { qs <- repLPs ps; repPunboxedTup qs }
1626 repP (SumPat p alt arity _) = do { p1 <- repLP p; repPunboxedSum p1 alt arity }
1627 repP (ConPatIn dc details)
1628 = do { con_str <- lookupLOcc dc
1629 ; case details of
1630 PrefixCon ps -> do { qs <- repLPs ps; repPcon con_str qs }
1631 RecCon rec -> do { fps <- repList fieldPatQTyConName rep_fld (rec_flds rec)
1632 ; repPrec con_str fps }
1633 InfixCon p1 p2 -> do { p1' <- repLP p1;
1634 p2' <- repLP p2;
1635 repPinfix p1' con_str p2' }
1636 }
1637 where
1638 rep_fld :: LHsRecField GhcRn (LPat GhcRn) -> DsM (Core (TH.Name,TH.PatQ))
1639 rep_fld (L _ fld) = do { MkC v <- lookupLOcc (hsRecFieldSel fld)
1640 ; MkC p <- repLP (hsRecFieldArg fld)
1641 ; rep2 fieldPatName [v,p] }
1642
1643 repP (NPat (L _ l) Nothing _ _) = do { a <- repOverloadedLiteral l; repPlit a }
1644 repP (ViewPat e p _) = do { e' <- repLE e; p' <- repLP p; repPview e' p' }
1645 repP p@(NPat _ (Just _) _ _) = notHandled "Negative overloaded patterns" (ppr p)
1646 repP (SigPatIn p t) = do { p' <- repLP p
1647 ; t' <- repLTy (hsSigWcType t)
1648 ; repPsig p' t' }
1649 repP (SplicePat splice) = repSplice splice
1650
1651 repP other = notHandled "Exotic pattern" (ppr other)
1652
1653 ----------------------------------------------------------
1654 -- Declaration ordering helpers
1655
1656 sort_by_loc :: [(SrcSpan, a)] -> [(SrcSpan, a)]
1657 sort_by_loc xs = sortBy comp xs
1658 where comp x y = compare (fst x) (fst y)
1659
1660 de_loc :: [(a, b)] -> [b]
1661 de_loc = map snd
1662
1663 ----------------------------------------------------------
1664 -- The meta-environment
1665
1666 -- A name/identifier association for fresh names of locally bound entities
1667 type GenSymBind = (Name, Id) -- Gensym the string and bind it to the Id
1668 -- I.e. (x, x_id) means
1669 -- let x_id = gensym "x" in ...
1670
1671 -- Generate a fresh name for a locally bound entity
1672
1673 mkGenSyms :: [Name] -> DsM [GenSymBind]
1674 -- We can use the existing name. For example:
1675 -- [| \x_77 -> x_77 + x_77 |]
1676 -- desugars to
1677 -- do { x_77 <- genSym "x"; .... }
1678 -- We use the same x_77 in the desugared program, but with the type Bndr
1679 -- instead of Int
1680 --
1681 -- We do make it an Internal name, though (hence localiseName)
1682 --
1683 -- Nevertheless, it's monadic because we have to generate nameTy
1684 mkGenSyms ns = do { var_ty <- lookupType nameTyConName
1685 ; return [(nm, mkLocalId (localiseName nm) var_ty) | nm <- ns] }
1686
1687
1688 addBinds :: [GenSymBind] -> DsM a -> DsM a
1689 -- Add a list of fresh names for locally bound entities to the
1690 -- meta environment (which is part of the state carried around
1691 -- by the desugarer monad)
1692 addBinds bs m = dsExtendMetaEnv (mkNameEnv [(n,DsBound id) | (n,id) <- bs]) m
1693
1694 -- Look up a locally bound name
1695 --
1696 lookupLBinder :: Located Name -> DsM (Core TH.Name)
1697 lookupLBinder (L _ n) = lookupBinder n
1698
1699 lookupBinder :: Name -> DsM (Core TH.Name)
1700 lookupBinder = lookupOcc
1701 -- Binders are brought into scope before the pattern or what-not is
1702 -- desugared. Moreover, in instance declaration the binder of a method
1703 -- will be the selector Id and hence a global; so we need the
1704 -- globalVar case of lookupOcc
1705
1706 -- Look up a name that is either locally bound or a global name
1707 --
1708 -- * If it is a global name, generate the "original name" representation (ie,
1709 -- the <module>:<name> form) for the associated entity
1710 --
1711 lookupLOcc :: Located Name -> DsM (Core TH.Name)
1712 -- Lookup an occurrence; it can't be a splice.
1713 -- Use the in-scope bindings if they exist
1714 lookupLOcc (L _ n) = lookupOcc n
1715
1716 lookupOcc :: Name -> DsM (Core TH.Name)
1717 lookupOcc n
1718 = do { mb_val <- dsLookupMetaEnv n ;
1719 case mb_val of
1720 Nothing -> globalVar n
1721 Just (DsBound x) -> return (coreVar x)
1722 Just (DsSplice _) -> pprPanic "repE:lookupOcc" (ppr n)
1723 }
1724
1725 globalVar :: Name -> DsM (Core TH.Name)
1726 -- Not bound by the meta-env
1727 -- Could be top-level; or could be local
1728 -- f x = $(g [| x |])
1729 -- Here the x will be local
1730 globalVar name
1731 | isExternalName name
1732 = do { MkC mod <- coreStringLit name_mod
1733 ; MkC pkg <- coreStringLit name_pkg
1734 ; MkC occ <- nameLit name
1735 ; rep2 mk_varg [pkg,mod,occ] }
1736 | otherwise
1737 = do { MkC occ <- nameLit name
1738 ; MkC uni <- coreIntLit (getKey (getUnique name))
1739 ; rep2 mkNameLName [occ,uni] }
1740 where
1741 mod = ASSERT( isExternalName name) nameModule name
1742 name_mod = moduleNameString (moduleName mod)
1743 name_pkg = unitIdString (moduleUnitId mod)
1744 name_occ = nameOccName name
1745 mk_varg | OccName.isDataOcc name_occ = mkNameG_dName
1746 | OccName.isVarOcc name_occ = mkNameG_vName
1747 | OccName.isTcOcc name_occ = mkNameG_tcName
1748 | otherwise = pprPanic "DsMeta.globalVar" (ppr name)
1749
1750 lookupType :: Name -- Name of type constructor (e.g. TH.ExpQ)
1751 -> DsM Type -- The type
1752 lookupType tc_name = do { tc <- dsLookupTyCon tc_name ;
1753 return (mkTyConApp tc []) }
1754
1755 wrapGenSyms :: [GenSymBind]
1756 -> Core (TH.Q a) -> DsM (Core (TH.Q a))
1757 -- wrapGenSyms [(nm1,id1), (nm2,id2)] y
1758 -- --> bindQ (gensym nm1) (\ id1 ->
1759 -- bindQ (gensym nm2 (\ id2 ->
1760 -- y))
1761
1762 wrapGenSyms binds body@(MkC b)
1763 = do { var_ty <- lookupType nameTyConName
1764 ; go var_ty binds }
1765 where
1766 [elt_ty] = tcTyConAppArgs (exprType b)
1767 -- b :: Q a, so we can get the type 'a' by looking at the
1768 -- argument type. NB: this relies on Q being a data/newtype,
1769 -- not a type synonym
1770
1771 go _ [] = return body
1772 go var_ty ((name,id) : binds)
1773 = do { MkC body' <- go var_ty binds
1774 ; lit_str <- nameLit name
1775 ; gensym_app <- repGensym lit_str
1776 ; repBindQ var_ty elt_ty
1777 gensym_app (MkC (Lam id body')) }
1778
1779 nameLit :: Name -> DsM (Core String)
1780 nameLit n = coreStringLit (occNameString (nameOccName n))
1781
1782 occNameLit :: OccName -> DsM (Core String)
1783 occNameLit name = coreStringLit (occNameString name)
1784
1785
1786 -- %*********************************************************************
1787 -- %* *
1788 -- Constructing code
1789 -- %* *
1790 -- %*********************************************************************
1791
1792 -----------------------------------------------------------------------------
1793 -- PHANTOM TYPES for consistency. In order to make sure we do this correct
1794 -- we invent a new datatype which uses phantom types.
1795
1796 newtype Core a = MkC CoreExpr
1797 unC :: Core a -> CoreExpr
1798 unC (MkC x) = x
1799
1800 rep2 :: Name -> [ CoreExpr ] -> DsM (Core a)
1801 rep2 n xs = do { id <- dsLookupGlobalId n
1802 ; return (MkC (foldl App (Var id) xs)) }
1803
1804 dataCon' :: Name -> [CoreExpr] -> DsM (Core a)
1805 dataCon' n args = do { id <- dsLookupDataCon n
1806 ; return $ MkC $ mkCoreConApps id args }
1807
1808 dataCon :: Name -> DsM (Core a)
1809 dataCon n = dataCon' n []
1810
1811
1812 -- %*********************************************************************
1813 -- %* *
1814 -- The 'smart constructors'
1815 -- %* *
1816 -- %*********************************************************************
1817
1818 --------------- Patterns -----------------
1819 repPlit :: Core TH.Lit -> DsM (Core TH.PatQ)
1820 repPlit (MkC l) = rep2 litPName [l]
1821
1822 repPvar :: Core TH.Name -> DsM (Core TH.PatQ)
1823 repPvar (MkC s) = rep2 varPName [s]
1824
1825 repPtup :: Core [TH.PatQ] -> DsM (Core TH.PatQ)
1826 repPtup (MkC ps) = rep2 tupPName [ps]
1827
1828 repPunboxedTup :: Core [TH.PatQ] -> DsM (Core TH.PatQ)
1829 repPunboxedTup (MkC ps) = rep2 unboxedTupPName [ps]
1830
1831 repPunboxedSum :: Core TH.PatQ -> TH.SumAlt -> TH.SumArity -> DsM (Core TH.PatQ)
1832 -- Note: not Core TH.SumAlt or Core TH.SumArity; it's easier to be direct here
1833 repPunboxedSum (MkC p) alt arity
1834 = do { dflags <- getDynFlags
1835 ; rep2 unboxedSumPName [ p
1836 , mkIntExprInt dflags alt
1837 , mkIntExprInt dflags arity ] }
1838
1839 repPcon :: Core TH.Name -> Core [TH.PatQ] -> DsM (Core TH.PatQ)
1840 repPcon (MkC s) (MkC ps) = rep2 conPName [s, ps]
1841
1842 repPrec :: Core TH.Name -> Core [(TH.Name,TH.PatQ)] -> DsM (Core TH.PatQ)
1843 repPrec (MkC c) (MkC rps) = rep2 recPName [c,rps]
1844
1845 repPinfix :: Core TH.PatQ -> Core TH.Name -> Core TH.PatQ -> DsM (Core TH.PatQ)
1846 repPinfix (MkC p1) (MkC n) (MkC p2) = rep2 infixPName [p1, n, p2]
1847
1848 repPtilde :: Core TH.PatQ -> DsM (Core TH.PatQ)
1849 repPtilde (MkC p) = rep2 tildePName [p]
1850
1851 repPbang :: Core TH.PatQ -> DsM (Core TH.PatQ)
1852 repPbang (MkC p) = rep2 bangPName [p]
1853
1854 repPaspat :: Core TH.Name -> Core TH.PatQ -> DsM (Core TH.PatQ)
1855 repPaspat (MkC s) (MkC p) = rep2 asPName [s, p]
1856
1857 repPwild :: DsM (Core TH.PatQ)
1858 repPwild = rep2 wildPName []
1859
1860 repPlist :: Core [TH.PatQ] -> DsM (Core TH.PatQ)
1861 repPlist (MkC ps) = rep2 listPName [ps]
1862
1863 repPview :: Core TH.ExpQ -> Core TH.PatQ -> DsM (Core TH.PatQ)
1864 repPview (MkC e) (MkC p) = rep2 viewPName [e,p]
1865
1866 repPsig :: Core TH.PatQ -> Core TH.TypeQ -> DsM (Core TH.PatQ)
1867 repPsig (MkC p) (MkC t) = rep2 sigPName [p, t]
1868
1869 --------------- Expressions -----------------
1870 repVarOrCon :: Name -> Core TH.Name -> DsM (Core TH.ExpQ)
1871 repVarOrCon vc str | isDataOcc (nameOccName vc) = repCon str
1872 | otherwise = repVar str
1873
1874 repVar :: Core TH.Name -> DsM (Core TH.ExpQ)
1875 repVar (MkC s) = rep2 varEName [s]
1876
1877 repCon :: Core TH.Name -> DsM (Core TH.ExpQ)
1878 repCon (MkC s) = rep2 conEName [s]
1879
1880 repLit :: Core TH.Lit -> DsM (Core TH.ExpQ)
1881 repLit (MkC c) = rep2 litEName [c]
1882
1883 repApp :: Core TH.ExpQ -> Core TH.ExpQ -> DsM (Core TH.ExpQ)
1884 repApp (MkC x) (MkC y) = rep2 appEName [x,y]
1885
1886 repAppType :: Core TH.ExpQ -> Core TH.TypeQ -> DsM (Core TH.ExpQ)
1887 repAppType (MkC x) (MkC y) = rep2 appTypeEName [x,y]
1888
1889 repLam :: Core [TH.PatQ] -> Core TH.ExpQ -> DsM (Core TH.ExpQ)
1890 repLam (MkC ps) (MkC e) = rep2 lamEName [ps, e]
1891
1892 repLamCase :: Core [TH.MatchQ] -> DsM (Core TH.ExpQ)
1893 repLamCase (MkC ms) = rep2 lamCaseEName [ms]
1894
1895 repTup :: Core [TH.ExpQ] -> DsM (Core TH.ExpQ)
1896 repTup (MkC es) = rep2 tupEName [es]
1897
1898 repUnboxedTup :: Core [TH.ExpQ] -> DsM (Core TH.ExpQ)
1899 repUnboxedTup (MkC es) = rep2 unboxedTupEName [es]
1900
1901 repUnboxedSum :: Core TH.ExpQ -> TH.SumAlt -> TH.SumArity -> DsM (Core TH.ExpQ)
1902 -- Note: not Core TH.SumAlt or Core TH.SumArity; it's easier to be direct here
1903 repUnboxedSum (MkC e) alt arity
1904 = do { dflags <- getDynFlags
1905 ; rep2 unboxedSumEName [ e
1906 , mkIntExprInt dflags alt
1907 , mkIntExprInt dflags arity ] }
1908
1909 repCond :: Core TH.ExpQ -> Core TH.ExpQ -> Core TH.ExpQ -> DsM (Core TH.ExpQ)
1910 repCond (MkC x) (MkC y) (MkC z) = rep2 condEName [x,y,z]
1911
1912 repMultiIf :: Core [TH.Q (TH.Guard, TH.Exp)] -> DsM (Core TH.ExpQ)
1913 repMultiIf (MkC alts) = rep2 multiIfEName [alts]
1914
1915 repLetE :: Core [TH.DecQ] -> Core TH.ExpQ -> DsM (Core TH.ExpQ)
1916 repLetE (MkC ds) (MkC e) = rep2 letEName [ds, e]
1917
1918 repCaseE :: Core TH.ExpQ -> Core [TH.MatchQ] -> DsM( Core TH.ExpQ)
1919 repCaseE (MkC e) (MkC ms) = rep2 caseEName [e, ms]
1920
1921 repDoE :: Core [TH.StmtQ] -> DsM (Core TH.ExpQ)
1922 repDoE (MkC ss) = rep2 doEName [ss]
1923
1924 repComp :: Core [TH.StmtQ] -> DsM (Core TH.ExpQ)
1925 repComp (MkC ss) = rep2 compEName [ss]
1926
1927 repListExp :: Core [TH.ExpQ] -> DsM (Core TH.ExpQ)
1928 repListExp (MkC es) = rep2 listEName [es]
1929
1930 repSigExp :: Core TH.ExpQ -> Core TH.TypeQ -> DsM (Core TH.ExpQ)
1931 repSigExp (MkC e) (MkC t) = rep2 sigEName [e,t]
1932
1933 repRecCon :: Core TH.Name -> Core [TH.Q TH.FieldExp]-> DsM (Core TH.ExpQ)
1934 repRecCon (MkC c) (MkC fs) = rep2 recConEName [c,fs]
1935
1936 repRecUpd :: Core TH.ExpQ -> Core [TH.Q TH.FieldExp] -> DsM (Core TH.ExpQ)
1937 repRecUpd (MkC e) (MkC fs) = rep2 recUpdEName [e,fs]
1938
1939 repFieldExp :: Core TH.Name -> Core TH.ExpQ -> DsM (Core (TH.Q TH.FieldExp))
1940 repFieldExp (MkC n) (MkC x) = rep2 fieldExpName [n,x]
1941
1942 repInfixApp :: Core TH.ExpQ -> Core TH.ExpQ -> Core TH.ExpQ -> DsM (Core TH.ExpQ)
1943 repInfixApp (MkC x) (MkC y) (MkC z) = rep2 infixAppName [x,y,z]
1944
1945 repSectionL :: Core TH.ExpQ -> Core TH.ExpQ -> DsM (Core TH.ExpQ)
1946 repSectionL (MkC x) (MkC y) = rep2 sectionLName [x,y]
1947
1948 repSectionR :: Core TH.ExpQ -> Core TH.ExpQ -> DsM (Core TH.ExpQ)
1949 repSectionR (MkC x) (MkC y) = rep2 sectionRName [x,y]
1950
1951 ------------ Right hand sides (guarded expressions) ----
1952 repGuarded :: Core [TH.Q (TH.Guard, TH.Exp)] -> DsM (Core TH.BodyQ)
1953 repGuarded (MkC pairs) = rep2 guardedBName [pairs]
1954
1955 repNormal :: Core TH.ExpQ -> DsM (Core TH.BodyQ)
1956 repNormal (MkC e) = rep2 normalBName [e]
1957
1958 ------------ Guards ----
1959 repLNormalGE :: LHsExpr GhcRn -> LHsExpr GhcRn
1960 -> DsM (Core (TH.Q (TH.Guard, TH.Exp)))
1961 repLNormalGE g e = do g' <- repLE g
1962 e' <- repLE e
1963 repNormalGE g' e'
1964
1965 repNormalGE :: Core TH.ExpQ -> Core TH.ExpQ -> DsM (Core (TH.Q (TH.Guard, TH.Exp)))
1966 repNormalGE (MkC g) (MkC e) = rep2 normalGEName [g, e]
1967
1968 repPatGE :: Core [TH.StmtQ] -> Core TH.ExpQ -> DsM (Core (TH.Q (TH.Guard, TH.Exp)))
1969 repPatGE (MkC ss) (MkC e) = rep2 patGEName [ss, e]
1970
1971 ------------- Stmts -------------------
1972 repBindSt :: Core TH.PatQ -> Core TH.ExpQ -> DsM (Core TH.StmtQ)
1973 repBindSt (MkC p) (MkC e) = rep2 bindSName [p,e]
1974
1975 repLetSt :: Core [TH.DecQ] -> DsM (Core TH.StmtQ)
1976 repLetSt (MkC ds) = rep2 letSName [ds]
1977
1978 repNoBindSt :: Core TH.ExpQ -> DsM (Core TH.StmtQ)
1979 repNoBindSt (MkC e) = rep2 noBindSName [e]
1980
1981 repParSt :: Core [[TH.StmtQ]] -> DsM (Core TH.StmtQ)
1982 repParSt (MkC sss) = rep2 parSName [sss]
1983
1984 -------------- Range (Arithmetic sequences) -----------
1985 repFrom :: Core TH.ExpQ -> DsM (Core TH.ExpQ)
1986 repFrom (MkC x) = rep2 fromEName [x]
1987
1988 repFromThen :: Core TH.ExpQ -> Core TH.ExpQ -> DsM (Core TH.ExpQ)
1989 repFromThen (MkC x) (MkC y) = rep2 fromThenEName [x,y]
1990
1991 repFromTo :: Core TH.ExpQ -> Core TH.ExpQ -> DsM (Core TH.ExpQ)
1992 repFromTo (MkC x) (MkC y) = rep2 fromToEName [x,y]
1993
1994 repFromThenTo :: Core TH.ExpQ -> Core TH.ExpQ -> Core TH.ExpQ -> DsM (Core TH.ExpQ)
1995 repFromThenTo (MkC x) (MkC y) (MkC z) = rep2 fromThenToEName [x,y,z]
1996
1997 ------------ Match and Clause Tuples -----------
1998 repMatch :: Core TH.PatQ -> Core TH.BodyQ -> Core [TH.DecQ] -> DsM (Core TH.MatchQ)
1999 repMatch (MkC p) (MkC bod) (MkC ds) = rep2 matchName [p, bod, ds]
2000
2001 repClause :: Core [TH.PatQ] -> Core TH.BodyQ -> Core [TH.DecQ] -> DsM (Core TH.ClauseQ)
2002 repClause (MkC ps) (MkC bod) (MkC ds) = rep2 clauseName [ps, bod, ds]
2003
2004 -------------- Dec -----------------------------
2005 repVal :: Core TH.PatQ -> Core TH.BodyQ -> Core [TH.DecQ] -> DsM (Core TH.DecQ)
2006 repVal (MkC p) (MkC b) (MkC ds) = rep2 valDName [p, b, ds]
2007
2008 repFun :: Core TH.Name -> Core [TH.ClauseQ] -> DsM (Core TH.DecQ)
2009 repFun (MkC nm) (MkC b) = rep2 funDName [nm, b]
2010
2011 repData :: Core TH.CxtQ -> Core TH.Name -> Core [TH.TyVarBndrQ]
2012 -> Maybe (Core [TH.TypeQ]) -> Core (Maybe TH.KindQ)
2013 -> Core [TH.ConQ] -> Core [TH.DerivClauseQ] -> DsM (Core TH.DecQ)
2014 repData (MkC cxt) (MkC nm) (MkC tvs) Nothing (MkC ksig) (MkC cons) (MkC derivs)
2015 = rep2 dataDName [cxt, nm, tvs, ksig, cons, derivs]
2016 repData (MkC cxt) (MkC nm) (MkC _) (Just (MkC tys)) (MkC ksig) (MkC cons)
2017 (MkC derivs)
2018 = rep2 dataInstDName [cxt, nm, tys, ksig, cons, derivs]
2019
2020 repNewtype :: Core TH.CxtQ -> Core TH.Name -> Core [TH.TyVarBndrQ]
2021 -> Maybe (Core [TH.TypeQ]) -> Core (Maybe TH.KindQ)
2022 -> Core TH.ConQ -> Core [TH.DerivClauseQ] -> DsM (Core TH.DecQ)
2023 repNewtype (MkC cxt) (MkC nm) (MkC tvs) Nothing (MkC ksig) (MkC con)
2024 (MkC derivs)
2025 = rep2 newtypeDName [cxt, nm, tvs, ksig, con, derivs]
2026 repNewtype (MkC cxt) (MkC nm) (MkC _) (Just (MkC tys)) (MkC ksig) (MkC con)
2027 (MkC derivs)
2028 = rep2 newtypeInstDName [cxt, nm, tys, ksig, con, derivs]
2029
2030 repTySyn :: Core TH.Name -> Core [TH.TyVarBndrQ]
2031 -> Core TH.TypeQ -> DsM (Core TH.DecQ)
2032 repTySyn (MkC nm) (MkC tvs) (MkC rhs)
2033 = rep2 tySynDName [nm, tvs, rhs]
2034
2035 repInst :: Core (Maybe TH.Overlap) ->
2036 Core TH.CxtQ -> Core TH.TypeQ -> Core [TH.DecQ] -> DsM (Core TH.DecQ)
2037 repInst (MkC o) (MkC cxt) (MkC ty) (MkC ds) = rep2 instanceWithOverlapDName
2038 [o, cxt, ty, ds]
2039
2040 repDerivStrategy :: Maybe (Located DerivStrategy)
2041 -> DsM (Core (Maybe TH.DerivStrategy))
2042 repDerivStrategy mds =
2043 case mds of
2044 Nothing -> nothing
2045 Just (L _ ds) ->
2046 case ds of
2047 StockStrategy -> just =<< dataCon stockStrategyDataConName
2048 AnyclassStrategy -> just =<< dataCon anyclassStrategyDataConName
2049 NewtypeStrategy -> just =<< dataCon newtypeStrategyDataConName
2050 where
2051 nothing = coreNothing derivStrategyTyConName
2052 just = coreJust derivStrategyTyConName
2053
2054 repOverlap :: Maybe OverlapMode -> DsM (Core (Maybe TH.Overlap))
2055 repOverlap mb =
2056 case mb of
2057 Nothing -> nothing
2058 Just o ->
2059 case o of
2060 NoOverlap _ -> nothing
2061 Overlappable _ -> just =<< dataCon overlappableDataConName
2062 Overlapping _ -> just =<< dataCon overlappingDataConName
2063 Overlaps _ -> just =<< dataCon overlapsDataConName
2064 Incoherent _ -> just =<< dataCon incoherentDataConName
2065 where
2066 nothing = coreNothing overlapTyConName
2067 just = coreJust overlapTyConName
2068
2069
2070 repClass :: Core TH.CxtQ -> Core TH.Name -> Core [TH.TyVarBndrQ]
2071 -> Core [TH.FunDep] -> Core [TH.DecQ]
2072 -> DsM (Core TH.DecQ)
2073 repClass (MkC cxt) (MkC cls) (MkC tvs) (MkC fds) (MkC ds)
2074 = rep2 classDName [cxt, cls, tvs, fds, ds]
2075
2076 repDeriv :: Core (Maybe TH.DerivStrategy)
2077 -> Core TH.CxtQ -> Core TH.TypeQ
2078 -> DsM (Core TH.DecQ)
2079 repDeriv (MkC ds) (MkC cxt) (MkC ty)
2080 = rep2 standaloneDerivWithStrategyDName [ds, cxt, ty]
2081
2082 repPragInl :: Core TH.Name -> Core TH.Inline -> Core TH.RuleMatch
2083 -> Core TH.Phases -> DsM (Core TH.DecQ)
2084 repPragInl (MkC nm) (MkC inline) (MkC rm) (MkC phases)
2085 = rep2 pragInlDName [nm, inline, rm, phases]
2086
2087 repPragSpec :: Core TH.Name -> Core TH.TypeQ -> Core TH.Phases
2088 -> DsM (Core TH.DecQ)
2089 repPragSpec (MkC nm) (MkC ty) (MkC phases)
2090 = rep2 pragSpecDName [nm, ty, phases]
2091
2092 repPragSpecInl :: Core TH.Name -> Core TH.TypeQ -> Core TH.Inline
2093 -> Core TH.Phases -> DsM (Core TH.DecQ)
2094 repPragSpecInl (MkC nm) (MkC ty) (MkC inline) (MkC phases)
2095 = rep2 pragSpecInlDName [nm, ty, inline, phases]
2096
2097 repPragSpecInst :: Core TH.TypeQ -> DsM (Core TH.DecQ)
2098 repPragSpecInst (MkC ty) = rep2 pragSpecInstDName [ty]
2099
2100 repPragComplete :: Core [TH.Name] -> Core (Maybe TH.Name) -> DsM (Core TH.DecQ)
2101 repPragComplete (MkC cls) (MkC mty) = rep2 pragCompleteDName [cls, mty]
2102
2103 repPragRule :: Core String -> Core [TH.RuleBndrQ] -> Core TH.ExpQ
2104 -> Core TH.ExpQ -> Core TH.Phases -> DsM (Core TH.DecQ)
2105 repPragRule (MkC nm) (MkC bndrs) (MkC lhs) (MkC rhs) (MkC phases)
2106 = rep2 pragRuleDName [nm, bndrs, lhs, rhs, phases]
2107
2108 repPragAnn :: Core TH.AnnTarget -> Core TH.ExpQ -> DsM (Core TH.DecQ)
2109 repPragAnn (MkC targ) (MkC e) = rep2 pragAnnDName [targ, e]
2110
2111 repTySynInst :: Core TH.Name -> Core TH.TySynEqnQ -> DsM (Core TH.DecQ)
2112 repTySynInst (MkC nm) (MkC eqn)
2113 = rep2 tySynInstDName [nm, eqn]
2114
2115 repDataFamilyD :: Core TH.Name -> Core [TH.TyVarBndrQ]
2116 -> Core (Maybe TH.KindQ) -> DsM (Core TH.DecQ)
2117 repDataFamilyD (MkC nm) (MkC tvs) (MkC kind)
2118 = rep2 dataFamilyDName [nm, tvs, kind]
2119
2120 repOpenFamilyD :: Core TH.Name
2121 -> Core [TH.TyVarBndrQ]
2122 -> Core TH.FamilyResultSigQ
2123 -> Core (Maybe TH.InjectivityAnn)
2124 -> DsM (Core TH.DecQ)
2125 repOpenFamilyD (MkC nm) (MkC tvs) (MkC result) (MkC inj)
2126 = rep2 openTypeFamilyDName [nm, tvs, result, inj]
2127
2128 repClosedFamilyD :: Core TH.Name
2129 -> Core [TH.TyVarBndrQ]
2130 -> Core TH.FamilyResultSigQ
2131 -> Core (Maybe TH.InjectivityAnn)
2132 -> Core [TH.TySynEqnQ]
2133 -> DsM (Core TH.DecQ)
2134 repClosedFamilyD (MkC nm) (MkC tvs) (MkC res) (MkC inj) (MkC eqns)
2135 = rep2 closedTypeFamilyDName [nm, tvs, res, inj, eqns]
2136
2137 repTySynEqn :: Core [TH.TypeQ] -> Core TH.TypeQ -> DsM (Core TH.TySynEqnQ)
2138 repTySynEqn (MkC lhs) (MkC rhs)
2139 = rep2 tySynEqnName [lhs, rhs]
2140
2141 repRoleAnnotD :: Core TH.Name -> Core [TH.Role] -> DsM (Core TH.DecQ)
2142 repRoleAnnotD (MkC n) (MkC roles) = rep2 roleAnnotDName [n, roles]
2143
2144 repFunDep :: Core [TH.Name] -> Core [TH.Name] -> DsM (Core TH.FunDep)
2145 repFunDep (MkC xs) (MkC ys) = rep2 funDepName [xs, ys]
2146
2147 repProto :: Name -> Core TH.Name -> Core TH.TypeQ -> DsM (Core TH.DecQ)
2148 repProto mk_sig (MkC s) (MkC ty) = rep2 mk_sig [s, ty]
2149
2150 repCtxt :: Core [TH.PredQ] -> DsM (Core TH.CxtQ)
2151 repCtxt (MkC tys) = rep2 cxtName [tys]
2152
2153 repDataCon :: Located Name
2154 -> HsConDeclDetails GhcRn
2155 -> DsM (Core TH.ConQ)
2156 repDataCon con details
2157 = do con' <- lookupLOcc con -- See Note [Binders and occurrences]
2158 repConstr details Nothing [con']
2159
2160 repGadtDataCons :: [Located Name]
2161 -> HsConDeclDetails GhcRn
2162 -> LHsType GhcRn
2163 -> DsM (Core TH.ConQ)
2164 repGadtDataCons cons details res_ty
2165 = do cons' <- mapM lookupLOcc cons -- See Note [Binders and occurrences]
2166 repConstr details (Just res_ty) cons'
2167
2168 -- Invariant:
2169 -- * for plain H98 data constructors second argument is Nothing and third
2170 -- argument is a singleton list
2171 -- * for GADTs data constructors second argument is (Just return_type) and
2172 -- third argument is a non-empty list
2173 repConstr :: HsConDeclDetails GhcRn
2174 -> Maybe (LHsType GhcRn)
2175 -> [Core TH.Name]
2176 -> DsM (Core TH.ConQ)
2177 repConstr (PrefixCon ps) Nothing [con]
2178 = do arg_tys <- repList bangTypeQTyConName repBangTy ps
2179 rep2 normalCName [unC con, unC arg_tys]
2180
2181 repConstr (PrefixCon ps) (Just (L _ res_ty)) cons
2182 = do arg_tys <- repList bangTypeQTyConName repBangTy ps
2183 res_ty' <- repTy res_ty
2184 rep2 gadtCName [ unC (nonEmptyCoreList cons), unC arg_tys, unC res_ty']
2185
2186 repConstr (RecCon (L _ ips)) resTy cons
2187 = do args <- concatMapM rep_ip ips
2188 arg_vtys <- coreList varBangTypeQTyConName args
2189 case resTy of
2190 Nothing -> rep2 recCName [unC (head cons), unC arg_vtys]
2191 Just (L _ res_ty) -> do
2192 res_ty' <- repTy res_ty
2193 rep2 recGadtCName [unC (nonEmptyCoreList cons), unC arg_vtys,
2194 unC res_ty']
2195
2196 where
2197 rep_ip (L _ ip) = mapM (rep_one_ip (cd_fld_type ip)) (cd_fld_names ip)
2198
2199 rep_one_ip :: LBangType GhcRn -> LFieldOcc GhcRn -> DsM (Core a)
2200 rep_one_ip t n = do { MkC v <- lookupOcc (selectorFieldOcc $ unLoc n)
2201 ; MkC ty <- repBangTy t
2202 ; rep2 varBangTypeName [v,ty] }
2203
2204 repConstr (InfixCon st1 st2) Nothing [con]
2205 = do arg1 <- repBangTy st1
2206 arg2 <- repBangTy st2
2207 rep2 infixCName [unC arg1, unC con, unC arg2]
2208
2209 repConstr (InfixCon {}) (Just _) _ =
2210 panic "repConstr: infix GADT constructor should be in a PrefixCon"
2211 repConstr _ _ _ =
2212 panic "repConstr: invariant violated"
2213
2214 ------------ Types -------------------
2215
2216 repTForall :: Core [TH.TyVarBndrQ] -> Core TH.CxtQ -> Core TH.TypeQ
2217 -> DsM (Core TH.TypeQ)
2218 repTForall (MkC tvars) (MkC ctxt) (MkC ty)
2219 = rep2 forallTName [tvars, ctxt, ty]
2220
2221 repTvar :: Core TH.Name -> DsM (Core TH.TypeQ)
2222 repTvar (MkC s) = rep2 varTName [s]
2223
2224 repTapp :: Core TH.TypeQ -> Core TH.TypeQ -> DsM (Core TH.TypeQ)
2225 repTapp (MkC t1) (MkC t2) = rep2 appTName [t1, t2]
2226
2227 repTapps :: Core TH.TypeQ -> [Core TH.TypeQ] -> DsM (Core TH.TypeQ)
2228 repTapps f [] = return f
2229 repTapps f (t:ts) = do { f1 <- repTapp f t; repTapps f1 ts }
2230
2231 repTSig :: Core TH.TypeQ -> Core TH.KindQ -> DsM (Core TH.TypeQ)
2232 repTSig (MkC ty) (MkC ki) = rep2 sigTName [ty, ki]
2233
2234 repTequality :: DsM (Core TH.TypeQ)
2235 repTequality = rep2 equalityTName []
2236
2237 repTPromotedList :: [Core TH.TypeQ] -> DsM (Core TH.TypeQ)
2238 repTPromotedList [] = repPromotedNilTyCon
2239 repTPromotedList (t:ts) = do { tcon <- repPromotedConsTyCon
2240 ; f <- repTapp tcon t
2241 ; t' <- repTPromotedList ts
2242 ; repTapp f t'
2243 }
2244
2245 repTLit :: Core TH.TyLitQ -> DsM (Core TH.TypeQ)
2246 repTLit (MkC lit) = rep2 litTName [lit]
2247
2248 repTWildCard :: DsM (Core TH.TypeQ)
2249 repTWildCard = rep2 wildCardTName []
2250
2251 repTStar :: DsM (Core TH.TypeQ)
2252 repTStar = rep2 starKName []
2253
2254 repTConstraint :: DsM (Core TH.TypeQ)
2255 repTConstraint = rep2 constraintKName []
2256
2257 --------- Type constructors --------------
2258
2259 repNamedTyCon :: Core TH.Name -> DsM (Core TH.TypeQ)
2260 repNamedTyCon (MkC s) = rep2 conTName [s]
2261
2262 repTupleTyCon :: Int -> DsM (Core TH.TypeQ)
2263 -- Note: not Core Int; it's easier to be direct here
2264 repTupleTyCon i = do dflags <- getDynFlags
2265 rep2 tupleTName [mkIntExprInt dflags i]
2266
2267 repUnboxedTupleTyCon :: Int -> DsM (Core TH.TypeQ)
2268 -- Note: not Core Int; it's easier to be direct here
2269 repUnboxedTupleTyCon i = do dflags <- getDynFlags
2270 rep2 unboxedTupleTName [mkIntExprInt dflags i]
2271
2272 repUnboxedSumTyCon :: TH.SumArity -> DsM (Core TH.TypeQ)
2273 -- Note: not Core TH.SumArity; it's easier to be direct here
2274 repUnboxedSumTyCon arity = do dflags <- getDynFlags
2275 rep2 unboxedSumTName [mkIntExprInt dflags arity]
2276
2277 repArrowTyCon :: DsM (Core TH.TypeQ)
2278 repArrowTyCon = rep2 arrowTName []
2279
2280 repListTyCon :: DsM (Core TH.TypeQ)
2281 repListTyCon = rep2 listTName []
2282
2283 repPromotedDataCon :: Core TH.Name -> DsM (Core TH.TypeQ)
2284 repPromotedDataCon (MkC s) = rep2 promotedTName [s]
2285
2286 repPromotedTupleTyCon :: Int -> DsM (Core TH.TypeQ)
2287 repPromotedTupleTyCon i = do dflags <- getDynFlags
2288 rep2 promotedTupleTName [mkIntExprInt dflags i]
2289
2290 repPromotedNilTyCon :: DsM (Core TH.TypeQ)
2291 repPromotedNilTyCon = rep2 promotedNilTName []
2292
2293 repPromotedConsTyCon :: DsM (Core TH.TypeQ)
2294 repPromotedConsTyCon = rep2 promotedConsTName []
2295
2296 ------------ TyVarBndrs -------------------
2297
2298 repPlainTV :: Core TH.Name -> DsM (Core TH.TyVarBndrQ)
2299 repPlainTV (MkC nm) = rep2 plainTVName [nm]
2300
2301 repKindedTV :: Core TH.Name -> Core TH.KindQ -> DsM (Core TH.TyVarBndrQ)
2302 repKindedTV (MkC nm) (MkC ki) = rep2 kindedTVName [nm, ki]
2303
2304 ----------------------------------------------------------
2305 -- Type family result signature
2306
2307 repNoSig :: DsM (Core TH.FamilyResultSigQ)
2308 repNoSig = rep2 noSigName []
2309
2310 repKindSig :: Core TH.KindQ -> DsM (Core TH.FamilyResultSigQ)
2311 repKindSig (MkC ki) = rep2 kindSigName [ki]
2312
2313 repTyVarSig :: Core TH.TyVarBndrQ -> DsM (Core TH.FamilyResultSigQ)
2314 repTyVarSig (MkC bndr) = rep2 tyVarSigName [bndr]
2315
2316 ----------------------------------------------------------
2317 -- Literals
2318
2319 repLiteral :: HsLit GhcRn -> DsM (Core TH.Lit)
2320 repLiteral (HsStringPrim _ bs)
2321 = do dflags <- getDynFlags
2322 word8_ty <- lookupType word8TyConName
2323 let w8s = unpack bs
2324 w8s_expr = map (\w8 -> mkCoreConApps word8DataCon
2325 [mkWordLit dflags (toInteger w8)]) w8s
2326 rep2 stringPrimLName [mkListExpr word8_ty w8s_expr]
2327 repLiteral lit
2328 = do lit' <- case lit of
2329 HsIntPrim _ i -> mk_integer i
2330 HsWordPrim _ w -> mk_integer w
2331 HsInt _ i -> mk_integer (il_value i)
2332 HsFloatPrim _ r -> mk_rational r
2333 HsDoublePrim _ r -> mk_rational r
2334 HsCharPrim _ c -> mk_char c
2335 _ -> return lit
2336 lit_expr <- dsLit lit'
2337 case mb_lit_name of
2338 Just lit_name -> rep2 lit_name [lit_expr]
2339 Nothing -> notHandled "Exotic literal" (ppr lit)
2340 where
2341 mb_lit_name = case lit of
2342 HsInteger _ _ _ -> Just integerLName
2343 HsInt _ _ -> Just integerLName
2344 HsIntPrim _ _ -> Just intPrimLName
2345 HsWordPrim _ _ -> Just wordPrimLName
2346 HsFloatPrim _ _ -> Just floatPrimLName
2347 HsDoublePrim _ _ -> Just doublePrimLName
2348 HsChar _ _ -> Just charLName
2349 HsCharPrim _ _ -> Just charPrimLName
2350 HsString _ _ -> Just stringLName
2351 HsRat _ _ _ -> Just rationalLName
2352 _ -> Nothing
2353
2354 mk_integer :: Integer -> DsM (HsLit GhcRn)
2355 mk_integer i = do integer_ty <- lookupType integerTyConName
2356 return $ HsInteger noSourceText i integer_ty
2357
2358 mk_rational :: FractionalLit -> DsM (HsLit GhcRn)
2359 mk_rational r = do rat_ty <- lookupType rationalTyConName
2360 return $ HsRat def r rat_ty
2361 mk_string :: FastString -> DsM (HsLit GhcRn)
2362 mk_string s = return $ HsString noSourceText s
2363
2364 mk_char :: Char -> DsM (HsLit GhcRn)
2365 mk_char c = return $ HsChar noSourceText c
2366
2367 repOverloadedLiteral :: HsOverLit GhcRn -> DsM (Core TH.Lit)
2368 repOverloadedLiteral (OverLit { ol_val = val})
2369 = do { lit <- mk_lit val; repLiteral lit }
2370 -- The type Rational will be in the environment, because
2371 -- the smart constructor 'TH.Syntax.rationalL' uses it in its type,
2372 -- and rationalL is sucked in when any TH stuff is used
2373
2374 mk_lit :: OverLitVal -> DsM (HsLit GhcRn)
2375 mk_lit (HsIntegral i) = mk_integer (il_value i)
2376 mk_lit (HsFractional f) = mk_rational f
2377 mk_lit (HsIsString _ s) = mk_string s
2378
2379 repNameS :: Core String -> DsM (Core TH.Name)
2380 repNameS (MkC name) = rep2 mkNameSName [name]
2381
2382 --------------- Miscellaneous -------------------
2383
2384 repGensym :: Core String -> DsM (Core (TH.Q TH.Name))
2385 repGensym (MkC lit_str) = rep2 newNameName [lit_str]
2386
2387 repBindQ :: Type -> Type -- a and b
2388 -> Core (TH.Q a) -> Core (a -> TH.Q b) -> DsM (Core (TH.Q b))
2389 repBindQ ty_a ty_b (MkC x) (MkC y)
2390 = rep2 bindQName [Type ty_a, Type ty_b, x, y]
2391
2392 repSequenceQ :: Type -> Core [TH.Q a] -> DsM (Core (TH.Q [a]))
2393 repSequenceQ ty_a (MkC list)
2394 = rep2 sequenceQName [Type ty_a, list]
2395
2396 repUnboundVar :: Core TH.Name -> DsM (Core TH.ExpQ)
2397 repUnboundVar (MkC name) = rep2 unboundVarEName [name]
2398
2399 repOverLabel :: FastString -> DsM (Core TH.ExpQ)
2400 repOverLabel fs = do
2401 (MkC s) <- coreStringLit $ unpackFS fs
2402 rep2 labelEName [s]
2403
2404
2405 ------------ Lists -------------------
2406 -- turn a list of patterns into a single pattern matching a list
2407
2408 repList :: Name -> (a -> DsM (Core b))
2409 -> [a] -> DsM (Core [b])
2410 repList tc_name f args
2411 = do { args1 <- mapM f args
2412 ; coreList tc_name args1 }
2413
2414 coreList :: Name -- Of the TyCon of the element type
2415 -> [Core a] -> DsM (Core [a])
2416 coreList tc_name es
2417 = do { elt_ty <- lookupType tc_name; return (coreList' elt_ty es) }
2418
2419 coreList' :: Type -- The element type
2420 -> [Core a] -> Core [a]
2421 coreList' elt_ty es = MkC (mkListExpr elt_ty (map unC es ))
2422
2423 nonEmptyCoreList :: [Core a] -> Core [a]
2424 -- The list must be non-empty so we can get the element type
2425 -- Otherwise use coreList
2426 nonEmptyCoreList [] = panic "coreList: empty argument"
2427 nonEmptyCoreList xs@(MkC x:_) = MkC (mkListExpr (exprType x) (map unC xs))
2428
2429 coreStringLit :: String -> DsM (Core String)
2430 coreStringLit s = do { z <- mkStringExpr s; return(MkC z) }
2431
2432 ------------------- Maybe ------------------
2433
2434 -- | Construct Core expression for Nothing of a given type name
2435 coreNothing :: Name -- ^ Name of the TyCon of the element type
2436 -> DsM (Core (Maybe a))
2437 coreNothing tc_name =
2438 do { elt_ty <- lookupType tc_name; return (coreNothing' elt_ty) }
2439
2440 -- | Construct Core expression for Nothing of a given type
2441 coreNothing' :: Type -- ^ The element type
2442 -> Core (Maybe a)
2443 coreNothing' elt_ty = MkC (mkNothingExpr elt_ty)
2444
2445 -- | Store given Core expression in a Just of a given type name
2446 coreJust :: Name -- ^ Name of the TyCon of the element type
2447 -> Core a -> DsM (Core (Maybe a))
2448 coreJust tc_name es
2449 = do { elt_ty <- lookupType tc_name; return (coreJust' elt_ty es) }
2450
2451 -- | Store given Core expression in a Just of a given type
2452 coreJust' :: Type -- ^ The element type
2453 -> Core a -> Core (Maybe a)
2454 coreJust' elt_ty es = MkC (mkJustExpr elt_ty (unC es))
2455
2456 ------------ Literals & Variables -------------------
2457
2458 coreIntLit :: Int -> DsM (Core Int)
2459 coreIntLit i = do dflags <- getDynFlags
2460 return (MkC (mkIntExprInt dflags i))
2461
2462 coreVar :: Id -> Core TH.Name -- The Id has type Name
2463 coreVar id = MkC (Var id)
2464
2465 ----------------- Failure -----------------------
2466 notHandledL :: SrcSpan -> String -> SDoc -> DsM a
2467 notHandledL loc what doc
2468 | isGoodSrcSpan loc
2469 = putSrcSpanDs loc $ notHandled what doc
2470 | otherwise
2471 = notHandled what doc
2472
2473 notHandled :: String -> SDoc -> DsM a
2474 notHandled what doc = failWithDs msg
2475 where
2476 msg = hang (text what <+> text "not (yet) handled by Template Haskell")
2477 2 doc