{-
(c) The University of Glasgow 2006
(c) The GRASP/AQUA Project, Glasgow University, 1992-1998


TcSplice: Template Haskell splices
-}

{-# LANGUAGE CPP #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE MagicHash #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE InstanceSigs #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE MultiWayIf #-}
{-# LANGUAGE TypeFamilies #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}

module TcSplice(
     tcSpliceExpr, tcTypedBracket, tcUntypedBracket,
--     runQuasiQuoteExpr, runQuasiQuotePat,
--     runQuasiQuoteDecl, runQuasiQuoteType,
     runAnnotation,

     runMetaE, runMetaP, runMetaT, runMetaD, runQuasi,
     tcTopSpliceExpr, lookupThName_maybe,
     defaultRunMeta, runMeta', runRemoteModFinalizers,
     finishTH, runTopSplice
      ) where

#include "HsVersions.h"

import GhcPrelude

import GHC.Hs
import Annotations
import Finder
import Name
import TcRnMonad
import TcType

import Outputable
import TcExpr
import SrcLoc
import THNames
import TcUnify
import TcEnv
import TcOrigin
import Coercion( etaExpandCoAxBranch )
import FileCleanup ( newTempName, TempFileLifetime(..) )

import Control.Monad

import GHCi.Message
import GHCi.RemoteTypes
import GHCi
import HscMain
        -- These imports are the reason that TcSplice
        -- is very high up the module hierarchy
import RnSplice( traceSplice, SpliceInfo(..))
import RdrName
import HscTypes
import GHC.ThToHs
import RnExpr
import RnEnv
import RnUtils ( HsDocContext(..) )
import RnFixity ( lookupFixityRn_help )
import RnTypes
import TcHsSyn
import TcSimplify
import Type
import NameSet
import TcMType
import TcHsType
import TcIface
import TyCoRep
import FamInst
import FamInstEnv
import InstEnv
import Inst
import NameEnv
import PrelNames
import TysWiredIn
import OccName
import Hooks
import Var
import Module
import LoadIface
import Class
import TyCon
import CoAxiom
import PatSyn
import ConLike
import DataCon
import TcEvidence( TcEvBinds(..) )
import Id
import IdInfo
import DsExpr
import DsMonad
import GHC.Serialized
import ErrUtils
import Util
import Unique
import VarSet
import Data.List        ( find )
import Data.Maybe
import FastString
import BasicTypes hiding( SuccessFlag(..) )
import Maybes( MaybeErr(..) )
import DynFlags
import Panic
import Lexeme
import qualified EnumSet
import Plugins
import Bag

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

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

import Control.Exception
import Data.Binary
import Data.Binary.Get
import qualified Data.ByteString as B
import qualified Data.ByteString.Lazy as LB
import Data.Dynamic  ( fromDynamic, toDyn )
import qualified Data.Map as Map
import Data.Typeable ( typeOf, Typeable, TypeRep, typeRep )
import Data.Data (Data)
import Data.Proxy    ( Proxy (..) )
import GHC.Exts         ( unsafeCoerce# )

{-
************************************************************************
*                                                                      *
\subsection{Main interface + stubs for the non-GHCI case
*                                                                      *
************************************************************************
-}

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

-- runQuasiQuoteExpr :: HsQuasiQuote RdrName -> RnM (LHsExpr RdrName)
-- runQuasiQuotePat  :: HsQuasiQuote RdrName -> RnM (LPat RdrName)
-- runQuasiQuoteType :: HsQuasiQuote RdrName -> RnM (LHsType RdrName)
-- runQuasiQuoteDecl :: HsQuasiQuote RdrName -> RnM [LHsDecl RdrName]

runAnnotation     :: CoreAnnTarget -> LHsExpr GhcRn -> TcM Annotation
{-
************************************************************************
*                                                                      *
\subsection{Quoting an expression}
*                                                                      *
************************************************************************
-}

-- See Note [How brackets and nested splices are handled]
-- tcTypedBracket :: HsBracket Name -> TcRhoType -> TcM (HsExpr TcId)
tcTypedBracket :: HsExpr GhcRn
-> HsBracket GhcRn -> ExpRhoType -> TcM (HsExpr GhcTcId)
tcTypedBracket HsExpr GhcRn
rn_expr brack :: HsBracket GhcRn
brack@(TExpBr XTExpBr GhcRn
_ LHsExpr GhcRn
expr) ExpRhoType
res_ty
  = MsgDoc -> TcM (HsExpr GhcTcId) -> TcM (HsExpr GhcTcId)
forall a. MsgDoc -> TcM a -> TcM a
addErrCtxt (HsBracket GhcRn -> MsgDoc
quotationCtxtDoc HsBracket GhcRn
brack) (TcM (HsExpr GhcTcId) -> TcM (HsExpr GhcTcId))
-> TcM (HsExpr GhcTcId) -> TcM (HsExpr GhcTcId)
forall a b. (a -> b) -> a -> b
$
    do { ThStage
cur_stage <- TcM ThStage
getStage
       ; IORef [PendingTcSplice]
ps_ref <- [PendingTcSplice]
-> IOEnv (Env TcGblEnv TcLclEnv) (IORef [PendingTcSplice])
forall a env. a -> IOEnv env (IORef a)
newMutVar []
       ; TcRef WantedConstraints
lie_var <- TcM (TcRef WantedConstraints)
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
       ; (LHsExpr GhcTcId
_tc_expr, TcRhoType
expr_ty) <- ThStage
-> TcM (LHsExpr GhcTcId, TcRhoType)
-> TcM (LHsExpr GhcTcId, TcRhoType)
forall a. ThStage -> TcM a -> TcM a
setStage (ThStage -> PendingStuff -> ThStage
Brack ThStage
cur_stage (IORef [PendingTcSplice] -> TcRef WantedConstraints -> PendingStuff
TcPending IORef [PendingTcSplice]
ps_ref TcRef WantedConstraints
lie_var)) (TcM (LHsExpr GhcTcId, TcRhoType)
 -> TcM (LHsExpr GhcTcId, TcRhoType))
-> TcM (LHsExpr GhcTcId, TcRhoType)
-> TcM (LHsExpr GhcTcId, TcRhoType)
forall a b. (a -> b) -> a -> b
$
                                LHsExpr GhcRn -> TcM (LHsExpr GhcTcId, TcRhoType)
tcInferRhoNC LHsExpr GhcRn
expr
                                -- NC for no context; tcBracket does that
       ; let rep :: TcRhoType
rep = HasDebugCallStack => TcRhoType -> TcRhoType
TcRhoType -> TcRhoType
getRuntimeRep TcRhoType
expr_ty

       ; TcRhoType
meta_ty <- TcRhoType -> TcM TcRhoType
tcTExpTy TcRhoType
expr_ty
       ; [PendingTcSplice]
ps' <- IORef [PendingTcSplice]
-> IOEnv (Env TcGblEnv TcLclEnv) [PendingTcSplice]
forall a env. IORef a -> IOEnv env a
readMutVar IORef [PendingTcSplice]
ps_ref
       ; Id
texpco <- Name -> TcM Id
tcLookupId Name
unsafeTExpCoerceName
       ; CtOrigin
-> HsExpr GhcRn
-> HsExpr GhcTcId
-> TcRhoType
-> ExpRhoType
-> TcM (HsExpr GhcTcId)
tcWrapResultO (String -> CtOrigin
Shouldn'tHappenOrigin String
"TExpBr")
                       HsExpr GhcRn
rn_expr
                       (LHsExpr GhcTcId -> SrcSpanLess (LHsExpr GhcTcId)
forall a. HasSrcSpan a => a -> SrcSpanLess a
unLoc (LHsExpr GhcTcId -> LHsExpr GhcTcId -> LHsExpr GhcTcId
forall (id :: Pass).
LHsExpr (GhcPass id)
-> LHsExpr (GhcPass id) -> LHsExpr (GhcPass id)
mkHsApp (IdP GhcTcId -> [TcRhoType] -> LHsExpr GhcTcId
forall (id :: Pass).
IdP (GhcPass id) -> [TcRhoType] -> LHsExpr (GhcPass id)
nlHsTyApp Id
IdP GhcTcId
texpco [TcRhoType
rep, TcRhoType
expr_ty])
                                      (SrcSpanLess (LHsExpr GhcTcId) -> LHsExpr GhcTcId
forall a. HasSrcSpan a => SrcSpanLess a -> a
noLoc (XTcBracketOut GhcTcId
-> HsBracket GhcRn -> [PendingTcSplice] -> HsExpr GhcTcId
forall p.
XTcBracketOut p -> HsBracket GhcRn -> [PendingTcSplice] -> HsExpr p
HsTcBracketOut XTcBracketOut GhcTcId
NoExtField
noExtField HsBracket GhcRn
brack [PendingTcSplice]
ps'))))
                       TcRhoType
meta_ty ExpRhoType
res_ty }
tcTypedBracket HsExpr GhcRn
_ HsBracket GhcRn
other_brack ExpRhoType
_
  = String -> MsgDoc -> TcM (HsExpr GhcTcId)
forall a. HasCallStack => String -> MsgDoc -> a
pprPanic String
"tcTypedBracket" (HsBracket GhcRn -> MsgDoc
forall a. Outputable a => a -> MsgDoc
ppr HsBracket GhcRn
other_brack)

-- tcUntypedBracket :: HsBracket Name -> [PendingRnSplice] -> ExpRhoType -> TcM (HsExpr TcId)
tcUntypedBracket :: HsExpr GhcRn
-> HsBracket GhcRn
-> [PendingRnSplice]
-> ExpRhoType
-> TcM (HsExpr GhcTcId)
tcUntypedBracket HsExpr GhcRn
rn_expr HsBracket GhcRn
brack [PendingRnSplice]
ps ExpRhoType
res_ty
  = do { String -> MsgDoc -> TcRn ()
traceTc String
"tc_bracket untyped" (HsBracket GhcRn -> MsgDoc
forall a. Outputable a => a -> MsgDoc
ppr HsBracket GhcRn
brack MsgDoc -> MsgDoc -> MsgDoc
$$ [PendingRnSplice] -> MsgDoc
forall a. Outputable a => a -> MsgDoc
ppr [PendingRnSplice]
ps)
       ; [PendingTcSplice]
ps' <- (PendingRnSplice -> IOEnv (Env TcGblEnv TcLclEnv) PendingTcSplice)
-> [PendingRnSplice]
-> IOEnv (Env TcGblEnv TcLclEnv) [PendingTcSplice]
forall (t :: * -> *) (m :: * -> *) a b.
(Traversable t, Monad m) =>
(a -> m b) -> t a -> m (t b)
mapM PendingRnSplice -> IOEnv (Env TcGblEnv TcLclEnv) PendingTcSplice
tcPendingSplice [PendingRnSplice]
ps
       ; TcRhoType
meta_ty <- HsBracket GhcRn -> TcM TcRhoType
tcBrackTy HsBracket GhcRn
brack
       ; String -> MsgDoc -> TcRn ()
traceTc String
"tc_bracket done untyped" (TcRhoType -> MsgDoc
forall a. Outputable a => a -> MsgDoc
ppr TcRhoType
meta_ty)
       ; CtOrigin
-> HsExpr GhcRn
-> HsExpr GhcTcId
-> TcRhoType
-> ExpRhoType
-> TcM (HsExpr GhcTcId)
tcWrapResultO (String -> CtOrigin
Shouldn'tHappenOrigin String
"untyped bracket")
                       HsExpr GhcRn
rn_expr (XTcBracketOut GhcTcId
-> HsBracket GhcRn -> [PendingTcSplice] -> HsExpr GhcTcId
forall p.
XTcBracketOut p -> HsBracket GhcRn -> [PendingTcSplice] -> HsExpr p
HsTcBracketOut XTcBracketOut GhcTcId
NoExtField
noExtField HsBracket GhcRn
brack [PendingTcSplice]
ps') TcRhoType
meta_ty ExpRhoType
res_ty }

---------------
tcBrackTy :: HsBracket GhcRn -> TcM TcType
tcBrackTy :: HsBracket GhcRn -> TcM TcRhoType
tcBrackTy (VarBr {})  = Name -> TcM TcRhoType
tcMetaTy Name
nameTyConName
                                           -- Result type is Var (not Q-monadic)
tcBrackTy (ExpBr {})  = Name -> TcM TcRhoType
tcMetaTy Name
expQTyConName  -- Result type is ExpQ (= Q Exp)
tcBrackTy (TypBr {})  = Name -> TcM TcRhoType
tcMetaTy Name
typeQTyConName -- Result type is Type (= Q Typ)
tcBrackTy (DecBrG {}) = Name -> TcM TcRhoType
tcMetaTy Name
decsQTyConName -- Result type is Q [Dec]
tcBrackTy (PatBr {})  = Name -> TcM TcRhoType
tcMetaTy Name
patQTyConName  -- Result type is PatQ (= Q Pat)
tcBrackTy (DecBrL {}) = String -> TcM TcRhoType
forall a. String -> a
panic String
"tcBrackTy: Unexpected DecBrL"
tcBrackTy (TExpBr {}) = String -> TcM TcRhoType
forall a. String -> a
panic String
"tcUntypedBracket: Unexpected TExpBr"
tcBrackTy (XBracket XXBracket GhcRn
nec) = NoExtCon -> TcM TcRhoType
forall a. NoExtCon -> a
noExtCon XXBracket GhcRn
NoExtCon
nec

---------------
tcPendingSplice :: PendingRnSplice -> TcM PendingTcSplice
tcPendingSplice :: PendingRnSplice -> IOEnv (Env TcGblEnv TcLclEnv) PendingTcSplice
tcPendingSplice (PendingRnSplice UntypedSpliceFlavour
flavour Name
splice_name LHsExpr GhcRn
expr)
  = do { TcRhoType
res_ty <- Name -> TcM TcRhoType
tcMetaTy Name
meta_ty_name
       ; LHsExpr GhcTcId
expr' <- LHsExpr GhcRn -> ExpRhoType -> TcM (LHsExpr GhcTcId)
tcMonoExpr LHsExpr GhcRn
expr (TcRhoType -> ExpRhoType
mkCheckExpType TcRhoType
res_ty)
       ; PendingTcSplice -> IOEnv (Env TcGblEnv TcLclEnv) PendingTcSplice
forall (m :: * -> *) a. Monad m => a -> m a
return (Name -> LHsExpr GhcTcId -> PendingTcSplice
PendingTcSplice Name
splice_name LHsExpr GhcTcId
expr') }
  where
     meta_ty_name :: Name
meta_ty_name = case UntypedSpliceFlavour
flavour of
                       UntypedSpliceFlavour
UntypedExpSplice  -> Name
expQTyConName
                       UntypedSpliceFlavour
UntypedPatSplice  -> Name
patQTyConName
                       UntypedSpliceFlavour
UntypedTypeSplice -> Name
typeQTyConName
                       UntypedSpliceFlavour
UntypedDeclSplice -> Name
decsQTyConName

---------------
-- Takes a tau and returns the type Q (TExp tau)
tcTExpTy :: TcType -> TcM TcType
tcTExpTy :: TcRhoType -> TcM TcRhoType
tcTExpTy TcRhoType
exp_ty
  = do { Bool -> TcRn () -> TcRn ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
unless (TcRhoType -> Bool
isTauTy TcRhoType
exp_ty) (TcRn () -> TcRn ()) -> TcRn () -> TcRn ()
forall a b. (a -> b) -> a -> b
$ MsgDoc -> TcRn ()
addErr (TcRhoType -> MsgDoc
forall a. Outputable a => a -> MsgDoc
err_msg TcRhoType
exp_ty)
       ; TyCon
q    <- Name -> TcM TyCon
tcLookupTyCon Name
qTyConName
       ; TyCon
texp <- Name -> TcM TyCon
tcLookupTyCon Name
tExpTyConName
       ; let rep :: TcRhoType
rep = HasDebugCallStack => TcRhoType -> TcRhoType
TcRhoType -> TcRhoType
getRuntimeRep TcRhoType
exp_ty
       ; TcRhoType -> TcM TcRhoType
forall (m :: * -> *) a. Monad m => a -> m a
return (TyCon -> [TcRhoType] -> TcRhoType
mkTyConApp TyCon
q [TyCon -> [TcRhoType] -> TcRhoType
mkTyConApp TyCon
texp [TcRhoType
rep, TcRhoType
exp_ty]]) }
  where
    err_msg :: a -> MsgDoc
err_msg a
ty
      = [MsgDoc] -> MsgDoc
vcat [ String -> MsgDoc
text String
"Illegal polytype:" MsgDoc -> MsgDoc -> MsgDoc
<+> a -> MsgDoc
forall a. Outputable a => a -> MsgDoc
ppr a
ty
             , String -> MsgDoc
text String
"The type of a Typed Template Haskell expression must" MsgDoc -> MsgDoc -> MsgDoc
<+>
               String -> MsgDoc
text String
"not have any quantification." ]

quotationCtxtDoc :: HsBracket GhcRn -> SDoc
quotationCtxtDoc :: HsBracket GhcRn -> MsgDoc
quotationCtxtDoc HsBracket GhcRn
br_body
  = MsgDoc -> Int -> MsgDoc -> MsgDoc
hang (String -> MsgDoc
text String
"In the Template Haskell quotation")
         Int
2 (HsBracket GhcRn -> MsgDoc
forall a. Outputable a => a -> MsgDoc
ppr HsBracket GhcRn
br_body)


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

{-
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
     GHC.Hs syntax 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

     (The last step is different for decls, because they can *only* be
      top-level: we return the result of step 2.)

Note [How brackets and nested splices are handled]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
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

      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
         is why we leave the *renamed* expression attached to the bracket:
         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).

Example:
    Source:       f = [| Just $(g 3) |]
      The [| |] part is a HsBracket

    Typechecked:  f = [| Just ${s7}(g 3) |]{s7 = g Int 3}
      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

    Desugared:    f = do { s7 <- g Int 3
                         ; return (ConE "Data.Maybe.Just" s7) }


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

     Start here
         |
         V
      -----------     $      ------------   $
      |  Comp   | ---------> |  Splice  | -----|
      |   1     |            |    0     | <----|
      -----------            ------------
        ^     |                ^      |
      $ |     | [||]         $ |      | [||]
        |     v                |      v
   --------------          ----------------
   | Brack Comp |          | Brack Splice |
   |     2      |          |      1       |
   --------------          ----------------

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

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

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

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

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

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

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

* Variables are bound at the "current level"

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

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

When a variable is used, we compare
        bind:  binding level, and
        use:   current level at usage site

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

        bind = use      Always OK (bound same stage as used)
                        [| \x -> $(f [| x |]) |]

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

  For (bind < use) inside brackets, there are three cases:
    - 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 |]

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

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

-}

-- | We only want to produce warnings for TH-splices if the user requests so.
-- See Note [Warnings for TH splices].
getThSpliceOrigin :: TcM Origin
getThSpliceOrigin :: TcM Origin
getThSpliceOrigin = do
  Bool
warn <- GeneralFlag -> TcRnIf TcGblEnv TcLclEnv Bool
forall gbl lcl. GeneralFlag -> TcRnIf gbl lcl Bool
goptM GeneralFlag
Opt_EnableThSpliceWarnings
  if Bool
warn then Origin -> TcM Origin
forall (m :: * -> *) a. Monad m => a -> m a
return Origin
FromSource else Origin -> TcM Origin
forall (m :: * -> *) a. Monad m => a -> m a
return Origin
Generated

{- Note [Warnings for TH splices]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
We only produce warnings for TH splices when the user requests so
(-fenable-th-splice-warnings). There are multiple reasons:

  * It's not clear that the user that compiles a splice is the author of the code
    that produces the warning. Think of the situation where she just splices in
    code from a third-party library that produces incomplete pattern matches.
    In this scenario, the user isn't even able to fix that warning.
  * Gathering information for producing the warnings (pattern-match check
    warnings in particular) is costly. There's no point in doing so if the user
    is not interested in those warnings.

That's why we store Origin flags in the Haskell AST. The functions from ThToHs
take such a flag and depending on whether TH splice warnings were enabled or
not, we pass FromSource (if the user requests warnings) or Generated
(otherwise). This is implemented in getThSpliceOrigin.

For correct pattern-match warnings it's crucial that we annotate the Origin
consistently (#17270). In the future we could offer the Origin as part of the
TH AST. That would enable us to give quotes from the current module get
FromSource origin, and/or third library authors to tag certain parts of
generated code as FromSource to enable warnings. That effort is tracked in
#14838.
-}

{-
************************************************************************
*                                                                      *
\subsection{Splicing an expression}
*                                                                      *
************************************************************************
-}

tcSpliceExpr :: HsSplice GhcRn -> ExpRhoType -> TcM (HsExpr GhcTcId)
tcSpliceExpr splice :: HsSplice GhcRn
splice@(HsTypedSplice XTypedSplice GhcRn
_ SpliceDecoration
_ IdP GhcRn
name LHsExpr GhcRn
expr) ExpRhoType
res_ty
  = MsgDoc -> TcM (HsExpr GhcTcId) -> TcM (HsExpr GhcTcId)
forall a. MsgDoc -> TcM a -> TcM a
addErrCtxt (HsSplice GhcRn -> MsgDoc
spliceCtxtDoc HsSplice GhcRn
splice) (TcM (HsExpr GhcTcId) -> TcM (HsExpr GhcTcId))
-> TcM (HsExpr GhcTcId) -> TcM (HsExpr GhcTcId)
forall a b. (a -> b) -> a -> b
$
    SrcSpan -> TcM (HsExpr GhcTcId) -> TcM (HsExpr GhcTcId)
forall a. SrcSpan -> TcRn a -> TcRn a
setSrcSpan (LHsExpr GhcRn -> SrcSpan
forall a. HasSrcSpan a => a -> SrcSpan
getLoc LHsExpr GhcRn
expr)    (TcM (HsExpr GhcTcId) -> TcM (HsExpr GhcTcId))
-> TcM (HsExpr GhcTcId) -> TcM (HsExpr GhcTcId)
forall a b. (a -> b) -> a -> b
$ do
    { ThStage
stage <- TcM ThStage
getStage
    ; case ThStage
stage of
          Splice {}            -> LHsExpr GhcRn -> ExpRhoType -> TcM (HsExpr GhcTcId)
tcTopSplice LHsExpr GhcRn
expr ExpRhoType
res_ty
          Brack ThStage
pop_stage PendingStuff
pend -> ThStage
-> PendingStuff
-> Name
-> LHsExpr GhcRn
-> ExpRhoType
-> TcM (HsExpr GhcTcId)
tcNestedSplice ThStage
pop_stage PendingStuff
pend Name
IdP GhcRn
name LHsExpr GhcRn
expr ExpRhoType
res_ty
          RunSplice TcRef [ForeignRef (Q ())]
_          ->
            -- See Note [RunSplice ThLevel] in "TcRnTypes".
            String -> MsgDoc -> TcM (HsExpr GhcTcId)
forall a. HasCallStack => String -> MsgDoc -> a
pprPanic (String
"tcSpliceExpr: attempted to typecheck a splice when " String -> String -> String
forall a. [a] -> [a] -> [a]
++
                      String
"running another splice") (HsSplice GhcRn -> MsgDoc
forall a. Outputable a => a -> MsgDoc
ppr HsSplice GhcRn
splice)
          ThStage
Comp                 -> LHsExpr GhcRn -> ExpRhoType -> TcM (HsExpr GhcTcId)
tcTopSplice LHsExpr GhcRn
expr ExpRhoType
res_ty
    }
tcSpliceExpr HsSplice GhcRn
splice ExpRhoType
_
  = String -> MsgDoc -> TcM (HsExpr GhcTcId)
forall a. HasCallStack => String -> MsgDoc -> a
pprPanic String
"tcSpliceExpr" (HsSplice GhcRn -> MsgDoc
forall a. Outputable a => a -> MsgDoc
ppr HsSplice GhcRn
splice)

{- 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').

-}

tcNestedSplice :: ThStage -> PendingStuff -> Name
                -> LHsExpr GhcRn -> ExpRhoType -> TcM (HsExpr GhcTc)
    -- See Note [How brackets and nested splices are handled]
    -- A splice inside brackets
tcNestedSplice :: ThStage
-> PendingStuff
-> Name
-> LHsExpr GhcRn
-> ExpRhoType
-> TcM (HsExpr GhcTcId)
tcNestedSplice ThStage
pop_stage (TcPending IORef [PendingTcSplice]
ps_var TcRef WantedConstraints
lie_var) Name
splice_name LHsExpr GhcRn
expr ExpRhoType
res_ty
  = do { TcRhoType
res_ty <- ExpRhoType -> TcM TcRhoType
expTypeToType ExpRhoType
res_ty
       ; let rep :: TcRhoType
rep = HasDebugCallStack => TcRhoType -> TcRhoType
TcRhoType -> TcRhoType
getRuntimeRep TcRhoType
res_ty
       ; TcRhoType
meta_exp_ty <- TcRhoType -> TcM TcRhoType
tcTExpTy TcRhoType
res_ty
       ; LHsExpr GhcTcId
expr' <- ThStage -> TcM (LHsExpr GhcTcId) -> TcM (LHsExpr GhcTcId)
forall a. ThStage -> TcM a -> TcM a
setStage ThStage
pop_stage (TcM (LHsExpr GhcTcId) -> TcM (LHsExpr GhcTcId))
-> TcM (LHsExpr GhcTcId) -> TcM (LHsExpr GhcTcId)
forall a b. (a -> b) -> a -> b
$
                  TcRef WantedConstraints
-> TcM (LHsExpr GhcTcId) -> TcM (LHsExpr GhcTcId)
forall a. TcRef WantedConstraints -> TcM a -> TcM a
setConstraintVar TcRef WantedConstraints
lie_var (TcM (LHsExpr GhcTcId) -> TcM (LHsExpr GhcTcId))
-> TcM (LHsExpr GhcTcId) -> TcM (LHsExpr GhcTcId)
forall a b. (a -> b) -> a -> b
$
                  LHsExpr GhcRn -> ExpRhoType -> TcM (LHsExpr GhcTcId)
tcMonoExpr LHsExpr GhcRn
expr (TcRhoType -> ExpRhoType
mkCheckExpType TcRhoType
meta_exp_ty)
       ; Id
untypeq <- Name -> TcM Id
tcLookupId Name
unTypeQName
       ; let expr'' :: LHsExpr GhcTcId
expr'' = LHsExpr GhcTcId -> LHsExpr GhcTcId -> LHsExpr GhcTcId
forall (id :: Pass).
LHsExpr (GhcPass id)
-> LHsExpr (GhcPass id) -> LHsExpr (GhcPass id)
mkHsApp (IdP GhcTcId -> [TcRhoType] -> LHsExpr GhcTcId
forall (id :: Pass).
IdP (GhcPass id) -> [TcRhoType] -> LHsExpr (GhcPass id)
nlHsTyApp Id
IdP GhcTcId
untypeq [TcRhoType
rep, TcRhoType
res_ty]) LHsExpr GhcTcId
expr'
       ; [PendingTcSplice]
ps <- IORef [PendingTcSplice]
-> IOEnv (Env TcGblEnv TcLclEnv) [PendingTcSplice]
forall a env. IORef a -> IOEnv env a
readMutVar IORef [PendingTcSplice]
ps_var
       ; IORef [PendingTcSplice] -> [PendingTcSplice] -> TcRn ()
forall a env. IORef a -> a -> IOEnv env ()
writeMutVar IORef [PendingTcSplice]
ps_var (Name -> LHsExpr GhcTcId -> PendingTcSplice
PendingTcSplice Name
splice_name LHsExpr GhcTcId
expr'' PendingTcSplice -> [PendingTcSplice] -> [PendingTcSplice]
forall a. a -> [a] -> [a]
: [PendingTcSplice]
ps)

       -- The returned expression is ignored; it's in the pending splices
       ; HsExpr GhcTcId -> TcM (HsExpr GhcTcId)
forall (m :: * -> *) a. Monad m => a -> m a
return (String -> HsExpr GhcTcId
forall a. String -> a
panic String
"tcSpliceExpr") }

tcNestedSplice ThStage
_ PendingStuff
_ Name
splice_name LHsExpr GhcRn
_ ExpRhoType
_
  = String -> MsgDoc -> TcM (HsExpr GhcTcId)
forall a. HasCallStack => String -> MsgDoc -> a
pprPanic String
"tcNestedSplice: rename stage found" (Name -> MsgDoc
forall a. Outputable a => a -> MsgDoc
ppr Name
splice_name)

tcTopSplice :: LHsExpr GhcRn -> ExpRhoType -> TcM (HsExpr GhcTc)
tcTopSplice :: LHsExpr GhcRn -> ExpRhoType -> TcM (HsExpr GhcTcId)
tcTopSplice LHsExpr GhcRn
expr ExpRhoType
res_ty
  = do { -- Typecheck the expression,
         -- making sure it has type Q (T res_ty)
         TcRhoType
res_ty <- ExpRhoType -> TcM TcRhoType
expTypeToType ExpRhoType
res_ty
       ; TcRhoType
meta_exp_ty <- TcRhoType -> TcM TcRhoType
tcTExpTy TcRhoType
res_ty
       ; LHsExpr GhcTcId
q_expr <- SpliceType -> TcM (LHsExpr GhcTcId) -> TcM (LHsExpr GhcTcId)
tcTopSpliceExpr SpliceType
Typed (TcM (LHsExpr GhcTcId) -> TcM (LHsExpr GhcTcId))
-> TcM (LHsExpr GhcTcId) -> TcM (LHsExpr GhcTcId)
forall a b. (a -> b) -> a -> b
$
                          LHsExpr GhcRn -> ExpRhoType -> TcM (LHsExpr GhcTcId)
tcMonoExpr LHsExpr GhcRn
expr (TcRhoType -> ExpRhoType
mkCheckExpType TcRhoType
meta_exp_ty)
       ; TcLclEnv
lcl_env <- TcRnIf TcGblEnv TcLclEnv TcLclEnv
forall gbl lcl. TcRnIf gbl lcl lcl
getLclEnv
       ; let delayed_splice :: DelayedSplice
delayed_splice
              = TcLclEnv
-> LHsExpr GhcRn -> TcRhoType -> LHsExpr GhcTcId -> DelayedSplice
DelayedSplice TcLclEnv
lcl_env LHsExpr GhcRn
expr TcRhoType
res_ty LHsExpr GhcTcId
q_expr
       ; HsExpr GhcTcId -> TcM (HsExpr GhcTcId)
forall (m :: * -> *) a. Monad m => a -> m a
return (XSpliceE GhcTcId -> HsSplice GhcTcId -> HsExpr GhcTcId
forall p. XSpliceE p -> HsSplice p -> HsExpr p
HsSpliceE XSpliceE GhcTcId
NoExtField
noExtField (DelayedSplice -> HsSplice GhcTcId
forall id. DelayedSplice -> HsSplice id
HsSplicedT DelayedSplice
delayed_splice))

       }


-- This is called in the zonker
-- See Note [Running typed splices in the zonker]
runTopSplice :: DelayedSplice -> TcM (HsExpr GhcTc)
runTopSplice :: DelayedSplice -> TcM (HsExpr GhcTcId)
runTopSplice (DelayedSplice TcLclEnv
lcl_env LHsExpr GhcRn
orig_expr TcRhoType
res_ty LHsExpr GhcTcId
q_expr)
  = TcLclEnv -> TcM (HsExpr GhcTcId) -> TcM (HsExpr GhcTcId)
forall lcl' gbl a lcl.
lcl' -> TcRnIf gbl lcl' a -> TcRnIf gbl lcl a
setLclEnv TcLclEnv
lcl_env (TcM (HsExpr GhcTcId) -> TcM (HsExpr GhcTcId))
-> TcM (HsExpr GhcTcId) -> TcM (HsExpr GhcTcId)
forall a b. (a -> b) -> a -> b
$ do {
         TcRhoType
zonked_ty <- TcRhoType -> TcM TcRhoType
zonkTcType TcRhoType
res_ty
       ; LHsExpr GhcTcId
zonked_q_expr <- LHsExpr GhcTcId -> TcM (LHsExpr GhcTcId)
zonkTopLExpr LHsExpr GhcTcId
q_expr
        -- See Note [Collecting modFinalizers in typed splices].
       ; TcRef [ForeignRef (Q ())]
modfinalizers_ref <- [ForeignRef (Q ())]
-> TcRnIf TcGblEnv TcLclEnv (TcRef [ForeignRef (Q ())])
forall a gbl lcl. a -> TcRnIf gbl lcl (TcRef a)
newTcRef []
         -- Run the expression
       ; LHsExpr GhcPs
expr2 <- ThStage -> TcM (LHsExpr GhcPs) -> TcM (LHsExpr GhcPs)
forall a. ThStage -> TcM a -> TcM a
setStage (TcRef [ForeignRef (Q ())] -> ThStage
RunSplice TcRef [ForeignRef (Q ())]
modfinalizers_ref) (TcM (LHsExpr GhcPs) -> TcM (LHsExpr GhcPs))
-> TcM (LHsExpr GhcPs) -> TcM (LHsExpr GhcPs)
forall a b. (a -> b) -> a -> b
$
                    LHsExpr GhcTcId -> TcM (LHsExpr GhcPs)
runMetaE LHsExpr GhcTcId
zonked_q_expr
       ; [ForeignRef (Q ())]
mod_finalizers <- TcRef [ForeignRef (Q ())]
-> TcRnIf TcGblEnv TcLclEnv [ForeignRef (Q ())]
forall a gbl lcl. TcRef a -> TcRnIf gbl lcl a
readTcRef TcRef [ForeignRef (Q ())]
modfinalizers_ref
       ; ThModFinalizers -> TcRn ()
addModFinalizersWithLclEnv (ThModFinalizers -> TcRn ()) -> ThModFinalizers -> TcRn ()
forall a b. (a -> b) -> a -> b
$ [ForeignRef (Q ())] -> ThModFinalizers
ThModFinalizers [ForeignRef (Q ())]
mod_finalizers
       -- 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.
       ; SpliceInfo -> TcRn ()
traceSplice (SpliceInfo :: String -> Maybe (LHsExpr GhcRn) -> Bool -> MsgDoc -> SpliceInfo
SpliceInfo { spliceDescription :: String
spliceDescription = String
"expression"
                                 , spliceIsDecl :: Bool
spliceIsDecl      = Bool
False
                                 , spliceSource :: Maybe (LHsExpr GhcRn)
spliceSource      = LHsExpr GhcRn -> Maybe (LHsExpr GhcRn)
forall a. a -> Maybe a
Just LHsExpr GhcRn
orig_expr
                                 , spliceGenerated :: MsgDoc
spliceGenerated   = LHsExpr GhcPs -> MsgDoc
forall a. Outputable a => a -> MsgDoc
ppr LHsExpr GhcPs
expr2 })
        -- Rename and typecheck the spliced-in expression,
        -- making sure it has type res_ty
        -- These steps should never fail; this is a *typed* splice
       ; (LHsExpr GhcTcId
res, WantedConstraints
wcs) <-
            TcM (LHsExpr GhcTcId) -> TcM (LHsExpr GhcTcId, WantedConstraints)
forall a. TcM a -> TcM (a, WantedConstraints)
captureConstraints (TcM (LHsExpr GhcTcId) -> TcM (LHsExpr GhcTcId, WantedConstraints))
-> TcM (LHsExpr GhcTcId)
-> TcM (LHsExpr GhcTcId, WantedConstraints)
forall a b. (a -> b) -> a -> b
$
              MsgDoc -> TcM (LHsExpr GhcTcId) -> TcM (LHsExpr GhcTcId)
forall a. MsgDoc -> TcM a -> TcM a
addErrCtxt (LHsExpr GhcTcId -> MsgDoc
spliceResultDoc LHsExpr GhcTcId
zonked_q_expr) (TcM (LHsExpr GhcTcId) -> TcM (LHsExpr GhcTcId))
-> TcM (LHsExpr GhcTcId) -> TcM (LHsExpr GhcTcId)
forall a b. (a -> b) -> a -> b
$ do
                { (LHsExpr GhcRn
exp3, FreeVars
_fvs) <- LHsExpr GhcPs -> RnM (LHsExpr GhcRn, FreeVars)
rnLExpr LHsExpr GhcPs
expr2
                ; LHsExpr GhcRn -> ExpRhoType -> TcM (LHsExpr GhcTcId)
tcMonoExpr LHsExpr GhcRn
exp3 (TcRhoType -> ExpRhoType
mkCheckExpType TcRhoType
zonked_ty)}
       ; Bag EvBind
ev <- WantedConstraints -> TcM (Bag EvBind)
simplifyTop WantedConstraints
wcs
       ; HsExpr GhcTcId -> TcM (HsExpr GhcTcId)
forall (m :: * -> *) a. Monad m => a -> m a
return (HsExpr GhcTcId -> TcM (HsExpr GhcTcId))
-> HsExpr GhcTcId -> TcM (HsExpr GhcTcId)
forall a b. (a -> b) -> a -> b
$ LHsExpr GhcTcId -> SrcSpanLess (LHsExpr GhcTcId)
forall a. HasSrcSpan a => a -> SrcSpanLess a
unLoc (TcEvBinds -> LHsExpr GhcTcId -> LHsExpr GhcTcId
mkHsDictLet (Bag EvBind -> TcEvBinds
EvBinds Bag EvBind
ev) LHsExpr GhcTcId
res)
       }


{-
************************************************************************
*                                                                      *
\subsection{Error messages}
*                                                                      *
************************************************************************
-}

spliceCtxtDoc :: HsSplice GhcRn -> SDoc
spliceCtxtDoc :: HsSplice GhcRn -> MsgDoc
spliceCtxtDoc HsSplice GhcRn
splice
  = MsgDoc -> Int -> MsgDoc -> MsgDoc
hang (String -> MsgDoc
text String
"In the Template Haskell splice")
         Int
2 (HsSplice GhcRn -> MsgDoc
forall (p :: Pass).
OutputableBndrId p =>
HsSplice (GhcPass p) -> MsgDoc
pprSplice HsSplice GhcRn
splice)

spliceResultDoc :: LHsExpr GhcTc -> SDoc
spliceResultDoc :: LHsExpr GhcTcId -> MsgDoc
spliceResultDoc LHsExpr GhcTcId
expr
  = [MsgDoc] -> MsgDoc
sep [ String -> MsgDoc
text String
"In the result of the splice:"
        , Int -> MsgDoc -> MsgDoc
nest Int
2 (Char -> MsgDoc
char Char
'$' MsgDoc -> MsgDoc -> MsgDoc
<> LHsExpr GhcTcId -> MsgDoc
forall a. Outputable a => a -> MsgDoc
ppr LHsExpr GhcTcId
expr)
        , String -> MsgDoc
text String
"To see what the splice expanded to, use -ddump-splices"]

-------------------
tcTopSpliceExpr :: SpliceType -> TcM (LHsExpr GhcTc) -> TcM (LHsExpr GhcTc)
-- Note [How top-level splices are handled]
-- Type check an expression that is the body of a top-level splice
--   (the caller will compile and run it)
-- Note that set the level to Splice, regardless of the original level,
-- before typechecking the expression.  For example:
--      f x = $( ...$(g 3) ... )
-- The recursive call to tcPolyExpr will simply expand the
-- inner escape before dealing with the outer one

tcTopSpliceExpr :: SpliceType -> TcM (LHsExpr GhcTcId) -> TcM (LHsExpr GhcTcId)
tcTopSpliceExpr SpliceType
isTypedSplice TcM (LHsExpr GhcTcId)
tc_action
  = TcM (LHsExpr GhcTcId) -> TcM (LHsExpr GhcTcId)
forall r. TcM r -> TcM r
checkNoErrs (TcM (LHsExpr GhcTcId) -> TcM (LHsExpr GhcTcId))
-> TcM (LHsExpr GhcTcId) -> TcM (LHsExpr GhcTcId)
forall a b. (a -> b) -> a -> b
$  -- checkNoErrs: must not try to run the thing
                   -- if the type checker fails!
    GeneralFlag -> TcM (LHsExpr GhcTcId) -> TcM (LHsExpr GhcTcId)
forall gbl lcl a.
GeneralFlag -> TcRnIf gbl lcl a -> TcRnIf gbl lcl a
unsetGOptM GeneralFlag
Opt_DeferTypeErrors (TcM (LHsExpr GhcTcId) -> TcM (LHsExpr GhcTcId))
-> TcM (LHsExpr GhcTcId) -> TcM (LHsExpr GhcTcId)
forall a b. (a -> b) -> a -> b
$
                   -- 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 (#7276)
    ThStage -> TcM (LHsExpr GhcTcId) -> TcM (LHsExpr GhcTcId)
forall a. ThStage -> TcM a -> TcM a
setStage (SpliceType -> ThStage
Splice SpliceType
isTypedSplice) (TcM (LHsExpr GhcTcId) -> TcM (LHsExpr GhcTcId))
-> TcM (LHsExpr GhcTcId) -> TcM (LHsExpr GhcTcId)
forall a b. (a -> b) -> a -> b
$
    do {    -- Typecheck the expression
         (LHsExpr GhcTcId
expr', WantedConstraints
wanted) <- TcM (LHsExpr GhcTcId) -> TcM (LHsExpr GhcTcId, WantedConstraints)
forall a. TcM a -> TcM (a, WantedConstraints)
captureConstraints TcM (LHsExpr GhcTcId)
tc_action
       ; Bag EvBind
const_binds     <- WantedConstraints -> TcM (Bag EvBind)
simplifyTop WantedConstraints
wanted

          -- Zonk it and tie the knot of dictionary bindings
       ; LHsExpr GhcTcId -> TcM (LHsExpr GhcTcId)
forall (m :: * -> *) a. Monad m => a -> m a
return (LHsExpr GhcTcId -> TcM (LHsExpr GhcTcId))
-> LHsExpr GhcTcId -> TcM (LHsExpr GhcTcId)
forall a b. (a -> b) -> a -> b
$ TcEvBinds -> LHsExpr GhcTcId -> LHsExpr GhcTcId
mkHsDictLet (Bag EvBind -> TcEvBinds
EvBinds Bag EvBind
const_binds) LHsExpr GhcTcId
expr' }

{-
************************************************************************
*                                                                      *
        Annotations
*                                                                      *
************************************************************************
-}

runAnnotation :: CoreAnnTarget -> LHsExpr GhcRn -> TcM Annotation
runAnnotation CoreAnnTarget
target LHsExpr GhcRn
expr = do
    -- Find the classes we want instances for in order to call toAnnotationWrapper
    SrcSpan
loc <- TcRn SrcSpan
getSrcSpanM
    Class
data_class <- Name -> TcM Class
tcLookupClass Name
dataClassName
    Id
to_annotation_wrapper_id <- Name -> TcM Id
tcLookupId Name
toAnnotationWrapperName

    -- 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
    LHsExpr GhcTcId
zonked_wrapped_expr' <- LHsExpr GhcTcId -> TcM (LHsExpr GhcTcId)
zonkTopLExpr (LHsExpr GhcTcId -> TcM (LHsExpr GhcTcId))
-> TcM (LHsExpr GhcTcId) -> TcM (LHsExpr GhcTcId)
forall (m :: * -> *) a b. Monad m => (a -> m b) -> m a -> m b
=<< SpliceType -> TcM (LHsExpr GhcTcId) -> TcM (LHsExpr GhcTcId)
tcTopSpliceExpr SpliceType
Untyped (
           do { (LHsExpr GhcTcId
expr', TcRhoType
expr_ty) <- LHsExpr GhcRn -> TcM (LHsExpr GhcTcId, TcRhoType)
tcInferRhoNC LHsExpr GhcRn
expr
                -- 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
                -- and hence ensures the appropriate dictionary is bound by const_binds
              ; HsWrapper
wrapper <- CtOrigin -> [TcRhoType] -> [TcRhoType] -> TcM HsWrapper
instCall CtOrigin
AnnOrigin [TcRhoType
expr_ty] [Class -> [TcRhoType] -> TcRhoType
mkClassPred Class
data_class [TcRhoType
expr_ty]]
              ; let specialised_to_annotation_wrapper_expr :: LHsExpr GhcTcId
specialised_to_annotation_wrapper_expr
                      = SrcSpan -> HsExpr GhcTcId -> LHsExpr GhcTcId
forall l e. l -> e -> GenLocated l e
L SrcSpan
loc (HsWrapper -> HsExpr GhcTcId -> HsExpr GhcTcId
forall (id :: Pass).
HsWrapper -> HsExpr (GhcPass id) -> HsExpr (GhcPass id)
mkHsWrap HsWrapper
wrapper
                                 (XVar GhcTcId -> Located (IdP GhcTcId) -> HsExpr GhcTcId
forall p. XVar p -> Located (IdP p) -> HsExpr p
HsVar XVar GhcTcId
NoExtField
noExtField (SrcSpan -> Id -> GenLocated SrcSpan Id
forall l e. l -> e -> GenLocated l e
L SrcSpan
loc Id
to_annotation_wrapper_id)))
              ; LHsExpr GhcTcId -> TcM (LHsExpr GhcTcId)
forall (m :: * -> *) a. Monad m => a -> m a
return (SrcSpan -> HsExpr GhcTcId -> LHsExpr GhcTcId
forall l e. l -> e -> GenLocated l e
L SrcSpan
loc (XApp GhcTcId
-> LHsExpr GhcTcId -> LHsExpr GhcTcId -> HsExpr GhcTcId
forall p. XApp p -> LHsExpr p -> LHsExpr p -> HsExpr p
HsApp XApp GhcTcId
NoExtField
noExtField
                                LHsExpr GhcTcId
specialised_to_annotation_wrapper_expr LHsExpr GhcTcId
expr'))
                                })

    -- 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
    Serialized
serialized <- LHsExpr GhcTcId -> TcM Serialized
runMetaAW LHsExpr GhcTcId
zonked_wrapped_expr'
    Annotation -> TcM Annotation
forall (m :: * -> *) a. Monad m => a -> m a
return Annotation :: CoreAnnTarget -> Serialized -> Annotation
Annotation {
               ann_target :: CoreAnnTarget
ann_target = CoreAnnTarget
target,
               ann_value :: Serialized
ann_value = Serialized
serialized
           }

convertAnnotationWrapper :: ForeignHValue -> TcM (Either MsgDoc Serialized)
convertAnnotationWrapper :: ForeignHValue -> TcM (Either MsgDoc Serialized)
convertAnnotationWrapper ForeignHValue
fhv = do
  DynFlags
dflags <- IOEnv (Env TcGblEnv TcLclEnv) DynFlags
forall (m :: * -> *). HasDynFlags m => m DynFlags
getDynFlags
  if GeneralFlag -> DynFlags -> Bool
gopt GeneralFlag
Opt_ExternalInterpreter DynFlags
dflags
    then do
      Serialized -> Either MsgDoc Serialized
forall a b. b -> Either a b
Right (Serialized -> Either MsgDoc Serialized)
-> TcM Serialized -> TcM (Either MsgDoc Serialized)
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> THResultType -> ForeignHValue -> TcM Serialized
forall a. Binary a => THResultType -> ForeignHValue -> TcM a
runTH THResultType
THAnnWrapper ForeignHValue
fhv
    else do
      HValue
annotation_wrapper <- IO HValue -> IOEnv (Env TcGblEnv TcLclEnv) HValue
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IO HValue -> IOEnv (Env TcGblEnv TcLclEnv) HValue)
-> IO HValue -> IOEnv (Env TcGblEnv TcLclEnv) HValue
forall a b. (a -> b) -> a -> b
$ DynFlags -> ForeignHValue -> IO HValue
forall a. DynFlags -> ForeignRef a -> IO a
wormhole DynFlags
dflags ForeignHValue
fhv
      Either MsgDoc Serialized -> TcM (Either MsgDoc Serialized)
forall (m :: * -> *) a. Monad m => a -> m a
return (Either MsgDoc Serialized -> TcM (Either MsgDoc Serialized))
-> Either MsgDoc Serialized -> TcM (Either MsgDoc Serialized)
forall a b. (a -> b) -> a -> b
$ Serialized -> Either MsgDoc Serialized
forall a b. b -> Either a b
Right (Serialized -> Either MsgDoc Serialized)
-> Serialized -> Either MsgDoc Serialized
forall a b. (a -> b) -> a -> b
$
        case HValue -> AnnotationWrapper
unsafeCoerce# HValue
annotation_wrapper of
           AnnotationWrapper a
value | let serialized :: Serialized
serialized = (a -> [Word8]) -> a -> Serialized
forall a. Typeable a => (a -> [Word8]) -> a -> Serialized
toSerialized a -> [Word8]
forall a. Data a => a -> [Word8]
serializeWithData a
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
               Serialized -> ()
seqSerialized Serialized
serialized () -> Serialized -> Serialized
`seq` Serialized
serialized

-- | Force the contents of the Serialized value so weknow it doesn't contain any bottoms
seqSerialized :: Serialized -> ()
seqSerialized :: Serialized -> ()
seqSerialized (Serialized TypeRep
the_type [Word8]
bytes) = TypeRep
the_type TypeRep -> () -> ()
`seq` [Word8]
bytes [Word8] -> () -> ()
forall a b. [a] -> b -> b
`seqList` ()


{-
************************************************************************
*                                                                      *
\subsection{Running an expression}
*                                                                      *
************************************************************************
-}

runQuasi :: TH.Q a -> TcM a
runQuasi :: Q a -> TcM a
runQuasi Q a
act = Q a -> TcM a
forall (m :: * -> *) a. Quasi m => Q a -> m a
TH.runQ Q a
act

runRemoteModFinalizers :: ThModFinalizers -> TcM ()
runRemoteModFinalizers :: ThModFinalizers -> TcRn ()
runRemoteModFinalizers (ThModFinalizers [ForeignRef (Q ())]
finRefs) = do
  DynFlags
dflags <- IOEnv (Env TcGblEnv TcLclEnv) DynFlags
forall (m :: * -> *). HasDynFlags m => m DynFlags
getDynFlags
  let withForeignRefs :: [ForeignRef a] -> ([RemoteRef a] -> IO b) -> IO b
withForeignRefs [] [RemoteRef a] -> IO b
f = [RemoteRef a] -> IO b
f []
      withForeignRefs (ForeignRef a
x : [ForeignRef a]
xs) [RemoteRef a] -> IO b
f = ForeignRef a -> (RemoteRef a -> IO b) -> IO b
forall a b. ForeignRef a -> (RemoteRef a -> IO b) -> IO b
withForeignRef ForeignRef a
x ((RemoteRef a -> IO b) -> IO b) -> (RemoteRef a -> IO b) -> IO b
forall a b. (a -> b) -> a -> b
$ \RemoteRef a
r ->
        [ForeignRef a] -> ([RemoteRef a] -> IO b) -> IO b
withForeignRefs [ForeignRef a]
xs (([RemoteRef a] -> IO b) -> IO b)
-> ([RemoteRef a] -> IO b) -> IO b
forall a b. (a -> b) -> a -> b
$ \[RemoteRef a]
rs -> [RemoteRef a] -> IO b
f (RemoteRef a
r RemoteRef a -> [RemoteRef a] -> [RemoteRef a]
forall a. a -> [a] -> [a]
: [RemoteRef a]
rs)
  if GeneralFlag -> DynFlags -> Bool
gopt GeneralFlag
Opt_ExternalInterpreter DynFlags
dflags then do
    HscEnv
hsc_env <- Env TcGblEnv TcLclEnv -> HscEnv
forall gbl lcl. Env gbl lcl -> HscEnv
env_top (Env TcGblEnv TcLclEnv -> HscEnv)
-> IOEnv (Env TcGblEnv TcLclEnv) (Env TcGblEnv TcLclEnv)
-> IOEnv (Env TcGblEnv TcLclEnv) HscEnv
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> IOEnv (Env TcGblEnv TcLclEnv) (Env TcGblEnv TcLclEnv)
forall env. IOEnv env env
getEnv
    HscEnv -> (IServ -> TcRn ()) -> TcRn ()
forall (m :: * -> *) a.
(MonadIO m, ExceptionMonad m) =>
HscEnv -> (IServ -> m a) -> m a
withIServ HscEnv
hsc_env ((IServ -> TcRn ()) -> TcRn ()) -> (IServ -> TcRn ()) -> TcRn ()
forall a b. (a -> b) -> a -> b
$ \IServ
i -> do
      TcGblEnv
tcg <- TcRnIf TcGblEnv TcLclEnv TcGblEnv
forall gbl lcl. TcRnIf gbl lcl gbl
getGblEnv
      Maybe (ForeignRef (IORef QState))
th_state <- TcRef (Maybe (ForeignRef (IORef QState)))
-> TcRnIf TcGblEnv TcLclEnv (Maybe (ForeignRef (IORef QState)))
forall a gbl lcl. TcRef a -> TcRnIf gbl lcl a
readTcRef (TcGblEnv -> TcRef (Maybe (ForeignRef (IORef QState)))
tcg_th_remote_state TcGblEnv
tcg)
      case Maybe (ForeignRef (IORef QState))
th_state of
        Maybe (ForeignRef (IORef QState))
Nothing -> () -> TcRn ()
forall (m :: * -> *) a. Monad m => a -> m a
return () -- TH was not started, nothing to do
        Just ForeignRef (IORef QState)
fhv -> do
          IO () -> TcRn ()
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IO () -> TcRn ()) -> IO () -> TcRn ()
forall a b. (a -> b) -> a -> b
$ ForeignRef (IORef QState)
-> (RemoteRef (IORef QState) -> IO ()) -> IO ()
forall a b. ForeignRef a -> (RemoteRef a -> IO b) -> IO b
withForeignRef ForeignRef (IORef QState)
fhv ((RemoteRef (IORef QState) -> IO ()) -> IO ())
-> (RemoteRef (IORef QState) -> IO ()) -> IO ()
forall a b. (a -> b) -> a -> b
$ \RemoteRef (IORef QState)
st ->
            [ForeignRef (Q ())] -> ([RemoteRef (Q ())] -> IO ()) -> IO ()
forall a b. [ForeignRef a] -> ([RemoteRef a] -> IO b) -> IO b
withForeignRefs [ForeignRef (Q ())]
finRefs (([RemoteRef (Q ())] -> IO ()) -> IO ())
-> ([RemoteRef (Q ())] -> IO ()) -> IO ()
forall a b. (a -> b) -> a -> b
$ \[RemoteRef (Q ())]
qrefs ->
              IServ -> Put -> IO ()
writeIServ IServ
i (Message (QResult ()) -> Put
forall a. Message a -> Put
putMessage (RemoteRef (IORef QState)
-> [RemoteRef (Q ())] -> Message (QResult ())
RunModFinalizers RemoteRef (IORef QState)
st [RemoteRef (Q ())]
qrefs))
          () <- IServ -> [Messages] -> TcRn ()
runRemoteTH IServ
i []
          IServ -> TcRn ()
forall a. Binary a => IServ -> TcM a
readQResult IServ
i
  else do
    [Q ()]
qs <- IO [Q ()] -> IOEnv (Env TcGblEnv TcLclEnv) [Q ()]
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO ([ForeignRef (Q ())]
-> ([RemoteRef (Q ())] -> IO [Q ()]) -> IO [Q ()]
forall a b. [ForeignRef a] -> ([RemoteRef a] -> IO b) -> IO b
withForeignRefs [ForeignRef (Q ())]
finRefs (([RemoteRef (Q ())] -> IO [Q ()]) -> IO [Q ()])
-> ([RemoteRef (Q ())] -> IO [Q ()]) -> IO [Q ()]
forall a b. (a -> b) -> a -> b
$ (RemoteRef (Q ()) -> IO (Q ())) -> [RemoteRef (Q ())] -> IO [Q ()]
forall (t :: * -> *) (m :: * -> *) a b.
(Traversable t, Monad m) =>
(a -> m b) -> t a -> m (t b)
mapM RemoteRef (Q ()) -> IO (Q ())
forall a. RemoteRef a -> IO a
localRef)
    Q () -> TcRn ()
forall a. Q a -> TcM a
runQuasi (Q () -> TcRn ()) -> Q () -> TcRn ()
forall a b. (a -> b) -> a -> b
$ [Q ()] -> Q ()
forall (t :: * -> *) (m :: * -> *) a.
(Foldable t, Monad m) =>
t (m a) -> m ()
sequence_ [Q ()]
qs

runQResult
  :: (a -> String)
  -> (Origin -> SrcSpan -> a -> b)
  -> (ForeignHValue -> TcM a)
  -> SrcSpan
  -> ForeignHValue {- TH.Q a -}
  -> TcM b
runQResult :: (a -> String)
-> (Origin -> SrcSpan -> a -> b)
-> (ForeignHValue -> TcM a)
-> SrcSpan
-> ForeignHValue
-> TcM b
runQResult a -> String
show_th Origin -> SrcSpan -> a -> b
f ForeignHValue -> TcM a
runQ SrcSpan
expr_span ForeignHValue
hval
  = do { a
th_result <- ForeignHValue -> TcM a
runQ ForeignHValue
hval
       ; Origin
th_origin <- TcM Origin
getThSpliceOrigin
       ; String -> MsgDoc -> TcRn ()
traceTc String
"Got TH result:" (String -> MsgDoc
text (a -> String
show_th a
th_result))
       ; b -> TcM b
forall (m :: * -> *) a. Monad m => a -> m a
return (Origin -> SrcSpan -> a -> b
f Origin
th_origin SrcSpan
expr_span a
th_result) }


-----------------
runMeta :: (MetaHook TcM -> LHsExpr GhcTc -> TcM hs_syn)
        -> LHsExpr GhcTc
        -> TcM hs_syn
runMeta :: (MetaHook TcM -> LHsExpr GhcTcId -> TcM hs_syn)
-> LHsExpr GhcTcId -> TcM hs_syn
runMeta MetaHook TcM -> LHsExpr GhcTcId -> TcM hs_syn
unwrap LHsExpr GhcTcId
e
  = do { MetaHook TcM
h <- (Hooks -> Maybe (MetaHook TcM))
-> MetaHook TcM -> IOEnv (Env TcGblEnv TcLclEnv) (MetaHook TcM)
forall (f :: * -> *) a.
(Functor f, HasDynFlags f) =>
(Hooks -> Maybe a) -> a -> f a
getHooked Hooks -> Maybe (MetaHook TcM)
runMetaHook MetaHook TcM
defaultRunMeta
       ; MetaHook TcM -> LHsExpr GhcTcId -> TcM hs_syn
unwrap MetaHook TcM
h LHsExpr GhcTcId
e }

defaultRunMeta :: MetaHook TcM
defaultRunMeta :: MetaHook TcM
defaultRunMeta (MetaE LHsExpr GhcPs -> MetaResult
r)
  = (LHsExpr GhcPs -> MetaResult)
-> TcM (LHsExpr GhcPs) -> IOEnv (Env TcGblEnv TcLclEnv) MetaResult
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap LHsExpr GhcPs -> MetaResult
r (TcM (LHsExpr GhcPs) -> IOEnv (Env TcGblEnv TcLclEnv) MetaResult)
-> (LHsExpr GhcTcId -> TcM (LHsExpr GhcPs))
-> LHsExpr GhcTcId
-> IOEnv (Env TcGblEnv TcLclEnv) MetaResult
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Bool
-> (LHsExpr GhcPs -> MsgDoc)
-> (SrcSpan
    -> ForeignHValue -> TcM (Either MsgDoc (LHsExpr GhcPs)))
-> LHsExpr GhcTcId
-> TcM (LHsExpr GhcPs)
forall hs_syn.
Bool
-> (hs_syn -> MsgDoc)
-> (SrcSpan -> ForeignHValue -> TcM (Either MsgDoc hs_syn))
-> LHsExpr GhcTcId
-> TcM hs_syn
runMeta' Bool
True LHsExpr GhcPs -> MsgDoc
forall a. Outputable a => a -> MsgDoc
ppr ((Exp -> String)
-> (Origin -> SrcSpan -> Exp -> Either MsgDoc (LHsExpr GhcPs))
-> (ForeignHValue -> TcM Exp)
-> SrcSpan
-> ForeignHValue
-> TcM (Either MsgDoc (LHsExpr GhcPs))
forall a b.
(a -> String)
-> (Origin -> SrcSpan -> a -> b)
-> (ForeignHValue -> TcM a)
-> SrcSpan
-> ForeignHValue
-> TcM b
runQResult Exp -> String
forall a. Ppr a => a -> String
TH.pprint Origin -> SrcSpan -> Exp -> Either MsgDoc (LHsExpr GhcPs)
convertToHsExpr ForeignHValue -> TcM Exp
runTHExp)
defaultRunMeta (MetaP LPat GhcPs -> MetaResult
r)
  = (Located (Pat GhcPs) -> MetaResult)
-> IOEnv (Env TcGblEnv TcLclEnv) (Located (Pat GhcPs))
-> IOEnv (Env TcGblEnv TcLclEnv) MetaResult
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap Located (Pat GhcPs) -> MetaResult
LPat GhcPs -> MetaResult
r (IOEnv (Env TcGblEnv TcLclEnv) (Located (Pat GhcPs))
 -> IOEnv (Env TcGblEnv TcLclEnv) MetaResult)
-> (LHsExpr GhcTcId
    -> IOEnv (Env TcGblEnv TcLclEnv) (Located (Pat GhcPs)))
-> LHsExpr GhcTcId
-> IOEnv (Env TcGblEnv TcLclEnv) MetaResult
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Bool
-> (Located (Pat GhcPs) -> MsgDoc)
-> (SrcSpan
    -> ForeignHValue -> TcM (Either MsgDoc (Located (Pat GhcPs))))
-> LHsExpr GhcTcId
-> IOEnv (Env TcGblEnv TcLclEnv) (Located (Pat GhcPs))
forall hs_syn.
Bool
-> (hs_syn -> MsgDoc)
-> (SrcSpan -> ForeignHValue -> TcM (Either MsgDoc hs_syn))
-> LHsExpr GhcTcId
-> TcM hs_syn
runMeta' Bool
True Located (Pat GhcPs) -> MsgDoc
forall a. Outputable a => a -> MsgDoc
ppr ((Pat -> String)
-> (Origin
    -> SrcSpan -> Pat -> Either MsgDoc (Located (Pat GhcPs)))
-> (ForeignHValue -> TcM Pat)
-> SrcSpan
-> ForeignHValue
-> TcM (Either MsgDoc (Located (Pat GhcPs)))
forall a b.
(a -> String)
-> (Origin -> SrcSpan -> a -> b)
-> (ForeignHValue -> TcM a)
-> SrcSpan
-> ForeignHValue
-> TcM b
runQResult Pat -> String
forall a. Ppr a => a -> String
TH.pprint Origin -> SrcSpan -> Pat -> Either MsgDoc (Located (Pat GhcPs))
Origin -> SrcSpan -> Pat -> Either MsgDoc (LPat GhcPs)
convertToPat ForeignHValue -> TcM Pat
runTHPat)
defaultRunMeta (MetaT LHsType GhcPs -> MetaResult
r)
  = (LHsType GhcPs -> MetaResult)
-> IOEnv (Env TcGblEnv TcLclEnv) (LHsType GhcPs)
-> IOEnv (Env TcGblEnv TcLclEnv) MetaResult
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap LHsType GhcPs -> MetaResult
r (IOEnv (Env TcGblEnv TcLclEnv) (LHsType GhcPs)
 -> IOEnv (Env TcGblEnv TcLclEnv) MetaResult)
-> (LHsExpr GhcTcId
    -> IOEnv (Env TcGblEnv TcLclEnv) (LHsType GhcPs))
-> LHsExpr GhcTcId
-> IOEnv (Env TcGblEnv TcLclEnv) MetaResult
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Bool
-> (LHsType GhcPs -> MsgDoc)
-> (SrcSpan
    -> ForeignHValue -> TcM (Either MsgDoc (LHsType GhcPs)))
-> LHsExpr GhcTcId
-> IOEnv (Env TcGblEnv TcLclEnv) (LHsType GhcPs)
forall hs_syn.
Bool
-> (hs_syn -> MsgDoc)
-> (SrcSpan -> ForeignHValue -> TcM (Either MsgDoc hs_syn))
-> LHsExpr GhcTcId
-> TcM hs_syn
runMeta' Bool
True LHsType GhcPs -> MsgDoc
forall a. Outputable a => a -> MsgDoc
ppr ((Type -> String)
-> (Origin -> SrcSpan -> Type -> Either MsgDoc (LHsType GhcPs))
-> (ForeignHValue -> TcM Type)
-> SrcSpan
-> ForeignHValue
-> TcM (Either MsgDoc (LHsType GhcPs))
forall a b.
(a -> String)
-> (Origin -> SrcSpan -> a -> b)
-> (ForeignHValue -> TcM a)
-> SrcSpan
-> ForeignHValue
-> TcM b
runQResult Type -> String
forall a. Ppr a => a -> String
TH.pprint Origin -> SrcSpan -> Type -> Either MsgDoc (LHsType GhcPs)
convertToHsType ForeignHValue -> TcM Type
runTHType)
defaultRunMeta (MetaD [LHsDecl GhcPs] -> MetaResult
r)
  = ([LHsDecl GhcPs] -> MetaResult)
-> IOEnv (Env TcGblEnv TcLclEnv) [LHsDecl GhcPs]
-> IOEnv (Env TcGblEnv TcLclEnv) MetaResult
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap [LHsDecl GhcPs] -> MetaResult
r (IOEnv (Env TcGblEnv TcLclEnv) [LHsDecl GhcPs]
 -> IOEnv (Env TcGblEnv TcLclEnv) MetaResult)
-> (LHsExpr GhcTcId
    -> IOEnv (Env TcGblEnv TcLclEnv) [LHsDecl GhcPs])
-> LHsExpr GhcTcId
-> IOEnv (Env TcGblEnv TcLclEnv) MetaResult
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Bool
-> ([LHsDecl GhcPs] -> MsgDoc)
-> (SrcSpan
    -> ForeignHValue -> TcM (Either MsgDoc [LHsDecl GhcPs]))
-> LHsExpr GhcTcId
-> IOEnv (Env TcGblEnv TcLclEnv) [LHsDecl GhcPs]
forall hs_syn.
Bool
-> (hs_syn -> MsgDoc)
-> (SrcSpan -> ForeignHValue -> TcM (Either MsgDoc hs_syn))
-> LHsExpr GhcTcId
-> TcM hs_syn
runMeta' Bool
True [LHsDecl GhcPs] -> MsgDoc
forall a. Outputable a => a -> MsgDoc
ppr (([Dec] -> String)
-> (Origin -> SrcSpan -> [Dec] -> Either MsgDoc [LHsDecl GhcPs])
-> (ForeignHValue -> TcM [Dec])
-> SrcSpan
-> ForeignHValue
-> TcM (Either MsgDoc [LHsDecl GhcPs])
forall a b.
(a -> String)
-> (Origin -> SrcSpan -> a -> b)
-> (ForeignHValue -> TcM a)
-> SrcSpan
-> ForeignHValue
-> TcM b
runQResult [Dec] -> String
forall a. Ppr a => a -> String
TH.pprint Origin -> SrcSpan -> [Dec] -> Either MsgDoc [LHsDecl GhcPs]
convertToHsDecls ForeignHValue -> TcM [Dec]
runTHDec)
defaultRunMeta (MetaAW Serialized -> MetaResult
r)
  = (Serialized -> MetaResult)
-> TcM Serialized -> IOEnv (Env TcGblEnv TcLclEnv) MetaResult
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap Serialized -> MetaResult
r (TcM Serialized -> IOEnv (Env TcGblEnv TcLclEnv) MetaResult)
-> (LHsExpr GhcTcId -> TcM Serialized)
-> LHsExpr GhcTcId
-> IOEnv (Env TcGblEnv TcLclEnv) MetaResult
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Bool
-> (Serialized -> MsgDoc)
-> (SrcSpan -> ForeignHValue -> TcM (Either MsgDoc Serialized))
-> LHsExpr GhcTcId
-> TcM Serialized
forall hs_syn.
Bool
-> (hs_syn -> MsgDoc)
-> (SrcSpan -> ForeignHValue -> TcM (Either MsgDoc hs_syn))
-> LHsExpr GhcTcId
-> TcM hs_syn
runMeta' Bool
False (MsgDoc -> Serialized -> MsgDoc
forall a b. a -> b -> a
const MsgDoc
empty) ((ForeignHValue -> TcM (Either MsgDoc Serialized))
-> SrcSpan -> ForeignHValue -> TcM (Either MsgDoc Serialized)
forall a b. a -> b -> a
const ForeignHValue -> TcM (Either MsgDoc Serialized)
convertAnnotationWrapper)
    -- We turn off showing the code in meta-level exceptions because doing so exposes
    -- the toAnnotationWrapper function that we slap around the user's code

----------------
runMetaAW :: LHsExpr GhcTc         -- Of type AnnotationWrapper
          -> TcM Serialized
runMetaAW :: LHsExpr GhcTcId -> TcM Serialized
runMetaAW = (MetaHook TcM -> LHsExpr GhcTcId -> TcM Serialized)
-> LHsExpr GhcTcId -> TcM Serialized
forall hs_syn.
(MetaHook TcM -> LHsExpr GhcTcId -> TcM hs_syn)
-> LHsExpr GhcTcId -> TcM hs_syn
runMeta MetaHook TcM -> LHsExpr GhcTcId -> TcM Serialized
forall (f :: * -> *).
Functor f =>
MetaHook f -> LHsExpr GhcTcId -> f Serialized
metaRequestAW

runMetaE :: LHsExpr GhcTc          -- Of type (Q Exp)
         -> TcM (LHsExpr GhcPs)
runMetaE :: LHsExpr GhcTcId -> TcM (LHsExpr GhcPs)
runMetaE = (MetaHook TcM -> LHsExpr GhcTcId -> TcM (LHsExpr GhcPs))
-> LHsExpr GhcTcId -> TcM (LHsExpr GhcPs)
forall hs_syn.
(MetaHook TcM -> LHsExpr GhcTcId -> TcM hs_syn)
-> LHsExpr GhcTcId -> TcM hs_syn
runMeta MetaHook TcM -> LHsExpr GhcTcId -> TcM (LHsExpr GhcPs)
forall (f :: * -> *).
Functor f =>
MetaHook f -> LHsExpr GhcTcId -> f (LHsExpr GhcPs)
metaRequestE

runMetaP :: LHsExpr GhcTc          -- Of type (Q Pat)
         -> TcM (LPat GhcPs)
runMetaP :: LHsExpr GhcTcId -> TcM (LPat GhcPs)
runMetaP = (MetaHook TcM
 -> LHsExpr GhcTcId
 -> IOEnv (Env TcGblEnv TcLclEnv) (Located (Pat GhcPs)))
-> LHsExpr GhcTcId
-> IOEnv (Env TcGblEnv TcLclEnv) (Located (Pat GhcPs))
forall hs_syn.
(MetaHook TcM -> LHsExpr GhcTcId -> TcM hs_syn)
-> LHsExpr GhcTcId -> TcM hs_syn
runMeta MetaHook TcM
-> LHsExpr GhcTcId
-> IOEnv (Env TcGblEnv TcLclEnv) (Located (Pat GhcPs))
forall (f :: * -> *).
Functor f =>
MetaHook f -> LHsExpr GhcTcId -> f (LPat GhcPs)
metaRequestP

runMetaT :: LHsExpr GhcTc          -- Of type (Q Type)
         -> TcM (LHsType GhcPs)
runMetaT :: LHsExpr GhcTcId -> IOEnv (Env TcGblEnv TcLclEnv) (LHsType GhcPs)
runMetaT = (MetaHook TcM
 -> LHsExpr GhcTcId
 -> IOEnv (Env TcGblEnv TcLclEnv) (LHsType GhcPs))
-> LHsExpr GhcTcId -> IOEnv (Env TcGblEnv TcLclEnv) (LHsType GhcPs)
forall hs_syn.
(MetaHook TcM -> LHsExpr GhcTcId -> TcM hs_syn)
-> LHsExpr GhcTcId -> TcM hs_syn
runMeta MetaHook TcM
-> LHsExpr GhcTcId -> IOEnv (Env TcGblEnv TcLclEnv) (LHsType GhcPs)
forall (f :: * -> *).
Functor f =>
MetaHook f -> LHsExpr GhcTcId -> f (LHsType GhcPs)
metaRequestT

runMetaD :: LHsExpr GhcTc          -- Of type Q [Dec]
         -> TcM [LHsDecl GhcPs]
runMetaD :: LHsExpr GhcTcId -> IOEnv (Env TcGblEnv TcLclEnv) [LHsDecl GhcPs]
runMetaD = (MetaHook TcM
 -> LHsExpr GhcTcId
 -> IOEnv (Env TcGblEnv TcLclEnv) [LHsDecl GhcPs])
-> LHsExpr GhcTcId -> IOEnv (Env TcGblEnv TcLclEnv) [LHsDecl GhcPs]
forall hs_syn.
(MetaHook TcM -> LHsExpr GhcTcId -> TcM hs_syn)
-> LHsExpr GhcTcId -> TcM hs_syn
runMeta MetaHook TcM
-> LHsExpr GhcTcId -> IOEnv (Env TcGblEnv TcLclEnv) [LHsDecl GhcPs]
forall (f :: * -> *).
Functor f =>
MetaHook f -> LHsExpr GhcTcId -> f [LHsDecl GhcPs]
metaRequestD

---------------
runMeta' :: Bool                 -- Whether code should be printed in the exception message
         -> (hs_syn -> SDoc)                                    -- how to print the code
         -> (SrcSpan -> ForeignHValue -> TcM (Either MsgDoc hs_syn))        -- How to run x
         -> LHsExpr GhcTc        -- Of type x; typically x = Q TH.Exp, or
                                 --    something like that
         -> TcM hs_syn           -- Of type t
runMeta' :: Bool
-> (hs_syn -> MsgDoc)
-> (SrcSpan -> ForeignHValue -> TcM (Either MsgDoc hs_syn))
-> LHsExpr GhcTcId
-> TcM hs_syn
runMeta' Bool
show_code hs_syn -> MsgDoc
ppr_hs SrcSpan -> ForeignHValue -> TcM (Either MsgDoc hs_syn)
run_and_convert LHsExpr GhcTcId
expr
  = do  { String -> MsgDoc -> TcRn ()
traceTc String
"About to run" (LHsExpr GhcTcId -> MsgDoc
forall a. Outputable a => a -> MsgDoc
ppr LHsExpr GhcTcId
expr)
        ; TcRn ()
recordThSpliceUse -- seems to be the best place to do this,
                            -- we catch all kinds of splices and annotations.

        -- 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 #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.
        ; TcRn ()
failIfErrsM

        -- run plugins
        ; HscEnv
hsc_env <- IOEnv (Env TcGblEnv TcLclEnv) HscEnv
forall gbl lcl. TcRnIf gbl lcl HscEnv
getTopEnv
        ; LHsExpr GhcTcId
expr' <- DynFlags
-> PluginOperation TcM (LHsExpr GhcTcId)
-> LHsExpr GhcTcId
-> TcM (LHsExpr GhcTcId)
forall (m :: * -> *) a.
Monad m =>
DynFlags -> PluginOperation m a -> a -> m a
withPlugins (HscEnv -> DynFlags
hsc_dflags HscEnv
hsc_env) PluginOperation TcM (LHsExpr GhcTcId)
spliceRunAction LHsExpr GhcTcId
expr

        -- Desugar
        ; CoreExpr
ds_expr <- DsM CoreExpr -> TcM CoreExpr
forall a. DsM a -> TcM a
initDsTc (LHsExpr GhcTcId -> DsM CoreExpr
dsLExpr LHsExpr GhcTcId
expr')
        -- Compile and link it; might fail if linking fails
        ; SrcSpan
src_span <- TcRn SrcSpan
getSrcSpanM
        ; String -> MsgDoc -> TcRn ()
traceTc String
"About to run (desugared)" (CoreExpr -> MsgDoc
forall a. Outputable a => a -> MsgDoc
ppr CoreExpr
ds_expr)
        ; Either IOEnvFailure ForeignHValue
either_hval <- IOEnv (Env TcGblEnv TcLclEnv) ForeignHValue
-> IOEnv
     (Env TcGblEnv TcLclEnv) (Either IOEnvFailure ForeignHValue)
forall env r. IOEnv env r -> IOEnv env (Either IOEnvFailure r)
tryM (IOEnv (Env TcGblEnv TcLclEnv) ForeignHValue
 -> IOEnv
      (Env TcGblEnv TcLclEnv) (Either IOEnvFailure ForeignHValue))
-> IOEnv (Env TcGblEnv TcLclEnv) ForeignHValue
-> IOEnv
     (Env TcGblEnv TcLclEnv) (Either IOEnvFailure ForeignHValue)
forall a b. (a -> b) -> a -> b
$ IO ForeignHValue -> IOEnv (Env TcGblEnv TcLclEnv) ForeignHValue
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IO ForeignHValue -> IOEnv (Env TcGblEnv TcLclEnv) ForeignHValue)
-> IO ForeignHValue -> IOEnv (Env TcGblEnv TcLclEnv) ForeignHValue
forall a b. (a -> b) -> a -> b
$
                         HscEnv -> SrcSpan -> CoreExpr -> IO ForeignHValue
HscMain.hscCompileCoreExpr HscEnv
hsc_env SrcSpan
src_span CoreExpr
ds_expr
        ; case Either IOEnvFailure ForeignHValue
either_hval of {
            Left IOEnvFailure
exn   -> String -> IOEnvFailure -> TcM hs_syn
forall e a. Exception e => String -> e -> TcM a
fail_with_exn String
"compile and link" IOEnvFailure
exn ;
            Right ForeignHValue
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 :: SrcSpan
expr_span = LHsExpr GhcTcId -> SrcSpan
forall a. HasSrcSpan a => a -> SrcSpan
getLoc LHsExpr GhcTcId
expr
        ; Either SomeException hs_syn
either_tval <- TcM hs_syn
-> IOEnv (Env TcGblEnv TcLclEnv) (Either SomeException hs_syn)
forall env r. IOEnv env r -> IOEnv env (Either SomeException r)
tryAllM (TcM hs_syn
 -> IOEnv (Env TcGblEnv TcLclEnv) (Either SomeException hs_syn))
-> TcM hs_syn
-> IOEnv (Env TcGblEnv TcLclEnv) (Either SomeException hs_syn)
forall a b. (a -> b) -> a -> b
$
                         SrcSpan -> TcM hs_syn -> TcM hs_syn
forall a. SrcSpan -> TcRn a -> TcRn a
setSrcSpan SrcSpan
expr_span (TcM hs_syn -> TcM hs_syn) -> TcM hs_syn -> TcM hs_syn
forall a b. (a -> b) -> a -> b
$ -- Set the span so that qLocation can
                                                -- see where this splice is
             do { Either MsgDoc hs_syn
mb_result <- SrcSpan -> ForeignHValue -> TcM (Either MsgDoc hs_syn)
run_and_convert SrcSpan
expr_span ForeignHValue
hval
                ; case Either MsgDoc hs_syn
mb_result of
                    Left MsgDoc
err     -> MsgDoc -> TcM hs_syn
forall a. MsgDoc -> TcM a
failWithTc MsgDoc
err
                    Right hs_syn
result -> do { String -> MsgDoc -> TcRn ()
traceTc String
"Got HsSyn result:" (hs_syn -> MsgDoc
ppr_hs hs_syn
result)
                                       ; hs_syn -> TcM hs_syn
forall (m :: * -> *) a. Monad m => a -> m a
return (hs_syn -> TcM hs_syn) -> hs_syn -> TcM hs_syn
forall a b. (a -> b) -> a -> b
$! hs_syn
result } }

        ; case Either SomeException hs_syn
either_tval of
            Right hs_syn
v -> hs_syn -> TcM hs_syn
forall (m :: * -> *) a. Monad m => a -> m a
return hs_syn
v
            Left SomeException
se -> case SomeException -> Maybe IOEnvFailure
forall e. Exception e => SomeException -> Maybe e
fromException SomeException
se of
                         Just IOEnvFailure
IOEnvFailure -> TcM hs_syn
forall env a. IOEnv env a
failM -- Error already in Tc monad
                         Maybe IOEnvFailure
_ -> String -> SomeException -> TcM hs_syn
forall e a. Exception e => String -> e -> TcM a
fail_with_exn String
"run" SomeException
se -- Exception
        }}}
  where
    -- see Note [Concealed TH exceptions]
    fail_with_exn :: Exception e => String -> e -> TcM a
    fail_with_exn :: String -> e -> TcM a
fail_with_exn String
phase e
exn = do
        String
exn_msg <- IO String -> IOEnv (Env TcGblEnv TcLclEnv) String
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IO String -> IOEnv (Env TcGblEnv TcLclEnv) String)
-> IO String -> IOEnv (Env TcGblEnv TcLclEnv) String
forall a b. (a -> b) -> a -> b
$ e -> IO String
forall e. Exception e => e -> IO String
Panic.safeShowException e
exn
        let msg :: MsgDoc
msg = [MsgDoc] -> MsgDoc
vcat [String -> MsgDoc
text String
"Exception when trying to" MsgDoc -> MsgDoc -> MsgDoc
<+> String -> MsgDoc
text String
phase MsgDoc -> MsgDoc -> MsgDoc
<+> String -> MsgDoc
text String
"compile-time code:",
                        Int -> MsgDoc -> MsgDoc
nest Int
2 (String -> MsgDoc
text String
exn_msg),
                        if Bool
show_code then String -> MsgDoc
text String
"Code:" MsgDoc -> MsgDoc -> MsgDoc
<+> LHsExpr GhcTcId -> MsgDoc
forall a. Outputable a => a -> MsgDoc
ppr LHsExpr GhcTcId
expr else MsgDoc
empty]
        MsgDoc -> TcM a
forall a. MsgDoc -> TcM a
failWithTc MsgDoc
msg

{-
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.



Note [Exceptions in TH]
~~~~~~~~~~~~~~~~~~~~~~~
Suppose we have something like this
        $( f 4 )
where
        f :: Int -> Q [Dec]
        f n | n>3       = fail "Too many declarations"
            | otherwise = ...

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
    effectively transforms (fail s) to
        qReport True s >> fail
    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.
    The 'fail' in TcM raises an IOEnvFailure exception

 * '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 (#8987):
        $(fail undefined)
   See also Note [Concealed TH exceptions]

  * 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
    and then fail

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.


To call runQ in the Tc monad, we need to make TcM an instance of Quasi:
-}

instance TH.Quasi TcM where
  qNewName :: String -> TcM Name
qNewName String
s = do { Unique
u <- TcRnIf TcGblEnv TcLclEnv Unique
forall gbl lcl. TcRnIf gbl lcl Unique
newUnique
                  ; let i :: Integer
i = Int -> Integer
forall a. Integral a => a -> Integer
toInteger (Unique -> Int
getKey Unique
u)
                  ; Name -> TcM Name
forall (m :: * -> *) a. Monad m => a -> m a
return (String -> Integer -> Name
TH.mkNameU String
s Integer
i) }

  -- 'msg' is forced to ensure exceptions don't escape,
  -- see Note [Exceptions in TH]
  qReport :: Bool -> String -> TcRn ()
qReport Bool
True String
msg  = String -> TcRn () -> TcRn ()
forall a b. [a] -> b -> b
seqList String
msg (TcRn () -> TcRn ()) -> TcRn () -> TcRn ()
forall a b. (a -> b) -> a -> b
$ MsgDoc -> TcRn ()
addErr  (String -> MsgDoc
text String
msg)
  qReport Bool
False String
msg = String -> TcRn () -> TcRn ()
forall a b. [a] -> b -> b
seqList String
msg (TcRn () -> TcRn ()) -> TcRn () -> TcRn ()
forall a b. (a -> b) -> a -> b
$ WarnReason -> MsgDoc -> TcRn ()
addWarn WarnReason
NoReason (String -> MsgDoc
text String
msg)

  qLocation :: TcM Loc
qLocation = do { Module
m <- IOEnv (Env TcGblEnv TcLclEnv) Module
forall (m :: * -> *). HasModule m => m Module
getModule
                 ; SrcSpan
l <- TcRn SrcSpan
getSrcSpanM
                 ; RealSrcSpan
r <- case SrcSpan
l of
                        UnhelpfulSpan FastString
_ -> String -> MsgDoc -> IOEnv (Env TcGblEnv TcLclEnv) RealSrcSpan
forall a. HasCallStack => String -> MsgDoc -> a
pprPanic String
"qLocation: Unhelpful location"
                                                    (SrcSpan -> MsgDoc
forall a. Outputable a => a -> MsgDoc
ppr SrcSpan
l)
                        RealSrcSpan RealSrcSpan
s -> RealSrcSpan -> IOEnv (Env TcGblEnv TcLclEnv) RealSrcSpan
forall (m :: * -> *) a. Monad m => a -> m a
return RealSrcSpan
s
                 ; Loc -> TcM Loc
forall (m :: * -> *) a. Monad m => a -> m a
return (Loc :: String -> String -> String -> CharPos -> CharPos -> Loc
TH.Loc { loc_filename :: String
TH.loc_filename = FastString -> String
unpackFS (RealSrcSpan -> FastString
srcSpanFile RealSrcSpan
r)
                                  , loc_module :: String
TH.loc_module   = ModuleName -> String
moduleNameString (Module -> ModuleName
moduleName Module
m)
                                  , loc_package :: String
TH.loc_package  = UnitId -> String
unitIdString (Module -> UnitId
moduleUnitId Module
m)
                                  , loc_start :: CharPos
TH.loc_start = (RealSrcSpan -> Int
srcSpanStartLine RealSrcSpan
r, RealSrcSpan -> Int
srcSpanStartCol RealSrcSpan
r)
                                  , loc_end :: CharPos
TH.loc_end = (RealSrcSpan -> Int
srcSpanEndLine   RealSrcSpan
r, RealSrcSpan -> Int
srcSpanEndCol   RealSrcSpan
r) }) }

  qLookupName :: Bool -> String -> TcM (Maybe Name)
qLookupName       = Bool -> String -> TcM (Maybe Name)
lookupName
  qReify :: Name -> TcM Info
qReify            = Name -> TcM Info
reify
  qReifyFixity :: Name -> TcM (Maybe Fixity)
qReifyFixity Name
nm   = Name -> TcM Name
lookupThName Name
nm TcM Name -> (Name -> TcM (Maybe Fixity)) -> TcM (Maybe Fixity)
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= Name -> TcM (Maybe Fixity)
reifyFixity
  qReifyType :: Name -> TcM Type
qReifyType        = Name -> TcM Type
reifyTypeOfThing
  qReifyInstances :: Name -> [Type] -> TcM [Dec]
qReifyInstances   = Name -> [Type] -> TcM [Dec]
reifyInstances
  qReifyRoles :: Name -> TcM [Role]
qReifyRoles       = Name -> TcM [Role]
reifyRoles
  qReifyAnnotations :: AnnLookup -> TcM [a]
qReifyAnnotations = AnnLookup -> TcM [a]
forall a. Data a => AnnLookup -> TcM [a]
reifyAnnotations
  qReifyModule :: Module -> TcM ModuleInfo
qReifyModule      = Module -> TcM ModuleInfo
reifyModule
  qReifyConStrictness :: Name -> TcM [DecidedStrictness]
qReifyConStrictness Name
nm = do { Name
nm' <- Name -> TcM Name
lookupThName Name
nm
                              ; DataCon
dc  <- Name -> TcM DataCon
tcLookupDataCon Name
nm'
                              ; let bangs :: [HsImplBang]
bangs = DataCon -> [HsImplBang]
dataConImplBangs DataCon
dc
                              ; [DecidedStrictness] -> TcM [DecidedStrictness]
forall (m :: * -> *) a. Monad m => a -> m a
return ((HsImplBang -> DecidedStrictness)
-> [HsImplBang] -> [DecidedStrictness]
forall a b. (a -> b) -> [a] -> [b]
map HsImplBang -> DecidedStrictness
reifyDecidedStrictness [HsImplBang]
bangs) }

        -- For qRecover, discard error messages if
        -- the recovery action is chosen.  Otherwise
        -- we'll only fail higher up.
  qRecover :: TcM a -> TcM a -> TcM a
qRecover TcM a
recover TcM a
main = TcM a -> TcM a -> TcM a
forall a. TcM a -> TcM a -> TcM a
tryTcDiscardingErrs TcM a
recover TcM a
main

  qAddDependentFile :: String -> TcRn ()
qAddDependentFile String
fp = do
    TcRef [String]
ref <- (TcGblEnv -> TcRef [String])
-> TcRnIf TcGblEnv TcLclEnv TcGblEnv
-> IOEnv (Env TcGblEnv TcLclEnv) (TcRef [String])
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap TcGblEnv -> TcRef [String]
tcg_dependent_files TcRnIf TcGblEnv TcLclEnv TcGblEnv
forall gbl lcl. TcRnIf gbl lcl gbl
getGblEnv
    [String]
dep_files <- TcRef [String] -> TcRnIf TcGblEnv TcLclEnv [String]
forall a gbl lcl. TcRef a -> TcRnIf gbl lcl a
readTcRef TcRef [String]
ref
    TcRef [String] -> [String] -> TcRn ()
forall a gbl lcl. TcRef a -> a -> TcRnIf gbl lcl ()
writeTcRef TcRef [String]
ref (String
fpString -> [String] -> [String]
forall a. a -> [a] -> [a]
:[String]
dep_files)

  qAddTempFile :: String -> IOEnv (Env TcGblEnv TcLclEnv) String
qAddTempFile String
suffix = do
    DynFlags
dflags <- IOEnv (Env TcGblEnv TcLclEnv) DynFlags
forall (m :: * -> *). HasDynFlags m => m DynFlags
getDynFlags
    IO String -> IOEnv (Env TcGblEnv TcLclEnv) String
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IO String -> IOEnv (Env TcGblEnv TcLclEnv) String)
-> IO String -> IOEnv (Env TcGblEnv TcLclEnv) String
forall a b. (a -> b) -> a -> b
$ DynFlags -> TempFileLifetime -> String -> IO String
newTempName DynFlags
dflags TempFileLifetime
TFL_GhcSession String
suffix

  qAddTopDecls :: [Dec] -> TcRn ()
qAddTopDecls [Dec]
thds = do
      SrcSpan
l <- TcRn SrcSpan
getSrcSpanM
      Origin
th_origin <- TcM Origin
getThSpliceOrigin
      let either_hval :: Either MsgDoc [LHsDecl GhcPs]
either_hval = Origin -> SrcSpan -> [Dec] -> Either MsgDoc [LHsDecl GhcPs]
convertToHsDecls Origin
th_origin SrcSpan
l [Dec]
thds
      [LHsDecl GhcPs]
ds <- case Either MsgDoc [LHsDecl GhcPs]
either_hval of
              Left MsgDoc
exn -> MsgDoc -> IOEnv (Env TcGblEnv TcLclEnv) [LHsDecl GhcPs]
forall a. MsgDoc -> TcM a
failWithTc (MsgDoc -> IOEnv (Env TcGblEnv TcLclEnv) [LHsDecl GhcPs])
-> MsgDoc -> IOEnv (Env TcGblEnv TcLclEnv) [LHsDecl GhcPs]
forall a b. (a -> b) -> a -> b
$
                MsgDoc -> Int -> MsgDoc -> MsgDoc
hang (String -> MsgDoc
text String
"Error in a declaration passed to addTopDecls:")
                   Int
2 MsgDoc
exn
              Right [LHsDecl GhcPs]
ds -> [LHsDecl GhcPs] -> IOEnv (Env TcGblEnv TcLclEnv) [LHsDecl GhcPs]
forall (m :: * -> *) a. Monad m => a -> m a
return [LHsDecl GhcPs]
ds
      (LHsDecl GhcPs -> TcRn ()) -> [LHsDecl GhcPs] -> TcRn ()
forall (t :: * -> *) (m :: * -> *) a b.
(Foldable t, Monad m) =>
(a -> m b) -> t a -> m ()
mapM_ (HsDecl GhcPs -> TcRn ()
checkTopDecl (HsDecl GhcPs -> TcRn ())
-> (LHsDecl GhcPs -> HsDecl GhcPs) -> LHsDecl GhcPs -> TcRn ()
forall b c a. (b -> c) -> (a -> b) -> a -> c
. LHsDecl GhcPs -> HsDecl GhcPs
forall a. HasSrcSpan a => a -> SrcSpanLess a
unLoc) [LHsDecl GhcPs]
ds
      TcRef [LHsDecl GhcPs]
th_topdecls_var <- (TcGblEnv -> TcRef [LHsDecl GhcPs])
-> TcRnIf TcGblEnv TcLclEnv TcGblEnv
-> IOEnv (Env TcGblEnv TcLclEnv) (TcRef [LHsDecl GhcPs])
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap TcGblEnv -> TcRef [LHsDecl GhcPs]
tcg_th_topdecls TcRnIf TcGblEnv TcLclEnv TcGblEnv
forall gbl lcl. TcRnIf gbl lcl gbl
getGblEnv
      TcRef [LHsDecl GhcPs]
-> ([LHsDecl GhcPs] -> [LHsDecl GhcPs]) -> TcRn ()
forall a gbl lcl. TcRef a -> (a -> a) -> TcRnIf gbl lcl ()
updTcRef TcRef [LHsDecl GhcPs]
th_topdecls_var (\[LHsDecl GhcPs]
topds -> [LHsDecl GhcPs]
ds [LHsDecl GhcPs] -> [LHsDecl GhcPs] -> [LHsDecl GhcPs]
forall a. [a] -> [a] -> [a]
++ [LHsDecl GhcPs]
topds)
    where
      checkTopDecl :: HsDecl GhcPs -> TcM ()
      checkTopDecl :: HsDecl GhcPs -> TcRn ()
checkTopDecl (ValD XValD GhcPs
_ HsBind GhcPs
binds)
        = (RdrName -> TcRn ()) -> [RdrName] -> TcRn ()
forall (t :: * -> *) (m :: * -> *) a b.
(Foldable t, Monad m) =>
(a -> m b) -> t a -> m ()
mapM_ RdrName -> TcRn ()
bindName (HsBind GhcPs -> [IdP GhcPs]
forall p idR.
(SrcSpanLess (LPat p) ~ Pat p, HasSrcSpan (LPat p)) =>
HsBindLR p idR -> [IdP p]
collectHsBindBinders HsBind GhcPs
binds)
      checkTopDecl (SigD XSigD GhcPs
_ Sig GhcPs
_)
        = () -> TcRn ()
forall (m :: * -> *) a. Monad m => a -> m a
return ()
      checkTopDecl (AnnD XAnnD GhcPs
_ AnnDecl GhcPs
_)
        = () -> TcRn ()
forall (m :: * -> *) a. Monad m => a -> m a
return ()
      checkTopDecl (ForD XForD GhcPs
_ (ForeignImport { fd_name :: forall pass. ForeignDecl pass -> Located (IdP pass)
fd_name = L SrcSpan
_ IdP GhcPs
name }))
        = RdrName -> TcRn ()
bindName RdrName
IdP GhcPs
name
      checkTopDecl HsDecl GhcPs
_
        = MsgDoc -> TcRn ()
addErr (MsgDoc -> TcRn ()) -> MsgDoc -> TcRn ()
forall a b. (a -> b) -> a -> b
$ String -> MsgDoc
text String
"Only function, value, annotation, and foreign import declarations may be added with addTopDecl"

      bindName :: RdrName -> TcM ()
      bindName :: RdrName -> TcRn ()
bindName (Exact Name
n)
        = do { TcRef FreeVars
th_topnames_var <- (TcGblEnv -> TcRef FreeVars)
-> TcRnIf TcGblEnv TcLclEnv TcGblEnv
-> IOEnv (Env TcGblEnv TcLclEnv) (TcRef FreeVars)
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap TcGblEnv -> TcRef FreeVars
tcg_th_topnames TcRnIf TcGblEnv TcLclEnv TcGblEnv
forall gbl lcl. TcRnIf gbl lcl gbl
getGblEnv
             ; TcRef FreeVars -> (FreeVars -> FreeVars) -> TcRn ()
forall a gbl lcl. TcRef a -> (a -> a) -> TcRnIf gbl lcl ()
updTcRef TcRef FreeVars
th_topnames_var (\FreeVars
ns -> FreeVars -> Name -> FreeVars
extendNameSet FreeVars
ns Name
n)
             }

      bindName RdrName
name =
          MsgDoc -> TcRn ()
addErr (MsgDoc -> TcRn ()) -> MsgDoc -> TcRn ()
forall a b. (a -> b) -> a -> b
$
          MsgDoc -> Int -> MsgDoc -> MsgDoc
hang (String -> MsgDoc
text String
"The binder" MsgDoc -> MsgDoc -> MsgDoc
<+> MsgDoc -> MsgDoc
quotes (RdrName -> MsgDoc
forall a. Outputable a => a -> MsgDoc
ppr RdrName
name) MsgDoc -> MsgDoc -> MsgDoc
<+> PtrString -> MsgDoc
ptext (String -> PtrString
sLit String
"is not a NameU."))
             Int
2 (String -> MsgDoc
text String
"Probable cause: you used mkName instead of newName to generate a binding.")

  qAddForeignFilePath :: ForeignSrcLang -> String -> TcRn ()
qAddForeignFilePath ForeignSrcLang
lang String
fp = do
    TcRef [(ForeignSrcLang, String)]
var <- (TcGblEnv -> TcRef [(ForeignSrcLang, String)])
-> TcRnIf TcGblEnv TcLclEnv TcGblEnv
-> IOEnv (Env TcGblEnv TcLclEnv) (TcRef [(ForeignSrcLang, String)])
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap TcGblEnv -> TcRef [(ForeignSrcLang, String)]
tcg_th_foreign_files TcRnIf TcGblEnv TcLclEnv TcGblEnv
forall gbl lcl. TcRnIf gbl lcl gbl
getGblEnv
    TcRef [(ForeignSrcLang, String)]
-> ([(ForeignSrcLang, String)] -> [(ForeignSrcLang, String)])
-> TcRn ()
forall a gbl lcl. TcRef a -> (a -> a) -> TcRnIf gbl lcl ()
updTcRef TcRef [(ForeignSrcLang, String)]
var ((ForeignSrcLang
lang, String
fp) (ForeignSrcLang, String)
-> [(ForeignSrcLang, String)] -> [(ForeignSrcLang, String)]
forall a. a -> [a] -> [a]
:)

  qAddModFinalizer :: Q () -> TcRn ()
qAddModFinalizer Q ()
fin = do
      RemoteRef (Q ())
r <- IO (RemoteRef (Q ()))
-> IOEnv (Env TcGblEnv TcLclEnv) (RemoteRef (Q ()))
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IO (RemoteRef (Q ()))
 -> IOEnv (Env TcGblEnv TcLclEnv) (RemoteRef (Q ())))
-> IO (RemoteRef (Q ()))
-> IOEnv (Env TcGblEnv TcLclEnv) (RemoteRef (Q ()))
forall a b. (a -> b) -> a -> b
$ Q () -> IO (RemoteRef (Q ()))
forall a. a -> IO (RemoteRef a)
mkRemoteRef Q ()
fin
      ForeignRef (Q ())
fref <- IO (ForeignRef (Q ()))
-> IOEnv (Env TcGblEnv TcLclEnv) (ForeignRef (Q ()))
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IO (ForeignRef (Q ()))
 -> IOEnv (Env TcGblEnv TcLclEnv) (ForeignRef (Q ())))
-> IO (ForeignRef (Q ()))
-> IOEnv (Env TcGblEnv TcLclEnv) (ForeignRef (Q ()))
forall a b. (a -> b) -> a -> b
$ RemoteRef (Q ()) -> IO () -> IO (ForeignRef (Q ()))
forall a. RemoteRef a -> IO () -> IO (ForeignRef a)
mkForeignRef RemoteRef (Q ())
r (RemoteRef (Q ()) -> IO ()
forall a. RemoteRef a -> IO ()
freeRemoteRef RemoteRef (Q ())
r)
      ForeignRef (Q ()) -> TcRn ()
addModFinalizerRef ForeignRef (Q ())
fref

  qAddCorePlugin :: String -> TcRn ()
qAddCorePlugin String
plugin = do
      HscEnv
hsc_env <- Env TcGblEnv TcLclEnv -> HscEnv
forall gbl lcl. Env gbl lcl -> HscEnv
env_top (Env TcGblEnv TcLclEnv -> HscEnv)
-> IOEnv (Env TcGblEnv TcLclEnv) (Env TcGblEnv TcLclEnv)
-> IOEnv (Env TcGblEnv TcLclEnv) HscEnv
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> IOEnv (Env TcGblEnv TcLclEnv) (Env TcGblEnv TcLclEnv)
forall env. IOEnv env env
getEnv
      FindResult
r <- IO FindResult -> IOEnv (Env TcGblEnv TcLclEnv) FindResult
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IO FindResult -> IOEnv (Env TcGblEnv TcLclEnv) FindResult)
-> IO FindResult -> IOEnv (Env TcGblEnv TcLclEnv) FindResult
forall a b. (a -> b) -> a -> b
$ HscEnv -> ModuleName -> IO FindResult
findHomeModule HscEnv
hsc_env (String -> ModuleName
mkModuleName String
plugin)
      let err :: MsgDoc
err = MsgDoc -> Int -> MsgDoc -> MsgDoc
hang
            (String -> MsgDoc
text String
"addCorePlugin: invalid plugin module "
               MsgDoc -> MsgDoc -> MsgDoc
<+> String -> MsgDoc
text (String -> String
forall a. Show a => a -> String
show String
plugin)
            )
            Int
2
            (String -> MsgDoc
text String
"Plugins in the current package can't be specified.")
      case FindResult
r of
        Found {} -> MsgDoc -> TcRn ()
addErr MsgDoc
err
        FoundMultiple {} -> MsgDoc -> TcRn ()
addErr MsgDoc
err
        FindResult
_ -> () -> TcRn ()
forall (m :: * -> *) a. Monad m => a -> m a
return ()
      TcRef [String]
th_coreplugins_var <- TcGblEnv -> TcRef [String]
tcg_th_coreplugins (TcGblEnv -> TcRef [String])
-> TcRnIf TcGblEnv TcLclEnv TcGblEnv
-> IOEnv (Env TcGblEnv TcLclEnv) (TcRef [String])
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> TcRnIf TcGblEnv TcLclEnv TcGblEnv
forall gbl lcl. TcRnIf gbl lcl gbl
getGblEnv
      TcRef [String] -> ([String] -> [String]) -> TcRn ()
forall a gbl lcl. TcRef a -> (a -> a) -> TcRnIf gbl lcl ()
updTcRef TcRef [String]
th_coreplugins_var (String
pluginString -> [String] -> [String]
forall a. a -> [a] -> [a]
:)

  qGetQ :: forall a. Typeable a => TcM (Maybe a)
  qGetQ :: TcM (Maybe a)
qGetQ = do
      TcRef (Map TypeRep Dynamic)
th_state_var <- (TcGblEnv -> TcRef (Map TypeRep Dynamic))
-> TcRnIf TcGblEnv TcLclEnv TcGblEnv
-> IOEnv (Env TcGblEnv TcLclEnv) (TcRef (Map TypeRep Dynamic))
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap TcGblEnv -> TcRef (Map TypeRep Dynamic)
tcg_th_state TcRnIf TcGblEnv TcLclEnv TcGblEnv
forall gbl lcl. TcRnIf gbl lcl gbl
getGblEnv
      Map TypeRep Dynamic
th_state <- TcRef (Map TypeRep Dynamic)
-> TcRnIf TcGblEnv TcLclEnv (Map TypeRep Dynamic)
forall a gbl lcl. TcRef a -> TcRnIf gbl lcl a
readTcRef TcRef (Map TypeRep Dynamic)
th_state_var
      -- See #10596 for why we use a scoped type variable here.
      Maybe a -> TcM (Maybe a)
forall (m :: * -> *) a. Monad m => a -> m a
return (TypeRep -> Map TypeRep Dynamic -> Maybe Dynamic
forall k a. Ord k => k -> Map k a -> Maybe a
Map.lookup (Proxy a -> TypeRep
forall k (proxy :: k -> *) (a :: k).
Typeable a =>
proxy a -> TypeRep
typeRep (Proxy a
forall k (t :: k). Proxy t
Proxy :: Proxy a)) Map TypeRep Dynamic
th_state Maybe Dynamic -> (Dynamic -> Maybe a) -> Maybe a
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= Dynamic -> Maybe a
forall a. Typeable a => Dynamic -> Maybe a
fromDynamic)

  qPutQ :: a -> TcRn ()
qPutQ a
x = do
      TcRef (Map TypeRep Dynamic)
th_state_var <- (TcGblEnv -> TcRef (Map TypeRep Dynamic))
-> TcRnIf TcGblEnv TcLclEnv TcGblEnv
-> IOEnv (Env TcGblEnv TcLclEnv) (TcRef (Map TypeRep Dynamic))
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap TcGblEnv -> TcRef (Map TypeRep Dynamic)
tcg_th_state TcRnIf TcGblEnv TcLclEnv TcGblEnv
forall gbl lcl. TcRnIf gbl lcl gbl
getGblEnv
      TcRef (Map TypeRep Dynamic)
-> (Map TypeRep Dynamic -> Map TypeRep Dynamic) -> TcRn ()
forall a gbl lcl. TcRef a -> (a -> a) -> TcRnIf gbl lcl ()
updTcRef TcRef (Map TypeRep Dynamic)
th_state_var (\Map TypeRep Dynamic
m -> TypeRep -> Dynamic -> Map TypeRep Dynamic -> Map TypeRep Dynamic
forall k a. Ord k => k -> a -> Map k a -> Map k a
Map.insert (a -> TypeRep
forall a. Typeable a => a -> TypeRep
typeOf a
x) (a -> Dynamic
forall a. Typeable a => a -> Dynamic
toDyn a
x) Map TypeRep Dynamic
m)

  qIsExtEnabled :: Extension -> TcRnIf TcGblEnv TcLclEnv Bool
qIsExtEnabled = Extension -> TcRnIf TcGblEnv TcLclEnv Bool
forall gbl lcl. Extension -> TcRnIf gbl lcl Bool
xoptM

  qExtsEnabled :: TcM [Extension]
qExtsEnabled =
    EnumSet Extension -> [Extension]
forall a. Enum a => EnumSet a -> [a]
EnumSet.toList (EnumSet Extension -> [Extension])
-> (HscEnv -> EnumSet Extension) -> HscEnv -> [Extension]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. DynFlags -> EnumSet Extension
extensionFlags (DynFlags -> EnumSet Extension)
-> (HscEnv -> DynFlags) -> HscEnv -> EnumSet Extension
forall b c a. (b -> c) -> (a -> b) -> a -> c
. HscEnv -> DynFlags
hsc_dflags (HscEnv -> [Extension])
-> IOEnv (Env TcGblEnv TcLclEnv) HscEnv -> TcM [Extension]
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> IOEnv (Env TcGblEnv TcLclEnv) HscEnv
forall gbl lcl. TcRnIf gbl lcl HscEnv
getTopEnv

-- | Adds a mod finalizer reference to the local environment.
addModFinalizerRef :: ForeignRef (TH.Q ()) -> TcM ()
addModFinalizerRef :: ForeignRef (Q ()) -> TcRn ()
addModFinalizerRef ForeignRef (Q ())
finRef = do
    ThStage
th_stage <- TcM ThStage
getStage
    case ThStage
th_stage of
      RunSplice TcRef [ForeignRef (Q ())]
th_modfinalizers_var -> TcRef [ForeignRef (Q ())]
-> ([ForeignRef (Q ())] -> [ForeignRef (Q ())]) -> TcRn ()
forall a gbl lcl. TcRef a -> (a -> a) -> TcRnIf gbl lcl ()
updTcRef TcRef [ForeignRef (Q ())]
th_modfinalizers_var (ForeignRef (Q ())
finRef ForeignRef (Q ()) -> [ForeignRef (Q ())] -> [ForeignRef (Q ())]
forall a. a -> [a] -> [a]
:)
      -- 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.
      ThStage
_ ->
        String -> MsgDoc -> TcRn ()
forall a. HasCallStack => String -> MsgDoc -> a
pprPanic String
"addModFinalizer was called when no finalizers were collected"
                 (ThStage -> MsgDoc
forall a. Outputable a => a -> MsgDoc
ppr ThStage
th_stage)

-- | Releases the external interpreter state.
finishTH :: TcM ()
finishTH :: TcRn ()
finishTH = do
  DynFlags
dflags <- IOEnv (Env TcGblEnv TcLclEnv) DynFlags
forall (m :: * -> *). HasDynFlags m => m DynFlags
getDynFlags
  Bool -> TcRn () -> TcRn ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
when (GeneralFlag -> DynFlags -> Bool
gopt GeneralFlag
Opt_ExternalInterpreter DynFlags
dflags) (TcRn () -> TcRn ()) -> TcRn () -> TcRn ()
forall a b. (a -> b) -> a -> b
$ do
    TcGblEnv
tcg <- TcRnIf TcGblEnv TcLclEnv TcGblEnv
forall gbl lcl. TcRnIf gbl lcl gbl
getGblEnv
    TcRef (Maybe (ForeignRef (IORef QState)))
-> Maybe (ForeignRef (IORef QState)) -> TcRn ()
forall a gbl lcl. TcRef a -> a -> TcRnIf gbl lcl ()
writeTcRef (TcGblEnv -> TcRef (Maybe (ForeignRef (IORef QState)))
tcg_th_remote_state TcGblEnv
tcg) Maybe (ForeignRef (IORef QState))
forall a. Maybe a
Nothing

runTHExp :: ForeignHValue -> TcM TH.Exp
runTHExp :: ForeignHValue -> TcM Exp
runTHExp = THResultType -> ForeignHValue -> TcM Exp
forall a. Binary a => THResultType -> ForeignHValue -> TcM a
runTH THResultType
THExp

runTHPat :: ForeignHValue -> TcM TH.Pat
runTHPat :: ForeignHValue -> TcM Pat
runTHPat = THResultType -> ForeignHValue -> TcM Pat
forall a. Binary a => THResultType -> ForeignHValue -> TcM a
runTH THResultType
THPat

runTHType :: ForeignHValue -> TcM TH.Type
runTHType :: ForeignHValue -> TcM Type
runTHType = THResultType -> ForeignHValue -> TcM Type
forall a. Binary a => THResultType -> ForeignHValue -> TcM a
runTH THResultType
THType

runTHDec :: ForeignHValue -> TcM [TH.Dec]
runTHDec :: ForeignHValue -> TcM [Dec]
runTHDec = THResultType -> ForeignHValue -> TcM [Dec]
forall a. Binary a => THResultType -> ForeignHValue -> TcM a
runTH THResultType
THDec

runTH :: Binary a => THResultType -> ForeignHValue -> TcM a
runTH :: THResultType -> ForeignHValue -> TcM a
runTH THResultType
ty ForeignHValue
fhv = do
  HscEnv
hsc_env <- Env TcGblEnv TcLclEnv -> HscEnv
forall gbl lcl. Env gbl lcl -> HscEnv
env_top (Env TcGblEnv TcLclEnv -> HscEnv)
-> IOEnv (Env TcGblEnv TcLclEnv) (Env TcGblEnv TcLclEnv)
-> IOEnv (Env TcGblEnv TcLclEnv) HscEnv
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> IOEnv (Env TcGblEnv TcLclEnv) (Env TcGblEnv TcLclEnv)
forall env. IOEnv env env
getEnv
  DynFlags
dflags <- IOEnv (Env TcGblEnv TcLclEnv) DynFlags
forall (m :: * -> *). HasDynFlags m => m DynFlags
getDynFlags
  if Bool -> Bool
not (GeneralFlag -> DynFlags -> Bool
gopt GeneralFlag
Opt_ExternalInterpreter DynFlags
dflags)
    then do
       -- Run it in the local TcM
      HValue
hv <- IO HValue -> IOEnv (Env TcGblEnv TcLclEnv) HValue
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IO HValue -> IOEnv (Env TcGblEnv TcLclEnv) HValue)
-> IO HValue -> IOEnv (Env TcGblEnv TcLclEnv) HValue
forall a b. (a -> b) -> a -> b
$ DynFlags -> ForeignHValue -> IO HValue
forall a. DynFlags -> ForeignRef a -> IO a
wormhole DynFlags
dflags ForeignHValue
fhv
      a
r <- Q a -> TcM a
forall a. Q a -> TcM a
runQuasi (HValue -> Q a
unsafeCoerce# HValue
hv :: TH.Q a)
      a -> TcM a
forall (m :: * -> *) a. Monad m => a -> m a
return a
r
    else
      -- 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.
      HscEnv -> (IServ -> TcM a) -> TcM a
forall (m :: * -> *) a.
(MonadIO m, ExceptionMonad m) =>
HscEnv -> (IServ -> m a) -> m a
withIServ HscEnv
hsc_env ((IServ -> TcM a) -> TcM a) -> (IServ -> TcM a) -> TcM a
forall a b. (a -> b) -> a -> b
$ \IServ
i -> do
        ForeignRef (IORef QState)
rstate <- IServ -> TcM (ForeignRef (IORef QState))
getTHState IServ
i
        Loc
loc <- TcM Loc
forall (m :: * -> *). Quasi m => m Loc
TH.qLocation
        IO () -> TcRn ()
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IO () -> TcRn ()) -> IO () -> TcRn ()
forall a b. (a -> b) -> a -> b
$
          ForeignRef (IORef QState)
-> (RemoteRef (IORef QState) -> IO ()) -> IO ()
forall a b. ForeignRef a -> (RemoteRef a -> IO b) -> IO b
withForeignRef ForeignRef (IORef QState)
rstate ((RemoteRef (IORef QState) -> IO ()) -> IO ())
-> (RemoteRef (IORef QState) -> IO ()) -> IO ()
forall a b. (a -> b) -> a -> b
$ \RemoteRef (IORef QState)
state_hv ->
          ForeignHValue -> (RemoteRef HValue -> IO ()) -> IO ()
forall a b. ForeignRef a -> (RemoteRef a -> IO b) -> IO b
withForeignRef ForeignHValue
fhv ((RemoteRef HValue -> IO ()) -> IO ())
-> (RemoteRef HValue -> IO ()) -> IO ()
forall a b. (a -> b) -> a -> b
$ \RemoteRef HValue
q_hv ->
            IServ -> Put -> IO ()
writeIServ IServ
i (Message (QResult ByteString) -> Put
forall a. Message a -> Put
putMessage (RemoteRef (IORef QState)
-> RemoteRef HValue
-> THResultType
-> Maybe Loc
-> Message (QResult ByteString)
RunTH RemoteRef (IORef QState)
state_hv RemoteRef HValue
q_hv THResultType
ty (Loc -> Maybe Loc
forall a. a -> Maybe a
Just Loc
loc)))
        IServ -> [Messages] -> TcRn ()
runRemoteTH IServ
i []
        ByteString
bs <- IServ -> TcM ByteString
forall a. Binary a => IServ -> TcM a
readQResult IServ
i
        a -> TcM a
forall (m :: * -> *) a. Monad m => a -> m a
return (a -> TcM a) -> a -> TcM a
forall a b. (a -> b) -> a -> b
$! Get a -> ByteString -> a
forall a. Get a -> ByteString -> a
runGet Get a
forall t. Binary t => Get t
get (ByteString -> ByteString
LB.fromStrict ByteString
bs)


-- | communicate with a remotely-running TH computation until it finishes.
-- See Note [Remote Template Haskell] in libraries/ghci/GHCi/TH.hs.
runRemoteTH
  :: IServ
  -> [Messages]   --  saved from nested calls to qRecover
  -> TcM ()
runRemoteTH :: IServ -> [Messages] -> TcRn ()
runRemoteTH IServ
iserv [Messages]
recovers = do
  THMsg THMessage a
msg <- IO THMsg -> IOEnv (Env TcGblEnv TcLclEnv) THMsg
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IO THMsg -> IOEnv (Env TcGblEnv TcLclEnv) THMsg)
-> IO THMsg -> IOEnv (Env TcGblEnv TcLclEnv) THMsg
forall a b. (a -> b) -> a -> b
$ IServ -> Get THMsg -> IO THMsg
forall a. IServ -> Get a -> IO a
readIServ IServ
iserv Get THMsg
getTHMessage
  case THMessage a
msg of
    THMessage a
RunTHDone -> () -> TcRn ()
forall (m :: * -> *) a. Monad m => a -> m a
return ()
    THMessage a
StartRecover -> do -- Note [TH recover with -fexternal-interpreter]
      TcRef Messages
v <- TcRn (TcRef Messages)
getErrsVar
      Messages
msgs <- TcRef Messages -> TcRnIf TcGblEnv TcLclEnv Messages
forall a gbl lcl. TcRef a -> TcRnIf gbl lcl a
readTcRef TcRef Messages
v
      TcRef Messages -> Messages -> TcRn ()
forall a gbl lcl. TcRef a -> a -> TcRnIf gbl lcl ()
writeTcRef TcRef Messages
v Messages
emptyMessages
      IServ -> [Messages] -> TcRn ()
runRemoteTH IServ
iserv (Messages
msgs Messages -> [Messages] -> [Messages]
forall a. a -> [a] -> [a]
: [Messages]
recovers)
    EndRecover Bool
caught_error -> do
      let (prev_msgs :: Messages
prev_msgs@(WarningMessages
prev_warns,WarningMessages
prev_errs), [Messages]
rest) = case [Messages]
recovers of
             [] -> String -> (Messages, [Messages])
forall a. String -> a
panic String
"EndRecover"
             Messages
a : [Messages]
b -> (Messages
a,[Messages]
b)
      TcRef Messages
v <- TcRn (TcRef Messages)
getErrsVar
      (WarningMessages
warn_msgs,WarningMessages
_) <- TcRef Messages -> TcRnIf TcGblEnv TcLclEnv Messages
forall a gbl lcl. TcRef a -> TcRnIf gbl lcl a
readTcRef TcRef Messages
v
      -- keep the warnings only if there were no errors
      TcRef Messages -> Messages -> TcRn ()
forall a gbl lcl. TcRef a -> a -> TcRnIf gbl lcl ()
writeTcRef TcRef Messages
v (Messages -> TcRn ()) -> Messages -> TcRn ()
forall a b. (a -> b) -> a -> b
$ if Bool
caught_error
        then Messages
prev_msgs
        else (WarningMessages
prev_warns WarningMessages -> WarningMessages -> WarningMessages
forall a. Bag a -> Bag a -> Bag a
`unionBags` WarningMessages
warn_msgs, WarningMessages
prev_errs)
      IServ -> [Messages] -> TcRn ()
runRemoteTH IServ
iserv [Messages]
rest
    THMessage a
_other -> do
      a
r <- THMessage a -> TcM a
forall a. THMessage a -> TcM a
handleTHMessage THMessage a
msg
      IO () -> TcRn ()
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IO () -> TcRn ()) -> IO () -> TcRn ()
forall a b. (a -> b) -> a -> b
$ IServ -> Put -> IO ()
writeIServ IServ
iserv (a -> Put
forall t. Binary t => t -> Put
put a
r)
      IServ -> [Messages] -> TcRn ()
runRemoteTH IServ
iserv [Messages]
recovers

-- | Read a value of type QResult from the iserv
readQResult :: Binary a => IServ -> TcM a
readQResult :: IServ -> TcM a
readQResult IServ
i = do
  QResult a
qr <- IO (QResult a) -> IOEnv (Env TcGblEnv TcLclEnv) (QResult a)
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IO (QResult a) -> IOEnv (Env TcGblEnv TcLclEnv) (QResult a))
-> IO (QResult a) -> IOEnv (Env TcGblEnv TcLclEnv) (QResult a)
forall a b. (a -> b) -> a -> b
$ IServ -> Get (QResult a) -> IO (QResult a)
forall a. IServ -> Get a -> IO a
readIServ IServ
i Get (QResult a)
forall t. Binary t => Get t
get
  case QResult a
qr of
    QDone a
a -> a -> TcM a
forall (m :: * -> *) a. Monad m => a -> m a
return a
a
    QException String
str -> IO a -> TcM a
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IO a -> TcM a) -> IO a -> TcM a
forall a b. (a -> b) -> a -> b
$ ErrorCall -> IO a
forall e a. Exception e => e -> IO a
throwIO (String -> ErrorCall
ErrorCall String
str)
    QFail String
str -> String -> TcM a
forall (m :: * -> *) a. MonadFail m => String -> m a
fail String
str

{- Note [TH recover with -fexternal-interpreter]

Recover is slightly tricky to implement.

The meaning of "recover a b" is
 - Do a
   - If it finished with no errors, then keep the warnings it generated
   - If it failed, discard any messages it generated, and do b

Note that "failed" here can mean either
  (1) threw an exception (failTc)
  (2) generated an error message (addErrTcM)

The messages are managed by GHC in the TcM monad, whereas the
exception-handling is done in the ghc-iserv process, so we have to
coordinate between the two.

On the server:
  - emit a StartRecover message
  - run "a; FailIfErrs" inside a try
  - emit an (EndRecover x) message, where x = True if "a; FailIfErrs" failed
  - if "a; FailIfErrs" failed, run "b"

Back in GHC, when we receive:

  FailIfErrrs
    failTc if there are any error messages (= failIfErrsM)
  StartRecover
    save the current messages and start with an empty set.
  EndRecover caught_error
    Restore the previous messages,
    and merge in the new messages if caught_error is false.
-}

-- | Retrieve (or create, if it hasn't been created already), the
-- remote TH state.  The TH state is a remote reference to an IORef
-- QState living on the server, and we have to pass this to each RunTH
-- call we make.
--
-- The TH state is stored in tcg_th_remote_state in the TcGblEnv.
--
getTHState :: IServ -> TcM (ForeignRef (IORef QState))
getTHState :: IServ -> TcM (ForeignRef (IORef QState))
getTHState IServ
i = do
  TcGblEnv
tcg <- TcRnIf TcGblEnv TcLclEnv TcGblEnv
forall gbl lcl. TcRnIf gbl lcl gbl
getGblEnv
  Maybe (ForeignRef (IORef QState))
th_state <- TcRef (Maybe (ForeignRef (IORef QState)))
-> TcRnIf TcGblEnv TcLclEnv (Maybe (ForeignRef (IORef QState)))
forall a gbl lcl. TcRef a -> TcRnIf gbl lcl a
readTcRef (TcGblEnv -> TcRef (Maybe (ForeignRef (IORef QState)))
tcg_th_remote_state TcGblEnv
tcg)
  case Maybe (ForeignRef (IORef QState))
th_state of
    Just ForeignRef (IORef QState)
rhv -> ForeignRef (IORef QState) -> TcM (ForeignRef (IORef QState))
forall (m :: * -> *) a. Monad m => a -> m a
return ForeignRef (IORef QState)
rhv
    Maybe (ForeignRef (IORef QState))
Nothing -> do
      HscEnv
hsc_env <- Env TcGblEnv TcLclEnv -> HscEnv
forall gbl lcl. Env gbl lcl -> HscEnv
env_top (Env TcGblEnv TcLclEnv -> HscEnv)
-> IOEnv (Env TcGblEnv TcLclEnv) (Env TcGblEnv TcLclEnv)
-> IOEnv (Env TcGblEnv TcLclEnv) HscEnv
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> IOEnv (Env TcGblEnv TcLclEnv) (Env TcGblEnv TcLclEnv)
forall env. IOEnv env env
getEnv
      ForeignRef (IORef QState)
fhv <- IO (ForeignRef (IORef QState)) -> TcM (ForeignRef (IORef QState))
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IO (ForeignRef (IORef QState)) -> TcM (ForeignRef (IORef QState)))
-> IO (ForeignRef (IORef QState))
-> TcM (ForeignRef (IORef QState))
forall a b. (a -> b) -> a -> b
$ HscEnv
-> RemoteRef (IORef QState) -> IO (ForeignRef (IORef QState))
forall a. HscEnv -> RemoteRef a -> IO (ForeignRef a)
mkFinalizedHValue HscEnv
hsc_env (RemoteRef (IORef QState) -> IO (ForeignRef (IORef QState)))
-> IO (RemoteRef (IORef QState)) -> IO (ForeignRef (IORef QState))
forall (m :: * -> *) a b. Monad m => (a -> m b) -> m a -> m b
=<< IServ
-> Message (RemoteRef (IORef QState))
-> IO (RemoteRef (IORef QState))
forall a. Binary a => IServ -> Message a -> IO a
iservCall IServ
i Message (RemoteRef (IORef QState))
StartTH
      TcRef (Maybe (ForeignRef (IORef QState)))
-> Maybe (ForeignRef (IORef QState)) -> TcRn ()
forall a gbl lcl. TcRef a -> a -> TcRnIf gbl lcl ()
writeTcRef (TcGblEnv -> TcRef (Maybe (ForeignRef (IORef QState)))
tcg_th_remote_state TcGblEnv
tcg) (ForeignRef (IORef QState) -> Maybe (ForeignRef (IORef QState))
forall a. a -> Maybe a
Just ForeignRef (IORef QState)
fhv)
      ForeignRef (IORef QState) -> TcM (ForeignRef (IORef QState))
forall (m :: * -> *) a. Monad m => a -> m a
return ForeignRef (IORef QState)
fhv

wrapTHResult :: TcM a -> TcM (THResult a)
wrapTHResult :: TcM a -> TcM (THResult a)
wrapTHResult TcM a
tcm = do
  Either IOEnvFailure a
e <- TcM a -> IOEnv (Env TcGblEnv TcLclEnv) (Either IOEnvFailure a)
forall env r. IOEnv env r -> IOEnv env (Either IOEnvFailure r)
tryM TcM a
tcm   -- only catch 'fail', treat everything else as catastrophic
  case Either IOEnvFailure a
e of
    Left IOEnvFailure
e -> THResult a -> TcM (THResult a)
forall (m :: * -> *) a. Monad m => a -> m a
return (String -> THResult a
forall a. String -> THResult a
THException (IOEnvFailure -> String
forall a. Show a => a -> String
show IOEnvFailure
e))
    Right a
a -> THResult a -> TcM (THResult a)
forall (m :: * -> *) a. Monad m => a -> m a
return (a -> THResult a
forall a. a -> THResult a
THComplete a
a)

handleTHMessage :: THMessage a -> TcM a
handleTHMessage :: THMessage a -> TcM a
handleTHMessage THMessage a
msg = case THMessage a
msg of
  NewName String
a -> TcM Name -> TcM (THResult Name)
forall a. TcM a -> TcM (THResult a)
wrapTHResult (TcM Name -> TcM (THResult Name))
-> TcM Name -> TcM (THResult Name)
forall a b. (a -> b) -> a -> b
$ String -> TcM Name
forall (m :: * -> *). Quasi m => String -> m Name
TH.qNewName String
a
  Report Bool
b String
str -> TcRn () -> TcM (THResult ())
forall a. TcM a -> TcM (THResult a)
wrapTHResult (TcRn () -> TcM (THResult ())) -> TcRn () -> TcM (THResult ())
forall a b. (a -> b) -> a -> b
$ Bool -> String -> TcRn ()
forall (m :: * -> *). Quasi m => Bool -> String -> m ()
TH.qReport Bool
b String
str
  LookupName Bool
b String
str -> TcM (Maybe Name) -> TcM (THResult (Maybe Name))
forall a. TcM a -> TcM (THResult a)
wrapTHResult (TcM (Maybe Name) -> TcM (THResult (Maybe Name)))
-> TcM (Maybe Name) -> TcM (THResult (Maybe Name))
forall a b. (a -> b) -> a -> b
$ Bool -> String -> TcM (Maybe Name)
forall (m :: * -> *). Quasi m => Bool -> String -> m (Maybe Name)
TH.qLookupName Bool
b String
str
  Reify Name
n -> TcM Info -> TcM (THResult Info)
forall a. TcM a -> TcM (THResult a)
wrapTHResult (TcM Info -> TcM (THResult Info))
-> TcM Info -> TcM (THResult Info)
forall a b. (a -> b) -> a -> b
$ Name -> TcM Info
forall (m :: * -> *). Quasi m => Name -> m Info
TH.qReify Name
n
  ReifyFixity Name
n -> TcM (Maybe Fixity) -> TcM (THResult (Maybe Fixity))
forall a. TcM a -> TcM (THResult a)
wrapTHResult (TcM (Maybe Fixity) -> TcM (THResult (Maybe Fixity)))
-> TcM (Maybe Fixity) -> TcM (THResult (Maybe Fixity))
forall a b. (a -> b) -> a -> b
$ Name -> TcM (Maybe Fixity)
forall (m :: * -> *). Quasi m => Name -> m (Maybe Fixity)
TH.qReifyFixity Name
n
  ReifyType Name
n -> TcM Type -> TcM (THResult Type)
forall a. TcM a -> TcM (THResult a)
wrapTHResult (TcM Type -> TcM (THResult Type))
-> TcM Type -> TcM (THResult Type)
forall a b. (a -> b) -> a -> b
$ Name -> TcM Type
forall (m :: * -> *). Quasi m => Name -> m Type
TH.qReifyType Name
n
  ReifyInstances Name
n [Type]
ts -> TcM [Dec] -> TcM (THResult [Dec])
forall a. TcM a -> TcM (THResult a)
wrapTHResult (TcM [Dec] -> TcM (THResult [Dec]))
-> TcM [Dec] -> TcM (THResult [Dec])
forall a b. (a -> b) -> a -> b
$ Name -> [Type] -> TcM [Dec]
forall (m :: * -> *). Quasi m => Name -> [Type] -> m [Dec]
TH.qReifyInstances Name
n [Type]
ts
  ReifyRoles Name
n -> TcM [Role] -> TcM (THResult [Role])
forall a. TcM a -> TcM (THResult a)
wrapTHResult (TcM [Role] -> TcM (THResult [Role]))
-> TcM [Role] -> TcM (THResult [Role])
forall a b. (a -> b) -> a -> b
$ Name -> TcM [Role]
forall (m :: * -> *). Quasi m => Name -> m [Role]
TH.qReifyRoles Name
n
  ReifyAnnotations AnnLookup
lookup TypeRep
tyrep ->
    TcM [ByteString] -> TcM (THResult [ByteString])
forall a. TcM a -> TcM (THResult a)
wrapTHResult (TcM [ByteString] -> TcM (THResult [ByteString]))
-> TcM [ByteString] -> TcM (THResult [ByteString])
forall a b. (a -> b) -> a -> b
$ (([Word8] -> ByteString) -> [[Word8]] -> [ByteString]
forall a b. (a -> b) -> [a] -> [b]
map [Word8] -> ByteString
B.pack ([[Word8]] -> [ByteString])
-> IOEnv (Env TcGblEnv TcLclEnv) [[Word8]] -> TcM [ByteString]
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> AnnLookup -> TypeRep -> IOEnv (Env TcGblEnv TcLclEnv) [[Word8]]
getAnnotationsByTypeRep AnnLookup
lookup TypeRep
tyrep)
  ReifyModule Module
m -> TcM ModuleInfo -> TcM (THResult ModuleInfo)
forall a. TcM a -> TcM (THResult a)
wrapTHResult (TcM ModuleInfo -> TcM (THResult ModuleInfo))
-> TcM ModuleInfo -> TcM (THResult ModuleInfo)
forall a b. (a -> b) -> a -> b
$ Module -> TcM ModuleInfo
forall (m :: * -> *). Quasi m => Module -> m ModuleInfo
TH.qReifyModule Module
m
  ReifyConStrictness Name
nm -> TcM [DecidedStrictness] -> TcM (THResult [DecidedStrictness])
forall a. TcM a -> TcM (THResult a)
wrapTHResult (TcM [DecidedStrictness] -> TcM (THResult [DecidedStrictness]))
-> TcM [DecidedStrictness] -> TcM (THResult [DecidedStrictness])
forall a b. (a -> b) -> a -> b
$ Name -> TcM [DecidedStrictness]
forall (m :: * -> *). Quasi m => Name -> m [DecidedStrictness]
TH.qReifyConStrictness Name
nm
  AddDependentFile String
f -> TcRn () -> TcM (THResult ())
forall a. TcM a -> TcM (THResult a)
wrapTHResult (TcRn () -> TcM (THResult ())) -> TcRn () -> TcM (THResult ())
forall a b. (a -> b) -> a -> b
$ String -> TcRn ()
forall (m :: * -> *). Quasi m => String -> m ()
TH.qAddDependentFile String
f
  AddTempFile String
s -> IOEnv (Env TcGblEnv TcLclEnv) String -> TcM (THResult String)
forall a. TcM a -> TcM (THResult a)
wrapTHResult (IOEnv (Env TcGblEnv TcLclEnv) String -> TcM (THResult String))
-> IOEnv (Env TcGblEnv TcLclEnv) String -> TcM (THResult String)
forall a b. (a -> b) -> a -> b
$ String -> IOEnv (Env TcGblEnv TcLclEnv) String
forall (m :: * -> *). Quasi m => String -> m String
TH.qAddTempFile String
s
  AddModFinalizer RemoteRef (Q ())
r -> do
    HscEnv
hsc_env <- Env TcGblEnv TcLclEnv -> HscEnv
forall gbl lcl. Env gbl lcl -> HscEnv
env_top (Env TcGblEnv TcLclEnv -> HscEnv)
-> IOEnv (Env TcGblEnv TcLclEnv) (Env TcGblEnv TcLclEnv)
-> IOEnv (Env TcGblEnv TcLclEnv) HscEnv
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> IOEnv (Env TcGblEnv TcLclEnv) (Env TcGblEnv TcLclEnv)
forall env. IOEnv env env
getEnv
    TcRn () -> TcM (THResult ())
forall a. TcM a -> TcM (THResult a)
wrapTHResult (TcRn () -> TcM (THResult ())) -> TcRn () -> TcM (THResult ())
forall a b. (a -> b) -> a -> b
$ IO (ForeignRef (Q ()))
-> IOEnv (Env TcGblEnv TcLclEnv) (ForeignRef (Q ()))
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (HscEnv -> RemoteRef (Q ()) -> IO (ForeignRef (Q ()))
forall a. HscEnv -> RemoteRef a -> IO (ForeignRef a)
mkFinalizedHValue HscEnv
hsc_env RemoteRef (Q ())
r) IOEnv (Env TcGblEnv TcLclEnv) (ForeignRef (Q ()))
-> (ForeignRef (Q ()) -> TcRn ()) -> TcRn ()
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= ForeignRef (Q ()) -> TcRn ()
addModFinalizerRef
  AddCorePlugin String
str -> TcRn () -> TcM (THResult ())
forall a. TcM a -> TcM (THResult a)
wrapTHResult (TcRn () -> TcM (THResult ())) -> TcRn () -> TcM (THResult ())
forall a b. (a -> b) -> a -> b
$ String -> TcRn ()
forall (m :: * -> *). Quasi m => String -> m ()
TH.qAddCorePlugin String
str
  AddTopDecls [Dec]
decs -> TcRn () -> TcM (THResult ())
forall a. TcM a -> TcM (THResult a)
wrapTHResult (TcRn () -> TcM (THResult ())) -> TcRn () -> TcM (THResult ())
forall a b. (a -> b) -> a -> b
$ [Dec] -> TcRn ()
forall (m :: * -> *). Quasi m => [Dec] -> m ()
TH.qAddTopDecls [Dec]
decs
  AddForeignFilePath ForeignSrcLang
lang String
str -> TcRn () -> TcM (THResult ())
forall a. TcM a -> TcM (THResult a)
wrapTHResult (TcRn () -> TcM (THResult ())) -> TcRn () -> TcM (THResult ())
forall a b. (a -> b) -> a -> b
$ ForeignSrcLang -> String -> TcRn ()
forall (m :: * -> *). Quasi m => ForeignSrcLang -> String -> m ()
TH.qAddForeignFilePath ForeignSrcLang
lang String
str
  IsExtEnabled Extension
ext -> TcRnIf TcGblEnv TcLclEnv Bool -> TcM (THResult Bool)
forall a. TcM a -> TcM (THResult a)
wrapTHResult (TcRnIf TcGblEnv TcLclEnv Bool -> TcM (THResult Bool))
-> TcRnIf TcGblEnv TcLclEnv Bool -> TcM (THResult Bool)
forall a b. (a -> b) -> a -> b
$ Extension -> TcRnIf TcGblEnv TcLclEnv Bool
forall (m :: * -> *). Quasi m => Extension -> m Bool
TH.qIsExtEnabled Extension
ext
  THMessage a
ExtsEnabled -> TcM [Extension] -> TcM (THResult [Extension])
forall a. TcM a -> TcM (THResult a)
wrapTHResult (TcM [Extension] -> TcM (THResult [Extension]))
-> TcM [Extension] -> TcM (THResult [Extension])
forall a b. (a -> b) -> a -> b
$ TcM [Extension]
forall (m :: * -> *). Quasi m => m [Extension]
TH.qExtsEnabled
  THMessage a
FailIfErrs -> TcRn () -> TcM (THResult ())
forall a. TcM a -> TcM (THResult a)
wrapTHResult TcRn ()
failIfErrsM
  THMessage a
_ -> String -> TcM a
forall a. String -> a
panic (String
"handleTHMessage: unexpected message " String -> String -> String
forall a. [a] -> [a] -> [a]
++ THMessage a -> String
forall a. Show a => a -> String
show THMessage a
msg)

getAnnotationsByTypeRep :: TH.AnnLookup -> TypeRep -> TcM [[Word8]]
getAnnotationsByTypeRep :: AnnLookup -> TypeRep -> IOEnv (Env TcGblEnv TcLclEnv) [[Word8]]
getAnnotationsByTypeRep AnnLookup
th_name TypeRep
tyrep
  = do { CoreAnnTarget
name <- AnnLookup -> TcM CoreAnnTarget
lookupThAnnLookup AnnLookup
th_name
       ; HscEnv
topEnv <- IOEnv (Env TcGblEnv TcLclEnv) HscEnv
forall gbl lcl. TcRnIf gbl lcl HscEnv
getTopEnv
       ; AnnEnv
epsHptAnns <- IO AnnEnv -> IOEnv (Env TcGblEnv TcLclEnv) AnnEnv
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IO AnnEnv -> IOEnv (Env TcGblEnv TcLclEnv) AnnEnv)
-> IO AnnEnv -> IOEnv (Env TcGblEnv TcLclEnv) AnnEnv
forall a b. (a -> b) -> a -> b
$ HscEnv -> Maybe ModGuts -> IO AnnEnv
prepareAnnotations HscEnv
topEnv Maybe ModGuts
forall a. Maybe a
Nothing
       ; TcGblEnv
tcg <- TcRnIf TcGblEnv TcLclEnv TcGblEnv
forall gbl lcl. TcRnIf gbl lcl gbl
getGblEnv
       ; let selectedEpsHptAnns :: [[Word8]]
selectedEpsHptAnns = AnnEnv -> CoreAnnTarget -> TypeRep -> [[Word8]]
findAnnsByTypeRep AnnEnv
epsHptAnns CoreAnnTarget
name TypeRep
tyrep
       ; let selectedTcgAnns :: [[Word8]]
selectedTcgAnns = AnnEnv -> CoreAnnTarget -> TypeRep -> [[Word8]]
findAnnsByTypeRep (TcGblEnv -> AnnEnv
tcg_ann_env TcGblEnv
tcg) CoreAnnTarget
name TypeRep
tyrep
       ; [[Word8]] -> IOEnv (Env TcGblEnv TcLclEnv) [[Word8]]
forall (m :: * -> *) a. Monad m => a -> m a
return ([[Word8]]
selectedEpsHptAnns [[Word8]] -> [[Word8]] -> [[Word8]]
forall a. [a] -> [a] -> [a]
++ [[Word8]]
selectedTcgAnns) }

{-
************************************************************************
*                                                                      *
            Instance Testing
*                                                                      *
************************************************************************
-}

reifyInstances :: TH.Name -> [TH.Type] -> TcM [TH.Dec]
reifyInstances :: Name -> [Type] -> TcM [Dec]
reifyInstances Name
th_nm [Type]
th_tys
   = MsgDoc -> TcM [Dec] -> TcM [Dec]
forall a. MsgDoc -> TcM a -> TcM a
addErrCtxt (String -> MsgDoc
text String
"In the argument of reifyInstances:"
                 MsgDoc -> MsgDoc -> MsgDoc
<+> Name -> MsgDoc
forall a. Ppr a => a -> MsgDoc
ppr_th Name
th_nm MsgDoc -> MsgDoc -> MsgDoc
<+> [MsgDoc] -> MsgDoc
sep ((Type -> MsgDoc) -> [Type] -> [MsgDoc]
forall a b. (a -> b) -> [a] -> [b]
map Type -> MsgDoc
forall a. Ppr a => a -> MsgDoc
ppr_th [Type]
th_tys)) (TcM [Dec] -> TcM [Dec]) -> TcM [Dec] -> TcM [Dec]
forall a b. (a -> b) -> a -> b
$
     do { SrcSpan
loc <- TcRn SrcSpan
getSrcSpanM
        ; Origin
th_origin <- TcM Origin
getThSpliceOrigin
        ; LHsType GhcPs
rdr_ty <- Origin
-> SrcSpan -> Type -> IOEnv (Env TcGblEnv TcLclEnv) (LHsType GhcPs)
cvt Origin
th_origin SrcSpan
loc (Type -> [Type] -> Type
mkThAppTs (Name -> Type
TH.ConT Name
th_nm) [Type]
th_tys)
          -- #9262 says to bring vars into scope, like in HsForAllTy case
          -- of rnHsTyKi
        ; let tv_rdrs :: FreeKiTyVarsNoDups
tv_rdrs = LHsType GhcPs -> FreeKiTyVarsNoDups
extractHsTyRdrTyVars LHsType GhcPs
rdr_ty
          -- Rename  to HsType Name
        ; (([Name]
tv_names, LHsType GhcRn
rn_ty), FreeVars
_fvs)
            <- TcM (([Name], LHsType GhcRn), FreeVars)
-> TcM (([Name], LHsType GhcRn), FreeVars)
forall r. TcM r -> TcM r
checkNoErrs (TcM (([Name], LHsType GhcRn), FreeVars)
 -> TcM (([Name], LHsType GhcRn), FreeVars))
-> TcM (([Name], LHsType GhcRn), FreeVars)
-> TcM (([Name], LHsType GhcRn), FreeVars)
forall a b. (a -> b) -> a -> b
$ -- If there are out-of-scope Names here, then we
                             -- must error before proceeding to typecheck the
                             -- renamed type, as that will result in GHC
                             -- internal errors (#13837).
               FreeKiTyVarsNoDups
-> ([Name] -> TcM (([Name], LHsType GhcRn), FreeVars))
-> TcM (([Name], LHsType GhcRn), FreeVars)
forall a.
FreeKiTyVarsNoDups
-> ([Name] -> RnM (a, FreeVars)) -> RnM (a, FreeVars)
bindLRdrNames FreeKiTyVarsNoDups
tv_rdrs (([Name] -> TcM (([Name], LHsType GhcRn), FreeVars))
 -> TcM (([Name], LHsType GhcRn), FreeVars))
-> ([Name] -> TcM (([Name], LHsType GhcRn), FreeVars))
-> TcM (([Name], LHsType GhcRn), FreeVars)
forall a b. (a -> b) -> a -> b
$ \ [Name]
tv_names ->
               do { (LHsType GhcRn
rn_ty, FreeVars
fvs) <- HsDocContext -> LHsType GhcPs -> RnM (LHsType GhcRn, FreeVars)
rnLHsType HsDocContext
doc LHsType GhcPs
rdr_ty
                  ; (([Name], LHsType GhcRn), FreeVars)
-> TcM (([Name], LHsType GhcRn), FreeVars)
forall (m :: * -> *) a. Monad m => a -> m a
return (([Name]
tv_names, LHsType GhcRn
rn_ty), FreeVars
fvs) }
        ; ([Id]
_tvs, TcRhoType
ty)
            <- TcM ([Id], TcRhoType) -> TcM ([Id], TcRhoType)
forall r. TcM r -> TcM r
pushTcLevelM_   (TcM ([Id], TcRhoType) -> TcM ([Id], TcRhoType))
-> TcM ([Id], TcRhoType) -> TcM ([Id], TcRhoType)
forall a b. (a -> b) -> a -> b
$
               TcM ([Id], TcRhoType) -> TcM ([Id], TcRhoType)
forall r. TcM r -> TcM r
solveEqualities (TcM ([Id], TcRhoType) -> TcM ([Id], TcRhoType))
-> TcM ([Id], TcRhoType) -> TcM ([Id], TcRhoType)
forall a b. (a -> b) -> a -> b
$ -- Avoid error cascade if there are unsolved
               [Name] -> TcM TcRhoType -> TcM ([Id], TcRhoType)
forall a. [Name] -> TcM a -> TcM ([Id], a)
bindImplicitTKBndrs_Skol [Name]
tv_names (TcM TcRhoType -> TcM ([Id], TcRhoType))
-> TcM TcRhoType -> TcM ([Id], TcRhoType)
forall a b. (a -> b) -> a -> b
$
               (TcRhoType, TcRhoType) -> TcRhoType
forall a b. (a, b) -> a
fst ((TcRhoType, TcRhoType) -> TcRhoType)
-> IOEnv (Env TcGblEnv TcLclEnv) (TcRhoType, TcRhoType)
-> TcM TcRhoType
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> LHsType GhcRn
-> IOEnv (Env TcGblEnv TcLclEnv) (TcRhoType, TcRhoType)
tcLHsType LHsType GhcRn
rn_ty
        ; TcRhoType
ty <- TcRhoType -> TcM TcRhoType
zonkTcTypeToType TcRhoType
ty
                -- Substitute out the meta type variables
                -- In particular, the type might have kind
                -- variables inside it (#7477)

        ; String -> MsgDoc -> TcRn ()
traceTc String
"reifyInstances" (TcRhoType -> MsgDoc
forall a. Outputable a => a -> MsgDoc
ppr TcRhoType
ty MsgDoc -> MsgDoc -> MsgDoc
$$ TcRhoType -> MsgDoc
forall a. Outputable a => a -> MsgDoc
ppr (HasDebugCallStack => TcRhoType -> TcRhoType
TcRhoType -> TcRhoType
tcTypeKind TcRhoType
ty))
        ; case HasDebugCallStack => TcRhoType -> Maybe (TyCon, [TcRhoType])
TcRhoType -> Maybe (TyCon, [TcRhoType])
splitTyConApp_maybe TcRhoType
ty of   -- This expands any type synonyms
            Just (TyCon
tc, [TcRhoType]
tys)                 -- See #7910
               | Just Class
cls <- TyCon -> Maybe Class
tyConClass_maybe TyCon
tc
               -> do { InstEnvs
inst_envs <- TcM InstEnvs
tcGetInstEnvs
                     ; let ([InstMatch]
matches, [ClsInst]
unifies, [InstMatch]
_) = Bool
-> InstEnvs
-> Class
-> [TcRhoType]
-> ([InstMatch], [ClsInst], [InstMatch])
lookupInstEnv Bool
False InstEnvs
inst_envs Class
cls [TcRhoType]
tys
                     ; String -> MsgDoc -> TcRn ()
traceTc String
"reifyInstances1" ([InstMatch] -> MsgDoc
forall a. Outputable a => a -> MsgDoc
ppr [InstMatch]
matches)
                     ; Class -> [ClsInst] -> TcM [Dec]
reifyClassInstances Class
cls ((InstMatch -> ClsInst) -> [InstMatch] -> [ClsInst]
forall a b. (a -> b) -> [a] -> [b]
map InstMatch -> ClsInst
forall a b. (a, b) -> a
fst [InstMatch]
matches [ClsInst] -> [ClsInst] -> [ClsInst]
forall a. [a] -> [a] -> [a]
++ [ClsInst]
unifies) }
               | TyCon -> Bool
isOpenFamilyTyCon TyCon
tc
               -> do { FamInstEnvs
inst_envs <- TcM FamInstEnvs
tcGetFamInstEnvs
                     ; let matches :: [FamInstMatch]
matches = FamInstEnvs -> TyCon -> [TcRhoType] -> [FamInstMatch]
lookupFamInstEnv FamInstEnvs
inst_envs TyCon
tc [TcRhoType]
tys
                     ; String -> MsgDoc -> TcRn ()
traceTc String
"reifyInstances2" ([FamInstMatch] -> MsgDoc
forall a. Outputable a => a -> MsgDoc
ppr [FamInstMatch]
matches)
                     ; TyCon -> [FamInst] -> TcM [Dec]
reifyFamilyInstances TyCon
tc ((FamInstMatch -> FamInst) -> [FamInstMatch] -> [FamInst]
forall a b. (a -> b) -> [a] -> [b]
map FamInstMatch -> FamInst
fim_instance [FamInstMatch]
matches) }
            Maybe (TyCon, [TcRhoType])
_  -> MsgDoc -> TcM [Dec]
forall a. MsgDoc -> TcM a
bale_out (MsgDoc -> Int -> MsgDoc -> MsgDoc
hang (String -> MsgDoc
text String
"reifyInstances:" MsgDoc -> MsgDoc -> MsgDoc
<+> MsgDoc -> MsgDoc
quotes (TcRhoType -> MsgDoc
forall a. Outputable a => a -> MsgDoc
ppr TcRhoType
ty))
                               Int
2 (String -> MsgDoc
text String
"is not a class constraint or type family application")) }
  where
    doc :: HsDocContext
doc = HsDocContext
ClassInstanceCtx
    bale_out :: MsgDoc -> TcM a
bale_out MsgDoc
msg = MsgDoc -> TcM a
forall a. MsgDoc -> TcM a
failWithTc MsgDoc
msg

    cvt :: Origin -> SrcSpan -> TH.Type -> TcM (LHsType GhcPs)
    cvt :: Origin
-> SrcSpan -> Type -> IOEnv (Env TcGblEnv TcLclEnv) (LHsType GhcPs)
cvt Origin
origin SrcSpan
loc Type
th_ty = case Origin -> SrcSpan -> Type -> Either MsgDoc (LHsType GhcPs)
convertToHsType Origin
origin SrcSpan
loc Type
th_ty of
      Left MsgDoc
msg -> MsgDoc -> IOEnv (Env TcGblEnv TcLclEnv) (LHsType GhcPs)
forall a. MsgDoc -> TcM a
failWithTc MsgDoc
msg
      Right LHsType GhcPs
ty -> LHsType GhcPs -> IOEnv (Env TcGblEnv TcLclEnv) (LHsType GhcPs)
forall (m :: * -> *) a. Monad m => a -> m a
return LHsType GhcPs
ty

{-
************************************************************************
*                                                                      *
                        Reification
*                                                                      *
************************************************************************
-}

lookupName :: Bool      -- True  <=> type namespace
                        -- False <=> value namespace
           -> String -> TcM (Maybe TH.Name)
lookupName :: Bool -> String -> TcM (Maybe Name)
lookupName Bool
is_type_name String
s
  = do { LocalRdrEnv
lcl_env <- RnM LocalRdrEnv
getLocalRdrEnv
       ; case LocalRdrEnv -> RdrName -> Maybe Name
lookupLocalRdrEnv LocalRdrEnv
lcl_env RdrName
rdr_name of
           Just Name
n  -> Maybe Name -> TcM (Maybe Name)
forall (m :: * -> *) a. Monad m => a -> m a
return (Name -> Maybe Name
forall a. a -> Maybe a
Just (Name -> Name
forall n. NamedThing n => n -> Name
reifyName Name
n))
           Maybe Name
Nothing -> do { Maybe Name
mb_nm <- RdrName -> RnM (Maybe Name)
lookupGlobalOccRn_maybe RdrName
rdr_name
                         ; Maybe Name -> TcM (Maybe Name)
forall (m :: * -> *) a. Monad m => a -> m a
return ((Name -> Name) -> Maybe Name -> Maybe Name
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap Name -> Name
forall n. NamedThing n => n -> Name
reifyName Maybe Name
mb_nm) } }
  where
    th_name :: Name
th_name = String -> Name
TH.mkName String
s       -- Parses M.x into a base of 'x' and a module of 'M'

    occ_fs :: FastString
    occ_fs :: FastString
occ_fs = String -> FastString
mkFastString (Name -> String
TH.nameBase Name
th_name)

    occ :: OccName
    occ :: OccName
occ | Bool
is_type_name
        = if FastString -> Bool
isLexVarSym FastString
occ_fs Bool -> Bool -> Bool
|| FastString -> Bool
isLexCon FastString
occ_fs
                             then FastString -> OccName
mkTcOccFS    FastString
occ_fs
                             else FastString -> OccName
mkTyVarOccFS FastString
occ_fs
        | Bool
otherwise
        = if FastString -> Bool
isLexCon FastString
occ_fs then FastString -> OccName
mkDataOccFS FastString
occ_fs
                             else FastString -> OccName
mkVarOccFS  FastString
occ_fs

    rdr_name :: RdrName
rdr_name = case Name -> Maybe String
TH.nameModule Name
th_name of
                 Maybe String
Nothing  -> OccName -> RdrName
mkRdrUnqual OccName
occ
                 Just String
mod -> ModuleName -> OccName -> RdrName
mkRdrQual (String -> ModuleName
mkModuleName String
mod) OccName
occ

getThing :: TH.Name -> TcM TcTyThing
getThing :: Name -> TcM TcTyThing
getThing Name
th_name
  = do  { Name
name <- Name -> TcM Name
lookupThName Name
th_name
        ; MsgDoc -> TcRn ()
forall m n. MsgDoc -> TcRnIf m n ()
traceIf (String -> MsgDoc
text String
"reify" MsgDoc -> MsgDoc -> MsgDoc
<+> String -> MsgDoc
text (Name -> String
forall a. Show a => a -> String
show Name
th_name) MsgDoc -> MsgDoc -> MsgDoc
<+> MsgDoc -> MsgDoc
brackets (Name -> MsgDoc
ppr_ns Name
th_name) MsgDoc -> MsgDoc -> MsgDoc
<+> Name -> MsgDoc
forall a. Outputable a => a -> MsgDoc
ppr Name
name)
        ; Name -> TcM TcTyThing
tcLookupTh Name
name }
        -- ToDo: this tcLookup could fail, which would give a
        --       rather unhelpful error message
  where
    ppr_ns :: Name -> MsgDoc
ppr_ns (TH.Name OccName
_ (TH.NameG NameSpace
TH.DataName  PkgName
_pkg ModName
_mod)) = String -> MsgDoc
text String
"data"
    ppr_ns (TH.Name OccName
_ (TH.NameG NameSpace
TH.TcClsName PkgName
_pkg ModName
_mod)) = String -> MsgDoc
text String
"tc"
    ppr_ns (TH.Name OccName
_ (TH.NameG NameSpace
TH.VarName   PkgName
_pkg ModName
_mod)) = String -> MsgDoc
text String
"var"
    ppr_ns Name
_ = String -> MsgDoc
forall a. String -> a
panic String
"reify/ppr_ns"

reify :: TH.Name -> TcM TH.Info
reify :: Name -> TcM Info
reify Name
th_name
  = do  { String -> MsgDoc -> TcRn ()
traceTc String
"reify 1" (String -> MsgDoc
text (Name -> String
TH.showName Name
th_name))
        ; TcTyThing
thing <- Name -> TcM TcTyThing
getThing Name
th_name
        ; String -> MsgDoc -> TcRn ()
traceTc String
"reify 2" (TcTyThing -> MsgDoc
forall a. Outputable a => a -> MsgDoc
ppr TcTyThing
thing)
        ; TcTyThing -> TcM Info
reifyThing TcTyThing
thing }

lookupThName :: TH.Name -> TcM Name
lookupThName :: Name -> TcM Name
lookupThName Name
th_name = do
    Maybe Name
mb_name <- Name -> RnM (Maybe Name)
lookupThName_maybe Name
th_name
    case Maybe Name
mb_name of
        Maybe Name
Nothing   -> MsgDoc -> TcM Name
forall a. MsgDoc -> TcM a
failWithTc (Name -> MsgDoc
notInScope Name
th_name)
        Just Name
name -> Name -> TcM Name
forall (m :: * -> *) a. Monad m => a -> m a
return Name
name

lookupThName_maybe :: TH.Name -> TcM (Maybe Name)
lookupThName_maybe :: Name -> RnM (Maybe Name)
lookupThName_maybe Name
th_name
  =  do { [Name]
names <- (RdrName -> RnM (Maybe Name))
-> [RdrName] -> IOEnv (Env TcGblEnv TcLclEnv) [Name]
forall (m :: * -> *) a b.
Applicative m =>
(a -> m (Maybe b)) -> [a] -> m [b]
mapMaybeM RdrName -> RnM (Maybe Name)
lookup (Name -> [RdrName]
thRdrNameGuesses Name
th_name)
          -- Pick the first that works
          -- E.g. reify (mkName "A") will pick the class A in preference to the data constructor A
        ; Maybe Name -> RnM (Maybe Name)
forall (m :: * -> *) a. Monad m => a -> m a
return ([Name] -> Maybe Name
forall a. [a] -> Maybe a
listToMaybe [Name]
names) }
  where
    lookup :: RdrName -> RnM (Maybe Name)
lookup RdrName
rdr_name
        = do {  -- Repeat much of lookupOccRn, because we want
                -- to report errors in a TH-relevant way
             ; LocalRdrEnv
rdr_env <- RnM LocalRdrEnv
getLocalRdrEnv
             ; case LocalRdrEnv -> RdrName -> Maybe Name
lookupLocalRdrEnv LocalRdrEnv
rdr_env RdrName
rdr_name of
                 Just Name
name -> Maybe Name -> RnM (Maybe Name)
forall (m :: * -> *) a. Monad m => a -> m a
return (Name -> Maybe Name
forall a. a -> Maybe a
Just Name
name)
                 Maybe Name
Nothing   -> RdrName -> RnM (Maybe Name)
lookupGlobalOccRn_maybe RdrName
rdr_name }

tcLookupTh :: Name -> TcM TcTyThing
-- This is a specialised version of TcEnv.tcLookup; specialised mainly in that
-- it gives a reify-related error message on failure, whereas in the normal
-- tcLookup, failure is a bug.
tcLookupTh :: Name -> TcM TcTyThing
tcLookupTh Name
name
  = do  { (TcGblEnv
gbl_env, TcLclEnv
lcl_env) <- TcRnIf TcGblEnv TcLclEnv (TcGblEnv, TcLclEnv)
forall gbl lcl. TcRnIf gbl lcl (gbl, lcl)
getEnvs
        ; case NameEnv TcTyThing -> Name -> Maybe TcTyThing
forall a. NameEnv a -> Name -> Maybe a
lookupNameEnv (TcLclEnv -> NameEnv TcTyThing
tcl_env TcLclEnv
lcl_env) Name
name of {
                Just TcTyThing
thing -> TcTyThing -> TcM TcTyThing
forall (m :: * -> *) a. Monad m => a -> m a
return TcTyThing
thing;
                Maybe TcTyThing
Nothing    ->

          case NameEnv TyThing -> Name -> Maybe TyThing
forall a. NameEnv a -> Name -> Maybe a
lookupNameEnv (TcGblEnv -> NameEnv TyThing
tcg_type_env TcGblEnv
gbl_env) Name
name of {
                Just TyThing
thing -> TcTyThing -> TcM TcTyThing
forall (m :: * -> *) a. Monad m => a -> m a
return (TyThing -> TcTyThing
AGlobal TyThing
thing);
                Maybe TyThing
Nothing    ->

          -- EZY: I don't think this choice matters, no TH in signatures!
          if Module -> Name -> Bool
nameIsLocalOrFrom (TcGblEnv -> Module
tcg_semantic_mod TcGblEnv
gbl_env) Name
name
          then  -- It's defined in this module
                MsgDoc -> TcM TcTyThing
forall a. MsgDoc -> TcM a
failWithTc (Name -> MsgDoc
notInEnv Name
name)

          else
     do { MaybeErr MsgDoc TyThing
mb_thing <- Name -> TcM (MaybeErr MsgDoc TyThing)
tcLookupImported_maybe Name
name
        ; case MaybeErr MsgDoc TyThing
mb_thing of
            Succeeded TyThing
thing -> TcTyThing -> TcM TcTyThing
forall (m :: * -> *) a. Monad m => a -> m a
return (TyThing -> TcTyThing
AGlobal TyThing
thing)
            Failed MsgDoc
msg      -> MsgDoc -> TcM TcTyThing
forall a. MsgDoc -> TcM a
failWithTc MsgDoc
msg
    }}}}

notInScope :: TH.Name -> SDoc
notInScope :: Name -> MsgDoc
notInScope Name
th_name = MsgDoc -> MsgDoc
quotes (String -> MsgDoc
text (Name -> String
forall a. Ppr a => a -> String
TH.pprint Name
th_name)) MsgDoc -> MsgDoc -> MsgDoc
<+>
                     String -> MsgDoc
text String
"is not in scope at a reify"
        -- Ugh! Rather an indirect way to display the name

notInEnv :: Name -> SDoc
notInEnv :: Name -> MsgDoc
notInEnv Name
name = MsgDoc -> MsgDoc
quotes (Name -> MsgDoc
forall a. Outputable a => a -> MsgDoc
ppr Name
name) MsgDoc -> MsgDoc -> MsgDoc
<+>
                     String -> MsgDoc
text String
"is not in the type environment at a reify"

------------------------------
reifyRoles :: TH.Name -> TcM [TH.Role]
reifyRoles :: Name -> TcM [Role]
reifyRoles Name
th_name
  = do { TcTyThing
thing <- Name -> TcM TcTyThing
getThing Name
th_name
       ; case TcTyThing
thing of
           AGlobal (ATyCon TyCon
tc) -> [Role] -> TcM [Role]
forall (m :: * -> *) a. Monad m => a -> m a
return ((Role -> Role) -> [Role] -> [Role]
forall a b. (a -> b) -> [a] -> [b]
map Role -> Role
reify_role (TyCon -> [Role]
tyConRoles TyCon
tc))
           TcTyThing
_ -> MsgDoc -> TcM [Role]
forall a. MsgDoc -> TcM a
failWithTc (String -> MsgDoc
text String
"No roles associated with" MsgDoc -> MsgDoc -> MsgDoc
<+> (TcTyThing -> MsgDoc
forall a. Outputable a => a -> MsgDoc
ppr TcTyThing
thing))
       }
  where
    reify_role :: Role -> Role
reify_role Role
Nominal          = Role
TH.NominalR
    reify_role Role
Representational = Role
TH.RepresentationalR
    reify_role Role
Phantom          = Role
TH.PhantomR

------------------------------
reifyThing :: TcTyThing -> TcM TH.Info
-- The only reason this is monadic is for error reporting,
-- which in turn is mainly for the case when TH can't express
-- some random GHC extension

reifyThing :: TcTyThing -> TcM Info
reifyThing (AGlobal (AnId Id
id))
  = do  { Type
ty <- TcRhoType -> TcM Type
reifyType (Id -> TcRhoType
idType Id
id)
        ; let v :: Name
v = Id -> Name
forall n. NamedThing n => n -> Name
reifyName Id
id
        ; case Id -> IdDetails
idDetails Id
id of
            ClassOpId Class
cls -> Info -> TcM Info
forall (m :: * -> *) a. Monad m => a -> m a
return (Name -> Type -> Name -> Info
TH.ClassOpI Name
v Type
ty (Class -> Name
forall n. NamedThing n => n -> Name
reifyName Class
cls))
            RecSelId{sel_tycon :: IdDetails -> RecSelParent
sel_tycon=RecSelData TyCon
tc}
                          -> Info -> TcM Info
forall (m :: * -> *) a. Monad m => a -> m a
return (Name -> Type -> Maybe Dec -> Info
TH.VarI (Id -> TyCon -> Name
reifySelector Id
id TyCon
tc) Type
ty Maybe Dec
forall a. Maybe a
Nothing)
            IdDetails
_             -> Info -> TcM Info
forall (m :: * -> *) a. Monad m => a -> m a
return (Name -> Type -> Maybe Dec -> Info
TH.VarI     Name
v Type
ty Maybe Dec
forall a. Maybe a
Nothing)
    }

reifyThing (AGlobal (ATyCon TyCon
tc))   = TyCon -> TcM Info
reifyTyCon TyCon
tc
reifyThing (AGlobal (AConLike (RealDataCon DataCon
dc)))
  = do  { let name :: Name
name = DataCon -> Name
dataConName DataCon
dc
        ; Type
ty <- TcRhoType -> TcM Type
reifyType (Id -> TcRhoType
idType (DataCon -> Id
dataConWrapId DataCon
dc))
        ; Info -> TcM Info
forall (m :: * -> *) a. Monad m => a -> m a
return (Name -> Type -> Name -> Info
TH.DataConI (Name -> Name
forall n. NamedThing n => n -> Name
reifyName Name
name) Type
ty
                              (TyCon -> Name
forall n. NamedThing n => n -> Name
reifyName (DataCon -> TyCon
dataConOrigTyCon DataCon
dc)))
        }

reifyThing (AGlobal (AConLike (PatSynCon PatSyn
ps)))
  = do { let name :: Name
name = PatSyn -> Name
forall n. NamedThing n => n -> Name
reifyName PatSyn
ps
       ; Type
ty <- ([Id], [TcRhoType], [Id], [TcRhoType], [TcRhoType], TcRhoType)
-> TcM Type
reifyPatSynType (PatSyn
-> ([Id], [TcRhoType], [Id], [TcRhoType], [TcRhoType], TcRhoType)
patSynSig PatSyn
ps)
       ; Info -> TcM Info
forall (m :: * -> *) a. Monad m => a -> m a
return (Name -> Type -> Info
TH.PatSynI Name
name Type
ty) }

reifyThing (ATcId {tct_id :: TcTyThing -> Id
tct_id = Id
id})
  = do  { TcRhoType
ty1 <- TcRhoType -> TcM TcRhoType
zonkTcType (Id -> TcRhoType
idType Id
id) -- Make use of all the info we have, even
                                        -- though it may be incomplete
        ; Type
ty2 <- TcRhoType -> TcM Type
reifyType TcRhoType
ty1
        ; Info -> TcM Info
forall (m :: * -> *) a. Monad m => a -> m a
return (Name -> Type -> Maybe Dec -> Info
TH.VarI (Id -> Name
forall n. NamedThing n => n -> Name
reifyName Id
id) Type
ty2 Maybe Dec
forall a. Maybe a
Nothing) }

reifyThing (ATyVar Name
tv Id
tv1)
  = do { TcRhoType
ty1 <- Id -> TcM TcRhoType
zonkTcTyVar Id
tv1
       ; Type
ty2 <- TcRhoType -> TcM Type
reifyType TcRhoType
ty1
       ; Info -> TcM Info
forall (m :: * -> *) a. Monad m => a -> m a
return (Name -> Type -> Info
TH.TyVarI (Name -> Name
forall n. NamedThing n => n -> Name
reifyName Name
tv) Type
ty2) }

reifyThing TcTyThing
thing = String -> MsgDoc -> TcM Info
forall a. HasCallStack => String -> MsgDoc -> a
pprPanic String
"reifyThing" (TcTyThing -> MsgDoc
pprTcTyThingCategory TcTyThing
thing)

-------------------------------------------
reifyAxBranch :: TyCon -> CoAxBranch -> TcM TH.TySynEqn
reifyAxBranch :: TyCon -> CoAxBranch -> TcM TySynEqn
reifyAxBranch TyCon
fam_tc (CoAxBranch { cab_tvs :: CoAxBranch -> [Id]
cab_tvs = [Id]
tvs
                                 , cab_lhs :: CoAxBranch -> [TcRhoType]
cab_lhs = [TcRhoType]
lhs
                                 , cab_rhs :: CoAxBranch -> TcRhoType
cab_rhs = TcRhoType
rhs })
            -- remove kind patterns (#8884)
  = do { Maybe [TyVarBndr]
tvs' <- [Id] -> TcM (Maybe [TyVarBndr])
reifyTyVarsToMaybe [Id]
tvs
       ; let lhs_types_only :: [TcRhoType]
lhs_types_only = TyCon -> [TcRhoType] -> [TcRhoType]
filterOutInvisibleTypes TyCon
fam_tc [TcRhoType]
lhs
       ; [Type]
lhs' <- [TcRhoType] -> TcM [Type]
reifyTypes [TcRhoType]
lhs_types_only
       ; [Type]
annot_th_lhs <- (Bool -> TcRhoType -> Type -> TcM Type)
-> [Bool] -> [TcRhoType] -> [Type] -> TcM [Type]
forall (m :: * -> *) a b c d.
Monad m =>
(a -> b -> c -> m d) -> [a] -> [b] -> [c] -> m [d]
zipWith3M Bool -> TcRhoType -> Type -> TcM Type
annotThType (TyCon -> [Bool]
tyConArgsPolyKinded TyCon
fam_tc)
                                   [TcRhoType]
lhs_types_only [Type]
lhs'
       ; let lhs_type :: Type
lhs_type = Type -> [Type] -> Type
mkThAppTs (Name -> Type
TH.ConT (Name -> Type) -> Name -> Type
forall a b. (a -> b) -> a -> b
$ TyCon -> Name
forall n. NamedThing n => n -> Name
reifyName TyCon
fam_tc) [Type]
annot_th_lhs
       ; Type
rhs'  <- TcRhoType -> TcM Type
reifyType TcRhoType
rhs
       ; TySynEqn -> TcM TySynEqn
forall (m :: * -> *) a. Monad m => a -> m a
return (Maybe [TyVarBndr] -> Type -> Type -> TySynEqn
TH.TySynEqn Maybe [TyVarBndr]
tvs' Type
lhs_type Type
rhs') }

reifyTyCon :: TyCon -> TcM TH.Info
reifyTyCon :: TyCon -> TcM Info
reifyTyCon TyCon
tc
  | Just Class
cls <- TyCon -> Maybe Class
tyConClass_maybe TyCon
tc
  = Class -> TcM Info
reifyClass Class
cls

  | TyCon -> Bool
isFunTyCon TyCon
tc
  = Info -> TcM Info
forall (m :: * -> *) a. Monad m => a -> m a
return (Name -> Int -> Bool -> Info
TH.PrimTyConI (TyCon -> Name
forall n. NamedThing n => n -> Name
reifyName TyCon
tc) Int
2                Bool
False)

  | TyCon -> Bool
isPrimTyCon TyCon
tc
  = Info -> TcM Info
forall (m :: * -> *) a. Monad m => a -> m a
return (Name -> Int -> Bool -> Info
TH.PrimTyConI (TyCon -> Name
forall n. NamedThing n => n -> Name
reifyName TyCon
tc) ([Id] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length (TyCon -> [Id]
tyConVisibleTyVars TyCon
tc))
                          (TyCon -> Bool
isUnliftedTyCon TyCon
tc))

  | TyCon -> Bool
isTypeFamilyTyCon TyCon
tc
  = do { let tvs :: [Id]
tvs      = TyCon -> [Id]
tyConTyVars TyCon
tc
             res_kind :: TcRhoType
res_kind = TyCon -> TcRhoType
tyConResKind TyCon
tc
             resVar :: Maybe Name
resVar   = TyCon -> Maybe Name
famTcResVar TyCon
tc

       ; Type
kind' <- TcRhoType -> TcM Type
reifyKind TcRhoType
res_kind
       ; let (FamilyResultSig
resultSig, Maybe InjectivityAnn
injectivity) =
                 case Maybe Name
resVar of
                   Maybe Name
Nothing   -> (Type -> FamilyResultSig
TH.KindSig Type
kind', Maybe InjectivityAnn
forall a. Maybe a
Nothing)
                   Just Name
name ->
                     let thName :: Name
thName   = Name -> Name
forall n. NamedThing n => n -> Name
reifyName Name
name
                         injAnnot :: Injectivity
injAnnot = TyCon -> Injectivity
tyConInjectivityInfo TyCon
tc
                         sig :: FamilyResultSig
sig = TyVarBndr -> FamilyResultSig
TH.TyVarSig (Name -> Type -> TyVarBndr
TH.KindedTV Name
thName Type
kind')
                         inj :: Maybe InjectivityAnn
inj = case Injectivity
injAnnot of
                                 Injectivity
NotInjective -> Maybe InjectivityAnn
forall a. Maybe a
Nothing
                                 Injective [Bool]
ms ->
                                     InjectivityAnn -> Maybe InjectivityAnn
forall a. a -> Maybe a
Just (Name -> [Name] -> InjectivityAnn
TH.InjectivityAnn Name
thName [Name]
injRHS)
                                   where
                                     injRHS :: [Name]
injRHS = (Id -> Name) -> [Id] -> [Name]
forall a b. (a -> b) -> [a] -> [b]
map (Name -> Name
forall n. NamedThing n => n -> Name
reifyName (Name -> Name) -> (Id -> Name) -> Id -> Name
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Id -> Name
tyVarName)
                                                  ([Bool] -> [Id] -> [Id]
forall a. [Bool] -> [a] -> [a]
filterByList [Bool]
ms [Id]
tvs)
                     in (FamilyResultSig
sig, Maybe InjectivityAnn
inj)
       ; [TyVarBndr]
tvs' <- [Id] -> TcM [TyVarBndr]
reifyTyVars (TyCon -> [Id]
tyConVisibleTyVars TyCon
tc)
       ; let tfHead :: TypeFamilyHead
tfHead =
               Name
-> [TyVarBndr]
-> FamilyResultSig
-> Maybe InjectivityAnn
-> TypeFamilyHead
TH.TypeFamilyHead (TyCon -> Name
forall n. NamedThing n => n -> Name
reifyName TyCon
tc) [TyVarBndr]
tvs' FamilyResultSig
resultSig Maybe InjectivityAnn
injectivity
       ; if TyCon -> Bool
isOpenTypeFamilyTyCon TyCon
tc
         then do { FamInstEnvs
fam_envs <- TcM FamInstEnvs
tcGetFamInstEnvs
                 ; [Dec]
instances <- TyCon -> [FamInst] -> TcM [Dec]
reifyFamilyInstances TyCon
tc
                                  (FamInstEnvs -> TyCon -> [FamInst]
familyInstances FamInstEnvs
fam_envs TyCon
tc)
                 ; Info -> TcM Info
forall (m :: * -> *) a. Monad m => a -> m a
return (Dec -> [Dec] -> Info
TH.FamilyI (TypeFamilyHead -> Dec
TH.OpenTypeFamilyD TypeFamilyHead
tfHead) [Dec]
instances) }
         else do { [TySynEqn]
eqns <-
                     case TyCon -> Maybe (CoAxiom Branched)
isClosedSynFamilyTyConWithAxiom_maybe TyCon
tc of
                       Just CoAxiom Branched
ax -> (CoAxBranch -> TcM TySynEqn)
-> [CoAxBranch] -> IOEnv (Env TcGblEnv TcLclEnv) [TySynEqn]
forall (t :: * -> *) (m :: * -> *) a b.
(Traversable t, Monad m) =>
(a -> m b) -> t a -> m (t b)
mapM (TyCon -> CoAxBranch -> TcM TySynEqn
reifyAxBranch TyCon
tc) ([CoAxBranch] -> IOEnv (Env TcGblEnv TcLclEnv) [TySynEqn])
-> [CoAxBranch] -> IOEnv (Env TcGblEnv TcLclEnv) [TySynEqn]
forall a b. (a -> b) -> a -> b
$
                                  Branches Branched -> [CoAxBranch]
forall (br :: BranchFlag). Branches br -> [CoAxBranch]
fromBranches (Branches Branched -> [CoAxBranch])
-> Branches Branched -> [CoAxBranch]
forall a b. (a -> b) -> a -> b
$ CoAxiom Branched -> Branches Branched
forall (br :: BranchFlag). CoAxiom br -> Branches br
coAxiomBranches CoAxiom Branched
ax
                       Maybe (CoAxiom Branched)
Nothing -> [TySynEqn] -> IOEnv (Env TcGblEnv TcLclEnv) [TySynEqn]
forall (m :: * -> *) a. Monad m => a -> m a
return []
                 ; Info -> TcM Info
forall (m :: * -> *) a. Monad m => a -> m a
return (Dec -> [Dec] -> Info
TH.FamilyI (TypeFamilyHead -> [TySynEqn] -> Dec
TH.ClosedTypeFamilyD TypeFamilyHead
tfHead [TySynEqn]
eqns)
                      []) } }

  | TyCon -> Bool
isDataFamilyTyCon TyCon
tc
  = do { let res_kind :: TcRhoType
res_kind = TyCon -> TcRhoType
tyConResKind TyCon
tc

       ; Maybe Type
kind' <- (Type -> Maybe Type)
-> TcM Type -> IOEnv (Env TcGblEnv TcLclEnv) (Maybe Type)
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap Type -> Maybe Type
forall a. a -> Maybe a
Just (TcRhoType -> TcM Type
reifyKind TcRhoType
res_kind)

       ; [TyVarBndr]
tvs' <- [Id] -> TcM [TyVarBndr]
reifyTyVars (TyCon -> [Id]
tyConVisibleTyVars TyCon
tc)
       ; FamInstEnvs
fam_envs <- TcM FamInstEnvs
tcGetFamInstEnvs
       ; [Dec]
instances <- TyCon -> [FamInst] -> TcM [Dec]
reifyFamilyInstances TyCon
tc (FamInstEnvs -> TyCon -> [FamInst]
familyInstances FamInstEnvs
fam_envs TyCon
tc)
       ; Info -> TcM Info
forall (m :: * -> *) a. Monad m => a -> m a
return (Dec -> [Dec] -> Info
TH.FamilyI
                       (Name -> [TyVarBndr] -> Maybe Type -> Dec
TH.DataFamilyD (TyCon -> Name
forall n. NamedThing n => n -> Name
reifyName TyCon
tc) [TyVarBndr]
tvs' Maybe Type
kind') [Dec]
instances) }

  | Just ([Id]
_, TcRhoType
rhs) <- TyCon -> Maybe ([Id], TcRhoType)
synTyConDefn_maybe TyCon
tc  -- Vanilla type synonym
  = do { Type
rhs' <- TcRhoType -> TcM Type
reifyType TcRhoType
rhs
       ; [TyVarBndr]
tvs' <- [Id] -> TcM [TyVarBndr]
reifyTyVars (TyCon -> [Id]
tyConVisibleTyVars TyCon
tc)
       ; Info -> TcM Info
forall (m :: * -> *) a. Monad m => a -> m a
return (Dec -> Info
TH.TyConI
                   (Name -> [TyVarBndr] -> Type -> Dec
TH.TySynD (TyCon -> Name
forall n. NamedThing n => n -> Name
reifyName TyCon
tc) [TyVarBndr]
tvs' Type
rhs'))
       }

  | Bool
otherwise
  = do  { [Type]
cxt <- [TcRhoType] -> TcM [Type]
reifyCxt (TyCon -> [TcRhoType]
tyConStupidTheta TyCon
tc)
        ; let tvs :: [Id]
tvs      = TyCon -> [Id]
tyConTyVars TyCon
tc
              dataCons :: [DataCon]
dataCons = TyCon -> [DataCon]
tyConDataCons TyCon
tc
              isGadt :: Bool
isGadt   = TyCon -> Bool
isGadtSyntaxTyCon TyCon
tc
        ; [Con]
cons <- (DataCon -> IOEnv (Env TcGblEnv TcLclEnv) Con)
-> [DataCon] -> IOEnv (Env TcGblEnv TcLclEnv) [Con]
forall (t :: * -> *) (m :: * -> *) a b.
(Traversable t, Monad m) =>
(a -> m b) -> t a -> m (t b)
mapM (Bool -> [TcRhoType] -> DataCon -> IOEnv (Env TcGblEnv TcLclEnv) Con
reifyDataCon Bool
isGadt ([Id] -> [TcRhoType]
mkTyVarTys [Id]
tvs)) [DataCon]
dataCons
        ; [TyVarBndr]
r_tvs <- [Id] -> TcM [TyVarBndr]
reifyTyVars (TyCon -> [Id]
tyConVisibleTyVars TyCon
tc)
        ; let name :: Name
name = TyCon -> Name
forall n. NamedThing n => n -> Name
reifyName TyCon
tc
              deriv :: [a]
deriv = []        -- Don't know about deriving
              decl :: Dec
decl | TyCon -> Bool
isNewTyCon TyCon
tc =
                       [Type]
-> Name -> [TyVarBndr] -> Maybe Type -> Con -> [DerivClause] -> Dec
TH.NewtypeD [Type]
cxt Name
name [TyVarBndr]
r_tvs Maybe Type
forall a. Maybe a
Nothing ([Con] -> Con
forall a. [a] -> a
head [Con]
cons) [DerivClause]
forall a. [a]
deriv
                   | Bool
otherwise     =
                       [Type]
-> Name
-> [TyVarBndr]
-> Maybe Type
-> [Con]
-> [DerivClause]
-> Dec
TH.DataD    [Type]
cxt Name
name [TyVarBndr]
r_tvs Maybe Type
forall a. Maybe a
Nothing       [Con]
cons  [DerivClause]
forall a. [a]
deriv
        ; Info -> TcM Info
forall (m :: * -> *) a. Monad m => a -> m a
return (Dec -> Info
TH.TyConI Dec
decl) }

reifyDataCon :: Bool -> [Type] -> DataCon -> TcM TH.Con
reifyDataCon :: Bool -> [TcRhoType] -> DataCon -> IOEnv (Env TcGblEnv TcLclEnv) Con
reifyDataCon Bool
isGadtDataCon [TcRhoType]
tys DataCon
dc
  = do { let -- used for H98 data constructors
             ([Id]
ex_tvs, [TcRhoType]
theta, [TcRhoType]
arg_tys)
                 = DataCon -> [TcRhoType] -> ([Id], [TcRhoType], [TcRhoType])
dataConInstSig DataCon
dc [TcRhoType]
tys
             -- used for GADTs data constructors
             g_user_tvs' :: [Id]
g_user_tvs' = DataCon -> [Id]
dataConUserTyVars DataCon
dc
             ([Id]
g_univ_tvs, [Id]
_, [EqSpec]
g_eq_spec, [TcRhoType]
g_theta', [TcRhoType]
g_arg_tys', TcRhoType
g_res_ty')
                 = DataCon
-> ([Id], [Id], [EqSpec], [TcRhoType], [TcRhoType], TcRhoType)
dataConFullSig DataCon
dc
             ([SourceUnpackedness]
srcUnpks, [SourceStrictness]
srcStricts)
                 = (HsSrcBang -> (SourceUnpackedness, SourceStrictness))
-> [HsSrcBang] -> ([SourceUnpackedness], [SourceStrictness])
forall a b c. (a -> (b, c)) -> [a] -> ([b], [c])
mapAndUnzip HsSrcBang -> (SourceUnpackedness, SourceStrictness)
reifySourceBang (DataCon -> [HsSrcBang]
dataConSrcBangs DataCon
dc)
             dcdBangs :: [Bang]
dcdBangs  = (SourceUnpackedness -> SourceStrictness -> Bang)
-> [SourceUnpackedness] -> [SourceStrictness] -> [Bang]
forall a b c. (a -> b -> c) -> [a] -> [b] -> [c]
zipWith SourceUnpackedness -> SourceStrictness -> Bang
TH.Bang [SourceUnpackedness]
srcUnpks [SourceStrictness]
srcStricts
             fields :: [FieldLabel]
fields    = DataCon -> [FieldLabel]
dataConFieldLabels DataCon
dc
             name :: Name
name      = DataCon -> Name
forall n. NamedThing n => n -> Name
reifyName DataCon
dc
             -- Universal tvs present in eq_spec need to be filtered out, as
             -- they will not appear anywhere in the type.
             eq_spec_tvs :: VarSet
eq_spec_tvs = [Id] -> VarSet
mkVarSet ((EqSpec -> Id) -> [EqSpec] -> [Id]
forall a b. (a -> b) -> [a] -> [b]
map EqSpec -> Id
eqSpecTyVar [EqSpec]
g_eq_spec)

       ; (TCvSubst
univ_subst, [Id]
_)
              -- See Note [Freshen reified GADT constructors' universal tyvars]
           <- [Id] -> TcM (TCvSubst, [Id])
freshenTyVarBndrs ([Id] -> TcM (TCvSubst, [Id])) -> [Id] -> TcM (TCvSubst, [Id])
forall a b. (a -> b) -> a -> b
$
              (Id -> Bool) -> [Id] -> [Id]
forall a. (a -> Bool) -> [a] -> [a]
filterOut (Id -> VarSet -> Bool
`elemVarSet` VarSet
eq_spec_tvs) [Id]
g_univ_tvs
       ; let (TCvSubst
tvb_subst, [Id]
g_user_tvs) = HasCallStack => TCvSubst -> [Id] -> (TCvSubst, [Id])
TCvSubst -> [Id] -> (TCvSubst, [Id])
substTyVarBndrs TCvSubst
univ_subst [Id]
g_user_tvs'
             g_theta :: [TcRhoType]
g_theta   = HasCallStack => TCvSubst -> [TcRhoType] -> [TcRhoType]
TCvSubst -> [TcRhoType] -> [TcRhoType]
substTys TCvSubst
tvb_subst [TcRhoType]
g_theta'
             g_arg_tys :: [TcRhoType]
g_arg_tys = HasCallStack => TCvSubst -> [TcRhoType] -> [TcRhoType]
TCvSubst -> [TcRhoType] -> [TcRhoType]
substTys TCvSubst
tvb_subst [TcRhoType]
g_arg_tys'
             g_res_ty :: TcRhoType
g_res_ty  = HasCallStack => TCvSubst -> TcRhoType -> TcRhoType
TCvSubst -> TcRhoType -> TcRhoType
substTy  TCvSubst
tvb_subst TcRhoType
g_res_ty'

       ; [Type]
r_arg_tys <- [TcRhoType] -> TcM [Type]
reifyTypes (if Bool
isGadtDataCon then [TcRhoType]
g_arg_tys else [TcRhoType]
arg_tys)

       ; Con
main_con <-
           if | Bool -> Bool
not ([FieldLabel] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null [FieldLabel]
fields) Bool -> Bool -> Bool
&& Bool -> Bool
not Bool
isGadtDataCon ->
                  Con -> IOEnv (Env TcGblEnv TcLclEnv) Con
forall (m :: * -> *) a. Monad m => a -> m a
return (Con -> IOEnv (Env TcGblEnv TcLclEnv) Con)
-> Con -> IOEnv (Env TcGblEnv TcLclEnv) Con
forall a b. (a -> b) -> a -> b
$ Name -> [VarBangType] -> Con
TH.RecC Name
name ([Name] -> [Bang] -> [Type] -> [VarBangType]
forall a b c. [a] -> [b] -> [c] -> [(a, b, c)]
zip3 ((FieldLabel -> Name) -> [FieldLabel] -> [Name]
forall a b. (a -> b) -> [a] -> [b]
map FieldLabel -> Name
reifyFieldLabel [FieldLabel]
fields)
                                         [Bang]
dcdBangs [Type]
r_arg_tys)
              | Bool -> Bool
not ([FieldLabel] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null [FieldLabel]
fields) -> do
                  { Type
res_ty <- TcRhoType -> TcM Type
reifyType TcRhoType
g_res_ty
                  ; Con -> IOEnv (Env TcGblEnv TcLclEnv) Con
forall (m :: * -> *) a. Monad m => a -> m a
return (Con -> IOEnv (Env TcGblEnv TcLclEnv) Con)
-> Con -> IOEnv (Env TcGblEnv TcLclEnv) Con
forall a b. (a -> b) -> a -> b
$ [Name] -> [VarBangType] -> Type -> Con
TH.RecGadtC [Name
name]
                                     ([Name] -> [Bang] -> [Type] -> [VarBangType]
forall a b c. [a] -> [b] -> [c] -> [(a, b, c)]
zip3 ((FieldLabel -> Name) -> [FieldLabel] -> [Name]
forall a b. (a -> b) -> [a] -> [b]
map (Name -> Name
forall n. NamedThing n => n -> Name
reifyName (Name -> Name) -> (FieldLabel -> Name) -> FieldLabel -> Name
forall b c a. (b -> c) -> (a -> b) -> a -> c
. FieldLabel -> Name
forall a. FieldLbl a -> a
flSelector) [FieldLabel]
fields)
                                      [Bang]
dcdBangs [Type]
r_arg_tys) Type
res_ty }
                -- We need to check not isGadtDataCon here because GADT
                -- constructors can be declared infix.
                -- See Note [Infix GADT constructors] in TcTyClsDecls.
              | DataCon -> Bool
dataConIsInfix DataCon
dc Bool -> Bool -> Bool
&& Bool -> Bool
not Bool
isGadtDataCon ->
                  ASSERT( arg_tys `lengthIs` 2 ) do
                  { let [r_a1, r_a2] = r_arg_tys
                        [s1,   s2]   = dcdBangs
                  ; return $ TH.InfixC (s1,r_a1) name (s2,r_a2) }
              | Bool
isGadtDataCon -> do
                  { Type
res_ty <- TcRhoType -> TcM Type
reifyType TcRhoType
g_res_ty
                  ; Con -> IOEnv (Env TcGblEnv TcLclEnv) Con
forall (m :: * -> *) a. Monad m => a -> m a
return (Con -> IOEnv (Env TcGblEnv TcLclEnv) Con)
-> Con -> IOEnv (Env TcGblEnv TcLclEnv) Con
forall a b. (a -> b) -> a -> b
$ [Name] -> [BangType] -> Type -> Con
TH.GadtC [Name
name] ([Bang]
dcdBangs [Bang] -> [Type] -> [BangType]
forall a b. [a] -> [b] -> [(a, b)]
`zip` [Type]
r_arg_tys) Type
res_ty }
              | Bool
otherwise ->
                  Con -> IOEnv (Env TcGblEnv TcLclEnv) Con
forall (m :: * -> *) a. Monad m => a -> m a
return (Con -> IOEnv (Env TcGblEnv TcLclEnv) Con)
-> Con -> IOEnv (Env TcGblEnv TcLclEnv) Con
forall a b. (a -> b) -> a -> b
$ Name -> [BangType] -> Con
TH.NormalC Name
name ([Bang]
dcdBangs [Bang] -> [Type] -> [BangType]
forall a b. [a] -> [b] -> [(a, b)]
`zip` [Type]
r_arg_tys)

       ; let ([Id]
ex_tvs', [TcRhoType]
theta') | Bool
isGadtDataCon = ([Id]
g_user_tvs, [TcRhoType]
g_theta)
                               | Bool
otherwise     = ASSERT( all isTyVar ex_tvs )
                                                 -- no covars for haskell syntax
                                                 ([Id]
ex_tvs, [TcRhoType]
theta)
             ret_con :: IOEnv (Env TcGblEnv TcLclEnv) Con
ret_con | [Id] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null [Id]
ex_tvs' Bool -> Bool -> Bool
&& [TcRhoType] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null [TcRhoType]
theta' = Con -> IOEnv (Env TcGblEnv TcLclEnv) Con
forall (m :: * -> *) a. Monad m => a -> m a
return Con
main_con
                     | Bool
otherwise                   = do
                         { [Type]
cxt <- [TcRhoType] -> TcM [Type]
reifyCxt [TcRhoType]
theta'
                         ; [TyVarBndr]
ex_tvs'' <- [Id] -> TcM [TyVarBndr]
reifyTyVars [Id]
ex_tvs'
                         ; Con -> IOEnv (Env TcGblEnv TcLclEnv) Con
forall (m :: * -> *) a. Monad m => a -> m a
return ([TyVarBndr] -> [Type] -> Con -> Con
TH.ForallC [TyVarBndr]
ex_tvs'' [Type]
cxt Con
main_con) }
       ; ASSERT( arg_tys `equalLength` dcdBangs )
         IOEnv (Env TcGblEnv TcLclEnv) Con
ret_con }

{-
Note [Freshen reified GADT constructors' universal tyvars]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Suppose one were to reify this GADT:

  data a :~: b where
    Refl :: forall a b. (a ~ b) => a :~: b

We ought to be careful here about the uniques we give to the occurrences of `a`
and `b` in this definition. That is because in the original DataCon, all uses
of `a` and `b` have the same unique, since `a` and `b` are both universally
quantified type variables--that is, they are used in both the (:~:) tycon as
well as in the constructor type signature. But when we turn the DataCon
definition into the reified one, the `a` and `b` in the constructor type
signature becomes differently scoped than the `a` and `b` in `data a :~: b`.

While it wouldn't technically be *wrong* per se to re-use the same uniques for
`a` and `b` across these two different scopes, it's somewhat annoying for end
users of Template Haskell, since they wouldn't be able to rely on the
assumption that all TH names have globally distinct uniques (#13885). For this
reason, we freshen the universally quantified tyvars that go into the reified
GADT constructor type signature to give them distinct uniques from their
counterparts in the tycon.
-}

------------------------------
reifyClass :: Class -> TcM TH.Info
reifyClass :: Class -> TcM Info
reifyClass Class
cls
  = do  { [Type]
cxt <- [TcRhoType] -> TcM [Type]
reifyCxt [TcRhoType]
theta
        ; InstEnvs
inst_envs <- TcM InstEnvs
tcGetInstEnvs
        ; [Dec]
insts <- Class -> [ClsInst] -> TcM [Dec]
reifyClassInstances Class
cls (InstEnvs -> Class -> [ClsInst]
InstEnv.classInstances InstEnvs
inst_envs Class
cls)
        ; [Dec]
assocTys <- (ClassATItem -> TcM [Dec]) -> [ClassATItem] -> TcM [Dec]
forall (m :: * -> *) a b. Monad m => (a -> m [b]) -> [a] -> m [b]
concatMapM ClassATItem -> TcM [Dec]
reifyAT [ClassATItem]
ats
        ; [Dec]
ops <- ((Id, Maybe (Name, DefMethSpec TcRhoType)) -> TcM [Dec])
-> [(Id, Maybe (Name, DefMethSpec TcRhoType))] -> TcM [Dec]
forall (m :: * -> *) a b. Monad m => (a -> m [b]) -> [a] -> m [b]
concatMapM (Id, Maybe (Name, DefMethSpec TcRhoType)) -> TcM [Dec]
forall a. (Id, Maybe (a, DefMethSpec TcRhoType)) -> TcM [Dec]
reify_op [(Id, Maybe (Name, DefMethSpec TcRhoType))]
op_stuff
        ; [TyVarBndr]
tvs' <- [Id] -> TcM [TyVarBndr]
reifyTyVars (TyCon -> [Id]
tyConVisibleTyVars (Class -> TyCon
classTyCon Class
cls))
        ; let dec :: Dec
dec = [Type] -> Name -> [TyVarBndr] -> [FunDep] -> [Dec] -> Dec
TH.ClassD [Type]
cxt (Class -> Name
forall n. NamedThing n => n -> Name
reifyName Class
cls) [TyVarBndr]
tvs' [FunDep]
fds' ([Dec]
assocTys [Dec] -> [Dec] -> [Dec]
forall a. [a] -> [a] -> [a]
++ [Dec]
ops)
        ; Info -> TcM Info
forall (m :: * -> *) a. Monad m => a -> m a
return (Dec -> [Dec] -> Info
TH.ClassI Dec
dec [Dec]
insts) }
  where
    ([Id]
_, [FunDep Id]
fds, [TcRhoType]
theta, [Id]
_, [ClassATItem]
ats, [(Id, Maybe (Name, DefMethSpec TcRhoType))]
op_stuff) = Class
-> ([Id], [FunDep Id], [TcRhoType], [Id], [ClassATItem],
    [(Id, Maybe (Name, DefMethSpec TcRhoType))])
classExtraBigSig Class
cls
    fds' :: [FunDep]
fds' = (FunDep Id -> FunDep) -> [FunDep Id] -> [FunDep]
forall a b. (a -> b) -> [a] -> [b]
map FunDep Id -> FunDep
reifyFunDep [FunDep Id]
fds
    reify_op :: (Id, Maybe (a, DefMethSpec TcRhoType)) -> TcM [Dec]
reify_op (Id
op, Maybe (a, DefMethSpec TcRhoType)
def_meth)
      = do { let ([Id]
_, TcRhoType
_, TcRhoType
ty) = TcRhoType -> ([Id], TcRhoType, TcRhoType)
tcSplitMethodTy (Id -> TcRhoType
idType Id
op)
               -- Use tcSplitMethodTy to get rid of the extraneous class
               -- variables and predicates at the beginning of op's type
               -- (see #15551).
           ; Type
ty' <- TcRhoType -> TcM Type
reifyType TcRhoType
ty
           ; let nm' :: Name
nm' = Id -> Name
forall n. NamedThing n => n -> Name
reifyName Id
op
           ; case Maybe (a, DefMethSpec TcRhoType)
def_meth of
                Just (a
_, GenericDM TcRhoType
gdm_ty) ->
                  do { Type
gdm_ty' <- TcRhoType -> TcM Type
reifyType TcRhoType
gdm_ty
                     ; [Dec] -> TcM [Dec]
forall (m :: * -> *) a. Monad m => a -> m a
return [Name -> Type -> Dec
TH.SigD Name
nm' Type
ty', Name -> Type -> Dec
TH.DefaultSigD Name
nm' Type
gdm_ty'] }
                Maybe (a, DefMethSpec TcRhoType)
_ -> [Dec] -> TcM [Dec]
forall (m :: * -> *) a. Monad m => a -> m a
return [Name -> Type -> Dec
TH.SigD Name
nm' Type
ty'] }

    reifyAT :: ClassATItem -> TcM [TH.Dec]
    reifyAT :: ClassATItem -> TcM [Dec]
reifyAT (ATI TyCon
tycon Maybe (TcRhoType, SrcSpan)
def) = do
      Info
tycon' <- TyCon -> TcM Info
reifyTyCon TyCon
tycon
      case Info
tycon' of
        TH.FamilyI Dec
dec [Dec]
_ -> do
          let (Name
tyName, [Name]
tyArgs) = Dec -> (Name, [Name])
tfNames Dec
dec
          (Dec
dec Dec -> [Dec] -> [Dec]
forall a. a -> [a] -> [a]
:) ([Dec] -> [Dec]) -> TcM [Dec] -> TcM [Dec]
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> TcM [Dec]
-> ((TcRhoType, SrcSpan) -> TcM [Dec])
-> Maybe (TcRhoType, SrcSpan)
-> TcM [Dec]
forall b a. b -> (a -> b) -> Maybe a -> b
maybe ([Dec] -> TcM [Dec]
forall (m :: * -> *) a. Monad m => a -> m a
return [])
                            ((Dec -> [Dec]) -> IOEnv (Env TcGblEnv TcLclEnv) Dec -> TcM [Dec]
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap (Dec -> [Dec] -> [Dec]
forall a. a -> [a] -> [a]
:[]) (IOEnv (Env TcGblEnv TcLclEnv) Dec -> TcM [Dec])
-> ((TcRhoType, SrcSpan) -> IOEnv (Env TcGblEnv TcLclEnv) Dec)
-> (TcRhoType, SrcSpan)
-> TcM [Dec]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Name -> [Name] -> TcRhoType -> IOEnv (Env TcGblEnv TcLclEnv) Dec
reifyDefImpl Name
tyName [Name]
tyArgs (TcRhoType -> IOEnv (Env TcGblEnv TcLclEnv) Dec)
-> ((TcRhoType, SrcSpan) -> TcRhoType)
-> (TcRhoType, SrcSpan)
-> IOEnv (Env TcGblEnv TcLclEnv) Dec
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (TcRhoType, SrcSpan) -> TcRhoType
forall a b. (a, b) -> a
fst)
                            Maybe (TcRhoType, SrcSpan)
def
        Info
_ -> String -> MsgDoc -> TcM [Dec]
forall a. HasCallStack => String -> MsgDoc -> a
pprPanic String
"reifyAT" (String -> MsgDoc
text (Info -> String
forall a. Show a => a -> String
show Info
tycon'))

    reifyDefImpl :: TH.Name -> [TH.Name] -> Type -> TcM TH.Dec
    reifyDefImpl :: Name -> [Name] -> TcRhoType -> IOEnv (Env TcGblEnv TcLclEnv) Dec
reifyDefImpl Name
n [Name]
args TcRhoType
ty =
      TySynEqn -> Dec
TH.TySynInstD (TySynEqn -> Dec) -> (Type -> TySynEqn) -> Type -> Dec
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Maybe [TyVarBndr] -> Type -> Type -> TySynEqn
TH.TySynEqn Maybe [TyVarBndr]
forall a. Maybe a
Nothing (Type -> [Type] -> Type
mkThAppTs (Name -> Type
TH.ConT Name
n) ((Name -> Type) -> [Name] -> [Type]
forall a b. (a -> b) -> [a] -> [b]
map Name -> Type
TH.VarT [Name]
args))
                                  (Type -> Dec) -> TcM Type -> IOEnv (Env TcGblEnv TcLclEnv) Dec
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> TcRhoType -> TcM Type
reifyType TcRhoType
ty

    tfNames :: TH.Dec -> (TH.Name, [TH.Name])
    tfNames :: Dec -> (Name, [Name])
tfNames (TH.OpenTypeFamilyD (TH.TypeFamilyHead Name
n [TyVarBndr]
args FamilyResultSig
_ Maybe InjectivityAnn
_))
      = (Name
n, (TyVarBndr -> Name) -> [TyVarBndr] -> [Name]
forall a b. (a -> b) -> [a] -> [b]
map TyVarBndr -> Name
bndrName [TyVarBndr]
args)
    tfNames Dec
d = String -> MsgDoc -> (Name, [Name])
forall a. HasCallStack => String -> MsgDoc -> a
pprPanic String
"tfNames" (String -> MsgDoc
text (Dec -> String
forall a. Show a => a -> String
show Dec
d))

    bndrName :: TH.TyVarBndr -> TH.Name
    bndrName :: TyVarBndr -> Name
bndrName (TH.PlainTV Name
n)    = Name
n
    bndrName (TH.KindedTV Name
n Type
_) = Name
n

------------------------------
-- | Annotate (with TH.SigT) a type if the first parameter is True
-- and if the type contains a free variable.
-- This is used to annotate type patterns for poly-kinded tyvars in
-- reifying class and type instances.
-- See @Note [Reified instances and explicit kind signatures]@.
annotThType :: Bool   -- True <=> annotate
            -> TyCoRep.Type -> TH.Type -> TcM TH.Type
  -- tiny optimization: if the type is annotated, don't annotate again.
annotThType :: Bool -> TcRhoType -> Type -> TcM Type
annotThType Bool
_    TcRhoType
_  th_ty :: Type
th_ty@(TH.SigT {}) = Type -> TcM Type
forall (m :: * -> *) a. Monad m => a -> m a
return Type
th_ty
annotThType Bool
True TcRhoType
ty Type
th_ty
  | Bool -> Bool
not (Bool -> Bool) -> Bool -> Bool
forall a b. (a -> b) -> a -> b
$ VarSet -> Bool
isEmptyVarSet (VarSet -> Bool) -> VarSet -> Bool
forall a b. (a -> b) -> a -> b
$ (Id -> Bool) -> VarSet -> VarSet
filterVarSet Id -> Bool
isTyVar (VarSet -> VarSet) -> VarSet -> VarSet
forall a b. (a -> b) -> a -> b
$ TcRhoType -> VarSet
tyCoVarsOfType TcRhoType
ty
  = do { let ki :: TcRhoType
ki = HasDebugCallStack => TcRhoType -> TcRhoType
TcRhoType -> TcRhoType
tcTypeKind TcRhoType
ty
       ; Type
th_ki <- TcRhoType -> TcM Type
reifyKind TcRhoType
ki
       ; Type -> TcM Type
forall (m :: * -> *) a. Monad m => a -> m a
return (Type -> Type -> Type
TH.SigT Type
th_ty Type
th_ki) }
annotThType Bool
_    TcRhoType
_ Type
th_ty = Type -> TcM Type
forall (m :: * -> *) a. Monad m => a -> m a
return Type
th_ty

-- | For every argument type that a type constructor accepts,
-- report whether or not the argument is poly-kinded. This is used to
-- eventually feed into 'annotThType'.
-- See @Note [Reified instances and explicit kind signatures]@.
tyConArgsPolyKinded :: TyCon -> [Bool]
tyConArgsPolyKinded :: TyCon -> [Bool]
tyConArgsPolyKinded TyCon
tc =
     (Id -> Bool) -> [Id] -> [Bool]
forall a b. (a -> b) -> [a] -> [b]
map (TcRhoType -> Bool
is_poly_ty (TcRhoType -> Bool) -> (Id -> TcRhoType) -> Id -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Id -> TcRhoType
tyVarKind)      [Id]
tc_vis_tvs
     -- See "Wrinkle: Oversaturated data family instances" in
     -- @Note [Reified instances and explicit kind signatures]@
  [Bool] -> [Bool] -> [Bool]
forall a. [a] -> [a] -> [a]
++ (TyCoBinder -> Bool) -> [TyCoBinder] -> [Bool]
forall a b. (a -> b) -> [a] -> [b]
map (TcRhoType -> Bool
is_poly_ty (TcRhoType -> Bool)
-> (TyCoBinder -> TcRhoType) -> TyCoBinder -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. TyCoBinder -> TcRhoType
tyCoBinderType) [TyCoBinder]
tc_res_kind_vis_bndrs -- (1) in Wrinkle
  [Bool] -> [Bool] -> [Bool]
forall a. [a] -> [a] -> [a]
++ Bool -> [Bool]
forall a. a -> [a]
repeat Bool
True                                             -- (2) in Wrinkle
  where
    is_poly_ty :: Type -> Bool
    is_poly_ty :: TcRhoType -> Bool
is_poly_ty TcRhoType
ty = Bool -> Bool
not (Bool -> Bool) -> Bool -> Bool
forall a b. (a -> b) -> a -> b
$
                    VarSet -> Bool
isEmptyVarSet (VarSet -> Bool) -> VarSet -> Bool
forall a b. (a -> b) -> a -> b
$
                    (Id -> Bool) -> VarSet -> VarSet
filterVarSet Id -> Bool
isTyVar (VarSet -> VarSet) -> VarSet -> VarSet
forall a b. (a -> b) -> a -> b
$
                    TcRhoType -> VarSet
tyCoVarsOfType TcRhoType
ty

    tc_vis_tvs :: [TyVar]
    tc_vis_tvs :: [Id]
tc_vis_tvs = TyCon -> [Id]
tyConVisibleTyVars TyCon
tc

    tc_res_kind_vis_bndrs :: [TyCoBinder]
    tc_res_kind_vis_bndrs :: [TyCoBinder]
tc_res_kind_vis_bndrs = (TyCoBinder -> Bool) -> [TyCoBinder] -> [TyCoBinder]
forall a. (a -> Bool) -> [a] -> [a]
filter TyCoBinder -> Bool
isVisibleBinder ([TyCoBinder] -> [TyCoBinder]) -> [TyCoBinder] -> [TyCoBinder]
forall a b. (a -> b) -> a -> b
$ ([TyCoBinder], TcRhoType) -> [TyCoBinder]
forall a b. (a, b) -> a
fst (([TyCoBinder], TcRhoType) -> [TyCoBinder])
-> ([TyCoBinder], TcRhoType) -> [TyCoBinder]
forall a b. (a -> b) -> a -> b
$ TcRhoType -> ([TyCoBinder], TcRhoType)
splitPiTys (TcRhoType -> ([TyCoBinder], TcRhoType))
-> TcRhoType -> ([TyCoBinder], TcRhoType)
forall a b. (a -> b) -> a -> b
$ TyCon -> TcRhoType
tyConResKind TyCon
tc

{-
Note [Reified instances and explicit kind signatures]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Reified class instances and type family instances often include extra kind
information to disambiguate instances. Here is one such example that
illustrates this (#8953):

    type family Poly (a :: k) :: Type
    type instance Poly (x :: Bool)    = Int
    type instance Poly (x :: Maybe k) = Double

If you're not careful, reifying these instances might yield this:

    type instance Poly x = Int
    type instance Poly x = Double

To avoid this, we go through some care to annotate things with extra kind
information. Some functions which accomplish this feat include:

* annotThType: This annotates a type with a kind signature if the type contains
  a free variable.
* tyConArgsPolyKinded: This checks every argument that a type constructor can
  accept and reports if the type of the argument is poly-kinded. This
  information is ultimately fed into annotThType.

-----
-- Wrinkle: Oversaturated data family instances
-----

What constitutes an argument to a type constructor in the definition of
tyConArgsPolyKinded? For most type constructors, it's simply the visible
type variable binders (i.e., tyConVisibleTyVars). There is one corner case
we must keep in mind, however: data family instances can appear oversaturated
(#17296). For instance:

    data family   Foo :: Type -> Type
    data instance Foo x

    data family Bar :: k
    data family Bar x

For these sorts of data family instances, tyConVisibleTyVars isn't enough,
as they won't give you the kinds of the oversaturated arguments. We must
also consult:

1. The kinds of the arguments in the result kind (i.e., the tyConResKind).
   This will tell us, e.g., the kind of `x` in `Foo x` above.
2. If we go beyond the number of arguments in the result kind (like the
   `x` in `Bar x`), then we conservatively assume that the argument's
   kind is poly-kinded.

-----
-- Wrinkle: data family instances with return kinds
-----

Another squirrelly corner case is this:

    data family Foo (a :: k)
    data instance Foo :: Bool -> Type
    data instance Foo :: Char -> Type

If you're not careful, reifying these instances might yield this:

    data instance Foo
    data instance Foo

We can fix this ambiguity by reifying the instances' explicit return kinds. We
should only do this if necessary (see
Note [When does a tycon application need an explicit kind signature?] in Type),
but more importantly, we *only* do this if either of the following are true:

1. The data family instance has no constructors.
2. The data family instance is declared with GADT syntax.

If neither of these are true, then reifying the return kind would yield
something like this:

    data instance (Bar a :: Type) = MkBar a

Which is not valid syntax.
-}

------------------------------
reifyClassInstances :: Class -> [ClsInst] -> TcM [TH.Dec]
reifyClassInstances :: Class -> [ClsInst] -> TcM [Dec]
reifyClassInstances Class
cls [ClsInst]
insts
  = (ClsInst -> IOEnv (Env TcGblEnv TcLclEnv) Dec)
-> [ClsInst] -> TcM [Dec]
forall (t :: * -> *) (m :: * -> *) a b.
(Traversable t, Monad m) =>
(a -> m b) -> t a -> m (t b)
mapM ([Bool] -> ClsInst -> IOEnv (Env TcGblEnv TcLclEnv) Dec
reifyClassInstance (TyCon -> [Bool]
tyConArgsPolyKinded (Class -> TyCon
classTyCon Class
cls))) [ClsInst]
insts

reifyClassInstance :: [Bool]  -- True <=> the corresponding tv is poly-kinded
                              -- includes only *visible* tvs
                   -> ClsInst -> TcM TH.Dec
reifyClassInstance :: [Bool] -> ClsInst -> IOEnv (Env TcGblEnv TcLclEnv) Dec
reifyClassInstance [Bool]
is_poly_tvs ClsInst
i
  = do { [Type]
cxt <- [TcRhoType] -> TcM [Type]
reifyCxt [TcRhoType]
theta
       ; let vis_types :: [TcRhoType]
vis_types = TyCon -> [TcRhoType] -> [TcRhoType]
filterOutInvisibleTypes TyCon
cls_tc [TcRhoType]
types
       ; [Type]
thtypes <- [TcRhoType] -> TcM [Type]
reifyTypes [TcRhoType]
vis_types
       ; [Type]
annot_thtypes <- (Bool -> TcRhoType -> Type -> TcM Type)
-> [Bool] -> [TcRhoType] -> [Type] -> TcM [Type]
forall (m :: * -> *) a b c d.
Monad m =>
(a -> b -> c -> m d) -> [a] -> [b] -> [c] -> m [d]
zipWith3M Bool -> TcRhoType -> Type -> TcM Type
annotThType [Bool]
is_poly_tvs [TcRhoType]
vis_types [Type]
thtypes
       ; let head_ty :: Type
head_ty = Type -> [Type] -> Type
mkThAppTs (Name -> Type
TH.ConT (Class -> Name
forall n. NamedThing n => n -> Name
reifyName Class
cls)) [Type]
annot_thtypes
       ; Dec -> IOEnv (Env TcGblEnv TcLclEnv) Dec
forall (m :: * -> *) a. Monad m => a -> m a
return (Dec -> IOEnv (Env TcGblEnv TcLclEnv) Dec)
-> Dec -> IOEnv (Env TcGblEnv TcLclEnv) Dec
forall a b. (a -> b) -> a -> b
$ (Maybe Overlap -> [Type] -> Type -> [Dec] -> Dec
TH.InstanceD Maybe Overlap
over [Type]
cxt Type
head_ty []) }
  where
     ([Id]
_tvs, [TcRhoType]
theta, Class
cls, [TcRhoType]
types) = TcRhoType -> ([Id], [TcRhoType], Class, [TcRhoType])
tcSplitDFunTy (Id -> TcRhoType
idType Id
dfun)
     cls_tc :: TyCon
cls_tc   = Class -> TyCon
classTyCon Class
cls
     dfun :: Id
dfun     = ClsInst -> Id
instanceDFunId ClsInst
i
     over :: Maybe Overlap
over     = case OverlapFlag -> OverlapMode
overlapMode (ClsInst -> OverlapFlag
is_flag ClsInst
i) of
                  NoOverlap SourceText
_     -> Maybe Overlap
forall a. Maybe a
Nothing
                  Overlappable SourceText
_  -> Overlap -> Maybe Overlap
forall a. a -> Maybe a
Just Overlap
TH.Overlappable
                  Overlapping SourceText
_   -> Overlap -> Maybe Overlap
forall a. a -> Maybe a
Just Overlap
TH.Overlapping
                  Overlaps SourceText
_      -> Overlap -> Maybe Overlap
forall a. a -> Maybe a
Just Overlap
TH.Overlaps
                  Incoherent SourceText
_    -> Overlap -> Maybe Overlap
forall a. a -> Maybe a
Just Overlap
TH.Incoherent

------------------------------
reifyFamilyInstances :: TyCon -> [FamInst] -> TcM [TH.Dec]
reifyFamilyInstances :: TyCon -> [FamInst] -> TcM [Dec]
reifyFamilyInstances TyCon
fam_tc [FamInst]
fam_insts
  = (FamInst -> IOEnv (Env TcGblEnv TcLclEnv) Dec)
-> [FamInst] -> TcM [Dec]
forall (t :: * -> *) (m :: * -> *) a b.
(Traversable t, Monad m) =>
(a -> m b) -> t a -> m (t b)
mapM ([Bool] -> FamInst -> IOEnv (Env TcGblEnv TcLclEnv) Dec
reifyFamilyInstance (TyCon -> [Bool]
tyConArgsPolyKinded TyCon
fam_tc)) [FamInst]
fam_insts

reifyFamilyInstance :: [Bool] -- True <=> the corresponding tv is poly-kinded
                              -- includes only *visible* tvs
                    -> FamInst -> TcM TH.Dec
reifyFamilyInstance :: [Bool] -> FamInst -> IOEnv (Env TcGblEnv TcLclEnv) Dec
reifyFamilyInstance [Bool]
is_poly_tvs (FamInst { fi_flavor :: FamInst -> FamFlavor
fi_flavor = FamFlavor
flavor
                                         , fi_axiom :: FamInst -> CoAxiom Unbranched
fi_axiom = CoAxiom Unbranched
ax
                                         , fi_fam :: FamInst -> Name
fi_fam = Name
fam })
  | let fam_tc :: TyCon
fam_tc = CoAxiom Unbranched -> TyCon
forall (br :: BranchFlag). CoAxiom br -> TyCon
coAxiomTyCon CoAxiom Unbranched
ax
        branch :: CoAxBranch
branch = CoAxiom Unbranched -> CoAxBranch
coAxiomSingleBranch CoAxiom Unbranched
ax
  , CoAxBranch { cab_tvs :: CoAxBranch -> [Id]
cab_tvs = [Id]
tvs, cab_lhs :: CoAxBranch -> [TcRhoType]
cab_lhs = [TcRhoType]
lhs, cab_rhs :: CoAxBranch -> TcRhoType
cab_rhs = TcRhoType
rhs } <- CoAxBranch
branch
  = case FamFlavor
flavor of
      FamFlavor
SynFamilyInst ->
               -- remove kind patterns (#8884)
        do { Maybe [TyVarBndr]
th_tvs <- [Id] -> TcM (Maybe [TyVarBndr])
reifyTyVarsToMaybe [Id]
tvs
           ; let lhs_types_only :: [TcRhoType]
lhs_types_only = TyCon -> [TcRhoType] -> [TcRhoType]
filterOutInvisibleTypes TyCon
fam_tc [TcRhoType]
lhs
           ; [Type]
th_lhs <- [TcRhoType] -> TcM [Type]
reifyTypes [TcRhoType]
lhs_types_only
           ; [Type]
annot_th_lhs <- (Bool -> TcRhoType -> Type -> TcM Type)
-> [Bool] -> [TcRhoType] -> [Type] -> TcM [Type]
forall (m :: * -> *) a b c d.
Monad m =>
(a -> b -> c -> m d) -> [a] -> [b] -> [c] -> m [d]
zipWith3M Bool -> TcRhoType -> Type -> TcM Type
annotThType [Bool]
is_poly_tvs [TcRhoType]
lhs_types_only
                                                   [Type]
th_lhs
           ; let lhs_type :: Type
lhs_type = Type -> [Type] -> Type
mkThAppTs (Name -> Type
TH.ConT (Name -> Type) -> Name -> Type
forall a b. (a -> b) -> a -> b
$ Name -> Name
forall n. NamedThing n => n -> Name
reifyName Name
fam) [Type]
annot_th_lhs
           ; Type
th_rhs <- TcRhoType -> TcM Type
reifyType TcRhoType
rhs
           ; Dec -> IOEnv (Env TcGblEnv TcLclEnv) Dec
forall (m :: * -> *) a. Monad m => a -> m a
return (TySynEqn -> Dec
TH.TySynInstD (Maybe [TyVarBndr] -> Type -> Type -> TySynEqn
TH.TySynEqn Maybe [TyVarBndr]
th_tvs Type
lhs_type Type
th_rhs)) }

      DataFamilyInst TyCon
rep_tc ->
        do { let -- eta-expand lhs types, because sometimes data/newtype
                 -- instances are eta-reduced; See #9692
                 -- See Note [Eta reduction for data families] in FamInstEnv
                 ([Id]
ee_tvs, [TcRhoType]
ee_lhs, TcRhoType
_) = CoAxBranch -> ([Id], [TcRhoType], TcRhoType)
etaExpandCoAxBranch CoAxBranch
branch
                 fam' :: Name
fam'     = Name -> Name
forall n. NamedThing n => n -> Name
reifyName Name
fam
                 dataCons :: [DataCon]
dataCons = TyCon -> [DataCon]
tyConDataCons TyCon
rep_tc
                 isGadt :: Bool
isGadt   = TyCon -> Bool
isGadtSyntaxTyCon TyCon
rep_tc
           ; Maybe [TyVarBndr]
th_tvs <- [Id] -> TcM (Maybe [TyVarBndr])
reifyTyVarsToMaybe [Id]
ee_tvs
           ; [Con]
cons <- (DataCon -> IOEnv (Env TcGblEnv TcLclEnv) Con)
-> [DataCon] -> IOEnv (Env TcGblEnv TcLclEnv) [Con]
forall (t :: * -> *) (m :: * -> *) a b.
(Traversable t, Monad m) =>
(a -> m b) -> t a -> m (t b)
mapM (Bool -> [TcRhoType] -> DataCon -> IOEnv (Env TcGblEnv TcLclEnv) Con
reifyDataCon Bool
isGadt ([Id] -> [TcRhoType]
mkTyVarTys [Id]
ee_tvs)) [DataCon]
dataCons
           ; let types_only :: [TcRhoType]
types_only = TyCon -> [TcRhoType] -> [TcRhoType]
filterOutInvisibleTypes TyCon
fam_tc [TcRhoType]
ee_lhs
           ; [Type]
th_tys <- [TcRhoType] -> TcM [Type]
reifyTypes [TcRhoType]
types_only
           ; [Type]
annot_th_tys <- (Bool -> TcRhoType -> Type -> TcM Type)
-> [Bool] -> [TcRhoType] -> [Type] -> TcM [Type]
forall (m :: * -> *) a b c d.
Monad m =>
(a -> b -> c -> m d) -> [a] -> [b] -> [c] -> m [d]
zipWith3M Bool -> TcRhoType -> Type -> TcM Type
annotThType [Bool]
is_poly_tvs [TcRhoType]
types_only [Type]
th_tys
           ; let lhs_type :: Type
lhs_type = Type -> [Type] -> Type
mkThAppTs (Name -> Type
TH.ConT Name
fam') [Type]
annot_th_tys
           ; Maybe Type
mb_sig <-
               -- See "Wrinkle: data family instances with return kinds" in
               -- Note [Reified instances and explicit kind signatures]
               if ([Con] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null [Con]
cons Bool -> Bool -> Bool
|| TyCon -> Bool
isGadtSyntaxTyCon TyCon
rep_tc)
                     Bool -> Bool -> Bool
&& Bool -> TyCon -> Int -> Bool
tyConAppNeedsKindSig Bool
False TyCon
fam_tc ([TcRhoType] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length [TcRhoType]
ee_lhs)
               then do { let full_kind :: TcRhoType
full_kind = HasDebugCallStack => TcRhoType -> TcRhoType
TcRhoType -> TcRhoType
tcTypeKind (TyCon -> [TcRhoType] -> TcRhoType
mkTyConApp TyCon
fam_tc [TcRhoType]
ee_lhs)
                       ; Type
th_full_kind <- TcRhoType -> TcM Type
reifyKind TcRhoType
full_kind
                       ; Maybe Type -> IOEnv (Env TcGblEnv TcLclEnv) (Maybe Type)
forall (f :: * -> *) a. Applicative f => a -> f a
pure (Maybe Type -> IOEnv (Env TcGblEnv TcLclEnv) (Maybe Type))
-> Maybe Type -> IOEnv (Env TcGblEnv TcLclEnv) (Maybe Type)
forall a b. (a -> b) -> a -> b
$ Type -> Maybe Type
forall a. a -> Maybe a
Just Type
th_full_kind }
               else Maybe Type -> IOEnv (Env TcGblEnv TcLclEnv) (Maybe Type)
forall (f :: * -> *) a. Applicative f => a -> f a
pure Maybe Type
forall a. Maybe a
Nothing
           ; Dec -> IOEnv (Env TcGblEnv TcLclEnv) Dec
forall (m :: * -> *) a. Monad m => a -> m a
return (Dec -> IOEnv (Env TcGblEnv TcLclEnv) Dec)
-> Dec -> IOEnv (Env TcGblEnv TcLclEnv) Dec
forall a b. (a -> b) -> a -> b
$
               if TyCon -> Bool
isNewTyCon TyCon
rep_tc
               then [Type]
-> Maybe [TyVarBndr]
-> Type
-> Maybe Type
-> Con
-> [DerivClause]
-> Dec
TH.NewtypeInstD [] Maybe [TyVarBndr]
th_tvs Type
lhs_type Maybe Type
mb_sig ([Con] -> Con
forall a. [a] -> a
head [Con]
cons) []
               else [Type]
-> Maybe [TyVarBndr]
-> Type
-> Maybe Type
-> [Con]
-> [DerivClause]
-> Dec
TH.DataInstD    [] Maybe [TyVarBndr]
th_tvs Type
lhs_type Maybe Type
mb_sig       [Con]
cons  []
           }

------------------------------
reifyType :: TyCoRep.Type -> TcM TH.Type
-- Monadic only because of failure
reifyType :: TcRhoType -> TcM Type
reifyType TcRhoType
ty                | TcRhoType -> Bool
tcIsLiftedTypeKind TcRhoType
ty = Type -> TcM Type
forall (m :: * -> *) a. Monad m => a -> m a
return Type
TH.StarT
  -- Make sure to use tcIsLiftedTypeKind here, since we don't want to confuse it
  -- with Constraint (#14869).
reifyType ty :: TcRhoType
ty@(ForAllTy (Bndr Id
_ ArgFlag
argf) TcRhoType
_)
                            = ArgFlag -> TcRhoType -> TcM Type
reify_for_all ArgFlag
argf TcRhoType
ty
reifyType (LitTy TyLit
t)         = do { TyLit
r <- TyLit -> TcM TyLit
reifyTyLit TyLit
t; Type -> TcM Type
forall (m :: * -> *) a. Monad m => a -> m a
return (TyLit -> Type
TH.LitT TyLit
r) }
reifyType (TyVarTy Id
tv)      = Type -> TcM Type
forall (m :: * -> *) a. Monad m => a -> m a
return (Name -> Type
TH.VarT (Id -> Name
forall n. NamedThing n => n -> Name
reifyName Id
tv))
reifyType (TyConApp TyCon
tc [TcRhoType]
tys) = TyCon -> [TcRhoType] -> TcM Type
reify_tc_app TyCon
tc [TcRhoType]
tys   -- Do not expand type synonyms here
reifyType ty :: TcRhoType
ty@(AppTy {})     = do
  let (TcRhoType
ty_head, [TcRhoType]
ty_args) = TcRhoType -> (TcRhoType, [TcRhoType])
splitAppTys TcRhoType
ty
  Type
ty_head' <- TcRhoType -> TcM Type
reifyType TcRhoType
ty_head
  [Type]
ty_args' <- [TcRhoType] -> TcM [Type]
reifyTypes (TcRhoType -> [TcRhoType] -> [TcRhoType]
filter_out_invisible_args TcRhoType
ty_head [TcRhoType]
ty_args)
  Type -> TcM Type
forall (f :: * -> *) a. Applicative f => a -> f a
pure (Type -> TcM Type) -> Type -> TcM Type
forall a b. (a -> b) -> a -> b
$ Type -> [Type] -> Type
mkThAppTs Type
ty_head' [Type]
ty_args'
  where
    -- Make sure to filter out any invisible arguments. For instance, if you
    -- reify the following:
    --
    --   newtype T (f :: forall a. a -> Type) = MkT (f Bool)
    --
    -- Then you should receive back `f Bool`, not `f Type Bool`, since the
    -- `Type` argument is invisible (#15792).
    filter_out_invisible_args :: Type -> [Type] -> [Type]
    filter_out_invisible_args :: TcRhoType -> [TcRhoType] -> [TcRhoType]
filter_out_invisible_args TcRhoType
ty_head [TcRhoType]
ty_args =
      [Bool] -> [TcRhoType] -> [TcRhoType]
forall a. [Bool] -> [a] -> [a]
filterByList ((ArgFlag -> Bool) -> [ArgFlag] -> [Bool]
forall a b. (a -> b) -> [a] -> [b]
map ArgFlag -> Bool
isVisibleArgFlag ([ArgFlag] -> [Bool]) -> [ArgFlag] -> [Bool]
forall a b. (a -> b) -> a -> b
$ TcRhoType -> [TcRhoType] -> [ArgFlag]
appTyArgFlags TcRhoType
ty_head [TcRhoType]
ty_args)
                   [TcRhoType]
ty_args
reifyType ty :: TcRhoType
ty@(FunTy { ft_af :: TcRhoType -> AnonArgFlag
ft_af = AnonArgFlag
af, ft_arg :: TcRhoType -> TcRhoType
ft_arg = TcRhoType
t1, ft_res :: TcRhoType -> TcRhoType
ft_res = TcRhoType
t2 })
  | AnonArgFlag
InvisArg <- AnonArgFlag
af = ArgFlag -> TcRhoType -> TcM Type
reify_for_all ArgFlag
Inferred TcRhoType
ty  -- Types like ((?x::Int) => Char -> Char)
  | Bool
otherwise      = do { [Type
r1,Type
r2] <- [TcRhoType] -> TcM [Type]
reifyTypes [TcRhoType
t1,TcRhoType
t2] ; Type -> TcM Type
forall (m :: * -> *) a. Monad m => a -> m a
return (Type
TH.ArrowT Type -> Type -> Type
`TH.AppT` Type
r1 Type -> Type -> Type
`TH.AppT` Type
r2) }
reifyType (CastTy TcRhoType
t KindCoercion
_)      = TcRhoType -> TcM Type
reifyType TcRhoType
t -- Casts are ignored in TH
reifyType ty :: TcRhoType
ty@(CoercionTy {})= PtrString -> MsgDoc -> TcM Type
forall a. PtrString -> MsgDoc -> TcM a
noTH (String -> PtrString
sLit String
"coercions in types") (TcRhoType -> MsgDoc
forall a. Outputable a => a -> MsgDoc
ppr TcRhoType
ty)

reify_for_all :: TyCoRep.ArgFlag -> TyCoRep.Type -> TcM TH.Type
-- Arg of reify_for_all is always ForAllTy or a predicate FunTy
reify_for_all :: ArgFlag -> TcRhoType -> TcM Type
reify_for_all ArgFlag
argf TcRhoType
ty = do
  [TyVarBndr]
tvs' <- [Id] -> TcM [TyVarBndr]
reifyTyVars [Id]
tvs
  case ArgFlag -> ForallVisFlag
argToForallVisFlag ArgFlag
argf of
    ForallVisFlag
ForallVis   -> do Type
phi' <- TcRhoType -> TcM Type
reifyType TcRhoType
phi
                      Type -> TcM Type
forall (f :: * -> *) a. Applicative f => a -> f a
pure (Type -> TcM Type) -> Type -> TcM Type
forall a b. (a -> b) -> a -> b
$ [TyVarBndr] -> Type -> Type
TH.ForallVisT [TyVarBndr]
tvs' Type
phi'
    ForallVisFlag
ForallInvis -> do let ([TcRhoType]
cxt, TcRhoType
tau) = TcRhoType -> ([TcRhoType], TcRhoType)
tcSplitPhiTy TcRhoType
phi
                      [Type]
cxt' <- [TcRhoType] -> TcM [Type]
reifyCxt [TcRhoType]
cxt
                      Type
tau' <- TcRhoType -> TcM Type
reifyType TcRhoType
tau
                      Type -> TcM Type
forall (f :: * -> *) a. Applicative f => a -> f a
pure (Type -> TcM Type) -> Type -> TcM Type
forall a b. (a -> b) -> a -> b
$ [TyVarBndr] -> [Type] -> Type -> Type
TH.ForallT [TyVarBndr]
tvs' [Type]
cxt' Type
tau'
  where
    ([Id]
tvs, TcRhoType
phi) = ArgFlag -> TcRhoType -> ([Id], TcRhoType)
tcSplitForAllTysSameVis ArgFlag
argf TcRhoType
ty

reifyTyLit :: TyCoRep.TyLit -> TcM TH.TyLit
reifyTyLit :: TyLit -> TcM TyLit
reifyTyLit (NumTyLit Integer
n) = TyLit -> TcM TyLit
forall (m :: * -> *) a. Monad m => a -> m a
return (Integer -> TyLit
TH.NumTyLit Integer
n)
reifyTyLit (StrTyLit FastString
s) = TyLit -> TcM TyLit
forall (m :: * -> *) a. Monad m => a -> m a
return (String -> TyLit
TH.StrTyLit (FastString -> String
unpackFS FastString
s))

reifyTypes :: [Type] -> TcM [TH.Type]
reifyTypes :: [TcRhoType] -> TcM [Type]
reifyTypes = (TcRhoType -> TcM Type) -> [TcRhoType] -> TcM [Type]
forall (t :: * -> *) (m :: * -> *) a b.
(Traversable t, Monad m) =>
(a -> m b) -> t a -> m (t b)
mapM TcRhoType -> TcM Type
reifyType

reifyPatSynType
  :: ([TyVar], ThetaType, [TyVar], ThetaType, [Type], Type) -> TcM TH.Type
-- reifies a pattern synonym's type and returns its *complete* type
-- signature; see NOTE [Pattern synonym signatures and Template
-- Haskell]
reifyPatSynType :: ([Id], [TcRhoType], [Id], [TcRhoType], [TcRhoType], TcRhoType)
-> TcM Type
reifyPatSynType ([Id]
univTyVars, [TcRhoType]
req, [Id]
exTyVars, [TcRhoType]
prov, [TcRhoType]
argTys, TcRhoType
resTy)
  = do { [TyVarBndr]
univTyVars' <- [Id] -> TcM [TyVarBndr]
reifyTyVars [Id]
univTyVars
       ; [Type]
req'        <- [TcRhoType] -> TcM [Type]
reifyCxt [TcRhoType]
req
       ; [TyVarBndr]
exTyVars'   <- [Id] -> TcM [TyVarBndr]
reifyTyVars [Id]
exTyVars
       ; [Type]
prov'       <- [TcRhoType] -> TcM [Type]
reifyCxt [TcRhoType]
prov
       ; Type
tau'        <- TcRhoType -> TcM Type
reifyType ([TcRhoType] -> TcRhoType -> TcRhoType
mkVisFunTys [TcRhoType]
argTys TcRhoType
resTy)
       ; Type -> TcM Type
forall (m :: * -> *) a. Monad m => a -> m a
return (Type -> TcM Type) -> Type -> TcM Type
forall a b. (a -> b) -> a -> b
$ [TyVarBndr] -> [Type] -> Type -> Type
TH.ForallT [TyVarBndr]
univTyVars' [Type]
req'
                (Type -> Type) -> Type -> Type
forall a b. (a -> b) -> a -> b
$ [TyVarBndr] -> [Type] -> Type -> Type
TH.ForallT [TyVarBndr]
exTyVars' [Type]
prov' Type
tau' }

reifyKind :: Kind -> TcM TH.Kind
reifyKind :: TcRhoType -> TcM Type
reifyKind = TcRhoType -> TcM Type
reifyType

reifyCxt :: [PredType] -> TcM [TH.Pred]
reifyCxt :: [TcRhoType] -> TcM [Type]
reifyCxt   = (TcRhoType -> TcM Type) -> [TcRhoType] -> TcM [Type]
forall (t :: * -> *) (m :: * -> *) a b.
(Traversable t, Monad m) =>
(a -> m b) -> t a -> m (t b)
mapM TcRhoType -> TcM Type
reifyType

reifyFunDep :: ([TyVar], [TyVar]) -> TH.FunDep
reifyFunDep :: FunDep Id -> FunDep
reifyFunDep ([Id]
xs, [Id]
ys) = [Name] -> [Name] -> FunDep
TH.FunDep ((Id -> Name) -> [Id] -> [Name]
forall a b. (a -> b) -> [a] -> [b]
map Id -> Name
forall n. NamedThing n => n -> Name
reifyName [Id]
xs) ((Id -> Name) -> [Id] -> [Name]
forall a b. (a -> b) -> [a] -> [b]
map Id -> Name
forall n. NamedThing n => n -> Name
reifyName [Id]
ys)

reifyTyVars :: [TyVar] -> TcM [TH.TyVarBndr]
reifyTyVars :: [Id] -> TcM [TyVarBndr]
reifyTyVars [Id]
tvs = (Id -> IOEnv (Env TcGblEnv TcLclEnv) TyVarBndr)
-> [Id] -> TcM [TyVarBndr]
forall (t :: * -> *) (m :: * -> *) a b.
(Traversable t, Monad m) =>
(a -> m b) -> t a -> m (t b)
mapM Id -> IOEnv (Env TcGblEnv TcLclEnv) TyVarBndr
reify_tv [Id]
tvs
  where
    -- even if the kind is *, we need to include a kind annotation,
    -- in case a poly-kind would be inferred without the annotation.
    -- See #8953 or test th/T8953
    reify_tv :: Id -> IOEnv (Env TcGblEnv TcLclEnv) TyVarBndr
reify_tv Id
tv = Name -> Type -> TyVarBndr
TH.KindedTV Name
name (Type -> TyVarBndr)
-> TcM Type -> IOEnv (Env TcGblEnv TcLclEnv) TyVarBndr
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> TcRhoType -> TcM Type
reifyKind TcRhoType
kind
      where
        kind :: TcRhoType
kind = Id -> TcRhoType
tyVarKind Id
tv
        name :: Name
name = Id -> Name
forall n. NamedThing n => n -> Name
reifyName Id
tv

reifyTyVarsToMaybe :: [TyVar] -> TcM (Maybe [TH.TyVarBndr])
reifyTyVarsToMaybe :: [Id] -> TcM (Maybe [TyVarBndr])
reifyTyVarsToMaybe []  = Maybe [TyVarBndr] -> TcM (Maybe [TyVarBndr])
forall (f :: * -> *) a. Applicative f => a -> f a
pure Maybe [TyVarBndr]
forall a. Maybe a
Nothing
reifyTyVarsToMaybe [Id]
tys = [TyVarBndr] -> Maybe [TyVarBndr]
forall a. a -> Maybe a
Just ([TyVarBndr] -> Maybe [TyVarBndr])
-> TcM [TyVarBndr] -> TcM (Maybe [TyVarBndr])
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> [Id] -> TcM [TyVarBndr]
reifyTyVars [Id]
tys

reify_tc_app :: TyCon -> [Type.Type] -> TcM TH.Type
reify_tc_app :: TyCon -> [TcRhoType] -> TcM Type
reify_tc_app TyCon
tc [TcRhoType]
tys
  = do { [Type]
tys' <- [TcRhoType] -> TcM [Type]
reifyTypes (TyCon -> [TcRhoType] -> [TcRhoType]
filterOutInvisibleTypes TyCon
tc [TcRhoType]
tys)
       ; Type -> TcM Type
maybe_sig_t (Type -> [Type] -> Type
mkThAppTs Type
r_tc [Type]
tys') }
  where
    arity :: Int
arity       = TyCon -> Int
tyConArity TyCon
tc

    r_tc :: Type
r_tc | TyCon -> Bool
isUnboxedSumTyCon TyCon
tc           = Int -> Type
TH.UnboxedSumT (Int
arity Int -> Int -> Int
forall a. Integral a => a -> a -> a
`div` Int
2)
         | TyCon -> Bool
isUnboxedTupleTyCon TyCon
tc         = Int -> Type
TH.UnboxedTupleT (Int
arity Int -> Int -> Int
forall a. Integral a => a -> a -> a
`div` Int
2)
         | TyCon -> Bool
isPromotedTupleTyCon TyCon
tc        = Int -> Type
TH.PromotedTupleT (Int
arity Int -> Int -> Int
forall a. Integral a => a -> a -> a
`div` Int
2)
             -- See Note [Unboxed tuple RuntimeRep vars] in TyCon
         | TyCon -> Bool
isTupleTyCon TyCon
tc                = if TyCon -> Bool
isPromotedDataCon TyCon
tc
                                            then Int -> Type
TH.PromotedTupleT Int
arity
                                            else Int -> Type
TH.TupleT Int
arity
         | TyCon
tc TyCon -> Unique -> Bool
forall a. Uniquable a => a -> Unique -> Bool
`hasKey` Unique
constraintKindTyConKey
                                          = Type
TH.ConstraintT
         | TyCon
tc TyCon -> Unique -> Bool
forall a. Uniquable a => a -> Unique -> Bool
`hasKey` Unique
funTyConKey        = Type
TH.ArrowT
         | TyCon
tc TyCon -> Unique -> Bool
forall a. Uniquable a => a -> Unique -> Bool
`hasKey` Unique
listTyConKey       = Type
TH.ListT
         | TyCon
tc TyCon -> Unique -> Bool
forall a. Uniquable a => a -> Unique -> Bool
`hasKey` Unique
nilDataConKey      = Type
TH.PromotedNilT
         | TyCon
tc TyCon -> Unique -> Bool
forall a. Uniquable a => a -> Unique -> Bool
`hasKey` Unique
consDataConKey     = Type
TH.PromotedConsT
         | TyCon
tc TyCon -> Unique -> Bool
forall a. Uniquable a => a -> Unique -> Bool
`hasKey` Unique
heqTyConKey        = Type
TH.EqualityT
         | TyCon
tc TyCon -> Unique -> Bool
forall a. Uniquable a => a -> Unique -> Bool
`hasKey` Unique
eqPrimTyConKey     = Type
TH.EqualityT
         | TyCon
tc TyCon -> Unique -> Bool
forall a. Uniquable a => a -> Unique -> Bool
`hasKey` Unique
eqReprPrimTyConKey = Name -> Type
TH.ConT (TyCon -> Name
forall n. NamedThing n => n -> Name
reifyName TyCon
coercibleTyCon)
         | TyCon -> Bool
isPromotedDataCon TyCon
tc           = Name -> Type
TH.PromotedT (TyCon -> Name
forall n. NamedThing n => n -> Name
reifyName TyCon
tc)
         | Bool
otherwise                      = Name -> Type
TH.ConT (TyCon -> Name
forall n. NamedThing n => n -> Name
reifyName TyCon
tc)

    -- See Note [When does a tycon application need an explicit kind
    -- signature?] in TyCoRep
    maybe_sig_t :: Type -> TcM Type
maybe_sig_t Type
th_type
      | Bool -> TyCon -> Int -> Bool
tyConAppNeedsKindSig
          Bool
False -- We don't reify types using visible kind applications, so
                -- don't count specified binders as contributing towards
                -- injective positions in the kind of the tycon.
          TyCon
tc ([TcRhoType] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length [TcRhoType]
tys)
      = do { let full_kind :: TcRhoType
full_kind = HasDebugCallStack => TcRhoType -> TcRhoType
TcRhoType -> TcRhoType
tcTypeKind (TyCon -> [TcRhoType] -> TcRhoType
mkTyConApp TyCon
tc [TcRhoType]
tys)
           ; Type
th_full_kind <- TcRhoType -> TcM Type
reifyKind TcRhoType
full_kind
           ; Type -> TcM Type
forall (m :: * -> *) a. Monad m => a -> m a
return (Type -> Type -> Type
TH.SigT Type
th_type Type
th_full_kind) }
      | Bool
otherwise
      = Type -> TcM Type
forall (m :: * -> *) a. Monad m => a -> m a
return Type
th_type

------------------------------
reifyName :: NamedThing n => n -> TH.Name
reifyName :: n -> Name
reifyName n
thing
  | Name -> Bool
isExternalName Name
name
              = String -> String -> String -> Name
mk_varg String
pkg_str String
mod_str String
occ_str
  | Bool
otherwise = String -> Integer -> Name
TH.mkNameU String
occ_str (Int -> Integer
forall a. Integral a => a -> Integer
toInteger (Int -> Integer) -> Int -> Integer
forall a b. (a -> b) -> a -> b
$ Unique -> Int
getKey (Name -> Unique
forall a. Uniquable a => a -> Unique
getUnique Name
name))
        -- Many of the things we reify have local bindings, and
        -- NameL's aren't supposed to appear in binding positions, so
        -- we use NameU.  When/if we start to reify nested things, that
        -- have free variables, we may need to generate NameL's for them.
  where
    name :: Name
name    = n -> Name
forall a. NamedThing a => a -> Name
getName n
thing
    mod :: Module
mod     = ASSERT( isExternalName name ) nameModule name
    pkg_str :: String
pkg_str = UnitId -> String
unitIdString (Module -> UnitId
moduleUnitId Module
mod)
    mod_str :: String
mod_str = ModuleName -> String
moduleNameString (Module -> ModuleName
moduleName Module
mod)
    occ_str :: String
occ_str = OccName -> String
occNameString OccName
occ
    occ :: OccName
occ     = Name -> OccName
nameOccName Name
name
    mk_varg :: String -> String -> String -> Name
mk_varg | OccName -> Bool
OccName.isDataOcc OccName
occ = String -> String -> String -> Name
TH.mkNameG_d
            | OccName -> Bool
OccName.isVarOcc  OccName
occ = String -> String -> String -> Name
TH.mkNameG_v
            | OccName -> Bool
OccName.isTcOcc   OccName
occ = String -> String -> String -> Name
TH.mkNameG_tc
            | Bool
otherwise             = String -> MsgDoc -> String -> String -> String -> Name
forall a. HasCallStack => String -> MsgDoc -> a
pprPanic String
"reifyName" (Name -> MsgDoc
forall a. Outputable a => a -> MsgDoc
ppr Name
name)

-- See Note [Reifying field labels]
reifyFieldLabel :: FieldLabel -> TH.Name
reifyFieldLabel :: FieldLabel -> Name
reifyFieldLabel FieldLabel
fl
  | FieldLabel -> Bool
forall a. FieldLbl a -> Bool
flIsOverloaded FieldLabel
fl
              = OccName -> NameFlavour -> Name
TH.Name (String -> OccName
TH.mkOccName String
occ_str) (ModName -> NameFlavour
TH.NameQ (String -> ModName
TH.mkModName String
mod_str))
  | Bool
otherwise = String -> String -> String -> Name
TH.mkNameG_v String
pkg_str String
mod_str String
occ_str
  where
    name :: Name
name    = FieldLabel -> Name
forall a. FieldLbl a -> a
flSelector FieldLabel
fl
    mod :: Module
mod     = ASSERT( isExternalName name ) nameModule name
    pkg_str :: String
pkg_str = UnitId -> String
unitIdString (Module -> UnitId
moduleUnitId Module
mod)
    mod_str :: String
mod_str = ModuleName -> String
moduleNameString (Module -> ModuleName
moduleName Module
mod)
    occ_str :: String
occ_str = FastString -> String
unpackFS (FieldLabel -> FastString
forall a. FieldLbl a -> FastString
flLabel FieldLabel
fl)

reifySelector :: Id -> TyCon -> TH.Name
reifySelector :: Id -> TyCon -> Name
reifySelector Id
id TyCon
tc
  = case (FieldLabel -> Bool) -> [FieldLabel] -> Maybe FieldLabel
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Maybe a
find ((Id -> Name
idName Id
id Name -> Name -> Bool
forall a. Eq a => a -> a -> Bool
==) (Name -> Bool) -> (FieldLabel -> Name) -> FieldLabel -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. FieldLabel -> Name
forall a. FieldLbl a -> a
flSelector) (TyCon -> [FieldLabel]
tyConFieldLabels TyCon
tc) of
      Just FieldLabel
fl -> FieldLabel -> Name
reifyFieldLabel FieldLabel
fl
      Maybe FieldLabel
Nothing -> String -> MsgDoc -> Name
forall a. HasCallStack => String -> MsgDoc -> a
pprPanic String
"reifySelector: missing field" (Id -> MsgDoc
forall a. Outputable a => a -> MsgDoc
ppr Id
id MsgDoc -> MsgDoc -> MsgDoc
$$ TyCon -> MsgDoc
forall a. Outputable a => a -> MsgDoc
ppr TyCon
tc)

------------------------------
reifyFixity :: Name -> TcM (Maybe TH.Fixity)
reifyFixity :: Name -> TcM (Maybe Fixity)
reifyFixity Name
name
  = do { (Bool
found, Fixity
fix) <- Name -> RnM (Bool, Fixity)
lookupFixityRn_help Name
name
       ; Maybe Fixity -> TcM (Maybe Fixity)
forall (m :: * -> *) a. Monad m => a -> m a
return (if Bool
found then Fixity -> Maybe Fixity
forall a. a -> Maybe a
Just (Fixity -> Fixity
conv_fix Fixity
fix) else Maybe Fixity
forall a. Maybe a
Nothing) }
    where
      conv_fix :: Fixity -> Fixity
conv_fix (BasicTypes.Fixity SourceText
_ Int
i FixityDirection
d) = Int -> FixityDirection -> Fixity
TH.Fixity Int
i (FixityDirection -> FixityDirection
conv_dir FixityDirection
d)
      conv_dir :: FixityDirection -> FixityDirection
conv_dir FixityDirection
BasicTypes.InfixR = FixityDirection
TH.InfixR
      conv_dir FixityDirection
BasicTypes.InfixL = FixityDirection
TH.InfixL
      conv_dir FixityDirection
BasicTypes.InfixN = FixityDirection
TH.InfixN

reifyUnpackedness :: DataCon.SrcUnpackedness -> TH.SourceUnpackedness
reifyUnpackedness :: SrcUnpackedness -> SourceUnpackedness
reifyUnpackedness SrcUnpackedness
NoSrcUnpack = SourceUnpackedness
TH.NoSourceUnpackedness
reifyUnpackedness SrcUnpackedness
SrcNoUnpack = SourceUnpackedness
TH.SourceNoUnpack
reifyUnpackedness SrcUnpackedness
SrcUnpack   = SourceUnpackedness
TH.SourceUnpack

reifyStrictness :: DataCon.SrcStrictness -> TH.SourceStrictness
reifyStrictness :: SrcStrictness -> SourceStrictness
reifyStrictness SrcStrictness
NoSrcStrict = SourceStrictness
TH.NoSourceStrictness
reifyStrictness SrcStrictness
SrcStrict   = SourceStrictness
TH.SourceStrict
reifyStrictness SrcStrictness
SrcLazy     = SourceStrictness
TH.SourceLazy

reifySourceBang :: DataCon.HsSrcBang
                -> (TH.SourceUnpackedness, TH.SourceStrictness)
reifySourceBang :: HsSrcBang -> (SourceUnpackedness, SourceStrictness)
reifySourceBang (HsSrcBang SourceText
_ SrcUnpackedness
u SrcStrictness
s) = (SrcUnpackedness -> SourceUnpackedness
reifyUnpackedness SrcUnpackedness
u, SrcStrictness -> SourceStrictness
reifyStrictness SrcStrictness
s)

reifyDecidedStrictness :: DataCon.HsImplBang -> TH.DecidedStrictness
reifyDecidedStrictness :: HsImplBang -> DecidedStrictness
reifyDecidedStrictness HsImplBang
HsLazy     = DecidedStrictness
TH.DecidedLazy
reifyDecidedStrictness HsImplBang
HsStrict   = DecidedStrictness
TH.DecidedStrict
reifyDecidedStrictness HsUnpack{} = DecidedStrictness
TH.DecidedUnpack

reifyTypeOfThing :: TH.Name -> TcM TH.Type
reifyTypeOfThing :: Name -> TcM Type
reifyTypeOfThing Name
th_name = do
  TcTyThing
thing <- Name -> TcM TcTyThing
getThing Name
th_name
  case TcTyThing
thing of
    AGlobal (AnId Id
id) -> TcRhoType -> TcM Type
reifyType (Id -> TcRhoType
idType Id
id)
    AGlobal (ATyCon TyCon
tc) -> TcRhoType -> TcM Type
reifyKind (TyCon -> TcRhoType
tyConKind TyCon
tc)
    AGlobal (AConLike (RealDataCon DataCon
dc)) ->
      TcRhoType -> TcM Type
reifyType (Id -> TcRhoType
idType (DataCon -> Id
dataConWrapId DataCon
dc))
    AGlobal (AConLike (PatSynCon PatSyn
ps)) ->
      ([Id], [TcRhoType], [Id], [TcRhoType], [TcRhoType], TcRhoType)
-> TcM Type
reifyPatSynType (PatSyn
-> ([Id], [TcRhoType], [Id], [TcRhoType], [TcRhoType], TcRhoType)
patSynSig PatSyn
ps)
    ATcId{tct_id :: TcTyThing -> Id
tct_id = Id
id} -> TcRhoType -> TcM TcRhoType
zonkTcType (Id -> TcRhoType
idType Id
id) TcM TcRhoType -> (TcRhoType -> TcM Type) -> TcM Type
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= TcRhoType -> TcM Type
reifyType
    ATyVar Name
_ Id
tctv -> Id -> TcM TcRhoType
zonkTcTyVar Id
tctv TcM TcRhoType -> (TcRhoType -> TcM Type) -> TcM Type
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= TcRhoType -> TcM Type
reifyType
    -- Impossible cases, supposedly:
    AGlobal (ACoAxiom CoAxiom Branched
_) -> String -> TcM Type
forall a. String -> a
panic String
"reifyTypeOfThing: ACoAxiom"
    ATcTyCon TyCon
_ -> String -> TcM Type
forall a. String -> a
panic String
"reifyTypeOfThing: ATcTyCon"
    APromotionErr PromotionErr
_ -> String -> TcM Type
forall a. String -> a
panic String
"reifyTypeOfThing: APromotionErr"

------------------------------
lookupThAnnLookup :: TH.AnnLookup -> TcM CoreAnnTarget
lookupThAnnLookup :: AnnLookup -> TcM CoreAnnTarget
lookupThAnnLookup (TH.AnnLookupName Name
th_nm) = (Name -> CoreAnnTarget) -> TcM Name -> TcM CoreAnnTarget
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap Name -> CoreAnnTarget
forall name. name -> AnnTarget name
NamedTarget (Name -> TcM Name
lookupThName Name
th_nm)
lookupThAnnLookup (TH.AnnLookupModule (TH.Module PkgName
pn ModName
mn))
  = CoreAnnTarget -> TcM CoreAnnTarget
forall (m :: * -> *) a. Monad m => a -> m a
return (CoreAnnTarget -> TcM CoreAnnTarget)
-> CoreAnnTarget -> TcM CoreAnnTarget
forall a b. (a -> b) -> a -> b
$ Module -> CoreAnnTarget
forall name. Module -> AnnTarget name
ModuleTarget (Module -> CoreAnnTarget) -> Module -> CoreAnnTarget
forall a b. (a -> b) -> a -> b
$
    UnitId -> ModuleName -> Module
mkModule (String -> UnitId
stringToUnitId (String -> UnitId) -> String -> UnitId
forall a b. (a -> b) -> a -> b
$ PkgName -> String
TH.pkgString PkgName
pn) (String -> ModuleName
mkModuleN