Udate hsSyn AST to use Trees that Grow
[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.TyVarBndr]
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' <- repMaybeLKind 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' <- repMaybeLKind 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.TyVarBndr]
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.FamilyResultSig)
377 repFamilyResultSig NoSig = repNoSig
378 repFamilyResultSig (KindSig ki) = do { ki' <- repLKind 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.Kind))
388 repFamilyResultSigToMaybeKind NoSig =
389 do { coreNothing kindTyConName }
390 repFamilyResultSigToMaybeKind (KindSig ki) =
391 do { ki' <- repLKind ki
392 ; coreJust kindTyConName 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 tyVarBndrTyConName 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.TyVarBndr] -> 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 tyVarBndrTyConName 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.TyVarBndr] -> 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 tyVarBndrTyConName mk_tv_bndr (hsQTvExplicit tvs)
903 ; m kbs }
904
905 ; wrapGenSyms freshNames term }
906 where
907 mk_tv_bndr tv = do { v <- lookupBinder (hsLTyVarName tv)
908 ; repTyVarBndrWithKind tv v }
909
910 -- Produce kinded binder constructors from the Haskell tyvar binders
911 --
912 repTyVarBndrWithKind :: LHsTyVarBndr GhcRn
913 -> Core TH.Name -> DsM (Core TH.TyVarBndr)
914 repTyVarBndrWithKind (L _ (UserTyVar _)) nm
915 = repPlainTV nm
916 repTyVarBndrWithKind (L _ (KindedTyVar _ ki)) nm
917 = repLKind ki >>= repKindedTV nm
918
919 -- | Represent a type variable binder
920 repTyVarBndr :: LHsTyVarBndr GhcRn -> DsM (Core TH.TyVarBndr)
921 repTyVarBndr (L _ (UserTyVar (L _ nm)) )= do { nm' <- lookupBinder nm
922 ; repPlainTV nm' }
923 repTyVarBndr (L _ (KindedTyVar (L _ nm) ki)) = do { nm' <- lookupBinder nm
924 ; ki' <- repLKind ki
925 ; repKindedTV nm' ki' }
926
927 -- represent a type context
928 --
929 repLContext :: LHsContext GhcRn -> DsM (Core TH.CxtQ)
930 repLContext (L _ ctxt) = repContext ctxt
931
932 repContext :: HsContext GhcRn -> DsM (Core TH.CxtQ)
933 repContext ctxt = do preds <- repList typeQTyConName repLTy ctxt
934 repCtxt preds
935
936 repHsSigType :: LHsSigType GhcRn -> DsM (Core TH.TypeQ)
937 repHsSigType (HsIB { hsib_vars = implicit_tvs
938 , hsib_body = body })
939 | (explicit_tvs, ctxt, ty) <- splitLHsSigmaTy body
940 = addTyVarBinds (HsQTvs { hsq_implicit = implicit_tvs
941 , hsq_explicit = explicit_tvs
942 , hsq_dependent = emptyNameSet })
943 -- NB: Don't pass implicit_tvs to the hsq_explicit field above
944 -- See Note [Don't quantify implicit type variables in quotes]
945 $ \ th_explicit_tvs ->
946 do { th_ctxt <- repLContext ctxt
947 ; th_ty <- repLTy ty
948 ; if null explicit_tvs && null (unLoc ctxt)
949 then return th_ty
950 else repTForall th_explicit_tvs th_ctxt th_ty }
951
952 repHsPatSynSigType :: LHsSigType GhcRn -> DsM (Core TH.TypeQ)
953 repHsPatSynSigType (HsIB { hsib_vars = implicit_tvs
954 , hsib_body = body })
955 = addTyVarBinds (newTvs implicit_tvs univs) $ \th_univs ->
956 addTyVarBinds (newTvs [] exis) $ \th_exis ->
957 do { th_reqs <- repLContext reqs
958 ; th_provs <- repLContext provs
959 ; th_ty <- repLTy ty
960 ; repTForall th_univs th_reqs =<< (repTForall th_exis th_provs th_ty) }
961 where
962 newTvs impl_tvs expl_tvs = HsQTvs
963 { hsq_implicit = impl_tvs
964 , hsq_explicit = expl_tvs
965 , hsq_dependent = emptyNameSet }
966 -- NB: Don't pass impl_tvs to the hsq_explicit field above
967 -- See Note [Don't quantify implicit type variables in quotes]
968
969 (univs, reqs, exis, provs, ty) = splitLHsPatSynTy body
970
971 repHsSigWcType :: LHsSigWcType GhcRn -> DsM (Core TH.TypeQ)
972 repHsSigWcType (HsWC { hswc_body = sig1 })
973 = repHsSigType sig1
974
975 -- yield the representation of a list of types
976 repLTys :: [LHsType GhcRn] -> DsM [Core TH.TypeQ]
977 repLTys tys = mapM repLTy tys
978
979 -- represent a type
980 repLTy :: LHsType GhcRn -> DsM (Core TH.TypeQ)
981 repLTy (L _ ty) = repTy ty
982
983 repForall :: HsType GhcRn -> DsM (Core TH.TypeQ)
984 -- Arg of repForall is always HsForAllTy or HsQualTy
985 repForall ty
986 | (tvs, ctxt, tau) <- splitLHsSigmaTy (noLoc ty)
987 = addTyVarBinds (HsQTvs { hsq_implicit = [], hsq_explicit = tvs
988 , hsq_dependent = emptyNameSet }) $ \bndrs ->
989 do { ctxt1 <- repLContext ctxt
990 ; ty1 <- repLTy tau
991 ; repTForall bndrs ctxt1 ty1 }
992
993 repTy :: HsType GhcRn -> DsM (Core TH.TypeQ)
994 repTy ty@(HsForAllTy {}) = repForall ty
995 repTy ty@(HsQualTy {}) = repForall ty
996
997 repTy (HsTyVar _ (L _ n))
998 | isTvOcc occ = do tv1 <- lookupOcc n
999 repTvar tv1
1000 | isDataOcc occ = do tc1 <- lookupOcc n
1001 repPromotedDataCon tc1
1002 | n == eqTyConName = repTequality
1003 | otherwise = do tc1 <- lookupOcc n
1004 repNamedTyCon tc1
1005 where
1006 occ = nameOccName n
1007
1008 repTy (HsAppTy f a) = do
1009 f1 <- repLTy f
1010 a1 <- repLTy a
1011 repTapp f1 a1
1012 repTy (HsFunTy f a) = do
1013 f1 <- repLTy f
1014 a1 <- repLTy a
1015 tcon <- repArrowTyCon
1016 repTapps tcon [f1, a1]
1017 repTy (HsListTy t) = do
1018 t1 <- repLTy t
1019 tcon <- repListTyCon
1020 repTapp tcon t1
1021 repTy (HsPArrTy t) = do
1022 t1 <- repLTy t
1023 tcon <- repTy (HsTyVar NotPromoted
1024 (noLoc (tyConName parrTyCon)))
1025 repTapp tcon t1
1026 repTy (HsTupleTy HsUnboxedTuple tys) = do
1027 tys1 <- repLTys tys
1028 tcon <- repUnboxedTupleTyCon (length tys)
1029 repTapps tcon tys1
1030 repTy (HsTupleTy _ tys) = do tys1 <- repLTys tys
1031 tcon <- repTupleTyCon (length tys)
1032 repTapps tcon tys1
1033 repTy (HsSumTy tys) = do tys1 <- repLTys tys
1034 tcon <- repUnboxedSumTyCon (length tys)
1035 repTapps tcon tys1
1036 repTy (HsOpTy ty1 n ty2) = repLTy ((nlHsTyVar (unLoc n) `nlHsAppTy` ty1)
1037 `nlHsAppTy` ty2)
1038 repTy (HsParTy t) = repLTy t
1039 repTy (HsEqTy t1 t2) = do
1040 t1' <- repLTy t1
1041 t2' <- repLTy t2
1042 eq <- repTequality
1043 repTapps eq [t1', t2']
1044 repTy (HsKindSig t k) = do
1045 t1 <- repLTy t
1046 k1 <- repLKind k
1047 repTSig t1 k1
1048 repTy (HsSpliceTy splice _) = repSplice splice
1049 repTy (HsExplicitListTy _ _ tys) = do
1050 tys1 <- repLTys tys
1051 repTPromotedList tys1
1052 repTy (HsExplicitTupleTy _ tys) = do
1053 tys1 <- repLTys tys
1054 tcon <- repPromotedTupleTyCon (length tys)
1055 repTapps tcon tys1
1056 repTy (HsTyLit lit) = do
1057 lit' <- repTyLit lit
1058 repTLit lit'
1059 repTy (HsWildCardTy (AnonWildCard _)) = repTWildCard
1060
1061 repTy ty = notHandled "Exotic form of type" (ppr ty)
1062
1063 repTyLit :: HsTyLit -> DsM (Core TH.TyLitQ)
1064 repTyLit (HsNumTy _ i) = do iExpr <- mkIntegerExpr i
1065 rep2 numTyLitName [iExpr]
1066 repTyLit (HsStrTy _ s) = do { s' <- mkStringExprFS s
1067 ; rep2 strTyLitName [s']
1068 }
1069
1070 -- represent a kind
1071 --
1072 repLKind :: LHsKind GhcRn -> DsM (Core TH.Kind)
1073 repLKind ki
1074 = do { let (kis, ki') = splitHsFunType ki
1075 ; kis_rep <- mapM repLKind kis
1076 ; ki'_rep <- repNonArrowLKind ki'
1077 ; kcon <- repKArrow
1078 ; let f k1 k2 = repKApp kcon k1 >>= flip repKApp k2
1079 ; foldrM f ki'_rep kis_rep
1080 }
1081
1082 -- | Represent a kind wrapped in a Maybe
1083 repMaybeLKind :: Maybe (LHsKind GhcRn)
1084 -> DsM (Core (Maybe TH.Kind))
1085 repMaybeLKind Nothing =
1086 do { coreNothing kindTyConName }
1087 repMaybeLKind (Just ki) =
1088 do { ki' <- repLKind ki
1089 ; coreJust kindTyConName ki' }
1090
1091 repNonArrowLKind :: LHsKind GhcRn -> DsM (Core TH.Kind)
1092 repNonArrowLKind (L _ ki) = repNonArrowKind ki
1093
1094 repNonArrowKind :: HsKind GhcRn -> DsM (Core TH.Kind)
1095 repNonArrowKind (HsTyVar _ (L _ name))
1096 | isLiftedTypeKindTyConName name = repKStar
1097 | name `hasKey` constraintKindTyConKey = repKConstraint
1098 | isTvOcc (nameOccName name) = lookupOcc name >>= repKVar
1099 | otherwise = lookupOcc name >>= repKCon
1100 repNonArrowKind (HsAppTy f a) = do { f' <- repLKind f
1101 ; a' <- repLKind a
1102 ; repKApp f' a'
1103 }
1104 repNonArrowKind (HsListTy k) = do { k' <- repLKind k
1105 ; kcon <- repKList
1106 ; repKApp kcon k'
1107 }
1108 repNonArrowKind (HsTupleTy _ ks) = do { ks' <- mapM repLKind ks
1109 ; kcon <- repKTuple (length ks)
1110 ; repKApps kcon ks'
1111 }
1112 repNonArrowKind k = notHandled "Exotic form of kind" (ppr k)
1113
1114 repRole :: Located (Maybe Role) -> DsM (Core TH.Role)
1115 repRole (L _ (Just Nominal)) = rep2 nominalRName []
1116 repRole (L _ (Just Representational)) = rep2 representationalRName []
1117 repRole (L _ (Just Phantom)) = rep2 phantomRName []
1118 repRole (L _ Nothing) = rep2 inferRName []
1119
1120 -----------------------------------------------------------------------------
1121 -- Splices
1122 -----------------------------------------------------------------------------
1123
1124 repSplice :: HsSplice GhcRn -> DsM (Core a)
1125 -- See Note [How brackets and nested splices are handled] in TcSplice
1126 -- We return a CoreExpr of any old type; the context should know
1127 repSplice (HsTypedSplice _ n _) = rep_splice n
1128 repSplice (HsUntypedSplice _ n _) = rep_splice n
1129 repSplice (HsQuasiQuote n _ _ _) = rep_splice n
1130 repSplice e@(HsSpliced _ _) = pprPanic "repSplice" (ppr e)
1131
1132 rep_splice :: Name -> DsM (Core a)
1133 rep_splice splice_name
1134 = do { mb_val <- dsLookupMetaEnv splice_name
1135 ; case mb_val of
1136 Just (DsSplice e) -> do { e' <- dsExpr e
1137 ; return (MkC e') }
1138 _ -> pprPanic "HsSplice" (ppr splice_name) }
1139 -- Should not happen; statically checked
1140
1141 -----------------------------------------------------------------------------
1142 -- Expressions
1143 -----------------------------------------------------------------------------
1144
1145 repLEs :: [LHsExpr GhcRn] -> DsM (Core [TH.ExpQ])
1146 repLEs es = repList expQTyConName repLE es
1147
1148 -- FIXME: some of these panics should be converted into proper error messages
1149 -- unless we can make sure that constructs, which are plainly not
1150 -- supported in TH already lead to error messages at an earlier stage
1151 repLE :: LHsExpr GhcRn -> DsM (Core TH.ExpQ)
1152 repLE (L loc e) = putSrcSpanDs loc (repE e)
1153
1154 repE :: HsExpr GhcRn -> DsM (Core TH.ExpQ)
1155 repE (HsVar (L _ x)) =
1156 do { mb_val <- dsLookupMetaEnv x
1157 ; case mb_val of
1158 Nothing -> do { str <- globalVar x
1159 ; repVarOrCon x str }
1160 Just (DsBound y) -> repVarOrCon x (coreVar y)
1161 Just (DsSplice e) -> do { e' <- dsExpr e
1162 ; return (MkC e') } }
1163 repE e@(HsIPVar _) = notHandled "Implicit parameters" (ppr e)
1164 repE e@(HsOverLabel{}) = notHandled "Overloaded labels" (ppr e)
1165
1166 repE e@(HsRecFld f) = case f of
1167 Unambiguous _ x -> repE (HsVar (noLoc x))
1168 Ambiguous{} -> notHandled "Ambiguous record selectors" (ppr e)
1169
1170 -- Remember, we're desugaring renamer output here, so
1171 -- HsOverlit can definitely occur
1172 repE (HsOverLit l) = do { a <- repOverloadedLiteral l; repLit a }
1173 repE (HsLit l) = do { a <- repLiteral l; repLit a }
1174 repE (HsLam (MG { mg_alts = L _ [m] })) = repLambda m
1175 repE (HsLamCase (MG { mg_alts = L _ ms }))
1176 = do { ms' <- mapM repMatchTup ms
1177 ; core_ms <- coreList matchQTyConName ms'
1178 ; repLamCase core_ms }
1179 repE (HsApp x y) = do {a <- repLE x; b <- repLE y; repApp a b}
1180 repE (HsAppType e t) = do { a <- repLE e
1181 ; s <- repLTy (hswc_body t)
1182 ; repAppType a s }
1183
1184 repE (OpApp e1 op _ e2) =
1185 do { arg1 <- repLE e1;
1186 arg2 <- repLE e2;
1187 the_op <- repLE op ;
1188 repInfixApp arg1 the_op arg2 }
1189 repE (NegApp x _) = do
1190 a <- repLE x
1191 negateVar <- lookupOcc negateName >>= repVar
1192 negateVar `repApp` a
1193 repE (HsPar x) = repLE x
1194 repE (SectionL x y) = do { a <- repLE x; b <- repLE y; repSectionL a b }
1195 repE (SectionR x y) = do { a <- repLE x; b <- repLE y; repSectionR a b }
1196 repE (HsCase e (MG { mg_alts = L _ ms }))
1197 = do { arg <- repLE e
1198 ; ms2 <- mapM repMatchTup ms
1199 ; core_ms2 <- coreList matchQTyConName ms2
1200 ; repCaseE arg core_ms2 }
1201 repE (HsIf _ x y z) = do
1202 a <- repLE x
1203 b <- repLE y
1204 c <- repLE z
1205 repCond a b c
1206 repE (HsMultiIf _ alts)
1207 = do { (binds, alts') <- liftM unzip $ mapM repLGRHS alts
1208 ; expr' <- repMultiIf (nonEmptyCoreList alts')
1209 ; wrapGenSyms (concat binds) expr' }
1210 repE (HsLet (L _ bs) e) = do { (ss,ds) <- repBinds bs
1211 ; e2 <- addBinds ss (repLE e)
1212 ; z <- repLetE ds e2
1213 ; wrapGenSyms ss z }
1214
1215 -- FIXME: I haven't got the types here right yet
1216 repE e@(HsDo ctxt (L _ sts) _)
1217 | case ctxt of { DoExpr -> True; GhciStmtCtxt -> True; _ -> False }
1218 = do { (ss,zs) <- repLSts sts;
1219 e' <- repDoE (nonEmptyCoreList zs);
1220 wrapGenSyms ss e' }
1221
1222 | ListComp <- ctxt
1223 = do { (ss,zs) <- repLSts sts;
1224 e' <- repComp (nonEmptyCoreList zs);
1225 wrapGenSyms ss e' }
1226
1227 | otherwise
1228 = notHandled "mdo, monad comprehension and [: :]" (ppr e)
1229
1230 repE (ExplicitList _ _ es) = do { xs <- repLEs es; repListExp xs }
1231 repE e@(ExplicitPArr _ _) = notHandled "Parallel arrays" (ppr e)
1232 repE e@(ExplicitTuple es boxed)
1233 | not (all tupArgPresent es) = notHandled "Tuple sections" (ppr e)
1234 | isBoxed boxed = do { xs <- repLEs [e | L _ (Present e) <- es]; repTup xs }
1235 | otherwise = do { xs <- repLEs [e | L _ (Present e) <- es]
1236 ; repUnboxedTup xs }
1237
1238 repE (ExplicitSum alt arity e _)
1239 = do { e1 <- repLE e
1240 ; repUnboxedSum e1 alt arity }
1241
1242 repE (RecordCon { rcon_con_name = c, rcon_flds = flds })
1243 = do { x <- lookupLOcc c;
1244 fs <- repFields flds;
1245 repRecCon x fs }
1246 repE (RecordUpd { rupd_expr = e, rupd_flds = flds })
1247 = do { x <- repLE e;
1248 fs <- repUpdFields flds;
1249 repRecUpd x fs }
1250
1251 repE (ExprWithTySig e ty)
1252 = do { e1 <- repLE e
1253 ; t1 <- repHsSigWcType ty
1254 ; repSigExp e1 t1 }
1255
1256 repE (ArithSeq _ _ aseq) =
1257 case aseq of
1258 From e -> do { ds1 <- repLE e; repFrom ds1 }
1259 FromThen e1 e2 -> do
1260 ds1 <- repLE e1
1261 ds2 <- repLE e2
1262 repFromThen ds1 ds2
1263 FromTo e1 e2 -> do
1264 ds1 <- repLE e1
1265 ds2 <- repLE e2
1266 repFromTo ds1 ds2
1267 FromThenTo e1 e2 e3 -> do
1268 ds1 <- repLE e1
1269 ds2 <- repLE e2
1270 ds3 <- repLE e3
1271 repFromThenTo ds1 ds2 ds3
1272
1273 repE (HsSpliceE splice) = repSplice splice
1274 repE (HsStatic _ e) = repLE e >>= rep2 staticEName . (:[]) . unC
1275 repE (HsUnboundVar uv) = do
1276 occ <- occNameLit (unboundVarOcc uv)
1277 sname <- repNameS occ
1278 repUnboundVar sname
1279
1280 repE e@(PArrSeq {}) = notHandled "Parallel arrays" (ppr e)
1281 repE e@(HsCoreAnn {}) = notHandled "Core annotations" (ppr e)
1282 repE e@(HsSCC {}) = notHandled "Cost centres" (ppr e)
1283 repE e@(HsTickPragma {}) = notHandled "Tick Pragma" (ppr e)
1284 repE e@(HsTcBracketOut {}) = notHandled "TH brackets" (ppr e)
1285 repE e = notHandled "Expression form" (ppr e)
1286
1287 -----------------------------------------------------------------------------
1288 -- Building representations of auxillary structures like Match, Clause, Stmt,
1289
1290 repMatchTup :: LMatch GhcRn (LHsExpr GhcRn) -> DsM (Core TH.MatchQ)
1291 repMatchTup (L _ (Match _ [p] _ (GRHSs guards (L _ wheres)))) =
1292 do { ss1 <- mkGenSyms (collectPatBinders p)
1293 ; addBinds ss1 $ do {
1294 ; p1 <- repLP p
1295 ; (ss2,ds) <- repBinds wheres
1296 ; addBinds ss2 $ do {
1297 ; gs <- repGuards guards
1298 ; match <- repMatch p1 gs ds
1299 ; wrapGenSyms (ss1++ss2) match }}}
1300 repMatchTup _ = panic "repMatchTup: case alt with more than one arg"
1301
1302 repClauseTup :: LMatch GhcRn (LHsExpr GhcRn) -> DsM (Core TH.ClauseQ)
1303 repClauseTup (L _ (Match _ ps _ (GRHSs guards (L _ wheres)))) =
1304 do { ss1 <- mkGenSyms (collectPatsBinders ps)
1305 ; addBinds ss1 $ do {
1306 ps1 <- repLPs ps
1307 ; (ss2,ds) <- repBinds wheres
1308 ; addBinds ss2 $ do {
1309 gs <- repGuards guards
1310 ; clause <- repClause ps1 gs ds
1311 ; wrapGenSyms (ss1++ss2) clause }}}
1312
1313 repGuards :: [LGRHS GhcRn (LHsExpr GhcRn)] -> DsM (Core TH.BodyQ)
1314 repGuards [L _ (GRHS [] e)]
1315 = do {a <- repLE e; repNormal a }
1316 repGuards other
1317 = do { zs <- mapM repLGRHS other
1318 ; let (xs, ys) = unzip zs
1319 ; gd <- repGuarded (nonEmptyCoreList ys)
1320 ; wrapGenSyms (concat xs) gd }
1321
1322 repLGRHS :: LGRHS GhcRn (LHsExpr GhcRn)
1323 -> DsM ([GenSymBind], (Core (TH.Q (TH.Guard, TH.Exp))))
1324 repLGRHS (L _ (GRHS [L _ (BodyStmt e1 _ _ _)] e2))
1325 = do { guarded <- repLNormalGE e1 e2
1326 ; return ([], guarded) }
1327 repLGRHS (L _ (GRHS ss rhs))
1328 = do { (gs, ss') <- repLSts ss
1329 ; rhs' <- addBinds gs $ repLE rhs
1330 ; guarded <- repPatGE (nonEmptyCoreList ss') rhs'
1331 ; return (gs, guarded) }
1332
1333 repFields :: HsRecordBinds GhcRn -> DsM (Core [TH.Q TH.FieldExp])
1334 repFields (HsRecFields { rec_flds = flds })
1335 = repList fieldExpQTyConName rep_fld flds
1336 where
1337 rep_fld :: LHsRecField GhcRn (LHsExpr GhcRn)
1338 -> DsM (Core (TH.Q TH.FieldExp))
1339 rep_fld (L _ fld) = do { fn <- lookupLOcc (hsRecFieldSel fld)
1340 ; e <- repLE (hsRecFieldArg fld)
1341 ; repFieldExp fn e }
1342
1343 repUpdFields :: [LHsRecUpdField GhcRn] -> DsM (Core [TH.Q TH.FieldExp])
1344 repUpdFields = repList fieldExpQTyConName rep_fld
1345 where
1346 rep_fld :: LHsRecUpdField GhcRn -> DsM (Core (TH.Q TH.FieldExp))
1347 rep_fld (L l fld) = case unLoc (hsRecFieldLbl fld) of
1348 Unambiguous _ sel_name -> do { fn <- lookupLOcc (L l sel_name)
1349 ; e <- repLE (hsRecFieldArg fld)
1350 ; repFieldExp fn e }
1351 _ -> notHandled "Ambiguous record updates" (ppr fld)
1352
1353
1354
1355 -----------------------------------------------------------------------------
1356 -- Representing Stmt's is tricky, especially if bound variables
1357 -- shadow each other. Consider: [| do { x <- f 1; x <- f x; g x } |]
1358 -- First gensym new names for every variable in any of the patterns.
1359 -- both static (x'1 and x'2), and dynamic ((gensym "x") and (gensym "y"))
1360 -- if variables didn't shaddow, the static gensym wouldn't be necessary
1361 -- and we could reuse the original names (x and x).
1362 --
1363 -- do { x'1 <- gensym "x"
1364 -- ; x'2 <- gensym "x"
1365 -- ; doE [ BindSt (pvar x'1) [| f 1 |]
1366 -- , BindSt (pvar x'2) [| f x |]
1367 -- , NoBindSt [| g x |]
1368 -- ]
1369 -- }
1370
1371 -- The strategy is to translate a whole list of do-bindings by building a
1372 -- bigger environment, and a bigger set of meta bindings
1373 -- (like: x'1 <- gensym "x" ) and then combining these with the translations
1374 -- of the expressions within the Do
1375
1376 -----------------------------------------------------------------------------
1377 -- The helper function repSts computes the translation of each sub expression
1378 -- and a bunch of prefix bindings denoting the dynamic renaming.
1379
1380 repLSts :: [LStmt GhcRn (LHsExpr GhcRn)] -> DsM ([GenSymBind], [Core TH.StmtQ])
1381 repLSts stmts = repSts (map unLoc stmts)
1382
1383 repSts :: [Stmt GhcRn (LHsExpr GhcRn)] -> DsM ([GenSymBind], [Core TH.StmtQ])
1384 repSts (BindStmt p e _ _ _ : ss) =
1385 do { e2 <- repLE e
1386 ; ss1 <- mkGenSyms (collectPatBinders p)
1387 ; addBinds ss1 $ do {
1388 ; p1 <- repLP p;
1389 ; (ss2,zs) <- repSts ss
1390 ; z <- repBindSt p1 e2
1391 ; return (ss1++ss2, z : zs) }}
1392 repSts (LetStmt (L _ bs) : ss) =
1393 do { (ss1,ds) <- repBinds bs
1394 ; z <- repLetSt ds
1395 ; (ss2,zs) <- addBinds ss1 (repSts ss)
1396 ; return (ss1++ss2, z : zs) }
1397 repSts (BodyStmt e _ _ _ : ss) =
1398 do { e2 <- repLE e
1399 ; z <- repNoBindSt e2
1400 ; (ss2,zs) <- repSts ss
1401 ; return (ss2, z : zs) }
1402 repSts (ParStmt stmt_blocks _ _ _ : ss) =
1403 do { (ss_s, stmt_blocks1) <- mapAndUnzipM rep_stmt_block stmt_blocks
1404 ; let stmt_blocks2 = nonEmptyCoreList stmt_blocks1
1405 ss1 = concat ss_s
1406 ; z <- repParSt stmt_blocks2
1407 ; (ss2, zs) <- addBinds ss1 (repSts ss)
1408 ; return (ss1++ss2, z : zs) }
1409 where
1410 rep_stmt_block :: ParStmtBlock GhcRn GhcRn
1411 -> DsM ([GenSymBind], Core [TH.StmtQ])
1412 rep_stmt_block (ParStmtBlock stmts _ _) =
1413 do { (ss1, zs) <- repSts (map unLoc stmts)
1414 ; zs1 <- coreList stmtQTyConName zs
1415 ; return (ss1, zs1) }
1416 repSts [LastStmt e _ _]
1417 = do { e2 <- repLE e
1418 ; z <- repNoBindSt e2
1419 ; return ([], [z]) }
1420 repSts [] = return ([],[])
1421 repSts other = notHandled "Exotic statement" (ppr other)
1422
1423
1424 -----------------------------------------------------------
1425 -- Bindings
1426 -----------------------------------------------------------
1427
1428 repBinds :: HsLocalBinds GhcRn -> DsM ([GenSymBind], Core [TH.DecQ])
1429 repBinds EmptyLocalBinds
1430 = do { core_list <- coreList decQTyConName []
1431 ; return ([], core_list) }
1432
1433 repBinds b@(HsIPBinds _) = notHandled "Implicit parameters" (ppr b)
1434
1435 repBinds (HsValBinds decs)
1436 = do { let { bndrs = hsSigTvBinders decs ++ collectHsValBinders decs }
1437 -- No need to worry about detailed scopes within
1438 -- the binding group, because we are talking Names
1439 -- here, so we can safely treat it as a mutually
1440 -- recursive group
1441 -- For hsSigTvBinders see Note [Scoped type variables in bindings]
1442 ; ss <- mkGenSyms bndrs
1443 ; prs <- addBinds ss (rep_val_binds decs)
1444 ; core_list <- coreList decQTyConName
1445 (de_loc (sort_by_loc prs))
1446 ; return (ss, core_list) }
1447
1448 rep_val_binds :: HsValBinds GhcRn -> DsM [(SrcSpan, Core TH.DecQ)]
1449 -- Assumes: all the binders of the binding are already in the meta-env
1450 rep_val_binds (ValBindsOut binds sigs)
1451 = do { core1 <- rep_binds' (unionManyBags (map snd binds))
1452 ; core2 <- rep_sigs' sigs
1453 ; return (core1 ++ core2) }
1454 rep_val_binds (ValBindsIn _ _)
1455 = panic "rep_val_binds: ValBindsIn"
1456
1457 rep_binds :: LHsBinds GhcRn -> DsM [Core TH.DecQ]
1458 rep_binds binds = do { binds_w_locs <- rep_binds' binds
1459 ; return (de_loc (sort_by_loc binds_w_locs)) }
1460
1461 rep_binds' :: LHsBinds GhcRn -> DsM [(SrcSpan, Core TH.DecQ)]
1462 rep_binds' = mapM rep_bind . bagToList
1463
1464 rep_bind :: LHsBind GhcRn -> DsM (SrcSpan, Core TH.DecQ)
1465 -- Assumes: all the binders of the binding are already in the meta-env
1466
1467 -- Note GHC treats declarations of a variable (not a pattern)
1468 -- e.g. x = g 5 as a Fun MonoBinds. This is indicated by a single match
1469 -- with an empty list of patterns
1470 rep_bind (L loc (FunBind
1471 { fun_id = fn,
1472 fun_matches = MG { mg_alts
1473 = L _ [L _ (Match _ [] _
1474 (GRHSs guards (L _ wheres)))] } }))
1475 = do { (ss,wherecore) <- repBinds wheres
1476 ; guardcore <- addBinds ss (repGuards guards)
1477 ; fn' <- lookupLBinder fn
1478 ; p <- repPvar fn'
1479 ; ans <- repVal p guardcore wherecore
1480 ; ans' <- wrapGenSyms ss ans
1481 ; return (loc, ans') }
1482
1483 rep_bind (L loc (FunBind { fun_id = fn
1484 , fun_matches = MG { mg_alts = L _ ms } }))
1485 = do { ms1 <- mapM repClauseTup ms
1486 ; fn' <- lookupLBinder fn
1487 ; ans <- repFun fn' (nonEmptyCoreList ms1)
1488 ; return (loc, ans) }
1489
1490 rep_bind (L loc (PatBind { pat_lhs = pat
1491 , pat_rhs = GRHSs guards (L _ wheres) }))
1492 = do { patcore <- repLP pat
1493 ; (ss,wherecore) <- repBinds wheres
1494 ; guardcore <- addBinds ss (repGuards guards)
1495 ; ans <- repVal patcore guardcore wherecore
1496 ; ans' <- wrapGenSyms ss ans
1497 ; return (loc, ans') }
1498
1499 rep_bind (L _ (VarBind { var_id = v, var_rhs = e}))
1500 = do { v' <- lookupBinder v
1501 ; e2 <- repLE e
1502 ; x <- repNormal e2
1503 ; patcore <- repPvar v'
1504 ; empty_decls <- coreList decQTyConName []
1505 ; ans <- repVal patcore x empty_decls
1506 ; return (srcLocSpan (getSrcLoc v), ans) }
1507
1508 rep_bind (L _ (AbsBinds {})) = panic "rep_bind: AbsBinds"
1509 rep_bind (L _ (AbsBindsSig {})) = panic "rep_bind: AbsBindsSig"
1510 rep_bind (L loc (PatSynBind (PSB { psb_id = syn
1511 , psb_fvs = _fvs
1512 , psb_args = args
1513 , psb_def = pat
1514 , psb_dir = dir })))
1515 = do { syn' <- lookupLBinder syn
1516 ; dir' <- repPatSynDir dir
1517 ; ss <- mkGenArgSyms args
1518 ; patSynD' <- addBinds ss (
1519 do { args' <- repPatSynArgs args
1520 ; pat' <- repLP pat
1521 ; repPatSynD syn' args' dir' pat' })
1522 ; patSynD'' <- wrapGenArgSyms args ss patSynD'
1523 ; return (loc, patSynD'') }
1524 where
1525 mkGenArgSyms :: HsPatSynDetails (Located Name) -> DsM [GenSymBind]
1526 -- for Record Pattern Synonyms we want to conflate the selector
1527 -- and the pattern-only names in order to provide a nicer TH
1528 -- API. Whereas inside GHC, record pattern synonym selectors and
1529 -- their pattern-only bound right hand sides have different names,
1530 -- we want to treat them the same in TH. This is the reason why we
1531 -- need an adjusted mkGenArgSyms in the `RecordPatSyn` case below.
1532 mkGenArgSyms (PrefixPatSyn args) = mkGenSyms (map unLoc args)
1533 mkGenArgSyms (InfixPatSyn arg1 arg2) = mkGenSyms [unLoc arg1, unLoc arg2]
1534 mkGenArgSyms (RecordPatSyn fields)
1535 = do { let pats = map (unLoc . recordPatSynPatVar) fields
1536 sels = map (unLoc . recordPatSynSelectorId) fields
1537 ; ss <- mkGenSyms sels
1538 ; return $ replaceNames (zip sels pats) ss }
1539
1540 replaceNames selsPats genSyms
1541 = [ (pat, id) | (sel, id) <- genSyms, (sel', pat) <- selsPats
1542 , sel == sel' ]
1543
1544 wrapGenArgSyms :: HsPatSynDetails (Located Name)
1545 -> [GenSymBind] -> Core TH.DecQ -> DsM (Core TH.DecQ)
1546 wrapGenArgSyms (RecordPatSyn _) _ dec = return dec
1547 wrapGenArgSyms _ ss dec = wrapGenSyms ss dec
1548
1549 repPatSynD :: Core TH.Name
1550 -> Core TH.PatSynArgsQ
1551 -> Core TH.PatSynDirQ
1552 -> Core TH.PatQ
1553 -> DsM (Core TH.DecQ)
1554 repPatSynD (MkC syn) (MkC args) (MkC dir) (MkC pat)
1555 = rep2 patSynDName [syn, args, dir, pat]
1556
1557 repPatSynArgs :: HsPatSynDetails (Located Name) -> DsM (Core TH.PatSynArgsQ)
1558 repPatSynArgs (PrefixPatSyn args)
1559 = do { args' <- repList nameTyConName lookupLOcc args
1560 ; repPrefixPatSynArgs args' }
1561 repPatSynArgs (InfixPatSyn arg1 arg2)
1562 = do { arg1' <- lookupLOcc arg1
1563 ; arg2' <- lookupLOcc arg2
1564 ; repInfixPatSynArgs arg1' arg2' }
1565 repPatSynArgs (RecordPatSyn fields)
1566 = do { sels' <- repList nameTyConName lookupLOcc sels
1567 ; repRecordPatSynArgs sels' }
1568 where sels = map recordPatSynSelectorId fields
1569
1570 repPrefixPatSynArgs :: Core [TH.Name] -> DsM (Core TH.PatSynArgsQ)
1571 repPrefixPatSynArgs (MkC nms) = rep2 prefixPatSynName [nms]
1572
1573 repInfixPatSynArgs :: Core TH.Name -> Core TH.Name -> DsM (Core TH.PatSynArgsQ)
1574 repInfixPatSynArgs (MkC nm1) (MkC nm2) = rep2 infixPatSynName [nm1, nm2]
1575
1576 repRecordPatSynArgs :: Core [TH.Name]
1577 -> DsM (Core TH.PatSynArgsQ)
1578 repRecordPatSynArgs (MkC sels) = rep2 recordPatSynName [sels]
1579
1580 repPatSynDir :: HsPatSynDir GhcRn -> DsM (Core TH.PatSynDirQ)
1581 repPatSynDir Unidirectional = rep2 unidirPatSynName []
1582 repPatSynDir ImplicitBidirectional = rep2 implBidirPatSynName []
1583 repPatSynDir (ExplicitBidirectional (MG { mg_alts = L _ clauses }))
1584 = do { clauses' <- mapM repClauseTup clauses
1585 ; repExplBidirPatSynDir (nonEmptyCoreList clauses') }
1586
1587 repExplBidirPatSynDir :: Core [TH.ClauseQ] -> DsM (Core TH.PatSynDirQ)
1588 repExplBidirPatSynDir (MkC cls) = rep2 explBidirPatSynName [cls]
1589
1590
1591 -----------------------------------------------------------------------------
1592 -- Since everything in a Bind is mutually recursive we need rename all
1593 -- all the variables simultaneously. For example:
1594 -- [| AndMonoBinds (f x = x + g 2) (g x = f 1 + 2) |] would translate to
1595 -- do { f'1 <- gensym "f"
1596 -- ; g'2 <- gensym "g"
1597 -- ; [ do { x'3 <- gensym "x"; fun f'1 [pvar x'3] [| x + g2 |]},
1598 -- do { x'4 <- gensym "x"; fun g'2 [pvar x'4] [| f 1 + 2 |]}
1599 -- ]}
1600 -- This requires collecting the bindings (f'1 <- gensym "f"), and the
1601 -- environment ( f |-> f'1 ) from each binding, and then unioning them
1602 -- together. As we do this we collect GenSymBinds's which represent the renamed
1603 -- variables bound by the Bindings. In order not to lose track of these
1604 -- representations we build a shadow datatype MB with the same structure as
1605 -- MonoBinds, but which has slots for the representations
1606
1607
1608 -----------------------------------------------------------------------------
1609 -- GHC allows a more general form of lambda abstraction than specified
1610 -- by Haskell 98. In particular it allows guarded lambda's like :
1611 -- (\ x | even x -> 0 | odd x -> 1) at the moment we can't represent this in
1612 -- Haskell Template's Meta.Exp type so we punt if it isn't a simple thing like
1613 -- (\ p1 .. pn -> exp) by causing an error.
1614
1615 repLambda :: LMatch GhcRn (LHsExpr GhcRn) -> DsM (Core TH.ExpQ)
1616 repLambda (L _ (Match _ ps _ (GRHSs [L _ (GRHS [] e)] (L _ EmptyLocalBinds))))
1617 = do { let bndrs = collectPatsBinders ps ;
1618 ; ss <- mkGenSyms bndrs
1619 ; lam <- addBinds ss (
1620 do { xs <- repLPs ps; body <- repLE e; repLam xs body })
1621 ; wrapGenSyms ss lam }
1622
1623 repLambda (L _ m) = notHandled "Guarded labmdas" (pprMatch m)
1624
1625
1626 -----------------------------------------------------------------------------
1627 -- Patterns
1628 -- repP deals with patterns. It assumes that we have already
1629 -- walked over the pattern(s) once to collect the binders, and
1630 -- have extended the environment. So every pattern-bound
1631 -- variable should already appear in the environment.
1632
1633 -- Process a list of patterns
1634 repLPs :: [LPat GhcRn] -> DsM (Core [TH.PatQ])
1635 repLPs ps = repList patQTyConName repLP ps
1636
1637 repLP :: LPat GhcRn -> DsM (Core TH.PatQ)
1638 repLP (L _ p) = repP p
1639
1640 repP :: Pat GhcRn -> DsM (Core TH.PatQ)
1641 repP (WildPat _) = repPwild
1642 repP (LitPat l) = do { l2 <- repLiteral l; repPlit l2 }
1643 repP (VarPat (L _ x)) = do { x' <- lookupBinder x; repPvar x' }
1644 repP (LazyPat p) = do { p1 <- repLP p; repPtilde p1 }
1645 repP (BangPat p) = do { p1 <- repLP p; repPbang p1 }
1646 repP (AsPat x p) = do { x' <- lookupLBinder x; p1 <- repLP p; repPaspat x' p1 }
1647 repP (ParPat p) = repLP p
1648 repP (ListPat ps _ Nothing) = do { qs <- repLPs ps; repPlist qs }
1649 repP (ListPat ps ty1 (Just (_,e))) = do { p <- repP (ListPat ps ty1 Nothing); e' <- repE (syn_expr e); repPview e' p}
1650 repP (TuplePat ps boxed _)
1651 | isBoxed boxed = do { qs <- repLPs ps; repPtup qs }
1652 | otherwise = do { qs <- repLPs ps; repPunboxedTup qs }
1653 repP (SumPat p alt arity _) = do { p1 <- repLP p; repPunboxedSum p1 alt arity }
1654 repP (ConPatIn dc details)
1655 = do { con_str <- lookupLOcc dc
1656 ; case details of
1657 PrefixCon ps -> do { qs <- repLPs ps; repPcon con_str qs }
1658 RecCon rec -> do { fps <- repList fieldPatQTyConName rep_fld (rec_flds rec)
1659 ; repPrec con_str fps }
1660 InfixCon p1 p2 -> do { p1' <- repLP p1;
1661 p2' <- repLP p2;
1662 repPinfix p1' con_str p2' }
1663 }
1664 where
1665 rep_fld :: LHsRecField GhcRn (LPat GhcRn) -> DsM (Core (TH.Name,TH.PatQ))
1666 rep_fld (L _ fld) = do { MkC v <- lookupLOcc (hsRecFieldSel fld)
1667 ; MkC p <- repLP (hsRecFieldArg fld)
1668 ; rep2 fieldPatName [v,p] }
1669
1670 repP (NPat (L _ l) Nothing _ _) = do { a <- repOverloadedLiteral l; repPlit a }
1671 repP (ViewPat e p _) = do { e' <- repLE e; p' <- repLP p; repPview e' p' }
1672 repP p@(NPat _ (Just _) _ _) = notHandled "Negative overloaded patterns" (ppr p)
1673 repP (SigPatIn p t) = do { p' <- repLP p
1674 ; t' <- repLTy (hsSigWcType t)
1675 ; repPsig p' t' }
1676 repP (SplicePat splice) = repSplice splice
1677
1678 repP other = notHandled "Exotic pattern" (ppr other)
1679
1680 ----------------------------------------------------------
1681 -- Declaration ordering helpers
1682
1683 sort_by_loc :: [(SrcSpan, a)] -> [(SrcSpan, a)]
1684 sort_by_loc xs = sortBy comp xs
1685 where comp x y = compare (fst x) (fst y)
1686
1687 de_loc :: [(a, b)] -> [b]
1688 de_loc = map snd
1689
1690 ----------------------------------------------------------
1691 -- The meta-environment
1692
1693 -- A name/identifier association for fresh names of locally bound entities
1694 type GenSymBind = (Name, Id) -- Gensym the string and bind it to the Id
1695 -- I.e. (x, x_id) means
1696 -- let x_id = gensym "x" in ...
1697
1698 -- Generate a fresh name for a locally bound entity
1699
1700 mkGenSyms :: [Name] -> DsM [GenSymBind]
1701 -- We can use the existing name. For example:
1702 -- [| \x_77 -> x_77 + x_77 |]
1703 -- desugars to
1704 -- do { x_77 <- genSym "x"; .... }
1705 -- We use the same x_77 in the desugared program, but with the type Bndr
1706 -- instead of Int
1707 --
1708 -- We do make it an Internal name, though (hence localiseName)
1709 --
1710 -- Nevertheless, it's monadic because we have to generate nameTy
1711 mkGenSyms ns = do { var_ty <- lookupType nameTyConName
1712 ; return [(nm, mkLocalId (localiseName nm) var_ty) | nm <- ns] }
1713
1714
1715 addBinds :: [GenSymBind] -> DsM a -> DsM a
1716 -- Add a list of fresh names for locally bound entities to the
1717 -- meta environment (which is part of the state carried around
1718 -- by the desugarer monad)
1719 addBinds bs m = dsExtendMetaEnv (mkNameEnv [(n,DsBound id) | (n,id) <- bs]) m
1720
1721 -- Look up a locally bound name
1722 --
1723 lookupLBinder :: Located Name -> DsM (Core TH.Name)
1724 lookupLBinder (L _ n) = lookupBinder n
1725
1726 lookupBinder :: Name -> DsM (Core TH.Name)
1727 lookupBinder = lookupOcc
1728 -- Binders are brought into scope before the pattern or what-not is
1729 -- desugared. Moreover, in instance declaration the binder of a method
1730 -- will be the selector Id and hence a global; so we need the
1731 -- globalVar case of lookupOcc
1732
1733 -- Look up a name that is either locally bound or a global name
1734 --
1735 -- * If it is a global name, generate the "original name" representation (ie,
1736 -- the <module>:<name> form) for the associated entity
1737 --
1738 lookupLOcc :: Located Name -> DsM (Core TH.Name)
1739 -- Lookup an occurrence; it can't be a splice.
1740 -- Use the in-scope bindings if they exist
1741 lookupLOcc (L _ n) = lookupOcc n
1742
1743 lookupOcc :: Name -> DsM (Core TH.Name)
1744 lookupOcc n
1745 = do { mb_val <- dsLookupMetaEnv n ;
1746 case mb_val of
1747 Nothing -> globalVar n
1748 Just (DsBound x) -> return (coreVar x)
1749 Just (DsSplice _) -> pprPanic "repE:lookupOcc" (ppr n)
1750 }
1751
1752 globalVar :: Name -> DsM (Core TH.Name)
1753 -- Not bound by the meta-env
1754 -- Could be top-level; or could be local
1755 -- f x = $(g [| x |])
1756 -- Here the x will be local
1757 globalVar name
1758 | isExternalName name
1759 = do { MkC mod <- coreStringLit name_mod
1760 ; MkC pkg <- coreStringLit name_pkg
1761 ; MkC occ <- nameLit name
1762 ; rep2 mk_varg [pkg,mod,occ] }
1763 | otherwise
1764 = do { MkC occ <- nameLit name
1765 ; MkC uni <- coreIntLit (getKey (getUnique name))
1766 ; rep2 mkNameLName [occ,uni] }
1767 where
1768 mod = ASSERT( isExternalName name) nameModule name
1769 name_mod = moduleNameString (moduleName mod)
1770 name_pkg = unitIdString (moduleUnitId mod)
1771 name_occ = nameOccName name
1772 mk_varg | OccName.isDataOcc name_occ = mkNameG_dName
1773 | OccName.isVarOcc name_occ = mkNameG_vName
1774 | OccName.isTcOcc name_occ = mkNameG_tcName
1775 | otherwise = pprPanic "DsMeta.globalVar" (ppr name)
1776
1777 lookupType :: Name -- Name of type constructor (e.g. TH.ExpQ)
1778 -> DsM Type -- The type
1779 lookupType tc_name = do { tc <- dsLookupTyCon tc_name ;
1780 return (mkTyConApp tc []) }
1781
1782 wrapGenSyms :: [GenSymBind]
1783 -> Core (TH.Q a) -> DsM (Core (TH.Q a))
1784 -- wrapGenSyms [(nm1,id1), (nm2,id2)] y
1785 -- --> bindQ (gensym nm1) (\ id1 ->
1786 -- bindQ (gensym nm2 (\ id2 ->
1787 -- y))
1788
1789 wrapGenSyms binds body@(MkC b)
1790 = do { var_ty <- lookupType nameTyConName
1791 ; go var_ty binds }
1792 where
1793 [elt_ty] = tcTyConAppArgs (exprType b)
1794 -- b :: Q a, so we can get the type 'a' by looking at the
1795 -- argument type. NB: this relies on Q being a data/newtype,
1796 -- not a type synonym
1797
1798 go _ [] = return body
1799 go var_ty ((name,id) : binds)
1800 = do { MkC body' <- go var_ty binds
1801 ; lit_str <- nameLit name
1802 ; gensym_app <- repGensym lit_str
1803 ; repBindQ var_ty elt_ty
1804 gensym_app (MkC (Lam id body')) }
1805
1806 nameLit :: Name -> DsM (Core String)
1807 nameLit n = coreStringLit (occNameString (nameOccName n))
1808
1809 occNameLit :: OccName -> DsM (Core String)
1810 occNameLit name = coreStringLit (occNameString name)
1811
1812
1813 -- %*********************************************************************
1814 -- %* *
1815 -- Constructing code
1816 -- %* *
1817 -- %*********************************************************************
1818
1819 -----------------------------------------------------------------------------
1820 -- PHANTOM TYPES for consistency. In order to make sure we do this correct
1821 -- we invent a new datatype which uses phantom types.
1822
1823 newtype Core a = MkC CoreExpr
1824 unC :: Core a -> CoreExpr
1825 unC (MkC x) = x
1826
1827 rep2 :: Name -> [ CoreExpr ] -> DsM (Core a)
1828 rep2 n xs = do { id <- dsLookupGlobalId n
1829 ; return (MkC (foldl App (Var id) xs)) }
1830
1831 dataCon' :: Name -> [CoreExpr] -> DsM (Core a)
1832 dataCon' n args = do { id <- dsLookupDataCon n
1833 ; return $ MkC $ mkCoreConApps id args }
1834
1835 dataCon :: Name -> DsM (Core a)
1836 dataCon n = dataCon' n []
1837
1838
1839 -- %*********************************************************************
1840 -- %* *
1841 -- The 'smart constructors'
1842 -- %* *
1843 -- %*********************************************************************
1844
1845 --------------- Patterns -----------------
1846 repPlit :: Core TH.Lit -> DsM (Core TH.PatQ)
1847 repPlit (MkC l) = rep2 litPName [l]
1848
1849 repPvar :: Core TH.Name -> DsM (Core TH.PatQ)
1850 repPvar (MkC s) = rep2 varPName [s]
1851
1852 repPtup :: Core [TH.PatQ] -> DsM (Core TH.PatQ)
1853 repPtup (MkC ps) = rep2 tupPName [ps]
1854
1855 repPunboxedTup :: Core [TH.PatQ] -> DsM (Core TH.PatQ)
1856 repPunboxedTup (MkC ps) = rep2 unboxedTupPName [ps]
1857
1858 repPunboxedSum :: Core TH.PatQ -> TH.SumAlt -> TH.SumArity -> DsM (Core TH.PatQ)
1859 -- Note: not Core TH.SumAlt or Core TH.SumArity; it's easier to be direct here
1860 repPunboxedSum (MkC p) alt arity
1861 = do { dflags <- getDynFlags
1862 ; rep2 unboxedSumPName [ p
1863 , mkIntExprInt dflags alt
1864 , mkIntExprInt dflags arity ] }
1865
1866 repPcon :: Core TH.Name -> Core [TH.PatQ] -> DsM (Core TH.PatQ)
1867 repPcon (MkC s) (MkC ps) = rep2 conPName [s, ps]
1868
1869 repPrec :: Core TH.Name -> Core [(TH.Name,TH.PatQ)] -> DsM (Core TH.PatQ)
1870 repPrec (MkC c) (MkC rps) = rep2 recPName [c,rps]
1871
1872 repPinfix :: Core TH.PatQ -> Core TH.Name -> Core TH.PatQ -> DsM (Core TH.PatQ)
1873 repPinfix (MkC p1) (MkC n) (MkC p2) = rep2 infixPName [p1, n, p2]
1874
1875 repPtilde :: Core TH.PatQ -> DsM (Core TH.PatQ)
1876 repPtilde (MkC p) = rep2 tildePName [p]
1877
1878 repPbang :: Core TH.PatQ -> DsM (Core TH.PatQ)
1879 repPbang (MkC p) = rep2 bangPName [p]
1880
1881 repPaspat :: Core TH.Name -> Core TH.PatQ -> DsM (Core TH.PatQ)
1882 repPaspat (MkC s) (MkC p) = rep2 asPName [s, p]
1883
1884 repPwild :: DsM (Core TH.PatQ)
1885 repPwild = rep2 wildPName []
1886
1887 repPlist :: Core [TH.PatQ] -> DsM (Core TH.PatQ)
1888 repPlist (MkC ps) = rep2 listPName [ps]
1889
1890 repPview :: Core TH.ExpQ -> Core TH.PatQ -> DsM (Core TH.PatQ)
1891 repPview (MkC e) (MkC p) = rep2 viewPName [e,p]
1892
1893 repPsig :: Core TH.PatQ -> Core TH.TypeQ -> DsM (Core TH.PatQ)
1894 repPsig (MkC p) (MkC t) = rep2 sigPName [p, t]
1895
1896 --------------- Expressions -----------------
1897 repVarOrCon :: Name -> Core TH.Name -> DsM (Core TH.ExpQ)
1898 repVarOrCon vc str | isDataOcc (nameOccName vc) = repCon str
1899 | otherwise = repVar str
1900
1901 repVar :: Core TH.Name -> DsM (Core TH.ExpQ)
1902 repVar (MkC s) = rep2 varEName [s]
1903
1904 repCon :: Core TH.Name -> DsM (Core TH.ExpQ)
1905 repCon (MkC s) = rep2 conEName [s]
1906
1907 repLit :: Core TH.Lit -> DsM (Core TH.ExpQ)
1908 repLit (MkC c) = rep2 litEName [c]
1909
1910 repApp :: Core TH.ExpQ -> Core TH.ExpQ -> DsM (Core TH.ExpQ)
1911 repApp (MkC x) (MkC y) = rep2 appEName [x,y]
1912
1913 repAppType :: Core TH.ExpQ -> Core TH.TypeQ -> DsM (Core TH.ExpQ)
1914 repAppType (MkC x) (MkC y) = rep2 appTypeEName [x,y]
1915
1916 repLam :: Core [TH.PatQ] -> Core TH.ExpQ -> DsM (Core TH.ExpQ)
1917 repLam (MkC ps) (MkC e) = rep2 lamEName [ps, e]
1918
1919 repLamCase :: Core [TH.MatchQ] -> DsM (Core TH.ExpQ)
1920 repLamCase (MkC ms) = rep2 lamCaseEName [ms]
1921
1922 repTup :: Core [TH.ExpQ] -> DsM (Core TH.ExpQ)
1923 repTup (MkC es) = rep2 tupEName [es]
1924
1925 repUnboxedTup :: Core [TH.ExpQ] -> DsM (Core TH.ExpQ)
1926 repUnboxedTup (MkC es) = rep2 unboxedTupEName [es]
1927
1928 repUnboxedSum :: Core TH.ExpQ -> TH.SumAlt -> TH.SumArity -> DsM (Core TH.ExpQ)
1929 -- Note: not Core TH.SumAlt or Core TH.SumArity; it's easier to be direct here
1930 repUnboxedSum (MkC e) alt arity
1931 = do { dflags <- getDynFlags
1932 ; rep2 unboxedSumEName [ e
1933 , mkIntExprInt dflags alt
1934 , mkIntExprInt dflags arity ] }
1935
1936 repCond :: Core TH.ExpQ -> Core TH.ExpQ -> Core TH.ExpQ -> DsM (Core TH.ExpQ)
1937 repCond (MkC x) (MkC y) (MkC z) = rep2 condEName [x,y,z]
1938
1939 repMultiIf :: Core [TH.Q (TH.Guard, TH.Exp)] -> DsM (Core TH.ExpQ)
1940 repMultiIf (MkC alts) = rep2 multiIfEName [alts]
1941
1942 repLetE :: Core [TH.DecQ] -> Core TH.ExpQ -> DsM (Core TH.ExpQ)
1943 repLetE (MkC ds) (MkC e) = rep2 letEName [ds, e]
1944
1945 repCaseE :: Core TH.ExpQ -> Core [TH.MatchQ] -> DsM( Core TH.ExpQ)
1946 repCaseE (MkC e) (MkC ms) = rep2 caseEName [e, ms]
1947
1948 repDoE :: Core [TH.StmtQ] -> DsM (Core TH.ExpQ)
1949 repDoE (MkC ss) = rep2 doEName [ss]
1950
1951 repComp :: Core [TH.StmtQ] -> DsM (Core TH.ExpQ)
1952 repComp (MkC ss) = rep2 compEName [ss]
1953
1954 repListExp :: Core [TH.ExpQ] -> DsM (Core TH.ExpQ)
1955 repListExp (MkC es) = rep2 listEName [es]
1956
1957 repSigExp :: Core TH.ExpQ -> Core TH.TypeQ -> DsM (Core TH.ExpQ)
1958 repSigExp (MkC e) (MkC t) = rep2 sigEName [e,t]
1959
1960 repRecCon :: Core TH.Name -> Core [TH.Q TH.FieldExp]-> DsM (Core TH.ExpQ)
1961 repRecCon (MkC c) (MkC fs) = rep2 recConEName [c,fs]
1962
1963 repRecUpd :: Core TH.ExpQ -> Core [TH.Q TH.FieldExp] -> DsM (Core TH.ExpQ)
1964 repRecUpd (MkC e) (MkC fs) = rep2 recUpdEName [e,fs]
1965
1966 repFieldExp :: Core TH.Name -> Core TH.ExpQ -> DsM (Core (TH.Q TH.FieldExp))
1967 repFieldExp (MkC n) (MkC x) = rep2 fieldExpName [n,x]
1968
1969 repInfixApp :: Core TH.ExpQ -> Core TH.ExpQ -> Core TH.ExpQ -> DsM (Core TH.ExpQ)
1970 repInfixApp (MkC x) (MkC y) (MkC z) = rep2 infixAppName [x,y,z]
1971
1972 repSectionL :: Core TH.ExpQ -> Core TH.ExpQ -> DsM (Core TH.ExpQ)
1973 repSectionL (MkC x) (MkC y) = rep2 sectionLName [x,y]
1974
1975 repSectionR :: Core TH.ExpQ -> Core TH.ExpQ -> DsM (Core TH.ExpQ)
1976 repSectionR (MkC x) (MkC y) = rep2 sectionRName [x,y]
1977
1978 ------------ Right hand sides (guarded expressions) ----
1979 repGuarded :: Core [TH.Q (TH.Guard, TH.Exp)] -> DsM (Core TH.BodyQ)
1980 repGuarded (MkC pairs) = rep2 guardedBName [pairs]
1981
1982 repNormal :: Core TH.ExpQ -> DsM (Core TH.BodyQ)
1983 repNormal (MkC e) = rep2 normalBName [e]
1984
1985 ------------ Guards ----
1986 repLNormalGE :: LHsExpr GhcRn -> LHsExpr GhcRn
1987 -> DsM (Core (TH.Q (TH.Guard, TH.Exp)))
1988 repLNormalGE g e = do g' <- repLE g
1989 e' <- repLE e
1990 repNormalGE g' e'
1991
1992 repNormalGE :: Core TH.ExpQ -> Core TH.ExpQ -> DsM (Core (TH.Q (TH.Guard, TH.Exp)))
1993 repNormalGE (MkC g) (MkC e) = rep2 normalGEName [g, e]
1994
1995 repPatGE :: Core [TH.StmtQ] -> Core TH.ExpQ -> DsM (Core (TH.Q (TH.Guard, TH.Exp)))
1996 repPatGE (MkC ss) (MkC e) = rep2 patGEName [ss, e]
1997
1998 ------------- Stmts -------------------
1999 repBindSt :: Core TH.PatQ -> Core TH.ExpQ -> DsM (Core TH.StmtQ)
2000 repBindSt (MkC p) (MkC e) = rep2 bindSName [p,e]
2001
2002 repLetSt :: Core [TH.DecQ] -> DsM (Core TH.StmtQ)
2003 repLetSt (MkC ds) = rep2 letSName [ds]
2004
2005 repNoBindSt :: Core TH.ExpQ -> DsM (Core TH.StmtQ)
2006 repNoBindSt (MkC e) = rep2 noBindSName [e]
2007
2008 repParSt :: Core [[TH.StmtQ]] -> DsM (Core TH.StmtQ)
2009 repParSt (MkC sss) = rep2 parSName [sss]
2010
2011 -------------- Range (Arithmetic sequences) -----------
2012 repFrom :: Core TH.ExpQ -> DsM (Core TH.ExpQ)
2013 repFrom (MkC x) = rep2 fromEName [x]
2014
2015 repFromThen :: Core TH.ExpQ -> Core TH.ExpQ -> DsM (Core TH.ExpQ)
2016 repFromThen (MkC x) (MkC y) = rep2 fromThenEName [x,y]
2017
2018 repFromTo :: Core TH.ExpQ -> Core TH.ExpQ -> DsM (Core TH.ExpQ)
2019 repFromTo (MkC x) (MkC y) = rep2 fromToEName [x,y]
2020
2021 repFromThenTo :: Core TH.ExpQ -> Core TH.ExpQ -> Core TH.ExpQ -> DsM (Core TH.ExpQ)
2022 repFromThenTo (MkC x) (MkC y) (MkC z) = rep2 fromThenToEName [x,y,z]
2023
2024 ------------ Match and Clause Tuples -----------
2025 repMatch :: Core TH.PatQ -> Core TH.BodyQ -> Core [TH.DecQ] -> DsM (Core TH.MatchQ)
2026 repMatch (MkC p) (MkC bod) (MkC ds) = rep2 matchName [p, bod, ds]
2027
2028 repClause :: Core [TH.PatQ] -> Core TH.BodyQ -> Core [TH.DecQ] -> DsM (Core TH.ClauseQ)
2029 repClause (MkC ps) (MkC bod) (MkC ds) = rep2 clauseName [ps, bod, ds]
2030
2031 -------------- Dec -----------------------------
2032 repVal :: Core TH.PatQ -> Core TH.BodyQ -> Core [TH.DecQ] -> DsM (Core TH.DecQ)
2033 repVal (MkC p) (MkC b) (MkC ds) = rep2 valDName [p, b, ds]
2034
2035 repFun :: Core TH.Name -> Core [TH.ClauseQ] -> DsM (Core TH.DecQ)
2036 repFun (MkC nm) (MkC b) = rep2 funDName [nm, b]
2037
2038 repData :: Core TH.CxtQ -> Core TH.Name -> Core [TH.TyVarBndr]
2039 -> Maybe (Core [TH.TypeQ]) -> Core (Maybe TH.Kind)
2040 -> Core [TH.ConQ] -> Core [TH.DerivClauseQ] -> DsM (Core TH.DecQ)
2041 repData (MkC cxt) (MkC nm) (MkC tvs) Nothing (MkC ksig) (MkC cons) (MkC derivs)
2042 = rep2 dataDName [cxt, nm, tvs, ksig, cons, derivs]
2043 repData (MkC cxt) (MkC nm) (MkC _) (Just (MkC tys)) (MkC ksig) (MkC cons)
2044 (MkC derivs)
2045 = rep2 dataInstDName [cxt, nm, tys, ksig, cons, derivs]
2046
2047 repNewtype :: Core TH.CxtQ -> Core TH.Name -> Core [TH.TyVarBndr]
2048 -> Maybe (Core [TH.TypeQ]) -> Core (Maybe TH.Kind)
2049 -> Core TH.ConQ -> Core [TH.DerivClauseQ] -> DsM (Core TH.DecQ)
2050 repNewtype (MkC cxt) (MkC nm) (MkC tvs) Nothing (MkC ksig) (MkC con)
2051 (MkC derivs)
2052 = rep2 newtypeDName [cxt, nm, tvs, ksig, con, derivs]
2053 repNewtype (MkC cxt) (MkC nm) (MkC _) (Just (MkC tys)) (MkC ksig) (MkC con)
2054 (MkC derivs)
2055 = rep2 newtypeInstDName [cxt, nm, tys, ksig, con, derivs]
2056
2057 repTySyn :: Core TH.Name -> Core [TH.TyVarBndr]
2058 -> Core TH.TypeQ -> DsM (Core TH.DecQ)
2059 repTySyn (MkC nm) (MkC tvs) (MkC rhs)
2060 = rep2 tySynDName [nm, tvs, rhs]
2061
2062 repInst :: Core (Maybe TH.Overlap) ->
2063 Core TH.CxtQ -> Core TH.TypeQ -> Core [TH.DecQ] -> DsM (Core TH.DecQ)
2064 repInst (MkC o) (MkC cxt) (MkC ty) (MkC ds) = rep2 instanceWithOverlapDName
2065 [o, cxt, ty, ds]
2066
2067 repDerivStrategy :: Maybe (Located DerivStrategy)
2068 -> DsM (Core (Maybe TH.DerivStrategy))
2069 repDerivStrategy mds =
2070 case mds of
2071 Nothing -> nothing
2072 Just (L _ ds) ->
2073 case ds of
2074 StockStrategy -> just =<< dataCon stockStrategyDataConName
2075 AnyclassStrategy -> just =<< dataCon anyclassStrategyDataConName
2076 NewtypeStrategy -> just =<< dataCon newtypeStrategyDataConName
2077 where
2078 nothing = coreNothing derivStrategyTyConName
2079 just = coreJust derivStrategyTyConName
2080
2081 repOverlap :: Maybe OverlapMode -> DsM (Core (Maybe TH.Overlap))
2082 repOverlap mb =
2083 case mb of
2084 Nothing -> nothing
2085 Just o ->
2086 case o of
2087 NoOverlap _ -> nothing
2088 Overlappable _ -> just =<< dataCon overlappableDataConName
2089 Overlapping _ -> just =<< dataCon overlappingDataConName
2090 Overlaps _ -> just =<< dataCon overlapsDataConName
2091 Incoherent _ -> just =<< dataCon incoherentDataConName
2092 where
2093 nothing = coreNothing overlapTyConName
2094 just = coreJust overlapTyConName
2095
2096
2097 repClass :: Core TH.CxtQ -> Core TH.Name -> Core [TH.TyVarBndr]
2098 -> Core [TH.FunDep] -> Core [TH.DecQ]
2099 -> DsM (Core TH.DecQ)
2100 repClass (MkC cxt) (MkC cls) (MkC tvs) (MkC fds) (MkC ds)
2101 = rep2 classDName [cxt, cls, tvs, fds, ds]
2102
2103 repDeriv :: Core (Maybe TH.DerivStrategy)
2104 -> Core TH.CxtQ -> Core TH.TypeQ
2105 -> DsM (Core TH.DecQ)
2106 repDeriv (MkC ds) (MkC cxt) (MkC ty)
2107 = rep2 standaloneDerivWithStrategyDName [ds, cxt, ty]
2108
2109 repPragInl :: Core TH.Name -> Core TH.Inline -> Core TH.RuleMatch
2110 -> Core TH.Phases -> DsM (Core TH.DecQ)
2111 repPragInl (MkC nm) (MkC inline) (MkC rm) (MkC phases)
2112 = rep2 pragInlDName [nm, inline, rm, phases]
2113
2114 repPragSpec :: Core TH.Name -> Core TH.TypeQ -> Core TH.Phases
2115 -> DsM (Core TH.DecQ)
2116 repPragSpec (MkC nm) (MkC ty) (MkC phases)
2117 = rep2 pragSpecDName [nm, ty, phases]
2118
2119 repPragSpecInl :: Core TH.Name -> Core TH.TypeQ -> Core TH.Inline
2120 -> Core TH.Phases -> DsM (Core TH.DecQ)
2121 repPragSpecInl (MkC nm) (MkC ty) (MkC inline) (MkC phases)
2122 = rep2 pragSpecInlDName [nm, ty, inline, phases]
2123
2124 repPragSpecInst :: Core TH.TypeQ -> DsM (Core TH.DecQ)
2125 repPragSpecInst (MkC ty) = rep2 pragSpecInstDName [ty]
2126
2127 repPragComplete :: Core [TH.Name] -> Core (Maybe TH.Name) -> DsM (Core TH.DecQ)
2128 repPragComplete (MkC cls) (MkC mty) = rep2 pragCompleteDName [cls, mty]
2129
2130 repPragRule :: Core String -> Core [TH.RuleBndrQ] -> Core TH.ExpQ
2131 -> Core TH.ExpQ -> Core TH.Phases -> DsM (Core TH.DecQ)
2132 repPragRule (MkC nm) (MkC bndrs) (MkC lhs) (MkC rhs) (MkC phases)
2133 = rep2 pragRuleDName [nm, bndrs, lhs, rhs, phases]
2134
2135 repPragAnn :: Core TH.AnnTarget -> Core TH.ExpQ -> DsM (Core TH.DecQ)
2136 repPragAnn (MkC targ) (MkC e) = rep2 pragAnnDName [targ, e]
2137
2138 repTySynInst :: Core TH.Name -> Core TH.TySynEqnQ -> DsM (Core TH.DecQ)
2139 repTySynInst (MkC nm) (MkC eqn)
2140 = rep2 tySynInstDName [nm, eqn]
2141
2142 repDataFamilyD :: Core TH.Name -> Core [TH.TyVarBndr]
2143 -> Core (Maybe TH.Kind) -> DsM (Core TH.DecQ)
2144 repDataFamilyD (MkC nm) (MkC tvs) (MkC kind)
2145 = rep2 dataFamilyDName [nm, tvs, kind]
2146
2147 repOpenFamilyD :: Core TH.Name
2148 -> Core [TH.TyVarBndr]
2149 -> Core TH.FamilyResultSig
2150 -> Core (Maybe TH.InjectivityAnn)
2151 -> DsM (Core TH.DecQ)
2152 repOpenFamilyD (MkC nm) (MkC tvs) (MkC result) (MkC inj)
2153 = rep2 openTypeFamilyDName [nm, tvs, result, inj]
2154
2155 repClosedFamilyD :: Core TH.Name
2156 -> Core [TH.TyVarBndr]
2157 -> Core TH.FamilyResultSig
2158 -> Core (Maybe TH.InjectivityAnn)
2159 -> Core [TH.TySynEqnQ]
2160 -> DsM (Core TH.DecQ)
2161 repClosedFamilyD (MkC nm) (MkC tvs) (MkC res) (MkC inj) (MkC eqns)
2162 = rep2 closedTypeFamilyDName [nm, tvs, res, inj, eqns]
2163
2164 repTySynEqn :: Core [TH.TypeQ] -> Core TH.TypeQ -> DsM (Core TH.TySynEqnQ)
2165 repTySynEqn (MkC lhs) (MkC rhs)
2166 = rep2 tySynEqnName [lhs, rhs]
2167
2168 repRoleAnnotD :: Core TH.Name -> Core [TH.Role] -> DsM (Core TH.DecQ)
2169 repRoleAnnotD (MkC n) (MkC roles) = rep2 roleAnnotDName [n, roles]
2170
2171 repFunDep :: Core [TH.Name] -> Core [TH.Name] -> DsM (Core TH.FunDep)
2172 repFunDep (MkC xs) (MkC ys) = rep2 funDepName [xs, ys]
2173
2174 repProto :: Name -> Core TH.Name -> Core TH.TypeQ -> DsM (Core TH.DecQ)
2175 repProto mk_sig (MkC s) (MkC ty) = rep2 mk_sig [s, ty]
2176
2177 repCtxt :: Core [TH.PredQ] -> DsM (Core TH.CxtQ)
2178 repCtxt (MkC tys) = rep2 cxtName [tys]
2179
2180 repDataCon :: Located Name
2181 -> HsConDeclDetails GhcRn
2182 -> DsM (Core TH.ConQ)
2183 repDataCon con details
2184 = do con' <- lookupLOcc con -- See Note [Binders and occurrences]
2185 repConstr details Nothing [con']
2186
2187 repGadtDataCons :: [Located Name]
2188 -> HsConDeclDetails GhcRn
2189 -> LHsType GhcRn
2190 -> DsM (Core TH.ConQ)
2191 repGadtDataCons cons details res_ty
2192 = do cons' <- mapM lookupLOcc cons -- See Note [Binders and occurrences]
2193 repConstr details (Just res_ty) cons'
2194
2195 -- Invariant:
2196 -- * for plain H98 data constructors second argument is Nothing and third
2197 -- argument is a singleton list
2198 -- * for GADTs data constructors second argument is (Just return_type) and
2199 -- third argument is a non-empty list
2200 repConstr :: HsConDeclDetails GhcRn
2201 -> Maybe (LHsType GhcRn)
2202 -> [Core TH.Name]
2203 -> DsM (Core TH.ConQ)
2204 repConstr (PrefixCon ps) Nothing [con]
2205 = do arg_tys <- repList bangTypeQTyConName repBangTy ps
2206 rep2 normalCName [unC con, unC arg_tys]
2207
2208 repConstr (PrefixCon ps) (Just (L _ res_ty)) cons
2209 = do arg_tys <- repList bangTypeQTyConName repBangTy ps
2210 res_ty' <- repTy res_ty
2211 rep2 gadtCName [ unC (nonEmptyCoreList cons), unC arg_tys, unC res_ty']
2212
2213 repConstr (RecCon (L _ ips)) resTy cons
2214 = do args <- concatMapM rep_ip ips
2215 arg_vtys <- coreList varBangTypeQTyConName args
2216 case resTy of
2217 Nothing -> rep2 recCName [unC (head cons), unC arg_vtys]
2218 Just (L _ res_ty) -> do
2219 res_ty' <- repTy res_ty
2220 rep2 recGadtCName [unC (nonEmptyCoreList cons), unC arg_vtys,
2221 unC res_ty']
2222
2223 where
2224 rep_ip (L _ ip) = mapM (rep_one_ip (cd_fld_type ip)) (cd_fld_names ip)
2225
2226 rep_one_ip :: LBangType GhcRn -> LFieldOcc GhcRn -> DsM (Core a)
2227 rep_one_ip t n = do { MkC v <- lookupOcc (selectorFieldOcc $ unLoc n)
2228 ; MkC ty <- repBangTy t
2229 ; rep2 varBangTypeName [v,ty] }
2230
2231 repConstr (InfixCon st1 st2) Nothing [con]
2232 = do arg1 <- repBangTy st1
2233 arg2 <- repBangTy st2
2234 rep2 infixCName [unC arg1, unC con, unC arg2]
2235
2236 repConstr (InfixCon {}) (Just _) _ =
2237 panic "repConstr: infix GADT constructor should be in a PrefixCon"
2238 repConstr _ _ _ =
2239 panic "repConstr: invariant violated"
2240
2241 ------------ Types -------------------
2242
2243 repTForall :: Core [TH.TyVarBndr] -> Core TH.CxtQ -> Core TH.TypeQ
2244 -> DsM (Core TH.TypeQ)
2245 repTForall (MkC tvars) (MkC ctxt) (MkC ty)
2246 = rep2 forallTName [tvars, ctxt, ty]
2247
2248 repTvar :: Core TH.Name -> DsM (Core TH.TypeQ)
2249 repTvar (MkC s) = rep2 varTName [s]
2250
2251 repTapp :: Core TH.TypeQ -> Core TH.TypeQ -> DsM (Core TH.TypeQ)
2252 repTapp (MkC t1) (MkC t2) = rep2 appTName [t1, t2]
2253
2254 repTapps :: Core TH.TypeQ -> [Core TH.TypeQ] -> DsM (Core TH.TypeQ)
2255 repTapps f [] = return f
2256 repTapps f (t:ts) = do { f1 <- repTapp f t; repTapps f1 ts }
2257
2258 repTSig :: Core TH.TypeQ -> Core TH.Kind -> DsM (Core TH.TypeQ)
2259 repTSig (MkC ty) (MkC ki) = rep2 sigTName [ty, ki]
2260
2261 repTequality :: DsM (Core TH.TypeQ)
2262 repTequality = rep2 equalityTName []
2263
2264 repTPromotedList :: [Core TH.TypeQ] -> DsM (Core TH.TypeQ)
2265 repTPromotedList [] = repPromotedNilTyCon
2266 repTPromotedList (t:ts) = do { tcon <- repPromotedConsTyCon
2267 ; f <- repTapp tcon t
2268 ; t' <- repTPromotedList ts
2269 ; repTapp f t'
2270 }
2271
2272 repTLit :: Core TH.TyLitQ -> DsM (Core TH.TypeQ)
2273 repTLit (MkC lit) = rep2 litTName [lit]
2274
2275 repTWildCard :: DsM (Core TH.TypeQ)
2276 repTWildCard = rep2 wildCardTName []
2277
2278 --------- Type constructors --------------
2279
2280 repNamedTyCon :: Core TH.Name -> DsM (Core TH.TypeQ)
2281 repNamedTyCon (MkC s) = rep2 conTName [s]
2282
2283 repTupleTyCon :: Int -> DsM (Core TH.TypeQ)
2284 -- Note: not Core Int; it's easier to be direct here
2285 repTupleTyCon i = do dflags <- getDynFlags
2286 rep2 tupleTName [mkIntExprInt dflags i]
2287
2288 repUnboxedTupleTyCon :: Int -> DsM (Core TH.TypeQ)
2289 -- Note: not Core Int; it's easier to be direct here
2290 repUnboxedTupleTyCon i = do dflags <- getDynFlags
2291 rep2 unboxedTupleTName [mkIntExprInt dflags i]
2292
2293 repUnboxedSumTyCon :: TH.SumArity -> DsM (Core TH.TypeQ)
2294 -- Note: not Core TH.SumArity; it's easier to be direct here
2295 repUnboxedSumTyCon arity = do dflags <- getDynFlags
2296 rep2 unboxedSumTName [mkIntExprInt dflags arity]
2297
2298 repArrowTyCon :: DsM (Core TH.TypeQ)
2299 repArrowTyCon = rep2 arrowTName []
2300
2301 repListTyCon :: DsM (Core TH.TypeQ)
2302 repListTyCon = rep2 listTName []
2303
2304 repPromotedDataCon :: Core TH.Name -> DsM (Core TH.TypeQ)
2305 repPromotedDataCon (MkC s) = rep2 promotedTName [s]
2306
2307 repPromotedTupleTyCon :: Int -> DsM (Core TH.TypeQ)
2308 repPromotedTupleTyCon i = do dflags <- getDynFlags
2309 rep2 promotedTupleTName [mkIntExprInt dflags i]
2310
2311 repPromotedNilTyCon :: DsM (Core TH.TypeQ)
2312 repPromotedNilTyCon = rep2 promotedNilTName []
2313
2314 repPromotedConsTyCon :: DsM (Core TH.TypeQ)
2315 repPromotedConsTyCon = rep2 promotedConsTName []
2316
2317 ------------ Kinds -------------------
2318
2319 repPlainTV :: Core TH.Name -> DsM (Core TH.TyVarBndr)
2320 repPlainTV (MkC nm) = rep2 plainTVName [nm]
2321
2322 repKindedTV :: Core TH.Name -> Core TH.Kind -> DsM (Core TH.TyVarBndr)
2323 repKindedTV (MkC nm) (MkC ki) = rep2 kindedTVName [nm, ki]
2324
2325 repKVar :: Core TH.Name -> DsM (Core TH.Kind)
2326 repKVar (MkC s) = rep2 varKName [s]
2327
2328 repKCon :: Core TH.Name -> DsM (Core TH.Kind)
2329 repKCon (MkC s) = rep2 conKName [s]
2330
2331 repKTuple :: Int -> DsM (Core TH.Kind)
2332 repKTuple i = do dflags <- getDynFlags
2333 rep2 tupleKName [mkIntExprInt dflags i]
2334
2335 repKArrow :: DsM (Core TH.Kind)
2336 repKArrow = rep2 arrowKName []
2337
2338 repKList :: DsM (Core TH.Kind)
2339 repKList = rep2 listKName []
2340
2341 repKApp :: Core TH.Kind -> Core TH.Kind -> DsM (Core TH.Kind)
2342 repKApp (MkC k1) (MkC k2) = rep2 appKName [k1, k2]
2343
2344 repKApps :: Core TH.Kind -> [Core TH.Kind] -> DsM (Core TH.Kind)
2345 repKApps f [] = return f
2346 repKApps f (k:ks) = do { f' <- repKApp f k; repKApps f' ks }
2347
2348 repKStar :: DsM (Core TH.Kind)
2349 repKStar = rep2 starKName []
2350
2351 repKConstraint :: DsM (Core TH.Kind)
2352 repKConstraint = rep2 constraintKName []
2353
2354 ----------------------------------------------------------
2355 -- Type family result signature
2356
2357 repNoSig :: DsM (Core TH.FamilyResultSig)
2358 repNoSig = rep2 noSigName []
2359
2360 repKindSig :: Core TH.Kind -> DsM (Core TH.FamilyResultSig)
2361 repKindSig (MkC ki) = rep2 kindSigName [ki]
2362
2363 repTyVarSig :: Core TH.TyVarBndr -> DsM (Core TH.FamilyResultSig)
2364 repTyVarSig (MkC bndr) = rep2 tyVarSigName [bndr]
2365
2366 ----------------------------------------------------------
2367 -- Literals
2368
2369 repLiteral :: HsLit GhcRn -> DsM (Core TH.Lit)
2370 repLiteral (HsStringPrim _ bs)
2371 = do dflags <- getDynFlags
2372 word8_ty <- lookupType word8TyConName
2373 let w8s = unpack bs
2374 w8s_expr = map (\w8 -> mkCoreConApps word8DataCon
2375 [mkWordLit dflags (toInteger w8)]) w8s
2376 rep2 stringPrimLName [mkListExpr word8_ty w8s_expr]
2377 repLiteral lit
2378 = do lit' <- case lit of
2379 HsIntPrim _ i -> mk_integer i
2380 HsWordPrim _ w -> mk_integer w
2381 HsInt _ i -> mk_integer (il_value i)
2382 HsFloatPrim _ r -> mk_rational r
2383 HsDoublePrim _ r -> mk_rational r
2384 HsCharPrim _ c -> mk_char c
2385 _ -> return lit
2386 lit_expr <- dsLit lit'
2387 case mb_lit_name of
2388 Just lit_name -> rep2 lit_name [lit_expr]
2389 Nothing -> notHandled "Exotic literal" (ppr lit)
2390 where
2391 mb_lit_name = case lit of
2392 HsInteger _ _ _ -> Just integerLName
2393 HsInt _ _ -> Just integerLName
2394 HsIntPrim _ _ -> Just intPrimLName
2395 HsWordPrim _ _ -> Just wordPrimLName
2396 HsFloatPrim _ _ -> Just floatPrimLName
2397 HsDoublePrim _ _ -> Just doublePrimLName
2398 HsChar _ _ -> Just charLName
2399 HsCharPrim _ _ -> Just charPrimLName
2400 HsString _ _ -> Just stringLName
2401 HsRat _ _ _ -> Just rationalLName
2402 _ -> Nothing
2403
2404 mk_integer :: Integer -> DsM (HsLit GhcRn)
2405 mk_integer i = do integer_ty <- lookupType integerTyConName
2406 return $ HsInteger noSourceText i integer_ty
2407
2408 mk_rational :: FractionalLit -> DsM (HsLit GhcRn)
2409 mk_rational r = do rat_ty <- lookupType rationalTyConName
2410 return $ HsRat def r rat_ty
2411 mk_string :: FastString -> DsM (HsLit GhcRn)
2412 mk_string s = return $ HsString noSourceText s
2413
2414 mk_char :: Char -> DsM (HsLit GhcRn)
2415 mk_char c = return $ HsChar noSourceText c
2416
2417 repOverloadedLiteral :: HsOverLit GhcRn -> DsM (Core TH.Lit)
2418 repOverloadedLiteral (OverLit { ol_val = val})
2419 = do { lit <- mk_lit val; repLiteral lit }
2420 -- The type Rational will be in the environment, because
2421 -- the smart constructor 'TH.Syntax.rationalL' uses it in its type,
2422 -- and rationalL is sucked in when any TH stuff is used
2423
2424 mk_lit :: OverLitVal -> DsM (HsLit GhcRn)
2425 mk_lit (HsIntegral i) = mk_integer (il_value i)
2426 mk_lit (HsFractional f) = mk_rational f
2427 mk_lit (HsIsString _ s) = mk_string s
2428
2429 repNameS :: Core String -> DsM (Core TH.Name)
2430 repNameS (MkC name) = rep2 mkNameSName [name]
2431
2432 --------------- Miscellaneous -------------------
2433
2434 repGensym :: Core String -> DsM (Core (TH.Q TH.Name))
2435 repGensym (MkC lit_str) = rep2 newNameName [lit_str]
2436
2437 repBindQ :: Type -> Type -- a and b
2438 -> Core (TH.Q a) -> Core (a -> TH.Q b) -> DsM (Core (TH.Q b))
2439 repBindQ ty_a ty_b (MkC x) (MkC y)
2440 = rep2 bindQName [Type ty_a, Type ty_b, x, y]
2441
2442 repSequenceQ :: Type -> Core [TH.Q a] -> DsM (Core (TH.Q [a]))
2443 repSequenceQ ty_a (MkC list)
2444 = rep2 sequenceQName [Type ty_a, list]
2445
2446 repUnboundVar :: Core TH.Name -> DsM (Core TH.ExpQ)
2447 repUnboundVar (MkC name) = rep2 unboundVarEName [name]
2448
2449 ------------ Lists -------------------
2450 -- turn a list of patterns into a single pattern matching a list
2451
2452 repList :: Name -> (a -> DsM (Core b))
2453 -> [a] -> DsM (Core [b])
2454 repList tc_name f args
2455 = do { args1 <- mapM f args
2456 ; coreList tc_name args1 }
2457
2458 coreList :: Name -- Of the TyCon of the element type
2459 -> [Core a] -> DsM (Core [a])
2460 coreList tc_name es
2461 = do { elt_ty <- lookupType tc_name; return (coreList' elt_ty es) }
2462
2463 coreList' :: Type -- The element type
2464 -> [Core a] -> Core [a]
2465 coreList' elt_ty es = MkC (mkListExpr elt_ty (map unC es ))
2466
2467 nonEmptyCoreList :: [Core a] -> Core [a]
2468 -- The list must be non-empty so we can get the element type
2469 -- Otherwise use coreList
2470 nonEmptyCoreList [] = panic "coreList: empty argument"
2471 nonEmptyCoreList xs@(MkC x:_) = MkC (mkListExpr (exprType x) (map unC xs))
2472
2473 coreStringLit :: String -> DsM (Core String)
2474 coreStringLit s = do { z <- mkStringExpr s; return(MkC z) }
2475
2476 ------------------- Maybe ------------------
2477
2478 -- | Construct Core expression for Nothing of a given type name
2479 coreNothing :: Name -- ^ Name of the TyCon of the element type
2480 -> DsM (Core (Maybe a))
2481 coreNothing tc_name =
2482 do { elt_ty <- lookupType tc_name; return (coreNothing' elt_ty) }
2483
2484 -- | Construct Core expression for Nothing of a given type
2485 coreNothing' :: Type -- ^ The element type
2486 -> Core (Maybe a)
2487 coreNothing' elt_ty = MkC (mkNothingExpr elt_ty)
2488
2489 -- | Store given Core expression in a Just of a given type name
2490 coreJust :: Name -- ^ Name of the TyCon of the element type
2491 -> Core a -> DsM (Core (Maybe a))
2492 coreJust tc_name es
2493 = do { elt_ty <- lookupType tc_name; return (coreJust' elt_ty es) }
2494
2495 -- | Store given Core expression in a Just of a given type
2496 coreJust' :: Type -- ^ The element type
2497 -> Core a -> Core (Maybe a)
2498 coreJust' elt_ty es = MkC (mkJustExpr elt_ty (unC es))
2499
2500 ------------ Literals & Variables -------------------
2501
2502 coreIntLit :: Int -> DsM (Core Int)
2503 coreIntLit i = do dflags <- getDynFlags
2504 return (MkC (mkIntExprInt dflags i))
2505
2506 coreVar :: Id -> Core TH.Name -- The Id has type Name
2507 coreVar id = MkC (Var id)
2508
2509 ----------------- Failure -----------------------
2510 notHandledL :: SrcSpan -> String -> SDoc -> DsM a
2511 notHandledL loc what doc
2512 | isGoodSrcSpan loc
2513 = putSrcSpanDs loc $ notHandled what doc
2514 | otherwise
2515 = notHandled what doc
2516
2517 notHandled :: String -> SDoc -> DsM a
2518 notHandled what doc = failWithDs msg
2519 where
2520 msg = hang (text what <+> text "not (yet) handled by Template Haskell")
2521 2 doc