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