Fix for recover with -fexternal-interpreter (#15418)
[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 NameSet
73 import TcMType
74 import TcHsType
75 import TcIface
76 import TyCoRep
77 import FamInst
78 import FamInstEnv
79 import InstEnv
80 import Inst
81 import NameEnv
82 import PrelNames
83 import TysWiredIn
84 import OccName
85 import Hooks
86 import Var
87 import Module
88 import LoadIface
89 import Class
90 import TyCon
91 import CoAxiom
92 import PatSyn
93 import ConLike
94 import DataCon
95 import TcEvidence( TcEvBinds(..) )
96 import Id
97 import IdInfo
98 import DsExpr
99 import DsMonad
100 import GHC.Serialized
101 import ErrUtils
102 import Util
103 import Unique
104 import VarSet
105 import Data.List ( find )
106 import Data.Maybe
107 import FastString
108 import BasicTypes hiding( SuccessFlag(..) )
109 import Maybes( MaybeErr(..) )
110 import DynFlags
111 import Panic
112 import Lexeme
113 import qualified EnumSet
114 import Plugins
115 import Bag
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 let (prev_msgs@(prev_warns,prev_errs), rest) = case recovers of
1044 [] -> panic "EndRecover"
1045 a : b -> (a,b)
1046 v <- getErrsVar
1047 (warn_msgs,_) <- readTcRef v
1048 -- keep the warnings only if there were no errors
1049 writeTcRef v $ if caught_error
1050 then prev_msgs
1051 else (prev_warns `unionBags` warn_msgs, prev_errs)
1052 runRemoteTH iserv rest
1053 _other -> do
1054 r <- handleTHMessage msg
1055 liftIO $ writeIServ iserv (put r)
1056 runRemoteTH iserv recovers
1057
1058 -- | Read a value of type QResult from the iserv
1059 readQResult :: Binary a => IServ -> TcM a
1060 readQResult i = do
1061 qr <- liftIO $ readIServ i get
1062 case qr of
1063 QDone a -> return a
1064 QException str -> liftIO $ throwIO (ErrorCall str)
1065 QFail str -> fail str
1066
1067 {- Note [TH recover with -fexternal-interpreter]
1068
1069 Recover is slightly tricky to implement.
1070
1071 The meaning of "recover a b" is
1072 - Do a
1073 - If it finished with no errors, then keep the warnings it generated
1074 - If it failed, discard any messages it generated, and do b
1075
1076 Note that "failed" here can mean either
1077 (1) threw an exception (failTc)
1078 (2) generated an error message (addErrTcM)
1079
1080 The messages are managed by GHC in the TcM monad, whereas the
1081 exception-handling is done in the ghc-iserv process, so we have to
1082 coordinate between the two.
1083
1084 On the server:
1085 - emit a StartRecover message
1086 - run "a; FailIfErrs" inside a try
1087 - emit an (EndRecover x) message, where x = True if "a; FailIfErrs" failed
1088 - if "a; FailIfErrs" failed, run "b"
1089
1090 Back in GHC, when we receive:
1091
1092 FailIfErrrs
1093 failTc if there are any error messages (= failIfErrsM)
1094 StartRecover
1095 save the current messages and start with an empty set.
1096 EndRecover caught_error
1097 Restore the previous messages,
1098 and merge in the new messages if caught_error is false.
1099 -}
1100
1101 -- | Retrieve (or create, if it hasn't been created already), the
1102 -- remote TH state. The TH state is a remote reference to an IORef
1103 -- QState living on the server, and we have to pass this to each RunTH
1104 -- call we make.
1105 --
1106 -- The TH state is stored in tcg_th_remote_state in the TcGblEnv.
1107 --
1108 getTHState :: IServ -> TcM (ForeignRef (IORef QState))
1109 getTHState i = do
1110 tcg <- getGblEnv
1111 th_state <- readTcRef (tcg_th_remote_state tcg)
1112 case th_state of
1113 Just rhv -> return rhv
1114 Nothing -> do
1115 hsc_env <- env_top <$> getEnv
1116 fhv <- liftIO $ mkFinalizedHValue hsc_env =<< iservCall i StartTH
1117 writeTcRef (tcg_th_remote_state tcg) (Just fhv)
1118 return fhv
1119
1120 wrapTHResult :: TcM a -> TcM (THResult a)
1121 wrapTHResult tcm = do
1122 e <- tryM tcm -- only catch 'fail', treat everything else as catastrophic
1123 case e of
1124 Left e -> return (THException (show e))
1125 Right a -> return (THComplete a)
1126
1127 handleTHMessage :: THMessage a -> TcM a
1128 handleTHMessage msg = case msg of
1129 NewName a -> wrapTHResult $ TH.qNewName a
1130 Report b str -> wrapTHResult $ TH.qReport b str
1131 LookupName b str -> wrapTHResult $ TH.qLookupName b str
1132 Reify n -> wrapTHResult $ TH.qReify n
1133 ReifyFixity n -> wrapTHResult $ TH.qReifyFixity n
1134 ReifyInstances n ts -> wrapTHResult $ TH.qReifyInstances n ts
1135 ReifyRoles n -> wrapTHResult $ TH.qReifyRoles n
1136 ReifyAnnotations lookup tyrep ->
1137 wrapTHResult $ (map B.pack <$> getAnnotationsByTypeRep lookup tyrep)
1138 ReifyModule m -> wrapTHResult $ TH.qReifyModule m
1139 ReifyConStrictness nm -> wrapTHResult $ TH.qReifyConStrictness nm
1140 AddDependentFile f -> wrapTHResult $ TH.qAddDependentFile f
1141 AddTempFile s -> wrapTHResult $ TH.qAddTempFile s
1142 AddModFinalizer r -> do
1143 hsc_env <- env_top <$> getEnv
1144 wrapTHResult $ liftIO (mkFinalizedHValue hsc_env r) >>= addModFinalizerRef
1145 AddCorePlugin str -> wrapTHResult $ TH.qAddCorePlugin str
1146 AddTopDecls decs -> wrapTHResult $ TH.qAddTopDecls decs
1147 AddForeignFilePath lang str -> wrapTHResult $ TH.qAddForeignFilePath lang str
1148 IsExtEnabled ext -> wrapTHResult $ TH.qIsExtEnabled ext
1149 ExtsEnabled -> wrapTHResult $ TH.qExtsEnabled
1150 FailIfErrs -> wrapTHResult failIfErrsM
1151 _ -> panic ("handleTHMessage: unexpected message " ++ show msg)
1152
1153 getAnnotationsByTypeRep :: TH.AnnLookup -> TypeRep -> TcM [[Word8]]
1154 getAnnotationsByTypeRep th_name tyrep
1155 = do { name <- lookupThAnnLookup th_name
1156 ; topEnv <- getTopEnv
1157 ; epsHptAnns <- liftIO $ prepareAnnotations topEnv Nothing
1158 ; tcg <- getGblEnv
1159 ; let selectedEpsHptAnns = findAnnsByTypeRep epsHptAnns name tyrep
1160 ; let selectedTcgAnns = findAnnsByTypeRep (tcg_ann_env tcg) name tyrep
1161 ; return (selectedEpsHptAnns ++ selectedTcgAnns) }
1162
1163 {-
1164 ************************************************************************
1165 * *
1166 Instance Testing
1167 * *
1168 ************************************************************************
1169 -}
1170
1171 reifyInstances :: TH.Name -> [TH.Type] -> TcM [TH.Dec]
1172 reifyInstances th_nm th_tys
1173 = addErrCtxt (text "In the argument of reifyInstances:"
1174 <+> ppr_th th_nm <+> sep (map ppr_th th_tys)) $
1175 do { loc <- getSrcSpanM
1176 ; rdr_ty <- cvt loc (mkThAppTs (TH.ConT th_nm) th_tys)
1177 -- #9262 says to bring vars into scope, like in HsForAllTy case
1178 -- of rnHsTyKi
1179 ; free_vars <- extractHsTyRdrTyVars rdr_ty
1180 ; let tv_rdrs = freeKiTyVarsAllVars free_vars
1181 -- Rename to HsType Name
1182 ; ((tv_names, rn_ty), _fvs)
1183 <- checkNoErrs $ -- If there are out-of-scope Names here, then we
1184 -- must error before proceeding to typecheck the
1185 -- renamed type, as that will result in GHC
1186 -- internal errors (#13837).
1187 bindLRdrNames tv_rdrs $ \ tv_names ->
1188 do { (rn_ty, fvs) <- rnLHsType doc rdr_ty
1189 ; return ((tv_names, rn_ty), fvs) }
1190 ; (_tvs, ty)
1191 <- solveEqualities $
1192 tcImplicitTKBndrs ReifySkol tv_names $
1193 fst <$> tcLHsType rn_ty
1194 ; ty <- zonkTcTypeToType emptyZonkEnv ty
1195 -- Substitute out the meta type variables
1196 -- In particular, the type might have kind
1197 -- variables inside it (Trac #7477)
1198
1199 ; traceTc "reifyInstances" (ppr ty $$ ppr (typeKind ty))
1200 ; case splitTyConApp_maybe ty of -- This expands any type synonyms
1201 Just (tc, tys) -- See Trac #7910
1202 | Just cls <- tyConClass_maybe tc
1203 -> do { inst_envs <- tcGetInstEnvs
1204 ; let (matches, unifies, _) = lookupInstEnv False inst_envs cls tys
1205 ; traceTc "reifyInstances1" (ppr matches)
1206 ; reifyClassInstances cls (map fst matches ++ unifies) }
1207 | isOpenFamilyTyCon tc
1208 -> do { inst_envs <- tcGetFamInstEnvs
1209 ; let matches = lookupFamInstEnv inst_envs tc tys
1210 ; traceTc "reifyInstances2" (ppr matches)
1211 ; reifyFamilyInstances tc (map fim_instance matches) }
1212 _ -> bale_out (hang (text "reifyInstances:" <+> quotes (ppr ty))
1213 2 (text "is not a class constraint or type family application")) }
1214 where
1215 doc = ClassInstanceCtx
1216 bale_out msg = failWithTc msg
1217
1218 cvt :: SrcSpan -> TH.Type -> TcM (LHsType GhcPs)
1219 cvt loc th_ty = case convertToHsType loc th_ty of
1220 Left msg -> failWithTc msg
1221 Right ty -> return ty
1222
1223 {-
1224 ************************************************************************
1225 * *
1226 Reification
1227 * *
1228 ************************************************************************
1229 -}
1230
1231 lookupName :: Bool -- True <=> type namespace
1232 -- False <=> value namespace
1233 -> String -> TcM (Maybe TH.Name)
1234 lookupName is_type_name s
1235 = do { lcl_env <- getLocalRdrEnv
1236 ; case lookupLocalRdrEnv lcl_env rdr_name of
1237 Just n -> return (Just (reifyName n))
1238 Nothing -> do { mb_nm <- lookupGlobalOccRn_maybe rdr_name
1239 ; return (fmap reifyName mb_nm) } }
1240 where
1241 th_name = TH.mkName s -- Parses M.x into a base of 'x' and a module of 'M'
1242
1243 occ_fs :: FastString
1244 occ_fs = mkFastString (TH.nameBase th_name)
1245
1246 occ :: OccName
1247 occ | is_type_name
1248 = if isLexVarSym occ_fs || isLexCon occ_fs
1249 then mkTcOccFS occ_fs
1250 else mkTyVarOccFS occ_fs
1251 | otherwise
1252 = if isLexCon occ_fs then mkDataOccFS occ_fs
1253 else mkVarOccFS occ_fs
1254
1255 rdr_name = case TH.nameModule th_name of
1256 Nothing -> mkRdrUnqual occ
1257 Just mod -> mkRdrQual (mkModuleName mod) occ
1258
1259 getThing :: TH.Name -> TcM TcTyThing
1260 getThing th_name
1261 = do { name <- lookupThName th_name
1262 ; traceIf (text "reify" <+> text (show th_name) <+> brackets (ppr_ns th_name) <+> ppr name)
1263 ; tcLookupTh name }
1264 -- ToDo: this tcLookup could fail, which would give a
1265 -- rather unhelpful error message
1266 where
1267 ppr_ns (TH.Name _ (TH.NameG TH.DataName _pkg _mod)) = text "data"
1268 ppr_ns (TH.Name _ (TH.NameG TH.TcClsName _pkg _mod)) = text "tc"
1269 ppr_ns (TH.Name _ (TH.NameG TH.VarName _pkg _mod)) = text "var"
1270 ppr_ns _ = panic "reify/ppr_ns"
1271
1272 reify :: TH.Name -> TcM TH.Info
1273 reify th_name
1274 = do { traceTc "reify 1" (text (TH.showName th_name))
1275 ; thing <- getThing th_name
1276 ; traceTc "reify 2" (ppr thing)
1277 ; reifyThing thing }
1278
1279 lookupThName :: TH.Name -> TcM Name
1280 lookupThName th_name = do
1281 mb_name <- lookupThName_maybe th_name
1282 case mb_name of
1283 Nothing -> failWithTc (notInScope th_name)
1284 Just name -> return name
1285
1286 lookupThName_maybe :: TH.Name -> TcM (Maybe Name)
1287 lookupThName_maybe th_name
1288 = do { names <- mapMaybeM lookup (thRdrNameGuesses th_name)
1289 -- Pick the first that works
1290 -- E.g. reify (mkName "A") will pick the class A in preference to the data constructor A
1291 ; return (listToMaybe names) }
1292 where
1293 lookup rdr_name
1294 = do { -- Repeat much of lookupOccRn, because we want
1295 -- to report errors in a TH-relevant way
1296 ; rdr_env <- getLocalRdrEnv
1297 ; case lookupLocalRdrEnv rdr_env rdr_name of
1298 Just name -> return (Just name)
1299 Nothing -> lookupGlobalOccRn_maybe rdr_name }
1300
1301 tcLookupTh :: Name -> TcM TcTyThing
1302 -- This is a specialised version of TcEnv.tcLookup; specialised mainly in that
1303 -- it gives a reify-related error message on failure, whereas in the normal
1304 -- tcLookup, failure is a bug.
1305 tcLookupTh name
1306 = do { (gbl_env, lcl_env) <- getEnvs
1307 ; case lookupNameEnv (tcl_env lcl_env) name of {
1308 Just thing -> return thing;
1309 Nothing ->
1310
1311 case lookupNameEnv (tcg_type_env gbl_env) name of {
1312 Just thing -> return (AGlobal thing);
1313 Nothing ->
1314
1315 -- EZY: I don't think this choice matters, no TH in signatures!
1316 if nameIsLocalOrFrom (tcg_semantic_mod gbl_env) name
1317 then -- It's defined in this module
1318 failWithTc (notInEnv name)
1319
1320 else
1321 do { mb_thing <- tcLookupImported_maybe name
1322 ; case mb_thing of
1323 Succeeded thing -> return (AGlobal thing)
1324 Failed msg -> failWithTc msg
1325 }}}}
1326
1327 notInScope :: TH.Name -> SDoc
1328 notInScope th_name = quotes (text (TH.pprint th_name)) <+>
1329 text "is not in scope at a reify"
1330 -- Ugh! Rather an indirect way to display the name
1331
1332 notInEnv :: Name -> SDoc
1333 notInEnv name = quotes (ppr name) <+>
1334 text "is not in the type environment at a reify"
1335
1336 ------------------------------
1337 reifyRoles :: TH.Name -> TcM [TH.Role]
1338 reifyRoles th_name
1339 = do { thing <- getThing th_name
1340 ; case thing of
1341 AGlobal (ATyCon tc) -> return (map reify_role (tyConRoles tc))
1342 _ -> failWithTc (text "No roles associated with" <+> (ppr thing))
1343 }
1344 where
1345 reify_role Nominal = TH.NominalR
1346 reify_role Representational = TH.RepresentationalR
1347 reify_role Phantom = TH.PhantomR
1348
1349 ------------------------------
1350 reifyThing :: TcTyThing -> TcM TH.Info
1351 -- The only reason this is monadic is for error reporting,
1352 -- which in turn is mainly for the case when TH can't express
1353 -- some random GHC extension
1354
1355 reifyThing (AGlobal (AnId id))
1356 = do { ty <- reifyType (idType id)
1357 ; let v = reifyName id
1358 ; case idDetails id of
1359 ClassOpId cls -> return (TH.ClassOpI v ty (reifyName cls))
1360 RecSelId{sel_tycon=RecSelData tc}
1361 -> return (TH.VarI (reifySelector id tc) ty Nothing)
1362 _ -> return (TH.VarI v ty Nothing)
1363 }
1364
1365 reifyThing (AGlobal (ATyCon tc)) = reifyTyCon tc
1366 reifyThing (AGlobal (AConLike (RealDataCon dc)))
1367 = do { let name = dataConName dc
1368 ; ty <- reifyType (idType (dataConWrapId dc))
1369 ; return (TH.DataConI (reifyName name) ty
1370 (reifyName (dataConOrigTyCon dc)))
1371 }
1372
1373 reifyThing (AGlobal (AConLike (PatSynCon ps)))
1374 = do { let name = reifyName ps
1375 ; ty <- reifyPatSynType (patSynSig ps)
1376 ; return (TH.PatSynI name ty) }
1377
1378 reifyThing (ATcId {tct_id = id})
1379 = do { ty1 <- zonkTcType (idType id) -- Make use of all the info we have, even
1380 -- though it may be incomplete
1381 ; ty2 <- reifyType ty1
1382 ; return (TH.VarI (reifyName id) ty2 Nothing) }
1383
1384 reifyThing (ATyVar tv tv1)
1385 = do { ty1 <- zonkTcTyVar tv1
1386 ; ty2 <- reifyType ty1
1387 ; return (TH.TyVarI (reifyName tv) ty2) }
1388
1389 reifyThing thing = pprPanic "reifyThing" (pprTcTyThingCategory thing)
1390
1391 -------------------------------------------
1392 reifyAxBranch :: TyCon -> CoAxBranch -> TcM TH.TySynEqn
1393 reifyAxBranch fam_tc (CoAxBranch { cab_lhs = lhs, cab_rhs = rhs })
1394 -- remove kind patterns (#8884)
1395 = do { let lhs_types_only = filterOutInvisibleTypes fam_tc lhs
1396 ; lhs' <- reifyTypes lhs_types_only
1397 ; annot_th_lhs <- zipWith3M annotThType (mkIsPolyTvs fam_tvs)
1398 lhs_types_only lhs'
1399 ; rhs' <- reifyType rhs
1400 ; return (TH.TySynEqn annot_th_lhs rhs') }
1401 where
1402 fam_tvs = tyConVisibleTyVars fam_tc
1403
1404 reifyTyCon :: TyCon -> TcM TH.Info
1405 reifyTyCon tc
1406 | Just cls <- tyConClass_maybe tc
1407 = reifyClass cls
1408
1409 | isFunTyCon tc
1410 = return (TH.PrimTyConI (reifyName tc) 2 False)
1411
1412 | isPrimTyCon tc
1413 = return (TH.PrimTyConI (reifyName tc) (tyConArity tc) (isUnliftedTyCon tc))
1414
1415 | isTypeFamilyTyCon tc
1416 = do { let tvs = tyConTyVars tc
1417 res_kind = tyConResKind tc
1418 resVar = famTcResVar tc
1419
1420 ; kind' <- reifyKind res_kind
1421 ; let (resultSig, injectivity) =
1422 case resVar of
1423 Nothing -> (TH.KindSig kind', Nothing)
1424 Just name ->
1425 let thName = reifyName name
1426 injAnnot = tyConInjectivityInfo tc
1427 sig = TH.TyVarSig (TH.KindedTV thName kind')
1428 inj = case injAnnot of
1429 NotInjective -> Nothing
1430 Injective ms ->
1431 Just (TH.InjectivityAnn thName injRHS)
1432 where
1433 injRHS = map (reifyName . tyVarName)
1434 (filterByList ms tvs)
1435 in (sig, inj)
1436 ; tvs' <- reifyTyVars (tyConVisibleTyVars tc)
1437 ; let tfHead =
1438 TH.TypeFamilyHead (reifyName tc) tvs' resultSig injectivity
1439 ; if isOpenTypeFamilyTyCon tc
1440 then do { fam_envs <- tcGetFamInstEnvs
1441 ; instances <- reifyFamilyInstances tc
1442 (familyInstances fam_envs tc)
1443 ; return (TH.FamilyI (TH.OpenTypeFamilyD tfHead) instances) }
1444 else do { eqns <-
1445 case isClosedSynFamilyTyConWithAxiom_maybe tc of
1446 Just ax -> mapM (reifyAxBranch tc) $
1447 fromBranches $ coAxiomBranches ax
1448 Nothing -> return []
1449 ; return (TH.FamilyI (TH.ClosedTypeFamilyD tfHead eqns)
1450 []) } }
1451
1452 | isDataFamilyTyCon tc
1453 = do { let res_kind = tyConResKind tc
1454
1455 ; kind' <- fmap Just (reifyKind res_kind)
1456
1457 ; tvs' <- reifyTyVars (tyConVisibleTyVars tc)
1458 ; fam_envs <- tcGetFamInstEnvs
1459 ; instances <- reifyFamilyInstances tc (familyInstances fam_envs tc)
1460 ; return (TH.FamilyI
1461 (TH.DataFamilyD (reifyName tc) tvs' kind') instances) }
1462
1463 | Just (_, rhs) <- synTyConDefn_maybe tc -- Vanilla type synonym
1464 = do { rhs' <- reifyType rhs
1465 ; tvs' <- reifyTyVars (tyConVisibleTyVars tc)
1466 ; return (TH.TyConI
1467 (TH.TySynD (reifyName tc) tvs' rhs'))
1468 }
1469
1470 | otherwise
1471 = do { cxt <- reifyCxt (tyConStupidTheta tc)
1472 ; let tvs = tyConTyVars tc
1473 dataCons = tyConDataCons tc
1474 isGadt = isGadtSyntaxTyCon tc
1475 ; cons <- mapM (reifyDataCon isGadt (mkTyVarTys tvs)) dataCons
1476 ; r_tvs <- reifyTyVars (tyConVisibleTyVars tc)
1477 ; let name = reifyName tc
1478 deriv = [] -- Don't know about deriving
1479 decl | isNewTyCon tc =
1480 TH.NewtypeD cxt name r_tvs Nothing (head cons) deriv
1481 | otherwise =
1482 TH.DataD cxt name r_tvs Nothing cons deriv
1483 ; return (TH.TyConI decl) }
1484
1485 reifyDataCon :: Bool -> [Type] -> DataCon -> TcM TH.Con
1486 reifyDataCon isGadtDataCon tys dc
1487 = do { let -- used for H98 data constructors
1488 (ex_tvs, theta, arg_tys)
1489 = dataConInstSig dc tys
1490 -- used for GADTs data constructors
1491 g_user_tvs' = dataConUserTyVars dc
1492 (g_univ_tvs, _, g_eq_spec, g_theta', g_arg_tys', g_res_ty')
1493 = dataConFullSig dc
1494 (srcUnpks, srcStricts)
1495 = mapAndUnzip reifySourceBang (dataConSrcBangs dc)
1496 dcdBangs = zipWith TH.Bang srcUnpks srcStricts
1497 fields = dataConFieldLabels dc
1498 name = reifyName dc
1499 -- Universal tvs present in eq_spec need to be filtered out, as
1500 -- they will not appear anywhere in the type.
1501 eq_spec_tvs = mkVarSet (map eqSpecTyVar g_eq_spec)
1502
1503 ; (univ_subst, _)
1504 -- See Note [Freshen reified GADT constructors' universal tyvars]
1505 <- freshenTyVarBndrs $
1506 filterOut (`elemVarSet` eq_spec_tvs) g_univ_tvs
1507 ; let (tvb_subst, g_user_tvs) = substTyVarBndrs univ_subst g_user_tvs'
1508 g_theta = substTys tvb_subst g_theta'
1509 g_arg_tys = substTys tvb_subst g_arg_tys'
1510 g_res_ty = substTy tvb_subst g_res_ty'
1511
1512 ; r_arg_tys <- reifyTypes (if isGadtDataCon then g_arg_tys else arg_tys)
1513
1514 ; main_con <-
1515 if | not (null fields) && not isGadtDataCon ->
1516 return $ TH.RecC name (zip3 (map reifyFieldLabel fields)
1517 dcdBangs r_arg_tys)
1518 | not (null fields) -> do
1519 { res_ty <- reifyType g_res_ty
1520 ; return $ TH.RecGadtC [name]
1521 (zip3 (map (reifyName . flSelector) fields)
1522 dcdBangs r_arg_tys) res_ty }
1523 -- We need to check not isGadtDataCon here because GADT
1524 -- constructors can be declared infix.
1525 -- See Note [Infix GADT constructors] in TcTyClsDecls.
1526 | dataConIsInfix dc && not isGadtDataCon ->
1527 ASSERT( arg_tys `lengthIs` 2 ) do
1528 { let [r_a1, r_a2] = r_arg_tys
1529 [s1, s2] = dcdBangs
1530 ; return $ TH.InfixC (s1,r_a1) name (s2,r_a2) }
1531 | isGadtDataCon -> do
1532 { res_ty <- reifyType g_res_ty
1533 ; return $ TH.GadtC [name] (dcdBangs `zip` r_arg_tys) res_ty }
1534 | otherwise ->
1535 return $ TH.NormalC name (dcdBangs `zip` r_arg_tys)
1536
1537 ; let (ex_tvs', theta') | isGadtDataCon = (g_user_tvs, g_theta)
1538 | otherwise = (ex_tvs, theta)
1539 ret_con | null ex_tvs' && null theta' = return main_con
1540 | otherwise = do
1541 { cxt <- reifyCxt theta'
1542 ; ex_tvs'' <- reifyTyVars ex_tvs'
1543 ; return (TH.ForallC ex_tvs'' cxt main_con) }
1544 ; ASSERT( arg_tys `equalLength` dcdBangs )
1545 ret_con }
1546
1547 {-
1548 Note [Freshen reified GADT constructors' universal tyvars]
1549 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1550 Suppose one were to reify this GADT:
1551
1552 data a :~: b where
1553 Refl :: forall a b. (a ~ b) => a :~: b
1554
1555 We ought to be careful here about the uniques we give to the occurrences of `a`
1556 and `b` in this definition. That is because in the original DataCon, all uses
1557 of `a` and `b` have the same unique, since `a` and `b` are both universally
1558 quantified type variables--that is, they are used in both the (:~:) tycon as
1559 well as in the constructor type signature. But when we turn the DataCon
1560 definition into the reified one, the `a` and `b` in the constructor type
1561 signature becomes differently scoped than the `a` and `b` in `data a :~: b`.
1562
1563 While it wouldn't technically be *wrong* per se to re-use the same uniques for
1564 `a` and `b` across these two different scopes, it's somewhat annoying for end
1565 users of Template Haskell, since they wouldn't be able to rely on the
1566 assumption that all TH names have globally distinct uniques (#13885). For this
1567 reason, we freshen the universally quantified tyvars that go into the reified
1568 GADT constructor type signature to give them distinct uniques from their
1569 counterparts in the tycon.
1570 -}
1571
1572 ------------------------------
1573 reifyClass :: Class -> TcM TH.Info
1574 reifyClass cls
1575 = do { cxt <- reifyCxt theta
1576 ; inst_envs <- tcGetInstEnvs
1577 ; insts <- reifyClassInstances cls (InstEnv.classInstances inst_envs cls)
1578 ; assocTys <- concatMapM reifyAT ats
1579 ; ops <- concatMapM reify_op op_stuff
1580 ; tvs' <- reifyTyVars (tyConVisibleTyVars (classTyCon cls))
1581 ; let dec = TH.ClassD cxt (reifyName cls) tvs' fds' (assocTys ++ ops)
1582 ; return (TH.ClassI dec insts) }
1583 where
1584 (_, fds, theta, _, ats, op_stuff) = classExtraBigSig cls
1585 fds' = map reifyFunDep fds
1586 reify_op (op, def_meth)
1587 = do { ty <- reifyType (idType op)
1588 ; let nm' = reifyName op
1589 ; case def_meth of
1590 Just (_, GenericDM gdm_ty) ->
1591 do { gdm_ty' <- reifyType gdm_ty
1592 ; return [TH.SigD nm' ty, TH.DefaultSigD nm' gdm_ty'] }
1593 _ -> return [TH.SigD nm' ty] }
1594
1595 reifyAT :: ClassATItem -> TcM [TH.Dec]
1596 reifyAT (ATI tycon def) = do
1597 tycon' <- reifyTyCon tycon
1598 case tycon' of
1599 TH.FamilyI dec _ -> do
1600 let (tyName, tyArgs) = tfNames dec
1601 (dec :) <$> maybe (return [])
1602 (fmap (:[]) . reifyDefImpl tyName tyArgs . fst)
1603 def
1604 _ -> pprPanic "reifyAT" (text (show tycon'))
1605
1606 reifyDefImpl :: TH.Name -> [TH.Name] -> Type -> TcM TH.Dec
1607 reifyDefImpl n args ty =
1608 TH.TySynInstD n . TH.TySynEqn (map TH.VarT args) <$> reifyType ty
1609
1610 tfNames :: TH.Dec -> (TH.Name, [TH.Name])
1611 tfNames (TH.OpenTypeFamilyD (TH.TypeFamilyHead n args _ _))
1612 = (n, map bndrName args)
1613 tfNames d = pprPanic "tfNames" (text (show d))
1614
1615 bndrName :: TH.TyVarBndr -> TH.Name
1616 bndrName (TH.PlainTV n) = n
1617 bndrName (TH.KindedTV n _) = n
1618
1619 ------------------------------
1620 -- | Annotate (with TH.SigT) a type if the first parameter is True
1621 -- and if the type contains a free variable.
1622 -- This is used to annotate type patterns for poly-kinded tyvars in
1623 -- reifying class and type instances. See #8953 and th/T8953.
1624 annotThType :: Bool -- True <=> annotate
1625 -> TyCoRep.Type -> TH.Type -> TcM TH.Type
1626 -- tiny optimization: if the type is annotated, don't annotate again.
1627 annotThType _ _ th_ty@(TH.SigT {}) = return th_ty
1628 annotThType True ty th_ty
1629 | not $ isEmptyVarSet $ filterVarSet isTyVar $ tyCoVarsOfType ty
1630 = do { let ki = typeKind ty
1631 ; th_ki <- reifyKind ki
1632 ; return (TH.SigT th_ty th_ki) }
1633 annotThType _ _ th_ty = return th_ty
1634
1635 -- | For every type variable in the input,
1636 -- report whether or not the tv is poly-kinded. This is used to eventually
1637 -- feed into 'annotThType'.
1638 mkIsPolyTvs :: [TyVar] -> [Bool]
1639 mkIsPolyTvs = map is_poly_tv
1640 where
1641 is_poly_tv tv = not $
1642 isEmptyVarSet $
1643 filterVarSet isTyVar $
1644 tyCoVarsOfType $
1645 tyVarKind tv
1646
1647 ------------------------------
1648 reifyClassInstances :: Class -> [ClsInst] -> TcM [TH.Dec]
1649 reifyClassInstances cls insts
1650 = mapM (reifyClassInstance (mkIsPolyTvs tvs)) insts
1651 where
1652 tvs = tyConVisibleTyVars (classTyCon cls)
1653
1654 reifyClassInstance :: [Bool] -- True <=> the corresponding tv is poly-kinded
1655 -- includes only *visible* tvs
1656 -> ClsInst -> TcM TH.Dec
1657 reifyClassInstance is_poly_tvs i
1658 = do { cxt <- reifyCxt theta
1659 ; let vis_types = filterOutInvisibleTypes cls_tc types
1660 ; thtypes <- reifyTypes vis_types
1661 ; annot_thtypes <- zipWith3M annotThType is_poly_tvs vis_types thtypes
1662 ; let head_ty = mkThAppTs (TH.ConT (reifyName cls)) annot_thtypes
1663 ; return $ (TH.InstanceD over cxt head_ty []) }
1664 where
1665 (_tvs, theta, cls, types) = tcSplitDFunTy (idType dfun)
1666 cls_tc = classTyCon cls
1667 dfun = instanceDFunId i
1668 over = case overlapMode (is_flag i) of
1669 NoOverlap _ -> Nothing
1670 Overlappable _ -> Just TH.Overlappable
1671 Overlapping _ -> Just TH.Overlapping
1672 Overlaps _ -> Just TH.Overlaps
1673 Incoherent _ -> Just TH.Incoherent
1674
1675 ------------------------------
1676 reifyFamilyInstances :: TyCon -> [FamInst] -> TcM [TH.Dec]
1677 reifyFamilyInstances fam_tc fam_insts
1678 = mapM (reifyFamilyInstance (mkIsPolyTvs fam_tvs)) fam_insts
1679 where
1680 fam_tvs = tyConVisibleTyVars fam_tc
1681
1682 reifyFamilyInstance :: [Bool] -- True <=> the corresponding tv is poly-kinded
1683 -- includes only *visible* tvs
1684 -> FamInst -> TcM TH.Dec
1685 reifyFamilyInstance is_poly_tvs inst@(FamInst { fi_flavor = flavor
1686 , fi_fam = fam
1687 , fi_tvs = fam_tvs
1688 , fi_tys = lhs
1689 , fi_rhs = rhs })
1690 = case flavor of
1691 SynFamilyInst ->
1692 -- remove kind patterns (#8884)
1693 do { let lhs_types_only = filterOutInvisibleTypes fam_tc lhs
1694 ; th_lhs <- reifyTypes lhs_types_only
1695 ; annot_th_lhs <- zipWith3M annotThType is_poly_tvs lhs_types_only
1696 th_lhs
1697 ; th_rhs <- reifyType rhs
1698 ; return (TH.TySynInstD (reifyName fam)
1699 (TH.TySynEqn annot_th_lhs th_rhs)) }
1700
1701 DataFamilyInst rep_tc ->
1702 do { let rep_tvs = tyConTyVars rep_tc
1703 fam' = reifyName fam
1704
1705 -- eta-expand lhs types, because sometimes data/newtype
1706 -- instances are eta-reduced; See Trac #9692
1707 -- See Note [Eta reduction for data family axioms]
1708 -- in TcInstDcls
1709 (_rep_tc, rep_tc_args) = splitTyConApp rhs
1710 etad_tyvars = dropList rep_tc_args rep_tvs
1711 etad_tys = mkTyVarTys etad_tyvars
1712 eta_expanded_tvs = mkTyVarTys fam_tvs `chkAppend` etad_tys
1713 eta_expanded_lhs = lhs `chkAppend` etad_tys
1714 dataCons = tyConDataCons rep_tc
1715 isGadt = isGadtSyntaxTyCon rep_tc
1716 ; cons <- mapM (reifyDataCon isGadt eta_expanded_tvs) dataCons
1717 ; let types_only = filterOutInvisibleTypes fam_tc eta_expanded_lhs
1718 ; th_tys <- reifyTypes types_only
1719 ; annot_th_tys <- zipWith3M annotThType is_poly_tvs types_only th_tys
1720 ; return $
1721 if isNewTyCon rep_tc
1722 then TH.NewtypeInstD [] fam' annot_th_tys Nothing (head cons) []
1723 else TH.DataInstD [] fam' annot_th_tys Nothing cons []
1724 }
1725 where
1726 fam_tc = famInstTyCon inst
1727
1728 ------------------------------
1729 reifyType :: TyCoRep.Type -> TcM TH.Type
1730 -- Monadic only because of failure
1731 reifyType ty | tcIsLiftedTypeKind ty = return TH.StarT
1732 -- Make sure to use tcIsLiftedTypeKind here, since we don't want to confuse it
1733 -- with Constraint (#14869).
1734 reifyType ty@(ForAllTy {}) = reify_for_all ty
1735 reifyType (LitTy t) = do { r <- reifyTyLit t; return (TH.LitT r) }
1736 reifyType (TyVarTy tv) = return (TH.VarT (reifyName tv))
1737 reifyType (TyConApp tc tys) = reify_tc_app tc tys -- Do not expand type synonyms here
1738 reifyType (AppTy t1 t2) = do { [r1,r2] <- reifyTypes [t1,t2] ; return (r1 `TH.AppT` r2) }
1739 reifyType ty@(FunTy t1 t2)
1740 | isPredTy t1 = reify_for_all ty -- Types like ((?x::Int) => Char -> Char)
1741 | otherwise = do { [r1,r2] <- reifyTypes [t1,t2] ; return (TH.ArrowT `TH.AppT` r1 `TH.AppT` r2) }
1742 reifyType (CastTy t _) = reifyType t -- Casts are ignored in TH
1743 reifyType ty@(CoercionTy {})= noTH (sLit "coercions in types") (ppr ty)
1744
1745 reify_for_all :: TyCoRep.Type -> TcM TH.Type
1746 reify_for_all ty
1747 = do { cxt' <- reifyCxt cxt;
1748 ; tau' <- reifyType tau
1749 ; tvs' <- reifyTyVars tvs
1750 ; return (TH.ForallT tvs' cxt' tau') }
1751 where
1752 (tvs, cxt, tau) = tcSplitSigmaTy ty
1753
1754 reifyTyLit :: TyCoRep.TyLit -> TcM TH.TyLit
1755 reifyTyLit (NumTyLit n) = return (TH.NumTyLit n)
1756 reifyTyLit (StrTyLit s) = return (TH.StrTyLit (unpackFS s))
1757
1758 reifyTypes :: [Type] -> TcM [TH.Type]
1759 reifyTypes = mapM reifyType
1760
1761 reifyPatSynType
1762 :: ([TyVar], ThetaType, [TyVar], ThetaType, [Type], Type) -> TcM TH.Type
1763 -- reifies a pattern synonym's type and returns its *complete* type
1764 -- signature; see NOTE [Pattern synonym signatures and Template
1765 -- Haskell]
1766 reifyPatSynType (univTyVars, req, exTyVars, prov, argTys, resTy)
1767 = do { univTyVars' <- reifyTyVars univTyVars
1768 ; req' <- reifyCxt req
1769 ; exTyVars' <- reifyTyVars exTyVars
1770 ; prov' <- reifyCxt prov
1771 ; tau' <- reifyType (mkFunTys argTys resTy)
1772 ; return $ TH.ForallT univTyVars' req'
1773 $ TH.ForallT exTyVars' prov' tau' }
1774
1775 reifyKind :: Kind -> TcM TH.Kind
1776 reifyKind = reifyType
1777
1778 reifyCxt :: [PredType] -> TcM [TH.Pred]
1779 reifyCxt = mapM reifyPred
1780
1781 reifyFunDep :: ([TyVar], [TyVar]) -> TH.FunDep
1782 reifyFunDep (xs, ys) = TH.FunDep (map reifyName xs) (map reifyName ys)
1783
1784 reifyTyVars :: [TyVar] -> TcM [TH.TyVarBndr]
1785 reifyTyVars tvs = mapM reify_tv tvs
1786 where
1787 -- even if the kind is *, we need to include a kind annotation,
1788 -- in case a poly-kind would be inferred without the annotation.
1789 -- See #8953 or test th/T8953
1790 reify_tv tv = TH.KindedTV name <$> reifyKind kind
1791 where
1792 kind = tyVarKind tv
1793 name = reifyName tv
1794
1795 {-
1796 Note [Kind annotations on TyConApps]
1797 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1798 A poly-kinded tycon sometimes needs a kind annotation to be unambiguous.
1799 For example:
1800
1801 type family F a :: k
1802 type instance F Int = (Proxy :: * -> *)
1803 type instance F Bool = (Proxy :: (* -> *) -> *)
1804
1805 It's hard to figure out where these annotations should appear, so we do this:
1806 Suppose we have a tycon application (T ty1 ... tyn). Assuming that T is not
1807 oversatured (more on this later), we can assume T's declaration is of the form
1808 T (tvb1 :: s1) ... (tvbn :: sn) :: p. If any kind variable that
1809 is free in p is not free in an injective position in tvb1 ... tvbn,
1810 then we put on a kind annotation, since we would not otherwise be able to infer
1811 the kind of the whole tycon application.
1812
1813 The injective positions in a tyvar binder are the injective positions in the
1814 kind of its tyvar, provided the tyvar binder is either:
1815
1816 * Anonymous. For example, in the promoted data constructor '(:):
1817
1818 '(:) :: forall a. a -> [a] -> [a]
1819
1820 The second and third tyvar binders (of kinds `a` and `[a]`) are both
1821 anonymous, so if we had '(:) 'True '[], then the inferred kinds of 'True and
1822 '[] would contribute to the inferred kind of '(:) 'True '[].
1823 * Has required visibility. For example, in the type family:
1824
1825 type family Wurble k (a :: k) :: k
1826 Wurble :: forall k -> k -> k
1827
1828 The first tyvar binder (of kind `forall k`) has required visibility, so if
1829 we had Wurble (Maybe a) Nothing, then the inferred kind of Maybe a would
1830 contribute to the inferred kind of Wurble (Maybe a) Nothing.
1831
1832 An injective position in a type is one that does not occur as an argument to
1833 a non-injective type constructor (e.g., non-injective type families). See
1834 injectiveVarsOfType.
1835
1836 How can be sure that this is correct? That is, how can we be sure that in the
1837 event that we leave off a kind annotation, that one could infer the kind of the
1838 tycon application from its arguments? It's essentially a proof by induction: if
1839 we can infer the kinds of every subtree of a type, then the whole tycon
1840 application will have an inferrable kind--unless, of course, the remainder of
1841 the tycon application's kind has uninstantiated kind variables.
1842
1843 An earlier implementation of this algorithm only checked if p contained any
1844 free variables. But this was unsatisfactory, since a datatype like this:
1845
1846 data Foo = Foo (Proxy '[False, True])
1847
1848 Would be reified like this:
1849
1850 data Foo = Foo (Proxy ('(:) False ('(:) True ('[] :: [Bool])
1851 :: [Bool]) :: [Bool]))
1852
1853 Which has a rather excessive amount of kind annotations. With the current
1854 algorithm, we instead reify Foo to this:
1855
1856 data Foo = Foo (Proxy ('(:) False ('(:) True ('[] :: [Bool]))))
1857
1858 Since in the case of '[], the kind p is [a], and there are no arguments in the
1859 kind of '[]. On the other hand, in the case of '(:) True '[], the kind p is
1860 (forall a. [a]), but a occurs free in the first and second arguments of the
1861 full kind of '(:), which is (forall a. a -> [a] -> [a]). (See Trac #14060.)
1862
1863 What happens if T is oversaturated? That is, if T's kind has fewer than n
1864 arguments, in the case that the concrete application instantiates a result
1865 kind variable with an arrow kind? If we run out of arguments, we do not attach
1866 a kind annotation. This should be a rare case, indeed. Here is an example:
1867
1868 data T1 :: k1 -> k2 -> *
1869 data T2 :: k1 -> k2 -> *
1870
1871 type family G (a :: k) :: k
1872 type instance G T1 = T2
1873
1874 type instance F Char = (G T1 Bool :: (* -> *) -> *) -- F from above
1875
1876 Here G's kind is (forall k. k -> k), and the desugared RHS of that last
1877 instance of F is (G (* -> (* -> *) -> *) (T1 * (* -> *)) Bool). According to
1878 the algorithm above, there are 3 arguments to G so we should peel off 3
1879 arguments in G's kind. But G's kind has only two arguments. This is the
1880 rare special case, and we choose not to annotate the application of G with
1881 a kind signature. After all, we needn't do this, since that instance would
1882 be reified as:
1883
1884 type instance F Char = G (T1 :: * -> (* -> *) -> *) Bool
1885
1886 So the kind of G isn't ambiguous anymore due to the explicit kind annotation
1887 on its argument. See #8953 and test th/T8953.
1888 -}
1889
1890 reify_tc_app :: TyCon -> [Type.Type] -> TcM TH.Type
1891 reify_tc_app tc tys
1892 = do { tys' <- reifyTypes (filterOutInvisibleTypes tc tys)
1893 ; maybe_sig_t (mkThAppTs r_tc tys') }
1894 where
1895 arity = tyConArity tc
1896 tc_binders = tyConBinders tc
1897 tc_res_kind = tyConResKind tc
1898
1899 r_tc | isUnboxedSumTyCon tc = TH.UnboxedSumT (arity `div` 2)
1900 | isUnboxedTupleTyCon tc = TH.UnboxedTupleT (arity `div` 2)
1901 | isPromotedTupleTyCon tc = TH.PromotedTupleT (arity `div` 2)
1902 -- See Note [Unboxed tuple RuntimeRep vars] in TyCon
1903 | isTupleTyCon tc = if isPromotedDataCon tc
1904 then TH.PromotedTupleT arity
1905 else TH.TupleT arity
1906 | tc `hasKey` constraintKindTyConKey
1907 = TH.ConstraintT
1908 | tc `hasKey` funTyConKey = TH.ArrowT
1909 | tc `hasKey` listTyConKey = TH.ListT
1910 | tc `hasKey` nilDataConKey = TH.PromotedNilT
1911 | tc `hasKey` consDataConKey = TH.PromotedConsT
1912 | tc `hasKey` heqTyConKey = TH.EqualityT
1913 | tc `hasKey` eqPrimTyConKey = TH.EqualityT
1914 | tc `hasKey` eqReprPrimTyConKey = TH.ConT (reifyName coercibleTyCon)
1915 | isPromotedDataCon tc = TH.PromotedT (reifyName tc)
1916 | otherwise = TH.ConT (reifyName tc)
1917
1918 -- See Note [Kind annotations on TyConApps]
1919 maybe_sig_t th_type
1920 | needs_kind_sig
1921 = do { let full_kind = typeKind (mkTyConApp tc tys)
1922 ; th_full_kind <- reifyKind full_kind
1923 ; return (TH.SigT th_type th_full_kind) }
1924 | otherwise
1925 = return th_type
1926
1927 needs_kind_sig
1928 | GT <- compareLength tys tc_binders
1929 = False
1930 | otherwise
1931 = let (dropped_binders, remaining_binders)
1932 = splitAtList tys tc_binders
1933 result_kind = mkTyConKind remaining_binders tc_res_kind
1934 result_vars = tyCoVarsOfType result_kind
1935 dropped_vars = fvVarSet $
1936 mapUnionFV injectiveVarsOfBinder dropped_binders
1937
1938 in not (subVarSet result_vars dropped_vars)
1939
1940 reifyPred :: TyCoRep.PredType -> TcM TH.Pred
1941 reifyPred ty
1942 -- We could reify the invisible parameter as a class but it seems
1943 -- nicer to support them properly...
1944 | isIPPred ty = noTH (sLit "implicit parameters") (ppr ty)
1945 | otherwise = reifyType ty
1946
1947 ------------------------------
1948 reifyName :: NamedThing n => n -> TH.Name
1949 reifyName thing
1950 | isExternalName name = mk_varg pkg_str mod_str occ_str
1951 | otherwise = TH.mkNameU occ_str (getKey (getUnique name))
1952 -- Many of the things we reify have local bindings, and
1953 -- NameL's aren't supposed to appear in binding positions, so
1954 -- we use NameU. When/if we start to reify nested things, that
1955 -- have free variables, we may need to generate NameL's for them.
1956 where
1957 name = getName thing
1958 mod = ASSERT( isExternalName name ) nameModule name
1959 pkg_str = unitIdString (moduleUnitId mod)
1960 mod_str = moduleNameString (moduleName mod)
1961 occ_str = occNameString occ
1962 occ = nameOccName name
1963 mk_varg | OccName.isDataOcc occ = TH.mkNameG_d
1964 | OccName.isVarOcc occ = TH.mkNameG_v
1965 | OccName.isTcOcc occ = TH.mkNameG_tc
1966 | otherwise = pprPanic "reifyName" (ppr name)
1967
1968 -- See Note [Reifying field labels]
1969 reifyFieldLabel :: FieldLabel -> TH.Name
1970 reifyFieldLabel fl
1971 | flIsOverloaded fl
1972 = TH.Name (TH.mkOccName occ_str) (TH.NameQ (TH.mkModName mod_str))
1973 | otherwise = TH.mkNameG_v pkg_str mod_str occ_str
1974 where
1975 name = flSelector fl
1976 mod = ASSERT( isExternalName name ) nameModule name
1977 pkg_str = unitIdString (moduleUnitId mod)
1978 mod_str = moduleNameString (moduleName mod)
1979 occ_str = unpackFS (flLabel fl)
1980
1981 reifySelector :: Id -> TyCon -> TH.Name
1982 reifySelector id tc
1983 = case find ((idName id ==) . flSelector) (tyConFieldLabels tc) of
1984 Just fl -> reifyFieldLabel fl
1985 Nothing -> pprPanic "reifySelector: missing field" (ppr id $$ ppr tc)
1986
1987 ------------------------------
1988 reifyFixity :: Name -> TcM (Maybe TH.Fixity)
1989 reifyFixity name
1990 = do { (found, fix) <- lookupFixityRn_help name
1991 ; return (if found then Just (conv_fix fix) else Nothing) }
1992 where
1993 conv_fix (BasicTypes.Fixity _ i d) = TH.Fixity i (conv_dir d)
1994 conv_dir BasicTypes.InfixR = TH.InfixR
1995 conv_dir BasicTypes.InfixL = TH.InfixL
1996 conv_dir BasicTypes.InfixN = TH.InfixN
1997
1998 reifyUnpackedness :: DataCon.SrcUnpackedness -> TH.SourceUnpackedness
1999 reifyUnpackedness NoSrcUnpack = TH.NoSourceUnpackedness
2000 reifyUnpackedness SrcNoUnpack = TH.SourceNoUnpack
2001 reifyUnpackedness SrcUnpack = TH.SourceUnpack
2002
2003 reifyStrictness :: DataCon.SrcStrictness -> TH.SourceStrictness
2004 reifyStrictness NoSrcStrict = TH.NoSourceStrictness
2005 reifyStrictness SrcStrict = TH.SourceStrict
2006 reifyStrictness SrcLazy = TH.SourceLazy
2007
2008 reifySourceBang :: DataCon.HsSrcBang
2009 -> (TH.SourceUnpackedness, TH.SourceStrictness)
2010 reifySourceBang (HsSrcBang _ u s) = (reifyUnpackedness u, reifyStrictness s)
2011
2012 reifyDecidedStrictness :: DataCon.HsImplBang -> TH.DecidedStrictness
2013 reifyDecidedStrictness HsLazy = TH.DecidedLazy
2014 reifyDecidedStrictness HsStrict = TH.DecidedStrict
2015 reifyDecidedStrictness HsUnpack{} = TH.DecidedUnpack
2016
2017 ------------------------------
2018 lookupThAnnLookup :: TH.AnnLookup -> TcM CoreAnnTarget
2019 lookupThAnnLookup (TH.AnnLookupName th_nm) = fmap NamedTarget (lookupThName th_nm)
2020 lookupThAnnLookup (TH.AnnLookupModule (TH.Module pn mn))
2021 = return $ ModuleTarget $
2022 mkModule (stringToUnitId $ TH.pkgString pn) (mkModuleName $ TH.modString mn)
2023
2024 reifyAnnotations :: Data a => TH.AnnLookup -> TcM [a]
2025 reifyAnnotations th_name
2026 = do { name <- lookupThAnnLookup th_name
2027 ; topEnv <- getTopEnv
2028 ; epsHptAnns <- liftIO $ prepareAnnotations topEnv Nothing
2029 ; tcg <- getGblEnv
2030 ; let selectedEpsHptAnns = findAnns deserializeWithData epsHptAnns name
2031 ; let selectedTcgAnns = findAnns deserializeWithData (tcg_ann_env tcg) name
2032 ; return (selectedEpsHptAnns ++ selectedTcgAnns) }
2033
2034 ------------------------------
2035 modToTHMod :: Module -> TH.Module
2036 modToTHMod m = TH.Module (TH.PkgName $ unitIdString $ moduleUnitId m)
2037 (TH.ModName $ moduleNameString $ moduleName m)
2038
2039 reifyModule :: TH.Module -> TcM TH.ModuleInfo
2040 reifyModule (TH.Module (TH.PkgName pkgString) (TH.ModName mString)) = do
2041 this_mod <- getModule
2042 let reifMod = mkModule (stringToUnitId pkgString) (mkModuleName mString)
2043 if (reifMod == this_mod) then reifyThisModule else reifyFromIface reifMod
2044 where
2045 reifyThisModule = do
2046 usages <- fmap (map modToTHMod . moduleEnvKeys . imp_mods) getImports
2047 return $ TH.ModuleInfo usages
2048
2049 reifyFromIface reifMod = do
2050 iface <- loadInterfaceForModule (text "reifying module from TH for" <+> ppr reifMod) reifMod
2051 let usages = [modToTHMod m | usage <- mi_usages iface,
2052 Just m <- [usageToModule (moduleUnitId reifMod) usage] ]
2053 return $ TH.ModuleInfo usages
2054
2055 usageToModule :: UnitId -> Usage -> Maybe Module
2056 usageToModule _ (UsageFile {}) = Nothing
2057 usageToModule this_pkg (UsageHomeModule { usg_mod_name = mn }) = Just $ mkModule this_pkg mn
2058 usageToModule _ (UsagePackageModule { usg_mod = m }) = Just m
2059 usageToModule _ (UsageMergedRequirement { usg_mod = m }) = Just m
2060
2061 ------------------------------
2062 mkThAppTs :: TH.Type -> [TH.Type] -> TH.Type
2063 mkThAppTs fun_ty arg_tys = foldl TH.AppT fun_ty arg_tys
2064
2065 noTH :: LitString -> SDoc -> TcM a
2066 noTH s d = failWithTc (hsep [text "Can't represent" <+> ptext s <+>
2067 text "in Template Haskell:",
2068 nest 2 d])
2069
2070 ppr_th :: TH.Ppr a => a -> SDoc
2071 ppr_th x = text (TH.pprint x)
2072
2073 {-
2074 Note [Reifying field labels]
2075 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2076 When reifying a datatype declared with DuplicateRecordFields enabled, we want
2077 the reified names of the fields to be labels rather than selector functions.
2078 That is, we want (reify ''T) and (reify 'foo) to produce
2079
2080 data T = MkT { foo :: Int }
2081 foo :: T -> Int
2082
2083 rather than
2084
2085 data T = MkT { $sel:foo:MkT :: Int }
2086 $sel:foo:MkT :: T -> Int
2087
2088 because otherwise TH code that uses the field names as strings will silently do
2089 the wrong thing. Thus we use the field label (e.g. foo) as the OccName, rather
2090 than the selector (e.g. $sel:foo:MkT). Since the Orig name M.foo isn't in the
2091 environment, NameG can't be used to represent such fields. Instead,
2092 reifyFieldLabel uses NameQ.
2093
2094 However, this means that extracting the field name from the output of reify, and
2095 trying to reify it again, may fail with an ambiguity error if there are multiple
2096 such fields defined in the module (see the test case
2097 overloadedrecflds/should_fail/T11103.hs). The "proper" fix requires changes to
2098 the TH AST to make it able to represent duplicate record fields.
2099 -}