Improve the desugaring of -XStrict
[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 _ [p] _ (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 _ ps _ (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 _ [] _
1443 (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 _ ps _ (GRHSs [L _ (GRHS [] e)] (L _ EmptyLocalBinds))))
1585 = do { let bndrs = collectPatsBinders ps ;
1586 ; ss <- mkGenSyms bndrs
1587 ; lam <- addBinds ss (
1588 do { xs <- repLPs ps; body <- repLE e; repLam xs body })
1589 ; wrapGenSyms ss lam }
1590
1591 repLambda (L _ m) = notHandled "Guarded labmdas" (pprMatch m)
1592
1593
1594 -----------------------------------------------------------------------------
1595 -- Patterns
1596 -- repP deals with patterns. It assumes that we have already
1597 -- walked over the pattern(s) once to collect the binders, and
1598 -- have extended the environment. So every pattern-bound
1599 -- variable should already appear in the environment.
1600
1601 -- Process a list of patterns
1602 repLPs :: [LPat GhcRn] -> DsM (Core [TH.PatQ])
1603 repLPs ps = repList patQTyConName repLP ps
1604
1605 repLP :: LPat GhcRn -> DsM (Core TH.PatQ)
1606 repLP (L _ p) = repP p
1607
1608 repP :: Pat GhcRn -> DsM (Core TH.PatQ)
1609 repP (WildPat _) = repPwild
1610 repP (LitPat l) = do { l2 <- repLiteral l; repPlit l2 }
1611 repP (VarPat (L _ x)) = do { x' <- lookupBinder x; repPvar x' }
1612 repP (LazyPat p) = do { p1 <- repLP p; repPtilde p1 }
1613 repP (BangPat p) = do { p1 <- repLP p; repPbang p1 }
1614 repP (AsPat x p) = do { x' <- lookupLBinder x; p1 <- repLP p; repPaspat x' p1 }
1615 repP (ParPat p) = repLP p
1616 repP (ListPat ps _ Nothing) = do { qs <- repLPs ps; repPlist qs }
1617 repP (ListPat ps ty1 (Just (_,e))) = do { p <- repP (ListPat ps ty1 Nothing); e' <- repE (syn_expr e); repPview e' p}
1618 repP (TuplePat ps boxed _)
1619 | isBoxed boxed = do { qs <- repLPs ps; repPtup qs }
1620 | otherwise = do { qs <- repLPs ps; repPunboxedTup qs }
1621 repP (SumPat p alt arity _) = do { p1 <- repLP p; repPunboxedSum p1 alt arity }
1622 repP (ConPatIn dc details)
1623 = do { con_str <- lookupLOcc dc
1624 ; case details of
1625 PrefixCon ps -> do { qs <- repLPs ps; repPcon con_str qs }
1626 RecCon rec -> do { fps <- repList fieldPatQTyConName rep_fld (rec_flds rec)
1627 ; repPrec con_str fps }
1628 InfixCon p1 p2 -> do { p1' <- repLP p1;
1629 p2' <- repLP p2;
1630 repPinfix p1' con_str p2' }
1631 }
1632 where
1633 rep_fld :: LHsRecField GhcRn (LPat GhcRn) -> DsM (Core (TH.Name,TH.PatQ))
1634 rep_fld (L _ fld) = do { MkC v <- lookupLOcc (hsRecFieldSel fld)
1635 ; MkC p <- repLP (hsRecFieldArg fld)
1636 ; rep2 fieldPatName [v,p] }
1637
1638 repP (NPat (L _ l) Nothing _ _) = do { a <- repOverloadedLiteral l; repPlit a }
1639 repP (ViewPat e p _) = do { e' <- repLE e; p' <- repLP p; repPview e' p' }
1640 repP p@(NPat _ (Just _) _ _) = notHandled "Negative overloaded patterns" (ppr p)
1641 repP (SigPatIn p t) = do { p' <- repLP p
1642 ; t' <- repLTy (hsSigWcType t)
1643 ; repPsig p' t' }
1644 repP (SplicePat splice) = repSplice splice
1645
1646 repP other = notHandled "Exotic pattern" (ppr other)
1647
1648 ----------------------------------------------------------
1649 -- Declaration ordering helpers
1650
1651 sort_by_loc :: [(SrcSpan, a)] -> [(SrcSpan, a)]
1652 sort_by_loc xs = sortBy comp xs
1653 where comp x y = compare (fst x) (fst y)
1654
1655 de_loc :: [(a, b)] -> [b]
1656 de_loc = map snd
1657
1658 ----------------------------------------------------------
1659 -- The meta-environment
1660
1661 -- A name/identifier association for fresh names of locally bound entities
1662 type GenSymBind = (Name, Id) -- Gensym the string and bind it to the Id
1663 -- I.e. (x, x_id) means
1664 -- let x_id = gensym "x" in ...
1665
1666 -- Generate a fresh name for a locally bound entity
1667
1668 mkGenSyms :: [Name] -> DsM [GenSymBind]
1669 -- We can use the existing name. For example:
1670 -- [| \x_77 -> x_77 + x_77 |]
1671 -- desugars to
1672 -- do { x_77 <- genSym "x"; .... }
1673 -- We use the same x_77 in the desugared program, but with the type Bndr
1674 -- instead of Int
1675 --
1676 -- We do make it an Internal name, though (hence localiseName)
1677 --
1678 -- Nevertheless, it's monadic because we have to generate nameTy
1679 mkGenSyms ns = do { var_ty <- lookupType nameTyConName
1680 ; return [(nm, mkLocalId (localiseName nm) var_ty) | nm <- ns] }
1681
1682
1683 addBinds :: [GenSymBind] -> DsM a -> DsM a
1684 -- Add a list of fresh names for locally bound entities to the
1685 -- meta environment (which is part of the state carried around
1686 -- by the desugarer monad)
1687 addBinds bs m = dsExtendMetaEnv (mkNameEnv [(n,DsBound id) | (n,id) <- bs]) m
1688
1689 -- Look up a locally bound name
1690 --
1691 lookupLBinder :: Located Name -> DsM (Core TH.Name)
1692 lookupLBinder (L _ n) = lookupBinder n
1693
1694 lookupBinder :: Name -> DsM (Core TH.Name)
1695 lookupBinder = lookupOcc
1696 -- Binders are brought into scope before the pattern or what-not is
1697 -- desugared. Moreover, in instance declaration the binder of a method
1698 -- will be the selector Id and hence a global; so we need the
1699 -- globalVar case of lookupOcc
1700
1701 -- Look up a name that is either locally bound or a global name
1702 --
1703 -- * If it is a global name, generate the "original name" representation (ie,
1704 -- the <module>:<name> form) for the associated entity
1705 --
1706 lookupLOcc :: Located Name -> DsM (Core TH.Name)
1707 -- Lookup an occurrence; it can't be a splice.
1708 -- Use the in-scope bindings if they exist
1709 lookupLOcc (L _ n) = lookupOcc n
1710
1711 lookupOcc :: Name -> DsM (Core TH.Name)
1712 lookupOcc n
1713 = do { mb_val <- dsLookupMetaEnv n ;
1714 case mb_val of
1715 Nothing -> globalVar n
1716 Just (DsBound x) -> return (coreVar x)
1717 Just (DsSplice _) -> pprPanic "repE:lookupOcc" (ppr n)
1718 }
1719
1720 globalVar :: Name -> DsM (Core TH.Name)
1721 -- Not bound by the meta-env
1722 -- Could be top-level; or could be local
1723 -- f x = $(g [| x |])
1724 -- Here the x will be local
1725 globalVar name
1726 | isExternalName name
1727 = do { MkC mod <- coreStringLit name_mod
1728 ; MkC pkg <- coreStringLit name_pkg
1729 ; MkC occ <- nameLit name
1730 ; rep2 mk_varg [pkg,mod,occ] }
1731 | otherwise
1732 = do { MkC occ <- nameLit name
1733 ; MkC uni <- coreIntLit (getKey (getUnique name))
1734 ; rep2 mkNameLName [occ,uni] }
1735 where
1736 mod = ASSERT( isExternalName name) nameModule name
1737 name_mod = moduleNameString (moduleName mod)
1738 name_pkg = unitIdString (moduleUnitId mod)
1739 name_occ = nameOccName name
1740 mk_varg | OccName.isDataOcc name_occ = mkNameG_dName
1741 | OccName.isVarOcc name_occ = mkNameG_vName
1742 | OccName.isTcOcc name_occ = mkNameG_tcName
1743 | otherwise = pprPanic "DsMeta.globalVar" (ppr name)
1744
1745 lookupType :: Name -- Name of type constructor (e.g. TH.ExpQ)
1746 -> DsM Type -- The type
1747 lookupType tc_name = do { tc <- dsLookupTyCon tc_name ;
1748 return (mkTyConApp tc []) }
1749
1750 wrapGenSyms :: [GenSymBind]
1751 -> Core (TH.Q a) -> DsM (Core (TH.Q a))
1752 -- wrapGenSyms [(nm1,id1), (nm2,id2)] y
1753 -- --> bindQ (gensym nm1) (\ id1 ->
1754 -- bindQ (gensym nm2 (\ id2 ->
1755 -- y))
1756
1757 wrapGenSyms binds body@(MkC b)
1758 = do { var_ty <- lookupType nameTyConName
1759 ; go var_ty binds }
1760 where
1761 [elt_ty] = tcTyConAppArgs (exprType b)
1762 -- b :: Q a, so we can get the type 'a' by looking at the
1763 -- argument type. NB: this relies on Q being a data/newtype,
1764 -- not a type synonym
1765
1766 go _ [] = return body
1767 go var_ty ((name,id) : binds)
1768 = do { MkC body' <- go var_ty binds
1769 ; lit_str <- nameLit name
1770 ; gensym_app <- repGensym lit_str
1771 ; repBindQ var_ty elt_ty
1772 gensym_app (MkC (Lam id body')) }
1773
1774 nameLit :: Name -> DsM (Core String)
1775 nameLit n = coreStringLit (occNameString (nameOccName n))
1776
1777 occNameLit :: OccName -> DsM (Core String)
1778 occNameLit name = coreStringLit (occNameString name)
1779
1780
1781 -- %*********************************************************************
1782 -- %* *
1783 -- Constructing code
1784 -- %* *
1785 -- %*********************************************************************
1786
1787 -----------------------------------------------------------------------------
1788 -- PHANTOM TYPES for consistency. In order to make sure we do this correct
1789 -- we invent a new datatype which uses phantom types.
1790
1791 newtype Core a = MkC CoreExpr
1792 unC :: Core a -> CoreExpr
1793 unC (MkC x) = x
1794
1795 rep2 :: Name -> [ CoreExpr ] -> DsM (Core a)
1796 rep2 n xs = do { id <- dsLookupGlobalId n
1797 ; return (MkC (foldl App (Var id) xs)) }
1798
1799 dataCon' :: Name -> [CoreExpr] -> DsM (Core a)
1800 dataCon' n args = do { id <- dsLookupDataCon n
1801 ; return $ MkC $ mkCoreConApps id args }
1802
1803 dataCon :: Name -> DsM (Core a)
1804 dataCon n = dataCon' n []
1805
1806
1807 -- %*********************************************************************
1808 -- %* *
1809 -- The 'smart constructors'
1810 -- %* *
1811 -- %*********************************************************************
1812
1813 --------------- Patterns -----------------
1814 repPlit :: Core TH.Lit -> DsM (Core TH.PatQ)
1815 repPlit (MkC l) = rep2 litPName [l]
1816
1817 repPvar :: Core TH.Name -> DsM (Core TH.PatQ)
1818 repPvar (MkC s) = rep2 varPName [s]
1819
1820 repPtup :: Core [TH.PatQ] -> DsM (Core TH.PatQ)
1821 repPtup (MkC ps) = rep2 tupPName [ps]
1822
1823 repPunboxedTup :: Core [TH.PatQ] -> DsM (Core TH.PatQ)
1824 repPunboxedTup (MkC ps) = rep2 unboxedTupPName [ps]
1825
1826 repPunboxedSum :: Core TH.PatQ -> TH.SumAlt -> TH.SumArity -> DsM (Core TH.PatQ)
1827 -- Note: not Core TH.SumAlt or Core TH.SumArity; it's easier to be direct here
1828 repPunboxedSum (MkC p) alt arity
1829 = do { dflags <- getDynFlags
1830 ; rep2 unboxedSumPName [ p
1831 , mkIntExprInt dflags alt
1832 , mkIntExprInt dflags arity ] }
1833
1834 repPcon :: Core TH.Name -> Core [TH.PatQ] -> DsM (Core TH.PatQ)
1835 repPcon (MkC s) (MkC ps) = rep2 conPName [s, ps]
1836
1837 repPrec :: Core TH.Name -> Core [(TH.Name,TH.PatQ)] -> DsM (Core TH.PatQ)
1838 repPrec (MkC c) (MkC rps) = rep2 recPName [c,rps]
1839
1840 repPinfix :: Core TH.PatQ -> Core TH.Name -> Core TH.PatQ -> DsM (Core TH.PatQ)
1841 repPinfix (MkC p1) (MkC n) (MkC p2) = rep2 infixPName [p1, n, p2]
1842
1843 repPtilde :: Core TH.PatQ -> DsM (Core TH.PatQ)
1844 repPtilde (MkC p) = rep2 tildePName [p]
1845
1846 repPbang :: Core TH.PatQ -> DsM (Core TH.PatQ)
1847 repPbang (MkC p) = rep2 bangPName [p]
1848
1849 repPaspat :: Core TH.Name -> Core TH.PatQ -> DsM (Core TH.PatQ)
1850 repPaspat (MkC s) (MkC p) = rep2 asPName [s, p]
1851
1852 repPwild :: DsM (Core TH.PatQ)
1853 repPwild = rep2 wildPName []
1854
1855 repPlist :: Core [TH.PatQ] -> DsM (Core TH.PatQ)
1856 repPlist (MkC ps) = rep2 listPName [ps]
1857
1858 repPview :: Core TH.ExpQ -> Core TH.PatQ -> DsM (Core TH.PatQ)
1859 repPview (MkC e) (MkC p) = rep2 viewPName [e,p]
1860
1861 repPsig :: Core TH.PatQ -> Core TH.TypeQ -> DsM (Core TH.PatQ)
1862 repPsig (MkC p) (MkC t) = rep2 sigPName [p, t]
1863
1864 --------------- Expressions -----------------
1865 repVarOrCon :: Name -> Core TH.Name -> DsM (Core TH.ExpQ)
1866 repVarOrCon vc str | isDataOcc (nameOccName vc) = repCon str
1867 | otherwise = repVar str
1868
1869 repVar :: Core TH.Name -> DsM (Core TH.ExpQ)
1870 repVar (MkC s) = rep2 varEName [s]
1871
1872 repCon :: Core TH.Name -> DsM (Core TH.ExpQ)
1873 repCon (MkC s) = rep2 conEName [s]
1874
1875 repLit :: Core TH.Lit -> DsM (Core TH.ExpQ)
1876 repLit (MkC c) = rep2 litEName [c]
1877
1878 repApp :: Core TH.ExpQ -> Core TH.ExpQ -> DsM (Core TH.ExpQ)
1879 repApp (MkC x) (MkC y) = rep2 appEName [x,y]
1880
1881 repAppType :: Core TH.ExpQ -> Core TH.TypeQ -> DsM (Core TH.ExpQ)
1882 repAppType (MkC x) (MkC y) = rep2 appTypeEName [x,y]
1883
1884 repLam :: Core [TH.PatQ] -> Core TH.ExpQ -> DsM (Core TH.ExpQ)
1885 repLam (MkC ps) (MkC e) = rep2 lamEName [ps, e]
1886
1887 repLamCase :: Core [TH.MatchQ] -> DsM (Core TH.ExpQ)
1888 repLamCase (MkC ms) = rep2 lamCaseEName [ms]
1889
1890 repTup :: Core [TH.ExpQ] -> DsM (Core TH.ExpQ)
1891 repTup (MkC es) = rep2 tupEName [es]
1892
1893 repUnboxedTup :: Core [TH.ExpQ] -> DsM (Core TH.ExpQ)
1894 repUnboxedTup (MkC es) = rep2 unboxedTupEName [es]
1895
1896 repUnboxedSum :: Core TH.ExpQ -> TH.SumAlt -> TH.SumArity -> DsM (Core TH.ExpQ)
1897 -- Note: not Core TH.SumAlt or Core TH.SumArity; it's easier to be direct here
1898 repUnboxedSum (MkC e) alt arity
1899 = do { dflags <- getDynFlags
1900 ; rep2 unboxedSumEName [ e
1901 , mkIntExprInt dflags alt
1902 , mkIntExprInt dflags arity ] }
1903
1904 repCond :: Core TH.ExpQ -> Core TH.ExpQ -> Core TH.ExpQ -> DsM (Core TH.ExpQ)
1905 repCond (MkC x) (MkC y) (MkC z) = rep2 condEName [x,y,z]
1906
1907 repMultiIf :: Core [TH.Q (TH.Guard, TH.Exp)] -> DsM (Core TH.ExpQ)
1908 repMultiIf (MkC alts) = rep2 multiIfEName [alts]
1909
1910 repLetE :: Core [TH.DecQ] -> Core TH.ExpQ -> DsM (Core TH.ExpQ)
1911 repLetE (MkC ds) (MkC e) = rep2 letEName [ds, e]
1912
1913 repCaseE :: Core TH.ExpQ -> Core [TH.MatchQ] -> DsM( Core TH.ExpQ)
1914 repCaseE (MkC e) (MkC ms) = rep2 caseEName [e, ms]
1915
1916 repDoE :: Core [TH.StmtQ] -> DsM (Core TH.ExpQ)
1917 repDoE (MkC ss) = rep2 doEName [ss]
1918
1919 repComp :: Core [TH.StmtQ] -> DsM (Core TH.ExpQ)
1920 repComp (MkC ss) = rep2 compEName [ss]
1921
1922 repListExp :: Core [TH.ExpQ] -> DsM (Core TH.ExpQ)
1923 repListExp (MkC es) = rep2 listEName [es]
1924
1925 repSigExp :: Core TH.ExpQ -> Core TH.TypeQ -> DsM (Core TH.ExpQ)
1926 repSigExp (MkC e) (MkC t) = rep2 sigEName [e,t]
1927
1928 repRecCon :: Core TH.Name -> Core [TH.Q TH.FieldExp]-> DsM (Core TH.ExpQ)
1929 repRecCon (MkC c) (MkC fs) = rep2 recConEName [c,fs]
1930
1931 repRecUpd :: Core TH.ExpQ -> Core [TH.Q TH.FieldExp] -> DsM (Core TH.ExpQ)
1932 repRecUpd (MkC e) (MkC fs) = rep2 recUpdEName [e,fs]
1933
1934 repFieldExp :: Core TH.Name -> Core TH.ExpQ -> DsM (Core (TH.Q TH.FieldExp))
1935 repFieldExp (MkC n) (MkC x) = rep2 fieldExpName [n,x]
1936
1937 repInfixApp :: Core TH.ExpQ -> Core TH.ExpQ -> Core TH.ExpQ -> DsM (Core TH.ExpQ)
1938 repInfixApp (MkC x) (MkC y) (MkC z) = rep2 infixAppName [x,y,z]
1939
1940 repSectionL :: Core TH.ExpQ -> Core TH.ExpQ -> DsM (Core TH.ExpQ)
1941 repSectionL (MkC x) (MkC y) = rep2 sectionLName [x,y]
1942
1943 repSectionR :: Core TH.ExpQ -> Core TH.ExpQ -> DsM (Core TH.ExpQ)
1944 repSectionR (MkC x) (MkC y) = rep2 sectionRName [x,y]
1945
1946 ------------ Right hand sides (guarded expressions) ----
1947 repGuarded :: Core [TH.Q (TH.Guard, TH.Exp)] -> DsM (Core TH.BodyQ)
1948 repGuarded (MkC pairs) = rep2 guardedBName [pairs]
1949
1950 repNormal :: Core TH.ExpQ -> DsM (Core TH.BodyQ)
1951 repNormal (MkC e) = rep2 normalBName [e]
1952
1953 ------------ Guards ----
1954 repLNormalGE :: LHsExpr GhcRn -> LHsExpr GhcRn
1955 -> DsM (Core (TH.Q (TH.Guard, TH.Exp)))
1956 repLNormalGE g e = do g' <- repLE g
1957 e' <- repLE e
1958 repNormalGE g' e'
1959
1960 repNormalGE :: Core TH.ExpQ -> Core TH.ExpQ -> DsM (Core (TH.Q (TH.Guard, TH.Exp)))
1961 repNormalGE (MkC g) (MkC e) = rep2 normalGEName [g, e]
1962
1963 repPatGE :: Core [TH.StmtQ] -> Core TH.ExpQ -> DsM (Core (TH.Q (TH.Guard, TH.Exp)))
1964 repPatGE (MkC ss) (MkC e) = rep2 patGEName [ss, e]
1965
1966 ------------- Stmts -------------------
1967 repBindSt :: Core TH.PatQ -> Core TH.ExpQ -> DsM (Core TH.StmtQ)
1968 repBindSt (MkC p) (MkC e) = rep2 bindSName [p,e]
1969
1970 repLetSt :: Core [TH.DecQ] -> DsM (Core TH.StmtQ)
1971 repLetSt (MkC ds) = rep2 letSName [ds]
1972
1973 repNoBindSt :: Core TH.ExpQ -> DsM (Core TH.StmtQ)
1974 repNoBindSt (MkC e) = rep2 noBindSName [e]
1975
1976 repParSt :: Core [[TH.StmtQ]] -> DsM (Core TH.StmtQ)
1977 repParSt (MkC sss) = rep2 parSName [sss]
1978
1979 -------------- Range (Arithmetic sequences) -----------
1980 repFrom :: Core TH.ExpQ -> DsM (Core TH.ExpQ)
1981 repFrom (MkC x) = rep2 fromEName [x]
1982
1983 repFromThen :: Core TH.ExpQ -> Core TH.ExpQ -> DsM (Core TH.ExpQ)
1984 repFromThen (MkC x) (MkC y) = rep2 fromThenEName [x,y]
1985
1986 repFromTo :: Core TH.ExpQ -> Core TH.ExpQ -> DsM (Core TH.ExpQ)
1987 repFromTo (MkC x) (MkC y) = rep2 fromToEName [x,y]
1988
1989 repFromThenTo :: Core TH.ExpQ -> Core TH.ExpQ -> Core TH.ExpQ -> DsM (Core TH.ExpQ)
1990 repFromThenTo (MkC x) (MkC y) (MkC z) = rep2 fromThenToEName [x,y,z]
1991
1992 ------------ Match and Clause Tuples -----------
1993 repMatch :: Core TH.PatQ -> Core TH.BodyQ -> Core [TH.DecQ] -> DsM (Core TH.MatchQ)
1994 repMatch (MkC p) (MkC bod) (MkC ds) = rep2 matchName [p, bod, ds]
1995
1996 repClause :: Core [TH.PatQ] -> Core TH.BodyQ -> Core [TH.DecQ] -> DsM (Core TH.ClauseQ)
1997 repClause (MkC ps) (MkC bod) (MkC ds) = rep2 clauseName [ps, bod, ds]
1998
1999 -------------- Dec -----------------------------
2000 repVal :: Core TH.PatQ -> Core TH.BodyQ -> Core [TH.DecQ] -> DsM (Core TH.DecQ)
2001 repVal (MkC p) (MkC b) (MkC ds) = rep2 valDName [p, b, ds]
2002
2003 repFun :: Core TH.Name -> Core [TH.ClauseQ] -> DsM (Core TH.DecQ)
2004 repFun (MkC nm) (MkC b) = rep2 funDName [nm, b]
2005
2006 repData :: Core TH.CxtQ -> Core TH.Name -> Core [TH.TyVarBndrQ]
2007 -> Maybe (Core [TH.TypeQ]) -> Core (Maybe TH.KindQ)
2008 -> Core [TH.ConQ] -> Core [TH.DerivClauseQ] -> DsM (Core TH.DecQ)
2009 repData (MkC cxt) (MkC nm) (MkC tvs) Nothing (MkC ksig) (MkC cons) (MkC derivs)
2010 = rep2 dataDName [cxt, nm, tvs, ksig, cons, derivs]
2011 repData (MkC cxt) (MkC nm) (MkC _) (Just (MkC tys)) (MkC ksig) (MkC cons)
2012 (MkC derivs)
2013 = rep2 dataInstDName [cxt, nm, tys, ksig, cons, derivs]
2014
2015 repNewtype :: Core TH.CxtQ -> Core TH.Name -> Core [TH.TyVarBndrQ]
2016 -> Maybe (Core [TH.TypeQ]) -> Core (Maybe TH.KindQ)
2017 -> Core TH.ConQ -> Core [TH.DerivClauseQ] -> DsM (Core TH.DecQ)
2018 repNewtype (MkC cxt) (MkC nm) (MkC tvs) Nothing (MkC ksig) (MkC con)
2019 (MkC derivs)
2020 = rep2 newtypeDName [cxt, nm, tvs, ksig, con, derivs]
2021 repNewtype (MkC cxt) (MkC nm) (MkC _) (Just (MkC tys)) (MkC ksig) (MkC con)
2022 (MkC derivs)
2023 = rep2 newtypeInstDName [cxt, nm, tys, ksig, con, derivs]
2024
2025 repTySyn :: Core TH.Name -> Core [TH.TyVarBndrQ]
2026 -> Core TH.TypeQ -> DsM (Core TH.DecQ)
2027 repTySyn (MkC nm) (MkC tvs) (MkC rhs)
2028 = rep2 tySynDName [nm, tvs, rhs]
2029
2030 repInst :: Core (Maybe TH.Overlap) ->
2031 Core TH.CxtQ -> Core TH.TypeQ -> Core [TH.DecQ] -> DsM (Core TH.DecQ)
2032 repInst (MkC o) (MkC cxt) (MkC ty) (MkC ds) = rep2 instanceWithOverlapDName
2033 [o, cxt, ty, ds]
2034
2035 repDerivStrategy :: Maybe (Located DerivStrategy)
2036 -> DsM (Core (Maybe TH.DerivStrategy))
2037 repDerivStrategy mds =
2038 case mds of
2039 Nothing -> nothing
2040 Just (L _ ds) ->
2041 case ds of
2042 StockStrategy -> just =<< dataCon stockStrategyDataConName
2043 AnyclassStrategy -> just =<< dataCon anyclassStrategyDataConName
2044 NewtypeStrategy -> just =<< dataCon newtypeStrategyDataConName
2045 where
2046 nothing = coreNothing derivStrategyTyConName
2047 just = coreJust derivStrategyTyConName
2048
2049 repOverlap :: Maybe OverlapMode -> DsM (Core (Maybe TH.Overlap))
2050 repOverlap mb =
2051 case mb of
2052 Nothing -> nothing
2053 Just o ->
2054 case o of
2055 NoOverlap _ -> nothing
2056 Overlappable _ -> just =<< dataCon overlappableDataConName
2057 Overlapping _ -> just =<< dataCon overlappingDataConName
2058 Overlaps _ -> just =<< dataCon overlapsDataConName
2059 Incoherent _ -> just =<< dataCon incoherentDataConName
2060 where
2061 nothing = coreNothing overlapTyConName
2062 just = coreJust overlapTyConName
2063
2064
2065 repClass :: Core TH.CxtQ -> Core TH.Name -> Core [TH.TyVarBndrQ]
2066 -> Core [TH.FunDep] -> Core [TH.DecQ]
2067 -> DsM (Core TH.DecQ)
2068 repClass (MkC cxt) (MkC cls) (MkC tvs) (MkC fds) (MkC ds)
2069 = rep2 classDName [cxt, cls, tvs, fds, ds]
2070
2071 repDeriv :: Core (Maybe TH.DerivStrategy)
2072 -> Core TH.CxtQ -> Core TH.TypeQ
2073 -> DsM (Core TH.DecQ)
2074 repDeriv (MkC ds) (MkC cxt) (MkC ty)
2075 = rep2 standaloneDerivWithStrategyDName [ds, cxt, ty]
2076
2077 repPragInl :: Core TH.Name -> Core TH.Inline -> Core TH.RuleMatch
2078 -> Core TH.Phases -> DsM (Core TH.DecQ)
2079 repPragInl (MkC nm) (MkC inline) (MkC rm) (MkC phases)
2080 = rep2 pragInlDName [nm, inline, rm, phases]
2081
2082 repPragSpec :: Core TH.Name -> Core TH.TypeQ -> Core TH.Phases
2083 -> DsM (Core TH.DecQ)
2084 repPragSpec (MkC nm) (MkC ty) (MkC phases)
2085 = rep2 pragSpecDName [nm, ty, phases]
2086
2087 repPragSpecInl :: Core TH.Name -> Core TH.TypeQ -> Core TH.Inline
2088 -> Core TH.Phases -> DsM (Core TH.DecQ)
2089 repPragSpecInl (MkC nm) (MkC ty) (MkC inline) (MkC phases)
2090 = rep2 pragSpecInlDName [nm, ty, inline, phases]
2091
2092 repPragSpecInst :: Core TH.TypeQ -> DsM (Core TH.DecQ)
2093 repPragSpecInst (MkC ty) = rep2 pragSpecInstDName [ty]
2094
2095 repPragComplete :: Core [TH.Name] -> Core (Maybe TH.Name) -> DsM (Core TH.DecQ)
2096 repPragComplete (MkC cls) (MkC mty) = rep2 pragCompleteDName [cls, mty]
2097
2098 repPragRule :: Core String -> Core [TH.RuleBndrQ] -> Core TH.ExpQ
2099 -> Core TH.ExpQ -> Core TH.Phases -> DsM (Core TH.DecQ)
2100 repPragRule (MkC nm) (MkC bndrs) (MkC lhs) (MkC rhs) (MkC phases)
2101 = rep2 pragRuleDName [nm, bndrs, lhs, rhs, phases]
2102
2103 repPragAnn :: Core TH.AnnTarget -> Core TH.ExpQ -> DsM (Core TH.DecQ)
2104 repPragAnn (MkC targ) (MkC e) = rep2 pragAnnDName [targ, e]
2105
2106 repTySynInst :: Core TH.Name -> Core TH.TySynEqnQ -> DsM (Core TH.DecQ)
2107 repTySynInst (MkC nm) (MkC eqn)
2108 = rep2 tySynInstDName [nm, eqn]
2109
2110 repDataFamilyD :: Core TH.Name -> Core [TH.TyVarBndrQ]
2111 -> Core (Maybe TH.KindQ) -> DsM (Core TH.DecQ)
2112 repDataFamilyD (MkC nm) (MkC tvs) (MkC kind)
2113 = rep2 dataFamilyDName [nm, tvs, kind]
2114
2115 repOpenFamilyD :: Core TH.Name
2116 -> Core [TH.TyVarBndrQ]
2117 -> Core TH.FamilyResultSigQ
2118 -> Core (Maybe TH.InjectivityAnn)
2119 -> DsM (Core TH.DecQ)
2120 repOpenFamilyD (MkC nm) (MkC tvs) (MkC result) (MkC inj)
2121 = rep2 openTypeFamilyDName [nm, tvs, result, inj]
2122
2123 repClosedFamilyD :: Core TH.Name
2124 -> Core [TH.TyVarBndrQ]
2125 -> Core TH.FamilyResultSigQ
2126 -> Core (Maybe TH.InjectivityAnn)
2127 -> Core [TH.TySynEqnQ]
2128 -> DsM (Core TH.DecQ)
2129 repClosedFamilyD (MkC nm) (MkC tvs) (MkC res) (MkC inj) (MkC eqns)
2130 = rep2 closedTypeFamilyDName [nm, tvs, res, inj, eqns]
2131
2132 repTySynEqn :: Core [TH.TypeQ] -> Core TH.TypeQ -> DsM (Core TH.TySynEqnQ)
2133 repTySynEqn (MkC lhs) (MkC rhs)
2134 = rep2 tySynEqnName [lhs, rhs]
2135
2136 repRoleAnnotD :: Core TH.Name -> Core [TH.Role] -> DsM (Core TH.DecQ)
2137 repRoleAnnotD (MkC n) (MkC roles) = rep2 roleAnnotDName [n, roles]
2138
2139 repFunDep :: Core [TH.Name] -> Core [TH.Name] -> DsM (Core TH.FunDep)
2140 repFunDep (MkC xs) (MkC ys) = rep2 funDepName [xs, ys]
2141
2142 repProto :: Name -> Core TH.Name -> Core TH.TypeQ -> DsM (Core TH.DecQ)
2143 repProto mk_sig (MkC s) (MkC ty) = rep2 mk_sig [s, ty]
2144
2145 repCtxt :: Core [TH.PredQ] -> DsM (Core TH.CxtQ)
2146 repCtxt (MkC tys) = rep2 cxtName [tys]
2147
2148 repDataCon :: Located Name
2149 -> HsConDeclDetails GhcRn
2150 -> DsM (Core TH.ConQ)
2151 repDataCon con details
2152 = do con' <- lookupLOcc con -- See Note [Binders and occurrences]
2153 repConstr details Nothing [con']
2154
2155 repGadtDataCons :: [Located Name]
2156 -> HsConDeclDetails GhcRn
2157 -> LHsType GhcRn
2158 -> DsM (Core TH.ConQ)
2159 repGadtDataCons cons details res_ty
2160 = do cons' <- mapM lookupLOcc cons -- See Note [Binders and occurrences]
2161 repConstr details (Just res_ty) cons'
2162
2163 -- Invariant:
2164 -- * for plain H98 data constructors second argument is Nothing and third
2165 -- argument is a singleton list
2166 -- * for GADTs data constructors second argument is (Just return_type) and
2167 -- third argument is a non-empty list
2168 repConstr :: HsConDeclDetails GhcRn
2169 -> Maybe (LHsType GhcRn)
2170 -> [Core TH.Name]
2171 -> DsM (Core TH.ConQ)
2172 repConstr (PrefixCon ps) Nothing [con]
2173 = do arg_tys <- repList bangTypeQTyConName repBangTy ps
2174 rep2 normalCName [unC con, unC arg_tys]
2175
2176 repConstr (PrefixCon ps) (Just (L _ res_ty)) cons
2177 = do arg_tys <- repList bangTypeQTyConName repBangTy ps
2178 res_ty' <- repTy res_ty
2179 rep2 gadtCName [ unC (nonEmptyCoreList cons), unC arg_tys, unC res_ty']
2180
2181 repConstr (RecCon (L _ ips)) resTy cons
2182 = do args <- concatMapM rep_ip ips
2183 arg_vtys <- coreList varBangTypeQTyConName args
2184 case resTy of
2185 Nothing -> rep2 recCName [unC (head cons), unC arg_vtys]
2186 Just (L _ res_ty) -> do
2187 res_ty' <- repTy res_ty
2188 rep2 recGadtCName [unC (nonEmptyCoreList cons), unC arg_vtys,
2189 unC res_ty']
2190
2191 where
2192 rep_ip (L _ ip) = mapM (rep_one_ip (cd_fld_type ip)) (cd_fld_names ip)
2193
2194 rep_one_ip :: LBangType GhcRn -> LFieldOcc GhcRn -> DsM (Core a)
2195 rep_one_ip t n = do { MkC v <- lookupOcc (selectorFieldOcc $ unLoc n)
2196 ; MkC ty <- repBangTy t
2197 ; rep2 varBangTypeName [v,ty] }
2198
2199 repConstr (InfixCon st1 st2) Nothing [con]
2200 = do arg1 <- repBangTy st1
2201 arg2 <- repBangTy st2
2202 rep2 infixCName [unC arg1, unC con, unC arg2]
2203
2204 repConstr (InfixCon {}) (Just _) _ =
2205 panic "repConstr: infix GADT constructor should be in a PrefixCon"
2206 repConstr _ _ _ =
2207 panic "repConstr: invariant violated"
2208
2209 ------------ Types -------------------
2210
2211 repTForall :: Core [TH.TyVarBndrQ] -> Core TH.CxtQ -> Core TH.TypeQ
2212 -> DsM (Core TH.TypeQ)
2213 repTForall (MkC tvars) (MkC ctxt) (MkC ty)
2214 = rep2 forallTName [tvars, ctxt, ty]
2215
2216 repTvar :: Core TH.Name -> DsM (Core TH.TypeQ)
2217 repTvar (MkC s) = rep2 varTName [s]
2218
2219 repTapp :: Core TH.TypeQ -> Core TH.TypeQ -> DsM (Core TH.TypeQ)
2220 repTapp (MkC t1) (MkC t2) = rep2 appTName [t1, t2]
2221
2222 repTapps :: Core TH.TypeQ -> [Core TH.TypeQ] -> DsM (Core TH.TypeQ)
2223 repTapps f [] = return f
2224 repTapps f (t:ts) = do { f1 <- repTapp f t; repTapps f1 ts }
2225
2226 repTSig :: Core TH.TypeQ -> Core TH.KindQ -> DsM (Core TH.TypeQ)
2227 repTSig (MkC ty) (MkC ki) = rep2 sigTName [ty, ki]
2228
2229 repTequality :: DsM (Core TH.TypeQ)
2230 repTequality = rep2 equalityTName []
2231
2232 repTPromotedList :: [Core TH.TypeQ] -> DsM (Core TH.TypeQ)
2233 repTPromotedList [] = repPromotedNilTyCon
2234 repTPromotedList (t:ts) = do { tcon <- repPromotedConsTyCon
2235 ; f <- repTapp tcon t
2236 ; t' <- repTPromotedList ts
2237 ; repTapp f t'
2238 }
2239
2240 repTLit :: Core TH.TyLitQ -> DsM (Core TH.TypeQ)
2241 repTLit (MkC lit) = rep2 litTName [lit]
2242
2243 repTWildCard :: DsM (Core TH.TypeQ)
2244 repTWildCard = rep2 wildCardTName []
2245
2246 repTStar :: DsM (Core TH.TypeQ)
2247 repTStar = rep2 starKName []
2248
2249 repTConstraint :: DsM (Core TH.TypeQ)
2250 repTConstraint = rep2 constraintKName []
2251
2252 --------- Type constructors --------------
2253
2254 repNamedTyCon :: Core TH.Name -> DsM (Core TH.TypeQ)
2255 repNamedTyCon (MkC s) = rep2 conTName [s]
2256
2257 repTupleTyCon :: Int -> DsM (Core TH.TypeQ)
2258 -- Note: not Core Int; it's easier to be direct here
2259 repTupleTyCon i = do dflags <- getDynFlags
2260 rep2 tupleTName [mkIntExprInt dflags i]
2261
2262 repUnboxedTupleTyCon :: Int -> DsM (Core TH.TypeQ)
2263 -- Note: not Core Int; it's easier to be direct here
2264 repUnboxedTupleTyCon i = do dflags <- getDynFlags
2265 rep2 unboxedTupleTName [mkIntExprInt dflags i]
2266
2267 repUnboxedSumTyCon :: TH.SumArity -> DsM (Core TH.TypeQ)
2268 -- Note: not Core TH.SumArity; it's easier to be direct here
2269 repUnboxedSumTyCon arity = do dflags <- getDynFlags
2270 rep2 unboxedSumTName [mkIntExprInt dflags arity]
2271
2272 repArrowTyCon :: DsM (Core TH.TypeQ)
2273 repArrowTyCon = rep2 arrowTName []
2274
2275 repListTyCon :: DsM (Core TH.TypeQ)
2276 repListTyCon = rep2 listTName []
2277
2278 repPromotedDataCon :: Core TH.Name -> DsM (Core TH.TypeQ)
2279 repPromotedDataCon (MkC s) = rep2 promotedTName [s]
2280
2281 repPromotedTupleTyCon :: Int -> DsM (Core TH.TypeQ)
2282 repPromotedTupleTyCon i = do dflags <- getDynFlags
2283 rep2 promotedTupleTName [mkIntExprInt dflags i]
2284
2285 repPromotedNilTyCon :: DsM (Core TH.TypeQ)
2286 repPromotedNilTyCon = rep2 promotedNilTName []
2287
2288 repPromotedConsTyCon :: DsM (Core TH.TypeQ)
2289 repPromotedConsTyCon = rep2 promotedConsTName []
2290
2291 ------------ TyVarBndrs -------------------
2292
2293 repPlainTV :: Core TH.Name -> DsM (Core TH.TyVarBndrQ)
2294 repPlainTV (MkC nm) = rep2 plainTVName [nm]
2295
2296 repKindedTV :: Core TH.Name -> Core TH.KindQ -> DsM (Core TH.TyVarBndrQ)
2297 repKindedTV (MkC nm) (MkC ki) = rep2 kindedTVName [nm, ki]
2298
2299 ----------------------------------------------------------
2300 -- Type family result signature
2301
2302 repNoSig :: DsM (Core TH.FamilyResultSigQ)
2303 repNoSig = rep2 noSigName []
2304
2305 repKindSig :: Core TH.KindQ -> DsM (Core TH.FamilyResultSigQ)
2306 repKindSig (MkC ki) = rep2 kindSigName [ki]
2307
2308 repTyVarSig :: Core TH.TyVarBndrQ -> DsM (Core TH.FamilyResultSigQ)
2309 repTyVarSig (MkC bndr) = rep2 tyVarSigName [bndr]
2310
2311 ----------------------------------------------------------
2312 -- Literals
2313
2314 repLiteral :: HsLit GhcRn -> DsM (Core TH.Lit)
2315 repLiteral (HsStringPrim _ bs)
2316 = do dflags <- getDynFlags
2317 word8_ty <- lookupType word8TyConName
2318 let w8s = unpack bs
2319 w8s_expr = map (\w8 -> mkCoreConApps word8DataCon
2320 [mkWordLit dflags (toInteger w8)]) w8s
2321 rep2 stringPrimLName [mkListExpr word8_ty w8s_expr]
2322 repLiteral lit
2323 = do lit' <- case lit of
2324 HsIntPrim _ i -> mk_integer i
2325 HsWordPrim _ w -> mk_integer w
2326 HsInt _ i -> mk_integer (il_value i)
2327 HsFloatPrim _ r -> mk_rational r
2328 HsDoublePrim _ r -> mk_rational r
2329 HsCharPrim _ c -> mk_char c
2330 _ -> return lit
2331 lit_expr <- dsLit lit'
2332 case mb_lit_name of
2333 Just lit_name -> rep2 lit_name [lit_expr]
2334 Nothing -> notHandled "Exotic literal" (ppr lit)
2335 where
2336 mb_lit_name = case lit of
2337 HsInteger _ _ _ -> Just integerLName
2338 HsInt _ _ -> Just integerLName
2339 HsIntPrim _ _ -> Just intPrimLName
2340 HsWordPrim _ _ -> Just wordPrimLName
2341 HsFloatPrim _ _ -> Just floatPrimLName
2342 HsDoublePrim _ _ -> Just doublePrimLName
2343 HsChar _ _ -> Just charLName
2344 HsCharPrim _ _ -> Just charPrimLName
2345 HsString _ _ -> Just stringLName
2346 HsRat _ _ _ -> Just rationalLName
2347 _ -> Nothing
2348
2349 mk_integer :: Integer -> DsM (HsLit GhcRn)
2350 mk_integer i = do integer_ty <- lookupType integerTyConName
2351 return $ HsInteger noSourceText i integer_ty
2352
2353 mk_rational :: FractionalLit -> DsM (HsLit GhcRn)
2354 mk_rational r = do rat_ty <- lookupType rationalTyConName
2355 return $ HsRat def r rat_ty
2356 mk_string :: FastString -> DsM (HsLit GhcRn)
2357 mk_string s = return $ HsString noSourceText s
2358
2359 mk_char :: Char -> DsM (HsLit GhcRn)
2360 mk_char c = return $ HsChar noSourceText c
2361
2362 repOverloadedLiteral :: HsOverLit GhcRn -> DsM (Core TH.Lit)
2363 repOverloadedLiteral (OverLit { ol_val = val})
2364 = do { lit <- mk_lit val; repLiteral lit }
2365 -- The type Rational will be in the environment, because
2366 -- the smart constructor 'TH.Syntax.rationalL' uses it in its type,
2367 -- and rationalL is sucked in when any TH stuff is used
2368
2369 mk_lit :: OverLitVal -> DsM (HsLit GhcRn)
2370 mk_lit (HsIntegral i) = mk_integer (il_value i)
2371 mk_lit (HsFractional f) = mk_rational f
2372 mk_lit (HsIsString _ s) = mk_string s
2373
2374 repNameS :: Core String -> DsM (Core TH.Name)
2375 repNameS (MkC name) = rep2 mkNameSName [name]
2376
2377 --------------- Miscellaneous -------------------
2378
2379 repGensym :: Core String -> DsM (Core (TH.Q TH.Name))
2380 repGensym (MkC lit_str) = rep2 newNameName [lit_str]
2381
2382 repBindQ :: Type -> Type -- a and b
2383 -> Core (TH.Q a) -> Core (a -> TH.Q b) -> DsM (Core (TH.Q b))
2384 repBindQ ty_a ty_b (MkC x) (MkC y)
2385 = rep2 bindQName [Type ty_a, Type ty_b, x, y]
2386
2387 repSequenceQ :: Type -> Core [TH.Q a] -> DsM (Core (TH.Q [a]))
2388 repSequenceQ ty_a (MkC list)
2389 = rep2 sequenceQName [Type ty_a, list]
2390
2391 repUnboundVar :: Core TH.Name -> DsM (Core TH.ExpQ)
2392 repUnboundVar (MkC name) = rep2 unboundVarEName [name]
2393
2394 repOverLabel :: FastString -> DsM (Core TH.ExpQ)
2395 repOverLabel fs = do
2396 (MkC s) <- coreStringLit $ unpackFS fs
2397 rep2 labelEName [s]
2398
2399
2400 ------------ Lists -------------------
2401 -- turn a list of patterns into a single pattern matching a list
2402
2403 repList :: Name -> (a -> DsM (Core b))
2404 -> [a] -> DsM (Core [b])
2405 repList tc_name f args
2406 = do { args1 <- mapM f args
2407 ; coreList tc_name args1 }
2408
2409 coreList :: Name -- Of the TyCon of the element type
2410 -> [Core a] -> DsM (Core [a])
2411 coreList tc_name es
2412 = do { elt_ty <- lookupType tc_name; return (coreList' elt_ty es) }
2413
2414 coreList' :: Type -- The element type
2415 -> [Core a] -> Core [a]
2416 coreList' elt_ty es = MkC (mkListExpr elt_ty (map unC es ))
2417
2418 nonEmptyCoreList :: [Core a] -> Core [a]
2419 -- The list must be non-empty so we can get the element type
2420 -- Otherwise use coreList
2421 nonEmptyCoreList [] = panic "coreList: empty argument"
2422 nonEmptyCoreList xs@(MkC x:_) = MkC (mkListExpr (exprType x) (map unC xs))
2423
2424 coreStringLit :: String -> DsM (Core String)
2425 coreStringLit s = do { z <- mkStringExpr s; return(MkC z) }
2426
2427 ------------------- Maybe ------------------
2428
2429 -- | Construct Core expression for Nothing of a given type name
2430 coreNothing :: Name -- ^ Name of the TyCon of the element type
2431 -> DsM (Core (Maybe a))
2432 coreNothing tc_name =
2433 do { elt_ty <- lookupType tc_name; return (coreNothing' elt_ty) }
2434
2435 -- | Construct Core expression for Nothing of a given type
2436 coreNothing' :: Type -- ^ The element type
2437 -> Core (Maybe a)
2438 coreNothing' elt_ty = MkC (mkNothingExpr elt_ty)
2439
2440 -- | Store given Core expression in a Just of a given type name
2441 coreJust :: Name -- ^ Name of the TyCon of the element type
2442 -> Core a -> DsM (Core (Maybe a))
2443 coreJust tc_name es
2444 = do { elt_ty <- lookupType tc_name; return (coreJust' elt_ty es) }
2445
2446 -- | Store given Core expression in a Just of a given type
2447 coreJust' :: Type -- ^ The element type
2448 -> Core a -> Core (Maybe a)
2449 coreJust' elt_ty es = MkC (mkJustExpr elt_ty (unC es))
2450
2451 ------------ Literals & Variables -------------------
2452
2453 coreIntLit :: Int -> DsM (Core Int)
2454 coreIntLit i = do dflags <- getDynFlags
2455 return (MkC (mkIntExprInt dflags i))
2456
2457 coreVar :: Id -> Core TH.Name -- The Id has type Name
2458 coreVar id = MkC (Var id)
2459
2460 ----------------- Failure -----------------------
2461 notHandledL :: SrcSpan -> String -> SDoc -> DsM a
2462 notHandledL loc what doc
2463 | isGoodSrcSpan loc
2464 = putSrcSpanDs loc $ notHandled what doc
2465 | otherwise
2466 = notHandled what doc
2467
2468 notHandled :: String -> SDoc -> DsM a
2469 notHandled what doc = failWithDs msg
2470 where
2471 msg = hang (text what <+> text "not (yet) handled by Template Haskell")
2472 2 doc