Embrace -XTypeInType, add -XStarIsType
[ghc.git] / compiler / typecheck / TcSplice.hs
1 {-
2 (c) The University of Glasgow 2006
3 (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4
5
6 TcSplice: Template Haskell splices
7 -}
8
9 {-# LANGUAGE CPP #-}
10 {-# LANGUAGE FlexibleInstances #-}
11 {-# LANGUAGE MagicHash #-}
12 {-# LANGUAGE ScopedTypeVariables #-}
13 {-# LANGUAGE InstanceSigs #-}
14 {-# LANGUAGE GADTs #-}
15 {-# LANGUAGE RecordWildCards #-}
16 {-# LANGUAGE MultiWayIf #-}
17 {-# LANGUAGE TypeFamilies #-}
18 {-# OPTIONS_GHC -fno-warn-orphans #-}
19
20 module TcSplice(
21 tcSpliceExpr, tcTypedBracket, tcUntypedBracket,
22 -- runQuasiQuoteExpr, runQuasiQuotePat,
23 -- runQuasiQuoteDecl, runQuasiQuoteType,
24 runAnnotation,
25
26 runMetaE, runMetaP, runMetaT, runMetaD, runQuasi,
27 tcTopSpliceExpr, lookupThName_maybe,
28 defaultRunMeta, runMeta', runRemoteModFinalizers,
29 finishTH
30 ) where
31
32 #include "HsVersions.h"
33
34 import GhcPrelude
35
36 import HsSyn
37 import Annotations
38 import Finder
39 import Name
40 import TcRnMonad
41 import TcType
42
43 import Outputable
44 import TcExpr
45 import SrcLoc
46 import THNames
47 import TcUnify
48 import TcEnv
49 import FileCleanup ( newTempName, TempFileLifetime(..) )
50
51 import Control.Monad
52
53 import GHCi.Message
54 import GHCi.RemoteTypes
55 import GHCi
56 import HscMain
57 -- These imports are the reason that TcSplice
58 -- is very high up the module hierarchy
59 import FV
60 import RnSplice( traceSplice, SpliceInfo(..) )
61 import RdrName
62 import HscTypes
63 import Convert
64 import RnExpr
65 import RnEnv
66 import RnUtils ( HsDocContext(..) )
67 import RnFixity ( lookupFixityRn_help )
68 import RnTypes
69 import TcHsSyn
70 import TcSimplify
71 import Type
72 import Kind
73 import NameSet
74 import TcMType
75 import TcHsType
76 import TcIface
77 import TyCoRep
78 import FamInst
79 import FamInstEnv
80 import InstEnv
81 import Inst
82 import NameEnv
83 import PrelNames
84 import TysWiredIn
85 import OccName
86 import Hooks
87 import Var
88 import Module
89 import LoadIface
90 import Class
91 import TyCon
92 import CoAxiom
93 import PatSyn
94 import ConLike
95 import DataCon
96 import TcEvidence( TcEvBinds(..) )
97 import Id
98 import IdInfo
99 import DsExpr
100 import DsMonad
101 import GHC.Serialized
102 import ErrUtils
103 import Util
104 import Unique
105 import VarSet
106 import Data.List ( find, mapAccumL )
107 import Data.Maybe
108 import FastString
109 import BasicTypes hiding( SuccessFlag(..) )
110 import Maybes( MaybeErr(..) )
111 import DynFlags
112 import Panic
113 import Lexeme
114 import qualified EnumSet
115 import Plugins
116
117 import qualified Language.Haskell.TH as TH
118 -- THSyntax gives access to internal functions and data types
119 import qualified Language.Haskell.TH.Syntax as TH
120
121 -- Because GHC.Desugar might not be in the base library of the bootstrapping compiler
122 import GHC.Desugar ( AnnotationWrapper(..) )
123
124 import Control.Exception
125 import Data.Binary
126 import Data.Binary.Get
127 import qualified Data.ByteString as B
128 import qualified Data.ByteString.Lazy as LB
129 import Data.Dynamic ( fromDynamic, toDyn )
130 import qualified Data.Map as Map
131 import Data.Typeable ( typeOf, Typeable, TypeRep, typeRep )
132 import Data.Data (Data)
133 import Data.Proxy ( Proxy (..) )
134 import GHC.Exts ( unsafeCoerce# )
135
136 {-
137 ************************************************************************
138 * *
139 \subsection{Main interface + stubs for the non-GHCI case
140 * *
141 ************************************************************************
142 -}
143
144 tcTypedBracket :: HsExpr GhcRn -> HsBracket GhcRn -> ExpRhoType -> TcM (HsExpr GhcTcId)
145 tcUntypedBracket :: HsExpr GhcRn -> HsBracket GhcRn -> [PendingRnSplice] -> ExpRhoType
146 -> TcM (HsExpr GhcTcId)
147 tcSpliceExpr :: HsSplice GhcRn -> ExpRhoType -> TcM (HsExpr GhcTcId)
148 -- None of these functions add constraints to the LIE
149
150 -- runQuasiQuoteExpr :: HsQuasiQuote RdrName -> RnM (LHsExpr RdrName)
151 -- runQuasiQuotePat :: HsQuasiQuote RdrName -> RnM (LPat RdrName)
152 -- runQuasiQuoteType :: HsQuasiQuote RdrName -> RnM (LHsType RdrName)
153 -- runQuasiQuoteDecl :: HsQuasiQuote RdrName -> RnM [LHsDecl RdrName]
154
155 runAnnotation :: CoreAnnTarget -> LHsExpr GhcRn -> TcM Annotation
156 {-
157 ************************************************************************
158 * *
159 \subsection{Quoting an expression}
160 * *
161 ************************************************************************
162 -}
163
164 -- See Note [How brackets and nested splices are handled]
165 -- tcTypedBracket :: HsBracket Name -> TcRhoType -> TcM (HsExpr TcId)
166 tcTypedBracket rn_expr brack@(TExpBr _ expr) res_ty
167 = addErrCtxt (quotationCtxtDoc brack) $
168 do { cur_stage <- getStage
169 ; ps_ref <- newMutVar []
170 ; lie_var <- getConstraintVar -- Any constraints arising from nested splices
171 -- should get thrown into the constraint set
172 -- from outside the bracket
173
174 -- Typecheck expr to make sure it is valid,
175 -- Throw away the typechecked expression but return its type.
176 -- We'll typecheck it again when we splice it in somewhere
177 ; (_tc_expr, expr_ty) <- setStage (Brack cur_stage (TcPending ps_ref lie_var)) $
178 tcInferRhoNC expr
179 -- NC for no context; tcBracket does that
180
181 ; meta_ty <- tcTExpTy expr_ty
182 ; ps' <- readMutVar ps_ref
183 ; texpco <- tcLookupId unsafeTExpCoerceName
184 ; tcWrapResultO (Shouldn'tHappenOrigin "TExpBr")
185 rn_expr
186 (unLoc (mkHsApp (nlHsTyApp texpco [expr_ty])
187 (noLoc (HsTcBracketOut noExt brack ps'))))
188 meta_ty res_ty }
189 tcTypedBracket _ other_brack _
190 = pprPanic "tcTypedBracket" (ppr other_brack)
191
192 -- tcUntypedBracket :: HsBracket Name -> [PendingRnSplice] -> ExpRhoType -> TcM (HsExpr TcId)
193 tcUntypedBracket rn_expr brack ps res_ty
194 = do { traceTc "tc_bracket untyped" (ppr brack $$ ppr ps)
195 ; ps' <- mapM tcPendingSplice ps
196 ; meta_ty <- tcBrackTy brack
197 ; traceTc "tc_bracket done untyped" (ppr meta_ty)
198 ; tcWrapResultO (Shouldn'tHappenOrigin "untyped bracket")
199 rn_expr (HsTcBracketOut noExt brack ps') meta_ty res_ty }
200
201 ---------------
202 tcBrackTy :: HsBracket GhcRn -> TcM TcType
203 tcBrackTy (VarBr {}) = tcMetaTy nameTyConName
204 -- Result type is Var (not Q-monadic)
205 tcBrackTy (ExpBr {}) = tcMetaTy expQTyConName -- Result type is ExpQ (= Q Exp)
206 tcBrackTy (TypBr {}) = tcMetaTy typeQTyConName -- Result type is Type (= Q Typ)
207 tcBrackTy (DecBrG {}) = tcMetaTy decsQTyConName -- Result type is Q [Dec]
208 tcBrackTy (PatBr {}) = tcMetaTy patQTyConName -- Result type is PatQ (= Q Pat)
209 tcBrackTy (DecBrL {}) = panic "tcBrackTy: Unexpected DecBrL"
210 tcBrackTy (TExpBr {}) = panic "tcUntypedBracket: Unexpected TExpBr"
211 tcBrackTy (XBracket {}) = panic "tcUntypedBracket: Unexpected XBracket"
212
213 ---------------
214 tcPendingSplice :: PendingRnSplice -> TcM PendingTcSplice
215 tcPendingSplice (PendingRnSplice flavour splice_name expr)
216 = do { res_ty <- tcMetaTy meta_ty_name
217 ; expr' <- tcMonoExpr expr (mkCheckExpType res_ty)
218 ; return (PendingTcSplice splice_name expr') }
219 where
220 meta_ty_name = case flavour of
221 UntypedExpSplice -> expQTyConName
222 UntypedPatSplice -> patQTyConName
223 UntypedTypeSplice -> typeQTyConName
224 UntypedDeclSplice -> decsQTyConName
225
226 ---------------
227 -- Takes a tau and returns the type Q (TExp tau)
228 tcTExpTy :: TcType -> TcM TcType
229 tcTExpTy exp_ty
230 = do { unless (isTauTy exp_ty) $ addErr (err_msg exp_ty)
231 ; q <- tcLookupTyCon qTyConName
232 ; texp <- tcLookupTyCon tExpTyConName
233 ; return (mkTyConApp q [mkTyConApp texp [exp_ty]]) }
234 where
235 err_msg ty
236 = vcat [ text "Illegal polytype:" <+> ppr ty
237 , text "The type of a Typed Template Haskell expression must" <+>
238 text "not have any quantification." ]
239
240 quotationCtxtDoc :: HsBracket GhcRn -> SDoc
241 quotationCtxtDoc br_body
242 = hang (text "In the Template Haskell quotation")
243 2 (ppr br_body)
244
245
246 -- The whole of the rest of the file is the else-branch (ie stage2 only)
247
248 {-
249 Note [How top-level splices are handled]
250 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
251 Top-level splices (those not inside a [| .. |] quotation bracket) are handled
252 very straightforwardly:
253
254 1. tcTopSpliceExpr: typecheck the body e of the splice $(e)
255
256 2. runMetaT: desugar, compile, run it, and convert result back to
257 HsSyn RdrName (of the appropriate flavour, eg HsType RdrName,
258 HsExpr RdrName etc)
259
260 3. treat the result as if that's what you saw in the first place
261 e.g for HsType, rename and kind-check
262 for HsExpr, rename and type-check
263
264 (The last step is different for decls, because they can *only* be
265 top-level: we return the result of step 2.)
266
267 Note [How brackets and nested splices are handled]
268 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
269 Nested splices (those inside a [| .. |] quotation bracket),
270 are treated quite differently.
271
272 Remember, there are two forms of bracket
273 typed [|| e ||]
274 and untyped [| e |]
275
276 The life cycle of a typed bracket:
277 * Starts as HsBracket
278
279 * When renaming:
280 * Set the ThStage to (Brack s RnPendingTyped)
281 * Rename the body
282 * Result is still a HsBracket
283
284 * When typechecking:
285 * Set the ThStage to (Brack s (TcPending ps_var lie_var))
286 * Typecheck the body, and throw away the elaborated result
287 * Nested splices (which must be typed) are typechecked, and
288 the results accumulated in ps_var; their constraints
289 accumulate in lie_var
290 * Result is a HsTcBracketOut rn_brack pending_splices
291 where rn_brack is the incoming renamed bracket
292
293 The life cycle of a un-typed bracket:
294 * Starts as HsBracket
295
296 * When renaming:
297 * Set the ThStage to (Brack s (RnPendingUntyped ps_var))
298 * Rename the body
299 * Nested splices (which must be untyped) are renamed, and the
300 results accumulated in ps_var
301 * Result is still (HsRnBracketOut rn_body pending_splices)
302
303 * When typechecking a HsRnBracketOut
304 * Typecheck the pending_splices individually
305 * Ignore the body of the bracket; just check that the context
306 expects a bracket of that type (e.g. a [p| pat |] bracket should
307 be in a context needing a (Q Pat)
308 * Result is a HsTcBracketOut rn_brack pending_splices
309 where rn_brack is the incoming renamed bracket
310
311
312 In both cases, desugaring happens like this:
313 * HsTcBracketOut is desugared by DsMeta.dsBracket. It
314
315 a) Extends the ds_meta environment with the PendingSplices
316 attached to the bracket
317
318 b) Converts the quoted (HsExpr Name) to a CoreExpr that, when
319 run, will produce a suitable TH expression/type/decl. This
320 is why we leave the *renamed* expression attached to the bracket:
321 the quoted expression should not be decorated with all the goop
322 added by the type checker
323
324 * Each splice carries a unique Name, called a "splice point", thus
325 ${n}(e). The name is initialised to an (Unqual "splice") when the
326 splice is created; the renamer gives it a unique.
327
328 * When DsMeta (used to desugar the body of the bracket) comes across
329 a splice, it looks up the splice's Name, n, in the ds_meta envt,
330 to find an (HsExpr Id) that should be substituted for the splice;
331 it just desugars it to get a CoreExpr (DsMeta.repSplice).
332
333 Example:
334 Source: f = [| Just $(g 3) |]
335 The [| |] part is a HsBracket
336
337 Typechecked: f = [| Just ${s7}(g 3) |]{s7 = g Int 3}
338 The [| |] part is a HsBracketOut, containing *renamed*
339 (not typechecked) expression
340 The "s7" is the "splice point"; the (g Int 3) part
341 is a typechecked expression
342
343 Desugared: f = do { s7 <- g Int 3
344 ; return (ConE "Data.Maybe.Just" s7) }
345
346
347 Note [Template Haskell state diagram]
348 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
349 Here are the ThStages, s, their corresponding level numbers
350 (the result of (thLevel s)), and their state transitions.
351 The top level of the program is stage Comp:
352
353 Start here
354 |
355 V
356 ----------- $ ------------ $
357 | Comp | ---------> | Splice | -----|
358 | 1 | | 0 | <----|
359 ----------- ------------
360 ^ | ^ |
361 $ | | [||] $ | | [||]
362 | v | v
363 -------------- ----------------
364 | Brack Comp | | Brack Splice |
365 | 2 | | 1 |
366 -------------- ----------------
367
368 * Normal top-level declarations start in state Comp
369 (which has level 1).
370 Annotations start in state Splice, since they are
371 treated very like a splice (only without a '$')
372
373 * Code compiled in state Splice (and only such code)
374 will be *run at compile time*, with the result replacing
375 the splice
376
377 * The original paper used level -1 instead of 0, etc.
378
379 * The original paper did not allow a splice within a
380 splice, but there is no reason not to. This is the
381 $ transition in the top right.
382
383 Note [Template Haskell levels]
384 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
385 * Imported things are impLevel (= 0)
386
387 * However things at level 0 are not *necessarily* imported.
388 eg $( \b -> ... ) here b is bound at level 0
389
390 * In GHCi, variables bound by a previous command are treated
391 as impLevel, because we have bytecode for them.
392
393 * Variables are bound at the "current level"
394
395 * The current level starts off at outerLevel (= 1)
396
397 * The level is decremented by splicing $(..)
398 incremented by brackets [| |]
399 incremented by name-quoting 'f
400
401 When a variable is used, we compare
402 bind: binding level, and
403 use: current level at usage site
404
405 Generally
406 bind > use Always error (bound later than used)
407 [| \x -> $(f x) |]
408
409 bind = use Always OK (bound same stage as used)
410 [| \x -> $(f [| x |]) |]
411
412 bind < use Inside brackets, it depends
413 Inside splice, OK
414 Inside neither, OK
415
416 For (bind < use) inside brackets, there are three cases:
417 - Imported things OK f = [| map |]
418 - Top-level things OK g = [| f |]
419 - Non-top-level Only if there is a liftable instance
420 h = \(x:Int) -> [| x |]
421
422 To track top-level-ness we use the ThBindEnv in TcLclEnv
423
424 For example:
425 f = ...
426 g1 = $(map ...) is OK
427 g2 = $(f ...) is not OK; because we havn't compiled f yet
428
429 -}
430
431 {-
432 ************************************************************************
433 * *
434 \subsection{Splicing an expression}
435 * *
436 ************************************************************************
437 -}
438
439 tcSpliceExpr splice@(HsTypedSplice _ _ name expr) res_ty
440 = addErrCtxt (spliceCtxtDoc splice) $
441 setSrcSpan (getLoc expr) $ do
442 { stage <- getStage
443 ; case stage of
444 Splice {} -> tcTopSplice expr res_ty
445 Brack pop_stage pend -> tcNestedSplice pop_stage pend name expr res_ty
446 RunSplice _ ->
447 -- See Note [RunSplice ThLevel] in "TcRnTypes".
448 pprPanic ("tcSpliceExpr: attempted to typecheck a splice when " ++
449 "running another splice") (ppr splice)
450 Comp -> tcTopSplice expr res_ty
451 }
452 tcSpliceExpr splice _
453 = pprPanic "tcSpliceExpr" (ppr splice)
454
455 {- Note [Collecting modFinalizers in typed splices]
456 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
457
458 'qAddModFinalizer' of the @Quasi TcM@ instance adds finalizers in the local
459 environment (see Note [Delaying modFinalizers in untyped splices] in
460 "RnSplice"). Thus after executing the splice, we move the finalizers to the
461 finalizer list in the global environment and set them to use the current local
462 environment (with 'addModFinalizersWithLclEnv').
463
464 -}
465
466 tcNestedSplice :: ThStage -> PendingStuff -> Name
467 -> LHsExpr GhcRn -> ExpRhoType -> TcM (HsExpr GhcTc)
468 -- See Note [How brackets and nested splices are handled]
469 -- A splice inside brackets
470 tcNestedSplice pop_stage (TcPending ps_var lie_var) splice_name expr res_ty
471 = do { res_ty <- expTypeToType res_ty
472 ; meta_exp_ty <- tcTExpTy res_ty
473 ; expr' <- setStage pop_stage $
474 setConstraintVar lie_var $
475 tcMonoExpr expr (mkCheckExpType meta_exp_ty)
476 ; untypeq <- tcLookupId unTypeQName
477 ; let expr'' = mkHsApp (nlHsTyApp untypeq [res_ty]) expr'
478 ; ps <- readMutVar ps_var
479 ; writeMutVar ps_var (PendingTcSplice splice_name expr'' : ps)
480
481 -- The returned expression is ignored; it's in the pending splices
482 ; return (panic "tcSpliceExpr") }
483
484 tcNestedSplice _ _ splice_name _ _
485 = pprPanic "tcNestedSplice: rename stage found" (ppr splice_name)
486
487 tcTopSplice :: LHsExpr GhcRn -> ExpRhoType -> TcM (HsExpr GhcTc)
488 tcTopSplice expr res_ty
489 = do { -- Typecheck the expression,
490 -- making sure it has type Q (T res_ty)
491 res_ty <- expTypeToType res_ty
492 ; meta_exp_ty <- tcTExpTy res_ty
493 ; zonked_q_expr <- tcTopSpliceExpr Typed $
494 tcMonoExpr expr (mkCheckExpType meta_exp_ty)
495
496 -- See Note [Collecting modFinalizers in typed splices].
497 ; modfinalizers_ref <- newTcRef []
498 -- Run the expression
499 ; expr2 <- setStage (RunSplice modfinalizers_ref) $
500 runMetaE zonked_q_expr
501 ; mod_finalizers <- readTcRef modfinalizers_ref
502 ; addModFinalizersWithLclEnv $ ThModFinalizers mod_finalizers
503 ; traceSplice (SpliceInfo { spliceDescription = "expression"
504 , spliceIsDecl = False
505 , spliceSource = Just expr
506 , spliceGenerated = ppr expr2 })
507
508 -- Rename and typecheck the spliced-in expression,
509 -- making sure it has type res_ty
510 -- These steps should never fail; this is a *typed* splice
511 ; addErrCtxt (spliceResultDoc expr) $ do
512 { (exp3, _fvs) <- rnLExpr expr2
513 ; exp4 <- tcMonoExpr exp3 (mkCheckExpType res_ty)
514 ; return (unLoc exp4) } }
515
516 {-
517 ************************************************************************
518 * *
519 \subsection{Error messages}
520 * *
521 ************************************************************************
522 -}
523
524 spliceCtxtDoc :: HsSplice GhcRn -> SDoc
525 spliceCtxtDoc splice
526 = hang (text "In the Template Haskell splice")
527 2 (pprSplice splice)
528
529 spliceResultDoc :: LHsExpr GhcRn -> SDoc
530 spliceResultDoc expr
531 = sep [ text "In the result of the splice:"
532 , nest 2 (char '$' <> ppr expr)
533 , text "To see what the splice expanded to, use -ddump-splices"]
534
535 -------------------
536 tcTopSpliceExpr :: SpliceType -> TcM (LHsExpr GhcTc) -> TcM (LHsExpr GhcTc)
537 -- Note [How top-level splices are handled]
538 -- Type check an expression that is the body of a top-level splice
539 -- (the caller will compile and run it)
540 -- Note that set the level to Splice, regardless of the original level,
541 -- before typechecking the expression. For example:
542 -- f x = $( ...$(g 3) ... )
543 -- The recursive call to tcPolyExpr will simply expand the
544 -- inner escape before dealing with the outer one
545
546 tcTopSpliceExpr isTypedSplice tc_action
547 = checkNoErrs $ -- checkNoErrs: must not try to run the thing
548 -- if the type checker fails!
549 unsetGOptM Opt_DeferTypeErrors $
550 -- Don't defer type errors. Not only are we
551 -- going to run this code, but we do an unsafe
552 -- coerce, so we get a seg-fault if, say we
553 -- splice a type into a place where an expression
554 -- is expected (Trac #7276)
555 setStage (Splice isTypedSplice) $
556 do { -- Typecheck the expression
557 (expr', wanted) <- captureConstraints tc_action
558 ; const_binds <- simplifyTop wanted
559
560 -- Zonk it and tie the knot of dictionary bindings
561 ; zonkTopLExpr (mkHsDictLet (EvBinds const_binds) expr') }
562
563 {-
564 ************************************************************************
565 * *
566 Annotations
567 * *
568 ************************************************************************
569 -}
570
571 runAnnotation target expr = do
572 -- Find the classes we want instances for in order to call toAnnotationWrapper
573 loc <- getSrcSpanM
574 data_class <- tcLookupClass dataClassName
575 to_annotation_wrapper_id <- tcLookupId toAnnotationWrapperName
576
577 -- Check the instances we require live in another module (we want to execute it..)
578 -- and check identifiers live in other modules using TH stage checks. tcSimplifyStagedExpr
579 -- also resolves the LIE constraints to detect e.g. instance ambiguity
580 zonked_wrapped_expr' <- tcTopSpliceExpr Untyped $
581 do { (expr', expr_ty) <- tcInferRhoNC expr
582 -- We manually wrap the typechecked expression in a call to toAnnotationWrapper
583 -- By instantiating the call >here< it gets registered in the
584 -- LIE consulted by tcTopSpliceExpr
585 -- and hence ensures the appropriate dictionary is bound by const_binds
586 ; wrapper <- instCall AnnOrigin [expr_ty] [mkClassPred data_class [expr_ty]]
587 ; let specialised_to_annotation_wrapper_expr
588 = L loc (mkHsWrap wrapper
589 (HsVar noExt (L loc to_annotation_wrapper_id)))
590 ; return (L loc (HsApp noExt
591 specialised_to_annotation_wrapper_expr expr')) }
592
593 -- Run the appropriately wrapped expression to get the value of
594 -- the annotation and its dictionaries. The return value is of
595 -- type AnnotationWrapper by construction, so this conversion is
596 -- safe
597 serialized <- runMetaAW zonked_wrapped_expr'
598 return Annotation {
599 ann_target = target,
600 ann_value = serialized
601 }
602
603 convertAnnotationWrapper :: ForeignHValue -> TcM (Either MsgDoc Serialized)
604 convertAnnotationWrapper fhv = do
605 dflags <- getDynFlags
606 if gopt Opt_ExternalInterpreter dflags
607 then do
608 Right <$> runTH THAnnWrapper fhv
609 else do
610 annotation_wrapper <- liftIO $ wormhole dflags fhv
611 return $ Right $
612 case unsafeCoerce# annotation_wrapper of
613 AnnotationWrapper value | let serialized = toSerialized serializeWithData value ->
614 -- Got the value and dictionaries: build the serialized value and
615 -- call it a day. We ensure that we seq the entire serialized value
616 -- in order that any errors in the user-written code for the
617 -- annotation are exposed at this point. This is also why we are
618 -- doing all this stuff inside the context of runMeta: it has the
619 -- facilities to deal with user error in a meta-level expression
620 seqSerialized serialized `seq` serialized
621
622 -- | Force the contents of the Serialized value so weknow it doesn't contain any bottoms
623 seqSerialized :: Serialized -> ()
624 seqSerialized (Serialized the_type bytes) = the_type `seq` bytes `seqList` ()
625
626
627 {-
628 ************************************************************************
629 * *
630 \subsection{Running an expression}
631 * *
632 ************************************************************************
633 -}
634
635 runQuasi :: TH.Q a -> TcM a
636 runQuasi act = TH.runQ act
637
638 runRemoteModFinalizers :: ThModFinalizers -> TcM ()
639 runRemoteModFinalizers (ThModFinalizers finRefs) = do
640 dflags <- getDynFlags
641 let withForeignRefs [] f = f []
642 withForeignRefs (x : xs) f = withForeignRef x $ \r ->
643 withForeignRefs xs $ \rs -> f (r : rs)
644 if gopt Opt_ExternalInterpreter dflags then do
645 hsc_env <- env_top <$> getEnv
646 withIServ hsc_env $ \i -> do
647 tcg <- getGblEnv
648 th_state <- readTcRef (tcg_th_remote_state tcg)
649 case th_state of
650 Nothing -> return () -- TH was not started, nothing to do
651 Just fhv -> do
652 liftIO $ withForeignRef fhv $ \st ->
653 withForeignRefs finRefs $ \qrefs ->
654 writeIServ i (putMessage (RunModFinalizers st qrefs))
655 () <- runRemoteTH i []
656 readQResult i
657 else do
658 qs <- liftIO (withForeignRefs finRefs $ mapM localRef)
659 runQuasi $ sequence_ qs
660
661 runQResult
662 :: (a -> String)
663 -> (SrcSpan -> a -> b)
664 -> (ForeignHValue -> TcM a)
665 -> SrcSpan
666 -> ForeignHValue {- TH.Q a -}
667 -> TcM b
668 runQResult show_th f runQ expr_span hval
669 = do { th_result <- runQ hval
670 ; traceTc "Got TH result:" (text (show_th th_result))
671 ; return (f expr_span th_result) }
672
673
674 -----------------
675 runMeta :: (MetaHook TcM -> LHsExpr GhcTc -> TcM hs_syn)
676 -> LHsExpr GhcTc
677 -> TcM hs_syn
678 runMeta unwrap e
679 = do { h <- getHooked runMetaHook defaultRunMeta
680 ; unwrap h e }
681
682 defaultRunMeta :: MetaHook TcM
683 defaultRunMeta (MetaE r)
684 = fmap r . runMeta' True ppr (runQResult TH.pprint convertToHsExpr runTHExp)
685 defaultRunMeta (MetaP r)
686 = fmap r . runMeta' True ppr (runQResult TH.pprint convertToPat runTHPat)
687 defaultRunMeta (MetaT r)
688 = fmap r . runMeta' True ppr (runQResult TH.pprint convertToHsType runTHType)
689 defaultRunMeta (MetaD r)
690 = fmap r . runMeta' True ppr (runQResult TH.pprint convertToHsDecls runTHDec)
691 defaultRunMeta (MetaAW r)
692 = fmap r . runMeta' False (const empty) (const convertAnnotationWrapper)
693 -- We turn off showing the code in meta-level exceptions because doing so exposes
694 -- the toAnnotationWrapper function that we slap around the user's code
695
696 ----------------
697 runMetaAW :: LHsExpr GhcTc -- Of type AnnotationWrapper
698 -> TcM Serialized
699 runMetaAW = runMeta metaRequestAW
700
701 runMetaE :: LHsExpr GhcTc -- Of type (Q Exp)
702 -> TcM (LHsExpr GhcPs)
703 runMetaE = runMeta metaRequestE
704
705 runMetaP :: LHsExpr GhcTc -- Of type (Q Pat)
706 -> TcM (LPat GhcPs)
707 runMetaP = runMeta metaRequestP
708
709 runMetaT :: LHsExpr GhcTc -- Of type (Q Type)
710 -> TcM (LHsType GhcPs)
711 runMetaT = runMeta metaRequestT
712
713 runMetaD :: LHsExpr GhcTc -- Of type Q [Dec]
714 -> TcM [LHsDecl GhcPs]
715 runMetaD = runMeta metaRequestD
716
717 ---------------
718 runMeta' :: Bool -- Whether code should be printed in the exception message
719 -> (hs_syn -> SDoc) -- how to print the code
720 -> (SrcSpan -> ForeignHValue -> TcM (Either MsgDoc hs_syn)) -- How to run x
721 -> LHsExpr GhcTc -- Of type x; typically x = Q TH.Exp, or
722 -- something like that
723 -> TcM hs_syn -- Of type t
724 runMeta' show_code ppr_hs run_and_convert expr
725 = do { traceTc "About to run" (ppr expr)
726 ; recordThSpliceUse -- seems to be the best place to do this,
727 -- we catch all kinds of splices and annotations.
728
729 -- Check that we've had no errors of any sort so far.
730 -- For example, if we found an error in an earlier defn f, but
731 -- recovered giving it type f :: forall a.a, it'd be very dodgy
732 -- to carry ont. Mind you, the staging restrictions mean we won't
733 -- actually run f, but it still seems wrong. And, more concretely,
734 -- see Trac #5358 for an example that fell over when trying to
735 -- reify a function with a "?" kind in it. (These don't occur
736 -- in type-correct programs.
737 ; failIfErrsM
738
739 -- run plugins
740 ; hsc_env <- getTopEnv
741 ; expr' <- withPlugins (hsc_dflags hsc_env) spliceRunAction expr
742
743 -- Desugar
744 ; ds_expr <- initDsTc (dsLExpr expr')
745 -- Compile and link it; might fail if linking fails
746 ; src_span <- getSrcSpanM
747 ; traceTc "About to run (desugared)" (ppr ds_expr)
748 ; either_hval <- tryM $ liftIO $
749 HscMain.hscCompileCoreExpr hsc_env src_span ds_expr
750 ; case either_hval of {
751 Left exn -> fail_with_exn "compile and link" exn ;
752 Right hval -> do
753
754 { -- Coerce it to Q t, and run it
755
756 -- Running might fail if it throws an exception of any kind (hence tryAllM)
757 -- including, say, a pattern-match exception in the code we are running
758 --
759 -- We also do the TH -> HS syntax conversion inside the same
760 -- exception-cacthing thing so that if there are any lurking
761 -- exceptions in the data structure returned by hval, we'll
762 -- encounter them inside the try
763 --
764 -- See Note [Exceptions in TH]
765 let expr_span = getLoc expr
766 ; either_tval <- tryAllM $
767 setSrcSpan expr_span $ -- Set the span so that qLocation can
768 -- see where this splice is
769 do { mb_result <- run_and_convert expr_span hval
770 ; case mb_result of
771 Left err -> failWithTc err
772 Right result -> do { traceTc "Got HsSyn result:" (ppr_hs result)
773 ; return $! result } }
774
775 ; case either_tval of
776 Right v -> return v
777 Left se -> case fromException se of
778 Just IOEnvFailure -> failM -- Error already in Tc monad
779 _ -> fail_with_exn "run" se -- Exception
780 }}}
781 where
782 -- see Note [Concealed TH exceptions]
783 fail_with_exn :: Exception e => String -> e -> TcM a
784 fail_with_exn phase exn = do
785 exn_msg <- liftIO $ Panic.safeShowException exn
786 let msg = vcat [text "Exception when trying to" <+> text phase <+> text "compile-time code:",
787 nest 2 (text exn_msg),
788 if show_code then text "Code:" <+> ppr expr else empty]
789 failWithTc msg
790
791 {-
792 Note [Exceptions in TH]
793 ~~~~~~~~~~~~~~~~~~~~~~~
794 Suppose we have something like this
795 $( f 4 )
796 where
797 f :: Int -> Q [Dec]
798 f n | n>3 = fail "Too many declarations"
799 | otherwise = ...
800
801 The 'fail' is a user-generated failure, and should be displayed as a
802 perfectly ordinary compiler error message, not a panic or anything
803 like that. Here's how it's processed:
804
805 * 'fail' is the monad fail. The monad instance for Q in TH.Syntax
806 effectively transforms (fail s) to
807 qReport True s >> fail
808 where 'qReport' comes from the Quasi class and fail from its monad
809 superclass.
810
811 * The TcM monad is an instance of Quasi (see TcSplice), and it implements
812 (qReport True s) by using addErr to add an error message to the bag of errors.
813 The 'fail' in TcM raises an IOEnvFailure exception
814
815 * 'qReport' forces the message to ensure any exception hidden in unevaluated
816 thunk doesn't get into the bag of errors. Otherwise the following splice
817 will triger panic (Trac #8987):
818 $(fail undefined)
819 See also Note [Concealed TH exceptions]
820
821 * So, when running a splice, we catch all exceptions; then for
822 - an IOEnvFailure exception, we assume the error is already
823 in the error-bag (above)
824 - other errors, we add an error to the bag
825 and then fail
826
827 Note [Concealed TH exceptions]
828 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
829 When displaying the error message contained in an exception originated from TH
830 code, we need to make sure that the error message itself does not contain an
831 exception. For example, when executing the following splice:
832
833 $( error ("foo " ++ error "bar") )
834
835 the message for the outer exception is a thunk which will throw the inner
836 exception when evaluated.
837
838 For this reason, we display the message of a TH exception using the
839 'safeShowException' function, which recursively catches any exception thrown
840 when showing an error message.
841
842
843 To call runQ in the Tc monad, we need to make TcM an instance of Quasi:
844 -}
845
846 instance TH.Quasi TcM where
847 qNewName s = do { u <- newUnique
848 ; let i = getKey u
849 ; return (TH.mkNameU s i) }
850
851 -- 'msg' is forced to ensure exceptions don't escape,
852 -- see Note [Exceptions in TH]
853 qReport True msg = seqList msg $ addErr (text msg)
854 qReport False msg = seqList msg $ addWarn NoReason (text msg)
855
856 qLocation = do { m <- getModule
857 ; l <- getSrcSpanM
858 ; r <- case l of
859 UnhelpfulSpan _ -> pprPanic "qLocation: Unhelpful location"
860 (ppr l)
861 RealSrcSpan s -> return s
862 ; return (TH.Loc { TH.loc_filename = unpackFS (srcSpanFile r)
863 , TH.loc_module = moduleNameString (moduleName m)
864 , TH.loc_package = unitIdString (moduleUnitId m)
865 , TH.loc_start = (srcSpanStartLine r, srcSpanStartCol r)
866 , TH.loc_end = (srcSpanEndLine r, srcSpanEndCol r) }) }
867
868 qLookupName = lookupName
869 qReify = reify
870 qReifyFixity nm = lookupThName nm >>= reifyFixity
871 qReifyInstances = reifyInstances
872 qReifyRoles = reifyRoles
873 qReifyAnnotations = reifyAnnotations
874 qReifyModule = reifyModule
875 qReifyConStrictness nm = do { nm' <- lookupThName nm
876 ; dc <- tcLookupDataCon nm'
877 ; let bangs = dataConImplBangs dc
878 ; return (map reifyDecidedStrictness bangs) }
879
880 -- For qRecover, discard error messages if
881 -- the recovery action is chosen. Otherwise
882 -- we'll only fail higher up.
883 qRecover recover main = tryTcDiscardingErrs recover main
884
885 qAddDependentFile fp = do
886 ref <- fmap tcg_dependent_files getGblEnv
887 dep_files <- readTcRef ref
888 writeTcRef ref (fp:dep_files)
889
890 qAddTempFile suffix = do
891 dflags <- getDynFlags
892 liftIO $ newTempName dflags TFL_GhcSession suffix
893
894 qAddTopDecls thds = do
895 l <- getSrcSpanM
896 let either_hval = convertToHsDecls l thds
897 ds <- case either_hval of
898 Left exn -> pprPanic "qAddTopDecls: can't convert top-level declarations" exn
899 Right ds -> return ds
900 mapM_ (checkTopDecl . unLoc) ds
901 th_topdecls_var <- fmap tcg_th_topdecls getGblEnv
902 updTcRef th_topdecls_var (\topds -> ds ++ topds)
903 where
904 checkTopDecl :: HsDecl GhcPs -> TcM ()
905 checkTopDecl (ValD _ binds)
906 = mapM_ bindName (collectHsBindBinders binds)
907 checkTopDecl (SigD _ _)
908 = return ()
909 checkTopDecl (AnnD _ _)
910 = return ()
911 checkTopDecl (ForD _ (ForeignImport { fd_name = L _ name }))
912 = bindName name
913 checkTopDecl _
914 = addErr $ text "Only function, value, annotation, and foreign import declarations may be added with addTopDecl"
915
916 bindName :: RdrName -> TcM ()
917 bindName (Exact n)
918 = do { th_topnames_var <- fmap tcg_th_topnames getGblEnv
919 ; updTcRef th_topnames_var (\ns -> extendNameSet ns n)
920 }
921
922 bindName name =
923 addErr $
924 hang (text "The binder" <+> quotes (ppr name) <+> ptext (sLit "is not a NameU."))
925 2 (text "Probable cause: you used mkName instead of newName to generate a binding.")
926
927 qAddForeignFilePath lang fp = do
928 var <- fmap tcg_th_foreign_files getGblEnv
929 updTcRef var ((lang, fp) :)
930
931 qAddModFinalizer fin = do
932 r <- liftIO $ mkRemoteRef fin
933 fref <- liftIO $ mkForeignRef r (freeRemoteRef r)
934 addModFinalizerRef fref
935
936 qAddCorePlugin plugin = do
937 hsc_env <- env_top <$> getEnv
938 r <- liftIO $ findHomeModule hsc_env (mkModuleName plugin)
939 let err = hang
940 (text "addCorePlugin: invalid plugin module "
941 <+> text (show plugin)
942 )
943 2
944 (text "Plugins in the current package can't be specified.")
945 case r of
946 Found {} -> addErr err
947 FoundMultiple {} -> addErr err
948 _ -> return ()
949 th_coreplugins_var <- tcg_th_coreplugins <$> getGblEnv
950 updTcRef th_coreplugins_var (plugin:)
951
952 qGetQ :: forall a. Typeable a => TcM (Maybe a)
953 qGetQ = do
954 th_state_var <- fmap tcg_th_state getGblEnv
955 th_state <- readTcRef th_state_var
956 -- See #10596 for why we use a scoped type variable here.
957 return (Map.lookup (typeRep (Proxy :: Proxy a)) th_state >>= fromDynamic)
958
959 qPutQ x = do
960 th_state_var <- fmap tcg_th_state getGblEnv
961 updTcRef th_state_var (\m -> Map.insert (typeOf x) (toDyn x) m)
962
963 qIsExtEnabled = xoptM
964
965 qExtsEnabled =
966 EnumSet.toList . extensionFlags . hsc_dflags <$> getTopEnv
967
968 -- | Adds a mod finalizer reference to the local environment.
969 addModFinalizerRef :: ForeignRef (TH.Q ()) -> TcM ()
970 addModFinalizerRef finRef = do
971 th_stage <- getStage
972 case th_stage of
973 RunSplice th_modfinalizers_var -> updTcRef th_modfinalizers_var (finRef :)
974 -- This case happens only if a splice is executed and the caller does
975 -- not set the 'ThStage' to 'RunSplice' to collect finalizers.
976 -- See Note [Delaying modFinalizers in untyped splices] in RnSplice.
977 _ ->
978 pprPanic "addModFinalizer was called when no finalizers were collected"
979 (ppr th_stage)
980
981 -- | Releases the external interpreter state.
982 finishTH :: TcM ()
983 finishTH = do
984 dflags <- getDynFlags
985 when (gopt Opt_ExternalInterpreter dflags) $ do
986 tcg <- getGblEnv
987 writeTcRef (tcg_th_remote_state tcg) Nothing
988
989 runTHExp :: ForeignHValue -> TcM TH.Exp
990 runTHExp = runTH THExp
991
992 runTHPat :: ForeignHValue -> TcM TH.Pat
993 runTHPat = runTH THPat
994
995 runTHType :: ForeignHValue -> TcM TH.Type
996 runTHType = runTH THType
997
998 runTHDec :: ForeignHValue -> TcM [TH.Dec]
999 runTHDec = runTH THDec
1000
1001 runTH :: Binary a => THResultType -> ForeignHValue -> TcM a
1002 runTH ty fhv = do
1003 hsc_env <- env_top <$> getEnv
1004 dflags <- getDynFlags
1005 if not (gopt Opt_ExternalInterpreter dflags)
1006 then do
1007 -- Run it in the local TcM
1008 hv <- liftIO $ wormhole dflags fhv
1009 r <- runQuasi (unsafeCoerce# hv :: TH.Q a)
1010 return r
1011 else
1012 -- Run it on the server. For an overview of how TH works with
1013 -- Remote GHCi, see Note [Remote Template Haskell] in
1014 -- libraries/ghci/GHCi/TH.hs.
1015 withIServ hsc_env $ \i -> do
1016 rstate <- getTHState i
1017 loc <- TH.qLocation
1018 liftIO $
1019 withForeignRef rstate $ \state_hv ->
1020 withForeignRef fhv $ \q_hv ->
1021 writeIServ i (putMessage (RunTH state_hv q_hv ty (Just loc)))
1022 runRemoteTH i []
1023 bs <- readQResult i
1024 return $! runGet get (LB.fromStrict bs)
1025
1026
1027 -- | communicate with a remotely-running TH computation until it finishes.
1028 -- See Note [Remote Template Haskell] in libraries/ghci/GHCi/TH.hs.
1029 runRemoteTH
1030 :: IServ
1031 -> [Messages] -- saved from nested calls to qRecover
1032 -> TcM ()
1033 runRemoteTH iserv recovers = do
1034 THMsg msg <- liftIO $ readIServ iserv getTHMessage
1035 case msg of
1036 RunTHDone -> return ()
1037 StartRecover -> do -- Note [TH recover with -fexternal-interpreter]
1038 v <- getErrsVar
1039 msgs <- readTcRef v
1040 writeTcRef v emptyMessages
1041 runRemoteTH iserv (msgs : recovers)
1042 EndRecover caught_error -> do
1043 v <- getErrsVar
1044 let (prev_msgs, rest) = case recovers of
1045 [] -> panic "EndRecover"
1046 a : b -> (a,b)
1047 if caught_error
1048 then writeTcRef v prev_msgs
1049 else updTcRef v (unionMessages prev_msgs)
1050 runRemoteTH iserv rest
1051 _other -> do
1052 r <- handleTHMessage msg
1053 liftIO $ writeIServ iserv (put r)
1054 runRemoteTH iserv recovers
1055
1056 -- | Read a value of type QResult from the iserv
1057 readQResult :: Binary a => IServ -> TcM a
1058 readQResult i = do
1059 qr <- liftIO $ readIServ i get
1060 case qr of
1061 QDone a -> return a
1062 QException str -> liftIO $ throwIO (ErrorCall str)
1063 QFail str -> fail str
1064
1065 {- Note [TH recover with -fexternal-interpreter]
1066
1067 Recover is slightly tricky to implement.
1068
1069 The meaning of "recover a b" is
1070 - Do a
1071 - If it finished successfully, then keep the messages it generated
1072 - If it failed, discard any messages it generated, and do b
1073
1074 The messages are managed by GHC in the TcM monad, whereas the
1075 exception-handling is done in the ghc-iserv process, so we have to
1076 coordinate between the two.
1077
1078 On the server:
1079 - emit a StartRecover message
1080 - run "a" inside a catch
1081 - if it finishes, emit EndRecover False
1082 - if it fails, emit EndRecover True, then run "b"
1083
1084 Back in GHC, when we receive:
1085
1086 StartRecover
1087 save the current messages and start with an empty set.
1088 EndRecover caught_error
1089 Restore the previous messages,
1090 and merge in the new messages if caught_error is false.
1091 -}
1092
1093 -- | Retrieve (or create, if it hasn't been created already), the
1094 -- remote TH state. The TH state is a remote reference to an IORef
1095 -- QState living on the server, and we have to pass this to each RunTH
1096 -- call we make.
1097 --
1098 -- The TH state is stored in tcg_th_remote_state in the TcGblEnv.
1099 --
1100 getTHState :: IServ -> TcM (ForeignRef (IORef QState))
1101 getTHState i = do
1102 tcg <- getGblEnv
1103 th_state <- readTcRef (tcg_th_remote_state tcg)
1104 case th_state of
1105 Just rhv -> return rhv
1106 Nothing -> do
1107 hsc_env <- env_top <$> getEnv
1108 fhv <- liftIO $ mkFinalizedHValue hsc_env =<< iservCall i StartTH
1109 writeTcRef (tcg_th_remote_state tcg) (Just fhv)
1110 return fhv
1111
1112 wrapTHResult :: TcM a -> TcM (THResult a)
1113 wrapTHResult tcm = do
1114 e <- tryM tcm -- only catch 'fail', treat everything else as catastrophic
1115 case e of
1116 Left e -> return (THException (show e))
1117 Right a -> return (THComplete a)
1118
1119 handleTHMessage :: THMessage a -> TcM a
1120 handleTHMessage msg = case msg of
1121 NewName a -> wrapTHResult $ TH.qNewName a
1122 Report b str -> wrapTHResult $ TH.qReport b str
1123 LookupName b str -> wrapTHResult $ TH.qLookupName b str
1124 Reify n -> wrapTHResult $ TH.qReify n
1125 ReifyFixity n -> wrapTHResult $ TH.qReifyFixity n
1126 ReifyInstances n ts -> wrapTHResult $ TH.qReifyInstances n ts
1127 ReifyRoles n -> wrapTHResult $ TH.qReifyRoles n
1128 ReifyAnnotations lookup tyrep ->
1129 wrapTHResult $ (map B.pack <$> getAnnotationsByTypeRep lookup tyrep)
1130 ReifyModule m -> wrapTHResult $ TH.qReifyModule m
1131 ReifyConStrictness nm -> wrapTHResult $ TH.qReifyConStrictness nm
1132 AddDependentFile f -> wrapTHResult $ TH.qAddDependentFile f
1133 AddTempFile s -> wrapTHResult $ TH.qAddTempFile s
1134 AddModFinalizer r -> do
1135 hsc_env <- env_top <$> getEnv
1136 wrapTHResult $ liftIO (mkFinalizedHValue hsc_env r) >>= addModFinalizerRef
1137 AddCorePlugin str -> wrapTHResult $ TH.qAddCorePlugin str
1138 AddTopDecls decs -> wrapTHResult $ TH.qAddTopDecls decs
1139 AddForeignFilePath lang str -> wrapTHResult $ TH.qAddForeignFilePath lang str
1140 IsExtEnabled ext -> wrapTHResult $ TH.qIsExtEnabled ext
1141 ExtsEnabled -> wrapTHResult $ TH.qExtsEnabled
1142 _ -> panic ("handleTHMessage: unexpected message " ++ show msg)
1143
1144 getAnnotationsByTypeRep :: TH.AnnLookup -> TypeRep -> TcM [[Word8]]
1145 getAnnotationsByTypeRep th_name tyrep
1146 = do { name <- lookupThAnnLookup th_name
1147 ; topEnv <- getTopEnv
1148 ; epsHptAnns <- liftIO $ prepareAnnotations topEnv Nothing
1149 ; tcg <- getGblEnv
1150 ; let selectedEpsHptAnns = findAnnsByTypeRep epsHptAnns name tyrep
1151 ; let selectedTcgAnns = findAnnsByTypeRep (tcg_ann_env tcg) name tyrep
1152 ; return (selectedEpsHptAnns ++ selectedTcgAnns) }
1153
1154 {-
1155 ************************************************************************
1156 * *
1157 Instance Testing
1158 * *
1159 ************************************************************************
1160 -}
1161
1162 reifyInstances :: TH.Name -> [TH.Type] -> TcM [TH.Dec]
1163 reifyInstances th_nm th_tys
1164 = addErrCtxt (text "In the argument of reifyInstances:"
1165 <+> ppr_th th_nm <+> sep (map ppr_th th_tys)) $
1166 do { loc <- getSrcSpanM
1167 ; rdr_ty <- cvt loc (mkThAppTs (TH.ConT th_nm) th_tys)
1168 -- #9262 says to bring vars into scope, like in HsForAllTy case
1169 -- of rnHsTyKi
1170 ; free_vars <- extractHsTyRdrTyVars rdr_ty
1171 ; let tv_rdrs = freeKiTyVarsAllVars free_vars
1172 -- Rename to HsType Name
1173 ; ((tv_names, rn_ty), _fvs)
1174 <- checkNoErrs $ -- If there are out-of-scope Names here, then we
1175 -- must error before proceeding to typecheck the
1176 -- renamed type, as that will result in GHC
1177 -- internal errors (#13837).
1178 bindLRdrNames tv_rdrs $ \ tv_names ->
1179 do { (rn_ty, fvs) <- rnLHsType doc rdr_ty
1180 ; return ((tv_names, rn_ty), fvs) }
1181 ; (_tvs, ty)
1182 <- solveEqualities $
1183 tcImplicitTKBndrs ReifySkol tv_names $
1184 fst <$> tcLHsType rn_ty
1185 ; ty <- zonkTcTypeToType emptyZonkEnv ty
1186 -- Substitute out the meta type variables
1187 -- In particular, the type might have kind
1188 -- variables inside it (Trac #7477)
1189
1190 ; traceTc "reifyInstances" (ppr ty $$ ppr (typeKind ty))
1191 ; case splitTyConApp_maybe ty of -- This expands any type synonyms
1192 Just (tc, tys) -- See Trac #7910
1193 | Just cls <- tyConClass_maybe tc
1194 -> do { inst_envs <- tcGetInstEnvs
1195 ; let (matches, unifies, _) = lookupInstEnv False inst_envs cls tys
1196 ; traceTc "reifyInstances1" (ppr matches)
1197 ; reifyClassInstances cls (map fst matches ++ unifies) }
1198 | isOpenFamilyTyCon tc
1199 -> do { inst_envs <- tcGetFamInstEnvs
1200 ; let matches = lookupFamInstEnv inst_envs tc tys
1201 ; traceTc "reifyInstances2" (ppr matches)
1202 ; reifyFamilyInstances tc (map fim_instance matches) }
1203 _ -> bale_out (hang (text "reifyInstances:" <+> quotes (ppr ty))
1204 2 (text "is not a class constraint or type family application")) }
1205 where
1206 doc = ClassInstanceCtx
1207 bale_out msg = failWithTc msg
1208
1209 cvt :: SrcSpan -> TH.Type -> TcM (LHsType GhcPs)
1210 cvt loc th_ty = case convertToHsType loc th_ty of
1211 Left msg -> failWithTc msg
1212 Right ty -> return ty
1213
1214 {-
1215 ************************************************************************
1216 * *
1217 Reification
1218 * *
1219 ************************************************************************
1220 -}
1221
1222 lookupName :: Bool -- True <=> type namespace
1223 -- False <=> value namespace
1224 -> String -> TcM (Maybe TH.Name)
1225 lookupName is_type_name s
1226 = do { lcl_env <- getLocalRdrEnv
1227 ; case lookupLocalRdrEnv lcl_env rdr_name of
1228 Just n -> return (Just (reifyName n))
1229 Nothing -> do { mb_nm <- lookupGlobalOccRn_maybe rdr_name
1230 ; return (fmap reifyName mb_nm) } }
1231 where
1232 th_name = TH.mkName s -- Parses M.x into a base of 'x' and a module of 'M'
1233
1234 occ_fs :: FastString
1235 occ_fs = mkFastString (TH.nameBase th_name)
1236
1237 occ :: OccName
1238 occ | is_type_name
1239 = if isLexVarSym occ_fs || isLexCon occ_fs
1240 then mkTcOccFS occ_fs
1241 else mkTyVarOccFS occ_fs
1242 | otherwise
1243 = if isLexCon occ_fs then mkDataOccFS occ_fs
1244 else mkVarOccFS occ_fs
1245
1246 rdr_name = case TH.nameModule th_name of
1247 Nothing -> mkRdrUnqual occ
1248 Just mod -> mkRdrQual (mkModuleName mod) occ
1249
1250 getThing :: TH.Name -> TcM TcTyThing
1251 getThing th_name
1252 = do { name <- lookupThName th_name
1253 ; traceIf (text "reify" <+> text (show th_name) <+> brackets (ppr_ns th_name) <+> ppr name)
1254 ; tcLookupTh name }
1255 -- ToDo: this tcLookup could fail, which would give a
1256 -- rather unhelpful error message
1257 where
1258 ppr_ns (TH.Name _ (TH.NameG TH.DataName _pkg _mod)) = text "data"
1259 ppr_ns (TH.Name _ (TH.NameG TH.TcClsName _pkg _mod)) = text "tc"
1260 ppr_ns (TH.Name _ (TH.NameG TH.VarName _pkg _mod)) = text "var"
1261 ppr_ns _ = panic "reify/ppr_ns"
1262
1263 reify :: TH.Name -> TcM TH.Info
1264 reify th_name
1265 = do { traceTc "reify 1" (text (TH.showName th_name))
1266 ; thing <- getThing th_name
1267 ; traceTc "reify 2" (ppr thing)
1268 ; reifyThing thing }
1269
1270 lookupThName :: TH.Name -> TcM Name
1271 lookupThName th_name = do
1272 mb_name <- lookupThName_maybe th_name
1273 case mb_name of
1274 Nothing -> failWithTc (notInScope th_name)
1275 Just name -> return name
1276
1277 lookupThName_maybe :: TH.Name -> TcM (Maybe Name)
1278 lookupThName_maybe th_name
1279 = do { names <- mapMaybeM lookup (thRdrNameGuesses th_name)
1280 -- Pick the first that works
1281 -- E.g. reify (mkName "A") will pick the class A in preference to the data constructor A
1282 ; return (listToMaybe names) }
1283 where
1284 lookup rdr_name
1285 = do { -- Repeat much of lookupOccRn, because we want
1286 -- to report errors in a TH-relevant way
1287 ; rdr_env <- getLocalRdrEnv
1288 ; case lookupLocalRdrEnv rdr_env rdr_name of
1289 Just name -> return (Just name)
1290 Nothing -> lookupGlobalOccRn_maybe rdr_name }
1291
1292 tcLookupTh :: Name -> TcM TcTyThing
1293 -- This is a specialised version of TcEnv.tcLookup; specialised mainly in that
1294 -- it gives a reify-related error message on failure, whereas in the normal
1295 -- tcLookup, failure is a bug.
1296 tcLookupTh name
1297 = do { (gbl_env, lcl_env) <- getEnvs
1298 ; case lookupNameEnv (tcl_env lcl_env) name of {
1299 Just thing -> return thing;
1300 Nothing ->
1301
1302 case lookupNameEnv (tcg_type_env gbl_env) name of {
1303 Just thing -> return (AGlobal thing);
1304 Nothing ->
1305
1306 -- EZY: I don't think this choice matters, no TH in signatures!
1307 if nameIsLocalOrFrom (tcg_semantic_mod gbl_env) name
1308 then -- It's defined in this module
1309 failWithTc (notInEnv name)
1310
1311 else
1312 do { mb_thing <- tcLookupImported_maybe name
1313 ; case mb_thing of
1314 Succeeded thing -> return (AGlobal thing)
1315 Failed msg -> failWithTc msg
1316 }}}}
1317
1318 notInScope :: TH.Name -> SDoc
1319 notInScope th_name = quotes (text (TH.pprint th_name)) <+>
1320 text "is not in scope at a reify"
1321 -- Ugh! Rather an indirect way to display the name
1322
1323 notInEnv :: Name -> SDoc
1324 notInEnv name = quotes (ppr name) <+>
1325 text "is not in the type environment at a reify"
1326
1327 ------------------------------
1328 reifyRoles :: TH.Name -> TcM [TH.Role]
1329 reifyRoles th_name
1330 = do { thing <- getThing th_name
1331 ; case thing of
1332 AGlobal (ATyCon tc) -> return (map reify_role (tyConRoles tc))
1333 _ -> failWithTc (text "No roles associated with" <+> (ppr thing))
1334 }
1335 where
1336 reify_role Nominal = TH.NominalR
1337 reify_role Representational = TH.RepresentationalR
1338 reify_role Phantom = TH.PhantomR
1339
1340 ------------------------------
1341 reifyThing :: TcTyThing -> TcM TH.Info
1342 -- The only reason this is monadic is for error reporting,
1343 -- which in turn is mainly for the case when TH can't express
1344 -- some random GHC extension
1345
1346 reifyThing (AGlobal (AnId id))
1347 = do { ty <- reifyType (idType id)
1348 ; let v = reifyName id
1349 ; case idDetails id of
1350 ClassOpId cls -> return (TH.ClassOpI v ty (reifyName cls))
1351 RecSelId{sel_tycon=RecSelData tc}
1352 -> return (TH.VarI (reifySelector id tc) ty Nothing)
1353 _ -> return (TH.VarI v ty Nothing)
1354 }
1355
1356 reifyThing (AGlobal (ATyCon tc)) = reifyTyCon tc
1357 reifyThing (AGlobal (AConLike (RealDataCon dc)))
1358 = do { let name = dataConName dc
1359 ; ty <- reifyType (idType (dataConWrapId dc))
1360 ; return (TH.DataConI (reifyName name) ty
1361 (reifyName (dataConOrigTyCon dc)))
1362 }
1363
1364 reifyThing (AGlobal (AConLike (PatSynCon ps)))
1365 = do { let name = reifyName ps
1366 ; ty <- reifyPatSynType (patSynSig ps)
1367 ; return (TH.PatSynI name ty) }
1368
1369 reifyThing (ATcId {tct_id = id})
1370 = do { ty1 <- zonkTcType (idType id) -- Make use of all the info we have, even
1371 -- though it may be incomplete
1372 ; ty2 <- reifyType ty1
1373 ; return (TH.VarI (reifyName id) ty2 Nothing) }
1374
1375 reifyThing (ATyVar tv tv1)
1376 = do { ty1 <- zonkTcTyVar tv1
1377 ; ty2 <- reifyType ty1
1378 ; return (TH.TyVarI (reifyName tv) ty2) }
1379
1380 reifyThing thing = pprPanic "reifyThing" (pprTcTyThingCategory thing)
1381
1382 -------------------------------------------
1383 reifyAxBranch :: TyCon -> CoAxBranch -> TcM TH.TySynEqn
1384 reifyAxBranch fam_tc (CoAxBranch { cab_lhs = lhs, cab_rhs = rhs })
1385 -- remove kind patterns (#8884)
1386 = do { let lhs_types_only = filterOutInvisibleTypes fam_tc lhs
1387 ; lhs' <- reifyTypes lhs_types_only
1388 ; annot_th_lhs <- zipWith3M annotThType (mkIsPolyTvs fam_tvs)
1389 lhs_types_only lhs'
1390 ; rhs' <- reifyType rhs
1391 ; return (TH.TySynEqn annot_th_lhs rhs') }
1392 where
1393 fam_tvs = tyConVisibleTyVars fam_tc
1394
1395 reifyTyCon :: TyCon -> TcM TH.Info
1396 reifyTyCon tc
1397 | Just cls <- tyConClass_maybe tc
1398 = reifyClass cls
1399
1400 | isFunTyCon tc
1401 = return (TH.PrimTyConI (reifyName tc) 2 False)
1402
1403 | isPrimTyCon tc
1404 = return (TH.PrimTyConI (reifyName tc) (tyConArity tc) (isUnliftedTyCon tc))
1405
1406 | isTypeFamilyTyCon tc
1407 = do { let tvs = tyConTyVars tc
1408 res_kind = tyConResKind tc
1409 resVar = famTcResVar tc
1410
1411 ; kind' <- reifyKind res_kind
1412 ; let (resultSig, injectivity) =
1413 case resVar of
1414 Nothing -> (TH.KindSig kind', Nothing)
1415 Just name ->
1416 let thName = reifyName name
1417 injAnnot = tyConInjectivityInfo tc
1418 sig = TH.TyVarSig (TH.KindedTV thName kind')
1419 inj = case injAnnot of
1420 NotInjective -> Nothing
1421 Injective ms ->
1422 Just (TH.InjectivityAnn thName injRHS)
1423 where
1424 injRHS = map (reifyName . tyVarName)
1425 (filterByList ms tvs)
1426 in (sig, inj)
1427 ; tvs' <- reifyTyVars (tyConVisibleTyVars tc)
1428 ; let tfHead =
1429 TH.TypeFamilyHead (reifyName tc) tvs' resultSig injectivity
1430 ; if isOpenTypeFamilyTyCon tc
1431 then do { fam_envs <- tcGetFamInstEnvs
1432 ; instances <- reifyFamilyInstances tc
1433 (familyInstances fam_envs tc)
1434 ; return (TH.FamilyI (TH.OpenTypeFamilyD tfHead) instances) }
1435 else do { eqns <-
1436 case isClosedSynFamilyTyConWithAxiom_maybe tc of
1437 Just ax -> mapM (reifyAxBranch tc) $
1438 fromBranches $ coAxiomBranches ax
1439 Nothing -> return []
1440 ; return (TH.FamilyI (TH.ClosedTypeFamilyD tfHead eqns)
1441 []) } }
1442
1443 | isDataFamilyTyCon tc
1444 = do { let res_kind = tyConResKind tc
1445
1446 ; kind' <- fmap Just (reifyKind res_kind)
1447
1448 ; tvs' <- reifyTyVars (tyConVisibleTyVars tc)
1449 ; fam_envs <- tcGetFamInstEnvs
1450 ; instances <- reifyFamilyInstances tc (familyInstances fam_envs tc)
1451 ; return (TH.FamilyI
1452 (TH.DataFamilyD (reifyName tc) tvs' kind') instances) }
1453
1454 | Just (_, rhs) <- synTyConDefn_maybe tc -- Vanilla type synonym
1455 = do { rhs' <- reifyType rhs
1456 ; tvs' <- reifyTyVars (tyConVisibleTyVars tc)
1457 ; return (TH.TyConI
1458 (TH.TySynD (reifyName tc) tvs' rhs'))
1459 }
1460
1461 | otherwise
1462 = do { cxt <- reifyCxt (tyConStupidTheta tc)
1463 ; let tvs = tyConTyVars tc
1464 dataCons = tyConDataCons tc
1465 isGadt = isGadtSyntaxTyCon tc
1466 ; cons <- mapM (reifyDataCon isGadt (mkTyVarTys tvs)) dataCons
1467 ; r_tvs <- reifyTyVars (tyConVisibleTyVars tc)
1468 ; let name = reifyName tc
1469 deriv = [] -- Don't know about deriving
1470 decl | isNewTyCon tc =
1471 TH.NewtypeD cxt name r_tvs Nothing (head cons) deriv
1472 | otherwise =
1473 TH.DataD cxt name r_tvs Nothing cons deriv
1474 ; return (TH.TyConI decl) }
1475
1476 reifyDataCon :: Bool -> [Type] -> DataCon -> TcM TH.Con
1477 reifyDataCon isGadtDataCon tys dc
1478 = do { let -- used for H98 data constructors
1479 (ex_tvs, theta, arg_tys)
1480 = dataConInstSig dc tys
1481 -- used for GADTs data constructors
1482 g_user_tvs' = dataConUserTyVars dc
1483 (g_univ_tvs, _, g_eq_spec, g_theta', g_arg_tys', g_res_ty')
1484 = dataConFullSig dc
1485 (srcUnpks, srcStricts)
1486 = mapAndUnzip reifySourceBang (dataConSrcBangs dc)
1487 dcdBangs = zipWith TH.Bang srcUnpks srcStricts
1488 fields = dataConFieldLabels dc
1489 name = reifyName dc
1490 -- Universal tvs present in eq_spec need to be filtered out, as
1491 -- they will not appear anywhere in the type.
1492 eq_spec_tvs = mkVarSet (map eqSpecTyVar g_eq_spec)
1493
1494 ; (univ_subst, _)
1495 -- See Note [Freshen reified GADT constructors' universal tyvars]
1496 <- freshenTyVarBndrs $
1497 filterOut (`elemVarSet` eq_spec_tvs) g_univ_tvs
1498 ; let (tvb_subst, g_user_tvs)
1499 = mapAccumL substTyVarBndr univ_subst g_user_tvs'
1500 g_theta = substTys tvb_subst g_theta'
1501 g_arg_tys = substTys tvb_subst g_arg_tys'
1502 g_res_ty = substTy tvb_subst g_res_ty'
1503
1504 ; r_arg_tys <- reifyTypes (if isGadtDataCon then g_arg_tys else arg_tys)
1505
1506 ; main_con <-
1507 if | not (null fields) && not isGadtDataCon ->
1508 return $ TH.RecC name (zip3 (map reifyFieldLabel fields)
1509 dcdBangs r_arg_tys)
1510 | not (null fields) -> do
1511 { res_ty <- reifyType g_res_ty
1512 ; return $ TH.RecGadtC [name]
1513 (zip3 (map (reifyName . flSelector) fields)
1514 dcdBangs r_arg_tys) res_ty }
1515 -- We need to check not isGadtDataCon here because GADT
1516 -- constructors can be declared infix.
1517 -- See Note [Infix GADT constructors] in TcTyClsDecls.
1518 | dataConIsInfix dc && not isGadtDataCon ->
1519 ASSERT( arg_tys `lengthIs` 2 ) do
1520 { let [r_a1, r_a2] = r_arg_tys
1521 [s1, s2] = dcdBangs
1522 ; return $ TH.InfixC (s1,r_a1) name (s2,r_a2) }
1523 | isGadtDataCon -> do
1524 { res_ty <- reifyType g_res_ty
1525 ; return $ TH.GadtC [name] (dcdBangs `zip` r_arg_tys) res_ty }
1526 | otherwise ->
1527 return $ TH.NormalC name (dcdBangs `zip` r_arg_tys)
1528
1529 ; let (ex_tvs', theta') | isGadtDataCon = (g_user_tvs, g_theta)
1530 | otherwise = (ex_tvs, theta)
1531 ret_con | null ex_tvs' && null theta' = return main_con
1532 | otherwise = do
1533 { cxt <- reifyCxt theta'
1534 ; ex_tvs'' <- reifyTyVars ex_tvs'
1535 ; return (TH.ForallC ex_tvs'' cxt main_con) }
1536 ; ASSERT( arg_tys `equalLength` dcdBangs )
1537 ret_con }
1538
1539 {-
1540 Note [Freshen reified GADT constructors' universal tyvars]
1541 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1542 Suppose one were to reify this GADT:
1543
1544 data a :~: b where
1545 Refl :: forall a b. (a ~ b) => a :~: b
1546
1547 We ought to be careful here about the uniques we give to the occurrences of `a`
1548 and `b` in this definition. That is because in the original DataCon, all uses
1549 of `a` and `b` have the same unique, since `a` and `b` are both universally
1550 quantified type variables--that is, they are used in both the (:~:) tycon as
1551 well as in the constructor type signature. But when we turn the DataCon
1552 definition into the reified one, the `a` and `b` in the constructor type
1553 signature becomes differently scoped than the `a` and `b` in `data a :~: b`.
1554
1555 While it wouldn't technically be *wrong* per se to re-use the same uniques for
1556 `a` and `b` across these two different scopes, it's somewhat annoying for end
1557 users of Template Haskell, since they wouldn't be able to rely on the
1558 assumption that all TH names have globally distinct uniques (#13885). For this
1559 reason, we freshen the universally quantified tyvars that go into the reified
1560 GADT constructor type signature to give them distinct uniques from their
1561 counterparts in the tycon.
1562 -}
1563
1564 ------------------------------
1565 reifyClass :: Class -> TcM TH.Info
1566 reifyClass cls
1567 = do { cxt <- reifyCxt theta
1568 ; inst_envs <- tcGetInstEnvs
1569 ; insts <- reifyClassInstances cls (InstEnv.classInstances inst_envs cls)
1570 ; assocTys <- concatMapM reifyAT ats
1571 ; ops <- concatMapM reify_op op_stuff
1572 ; tvs' <- reifyTyVars (tyConVisibleTyVars (classTyCon cls))
1573 ; let dec = TH.ClassD cxt (reifyName cls) tvs' fds' (assocTys ++ ops)
1574 ; return (TH.ClassI dec insts) }
1575 where
1576 (_, fds, theta, _, ats, op_stuff) = classExtraBigSig cls
1577 fds' = map reifyFunDep fds
1578 reify_op (op, def_meth)
1579 = do { ty <- reifyType (idType op)
1580 ; let nm' = reifyName op
1581 ; case def_meth of
1582 Just (_, GenericDM gdm_ty) ->
1583 do { gdm_ty' <- reifyType gdm_ty
1584 ; return [TH.SigD nm' ty, TH.DefaultSigD nm' gdm_ty'] }
1585 _ -> return [TH.SigD nm' ty] }
1586
1587 reifyAT :: ClassATItem -> TcM [TH.Dec]
1588 reifyAT (ATI tycon def) = do
1589 tycon' <- reifyTyCon tycon
1590 case tycon' of
1591 TH.FamilyI dec _ -> do
1592 let (tyName, tyArgs) = tfNames dec
1593 (dec :) <$> maybe (return [])
1594 (fmap (:[]) . reifyDefImpl tyName tyArgs . fst)
1595 def
1596 _ -> pprPanic "reifyAT" (text (show tycon'))
1597
1598 reifyDefImpl :: TH.Name -> [TH.Name] -> Type -> TcM TH.Dec
1599 reifyDefImpl n args ty =
1600 TH.TySynInstD n . TH.TySynEqn (map TH.VarT args) <$> reifyType ty
1601
1602 tfNames :: TH.Dec -> (TH.Name, [TH.Name])
1603 tfNames (TH.OpenTypeFamilyD (TH.TypeFamilyHead n args _ _))
1604 = (n, map bndrName args)
1605 tfNames d = pprPanic "tfNames" (text (show d))
1606
1607 bndrName :: TH.TyVarBndr -> TH.Name
1608 bndrName (TH.PlainTV n) = n
1609 bndrName (TH.KindedTV n _) = n
1610
1611 ------------------------------
1612 -- | Annotate (with TH.SigT) a type if the first parameter is True
1613 -- and if the type contains a free variable.
1614 -- This is used to annotate type patterns for poly-kinded tyvars in
1615 -- reifying class and type instances. See #8953 and th/T8953.
1616 annotThType :: Bool -- True <=> annotate
1617 -> TyCoRep.Type -> TH.Type -> TcM TH.Type
1618 -- tiny optimization: if the type is annotated, don't annotate again.
1619 annotThType _ _ th_ty@(TH.SigT {}) = return th_ty
1620 annotThType True ty th_ty
1621 | not $ isEmptyVarSet $ filterVarSet isTyVar $ tyCoVarsOfType ty
1622 = do { let ki = typeKind ty
1623 ; th_ki <- reifyKind ki
1624 ; return (TH.SigT th_ty th_ki) }
1625 annotThType _ _ th_ty = return th_ty
1626
1627 -- | For every type variable in the input,
1628 -- report whether or not the tv is poly-kinded. This is used to eventually
1629 -- feed into 'annotThType'.
1630 mkIsPolyTvs :: [TyVar] -> [Bool]
1631 mkIsPolyTvs = map is_poly_tv
1632 where
1633 is_poly_tv tv = not $
1634 isEmptyVarSet $
1635 filterVarSet isTyVar $
1636 tyCoVarsOfType $
1637 tyVarKind tv
1638
1639 ------------------------------
1640 reifyClassInstances :: Class -> [ClsInst] -> TcM [TH.Dec]
1641 reifyClassInstances cls insts
1642 = mapM (reifyClassInstance (mkIsPolyTvs tvs)) insts
1643 where
1644 tvs = tyConVisibleTyVars (classTyCon cls)
1645
1646 reifyClassInstance :: [Bool] -- True <=> the corresponding tv is poly-kinded
1647 -- includes only *visible* tvs
1648 -> ClsInst -> TcM TH.Dec
1649 reifyClassInstance is_poly_tvs i
1650 = do { cxt <- reifyCxt theta
1651 ; let vis_types = filterOutInvisibleTypes cls_tc types
1652 ; thtypes <- reifyTypes vis_types
1653 ; annot_thtypes <- zipWith3M annotThType is_poly_tvs vis_types thtypes
1654 ; let head_ty = mkThAppTs (TH.ConT (reifyName cls)) annot_thtypes
1655 ; return $ (TH.InstanceD over cxt head_ty []) }
1656 where
1657 (_tvs, theta, cls, types) = tcSplitDFunTy (idType dfun)
1658 cls_tc = classTyCon cls
1659 dfun = instanceDFunId i
1660 over = case overlapMode (is_flag i) of
1661 NoOverlap _ -> Nothing
1662 Overlappable _ -> Just TH.Overlappable
1663 Overlapping _ -> Just TH.Overlapping
1664 Overlaps _ -> Just TH.Overlaps
1665 Incoherent _ -> Just TH.Incoherent
1666
1667 ------------------------------
1668 reifyFamilyInstances :: TyCon -> [FamInst] -> TcM [TH.Dec]
1669 reifyFamilyInstances fam_tc fam_insts
1670 = mapM (reifyFamilyInstance (mkIsPolyTvs fam_tvs)) fam_insts
1671 where
1672 fam_tvs = tyConVisibleTyVars fam_tc
1673
1674 reifyFamilyInstance :: [Bool] -- True <=> the corresponding tv is poly-kinded
1675 -- includes only *visible* tvs
1676 -> FamInst -> TcM TH.Dec
1677 reifyFamilyInstance is_poly_tvs inst@(FamInst { fi_flavor = flavor
1678 , fi_fam = fam
1679 , fi_tvs = fam_tvs
1680 , fi_tys = lhs
1681 , fi_rhs = rhs })
1682 = case flavor of
1683 SynFamilyInst ->
1684 -- remove kind patterns (#8884)
1685 do { let lhs_types_only = filterOutInvisibleTypes fam_tc lhs
1686 ; th_lhs <- reifyTypes lhs_types_only
1687 ; annot_th_lhs <- zipWith3M annotThType is_poly_tvs lhs_types_only
1688 th_lhs
1689 ; th_rhs <- reifyType rhs
1690 ; return (TH.TySynInstD (reifyName fam)
1691 (TH.TySynEqn annot_th_lhs th_rhs)) }
1692
1693 DataFamilyInst rep_tc ->
1694 do { let rep_tvs = tyConTyVars rep_tc
1695 fam' = reifyName fam
1696
1697 -- eta-expand lhs types, because sometimes data/newtype
1698 -- instances are eta-reduced; See Trac #9692
1699 -- See Note [Eta reduction for data family axioms]
1700 -- in TcInstDcls
1701 (_rep_tc, rep_tc_args) = splitTyConApp rhs
1702 etad_tyvars = dropList rep_tc_args rep_tvs
1703 etad_tys = mkTyVarTys etad_tyvars
1704 eta_expanded_tvs = mkTyVarTys fam_tvs `chkAppend` etad_tys
1705 eta_expanded_lhs = lhs `chkAppend` etad_tys
1706 dataCons = tyConDataCons rep_tc
1707 isGadt = isGadtSyntaxTyCon rep_tc
1708 ; cons <- mapM (reifyDataCon isGadt eta_expanded_tvs) dataCons
1709 ; let types_only = filterOutInvisibleTypes fam_tc eta_expanded_lhs
1710 ; th_tys <- reifyTypes types_only
1711 ; annot_th_tys <- zipWith3M annotThType is_poly_tvs types_only th_tys
1712 ; return $
1713 if isNewTyCon rep_tc
1714 then TH.NewtypeInstD [] fam' annot_th_tys Nothing (head cons) []
1715 else TH.DataInstD [] fam' annot_th_tys Nothing cons []
1716 }
1717 where
1718 fam_tc = famInstTyCon inst
1719
1720 ------------------------------
1721 reifyType :: TyCoRep.Type -> TcM TH.Type
1722 -- Monadic only because of failure
1723 reifyType ty | tcIsLiftedTypeKind ty = return TH.StarT
1724 -- Make sure to use tcIsLiftedTypeKind here, since we don't want to confuse it
1725 -- with Constraint (#14869).
1726 reifyType ty@(ForAllTy {}) = reify_for_all ty
1727 reifyType (LitTy t) = do { r <- reifyTyLit t; return (TH.LitT r) }
1728 reifyType (TyVarTy tv) = return (TH.VarT (reifyName tv))
1729 reifyType (TyConApp tc tys) = reify_tc_app tc tys -- Do not expand type synonyms here
1730 reifyType (AppTy t1 t2) = do { [r1,r2] <- reifyTypes [t1,t2] ; return (r1 `TH.AppT` r2) }
1731 reifyType ty@(FunTy t1 t2)
1732 | isPredTy t1 = reify_for_all ty -- Types like ((?x::Int) => Char -> Char)
1733 | otherwise = do { [r1,r2] <- reifyTypes [t1,t2] ; return (TH.ArrowT `TH.AppT` r1 `TH.AppT` r2) }
1734 reifyType (CastTy t _) = reifyType t -- Casts are ignored in TH
1735 reifyType ty@(CoercionTy {})= noTH (sLit "coercions in types") (ppr ty)
1736
1737 reify_for_all :: TyCoRep.Type -> TcM TH.Type
1738 reify_for_all ty
1739 = do { cxt' <- reifyCxt cxt;
1740 ; tau' <- reifyType tau
1741 ; tvs' <- reifyTyVars tvs
1742 ; return (TH.ForallT tvs' cxt' tau') }
1743 where
1744 (tvs, cxt, tau) = tcSplitSigmaTy ty
1745
1746 reifyTyLit :: TyCoRep.TyLit -> TcM TH.TyLit
1747 reifyTyLit (NumTyLit n) = return (TH.NumTyLit n)
1748 reifyTyLit (StrTyLit s) = return (TH.StrTyLit (unpackFS s))
1749
1750 reifyTypes :: [Type] -> TcM [TH.Type]
1751 reifyTypes = mapM reifyType
1752
1753 reifyPatSynType
1754 :: ([TyVar], ThetaType, [TyVar], ThetaType, [Type], Type) -> TcM TH.Type
1755 -- reifies a pattern synonym's type and returns its *complete* type
1756 -- signature; see NOTE [Pattern synonym signatures and Template
1757 -- Haskell]
1758 reifyPatSynType (univTyVars, req, exTyVars, prov, argTys, resTy)
1759 = do { univTyVars' <- reifyTyVars univTyVars
1760 ; req' <- reifyCxt req
1761 ; exTyVars' <- reifyTyVars exTyVars
1762 ; prov' <- reifyCxt prov
1763 ; tau' <- reifyType (mkFunTys argTys resTy)
1764 ; return $ TH.ForallT univTyVars' req'
1765 $ TH.ForallT exTyVars' prov' tau' }
1766
1767 reifyKind :: Kind -> TcM TH.Kind
1768 reifyKind = reifyType
1769
1770 reifyCxt :: [PredType] -> TcM [TH.Pred]
1771 reifyCxt = mapM reifyPred
1772
1773 reifyFunDep :: ([TyVar], [TyVar]) -> TH.FunDep
1774 reifyFunDep (xs, ys) = TH.FunDep (map reifyName xs) (map reifyName ys)
1775
1776 reifyTyVars :: [TyVar] -> TcM [TH.TyVarBndr]
1777 reifyTyVars tvs = mapM reify_tv tvs
1778 where
1779 -- even if the kind is *, we need to include a kind annotation,
1780 -- in case a poly-kind would be inferred without the annotation.
1781 -- See #8953 or test th/T8953
1782 reify_tv tv = TH.KindedTV name <$> reifyKind kind
1783 where
1784 kind = tyVarKind tv
1785 name = reifyName tv
1786
1787 {-
1788 Note [Kind annotations on TyConApps]
1789 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1790 A poly-kinded tycon sometimes needs a kind annotation to be unambiguous.
1791 For example:
1792
1793 type family F a :: k
1794 type instance F Int = (Proxy :: * -> *)
1795 type instance F Bool = (Proxy :: (* -> *) -> *)
1796
1797 It's hard to figure out where these annotations should appear, so we do this:
1798 Suppose we have a tycon application (T ty1 ... tyn). Assuming that T is not
1799 oversatured (more on this later), we can assume T's declaration is of the form
1800 T (tvb1 :: s1) ... (tvbn :: sn) :: p. If any kind variable that
1801 is free in p is not free in an injective position in tvb1 ... tvbn,
1802 then we put on a kind annotation, since we would not otherwise be able to infer
1803 the kind of the whole tycon application.
1804
1805 The injective positions in a tyvar binder are the injective positions in the
1806 kind of its tyvar, provided the tyvar binder is either:
1807
1808 * Anonymous. For example, in the promoted data constructor '(:):
1809
1810 '(:) :: forall a. a -> [a] -> [a]
1811
1812 The second and third tyvar binders (of kinds `a` and `[a]`) are both
1813 anonymous, so if we had '(:) 'True '[], then the inferred kinds of 'True and
1814 '[] would contribute to the inferred kind of '(:) 'True '[].
1815 * Has required visibility. For example, in the type family:
1816
1817 type family Wurble k (a :: k) :: k
1818 Wurble :: forall k -> k -> k
1819
1820 The first tyvar binder (of kind `forall k`) has required visibility, so if
1821 we had Wurble (Maybe a) Nothing, then the inferred kind of Maybe a would
1822 contribute to the inferred kind of Wurble (Maybe a) Nothing.
1823
1824 An injective position in a type is one that does not occur as an argument to
1825 a non-injective type constructor (e.g., non-injective type families). See
1826 injectiveVarsOfType.
1827
1828 How can be sure that this is correct? That is, how can we be sure that in the
1829 event that we leave off a kind annotation, that one could infer the kind of the
1830 tycon application from its arguments? It's essentially a proof by induction: if
1831 we can infer the kinds of every subtree of a type, then the whole tycon
1832 application will have an inferrable kind--unless, of course, the remainder of
1833 the tycon application's kind has uninstantiated kind variables.
1834
1835 An earlier implementation of this algorithm only checked if p contained any
1836 free variables. But this was unsatisfactory, since a datatype like this:
1837
1838 data Foo = Foo (Proxy '[False, True])
1839
1840 Would be reified like this:
1841
1842 data Foo = Foo (Proxy ('(:) False ('(:) True ('[] :: [Bool])
1843 :: [Bool]) :: [Bool]))
1844
1845 Which has a rather excessive amount of kind annotations. With the current
1846 algorithm, we instead reify Foo to this:
1847
1848 data Foo = Foo (Proxy ('(:) False ('(:) True ('[] :: [Bool]))))
1849
1850 Since in the case of '[], the kind p is [a], and there are no arguments in the
1851 kind of '[]. On the other hand, in the case of '(:) True '[], the kind p is
1852 (forall a. [a]), but a occurs free in the first and second arguments of the
1853 full kind of '(:), which is (forall a. a -> [a] -> [a]). (See Trac #14060.)
1854
1855 What happens if T is oversaturated? That is, if T's kind has fewer than n
1856 arguments, in the case that the concrete application instantiates a result
1857 kind variable with an arrow kind? If we run out of arguments, we do not attach
1858 a kind annotation. This should be a rare case, indeed. Here is an example:
1859
1860 data T1 :: k1 -> k2 -> *
1861 data T2 :: k1 -> k2 -> *
1862
1863 type family G (a :: k) :: k
1864 type instance G T1 = T2
1865
1866 type instance F Char = (G T1 Bool :: (* -> *) -> *) -- F from above
1867
1868 Here G's kind is (forall k. k -> k), and the desugared RHS of that last
1869 instance of F is (G (* -> (* -> *) -> *) (T1 * (* -> *)) Bool). According to
1870 the algorithm above, there are 3 arguments to G so we should peel off 3
1871 arguments in G's kind. But G's kind has only two arguments. This is the
1872 rare special case, and we choose not to annotate the application of G with
1873 a kind signature. After all, we needn't do this, since that instance would
1874 be reified as:
1875
1876 type instance F Char = G (T1 :: * -> (* -> *) -> *) Bool
1877
1878 So the kind of G isn't ambiguous anymore due to the explicit kind annotation
1879 on its argument. See #8953 and test th/T8953.
1880 -}
1881
1882 reify_tc_app :: TyCon -> [Type.Type] -> TcM TH.Type
1883 reify_tc_app tc tys
1884 = do { tys' <- reifyTypes (filterOutInvisibleTypes tc tys)
1885 ; maybe_sig_t (mkThAppTs r_tc tys') }
1886 where
1887 arity = tyConArity tc
1888 tc_binders = tyConBinders tc
1889 tc_res_kind = tyConResKind tc
1890
1891 r_tc | isUnboxedSumTyCon tc = TH.UnboxedSumT (arity `div` 2)
1892 | isUnboxedTupleTyCon tc = TH.UnboxedTupleT (arity `div` 2)
1893 | isPromotedTupleTyCon tc = TH.PromotedTupleT (arity `div` 2)
1894 -- See Note [Unboxed tuple RuntimeRep vars] in TyCon
1895 | isTupleTyCon tc = if isPromotedDataCon tc
1896 then TH.PromotedTupleT arity
1897 else TH.TupleT arity
1898 | tc `hasKey` constraintKindTyConKey
1899 = TH.ConstraintT
1900 | tc `hasKey` funTyConKey = TH.ArrowT
1901 | tc `hasKey` listTyConKey = TH.ListT
1902 | tc `hasKey` nilDataConKey = TH.PromotedNilT
1903 | tc `hasKey` consDataConKey = TH.PromotedConsT
1904 | tc `hasKey` heqTyConKey = TH.EqualityT
1905 | tc `hasKey` eqPrimTyConKey = TH.EqualityT
1906 | tc `hasKey` eqReprPrimTyConKey = TH.ConT (reifyName coercibleTyCon)
1907 | isPromotedDataCon tc = TH.PromotedT (reifyName tc)
1908 | otherwise = TH.ConT (reifyName tc)
1909
1910 -- See Note [Kind annotations on TyConApps]
1911 maybe_sig_t th_type
1912 | needs_kind_sig
1913 = do { let full_kind = typeKind (mkTyConApp tc tys)
1914 ; th_full_kind <- reifyKind full_kind
1915 ; return (TH.SigT th_type th_full_kind) }
1916 | otherwise
1917 = return th_type
1918
1919 needs_kind_sig
1920 | GT <- compareLength tys tc_binders
1921 = False
1922 | otherwise
1923 = let (dropped_binders, remaining_binders)
1924 = splitAtList tys tc_binders
1925 result_kind = mkTyConKind remaining_binders tc_res_kind
1926 result_vars = tyCoVarsOfType result_kind
1927 dropped_vars = fvVarSet $
1928 mapUnionFV injectiveVarsOfBinder dropped_binders
1929
1930 in not (subVarSet result_vars dropped_vars)
1931
1932 reifyPred :: TyCoRep.PredType -> TcM TH.Pred
1933 reifyPred ty
1934 -- We could reify the invisible parameter as a class but it seems
1935 -- nicer to support them properly...
1936 | isIPPred ty = noTH (sLit "implicit parameters") (ppr ty)
1937 | otherwise = reifyType ty
1938
1939 ------------------------------
1940 reifyName :: NamedThing n => n -> TH.Name
1941 reifyName thing
1942 | isExternalName name = mk_varg pkg_str mod_str occ_str
1943 | otherwise = TH.mkNameU occ_str (getKey (getUnique name))
1944 -- Many of the things we reify have local bindings, and
1945 -- NameL's aren't supposed to appear in binding positions, so
1946 -- we use NameU. When/if we start to reify nested things, that
1947 -- have free variables, we may need to generate NameL's for them.
1948 where
1949 name = getName thing
1950 mod = ASSERT( isExternalName name ) nameModule name
1951 pkg_str = unitIdString (moduleUnitId mod)
1952 mod_str = moduleNameString (moduleName mod)
1953 occ_str = occNameString occ
1954 occ = nameOccName name
1955 mk_varg | OccName.isDataOcc occ = TH.mkNameG_d
1956 | OccName.isVarOcc occ = TH.mkNameG_v
1957 | OccName.isTcOcc occ = TH.mkNameG_tc
1958 | otherwise = pprPanic "reifyName" (ppr name)
1959
1960 -- See Note [Reifying field labels]
1961 reifyFieldLabel :: FieldLabel -> TH.Name
1962 reifyFieldLabel fl
1963 | flIsOverloaded fl
1964 = TH.Name (TH.mkOccName occ_str) (TH.NameQ (TH.mkModName mod_str))
1965 | otherwise = TH.mkNameG_v pkg_str mod_str occ_str
1966 where
1967 name = flSelector fl
1968 mod = ASSERT( isExternalName name ) nameModule name
1969 pkg_str = unitIdString (moduleUnitId mod)
1970 mod_str = moduleNameString (moduleName mod)
1971 occ_str = unpackFS (flLabel fl)
1972
1973 reifySelector :: Id -> TyCon -> TH.Name
1974 reifySelector id tc
1975 = case find ((idName id ==) . flSelector) (tyConFieldLabels tc) of
1976 Just fl -> reifyFieldLabel fl
1977 Nothing -> pprPanic "reifySelector: missing field" (ppr id $$ ppr tc)
1978
1979 ------------------------------
1980 reifyFixity :: Name -> TcM (Maybe TH.Fixity)
1981 reifyFixity name
1982 = do { (found, fix) <- lookupFixityRn_help name
1983 ; return (if found then Just (conv_fix fix) else Nothing) }
1984 where
1985 conv_fix (BasicTypes.Fixity _ i d) = TH.Fixity i (conv_dir d)
1986 conv_dir BasicTypes.InfixR = TH.InfixR
1987 conv_dir BasicTypes.InfixL = TH.InfixL
1988 conv_dir BasicTypes.InfixN = TH.InfixN
1989
1990 reifyUnpackedness :: DataCon.SrcUnpackedness -> TH.SourceUnpackedness
1991 reifyUnpackedness NoSrcUnpack = TH.NoSourceUnpackedness
1992 reifyUnpackedness SrcNoUnpack = TH.SourceNoUnpack
1993 reifyUnpackedness SrcUnpack = TH.SourceUnpack
1994
1995 reifyStrictness :: DataCon.SrcStrictness -> TH.SourceStrictness
1996 reifyStrictness NoSrcStrict = TH.NoSourceStrictness
1997 reifyStrictness SrcStrict = TH.SourceStrict
1998 reifyStrictness SrcLazy = TH.SourceLazy
1999
2000 reifySourceBang :: DataCon.HsSrcBang
2001 -> (TH.SourceUnpackedness, TH.SourceStrictness)
2002 reifySourceBang (HsSrcBang _ u s) = (reifyUnpackedness u, reifyStrictness s)
2003
2004 reifyDecidedStrictness :: DataCon.HsImplBang -> TH.DecidedStrictness
2005 reifyDecidedStrictness HsLazy = TH.DecidedLazy
2006 reifyDecidedStrictness HsStrict = TH.DecidedStrict
2007 reifyDecidedStrictness HsUnpack{} = TH.DecidedUnpack
2008
2009 ------------------------------
2010 lookupThAnnLookup :: TH.AnnLookup -> TcM CoreAnnTarget
2011 lookupThAnnLookup (TH.AnnLookupName th_nm) = fmap NamedTarget (lookupThName th_nm)
2012 lookupThAnnLookup (TH.AnnLookupModule (TH.Module pn mn))
2013 = return $ ModuleTarget $
2014 mkModule (stringToUnitId $ TH.pkgString pn) (mkModuleName $ TH.modString mn)
2015
2016 reifyAnnotations :: Data a => TH.AnnLookup -> TcM [a]
2017 reifyAnnotations th_name
2018 = do { name <- lookupThAnnLookup th_name
2019 ; topEnv <- getTopEnv
2020 ; epsHptAnns <- liftIO $ prepareAnnotations topEnv Nothing
2021 ; tcg <- getGblEnv
2022 ; let selectedEpsHptAnns = findAnns deserializeWithData epsHptAnns name
2023 ; let selectedTcgAnns = findAnns deserializeWithData (tcg_ann_env tcg) name
2024 ; return (selectedEpsHptAnns ++ selectedTcgAnns) }
2025
2026 ------------------------------
2027 modToTHMod :: Module -> TH.Module
2028 modToTHMod m = TH.Module (TH.PkgName $ unitIdString $ moduleUnitId m)
2029 (TH.ModName $ moduleNameString $ moduleName m)
2030
2031 reifyModule :: TH.Module -> TcM TH.ModuleInfo
2032 reifyModule (TH.Module (TH.PkgName pkgString) (TH.ModName mString)) = do
2033 this_mod <- getModule
2034 let reifMod = mkModule (stringToUnitId pkgString) (mkModuleName mString)
2035 if (reifMod == this_mod) then reifyThisModule else reifyFromIface reifMod
2036 where
2037 reifyThisModule = do
2038 usages <- fmap (map modToTHMod . moduleEnvKeys . imp_mods) getImports
2039 return $ TH.ModuleInfo usages
2040
2041 reifyFromIface reifMod = do
2042 iface <- loadInterfaceForModule (text "reifying module from TH for" <+> ppr reifMod) reifMod
2043 let usages = [modToTHMod m | usage <- mi_usages iface,
2044 Just m <- [usageToModule (moduleUnitId reifMod) usage] ]
2045 return $ TH.ModuleInfo usages
2046
2047 usageToModule :: UnitId -> Usage -> Maybe Module
2048 usageToModule _ (UsageFile {}) = Nothing
2049 usageToModule this_pkg (UsageHomeModule { usg_mod_name = mn }) = Just $ mkModule this_pkg mn
2050 usageToModule _ (UsagePackageModule { usg_mod = m }) = Just m
2051 usageToModule _ (UsageMergedRequirement { usg_mod = m }) = Just m
2052
2053 ------------------------------
2054 mkThAppTs :: TH.Type -> [TH.Type] -> TH.Type
2055 mkThAppTs fun_ty arg_tys = foldl TH.AppT fun_ty arg_tys
2056
2057 noTH :: LitString -> SDoc -> TcM a
2058 noTH s d = failWithTc (hsep [text "Can't represent" <+> ptext s <+>
2059 text "in Template Haskell:",
2060 nest 2 d])
2061
2062 ppr_th :: TH.Ppr a => a -> SDoc
2063 ppr_th x = text (TH.pprint x)
2064
2065 {-
2066 Note [Reifying field labels]
2067 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2068 When reifying a datatype declared with DuplicateRecordFields enabled, we want
2069 the reified names of the fields to be labels rather than selector functions.
2070 That is, we want (reify ''T) and (reify 'foo) to produce
2071
2072 data T = MkT { foo :: Int }
2073 foo :: T -> Int
2074
2075 rather than
2076
2077 data T = MkT { $sel:foo:MkT :: Int }
2078 $sel:foo:MkT :: T -> Int
2079
2080 because otherwise TH code that uses the field names as strings will silently do
2081 the wrong thing. Thus we use the field label (e.g. foo) as the OccName, rather
2082 than the selector (e.g. $sel:foo:MkT). Since the Orig name M.foo isn't in the
2083 environment, NameG can't be used to represent such fields. Instead,
2084 reifyFieldLabel uses NameQ.
2085
2086 However, this means that extracting the field name from the output of reify, and
2087 trying to reify it again, may fail with an ambiguity error if there are multiple
2088 such fields defined in the module (see the test case
2089 overloadedrecflds/should_fail/T11103.hs). The "proper" fix requires changes to
2090 the TH AST to make it able to represent duplicate record fields.
2091 -}