TcSplice.hs 86.8 KB
Newer Older
Austin Seipp's avatar
Austin Seipp committed
1 2 3
{-
(c) The University of Glasgow 2006
(c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4

5

Austin Seipp's avatar
Austin Seipp committed
6 7
TcSplice: Template Haskell splices
-}
8

9 10 11 12 13
{-# LANGUAGE CPP #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE MagicHash #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE InstanceSigs #-}
14 15
{-# LANGUAGE GADTs #-}
{-# LANGUAGE RecordWildCards #-}
16
{-# LANGUAGE MultiWayIf #-}
17
{-# LANGUAGE TypeFamilies #-}
18
{-# OPTIONS_GHC -fno-warn-orphans #-}
19

20
module TcSplice(
21
     tcSpliceExpr, tcTypedBracket, tcUntypedBracket,
22 23
--     runQuasiQuoteExpr, runQuasiQuotePat,
--     runQuasiQuoteDecl, runQuasiQuoteType,
24 25 26
     runAnnotation,

     runMetaE, runMetaP, runMetaT, runMetaD, runQuasi,
27
     tcTopSpliceExpr, lookupThName_maybe,
28
     defaultRunMeta, runMeta', runRemoteModFinalizers,
29
     finishTH, runTopSplice
30
      ) where
31 32 33

#include "HsVersions.h"

34 35
import GhcPrelude

36 37
import HsSyn
import Annotations
38
import Finder
39 40 41 42
import Name
import TcRnMonad
import TcType

43 44 45
import Outputable
import TcExpr
import SrcLoc
46
import THNames
47 48
import TcUnify
import TcEnv
49
import Coercion( etaExpandCoAxBranch )
50
import FileCleanup ( newTempName, TempFileLifetime(..) )
51

52 53
import Control.Monad

54 55 56
import GHCi.Message
import GHCi.RemoteTypes
import GHCi
57
import HscMain
58 59
        -- These imports are the reason that TcSplice
        -- is very high up the module hierarchy
60
import FV
61
import RnSplice( traceSplice, SpliceInfo(..))
62
import RdrName
63
import HscTypes
64 65 66
import Convert
import RnExpr
import RnEnv
67 68
import RnUtils ( HsDocContext(..) )
import RnFixity ( lookupFixityRn_help )
69 70 71
import RnTypes
import TcHsSyn
import TcSimplify
batterseapower's avatar
batterseapower committed
72
import Type
73
import NameSet
74 75 76
import TcMType
import TcHsType
import TcIface
77
import TyCoRep
78 79
import FamInst
import FamInstEnv
80
import InstEnv
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
81
import Inst
82
import NameEnv
83
import PrelNames
84
import TysWiredIn
85
import OccName
86
import Hooks
87 88
import Var
import Module
89
import LoadIface
90 91
import Class
import TyCon
92
import CoAxiom
93
import PatSyn
cactus's avatar
cactus committed
94
import ConLike
95
import DataCon
96
import TcEvidence( TcEvBinds(..) )
97 98 99
import Id
import IdInfo
import DsExpr
100
import DsMonad
101
import GHC.Serialized
102
import ErrUtils
103
import Util
104
import Unique
105
import VarSet
Simon Peyton Jones's avatar
Simon Peyton Jones committed
106
import Data.List        ( find )
107
import Data.Maybe
108
import FastString
109 110
import BasicTypes hiding( SuccessFlag(..) )
import Maybes( MaybeErr(..) )
111
import DynFlags
112
import Panic
113
import Lexeme
114
import qualified EnumSet
115
import Plugins
116
import Bag
117

118 119 120
import qualified Language.Haskell.TH as TH
-- THSyntax gives access to internal functions and data types
import qualified Language.Haskell.TH.Syntax as TH
121

122 123
-- Because GHC.Desugar might not be in the base library of the bootstrapping compiler
import GHC.Desugar      ( AnnotationWrapper(..) )
124

125 126 127 128 129
import Control.Exception
import Data.Binary
import Data.Binary.Get
import qualified Data.ByteString as B
import qualified Data.ByteString.Lazy as LB
130
import Data.Dynamic  ( fromDynamic, toDyn )
131 132
import qualified Data.Map as Map
import Data.Typeable ( typeOf, Typeable, TypeRep, typeRep )
133
import Data.Data (Data)
134
import Data.Proxy    ( Proxy (..) )
135
import GHC.Exts         ( unsafeCoerce# )
136

Austin Seipp's avatar
Austin Seipp committed
137 138 139
{-
************************************************************************
*                                                                      *
140
\subsection{Main interface + stubs for the non-GHCI case
Austin Seipp's avatar
Austin Seipp committed
141 142 143
*                                                                      *
************************************************************************
-}
144

145 146
tcTypedBracket   :: HsExpr GhcRn -> HsBracket GhcRn -> ExpRhoType -> TcM (HsExpr GhcTcId)
tcUntypedBracket :: HsExpr GhcRn -> HsBracket GhcRn -> [PendingRnSplice] -> ExpRhoType
147 148
                 -> TcM (HsExpr GhcTcId)
tcSpliceExpr     :: HsSplice GhcRn  -> ExpRhoType -> TcM (HsExpr GhcTcId)
149 150
        -- None of these functions add constraints to the LIE

151 152 153 154
-- runQuasiQuoteExpr :: HsQuasiQuote RdrName -> RnM (LHsExpr RdrName)
-- runQuasiQuotePat  :: HsQuasiQuote RdrName -> RnM (LPat RdrName)
-- runQuasiQuoteType :: HsQuasiQuote RdrName -> RnM (LHsType RdrName)
-- runQuasiQuoteDecl :: HsQuasiQuote RdrName -> RnM [LHsDecl RdrName]
155

156
runAnnotation     :: CoreAnnTarget -> LHsExpr GhcRn -> TcM Annotation
157 158 159 160 161 162 163 164 165 166
{-
************************************************************************
*                                                                      *
\subsection{Quoting an expression}
*                                                                      *
************************************************************************
-}

-- See Note [How brackets and nested splices are handled]
-- tcTypedBracket :: HsBracket Name -> TcRhoType -> TcM (HsExpr TcId)
167
tcTypedBracket rn_expr brack@(TExpBr _ expr) res_ty
168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184
  = addErrCtxt (quotationCtxtDoc brack) $
    do { cur_stage <- getStage
       ; ps_ref <- newMutVar []
       ; lie_var <- getConstraintVar   -- Any constraints arising from nested splices
                                       -- should get thrown into the constraint set
                                       -- from outside the bracket

       -- Typecheck expr to make sure it is valid,
       -- Throw away the typechecked expression but return its type.
       -- We'll typecheck it again when we splice it in somewhere
       ; (_tc_expr, expr_ty) <- setStage (Brack cur_stage (TcPending ps_ref lie_var)) $
                                tcInferRhoNC expr
                                -- NC for no context; tcBracket does that

       ; meta_ty <- tcTExpTy expr_ty
       ; ps' <- readMutVar ps_ref
       ; texpco <- tcLookupId unsafeTExpCoerceName
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
185
       ; tcWrapResultO (Shouldn'tHappenOrigin "TExpBr")
186
                       rn_expr
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
187
                       (unLoc (mkHsApp (nlHsTyApp texpco [expr_ty])
188
                                      (noLoc (HsTcBracketOut noExt brack ps'))))
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
189
                       meta_ty res_ty }
190
tcTypedBracket _ other_brack _
191 192
  = pprPanic "tcTypedBracket" (ppr other_brack)

193
-- tcUntypedBracket :: HsBracket Name -> [PendingRnSplice] -> ExpRhoType -> TcM (HsExpr TcId)
194
tcUntypedBracket rn_expr brack ps res_ty
195 196 197 198
  = do { traceTc "tc_bracket untyped" (ppr brack $$ ppr ps)
       ; ps' <- mapM tcPendingSplice ps
       ; meta_ty <- tcBrackTy brack
       ; traceTc "tc_bracket done untyped" (ppr meta_ty)
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
199
       ; tcWrapResultO (Shouldn'tHappenOrigin "untyped bracket")
200
                       rn_expr (HsTcBracketOut noExt brack ps') meta_ty res_ty }
201 202

---------------
203
tcBrackTy :: HsBracket GhcRn -> TcM TcType
204 205 206 207 208 209 210 211 212
tcBrackTy (VarBr {})  = tcMetaTy nameTyConName
                                           -- Result type is Var (not Q-monadic)
tcBrackTy (ExpBr {})  = tcMetaTy expQTyConName  -- Result type is ExpQ (= Q Exp)
tcBrackTy (TypBr {})  = tcMetaTy typeQTyConName -- Result type is Type (= Q Typ)
tcBrackTy (DecBrG {}) = tcMetaTy decsQTyConName -- Result type is Q [Dec]
tcBrackTy (PatBr {})  = tcMetaTy patQTyConName  -- Result type is PatQ (= Q Pat)
tcBrackTy (DecBrL {})   = panic "tcBrackTy: Unexpected DecBrL"
tcBrackTy (TExpBr {})   = panic "tcUntypedBracket: Unexpected TExpBr"
tcBrackTy (XBracket {}) = panic "tcUntypedBracket: Unexpected XBracket"
213 214 215 216 217

---------------
tcPendingSplice :: PendingRnSplice -> TcM PendingTcSplice
tcPendingSplice (PendingRnSplice flavour splice_name expr)
  = do { res_ty <- tcMetaTy meta_ty_name
218
       ; expr' <- tcMonoExpr expr (mkCheckExpType res_ty)
219 220 221 222 223 224 225 226 227
       ; return (PendingTcSplice splice_name expr') }
  where
     meta_ty_name = case flavour of
                       UntypedExpSplice  -> expQTyConName
                       UntypedPatSplice  -> patQTyConName
                       UntypedTypeSplice -> typeQTyConName
                       UntypedDeclSplice -> decsQTyConName

---------------
228
-- Takes a tau and returns the type Q (TExp tau)
229
tcTExpTy :: TcType -> TcM TcType
230 231 232
tcTExpTy exp_ty
  = do { unless (isTauTy exp_ty) $ addErr (err_msg exp_ty)
       ; q    <- tcLookupTyCon qTyConName
233
       ; texp <- tcLookupTyCon tExpTyConName
234 235 236 237 238 239
       ; return (mkTyConApp q [mkTyConApp texp [exp_ty]]) }
  where
    err_msg ty
      = vcat [ text "Illegal polytype:" <+> ppr ty
             , text "The type of a Typed Template Haskell expression must" <+>
               text "not have any quantification." ]
240

241
quotationCtxtDoc :: HsBracket GhcRn -> SDoc
242
quotationCtxtDoc br_body
243
  = hang (text "In the Template Haskell quotation")
244 245
         2 (ppr br_body)

246 247 248

  -- The whole of the rest of the file is the else-branch (ie stage2 only)

Austin Seipp's avatar
Austin Seipp committed
249
{-
250 251 252 253 254 255 256 257 258 259 260 261 262 263 264
Note [How top-level splices are handled]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Top-level splices (those not inside a [| .. |] quotation bracket) are handled
very straightforwardly:

  1. tcTopSpliceExpr: typecheck the body e of the splice $(e)

  2. runMetaT: desugar, compile, run it, and convert result back to
     HsSyn RdrName (of the appropriate flavour, eg HsType RdrName,
     HsExpr RdrName etc)

  3. treat the result as if that's what you saw in the first place
     e.g for HsType, rename and kind-check
         for HsExpr, rename and type-check

Gabor Greif's avatar
typos  
Gabor Greif committed
265
     (The last step is different for decls, because they can *only* be
266 267 268 269
      top-level: we return the result of step 2.)

Note [How brackets and nested splices are handled]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314
Nested splices (those inside a [| .. |] quotation bracket),
are treated quite differently.

Remember, there are two forms of bracket
         typed   [|| e ||]
   and untyped   [|  e  |]

The life cycle of a typed bracket:
   * Starts as HsBracket

   * When renaming:
        * Set the ThStage to (Brack s RnPendingTyped)
        * Rename the body
        * Result is still a HsBracket

   * When typechecking:
        * Set the ThStage to (Brack s (TcPending ps_var lie_var))
        * Typecheck the body, and throw away the elaborated result
        * Nested splices (which must be typed) are typechecked, and
          the results accumulated in ps_var; their constraints
          accumulate in lie_var
        * Result is a HsTcBracketOut rn_brack pending_splices
          where rn_brack is the incoming renamed bracket

The life cycle of a un-typed bracket:
   * Starts as HsBracket

   * When renaming:
        * Set the ThStage to (Brack s (RnPendingUntyped ps_var))
        * Rename the body
        * Nested splices (which must be untyped) are renamed, and the
          results accumulated in ps_var
        * Result is still (HsRnBracketOut rn_body pending_splices)

   * When typechecking a HsRnBracketOut
        * Typecheck the pending_splices individually
        * Ignore the body of the bracket; just check that the context
          expects a bracket of that type (e.g. a [p| pat |] bracket should
          be in a context needing a (Q Pat)
        * Result is a HsTcBracketOut rn_brack pending_splices
          where rn_brack is the incoming renamed bracket


In both cases, desugaring happens like this:
  * HsTcBracketOut is desugared by DsMeta.dsBracket.  It
315 316 317 318 319 320

      a) Extends the ds_meta environment with the PendingSplices
         attached to the bracket

      b) Converts the quoted (HsExpr Name) to a CoreExpr that, when
         run, will produce a suitable TH expression/type/decl.  This
321
         is why we leave the *renamed* expression attached to the bracket:
322 323 324 325 326 327 328 329 330 331 332 333
         the quoted expression should not be decorated with all the goop
         added by the type checker

  * Each splice carries a unique Name, called a "splice point", thus
    ${n}(e).  The name is initialised to an (Unqual "splice") when the
    splice is created; the renamer gives it a unique.

  * When DsMeta (used to desugar the body of the bracket) comes across
    a splice, it looks up the splice's Name, n, in the ds_meta envt,
    to find an (HsExpr Id) that should be substituted for the splice;
    it just desugars it to get a CoreExpr (DsMeta.repSplice).

334 335
Example:
    Source:       f = [| Just $(g 3) |]
336 337 338
      The [| |] part is a HsBracket

    Typechecked:  f = [| Just ${s7}(g 3) |]{s7 = g Int 3}
339 340 341 342
      The [| |] part is a HsBracketOut, containing *renamed*
        (not typechecked) expression
      The "s7" is the "splice point"; the (g Int 3) part
        is a typechecked expression
343

344 345
    Desugared:    f = do { s7 <- g Int 3
                         ; return (ConE "Data.Maybe.Just" s7) }
346 347 348 349 350


Note [Template Haskell state diagram]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Here are the ThStages, s, their corresponding level numbers
351
(the result of (thLevel s)), and their state transitions.
352
The top level of the program is stage Comp:
353

354 355 356
     Start here
         |
         V
357
      -----------     $      ------------   $
358
      |  Comp   | ---------> |  Splice  | -----|
359 360 361 362 363 364 365 366 367 368 369
      |   1     |            |    0     | <----|
      -----------            ------------
        ^     |                ^      |
      $ |     | [||]         $ |      | [||]
        |     v                |      v
   --------------          ----------------
   | Brack Comp |          | Brack Splice |
   |     2      |          |      1       |
   --------------          ----------------

* Normal top-level declarations start in state Comp
370 371 372 373
       (which has level 1).
  Annotations start in state Splice, since they are
       treated very like a splice (only without a '$')

374
* Code compiled in state Splice (and only such code)
375 376 377 378 379
  will be *run at compile time*, with the result replacing
  the splice

* The original paper used level -1 instead of 0, etc.

380 381
* The original paper did not allow a splice within a
  splice, but there is no reason not to. This is the
382 383
  $ transition in the top right.

384 385 386
Note [Template Haskell levels]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
* Imported things are impLevel (= 0)
387

388 389 390
* However things at level 0 are not *necessarily* imported.
      eg  $( \b -> ... )   here b is bound at level 0

391 392 393
* In GHCi, variables bound by a previous command are treated
  as impLevel, because we have bytecode for them.

394
* Variables are bound at the "current level"
395

396
* The current level starts off at outerLevel (= 1)
397

398
* The level is decremented by splicing $(..)
399 400
               incremented by brackets [| |]
               incremented by name-quoting 'f
401

402 403 404
When a variable is used, we compare
        bind:  binding level, and
        use:   current level at usage site
405 406

  Generally
407 408
        bind > use      Always error (bound later than used)
                        [| \x -> $(f x) |]
409

410 411 412 413 414 415
        bind = use      Always OK (bound same stage as used)
                        [| \x -> $(f [| x |]) |]

        bind < use      Inside brackets, it depends
                        Inside splice, OK
                        Inside neither, OK
416 417

  For (bind < use) inside brackets, there are three cases:
418 419 420 421
    - Imported things   OK      f = [| map |]
    - Top-level things  OK      g = [| f |]
    - Non-top-level     Only if there is a liftable instance
                                h = \(x:Int) -> [| x |]
422

423
  To track top-level-ness we use the ThBindEnv in TcLclEnv
424

425 426 427 428
  For example:
           f = ...
           g1 = $(map ...)         is OK
           g2 = $(f ...)           is not OK; because we havn't compiled f yet
429

Austin Seipp's avatar
Austin Seipp committed
430
-}
simonpj@microsoft.com's avatar
simonpj@microsoft.com committed
431

Austin Seipp's avatar
Austin Seipp committed
432 433 434
{-
************************************************************************
*                                                                      *
435
\subsection{Splicing an expression}
Austin Seipp's avatar
Austin Seipp committed
436 437 438
*                                                                      *
************************************************************************
-}
439

440
tcSpliceExpr splice@(HsTypedSplice _ _ name expr) res_ty
441
  = addErrCtxt (spliceCtxtDoc splice) $
442
    setSrcSpan (getLoc expr)    $ do
443
    { stage <- getStage
gmainland's avatar
gmainland committed
444
    ; case stage of
445 446 447 448 449 450 451 452
          Splice {}            -> tcTopSplice expr res_ty
          Brack pop_stage pend -> tcNestedSplice pop_stage pend name expr res_ty
          RunSplice _          ->
            -- See Note [RunSplice ThLevel] in "TcRnTypes".
            pprPanic ("tcSpliceExpr: attempted to typecheck a splice when " ++
                      "running another splice") (ppr splice)
          Comp                 -> tcTopSplice expr res_ty
    }
453 454
tcSpliceExpr splice _
  = pprPanic "tcSpliceExpr" (ppr splice)
455

456 457 458 459 460 461 462 463 464 465 466
{- Note [Collecting modFinalizers in typed splices]
   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

'qAddModFinalizer' of the @Quasi TcM@ instance adds finalizers in the local
environment (see Note [Delaying modFinalizers in untyped splices] in
"RnSplice"). Thus after executing the splice, we move the finalizers to the
finalizer list in the global environment and set them to use the current local
environment (with 'addModFinalizersWithLclEnv').

-}

467
tcNestedSplice :: ThStage -> PendingStuff -> Name
468
                -> LHsExpr GhcRn -> ExpRhoType -> TcM (HsExpr GhcTc)
469 470
    -- See Note [How brackets and nested splices are handled]
    -- A splice inside brackets
471
tcNestedSplice pop_stage (TcPending ps_var lie_var) splice_name expr res_ty
472 473
  = do { res_ty <- expTypeToType res_ty
       ; meta_exp_ty <- tcTExpTy res_ty
474 475
       ; expr' <- setStage pop_stage $
                  setConstraintVar lie_var $
476
                  tcMonoExpr expr (mkCheckExpType meta_exp_ty)
477 478 479
       ; untypeq <- tcLookupId unTypeQName
       ; let expr'' = mkHsApp (nlHsTyApp untypeq [res_ty]) expr'
       ; ps <- readMutVar ps_var
480
       ; writeMutVar ps_var (PendingTcSplice splice_name expr'' : ps)
481 482 483 484 485 486

       -- The returned expression is ignored; it's in the pending splices
       ; return (panic "tcSpliceExpr") }

tcNestedSplice _ _ splice_name _ _
  = pprPanic "tcNestedSplice: rename stage found" (ppr splice_name)
487

488
tcTopSplice :: LHsExpr GhcRn -> ExpRhoType -> TcM (HsExpr GhcTc)
gmainland's avatar
gmainland committed
489
tcTopSplice expr res_ty
490 491
  = do { -- Typecheck the expression,
         -- making sure it has type Q (T res_ty)
492 493
         res_ty <- expTypeToType res_ty
       ; meta_exp_ty <- tcTExpTy res_ty
494
       ; q_expr <- tcTopSpliceExpr Typed $
495
                          tcMonoExpr expr (mkCheckExpType meta_exp_ty)
496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511
       ; lcl_env <- getLclEnv
       ; let delayed_splice
              = DelayedSplice lcl_env expr res_ty q_expr
       ; return (HsSpliceE noExt (HsSplicedT delayed_splice))

       }


-- This is called in the zonker
-- See Note [Running typed splices in the zonker]
runTopSplice :: DelayedSplice -> TcM (HsExpr GhcTc)
runTopSplice (DelayedSplice lcl_env orig_expr res_ty q_expr)
  = setLclEnv lcl_env $ do {
         zonked_ty <- zonkTcType res_ty
       ; zonked_q_expr <- zonkTopLExpr q_expr
        -- See Note [Collecting modFinalizers in typed splices].
512
       ; modfinalizers_ref <- newTcRef []
513
         -- Run the expression
514 515 516 517
       ; expr2 <- setStage (RunSplice modfinalizers_ref) $
                    runMetaE zonked_q_expr
       ; mod_finalizers <- readTcRef modfinalizers_ref
       ; addModFinalizersWithLclEnv $ ThModFinalizers mod_finalizers
518 519 520
       -- We use orig_expr here and not q_expr when tracing as a call to
       -- unsafeTExpCoerce is added to the original expression by the
       -- typechecker when typed quotes are type checked.
521 522
       ; traceSplice (SpliceInfo { spliceDescription = "expression"
                                 , spliceIsDecl      = False
523
                                 , spliceSource      = Just orig_expr
524
                                 , spliceGenerated   = ppr expr2 })
525 526 527 528 529 530
        -- Rename and typecheck the spliced-in expression,
        -- making sure it has type res_ty
        -- These steps should never fail; this is a *typed* splice
       ; addErrCtxt (spliceResultDoc zonked_q_expr) $ do
         { (exp3, _fvs) <- rnLExpr expr2
         ; unLoc <$> tcMonoExpr exp3 (mkCheckExpType zonked_ty)} }
531

gmainland's avatar
gmainland committed
532

Austin Seipp's avatar
Austin Seipp committed
533 534 535
{-
************************************************************************
*                                                                      *
gmainland's avatar
gmainland committed
536
\subsection{Error messages}
Austin Seipp's avatar
Austin Seipp committed
537 538 539
*                                                                      *
************************************************************************
-}
540

541
spliceCtxtDoc :: HsSplice GhcRn -> SDoc
542
spliceCtxtDoc splice
543
  = hang (text "In the Template Haskell splice")
544
         2 (pprSplice splice)
545

546
spliceResultDoc :: LHsExpr GhcTc -> SDoc
547
spliceResultDoc expr
548
  = sep [ text "In the result of the splice:"
549
        , nest 2 (char '$' <> ppr expr)
550
        , text "To see what the splice expanded to, use -ddump-splices"]
551

552
-------------------
553
tcTopSpliceExpr :: SpliceType -> TcM (LHsExpr GhcTc) -> TcM (LHsExpr GhcTc)
554
-- Note [How top-level splices are handled]
555 556
-- Type check an expression that is the body of a top-level splice
--   (the caller will compile and run it)
557 558
-- Note that set the level to Splice, regardless of the original level,
-- before typechecking the expression.  For example:
559
--      f x = $( ...$(g 3) ... )
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
560
-- The recursive call to tcPolyExpr will simply expand the
561 562
-- inner escape before dealing with the outer one

563
tcTopSpliceExpr isTypedSplice tc_action
564 565
  = checkNoErrs $  -- checkNoErrs: must not try to run the thing
                   -- if the type checker fails!
ian@well-typed.com's avatar
ian@well-typed.com committed
566
    unsetGOptM Opt_DeferTypeErrors $
567 568 569 570 571
                   -- Don't defer type errors.  Not only are we
                   -- going to run this code, but we do an unsafe
                   -- coerce, so we get a seg-fault if, say we
                   -- splice a type into a place where an expression
                   -- is expected (Trac #7276)
572
    setStage (Splice isTypedSplice) $
573
    do {    -- Typecheck the expression
574 575
         (expr', wanted) <- captureConstraints tc_action
       ; const_binds     <- simplifyTop wanted
576

577
          -- Zonk it and tie the knot of dictionary bindings
578
       ; return $ mkHsDictLet (EvBinds const_binds) expr' }
579

Austin Seipp's avatar
Austin Seipp committed
580 581 582
{-
************************************************************************
*                                                                      *
583
        Annotations
Austin Seipp's avatar
Austin Seipp committed
584 585 586
*                                                                      *
************************************************************************
-}
587

588 589
runAnnotation target expr = do
    -- Find the classes we want instances for in order to call toAnnotationWrapper
590
    loc <- getSrcSpanM
591
    data_class <- tcLookupClass dataClassName
592
    to_annotation_wrapper_id <- tcLookupId toAnnotationWrapperName
593

594 595 596
    -- Check the instances we require live in another module (we want to execute it..)
    -- and check identifiers live in other modules using TH stage checks. tcSimplifyStagedExpr
    -- also resolves the LIE constraints to detect e.g. instance ambiguity
597
    zonked_wrapped_expr' <- zonkTopLExpr =<< tcTopSpliceExpr Untyped (
598
           do { (expr', expr_ty) <- tcInferRhoNC expr
599 600 601
                -- We manually wrap the typechecked expression in a call to toAnnotationWrapper
                -- By instantiating the call >here< it gets registered in the
                -- LIE consulted by tcTopSpliceExpr
602
                -- and hence ensures the appropriate dictionary is bound by const_binds
603
              ; wrapper <- instCall AnnOrigin [expr_ty] [mkClassPred data_class [expr_ty]]
604
              ; let specialised_to_annotation_wrapper_expr
605
                      = L loc (mkHsWrap wrapper
606 607
                                 (HsVar noExt (L loc to_annotation_wrapper_id)))
              ; return (L loc (HsApp noExt
608 609
                                specialised_to_annotation_wrapper_expr expr'))
                                })
610 611 612 613 614

    -- Run the appropriately wrapped expression to get the value of
    -- the annotation and its dictionaries. The return value is of
    -- type AnnotationWrapper by construction, so this conversion is
    -- safe
Luite Stegeman's avatar
Luite Stegeman committed
615 616 617 618 619 620
    serialized <- runMetaAW zonked_wrapped_expr'
    return Annotation {
               ann_target = target,
               ann_value = serialized
           }

621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642
convertAnnotationWrapper :: ForeignHValue -> TcM (Either MsgDoc Serialized)
convertAnnotationWrapper fhv = do
  dflags <- getDynFlags
  if gopt Opt_ExternalInterpreter dflags
    then do
      Right <$> runTH THAnnWrapper fhv
    else do
      annotation_wrapper <- liftIO $ wormhole dflags fhv
      return $ Right $
        case unsafeCoerce# annotation_wrapper of
           AnnotationWrapper value | let serialized = toSerialized serializeWithData value ->
               -- Got the value and dictionaries: build the serialized value and
               -- call it a day. We ensure that we seq the entire serialized value
               -- in order that any errors in the user-written code for the
               -- annotation are exposed at this point.  This is also why we are
               -- doing all this stuff inside the context of runMeta: it has the
               -- facilities to deal with user error in a meta-level expression
               seqSerialized serialized `seq` serialized

-- | Force the contents of the Serialized value so weknow it doesn't contain any bottoms
seqSerialized :: Serialized -> ()
seqSerialized (Serialized the_type bytes) = the_type `seq` bytes `seqList` ()
643

644

Austin Seipp's avatar
Austin Seipp committed
645 646 647
{-
************************************************************************
*                                                                      *
648
\subsection{Running an expression}
Austin Seipp's avatar
Austin Seipp committed
649 650 651
*                                                                      *
************************************************************************
-}
652

653 654 655
runQuasi :: TH.Q a -> TcM a
runQuasi act = TH.runQ act

656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678
runRemoteModFinalizers :: ThModFinalizers -> TcM ()
runRemoteModFinalizers (ThModFinalizers finRefs) = do
  dflags <- getDynFlags
  let withForeignRefs [] f = f []
      withForeignRefs (x : xs) f = withForeignRef x $ \r ->
        withForeignRefs xs $ \rs -> f (r : rs)
  if gopt Opt_ExternalInterpreter dflags then do
    hsc_env <- env_top <$> getEnv
    withIServ hsc_env $ \i -> do
      tcg <- getGblEnv
      th_state <- readTcRef (tcg_th_remote_state tcg)
      case th_state of
        Nothing -> return () -- TH was not started, nothing to do
        Just fhv -> do
          liftIO $ withForeignRef fhv $ \st ->
            withForeignRefs finRefs $ \qrefs ->
              writeIServ i (putMessage (RunModFinalizers st qrefs))
          () <- runRemoteTH i []
          readQResult i
  else do
    qs <- liftIO (withForeignRefs finRefs $ mapM localRef)
    runQuasi $ sequence_ qs

679 680 681 682 683 684 685 686 687
runQResult
  :: (a -> String)
  -> (SrcSpan -> a -> b)
  -> (ForeignHValue -> TcM a)
  -> SrcSpan
  -> ForeignHValue {- TH.Q a -}
  -> TcM b
runQResult show_th f runQ expr_span hval
  = do { th_result <- runQ hval
Luite Stegeman's avatar
Luite Stegeman committed
688 689
       ; traceTc "Got TH result:" (text (show_th th_result))
       ; return (f expr_span th_result) }
690

691

Luite Stegeman's avatar
Luite Stegeman committed
692
-----------------
693 694
runMeta :: (MetaHook TcM -> LHsExpr GhcTc -> TcM hs_syn)
        -> LHsExpr GhcTc
Luite Stegeman's avatar
Luite Stegeman committed
695 696 697 698 699 700 701
        -> TcM hs_syn
runMeta unwrap e
  = do { h <- getHooked runMetaHook defaultRunMeta
       ; unwrap h e }

defaultRunMeta :: MetaHook TcM
defaultRunMeta (MetaE r)
702
  = fmap r . runMeta' True ppr (runQResult TH.pprint convertToHsExpr runTHExp)
Luite Stegeman's avatar
Luite Stegeman committed
703
defaultRunMeta (MetaP r)
704
  = fmap r . runMeta' True ppr (runQResult TH.pprint convertToPat runTHPat)
Luite Stegeman's avatar
Luite Stegeman committed
705
defaultRunMeta (MetaT r)
706
  = fmap r . runMeta' True ppr (runQResult TH.pprint convertToHsType runTHType)
Luite Stegeman's avatar
Luite Stegeman committed
707
defaultRunMeta (MetaD r)
708
  = fmap r . runMeta' True ppr (runQResult TH.pprint convertToHsDecls runTHDec)
Luite Stegeman's avatar
Luite Stegeman committed
709
defaultRunMeta (MetaAW r)
710
  = fmap r . runMeta' False (const empty) (const convertAnnotationWrapper)
711
    -- We turn off showing the code in meta-level exceptions because doing so exposes
Gabor Greif's avatar
Gabor Greif committed
712
    -- the toAnnotationWrapper function that we slap around the user's code
713

Luite Stegeman's avatar
Luite Stegeman committed
714
----------------
715
runMetaAW :: LHsExpr GhcTc         -- Of type AnnotationWrapper
Luite Stegeman's avatar
Luite Stegeman committed
716 717
          -> TcM Serialized
runMetaAW = runMeta metaRequestAW
718

719 720
runMetaE :: LHsExpr GhcTc          -- Of type (Q Exp)
         -> TcM (LHsExpr GhcPs)
Luite Stegeman's avatar
Luite Stegeman committed
721
runMetaE = runMeta metaRequestE
722

723 724
runMetaP :: LHsExpr GhcTc          -- Of type (Q Pat)
         -> TcM (LPat GhcPs)
Luite Stegeman's avatar
Luite Stegeman committed
725
runMetaP = runMeta metaRequestP
gmainland's avatar
gmainland committed
726

727 728
runMetaT :: LHsExpr GhcTc          -- Of type (Q Type)
         -> TcM (LHsType GhcPs)
Luite Stegeman's avatar
Luite Stegeman committed
729
runMetaT = runMeta metaRequestT
730

731 732
runMetaD :: LHsExpr GhcTc          -- Of type Q [Dec]
         -> TcM [LHsDecl GhcPs]
Luite Stegeman's avatar
Luite Stegeman committed
733
runMetaD = runMeta metaRequestD
734 735

---------------
Luite Stegeman's avatar
Luite Stegeman committed
736 737
runMeta' :: Bool                 -- Whether code should be printed in the exception message
         -> (hs_syn -> SDoc)                                    -- how to print the code
738
         -> (SrcSpan -> ForeignHValue -> TcM (Either MsgDoc hs_syn))        -- How to run x
739 740
         -> LHsExpr GhcTc        -- Of type x; typically x = Q TH.Exp, or
                                 --    something like that
Luite Stegeman's avatar
Luite Stegeman committed
741 742
         -> TcM hs_syn           -- Of type t
runMeta' show_code ppr_hs run_and_convert expr
743
  = do  { traceTc "About to run" (ppr expr)
744 745
        ; recordThSpliceUse -- seems to be the best place to do this,
                            -- we catch all kinds of splices and annotations.
746

747 748 749 750 751 752 753 754 755 756
        -- Check that we've had no errors of any sort so far.
        -- For example, if we found an error in an earlier defn f, but
        -- recovered giving it type f :: forall a.a, it'd be very dodgy
        -- to carry ont.  Mind you, the staging restrictions mean we won't
        -- actually run f, but it still seems wrong. And, more concretely,
        -- see Trac #5358 for an example that fell over when trying to
        -- reify a function with a "?" kind in it.  (These don't occur
        -- in type-correct programs.
        ; failIfErrsM

757 758 759 760
        -- run plugins
        ; hsc_env <- getTopEnv
        ; expr' <- withPlugins (hsc_dflags hsc_env) spliceRunAction expr

761
        -- Desugar
762
        ; ds_expr <- initDsTc (dsLExpr expr')
763 764 765
        -- Compile and link it; might fail if linking fails
        ; src_span <- getSrcSpanM
        ; traceTc "About to run (desugared)" (ppr ds_expr)
Simon Peyton Jones's avatar
Simon Peyton Jones committed
766
        ; either_hval <- tryM $ liftIO $
767 768
                         HscMain.hscCompileCoreExpr hsc_env src_span ds_expr
        ; case either_hval of {
769
            Left exn   -> fail_with_exn "compile and link" exn ;
770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786
            Right hval -> do

        {       -- Coerce it to Q t, and run it

                -- Running might fail if it throws an exception of any kind (hence tryAllM)
                -- including, say, a pattern-match exception in the code we are running
                --
                -- We also do the TH -> HS syntax conversion inside the same
                -- exception-cacthing thing so that if there are any lurking
                -- exceptions in the data structure returned by hval, we'll
                -- encounter them inside the try
                --
                -- See Note [Exceptions in TH]
          let expr_span = getLoc expr
        ; either_tval <- tryAllM $
                         setSrcSpan expr_span $ -- Set the span so that qLocation can
                                                -- see where this splice is
787
             do { mb_result <- run_and_convert expr_span hval
788 789
                ; case mb_result of
                    Left err     -> failWithTc err
Luite Stegeman's avatar
Luite Stegeman committed
790
                    Right result -> do { traceTc "Got HsSyn result:" (ppr_hs result)
791
                                       ; return $! result } }
792

793 794 795 796
        ; case either_tval of
            Right v -> return v
            Left se -> case fromException se of
                         Just IOEnvFailure -> failM -- Error already in Tc monad
797
                         _ -> fail_with_exn "run" se -- Exception
798
        }}}
799
  where
800
    -- see Note [Concealed TH exceptions]
801
    fail_with_exn :: Exception e => String -> e -> TcM a
802 803 804 805
    fail_with_exn phase exn = do
        exn_msg <- liftIO $ Panic.safeShowException exn
        let msg = vcat [text "Exception when trying to" <+> text phase <+> text "compile-time code:",
                        nest 2 (text exn_msg),
Simon Peyton Jones's avatar
Simon Peyton Jones committed
806
                        if show_code then text "Code:" <+> ppr expr else empty]
807
        failWithTc msg
808

Austin Seipp's avatar
Austin Seipp committed
809
{-
810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861
Note [Running typed splices in the zonker]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

See #15471 for the full discussion.

For many years typed splices were run immediately after they were type checked
however, this is too early as it means to zonk some type variables before
they can be unified with type variables in the surrounding context.

For example,

```
module A where

test_foo :: forall a . Q (TExp (a -> a))
test_foo = [|| id ||]

module B where

import A

qux = $$(test_foo)
```

We would expect `qux` to have inferred type `forall a . a -> a` but if
we run the splices too early the unified variables are zonked to `Any`. The
inferred type is the unusable `Any -> Any`.

To run the splice, we must compile `test_foo` all the way to byte code.
But at the moment when the type checker is looking at the splice, test_foo
has type `Q (TExp (alpha -> alpha))` and we
certainly can't compile code involving unification variables!

We could default `alpha` to `Any` but then we infer `qux :: Any -> Any`
which definitely is not what we want.  Moreover, if we had
  qux = [$$(test_foo), (\x -> x +1::Int)]
then `alpha` would have to be `Int`.

Conclusion: we must defer taking decisions about `alpha` until the
typechecker is done; and *then* we can run the splice.  It's fine to do it
later, because we know it'll produce type-correct code.

Deferring running the splice until later, in the zonker, means that the
unification variables propagate upwards from the splice into the surrounding
context and are unified correctly.

This is implemented by storing the arguments we need for running the splice
in a `DelayedSplice`. In the zonker, the arguments are passed to
`TcSplice.runTopSplice` and the expression inserted into the AST as normal.



862 863
Note [Exceptions in TH]
~~~~~~~~~~~~~~~~~~~~~~~
Gabor Greif's avatar
Gabor Greif committed
864
Suppose we have something like this
865
        $( f 4 )
866
where
867 868 869
        f :: Int -> Q [Dec]
        f n | n>3       = fail "Too many declarations"
            | otherwise = ...
870 871 872 873 874 875

The 'fail' is a user-generated failure, and should be displayed as a
perfectly ordinary compiler error message, not a panic or anything
like that.  Here's how it's processed:

  * 'fail' is the monad fail.  The monad instance for Q in TH.Syntax
876 877
    effectively transforms (fail s) to
        qReport True s >> fail
878 879 880 881 882
    where 'qReport' comes from the Quasi class and fail from its monad
    superclass.

  * The TcM monad is an instance of Quasi (see TcSplice), and it implements
    (qReport True s) by using addErr to add an error message to the bag of errors.
883
    The 'fail' in TcM raises an IOEnvFailure exception
884

885 886 887 888 889 890
 * 'qReport' forces the message to ensure any exception hidden in unevaluated
   thunk doesn't get into the bag of errors. Otherwise the following splice
   will triger panic (Trac #8987):
        $(fail undefined)
   See also Note [Concealed TH exceptions]

891 892 893 894
  * So, when running a splice, we catch all exceptions; then for
        - an IOEnvFailure exception, we assume the error is already
                in the error-bag (above)
        - other errors, we add an error to the bag
895 896
    and then fail

897 898 899 900 901 902 903 904 905 906 907 908 909 910 911
Note [Concealed TH exceptions]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
When displaying the error message contained in an exception originated from TH
code, we need to make sure that the error message itself does not contain an
exception.  For example, when executing the following splice:

    $( error ("foo " ++ error "bar") )

the message for the outer exception is a thunk which will throw the inner
exception when evaluated.

For this reason, we display the message of a TH exception using the
'safeShowException' function, which recursively catches any exception thrown
when showing an error message.

912

913
To call runQ in the Tc monad, we need to make TcM an instance of Quasi:
Austin Seipp's avatar
Austin Seipp committed
914
-}
915

916
instance TH.Quasi TcM where
917 918 919
  qNewName s = do { u <- newUnique
                  ; let i = getKey u
                  ; return (TH.mkNameU s i) }
920

921 922 923
  -- 'msg' is forced to ensure exceptions don't escape,
  -- see Note [Exceptions in TH]
  qReport True msg  = seqList msg $ addErr  (text msg)
924
  qReport False msg = seqList msg $ addWarn NoReason (text msg)
925

926
  qLocation = do { m <- getModule
Ian Lynagh's avatar
Ian Lynagh committed
927 928 929 930 931 932 933
                 ; l <- getSrcSpanM
                 ; r <- case l of
                        UnhelpfulSpan _ -> pprPanic "qLocation: Unhelpful location"
                                                    (ppr l)
                        RealSrcSpan s -> return s
                 ; return (TH.Loc { TH.loc_filename = unpackFS (srcSpanFile r)
                                  , TH.loc_module   = moduleNameString (moduleName m)
934
                                  , TH.loc_package  = unitIdString (moduleUnitId m)
Ian Lynagh's avatar
Ian Lynagh committed
935 936 937
                                  , TH.loc_start = (srcSpanStartLine r, srcSpanStartCol r)
                                  , TH.loc_end = (srcSpanEndLine   r, srcSpanEndCol   r) }) }

938 939
  qLookupName       = lookupName
  qReify            = reify
Ryan Scott's avatar
Ryan Scott committed
940
  qReifyFixity nm   = lookupThName nm >>= reifyFixity
941 942 943
  qReifyInstances   = reifyInstances
  qReifyRoles       = reifyRoles
  qReifyAnnotations = reifyAnnotations
944
  qReifyModule      = reifyModule
945 946 947 948
  qReifyConStrictness nm = do { nm' <- lookupThName nm
                              ; dc  <- tcLookupDataCon nm'
                              ; let bangs = dataConImplBangs dc
                              ; return (map reifyDecidedStrictness bangs) }
949

950 951
        -- For qRecover, discard error messages if
        -- the recovery action is chosen.  Otherwise
952
        -- we'll only fail higher up.
953
  qRecover recover main = tryTcDiscardingErrs recover main
GregWeber's avatar
GregWeber committed
954 955 956 957 958

  qAddDependentFile fp = do
    ref <- fmap tcg_dependent_files getGblEnv
    dep_files <- readTcRef ref
    writeTcRef ref (fp:dep_files)
959

960 961 962 963
  qAddTempFile suffix = do
    dflags <- getDynFlags
    liftIO $ newTempName dflags TFL_GhcSession suffix

964 965 966 967
  qAddTopDecls thds = do
      l <- getSrcSpanM
      let either_hval = convertToHsDecls l thds
      ds <- case either_hval of
968 969 970
              Left exn -> failWithTc $
                hang (text "Error in a declaration passed to addTopDecls:")
                   2 exn
971 972 973 974 975
              Right ds -> return ds
      mapM_ (checkTopDecl . unLoc) ds
      th_topdecls_var <- fmap tcg_th_topdecls getGblEnv
      updTcRef th_topdecls_var (\topds -> ds ++ topds)
    where
976
      checkTopDecl :: HsDecl GhcPs -> TcM ()
977
      checkTopDecl (ValD _ binds)
978
        = mapM_ bindName (collectHsBindBinders binds)
979
      checkTopDecl (SigD _ _)
980
        = return ()
981
      checkTopDecl (AnnD _ _)
982
        = return ()
983
      checkTopDecl (ForD _ (ForeignImport { fd_name = L _ name }))
984 985
        = bindName name
      checkTopDecl _
986
        = addErr $ text "Only function, value, annotation, and foreign import declarations may be added with addTopDecl"
987

988 989 990
      bindName :: RdrName -> TcM ()
      bindName (Exact n)
        = do { th_topnames_var <- fmap tcg_th_topnames getGblEnv
991
             ; updTcRef th_topnames_var (\ns -> extendNameSet ns n)
992 993 994 995
             }

      bindName name =
          addErr $
996
          hang (text "The binder" <+> quotes (ppr name) <+> ptext (sLit "is not a NameU."))
997
             2 (text "Probable cause: you used mkName instead of newName to generate a binding.")
998

999
  qAddForeignFilePath lang fp = do
1000
    var <- fmap tcg_th_foreign_files getGblEnv
1001
    updTcRef var ((lang, fp) :)
1002

1003
  qAddModFinalizer fin = do
1004 1005 1006
      r <- liftIO $ mkRemoteRef fin
      fref <- liftIO $ mkForeignRef r (freeRemoteRef r)
      addModFinalizerRef fref
1007

1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023
  qAddCorePlugin plugin = do
      hsc_env <- env_top <$> getEnv
      r <- liftIO $ findHomeModule hsc_env (mkModuleName plugin)
      let err = hang
            (text "addCorePlugin: invalid plugin module "
               <+> text (show plugin)
            )
            2
            (text "Plugins in the current package can't be specified.")
      case r of
        Found {} -> addErr err
        FoundMultiple {} -> addErr err
        _ -> return ()
      th_coreplugins_var <- tcg_th_coreplugins <$> getGblEnv
      updTcRef th_coreplugins_var (plugin:)

1024
  qGetQ :: forall a. Typeable a => TcM (Maybe a)
1025 1026 1027
  qGetQ = do
      th_state_var <- fmap tcg_th_state getGblEnv
      th_state <- readTcRef th_state_var
1028
      -- See #10596 for why we use a scoped type variable here.
1029
      return (Map.lookup (typeRep (Proxy :: Proxy a)) th_state >>= fromDynamic)
1030 1031 1032 1033

  qPutQ x = do
      th_state_var <- fmap tcg_th_state getGblEnv
      updTcRef th_state_var (\m -> Map.insert (typeOf x) (toDyn x) m)
1034

1035 1036
  qIsExtEnabled = xoptM

1037 1038
  qExtsEnabled =
    EnumSet.toList . extensionFlags . hsc_dflags <$> getTopEnv
1039

1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051
-- | Adds a mod finalizer reference to the local environment.
addModFinalizerRef :: ForeignRef (TH.Q ()) -> TcM ()
addModFinalizerRef finRef = do
    th_stage <- getStage
    case th_stage of
      RunSplice th_modfinalizers_var -> updTcRef th_modfinalizers_var (finRef :)
      -- This case happens only if a splice is executed and the caller does
      -- not set the 'ThStage' to 'RunSplice' to collect finalizers.
      -- See Note [Delaying modFinalizers in untyped splices] in RnSplice.
      _ ->
        pprPanic "addModFinalizer was called when no finalizers were collected"
                 (ppr th_stage)
1052

1053
-- | Releases the external interpreter state.
1054 1055 1056
finishTH :: TcM ()
finishTH = do
  dflags <- getDynFlags
1057 1058
  when (gopt Opt_ExternalInterpreter dflags) $ do
    tcg <- getGblEnv
1059
    writeTcRef (tcg_th_remote_state tcg) Nothing
1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078

runTHExp :: ForeignHValue -> TcM TH.Exp
runTHExp = runTH THExp

runTHPat :: ForeignHValue -> TcM TH.Pat
runTHPat = runTH THPat

runTHType :: ForeignHValue -> TcM TH.Type
runTHType = runTH THType

runTHDec :: ForeignHValue -> TcM [TH.Dec]
runTHDec = runTH THDec

runTH :: Binary a => THResultType -> ForeignHValue -> TcM a
runTH ty fhv = do
  hsc_env <- env_top <$> getEnv
  dflags <- getDynFlags
  if not (gopt Opt_ExternalInterpreter dflags)
    then do
Simon Marlow's avatar
Simon Marlow committed
1079
       -- Run it in the local TcM
1080 1081 1082 1083
      hv <- liftIO $ wormhole dflags fhv
      r <- runQuasi (unsafeCoerce# hv :: TH.Q a)
      return r
    else
Simon Marlow's avatar
Simon Marlow committed
1084 1085 1086
      -- Run it on the server.  For an overview of how TH works with
      -- Remote GHCi, see Note [Remote Template Haskell] in
      -- libraries/ghci/GHCi/TH.hs.
1087 1088 1089 1090
      withIServ hsc_env $ \i -> do
        rstate <- getTHState i
        loc <- TH.qLocation
        liftIO $
1091 1092
          withForeignRef rstate $ \state_hv ->
          withForeignRef fhv $ \q_hv ->
1093
            writeIServ i (putMessage (RunTH state_hv q_hv ty (Just loc)))
1094 1095
        runRemoteTH i []
        bs <- readQResult i
1096 1097
        return $! runGet get (LB.fromStrict bs)

1098

Simon Marlow's avatar
Simon Marlow committed
1099 1100
-- | communicate with a remotely-running TH computation until it finishes.
-- See Note [Remote Template Haskell] in libraries/ghci/GHCi/TH.hs.
1101
runRemoteTH
1102
  :: IServ
1103
  -> [Messages]   --  saved from nested calls to qRecover
1104
  -> TcM ()
1105
runRemoteTH iserv recovers = do
1106
  THMsg msg <- liftIO $ readIServ iserv getTHMessage
1107
  case msg of
1108
    RunTHDone -> return ()
1109 1110 1111 1112 1113 1114
    StartRecover -> do -- Note [TH recover with -fexternal-interpreter]
      v <- getErrsVar
      msgs <- readTcRef v
      writeTcRef v emptyMessages
      runRemoteTH iserv (msgs : recovers)
    EndRecover caught_error -> do
1115
      let (prev_msgs@(prev_warns,prev_errs), rest) = case recovers of
1116 1117
             [] -> panic "EndRecover"
             a : b -> (a,b)
1118 1119 1120 1121 1122 1123
      v <- getErrsVar
      (warn_msgs,_) <- readTcRef v
      -- keep the warnings only if there were no errors
      writeTcRef v $ if caught_error
        then prev_msgs
        else (prev_warns `unionBags` warn_msgs, prev_errs)
Simon Marlow's avatar