{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE TypeFamilies #-}

{-# OPTIONS_GHC -Wno-incomplete-uni-patterns #-}

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


Pattern-matching bindings (HsBinds and MonoBinds)

Handles @HsBinds@; those at the top level require different handling,
in that the @Rec@/@NonRec@/etc structure is thrown away (whereas at
lower levels it is preserved with @let@/@letrec@s).
-}

module GHC.HsToCore.Binds
   ( dsTopLHsBinds, dsLHsBinds, decomposeRuleLhs, dsSpec
   , dsHsWrapper, dsEvTerm, dsTcEvBinds, dsTcEvBinds_s, dsEvBinds, dsMkUserRule
   )
where

import GHC.Prelude

import GHC.Driver.Session
import GHC.Driver.Ppr
import GHC.Driver.Config
import qualified GHC.LanguageExtensions as LangExt
import GHC.Unit.Module

import {-# SOURCE #-}   GHC.HsToCore.Expr  ( dsLExpr )
import {-# SOURCE #-}   GHC.HsToCore.Match ( matchWrapper )

import GHC.HsToCore.Monad
import GHC.HsToCore.Errors.Types
import GHC.HsToCore.GuardedRHSs
import GHC.HsToCore.Utils
import GHC.HsToCore.Pmc ( addTyCs, pmcGRHSs )

import GHC.Hs             -- lots of things
import GHC.Core           -- lots of things
import GHC.Core.SimpleOpt    ( simpleOptExpr )
import GHC.Core.Opt.OccurAnal ( occurAnalyseExpr )
import GHC.Core.Make
import GHC.Core.Utils
import GHC.Core.Opt.Arity     ( etaExpand )
import GHC.Core.Unfold.Make
import GHC.Core.FVs
import GHC.Core.Predicate
import GHC.Core.TyCon
import GHC.Core.Type
import GHC.Core.Coercion
import GHC.Core.Multiplicity
import GHC.Core.Rules

import GHC.Builtin.Names
import GHC.Builtin.Types ( naturalTy, typeSymbolKind, charTy )

import GHC.Tc.Types.Evidence

import GHC.Types.Id
import GHC.Types.Name
import GHC.Types.Var.Set
import GHC.Types.Var.Env
import GHC.Types.Var( EvVar )
import GHC.Types.SrcLoc
import GHC.Types.Basic
import GHC.Types.Unique.Set( nonDetEltsUniqSet )

import GHC.Data.Maybe
import GHC.Data.OrdList
import GHC.Data.Graph.Directed
import GHC.Data.Bag
import GHC.Data.FastString

import GHC.Utils.Constants (debugIsOn)
import GHC.Utils.Misc
import GHC.Utils.Monad
import GHC.Utils.Outputable
import GHC.Utils.Panic
import GHC.Utils.Panic.Plain
import GHC.Utils.Trace

import Control.Monad

{-**********************************************************************
*                                                                      *
           Desugaring a MonoBinds
*                                                                      *
**********************************************************************-}

-- | Desugar top level binds, strict binds are treated like normal
-- binds since there is no good time to force before first usage.
dsTopLHsBinds :: LHsBinds GhcTc -> DsM (OrdList (Id,CoreExpr))
dsTopLHsBinds :: LHsBinds GhcTc -> DsM (OrdList (Id, CoreExpr))
dsTopLHsBinds LHsBinds GhcTc
binds
     -- see Note [Strict binds checks]
  | Bool -> Bool
not (Bag (GenLocated (SrcSpanAnn' (EpAnn AnnListItem)) (HsBind GhcTc))
-> Bool
forall a. Bag a -> Bool
isEmptyBag Bag (GenLocated (SrcSpanAnn' (EpAnn AnnListItem)) (HsBind GhcTc))
unlifted_binds) Bool -> Bool -> Bool
|| Bool -> Bool
not (Bag (GenLocated (SrcSpanAnn' (EpAnn AnnListItem)) (HsBind GhcTc))
-> Bool
forall a. Bag a -> Bool
isEmptyBag Bag (GenLocated (SrcSpanAnn' (EpAnn AnnListItem)) (HsBind GhcTc))
bang_binds)
  = do { (GenLocated (SrcSpanAnn' (EpAnn AnnListItem)) (HsBind GhcTc)
 -> IOEnv (Env DsGblEnv DsLclEnv) ())
-> Bag
     (GenLocated (SrcSpanAnn' (EpAnn AnnListItem)) (HsBind GhcTc))
-> IOEnv (Env DsGblEnv DsLclEnv) ()
forall (m :: * -> *) a b. Monad m => (a -> m b) -> Bag a -> m ()
mapBagM_ (BindsType
-> GenLocated (SrcSpanAnn' (EpAnn AnnListItem)) (HsBind GhcTc)
-> IOEnv (Env DsGblEnv DsLclEnv) ()
forall a.
BindsType
-> GenLocated (SrcSpanAnn' a) (HsBind GhcTc)
-> IOEnv (Env DsGblEnv DsLclEnv) ()
top_level_err BindsType
UnliftedTypeBinds) Bag (GenLocated (SrcSpanAnn' (EpAnn AnnListItem)) (HsBind GhcTc))
unlifted_binds
       ; (GenLocated (SrcSpanAnn' (EpAnn AnnListItem)) (HsBind GhcTc)
 -> IOEnv (Env DsGblEnv DsLclEnv) ())
-> Bag
     (GenLocated (SrcSpanAnn' (EpAnn AnnListItem)) (HsBind GhcTc))
-> IOEnv (Env DsGblEnv DsLclEnv) ()
forall (m :: * -> *) a b. Monad m => (a -> m b) -> Bag a -> m ()
mapBagM_ (BindsType
-> GenLocated (SrcSpanAnn' (EpAnn AnnListItem)) (HsBind GhcTc)
-> IOEnv (Env DsGblEnv DsLclEnv) ()
forall a.
BindsType
-> GenLocated (SrcSpanAnn' a) (HsBind GhcTc)
-> IOEnv (Env DsGblEnv DsLclEnv) ()
top_level_err BindsType
StrictBinds)       Bag (GenLocated (SrcSpanAnn' (EpAnn AnnListItem)) (HsBind GhcTc))
bang_binds
       ; OrdList (Id, CoreExpr) -> DsM (OrdList (Id, CoreExpr))
forall (m :: * -> *) a. Monad m => a -> m a
return OrdList (Id, CoreExpr)
forall a. OrdList a
nilOL }

  | Bool
otherwise
  = do { ([Id]
force_vars, [(Id, CoreExpr)]
prs) <- LHsBinds GhcTc -> DsM ([Id], [(Id, CoreExpr)])
dsLHsBinds LHsBinds GhcTc
binds
       ; Bool
-> IOEnv (Env DsGblEnv DsLclEnv) ()
-> IOEnv (Env DsGblEnv DsLclEnv) ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
when Bool
debugIsOn (IOEnv (Env DsGblEnv DsLclEnv) ()
 -> IOEnv (Env DsGblEnv DsLclEnv) ())
-> IOEnv (Env DsGblEnv DsLclEnv) ()
-> IOEnv (Env DsGblEnv DsLclEnv) ()
forall a b. (a -> b) -> a -> b
$
         do { Bool
xstrict <- Extension -> TcRnIf DsGblEnv DsLclEnv Bool
forall gbl lcl. Extension -> TcRnIf gbl lcl Bool
xoptM Extension
LangExt.Strict
            ; Bool -> SDoc -> IOEnv (Env DsGblEnv DsLclEnv) ()
forall (m :: * -> *).
(HasCallStack, Applicative m) =>
Bool -> SDoc -> m ()
massertPpr ([Id] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null [Id]
force_vars Bool -> Bool -> Bool
|| Bool
xstrict) (Bag (GenLocated (SrcSpanAnn' (EpAnn AnnListItem)) (HsBind GhcTc))
-> SDoc
forall a. Outputable a => a -> SDoc
ppr LHsBinds GhcTc
Bag (GenLocated (SrcSpanAnn' (EpAnn AnnListItem)) (HsBind GhcTc))
binds SDoc -> SDoc -> SDoc
$$ [Id] -> SDoc
forall a. Outputable a => a -> SDoc
ppr [Id]
force_vars) }
              -- with -XStrict, even top-level vars are listed as force vars.

       ; OrdList (Id, CoreExpr) -> DsM (OrdList (Id, CoreExpr))
forall (m :: * -> *) a. Monad m => a -> m a
return ([(Id, CoreExpr)] -> OrdList (Id, CoreExpr)
forall a. [a] -> OrdList a
toOL [(Id, CoreExpr)]
prs) }

  where
    unlifted_binds :: Bag (GenLocated (SrcSpanAnn' (EpAnn AnnListItem)) (HsBind GhcTc))
unlifted_binds = (GenLocated (SrcSpanAnn' (EpAnn AnnListItem)) (HsBind GhcTc)
 -> Bool)
-> Bag
     (GenLocated (SrcSpanAnn' (EpAnn AnnListItem)) (HsBind GhcTc))
-> Bag
     (GenLocated (SrcSpanAnn' (EpAnn AnnListItem)) (HsBind GhcTc))
forall a. (a -> Bool) -> Bag a -> Bag a
filterBag (HsBind GhcTc -> Bool
isUnliftedHsBind (HsBind GhcTc -> Bool)
-> (GenLocated (SrcSpanAnn' (EpAnn AnnListItem)) (HsBind GhcTc)
    -> HsBind GhcTc)
-> GenLocated (SrcSpanAnn' (EpAnn AnnListItem)) (HsBind GhcTc)
-> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. GenLocated (SrcSpanAnn' (EpAnn AnnListItem)) (HsBind GhcTc)
-> HsBind GhcTc
forall l e. GenLocated l e -> e
unLoc) LHsBinds GhcTc
Bag (GenLocated (SrcSpanAnn' (EpAnn AnnListItem)) (HsBind GhcTc))
binds
    bang_binds :: Bag (GenLocated (SrcSpanAnn' (EpAnn AnnListItem)) (HsBind GhcTc))
bang_binds     = (GenLocated (SrcSpanAnn' (EpAnn AnnListItem)) (HsBind GhcTc)
 -> Bool)
-> Bag
     (GenLocated (SrcSpanAnn' (EpAnn AnnListItem)) (HsBind GhcTc))
-> Bag
     (GenLocated (SrcSpanAnn' (EpAnn AnnListItem)) (HsBind GhcTc))
forall a. (a -> Bool) -> Bag a -> Bag a
filterBag (HsBind GhcTc -> Bool
isBangedHsBind   (HsBind GhcTc -> Bool)
-> (GenLocated (SrcSpanAnn' (EpAnn AnnListItem)) (HsBind GhcTc)
    -> HsBind GhcTc)
-> GenLocated (SrcSpanAnn' (EpAnn AnnListItem)) (HsBind GhcTc)
-> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. GenLocated (SrcSpanAnn' (EpAnn AnnListItem)) (HsBind GhcTc)
-> HsBind GhcTc
forall l e. GenLocated l e -> e
unLoc) LHsBinds GhcTc
Bag (GenLocated (SrcSpanAnn' (EpAnn AnnListItem)) (HsBind GhcTc))
binds

    top_level_err :: BindsType
-> GenLocated (SrcSpanAnn' a) (HsBind GhcTc)
-> IOEnv (Env DsGblEnv DsLclEnv) ()
top_level_err BindsType
bindsType (L SrcSpanAnn' a
loc HsBind GhcTc
bind)
      = SrcSpan
-> IOEnv (Env DsGblEnv DsLclEnv) ()
-> IOEnv (Env DsGblEnv DsLclEnv) ()
forall a. SrcSpan -> DsM a -> DsM a
putSrcSpanDs (SrcSpanAnn' a -> SrcSpan
forall a. SrcSpanAnn' a -> SrcSpan
locA SrcSpanAnn' a
loc) (IOEnv (Env DsGblEnv DsLclEnv) ()
 -> IOEnv (Env DsGblEnv DsLclEnv) ())
-> IOEnv (Env DsGblEnv DsLclEnv) ()
-> IOEnv (Env DsGblEnv DsLclEnv) ()
forall a b. (a -> b) -> a -> b
$
        DsMessage -> IOEnv (Env DsGblEnv DsLclEnv) ()
diagnosticDs (BindsType -> HsBind GhcTc -> DsMessage
DsTopLevelBindsNotAllowed BindsType
bindsType HsBind GhcTc
bind)


-- | Desugar all other kind of bindings, Ids of strict binds are returned to
-- later be forced in the binding group body, see Note [Desugar Strict binds]
dsLHsBinds :: LHsBinds GhcTc -> DsM ([Id], [(Id,CoreExpr)])
dsLHsBinds :: LHsBinds GhcTc -> DsM ([Id], [(Id, CoreExpr)])
dsLHsBinds LHsBinds GhcTc
binds
  = do { Bag ([Id], [(Id, CoreExpr)])
ds_bs <- (GenLocated (SrcSpanAnn' (EpAnn AnnListItem)) (HsBind GhcTc)
 -> DsM ([Id], [(Id, CoreExpr)]))
-> Bag
     (GenLocated (SrcSpanAnn' (EpAnn AnnListItem)) (HsBind GhcTc))
-> IOEnv (Env DsGblEnv DsLclEnv) (Bag ([Id], [(Id, CoreExpr)]))
forall (m :: * -> *) a b.
Monad m =>
(a -> m b) -> Bag a -> m (Bag b)
mapBagM LHsBind GhcTc -> DsM ([Id], [(Id, CoreExpr)])
GenLocated (SrcSpanAnn' (EpAnn AnnListItem)) (HsBind GhcTc)
-> DsM ([Id], [(Id, CoreExpr)])
dsLHsBind LHsBinds GhcTc
Bag (GenLocated (SrcSpanAnn' (EpAnn AnnListItem)) (HsBind GhcTc))
binds
       ; ([Id], [(Id, CoreExpr)]) -> DsM ([Id], [(Id, CoreExpr)])
forall (m :: * -> *) a. Monad m => a -> m a
return ((([Id], [(Id, CoreExpr)])
 -> ([Id], [(Id, CoreExpr)]) -> ([Id], [(Id, CoreExpr)]))
-> (([Id], [(Id, CoreExpr)]) -> ([Id], [(Id, CoreExpr)]))
-> ([Id], [(Id, CoreExpr)])
-> Bag ([Id], [(Id, CoreExpr)])
-> ([Id], [(Id, CoreExpr)])
forall r a. (r -> r -> r) -> (a -> r) -> r -> Bag a -> r
foldBag (\([Id]
a, [(Id, CoreExpr)]
a') ([Id]
b, [(Id, CoreExpr)]
b') -> ([Id]
a [Id] -> [Id] -> [Id]
forall a. [a] -> [a] -> [a]
++ [Id]
b, [(Id, CoreExpr)]
a' [(Id, CoreExpr)] -> [(Id, CoreExpr)] -> [(Id, CoreExpr)]
forall a. [a] -> [a] -> [a]
++ [(Id, CoreExpr)]
b'))
                         ([Id], [(Id, CoreExpr)]) -> ([Id], [(Id, CoreExpr)])
forall a. a -> a
id ([], []) Bag ([Id], [(Id, CoreExpr)])
ds_bs) }

------------------------
dsLHsBind :: LHsBind GhcTc
          -> DsM ([Id], [(Id,CoreExpr)])
dsLHsBind :: LHsBind GhcTc -> DsM ([Id], [(Id, CoreExpr)])
dsLHsBind (L loc bind) = do DynFlags
dflags <- IOEnv (Env DsGblEnv DsLclEnv) DynFlags
forall (m :: * -> *). HasDynFlags m => m DynFlags
getDynFlags
                            SrcSpan
-> DsM ([Id], [(Id, CoreExpr)]) -> DsM ([Id], [(Id, CoreExpr)])
forall a. SrcSpan -> DsM a -> DsM a
putSrcSpanDs (SrcSpanAnn' (EpAnn AnnListItem) -> SrcSpan
forall a. SrcSpanAnn' a -> SrcSpan
locA SrcSpanAnn' (EpAnn AnnListItem)
loc) (DsM ([Id], [(Id, CoreExpr)]) -> DsM ([Id], [(Id, CoreExpr)]))
-> DsM ([Id], [(Id, CoreExpr)]) -> DsM ([Id], [(Id, CoreExpr)])
forall a b. (a -> b) -> a -> b
$ DynFlags -> HsBind GhcTc -> DsM ([Id], [(Id, CoreExpr)])
dsHsBind DynFlags
dflags HsBind GhcTc
bind

-- | Desugar a single binding (or group of recursive binds).
dsHsBind :: DynFlags
         -> HsBind GhcTc
         -> DsM ([Id], [(Id,CoreExpr)])
         -- ^ The Ids of strict binds, to be forced in the body of the
         -- binding group see Note [Desugar Strict binds] and all
         -- bindings and their desugared right hand sides.

dsHsBind :: DynFlags -> HsBind GhcTc -> DsM ([Id], [(Id, CoreExpr)])
dsHsBind DynFlags
dflags (VarBind { var_id :: forall idL idR. HsBindLR idL idR -> IdP idL
var_id = IdP GhcTc
var
                         , var_rhs :: forall idL idR. HsBindLR idL idR -> LHsExpr idR
var_rhs = LHsExpr GhcTc
expr })
  = do  { CoreExpr
core_expr <- LHsExpr GhcTc -> DsM CoreExpr
dsLExpr LHsExpr GhcTc
expr
                -- Dictionary bindings are always VarBinds,
                -- so we only need do this here
        ; let core_bind :: (Id, CoreExpr)
core_bind@(Id
id,CoreExpr
_) = DynFlags -> Id -> Bool -> Arity -> CoreExpr -> (Id, CoreExpr)
makeCorePair DynFlags
dflags IdP GhcTc
Id
var Bool
False Arity
0 CoreExpr
core_expr
              force_var :: [Id]
force_var = if Extension -> DynFlags -> Bool
xopt Extension
LangExt.Strict DynFlags
dflags
                          then [Id
id]
                          else []
        ; ([Id], [(Id, CoreExpr)]) -> DsM ([Id], [(Id, CoreExpr)])
forall (m :: * -> *) a. Monad m => a -> m a
return ([Id]
force_var, [(Id, CoreExpr)
core_bind]) }

dsHsBind DynFlags
dflags b :: HsBind GhcTc
b@(FunBind { fun_id :: forall idL idR. HsBindLR idL idR -> LIdP idL
fun_id = L loc fun
                           , fun_matches :: forall idL idR. HsBindLR idL idR -> MatchGroup idR (LHsExpr idR)
fun_matches = MatchGroup GhcTc (LHsExpr GhcTc)
matches
                           , fun_ext :: forall idL idR. HsBindLR idL idR -> XFunBind idL idR
fun_ext = XFunBind GhcTc GhcTc
co_fn
                           , fun_tick :: forall idL idR. HsBindLR idL idR -> [CoreTickish]
fun_tick = [CoreTickish]
tick })
 = do   { ([Id]
args, CoreExpr
body) <- Origin -> Bag Id -> DsM ([Id], CoreExpr) -> DsM ([Id], CoreExpr)
forall a. Origin -> Bag Id -> DsM a -> DsM a
addTyCs Origin
FromSource (HsWrapper -> Bag Id
hsWrapDictBinders HsWrapper
XFunBind GhcTc GhcTc
co_fn) (DsM ([Id], CoreExpr) -> DsM ([Id], CoreExpr))
-> DsM ([Id], CoreExpr) -> DsM ([Id], CoreExpr)
forall a b. (a -> b) -> a -> b
$
                          -- FromSource might not be accurate (we don't have any
                          -- origin annotations for things in this module), but at
                          -- worst we do superfluous calls to the pattern match
                          -- oracle.
                          -- addTyCs: Add type evidence to the refinement type
                          --            predicate of the coverage checker
                          -- See Note [Long-distance information] in "GHC.HsToCore.Pmc"
                          HsMatchContext GhcRn
-> Maybe [LHsExpr GhcTc]
-> MatchGroup GhcTc (LHsExpr GhcTc)
-> DsM ([Id], CoreExpr)
matchWrapper (LIdP GhcRn -> HsMatchContext GhcRn
forall p. LIdP p -> HsMatchContext p
mkPrefixFunRhs (SrcSpanAnnN -> Name -> GenLocated SrcSpanAnnN Name
forall l e. l -> e -> GenLocated l e
L SrcSpanAnnN
loc (Id -> Name
idName Id
fun))) Maybe [LHsExpr GhcTc]
forall a. Maybe a
Nothing MatchGroup GhcTc (LHsExpr GhcTc)
matches

        ; CoreExpr -> CoreExpr
core_wrap <- HsWrapper -> DsM (CoreExpr -> CoreExpr)
dsHsWrapper HsWrapper
XFunBind GhcTc GhcTc
co_fn
        ; let body' :: CoreExpr
body' = [CoreTickish] -> CoreExpr -> CoreExpr
mkOptTickBox [CoreTickish]
tick CoreExpr
body
              rhs :: CoreExpr
rhs   = CoreExpr -> CoreExpr
core_wrap ([Id] -> CoreExpr -> CoreExpr
forall b. [b] -> Expr b -> Expr b
mkLams [Id]
args CoreExpr
body')
              core_binds :: (Id, CoreExpr)
core_binds@(Id
id,CoreExpr
_) = DynFlags -> Id -> Bool -> Arity -> CoreExpr -> (Id, CoreExpr)
makeCorePair DynFlags
dflags Id
fun Bool
False Arity
0 CoreExpr
rhs
              force_var :: [Id]
force_var
                  -- Bindings are strict when -XStrict is enabled
                | Extension -> DynFlags -> Bool
xopt Extension
LangExt.Strict DynFlags
dflags
                , MatchGroup
  GhcTc (GenLocated (SrcSpanAnn' (EpAnn AnnListItem)) (HsExpr GhcTc))
-> Arity
forall (id :: Pass) body. MatchGroup (GhcPass id) body -> Arity
matchGroupArity MatchGroup GhcTc (LHsExpr GhcTc)
MatchGroup
  GhcTc (GenLocated (SrcSpanAnn' (EpAnn AnnListItem)) (HsExpr GhcTc))
matches Arity -> Arity -> Bool
forall a. Eq a => a -> a -> Bool
== Arity
0 -- no need to force lambdas
                = [Id
id]
                | HsBind GhcTc -> Bool
isBangedHsBind HsBind GhcTc
b
                = [Id
id]
                | Bool
otherwise
                = []
        ; --pprTrace "dsHsBind" (vcat [ ppr fun <+> ppr (idInlinePragma fun)
          --                          , ppr (mg_alts matches)
          --                          , ppr args, ppr core_binds, ppr body']) $
          ([Id], [(Id, CoreExpr)]) -> DsM ([Id], [(Id, CoreExpr)])
forall (m :: * -> *) a. Monad m => a -> m a
return ([Id]
force_var, [(Id, CoreExpr)
core_binds]) }

dsHsBind DynFlags
dflags (PatBind { pat_lhs :: forall idL idR. HsBindLR idL idR -> LPat idL
pat_lhs = LPat GhcTc
pat, pat_rhs :: forall idL idR. HsBindLR idL idR -> GRHSs idR (LHsExpr idR)
pat_rhs = GRHSs GhcTc (LHsExpr GhcTc)
grhss
                         , pat_ext :: forall idL idR. HsBindLR idL idR -> XPatBind idL idR
pat_ext = XPatBind GhcTc GhcTc
ty
                         , pat_ticks :: forall idL idR.
HsBindLR idL idR -> ([CoreTickish], [[CoreTickish]])
pat_ticks = ([CoreTickish]
rhs_tick, [[CoreTickish]]
var_ticks) })
  = do  { NonEmpty Nablas
rhss_nablas <- HsMatchContext GhcRn
-> GRHSs GhcTc (LHsExpr GhcTc) -> DsM (NonEmpty Nablas)
pmcGRHSs HsMatchContext GhcRn
forall p. HsMatchContext p
PatBindGuards GRHSs GhcTc (LHsExpr GhcTc)
grhss
        ; CoreExpr
body_expr <- GRHSs GhcTc (LHsExpr GhcTc)
-> Type -> NonEmpty Nablas -> DsM CoreExpr
dsGuarded GRHSs GhcTc (LHsExpr GhcTc)
grhss XPatBind GhcTc GhcTc
Type
ty NonEmpty Nablas
rhss_nablas
        ; let body' :: CoreExpr
body' = [CoreTickish] -> CoreExpr -> CoreExpr
mkOptTickBox [CoreTickish]
rhs_tick CoreExpr
body_expr
              pat' :: LPat GhcTc
pat'  = DynFlags -> LPat GhcTc -> LPat GhcTc
decideBangHood DynFlags
dflags LPat GhcTc
pat
        ; (Id
force_var,[(Id, CoreExpr)]
sel_binds) <- [[CoreTickish]]
-> LPat GhcTc -> CoreExpr -> DsM (Id, [(Id, CoreExpr)])
mkSelectorBinds [[CoreTickish]]
var_ticks LPat GhcTc
pat CoreExpr
body'
          -- We silently ignore inline pragmas; no makeCorePair
          -- Not so cool, but really doesn't matter
        ; let force_var' :: [Id]
force_var' = if LPat GhcTc -> Bool
forall (p :: Pass). LPat (GhcPass p) -> Bool
isBangedLPat LPat GhcTc
pat'
                           then [Id
force_var]
                           else []
        ; ([Id], [(Id, CoreExpr)]) -> DsM ([Id], [(Id, CoreExpr)])
forall (m :: * -> *) a. Monad m => a -> m a
return ([Id]
force_var', [(Id, CoreExpr)]
sel_binds) }

dsHsBind
  DynFlags
dflags
  (XHsBindsLR (AbsBinds { abs_tvs = tyvars, abs_ev_vars = dicts
                        , abs_exports = exports
                        , abs_ev_binds = ev_binds
                        , abs_binds = binds, abs_sig = has_sig }))
  = do { ([Id], [(Id, CoreExpr)])
ds_binds <- Origin
-> Bag Id
-> DsM ([Id], [(Id, CoreExpr)])
-> DsM ([Id], [(Id, CoreExpr)])
forall a. Origin -> Bag Id -> DsM a -> DsM a
addTyCs Origin
FromSource ([Id] -> Bag Id
forall a. [a] -> Bag a
listToBag [Id]
dicts) (DsM ([Id], [(Id, CoreExpr)]) -> DsM ([Id], [(Id, CoreExpr)]))
-> DsM ([Id], [(Id, CoreExpr)]) -> DsM ([Id], [(Id, CoreExpr)])
forall a b. (a -> b) -> a -> b
$
                     LHsBinds GhcTc -> DsM ([Id], [(Id, CoreExpr)])
dsLHsBinds LHsBinds GhcTc
binds
             -- addTyCs: push type constraints deeper
             --            for inner pattern match check
             -- See Check, Note [Long-distance information]

       ; [CoreBind]
ds_ev_binds <- [TcEvBinds] -> DsM [CoreBind]
dsTcEvBinds_s [TcEvBinds]
ev_binds

       -- dsAbsBinds does the hard work
       ; DynFlags
-> [Id]
-> [Id]
-> [ABExport]
-> [CoreBind]
-> ([Id], [(Id, CoreExpr)])
-> Bool
-> DsM ([Id], [(Id, CoreExpr)])
dsAbsBinds DynFlags
dflags [Id]
tyvars [Id]
dicts [ABExport]
exports [CoreBind]
ds_ev_binds ([Id], [(Id, CoreExpr)])
ds_binds Bool
has_sig }

dsHsBind DynFlags
_ (PatSynBind{}) = String -> DsM ([Id], [(Id, CoreExpr)])
forall a. String -> a
panic String
"dsHsBind: PatSynBind"

-----------------------
dsAbsBinds :: DynFlags
           -> [TyVar] -> [EvVar] -> [ABExport]
           -> [CoreBind]                -- Desugared evidence bindings
           -> ([Id], [(Id,CoreExpr)])   -- Desugared value bindings
           -> Bool                      -- Single binding with signature
           -> DsM ([Id], [(Id,CoreExpr)])

dsAbsBinds :: DynFlags
-> [Id]
-> [Id]
-> [ABExport]
-> [CoreBind]
-> ([Id], [(Id, CoreExpr)])
-> Bool
-> DsM ([Id], [(Id, CoreExpr)])
dsAbsBinds DynFlags
dflags [Id]
tyvars [Id]
dicts [ABExport]
exports
           [CoreBind]
ds_ev_binds ([Id]
force_vars, [(Id, CoreExpr)]
bind_prs) Bool
has_sig

    -- A very important common case: one exported variable
    -- Non-recursive bindings come through this way
    -- So do self-recursive bindings
    --    gbl_id = wrap (/\tvs \dicts. let ev_binds
    --                                 letrec bind_prs
    --                                 in lcl_id)
  | [ABExport
export] <- [ABExport]
exports
  , ABE { abe_poly :: ABExport -> Id
abe_poly = Id
global_id, abe_mono :: ABExport -> Id
abe_mono = Id
local_id
        , abe_wrap :: ABExport -> HsWrapper
abe_wrap = HsWrapper
wrap, abe_prags :: ABExport -> TcSpecPrags
abe_prags = TcSpecPrags
prags } <- ABExport
export
  , Just [Id]
force_vars' <- case [Id]
force_vars of
                           []                  -> [Id] -> Maybe [Id]
forall a. a -> Maybe a
Just []
                           [Id
v] | Id
v Id -> Id -> Bool
forall a. Eq a => a -> a -> Bool
== Id
local_id -> [Id] -> Maybe [Id]
forall a. a -> Maybe a
Just [Id
global_id]
                           [Id]
_                   -> Maybe [Id]
forall a. Maybe a
Nothing
       -- If there is a variable to force, it's just the
       -- single variable we are binding here
  = do { CoreExpr -> CoreExpr
core_wrap <- HsWrapper -> DsM (CoreExpr -> CoreExpr)
dsHsWrapper HsWrapper
wrap -- Usually the identity

       ; let rhs :: CoreExpr
rhs = CoreExpr -> CoreExpr
core_wrap (CoreExpr -> CoreExpr) -> CoreExpr -> CoreExpr
forall a b. (a -> b) -> a -> b
$
                   [Id] -> CoreExpr -> CoreExpr
forall b. [b] -> Expr b -> Expr b
mkLams [Id]
tyvars (CoreExpr -> CoreExpr) -> CoreExpr -> CoreExpr
forall a b. (a -> b) -> a -> b
$ [Id] -> CoreExpr -> CoreExpr
forall b. [b] -> Expr b -> Expr b
mkLams [Id]
dicts (CoreExpr -> CoreExpr) -> CoreExpr -> CoreExpr
forall a b. (a -> b) -> a -> b
$
                   [CoreBind] -> CoreExpr -> CoreExpr
mkCoreLets [CoreBind]
ds_ev_binds (CoreExpr -> CoreExpr) -> CoreExpr -> CoreExpr
forall a b. (a -> b) -> a -> b
$
                   CoreExpr
body

             body :: CoreExpr
body | Bool
has_sig
                  , [(Id
_, CoreExpr
lrhs)] <- [(Id, CoreExpr)]
bind_prs
                  = CoreExpr
lrhs
                  | Bool
otherwise
                  = [(Id, CoreExpr)] -> CoreExpr -> CoreExpr
forall b. [(b, Expr b)] -> Expr b -> Expr b
mkLetRec [(Id, CoreExpr)]
bind_prs (Id -> CoreExpr
forall b. Id -> Expr b
Var Id
local_id)

       ; (OrdList (Id, CoreExpr)
spec_binds, [CoreRule]
rules) <- CoreExpr -> TcSpecPrags -> DsM (OrdList (Id, CoreExpr), [CoreRule])
dsSpecs CoreExpr
rhs TcSpecPrags
prags

       ; let global_id' :: Id
global_id' = Id -> [CoreRule] -> Id
addIdSpecialisations Id
global_id [CoreRule]
rules
             main_bind :: (Id, CoreExpr)
main_bind  = DynFlags -> Id -> Bool -> Arity -> CoreExpr -> (Id, CoreExpr)
makeCorePair DynFlags
dflags Id
global_id'
                                       (TcSpecPrags -> Bool
isDefaultMethod TcSpecPrags
prags)
                                       ([Id] -> Arity
dictArity [Id]
dicts) CoreExpr
rhs

       ; ([Id], [(Id, CoreExpr)]) -> DsM ([Id], [(Id, CoreExpr)])
forall (m :: * -> *) a. Monad m => a -> m a
return ([Id]
force_vars', (Id, CoreExpr)
main_bind (Id, CoreExpr) -> [(Id, CoreExpr)] -> [(Id, CoreExpr)]
forall a. a -> [a] -> [a]
: OrdList (Id, CoreExpr) -> [(Id, CoreExpr)]
forall a. OrdList a -> [a]
fromOL OrdList (Id, CoreExpr)
spec_binds) }

    -- Another common case: no tyvars, no dicts
    -- In this case we can have a much simpler desugaring
    --    lcl_id{inl-prag} = rhs  -- Auxiliary binds
    --    gbl_id = lcl_id |> co   -- Main binds
  | [Id] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null [Id]
tyvars, [Id] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null [Id]
dicts
  = do { let mk_main :: ABExport -> DsM (Id, CoreExpr)
             mk_main :: ABExport -> DsM (Id, CoreExpr)
mk_main (ABE { abe_poly :: ABExport -> Id
abe_poly = Id
gbl_id, abe_mono :: ABExport -> Id
abe_mono = Id
lcl_id
                          , abe_wrap :: ABExport -> HsWrapper
abe_wrap = HsWrapper
wrap })
                     -- No SpecPrags (no dicts)
                     -- Can't be a default method (default methods are singletons)
               = do { CoreExpr -> CoreExpr
core_wrap <- HsWrapper -> DsM (CoreExpr -> CoreExpr)
dsHsWrapper HsWrapper
wrap
                    ; (Id, CoreExpr) -> DsM (Id, CoreExpr)
forall (m :: * -> *) a. Monad m => a -> m a
return ( Id
gbl_id Id -> InlinePragma -> Id
`setInlinePragma` InlinePragma
defaultInlinePragma
                             , CoreExpr -> CoreExpr
core_wrap (Id -> CoreExpr
forall b. Id -> Expr b
Var Id
lcl_id)) }

       ; [(Id, CoreExpr)]
main_prs <- (ABExport -> DsM (Id, CoreExpr))
-> [ABExport] -> IOEnv (Env DsGblEnv DsLclEnv) [(Id, CoreExpr)]
forall (t :: * -> *) (m :: * -> *) a b.
(Traversable t, Monad m) =>
(a -> m b) -> t a -> m (t b)
mapM ABExport -> DsM (Id, CoreExpr)
mk_main [ABExport]
exports
       ; ([Id], [(Id, CoreExpr)]) -> DsM ([Id], [(Id, CoreExpr)])
forall (m :: * -> *) a. Monad m => a -> m a
return ([Id]
force_vars, [CoreBind] -> [(Id, CoreExpr)]
forall b. [Bind b] -> [(b, Expr b)]
flattenBinds [CoreBind]
ds_ev_binds
                              [(Id, CoreExpr)] -> [(Id, CoreExpr)] -> [(Id, CoreExpr)]
forall a. [a] -> [a] -> [a]
++ [(Id, CoreExpr)] -> [(Id, CoreExpr)]
mk_aux_binds [(Id, CoreExpr)]
bind_prs [(Id, CoreExpr)] -> [(Id, CoreExpr)] -> [(Id, CoreExpr)]
forall a. [a] -> [a] -> [a]
++ [(Id, CoreExpr)]
main_prs ) }

    -- The general case
    -- See Note [Desugaring AbsBinds]
  | Bool
otherwise
  = do { let aux_binds :: CoreBind
aux_binds = [(Id, CoreExpr)] -> CoreBind
forall b. [(b, Expr b)] -> Bind b
Rec ([(Id, CoreExpr)] -> [(Id, CoreExpr)]
mk_aux_binds [(Id, CoreExpr)]
bind_prs)
                -- Monomorphic recursion possible, hence Rec

             new_force_vars :: [Id]
new_force_vars = [Id] -> [Id]
forall (t :: * -> *). Foldable t => t Id -> [Id]
get_new_force_vars [Id]
force_vars
             locals :: [Id]
locals       = (ABExport -> Id) -> [ABExport] -> [Id]
forall a b. (a -> b) -> [a] -> [b]
map ABExport -> Id
abe_mono [ABExport]
exports
             all_locals :: [Id]
all_locals   = [Id]
locals [Id] -> [Id] -> [Id]
forall a. [a] -> [a] -> [a]
++ [Id]
new_force_vars
             tup_expr :: CoreExpr
tup_expr     = [Id] -> CoreExpr
mkBigCoreVarTup [Id]
all_locals
             tup_ty :: Type
tup_ty       = HasDebugCallStack => CoreExpr -> Type
CoreExpr -> Type
exprType CoreExpr
tup_expr
       ; let poly_tup_rhs :: CoreExpr
poly_tup_rhs = [Id] -> CoreExpr -> CoreExpr
forall b. [b] -> Expr b -> Expr b
mkLams [Id]
tyvars (CoreExpr -> CoreExpr) -> CoreExpr -> CoreExpr
forall a b. (a -> b) -> a -> b
$ [Id] -> CoreExpr -> CoreExpr
forall b. [b] -> Expr b -> Expr b
mkLams [Id]
dicts (CoreExpr -> CoreExpr) -> CoreExpr -> CoreExpr
forall a b. (a -> b) -> a -> b
$
                            [CoreBind] -> CoreExpr -> CoreExpr
mkCoreLets [CoreBind]
ds_ev_binds (CoreExpr -> CoreExpr) -> CoreExpr -> CoreExpr
forall a b. (a -> b) -> a -> b
$
                            CoreBind -> CoreExpr -> CoreExpr
forall b. Bind b -> Expr b -> Expr b
mkLet CoreBind
aux_binds (CoreExpr -> CoreExpr) -> CoreExpr -> CoreExpr
forall a b. (a -> b) -> a -> b
$
                            CoreExpr
tup_expr

       ; Id
poly_tup_id <- Type -> Type -> DsM Id
newSysLocalDs Type
Many (HasDebugCallStack => CoreExpr -> Type
CoreExpr -> Type
exprType CoreExpr
poly_tup_rhs)

        -- Find corresponding global or make up a new one: sometimes
        -- we need to make new export to desugar strict binds, see
        -- Note [Desugar Strict binds]
       ; ([Id]
exported_force_vars, [ABExport]
extra_exports) <- [Id] -> DsM ([Id], [ABExport])
get_exports [Id]
force_vars

       ; let mk_bind :: ABExport -> IOEnv (Env DsGblEnv DsLclEnv) [(Id, CoreExpr)]
mk_bind (ABE { abe_wrap :: ABExport -> HsWrapper
abe_wrap = HsWrapper
wrap
                          , abe_poly :: ABExport -> Id
abe_poly = Id
global
                          , abe_mono :: ABExport -> Id
abe_mono = Id
local, abe_prags :: ABExport -> TcSpecPrags
abe_prags = TcSpecPrags
spec_prags })
                          -- See Note [AbsBinds wrappers] in "GHC.Hs.Binds"
                = do { Id
tup_id  <- Type -> Type -> DsM Id
newSysLocalDs Type
Many Type
tup_ty
                     ; CoreExpr -> CoreExpr
core_wrap <- HsWrapper -> DsM (CoreExpr -> CoreExpr)
dsHsWrapper HsWrapper
wrap
                     ; let rhs :: CoreExpr
rhs = CoreExpr -> CoreExpr
core_wrap (CoreExpr -> CoreExpr) -> CoreExpr -> CoreExpr
forall a b. (a -> b) -> a -> b
$ [Id] -> CoreExpr -> CoreExpr
forall b. [b] -> Expr b -> Expr b
mkLams [Id]
tyvars (CoreExpr -> CoreExpr) -> CoreExpr -> CoreExpr
forall a b. (a -> b) -> a -> b
$ [Id] -> CoreExpr -> CoreExpr
forall b. [b] -> Expr b -> Expr b
mkLams [Id]
dicts (CoreExpr -> CoreExpr) -> CoreExpr -> CoreExpr
forall a b. (a -> b) -> a -> b
$
                                 [Id] -> Id -> Id -> CoreExpr -> CoreExpr
mkTupleSelector [Id]
all_locals Id
local Id
tup_id (CoreExpr -> CoreExpr) -> CoreExpr -> CoreExpr
forall a b. (a -> b) -> a -> b
$
                                 CoreExpr -> [Id] -> CoreExpr
forall b. Expr b -> [Id] -> Expr b
mkVarApps (Id -> CoreExpr
forall b. Id -> Expr b
Var Id
poly_tup_id) ([Id]
tyvars [Id] -> [Id] -> [Id]
forall a. [a] -> [a] -> [a]
++ [Id]
dicts)
                           rhs_for_spec :: CoreExpr
rhs_for_spec = CoreBind -> CoreExpr -> CoreExpr
forall b. Bind b -> Expr b -> Expr b
Let (Id -> CoreExpr -> CoreBind
forall b. b -> Expr b -> Bind b
NonRec Id
poly_tup_id CoreExpr
poly_tup_rhs) CoreExpr
rhs
                     ; (OrdList (Id, CoreExpr)
spec_binds, [CoreRule]
rules) <- CoreExpr -> TcSpecPrags -> DsM (OrdList (Id, CoreExpr), [CoreRule])
dsSpecs CoreExpr
rhs_for_spec TcSpecPrags
spec_prags
                     ; let global' :: Id
global' = (Id
global Id -> InlinePragma -> Id
`setInlinePragma` InlinePragma
defaultInlinePragma)
                                             Id -> [CoreRule] -> Id
`addIdSpecialisations` [CoreRule]
rules
                           -- Kill the INLINE pragma because it applies to
                           -- the user written (local) function.  The global
                           -- Id is just the selector.  Hmm.
                     ; [(Id, CoreExpr)] -> IOEnv (Env DsGblEnv DsLclEnv) [(Id, CoreExpr)]
forall (m :: * -> *) a. Monad m => a -> m a
return ((Id
global', CoreExpr
rhs) (Id, CoreExpr) -> [(Id, CoreExpr)] -> [(Id, CoreExpr)]
forall a. a -> [a] -> [a]
: OrdList (Id, CoreExpr) -> [(Id, CoreExpr)]
forall a. OrdList a -> [a]
fromOL OrdList (Id, CoreExpr)
spec_binds) }

       ; [[(Id, CoreExpr)]]
export_binds_s <- (ABExport -> IOEnv (Env DsGblEnv DsLclEnv) [(Id, CoreExpr)])
-> [ABExport] -> IOEnv (Env DsGblEnv DsLclEnv) [[(Id, CoreExpr)]]
forall (t :: * -> *) (m :: * -> *) a b.
(Traversable t, Monad m) =>
(a -> m b) -> t a -> m (t b)
mapM ABExport -> IOEnv (Env DsGblEnv DsLclEnv) [(Id, CoreExpr)]
mk_bind ([ABExport]
exports [ABExport] -> [ABExport] -> [ABExport]
forall a. [a] -> [a] -> [a]
++ [ABExport]
extra_exports)

       ; ([Id], [(Id, CoreExpr)]) -> DsM ([Id], [(Id, CoreExpr)])
forall (m :: * -> *) a. Monad m => a -> m a
return ( [Id]
exported_force_vars
                , (Id
poly_tup_id, CoreExpr
poly_tup_rhs) (Id, CoreExpr) -> [(Id, CoreExpr)] -> [(Id, CoreExpr)]
forall a. a -> [a] -> [a]
:
                   [[(Id, CoreExpr)]] -> [(Id, CoreExpr)]
forall (t :: * -> *) a. Foldable t => t [a] -> [a]
concat [[(Id, CoreExpr)]]
export_binds_s) }
  where
    mk_aux_binds :: [(Id,CoreExpr)] -> [(Id,CoreExpr)]
    mk_aux_binds :: [(Id, CoreExpr)] -> [(Id, CoreExpr)]
mk_aux_binds [(Id, CoreExpr)]
bind_prs = [ DynFlags -> Id -> Bool -> Arity -> CoreExpr -> (Id, CoreExpr)
makeCorePair DynFlags
dflags Id
lcl_w_inline Bool
False Arity
0 CoreExpr
rhs
                            | (Id
lcl_id, CoreExpr
rhs) <- [(Id, CoreExpr)]
bind_prs
                            , let lcl_w_inline :: Id
lcl_w_inline = VarEnv Id -> Id -> Maybe Id
forall a. VarEnv a -> Id -> Maybe a
lookupVarEnv VarEnv Id
inline_env Id
lcl_id
                                                 Maybe Id -> Id -> Id
forall a. Maybe a -> a -> a
`orElse` Id
lcl_id ]

    inline_env :: IdEnv Id -- Maps a monomorphic local Id to one with
                           -- the inline pragma from the source
                           -- The type checker put the inline pragma
                           -- on the *global* Id, so we need to transfer it
    inline_env :: VarEnv Id
inline_env
      = [(Id, Id)] -> VarEnv Id
forall a. [(Id, a)] -> VarEnv a
mkVarEnv [ (Id
lcl_id, Id -> InlinePragma -> Id
setInlinePragma Id
lcl_id InlinePragma
prag)
                 | ABE { abe_mono :: ABExport -> Id
abe_mono = Id
lcl_id, abe_poly :: ABExport -> Id
abe_poly = Id
gbl_id } <- [ABExport]
exports
                 , let prag :: InlinePragma
prag = Id -> InlinePragma
idInlinePragma Id
gbl_id ]

    global_env :: IdEnv Id -- Maps local Id to its global exported Id
    global_env :: VarEnv Id
global_env =
      [(Id, Id)] -> VarEnv Id
forall a. [(Id, a)] -> VarEnv a
mkVarEnv [ (Id
local, Id
global)
               | ABE { abe_mono :: ABExport -> Id
abe_mono = Id
local, abe_poly :: ABExport -> Id
abe_poly = Id
global } <- [ABExport]
exports
               ]

    -- find variables that are not exported
    get_new_force_vars :: t Id -> [Id]
get_new_force_vars t Id
lcls =
      (Id -> [Id] -> [Id]) -> [Id] -> t Id -> [Id]
forall (t :: * -> *) a b.
Foldable t =>
(a -> b -> b) -> b -> t a -> b
foldr (\Id
lcl [Id]
acc -> case VarEnv Id -> Id -> Maybe Id
forall a. VarEnv a -> Id -> Maybe a
lookupVarEnv VarEnv Id
global_env Id
lcl of
                           Just Id
_ -> [Id]
acc
                           Maybe Id
Nothing -> Id
lclId -> [Id] -> [Id]
forall a. a -> [a] -> [a]
:[Id]
acc)
            [] t Id
lcls

    -- find exports or make up new exports for force variables
    get_exports :: [Id] -> DsM ([Id], [ABExport])
    get_exports :: [Id] -> DsM ([Id], [ABExport])
get_exports [Id]
lcls =
      (([Id], [ABExport]) -> Id -> DsM ([Id], [ABExport]))
-> ([Id], [ABExport]) -> [Id] -> DsM ([Id], [ABExport])
forall (t :: * -> *) (m :: * -> *) b a.
(Foldable t, Monad m) =>
(b -> a -> m b) -> b -> t a -> m b
foldM (\([Id]
glbls, [ABExport]
exports) Id
lcl ->
              case VarEnv Id -> Id -> Maybe Id
forall a. VarEnv a -> Id -> Maybe a
lookupVarEnv VarEnv Id
global_env Id
lcl of
                Just Id
glbl -> ([Id], [ABExport]) -> DsM ([Id], [ABExport])
forall (m :: * -> *) a. Monad m => a -> m a
return (Id
glblId -> [Id] -> [Id]
forall a. a -> [a] -> [a]
:[Id]
glbls, [ABExport]
exports)
                Maybe Id
Nothing   -> do ABExport
export <- Id -> IOEnv (Env DsGblEnv DsLclEnv) ABExport
mk_export Id
lcl
                                let glbl :: Id
glbl = ABExport -> Id
abe_poly ABExport
export
                                ([Id], [ABExport]) -> DsM ([Id], [ABExport])
forall (m :: * -> *) a. Monad m => a -> m a
return (Id
glblId -> [Id] -> [Id]
forall a. a -> [a] -> [a]
:[Id]
glbls, ABExport
exportABExport -> [ABExport] -> [ABExport]
forall a. a -> [a] -> [a]
:[ABExport]
exports))
            ([],[]) [Id]
lcls

    mk_export :: Id -> IOEnv (Env DsGblEnv DsLclEnv) ABExport
mk_export Id
local =
      do Id
global <- Type -> Type -> DsM Id
newSysLocalDs Type
Many
                     (HasDebugCallStack => CoreExpr -> Type
CoreExpr -> Type
exprType ([Id] -> CoreExpr -> CoreExpr
forall b. [b] -> Expr b -> Expr b
mkLams [Id]
tyvars ([Id] -> CoreExpr -> CoreExpr
forall b. [b] -> Expr b -> Expr b
mkLams [Id]
dicts (Id -> CoreExpr
forall b. Id -> Expr b
Var Id
local))))
         ABExport -> IOEnv (Env DsGblEnv DsLclEnv) ABExport
forall (m :: * -> *) a. Monad m => a -> m a
return (ABE :: Id -> Id -> HsWrapper -> TcSpecPrags -> ABExport
ABE { abe_poly :: Id
abe_poly  = Id
global
                     , abe_mono :: Id
abe_mono  = Id
local
                     , abe_wrap :: HsWrapper
abe_wrap  = HsWrapper
WpHole
                     , abe_prags :: TcSpecPrags
abe_prags = [LTcSpecPrag] -> TcSpecPrags
SpecPrags [] })

-- | This is where we apply INLINE and INLINABLE pragmas. All we need to
-- do is to attach the unfolding information to the Id.
--
-- Other decisions about whether to inline are made in
-- `calcUnfoldingGuidance` but the decision about whether to then expose
-- the unfolding in the interface file is made in `GHC.Iface.Tidy.addExternal`
-- using this information.
------------------------
makeCorePair :: DynFlags -> Id -> Bool -> Arity -> CoreExpr
             -> (Id, CoreExpr)
makeCorePair :: DynFlags -> Id -> Bool -> Arity -> CoreExpr -> (Id, CoreExpr)
makeCorePair DynFlags
dflags Id
gbl_id Bool
is_default_method Arity
dict_arity CoreExpr
rhs
  | Bool
is_default_method    -- Default methods are *always* inlined
                         -- See Note [INLINE and default methods] in GHC.Tc.TyCl.Instance
  = (Id
gbl_id Id -> Unfolding -> Id
`setIdUnfolding` SimpleOpts -> CoreExpr -> Unfolding
mkCompulsoryUnfolding SimpleOpts
simpl_opts CoreExpr
rhs, CoreExpr
rhs)

  | Bool
otherwise
  = case InlinePragma -> InlineSpec
inlinePragmaSpec InlinePragma
inline_prag of
          InlineSpec
NoUserInlinePrag -> (Id
gbl_id, CoreExpr
rhs)
          NoInline  {}     -> (Id
gbl_id, CoreExpr
rhs)
          Opaque    {}     -> (Id
gbl_id, CoreExpr
rhs)
          Inlinable {}     -> (Id
gbl_id Id -> Unfolding -> Id
`setIdUnfolding` Unfolding
inlinable_unf, CoreExpr
rhs)
          Inline    {}     -> (Id, CoreExpr)
inline_pair
  where
    simpl_opts :: SimpleOpts
simpl_opts    = DynFlags -> SimpleOpts
initSimpleOpts DynFlags
dflags
    inline_prag :: InlinePragma
inline_prag   = Id -> InlinePragma
idInlinePragma Id
gbl_id
    inlinable_unf :: Unfolding
inlinable_unf = SimpleOpts -> CoreExpr -> Unfolding
mkInlinableUnfolding SimpleOpts
simpl_opts CoreExpr
rhs
    inline_pair :: (Id, CoreExpr)
inline_pair
       | Just Arity
arity <- InlinePragma -> Maybe Arity
inlinePragmaSat InlinePragma
inline_prag
        -- Add an Unfolding for an INLINE (but not for NOINLINE)
        -- And eta-expand the RHS; see Note [Eta-expanding INLINE things]
       , let real_arity :: Arity
real_arity = Arity
dict_arity Arity -> Arity -> Arity
forall a. Num a => a -> a -> a
+ Arity
arity
        -- NB: The arity in the InlineRule takes account of the dictionaries
       = ( Id
gbl_id Id -> Unfolding -> Id
`setIdUnfolding` Arity -> SimpleOpts -> CoreExpr -> Unfolding
mkInlineUnfoldingWithArity Arity
real_arity SimpleOpts
simpl_opts CoreExpr
rhs
         , Arity -> CoreExpr -> CoreExpr
etaExpand Arity
real_arity CoreExpr
rhs)

       | Bool
otherwise
       = String -> SDoc -> (Id, CoreExpr) -> (Id, CoreExpr)
forall a. String -> SDoc -> a -> a
pprTrace String
"makeCorePair: arity missing" (Id -> SDoc
forall a. Outputable a => a -> SDoc
ppr Id
gbl_id) ((Id, CoreExpr) -> (Id, CoreExpr))
-> (Id, CoreExpr) -> (Id, CoreExpr)
forall a b. (a -> b) -> a -> b
$
         (Id
gbl_id Id -> Unfolding -> Id
`setIdUnfolding` SimpleOpts -> CoreExpr -> Unfolding
mkInlineUnfolding SimpleOpts
simpl_opts CoreExpr
rhs, CoreExpr
rhs)

dictArity :: [Var] -> Arity
-- Don't count coercion variables in arity
dictArity :: [Id] -> Arity
dictArity [Id]
dicts = (Id -> Bool) -> [Id] -> Arity
forall a. (a -> Bool) -> [a] -> Arity
count Id -> Bool
isId [Id]
dicts

{-
Note [Desugaring AbsBinds]
~~~~~~~~~~~~~~~~~~~~~~~~~~
In the general AbsBinds case we desugar the binding to this:

       tup a (d:Num a) = let fm = ...gm...
                             gm = ...fm...
                         in (fm,gm)
       f a d = case tup a d of { (fm,gm) -> fm }
       g a d = case tup a d of { (fm,gm) -> fm }

Note [Rules and inlining]
~~~~~~~~~~~~~~~~~~~~~~~~~
Common special case: no type or dictionary abstraction
This is a bit less trivial than you might suppose
The naive way would be to desugar to something like
        f_lcl = ...f_lcl...     -- The "binds" from AbsBinds
        M.f = f_lcl             -- Generated from "exports"
But we don't want that, because if M.f isn't exported,
it'll be inlined unconditionally at every call site (its rhs is
trivial).  That would be ok unless it has RULES, which would
thereby be completely lost.  Bad, bad, bad.

Instead we want to generate
        M.f = ...f_lcl...
        f_lcl = M.f
Now all is cool. The RULES are attached to M.f (by SimplCore),
and f_lcl is rapidly inlined away.

This does not happen in the same way to polymorphic binds,
because they desugar to
        M.f = /\a. let f_lcl = ...f_lcl... in f_lcl
Although I'm a bit worried about whether full laziness might
float the f_lcl binding out and then inline M.f at its call site

Note [Specialising in no-dict case]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Even if there are no tyvars or dicts, we may have specialisation pragmas.
Class methods can generate
      AbsBinds [] [] [( ... spec-prag]
         { AbsBinds [tvs] [dicts] ...blah }
So the overloading is in the nested AbsBinds. A good example is in GHC.Float:

  class  (Real a, Fractional a) => RealFrac a  where
    round :: (Integral b) => a -> b

  instance  RealFrac Float  where
    {-# SPECIALIZE round :: Float -> Int #-}

The top-level AbsBinds for $cround has no tyvars or dicts (because the
instance does not).  But the method is locally overloaded!

Note [Abstracting over tyvars only]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
When abstracting over type variable only (not dictionaries), we don't really need to
built a tuple and select from it, as we do in the general case. Instead we can take

        AbsBinds [a,b] [ ([a,b], fg, fl, _),
                         ([b],   gg, gl, _) ]
                { fl = e1
                  gl = e2
                   h = e3 }

and desugar it to

        fg = /\ab. let B in e1
        gg = /\b. let a = () in let B in S(e2)
        h  = /\ab. let B in e3

where B is the *non-recursive* binding
        fl = fg a b
        gl = gg b
        h  = h a b    -- See (b); note shadowing!

Notice (a) g has a different number of type variables to f, so we must
             use the mkArbitraryType thing to fill in the gaps.
             We use a type-let to do that.

         (b) The local variable h isn't in the exports, and rather than
             clone a fresh copy we simply replace h by (h a b), where
             the two h's have different types!  Shadowing happens here,
             which looks confusing but works fine.

         (c) The result is *still* quadratic-sized if there are a lot of
             small bindings.  So if there are more than some small
             number (10), we filter the binding set B by the free
             variables of the particular RHS.  Tiresome.

Why got to this trouble?  It's a common case, and it removes the
quadratic-sized tuple desugaring.  Less clutter, hopefully faster
compilation, especially in a case where there are a *lot* of
bindings.


Note [Eta-expanding INLINE things]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider
   foo :: Eq a => a -> a
   {-# INLINE foo #-}
   foo x = ...

If (foo d) ever gets floated out as a common sub-expression (which can
happen as a result of method sharing), there's a danger that we never
get to do the inlining, which is a Terribly Bad thing given that the
user said "inline"!

To avoid this we pre-emptively eta-expand the definition, so that foo
has the arity with which it is declared in the source code.  In this
example it has arity 2 (one for the Eq and one for x). Doing this
should mean that (foo d) is a PAP and we don't share it.

Note [Nested arities]
~~~~~~~~~~~~~~~~~~~~~
For reasons that are not entirely clear, method bindings come out looking like
this:

  AbsBinds [] [] [$cfromT <= [] fromT]
    $cfromT [InlPrag=INLINE] :: T Bool -> Bool
    { AbsBinds [] [] [fromT <= [] fromT_1]
        fromT :: T Bool -> Bool
        { fromT_1 ((TBool b)) = not b } } }

Note the nested AbsBind.  The arity for the InlineRule on $cfromT should be
gotten from the binding for fromT_1.

It might be better to have just one level of AbsBinds, but that requires more
thought!


Note [Desugar Strict binds]
~~~~~~~~~~~~~~~~~~~~~~~~~~~
See https://gitlab.haskell.org/ghc/ghc/wikis/strict-pragma

Desugaring strict variable bindings looks as follows (core below ==>)

  let !x = rhs
  in  body
==>
  let x = rhs
  in x `seq` body -- seq the variable

and if it is a pattern binding the desugaring looks like

  let !pat = rhs
  in body
==>
  let x = rhs -- bind the rhs to a new variable
      pat = x
  in x `seq` body -- seq the new variable

if there is no variable in the pattern desugaring looks like

  let False = rhs
  in body
==>
  let x = case rhs of {False -> (); _ -> error "Match failed"}
  in x `seq` body

In order to force the Ids in the binding group they are passed around
in the dsHsBind family of functions, and later seq'ed in GHC.HsToCore.Expr.ds_val_bind.

Consider a recursive group like this

  letrec
     f : g = rhs[f,g]
  in <body>

Without `Strict`, we get a translation like this:

  let t = /\a. letrec tm = rhs[fm,gm]
                      fm = case t of fm:_ -> fm
                      gm = case t of _:gm -> gm
                in
                (fm,gm)

  in let f = /\a. case t a of (fm,_) -> fm
  in let g = /\a. case t a of (_,gm) -> gm
  in <body>

Here `tm` is the monomorphic binding for `rhs`.

With `Strict`, we want to force `tm`, but NOT `fm` or `gm`.
Alas, `tm` isn't in scope in the `in <body>` part.

The simplest thing is to return it in the polymorphic
tuple `t`, thus:

  let t = /\a. letrec tm = rhs[fm,gm]
                      fm = case t of fm:_ -> fm
                      gm = case t of _:gm -> gm
                in
                (tm, fm, gm)

  in let f = /\a. case t a of (_,fm,_) -> fm
  in let g = /\a. case t a of (_,_,gm) -> gm
  in let tm = /\a. case t a of (tm,_,_) -> tm
  in tm `seq` <body>


See https://gitlab.haskell.org/ghc/ghc/wikis/strict-pragma for a more
detailed explanation of the desugaring of strict bindings.

Note [Strict binds checks]
~~~~~~~~~~~~~~~~~~~~~~~~~~
There are several checks around properly formed strict bindings. They
all link to this Note. These checks must be here in the desugarer because
we cannot know whether or not a type is unlifted until after zonking, due
to representation polymorphism. These checks all used to be handled in the
typechecker in checkStrictBinds (before Jan '17).

We define an "unlifted bind" to be any bind that binds an unlifted id. Note that

  x :: Char
  (# True, x #) = blah

is *not* an unlifted bind. Unlifted binds are detected by GHC.Hs.Utils.isUnliftedHsBind.

Define a "banged bind" to have a top-level bang. Detected by GHC.Hs.Pat.isBangedHsBind.
Define a "strict bind" to be either an unlifted bind or a banged bind.

The restrictions are:
  1. Strict binds may not be top-level. Checked in dsTopLHsBinds.

  2. Unlifted binds must also be banged. (There is no trouble to compile an unbanged
     unlifted bind, but an unbanged bind looks lazy, and we don't want users to be
     surprised by the strictness of an unlifted bind.) Checked in first clause
     of GHC.HsToCore.Expr.ds_val_bind.

  3. Unlifted binds may not have polymorphism (#6078). (That is, no quantified type
     variables or constraints.) Checked in first clause
     of GHC.HsToCore.Expr.ds_val_bind.

  4. Unlifted binds may not be recursive. Checked in second clause of ds_val_bind.

-}

------------------------
dsSpecs :: CoreExpr     -- Its rhs
        -> TcSpecPrags
        -> DsM ( OrdList (Id,CoreExpr)  -- Binding for specialised Ids
               , [CoreRule] )           -- Rules for the Global Ids
-- See Note [Handling SPECIALISE pragmas] in GHC.Tc.Gen.Bind
dsSpecs :: CoreExpr -> TcSpecPrags -> DsM (OrdList (Id, CoreExpr), [CoreRule])
dsSpecs CoreExpr
_ TcSpecPrags
IsDefaultMethod = (OrdList (Id, CoreExpr), [CoreRule])
-> DsM (OrdList (Id, CoreExpr), [CoreRule])
forall (m :: * -> *) a. Monad m => a -> m a
return (OrdList (Id, CoreExpr)
forall a. OrdList a
nilOL, [])
dsSpecs CoreExpr
poly_rhs (SpecPrags [LTcSpecPrag]
sps)
  = do { [(OrdList (Id, CoreExpr), CoreRule)]
pairs <- (LTcSpecPrag
 -> IOEnv
      (Env DsGblEnv DsLclEnv) (Maybe (OrdList (Id, CoreExpr), CoreRule)))
-> [LTcSpecPrag]
-> IOEnv
     (Env DsGblEnv DsLclEnv) [(OrdList (Id, CoreExpr), CoreRule)]
forall (m :: * -> *) a b.
Applicative m =>
(a -> m (Maybe b)) -> [a] -> m [b]
mapMaybeM (Maybe CoreExpr
-> LTcSpecPrag
-> IOEnv
     (Env DsGblEnv DsLclEnv) (Maybe (OrdList (Id, CoreExpr), CoreRule))
dsSpec (CoreExpr -> Maybe CoreExpr
forall a. a -> Maybe a
Just CoreExpr
poly_rhs)) [LTcSpecPrag]
sps
       ; let ([OrdList (Id, CoreExpr)]
spec_binds_s, [CoreRule]
rules) = [(OrdList (Id, CoreExpr), CoreRule)]
-> ([OrdList (Id, CoreExpr)], [CoreRule])
forall a b. [(a, b)] -> ([a], [b])
unzip [(OrdList (Id, CoreExpr), CoreRule)]
pairs
       ; (OrdList (Id, CoreExpr), [CoreRule])
-> DsM (OrdList (Id, CoreExpr), [CoreRule])
forall (m :: * -> *) a. Monad m => a -> m a
return ([OrdList (Id, CoreExpr)] -> OrdList (Id, CoreExpr)
forall a. [OrdList a] -> OrdList a
concatOL [OrdList (Id, CoreExpr)]
spec_binds_s, [CoreRule]
rules) }

dsSpec :: Maybe CoreExpr        -- Just rhs => RULE is for a local binding
                                -- Nothing => RULE is for an imported Id
                                --            rhs is in the Id's unfolding
       -> Located TcSpecPrag
       -> DsM (Maybe (OrdList (Id,CoreExpr), CoreRule))
dsSpec :: Maybe CoreExpr
-> LTcSpecPrag
-> IOEnv
     (Env DsGblEnv DsLclEnv) (Maybe (OrdList (Id, CoreExpr), CoreRule))
dsSpec Maybe CoreExpr
mb_poly_rhs (L SrcSpan
loc (SpecPrag Id
poly_id HsWrapper
spec_co InlinePragma
spec_inl))
  | Maybe Class -> Bool
forall a. Maybe a -> Bool
isJust (Id -> Maybe Class
isClassOpId_maybe Id
poly_id)
  = SrcSpan
-> IOEnv
     (Env DsGblEnv DsLclEnv) (Maybe (OrdList (Id, CoreExpr), CoreRule))
-> IOEnv
     (Env DsGblEnv DsLclEnv) (Maybe (OrdList (Id, CoreExpr), CoreRule))
forall a. SrcSpan -> DsM a -> DsM a
putSrcSpanDs SrcSpan
loc (IOEnv
   (Env DsGblEnv DsLclEnv) (Maybe (OrdList (Id, CoreExpr), CoreRule))
 -> IOEnv
      (Env DsGblEnv DsLclEnv) (Maybe (OrdList (Id, CoreExpr), CoreRule)))
-> IOEnv
     (Env DsGblEnv DsLclEnv) (Maybe (OrdList (Id, CoreExpr), CoreRule))
-> IOEnv
     (Env DsGblEnv DsLclEnv) (Maybe (OrdList (Id, CoreExpr), CoreRule))
forall a b. (a -> b) -> a -> b
$
    do { DsMessage -> IOEnv (Env DsGblEnv DsLclEnv) ()
diagnosticDs (Id -> DsMessage
DsUselessSpecialiseForClassMethodSelector Id
poly_id)
       ; Maybe (OrdList (Id, CoreExpr), CoreRule)
-> IOEnv
     (Env DsGblEnv DsLclEnv) (Maybe (OrdList (Id, CoreExpr), CoreRule))
forall (m :: * -> *) a. Monad m => a -> m a
return Maybe (OrdList (Id, CoreExpr), CoreRule)
forall a. Maybe a
Nothing  }  -- There is no point in trying to specialise a class op
                            -- Moreover, classops don't (currently) have an inl_sat arity set
                            -- (it would be Just 0) and that in turn makes makeCorePair bleat

  | Bool
no_act_spec Bool -> Bool -> Bool
&& Activation -> Bool
isNeverActive Activation
rule_act
  = SrcSpan
-> IOEnv
     (Env DsGblEnv DsLclEnv) (Maybe (OrdList (Id, CoreExpr), CoreRule))
-> IOEnv
     (Env DsGblEnv DsLclEnv) (Maybe (OrdList (Id, CoreExpr), CoreRule))
forall a. SrcSpan -> DsM a -> DsM a
putSrcSpanDs SrcSpan
loc (IOEnv
   (Env DsGblEnv DsLclEnv) (Maybe (OrdList (Id, CoreExpr), CoreRule))
 -> IOEnv
      (Env DsGblEnv DsLclEnv) (Maybe (OrdList (Id, CoreExpr), CoreRule)))
-> IOEnv
     (Env DsGblEnv DsLclEnv) (Maybe (OrdList (Id, CoreExpr), CoreRule))
-> IOEnv
     (Env DsGblEnv DsLclEnv) (Maybe (OrdList (Id, CoreExpr), CoreRule))
forall a b. (a -> b) -> a -> b
$
    do { DsMessage -> IOEnv (Env DsGblEnv DsLclEnv) ()
diagnosticDs (Id -> DsMessage
DsUselessSpecialiseForNoInlineFunction Id
poly_id)
       ; Maybe (OrdList (Id, CoreExpr), CoreRule)
-> IOEnv
     (Env DsGblEnv DsLclEnv) (Maybe (OrdList (Id, CoreExpr), CoreRule))
forall (m :: * -> *) a. Monad m => a -> m a
return Maybe (OrdList (Id, CoreExpr), CoreRule)
forall a. Maybe a
Nothing  }  -- Function is NOINLINE, and the specialisation inherits that
                            -- See Note [Activation pragmas for SPECIALISE]

  | Bool
otherwise
  = SrcSpan
-> IOEnv
     (Env DsGblEnv DsLclEnv) (Maybe (OrdList (Id, CoreExpr), CoreRule))
-> IOEnv
     (Env DsGblEnv DsLclEnv) (Maybe (OrdList (Id, CoreExpr), CoreRule))
forall a. SrcSpan -> DsM a -> DsM a
putSrcSpanDs SrcSpan
loc (IOEnv
   (Env DsGblEnv DsLclEnv) (Maybe (OrdList (Id, CoreExpr), CoreRule))
 -> IOEnv
      (Env DsGblEnv DsLclEnv) (Maybe (OrdList (Id, CoreExpr), CoreRule)))
-> IOEnv
     (Env DsGblEnv DsLclEnv) (Maybe (OrdList (Id, CoreExpr), CoreRule))
-> IOEnv
     (Env DsGblEnv DsLclEnv) (Maybe (OrdList (Id, CoreExpr), CoreRule))
forall a b. (a -> b) -> a -> b
$
    do { Unique
uniq <- TcRnIf DsGblEnv DsLclEnv Unique
forall gbl lcl. TcRnIf gbl lcl Unique
newUnique
       ; let poly_name :: Name
poly_name = Id -> Name
idName Id
poly_id
             spec_occ :: OccName
spec_occ  = OccName -> OccName
mkSpecOcc (Name -> OccName
forall a. NamedThing a => a -> OccName
getOccName Name
poly_name)
             spec_name :: Name
spec_name = Unique -> OccName -> SrcSpan -> Name
mkInternalName Unique
uniq OccName
spec_occ (Name -> SrcSpan
forall a. NamedThing a => a -> SrcSpan
getSrcSpan Name
poly_name)
             ([Id]
spec_bndrs, HsWrapper
spec_app) = HsWrapper -> ([Id], HsWrapper)
collectHsWrapBinders HsWrapper
spec_co
               -- spec_co looks like
               --         \spec_bndrs. [] spec_args
               -- perhaps with the body of the lambda wrapped in some WpLets
               -- E.g. /\a \(d:Eq a). let d2 = $df d in [] (Maybe a) d2

       ; CoreExpr -> CoreExpr
core_app <- HsWrapper -> DsM (CoreExpr -> CoreExpr)
dsHsWrapper HsWrapper
spec_app

       ; let ds_lhs :: CoreExpr
ds_lhs  = CoreExpr -> CoreExpr
core_app (Id -> CoreExpr
forall b. Id -> Expr b
Var Id
poly_id)
             spec_ty :: Type
spec_ty = [Id] -> Type -> Type
mkLamTypes [Id]
spec_bndrs (HasDebugCallStack => CoreExpr -> Type
CoreExpr -> Type
exprType CoreExpr
ds_lhs)
       ; -- pprTrace "dsRule" (vcat [ text "Id:" <+> ppr poly_id
         --                         , text "spec_co:" <+> ppr spec_co
         --                         , text "ds_rhs:" <+> ppr ds_lhs ]) $
         DynFlags
dflags <- IOEnv (Env DsGblEnv DsLclEnv) DynFlags
forall (m :: * -> *). HasDynFlags m => m DynFlags
getDynFlags
       ; case DynFlags
-> [Id] -> CoreExpr -> Either DsMessage ([Id], Id, [CoreExpr])
decomposeRuleLhs DynFlags
dflags [Id]
spec_bndrs CoreExpr
ds_lhs of {
           Left DsMessage
msg -> do { DsMessage -> IOEnv (Env DsGblEnv DsLclEnv) ()
diagnosticDs DsMessage
msg; Maybe (OrdList (Id, CoreExpr), CoreRule)
-> IOEnv
     (Env DsGblEnv DsLclEnv) (Maybe (OrdList (Id, CoreExpr), CoreRule))
forall (m :: * -> *) a. Monad m => a -> m a
return Maybe (OrdList (Id, CoreExpr), CoreRule)
forall a. Maybe a
Nothing } ;
           Right ([Id]
rule_bndrs, Id
_fn, [CoreExpr]
rule_lhs_args) -> do

       { Module
this_mod <- IOEnv (Env DsGblEnv DsLclEnv) Module
forall (m :: * -> *). HasModule m => m Module
getModule
       ; let fn_unf :: Unfolding
fn_unf    = Id -> Unfolding
realIdUnfolding Id
poly_id
             simpl_opts :: SimpleOpts
simpl_opts = DynFlags -> SimpleOpts
initSimpleOpts DynFlags
dflags
             spec_unf :: Unfolding
spec_unf   = SimpleOpts
-> [Id]
-> (CoreExpr -> CoreExpr)
-> [CoreExpr]
-> Unfolding
-> Unfolding
specUnfolding SimpleOpts
simpl_opts [Id]
spec_bndrs CoreExpr -> CoreExpr
core_app [CoreExpr]
rule_lhs_args Unfolding
fn_unf
             spec_id :: Id
spec_id    = HasDebugCallStack => Name -> Type -> Type -> Id
Name -> Type -> Type -> Id
mkLocalId Name
spec_name Type
Many Type
spec_ty -- Specialised binding is toplevel, hence Many.
                            Id -> InlinePragma -> Id
`setInlinePragma` InlinePragma
inl_prag
                            Id -> Unfolding -> Id
`setIdUnfolding`  Unfolding
spec_unf

       ; CoreRule
rule <- Module
-> Bool
-> RuleName
-> Activation
-> Name
-> [Id]
-> [CoreExpr]
-> CoreExpr
-> DsM CoreRule
dsMkUserRule Module
this_mod Bool
is_local_id
                        (String -> RuleName
mkFastString (String
"SPEC " String -> String -> String
forall a. [a] -> [a] -> [a]
++ DynFlags -> Name -> String
forall a. Outputable a => DynFlags -> a -> String
showPpr DynFlags
dflags Name
poly_name))
                        Activation
rule_act Name
poly_name
                        [Id]
rule_bndrs [CoreExpr]
rule_lhs_args
                        (CoreExpr -> [Id] -> CoreExpr
forall b. Expr b -> [Id] -> Expr b
mkVarApps (Id -> CoreExpr
forall b. Id -> Expr b
Var Id
spec_id) [Id]
spec_bndrs)

       ; let spec_rhs :: CoreExpr
spec_rhs = [Id] -> CoreExpr -> CoreExpr
forall b. [b] -> Expr b -> Expr b
mkLams [Id]
spec_bndrs (CoreExpr -> CoreExpr
core_app CoreExpr
poly_rhs)

-- Commented out: see Note [SPECIALISE on INLINE functions]
--       ; when (isInlinePragma id_inl)
--              (diagnosticDs $ text "SPECIALISE pragma on INLINE function probably won't fire:"
--                        <+> quotes (ppr poly_name))

       ; Maybe (OrdList (Id, CoreExpr), CoreRule)
-> IOEnv
     (Env DsGblEnv DsLclEnv) (Maybe (OrdList (Id, CoreExpr), CoreRule))
forall (m :: * -> *) a. Monad m => a -> m a
return ((OrdList (Id, CoreExpr), CoreRule)
-> Maybe (OrdList (Id, CoreExpr), CoreRule)
forall a. a -> Maybe a
Just ((Id, CoreExpr) -> OrdList (Id, CoreExpr)
forall a. a -> OrdList a
unitOL (Id
spec_id, CoreExpr
spec_rhs), CoreRule
rule))
            -- NB: do *not* use makeCorePair on (spec_id,spec_rhs), because
            --     makeCorePair overwrites the unfolding, which we have
            --     just created using specUnfolding
       } } }
  where
    is_local_id :: Bool
is_local_id = Maybe CoreExpr -> Bool
forall a. Maybe a -> Bool
isJust Maybe CoreExpr
mb_poly_rhs
    poly_rhs :: CoreExpr
poly_rhs | Just CoreExpr
rhs <-  Maybe CoreExpr
mb_poly_rhs
             = CoreExpr
rhs          -- Local Id; this is its rhs
             | Just CoreExpr
unfolding <- Unfolding -> Maybe CoreExpr
maybeUnfoldingTemplate (Id -> Unfolding
realIdUnfolding Id
poly_id)
             = CoreExpr
unfolding    -- Imported Id; this is its unfolding
                            -- Use realIdUnfolding so we get the unfolding
                            -- even when it is a loop breaker.
                            -- We want to specialise recursive functions!
             | Bool
otherwise = String -> SDoc -> CoreExpr
forall a. HasCallStack => String -> SDoc -> a
pprPanic String
"dsImpSpecs" (Id -> SDoc
forall a. Outputable a => a -> SDoc
ppr Id
poly_id)
                            -- The type checker has checked that it *has* an unfolding

    id_inl :: InlinePragma
id_inl = Id -> InlinePragma
idInlinePragma Id
poly_id

    -- See Note [Activation pragmas for SPECIALISE]
    inl_prag :: InlinePragma
inl_prag | Bool -> Bool
not (InlinePragma -> Bool
isDefaultInlinePragma InlinePragma
spec_inl)    = InlinePragma
spec_inl
             | Bool -> Bool
not Bool
is_local_id  -- See Note [Specialising imported functions]
                                 -- in OccurAnal
             , OccInfo -> Bool
isStrongLoopBreaker (Id -> OccInfo
idOccInfo Id
poly_id) = InlinePragma
neverInlinePragma
             | Bool
otherwise                               = InlinePragma
id_inl
     -- Get the INLINE pragma from SPECIALISE declaration, or,
     -- failing that, from the original Id

    spec_prag_act :: Activation
spec_prag_act = InlinePragma -> Activation
inlinePragmaActivation InlinePragma
spec_inl

    -- See Note [Activation pragmas for SPECIALISE]
    -- no_act_spec is True if the user didn't write an explicit
    -- phase specification in the SPECIALISE pragma
    no_act_spec :: Bool
no_act_spec = case InlinePragma -> InlineSpec
inlinePragmaSpec InlinePragma
spec_inl of
                    NoInline SourceText
_   -> Activation -> Bool
isNeverActive  Activation
spec_prag_act
                    Opaque SourceText
_     -> Activation -> Bool
isNeverActive  Activation
spec_prag_act
                    InlineSpec
_            -> Activation -> Bool
isAlwaysActive Activation
spec_prag_act
    rule_act :: Activation
rule_act | Bool
no_act_spec = InlinePragma -> Activation
inlinePragmaActivation InlinePragma
id_inl   -- Inherit
             | Bool
otherwise   = Activation
spec_prag_act                   -- Specified by user


dsMkUserRule :: Module -> Bool -> RuleName -> Activation
       -> Name -> [CoreBndr] -> [CoreExpr] -> CoreExpr -> DsM CoreRule
dsMkUserRule :: Module
-> Bool
-> RuleName
-> Activation
-> Name
-> [Id]
-> [CoreExpr]
-> CoreExpr
-> DsM CoreRule
dsMkUserRule Module
this_mod Bool
is_local RuleName
name Activation
act Name
fn [Id]
bndrs [CoreExpr]
args CoreExpr
rhs = do
    let rule :: CoreRule
rule = Module
-> Bool
-> Bool
-> RuleName
-> Activation
-> Name
-> [Id]
-> [CoreExpr]
-> CoreExpr
-> CoreRule
mkRule Module
this_mod Bool
False Bool
is_local RuleName
name Activation
act Name
fn [Id]
bndrs [CoreExpr]
args CoreExpr
rhs
    Bool
-> IOEnv (Env DsGblEnv DsLclEnv) ()
-> IOEnv (Env DsGblEnv DsLclEnv) ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
when (IsOrphan -> Bool
isOrphan (CoreRule -> IsOrphan
ru_orphan CoreRule
rule)) (IOEnv (Env DsGblEnv DsLclEnv) ()
 -> IOEnv (Env DsGblEnv DsLclEnv) ())
-> IOEnv (Env DsGblEnv DsLclEnv) ()
-> IOEnv (Env DsGblEnv DsLclEnv) ()
forall a b. (a -> b) -> a -> b
$
        DsMessage -> IOEnv (Env DsGblEnv DsLclEnv) ()
diagnosticDs (CoreRule -> DsMessage
DsOrphanRule CoreRule
rule)
    CoreRule -> DsM CoreRule
forall (m :: * -> *) a. Monad m => a -> m a
return CoreRule
rule

{- Note [SPECIALISE on INLINE functions]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
We used to warn that using SPECIALISE for a function marked INLINE
would be a no-op; but it isn't!  Especially with worker/wrapper split
we might have
   {-# INLINE f #-}
   f :: Ord a => Int -> a -> ...
   f d x y = case x of I# x' -> $wf d x' y

We might want to specialise 'f' so that we in turn specialise '$wf'.
We can't even /name/ '$wf' in the source code, so we can't specialise
it even if we wanted to.  #10721 is a case in point.

Note [Activation pragmas for SPECIALISE]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
From a user SPECIALISE pragma for f, we generate
  a) A top-level binding    spec_fn = rhs
  b) A RULE                 f dOrd = spec_fn

We need two pragma-like things:

* spec_fn's inline pragma: inherited from f's inline pragma (ignoring
                           activation on SPEC), unless overridden by SPEC INLINE

* Activation of RULE: from SPECIALISE pragma (if activation given)
                      otherwise from f's inline pragma

This is not obvious (see #5237)!

Examples      Rule activation   Inline prag on spec'd fn
---------------------------------------------------------------------
SPEC [n] f :: ty            [n]   Always, or NOINLINE [n]
                                  copy f's prag

NOINLINE f
SPEC [n] f :: ty            [n]   NOINLINE
                                  copy f's prag

NOINLINE [k] f
SPEC [n] f :: ty            [n]   NOINLINE [k]
                                  copy f's prag

INLINE [k] f
SPEC [n] f :: ty            [n]   INLINE [k]
                                  copy f's prag

SPEC INLINE [n] f :: ty     [n]   INLINE [n]
                                  (ignore INLINE prag on f,
                                  same activation for rule and spec'd fn)

NOINLINE [k] f
SPEC f :: ty                [n]   INLINE [k]


************************************************************************
*                                                                      *
\subsection{Adding inline pragmas}
*                                                                      *
************************************************************************
-}

decomposeRuleLhs :: DynFlags -> [Var] -> CoreExpr
                 -> Either DsMessage ([Var], Id, [CoreExpr])
-- (decomposeRuleLhs bndrs lhs) takes apart the LHS of a RULE,
-- The 'bndrs' are the quantified binders of the rules, but decomposeRuleLhs
-- may add some extra dictionary binders (see Note [Free dictionaries])
--
-- Returns an error message if the LHS isn't of the expected shape
-- Note [Decomposing the left-hand side of a RULE]
decomposeRuleLhs :: DynFlags
-> [Id] -> CoreExpr -> Either DsMessage ([Id], Id, [CoreExpr])
decomposeRuleLhs DynFlags
dflags [Id]
orig_bndrs CoreExpr
orig_lhs
  | Bool -> Bool
not ([Id] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null [Id]
unbound)    -- Check for things unbound on LHS
                          -- See Note [Unused spec binders]
  = DsMessage -> Either DsMessage ([Id], Id, [CoreExpr])
forall a b. a -> Either a b
Left ([Id] -> [Id] -> CoreExpr -> CoreExpr -> DsMessage
DsRuleBindersNotBound [Id]
unbound [Id]
orig_bndrs CoreExpr
orig_lhs CoreExpr
lhs2)
  | Var Id
funId <- CoreExpr
fun2
  , Just DataCon
con <- Id -> Maybe DataCon
isDataConId_maybe Id
funId
  = DsMessage -> Either DsMessage ([Id], Id, [CoreExpr])
forall a b. a -> Either a b
Left (DataCon -> DsMessage
DsRuleIgnoredDueToConstructor DataCon
con) -- See Note [No RULES on datacons]
  | Just (Id
fn_id, [CoreExpr]
args) <- CoreExpr -> [CoreExpr] -> Maybe (Id, [CoreExpr])
decompose CoreExpr
fun2 [CoreExpr]
args2
  , let extra_bndrs :: [Id]
extra_bndrs = Id -> [CoreExpr] -> [Id]
mk_extra_bndrs Id
fn_id [CoreExpr]
args
  = -- pprTrace "decomposeRuleLhs" (vcat [ text "orig_bndrs:" <+> ppr orig_bndrs
    --                                  , text "orig_lhs:" <+> ppr orig_lhs
    --                                  , text "lhs1:"     <+> ppr lhs1
    --                                  , text "extra_bndrs:" <+> ppr extra_bndrs
    --                                  , text "fn_id:" <+> ppr fn_id
    --                                  , text "args:"   <+> ppr args]) $
    ([Id], Id, [CoreExpr]) -> Either DsMessage ([Id], Id, [CoreExpr])
forall a b. b -> Either a b
Right ([Id]
orig_bndrs [Id] -> [Id] -> [Id]
forall a. [a] -> [a] -> [a]
++ [Id]
extra_bndrs, Id
fn_id, [CoreExpr]
args)

  | Bool
otherwise
  = DsMessage -> Either DsMessage ([Id], Id, [CoreExpr])
forall a b. a -> Either a b
Left (CoreExpr -> CoreExpr -> DsMessage
DsRuleLhsTooComplicated CoreExpr
orig_lhs CoreExpr
lhs2)
 where
   simpl_opts :: SimpleOpts
simpl_opts   = DynFlags -> SimpleOpts
initSimpleOpts DynFlags
dflags
   lhs1 :: CoreExpr
lhs1         = CoreExpr -> CoreExpr
drop_dicts CoreExpr
orig_lhs
   lhs2 :: CoreExpr
lhs2         = HasDebugCallStack => SimpleOpts -> CoreExpr -> CoreExpr
SimpleOpts -> CoreExpr -> CoreExpr
simpleOptExpr SimpleOpts
simpl_opts CoreExpr
lhs1  -- See Note [Simplify rule LHS]
   (CoreExpr
fun2,[CoreExpr]
args2) = CoreExpr -> (CoreExpr, [CoreExpr])
forall b. Expr b -> (Expr b, [Expr b])
collectArgs CoreExpr
lhs2

   lhs_fvs :: VarSet
lhs_fvs    = CoreExpr -> VarSet
exprFreeVars CoreExpr
lhs2
   unbound :: [Id]
unbound    = (Id -> Bool) -> [Id] -> [Id]
forall a. (a -> Bool) -> [a] -> [a]
filterOut (Id -> VarSet -> Bool
`elemVarSet` VarSet
lhs_fvs) [Id]
orig_bndrs

   orig_bndr_set :: VarSet
orig_bndr_set = [Id] -> VarSet
mkVarSet [Id]
orig_bndrs

        -- Add extra tyvar binders: Note [Free tyvars in rule LHS]
        -- and extra dict binders: Note [Free dictionaries in rule LHS]
   mk_extra_bndrs :: Id -> [CoreExpr] -> [Id]
mk_extra_bndrs Id
fn_id [CoreExpr]
args
     = [Id] -> [Id]
scopedSort [Id]
unbound_tvs [Id] -> [Id] -> [Id]
forall a. [a] -> [a] -> [a]
++ [Id]
unbound_dicts
     where
       unbound_tvs :: [Id]
unbound_tvs   = [ Id
v | Id
v <- [Id]
unbound_vars, Id -> Bool
isTyVar Id
v ]
       unbound_dicts :: [Id]
unbound_dicts = [ HasDebugCallStack => Name -> Type -> Type -> Id
Name -> Type -> Type -> Id
mkLocalId (Name -> Name
localiseName (Id -> Name
idName Id
d)) Type
Many (Id -> Type
idType Id
d)
                       | Id
d <- [Id]
unbound_vars, Id -> Bool
isDictId Id
d ]
       unbound_vars :: [Id]
unbound_vars  = [ Id
v | Id
v <- [CoreExpr] -> [Id]
exprsFreeVarsList [CoreExpr]
args
                           , Bool -> Bool
not (Id
v Id -> VarSet -> Bool
`elemVarSet` VarSet
orig_bndr_set)
                           , Bool -> Bool
not (Id
v Id -> Id -> Bool
forall a. Eq a => a -> a -> Bool
== Id
fn_id) ]
         -- fn_id: do not quantify over the function itself, which may
         -- itself be a dictionary (in pathological cases, #10251)

   decompose :: CoreExpr -> [CoreExpr] -> Maybe (Id, [CoreExpr])
decompose (Var Id
fn_id) [CoreExpr]
args
      | Bool -> Bool
not (Id
fn_id Id -> VarSet -> Bool
`elemVarSet` VarSet
orig_bndr_set)
      = (Id, [CoreExpr]) -> Maybe (Id, [CoreExpr])
forall a. a -> Maybe a
Just (Id
fn_id, [CoreExpr]
args)

   decompose CoreExpr
_ [CoreExpr]
_ = Maybe (Id, [CoreExpr])
forall a. Maybe a
Nothing

   drop_dicts :: CoreExpr -> CoreExpr
   drop_dicts :: CoreExpr -> CoreExpr
drop_dicts CoreExpr
e
       = VarSet -> [(Id, CoreExpr)] -> CoreExpr -> CoreExpr
wrap_lets VarSet
needed [(Id, CoreExpr)]
bnds CoreExpr
body
     where
       needed :: VarSet
needed = VarSet
orig_bndr_set VarSet -> VarSet -> VarSet
`minusVarSet` CoreExpr -> VarSet
exprFreeVars CoreExpr
body
       ([(Id, CoreExpr)]
bnds, CoreExpr
body) = CoreExpr -> ([(Id, CoreExpr)], CoreExpr)
split_lets (CoreExpr -> CoreExpr
occurAnalyseExpr CoreExpr
e)
           -- The occurAnalyseExpr drops dead bindings which is
           -- crucial to ensure that every binding is used later;
           -- which in turn makes wrap_lets work right

   split_lets :: CoreExpr -> ([(DictId,CoreExpr)], CoreExpr)
   split_lets :: CoreExpr -> ([(Id, CoreExpr)], CoreExpr)
split_lets (Let (NonRec Id
d CoreExpr
r) CoreExpr
body)
     | Id -> Bool
isDictId Id
d
     = ((Id
d,CoreExpr
r)(Id, CoreExpr) -> [(Id, CoreExpr)] -> [(Id, CoreExpr)]
forall a. a -> [a] -> [a]
:[(Id, CoreExpr)]
bs, CoreExpr
body')
     where ([(Id, CoreExpr)]
bs, CoreExpr
body') = CoreExpr -> ([(Id, CoreExpr)], CoreExpr)
split_lets CoreExpr
body

    -- handle "unlifted lets" too, needed for "map/coerce"
   split_lets (Case CoreExpr
r Id
d Type
_ [Alt AltCon
DEFAULT [Id]
_ CoreExpr
body])
     | Id -> Bool
isCoVar Id
d
     = ((Id
d,CoreExpr
r)(Id, CoreExpr) -> [(Id, CoreExpr)] -> [(Id, CoreExpr)]
forall a. a -> [a] -> [a]
:[(Id, CoreExpr)]
bs, CoreExpr
body')
     where ([(Id, CoreExpr)]
bs, CoreExpr
body') = CoreExpr -> ([(Id, CoreExpr)], CoreExpr)
split_lets CoreExpr
body

   split_lets CoreExpr
e = ([], CoreExpr
e)

   wrap_lets :: VarSet -> [(DictId,CoreExpr)] -> CoreExpr -> CoreExpr
   wrap_lets :: VarSet -> [(Id, CoreExpr)] -> CoreExpr -> CoreExpr
wrap_lets VarSet
_ [] CoreExpr
body = CoreExpr
body
   wrap_lets VarSet
needed ((Id
d, CoreExpr
r) : [(Id, CoreExpr)]
bs) CoreExpr
body
     | VarSet
rhs_fvs VarSet -> VarSet -> Bool
`intersectsVarSet` VarSet
needed = CoreBind -> CoreExpr -> CoreExpr
mkCoreLet (Id -> CoreExpr -> CoreBind
forall b. b -> Expr b -> Bind b
NonRec Id
d CoreExpr
r) (VarSet -> [(Id, CoreExpr)] -> CoreExpr -> CoreExpr
wrap_lets VarSet
needed' [(Id, CoreExpr)]
bs CoreExpr
body)
     | Bool
otherwise                         = VarSet -> [(Id, CoreExpr)] -> CoreExpr -> CoreExpr
wrap_lets VarSet
needed [(Id, CoreExpr)]
bs CoreExpr
body
     where
       rhs_fvs :: VarSet
rhs_fvs = CoreExpr -> VarSet
exprFreeVars CoreExpr
r
       needed' :: VarSet
needed' = (VarSet
needed VarSet -> VarSet -> VarSet
`minusVarSet` VarSet
rhs_fvs) VarSet -> Id -> VarSet
`extendVarSet` Id
d

{-
Note [Decomposing the left-hand side of a RULE]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
There are several things going on here.
* drop_dicts: see Note [Drop dictionary bindings on rule LHS]
* simpleOptExpr: see Note [Simplify rule LHS]
* extra_dict_bndrs: see Note [Free dictionaries]

Note [Free tyvars on rule LHS]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider
  data T a = C

  foo :: T a -> Int
  foo C = 1

  {-# RULES "myrule"  foo C = 1 #-}

After type checking the LHS becomes (foo alpha (C alpha)), where alpha
is an unbound meta-tyvar.  The zonker in GHC.Tc.Utils.Zonk is careful not to
turn the free alpha into Any (as it usually does).  Instead it turns it
into a TyVar 'a'.  See Note [Zonking the LHS of a RULE] in "GHC.Tc.Utils.Zonk".

Now we must quantify over that 'a'.  It's /really/ inconvenient to do that
in the zonker, because the HsExpr data type is very large.  But it's /easy/
to do it here in the desugarer.

Moreover, we have to do something rather similar for dictionaries;
see Note [Free dictionaries on rule LHS].   So that's why we look for
type variables free on the LHS, and quantify over them.

Note [Free dictionaries on rule LHS]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
When the LHS of a specialisation rule, (/\as\ds. f es) has a free dict,
which is presumably in scope at the function definition site, we can quantify
over it too.  *Any* dict with that type will do.

So for example when you have
        f :: Eq a => a -> a
        f = <rhs>
        ... SPECIALISE f :: Int -> Int ...

Then we get the SpecPrag
        SpecPrag (f Int dInt)

And from that we want the rule

        RULE forall dInt. f Int dInt = f_spec
        f_spec = let f = <rhs> in f Int dInt

But be careful!  That dInt might be GHC.Base.$fOrdInt, which is an External
Name, and you can't bind them in a lambda or forall without getting things
confused.   Likewise it might have an InlineRule or something, which would be
utterly bogus. So we really make a fresh Id, with the same unique and type
as the old one, but with an Internal name and no IdInfo.

Note [Drop dictionary bindings on rule LHS]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
drop_dicts drops dictionary bindings on the LHS where possible.
   E.g.  let d:Eq [Int] = $fEqList $fEqInt in f d
     --> f d
   Reasoning here is that there is only one d:Eq [Int], and so we can
   quantify over it. That makes 'd' free in the LHS, but that is later
   picked up by extra_dict_bndrs (Note [Dead spec binders]).

   NB 1: We can only drop the binding if the RHS doesn't bind
         one of the orig_bndrs, which we assume occur on RHS.
         Example
            f :: (Eq a) => b -> a -> a
            {-# SPECIALISE f :: Eq a => b -> [a] -> [a] #-}
         Here we want to end up with
            RULE forall d:Eq a.  f ($dfEqList d) = f_spec d
         Of course, the ($dfEqlist d) in the pattern makes it less likely
         to match, but there is no other way to get d:Eq a

   NB 2: We do drop_dicts *before* simplOptEpxr, so that we expect all
         the evidence bindings to be wrapped around the outside of the
         LHS.  (After simplOptExpr they'll usually have been inlined.)
         dsHsWrapper does dependency analysis, so that civilised ones
         will be simple NonRec bindings.  We don't handle recursive
         dictionaries!

    NB3: In the common case of a non-overloaded, but perhaps-polymorphic
         specialisation, we don't need to bind *any* dictionaries for use
         in the RHS. For example (#8331)
             {-# SPECIALIZE INLINE useAbstractMonad :: ReaderST s Int #-}
             useAbstractMonad :: MonadAbstractIOST m => m Int
         Here, deriving (MonadAbstractIOST (ReaderST s)) is a lot of code
         but the RHS uses no dictionaries, so we want to end up with
             RULE forall s (d :: MonadAbstractIOST (ReaderT s)).
                useAbstractMonad (ReaderT s) d = $suseAbstractMonad s

   #8848 is a good example of where there are some interesting
   dictionary bindings to discard.

The drop_dicts algorithm is based on these observations:

  * Given (let d = rhs in e) where d is a DictId,
    matching 'e' will bind e's free variables.

  * So we want to keep the binding if one of the needed variables (for
    which we need a binding) is in fv(rhs) but not already in fv(e).

  * The "needed variables" are simply the orig_bndrs.  Consider
       f :: (Eq a, Show b) => a -> b -> String
       ... SPECIALISE f :: (Show b) => Int -> b -> String ...
    Then orig_bndrs includes the *quantified* dictionaries of the type
    namely (dsb::Show b), but not the one for Eq Int

So we work inside out, applying the above criterion at each step.


Note [Simplify rule LHS]
~~~~~~~~~~~~~~~~~~~~~~~~
simplOptExpr occurrence-analyses and simplifies the LHS:

   (a) Inline any remaining dictionary bindings (which hopefully
       occur just once)

   (b) Substitute trivial lets, so that they don't get in the way.
       Note that we substitute the function too; we might
       have this as a LHS:  let f71 = M.f Int in f71

   (c) Do eta reduction.  To see why, consider the fold/build rule,
       which without simplification looked like:
          fold k z (build (/\a. g a))  ==>  ...
       This doesn't match unless you do eta reduction on the build argument.
       Similarly for a LHS like
         augment g (build h)
       we do not want to get
         augment (\a. g a) (build h)
       otherwise we don't match when given an argument like
          augment (\a. h a a) (build h)

Note [Unused spec binders]
~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider
        f :: a -> a
        ... SPECIALISE f :: Eq a => a -> a ...
It's true that this *is* a more specialised type, but the rule
we get is something like this:
        f_spec d = f
        RULE: f = f_spec d
Note that the rule is bogus, because it mentions a 'd' that is
not bound on the LHS!  But it's a silly specialisation anyway, because
the constraint is unused.  We could bind 'd' to (error "unused")
but it seems better to reject the program because it's almost certainly
a mistake.  That's what the isDeadBinder call detects.

Note [No RULES on datacons]
~~~~~~~~~~~~~~~~~~~~~~~~~~~

Previously, `RULES` like

    "JustNothing" forall x . Just x = Nothing

were allowed. Simon Peyton Jones says this seems to have been a
mistake, that such rules have never been supported intentionally,
and that he doesn't know if they can break in horrible ways.
Furthermore, Ben Gamari and Reid Barton are considering trying to
detect the presence of "static data" that the simplifier doesn't
need to traverse at all. Such rules do not play well with that.
So for now, we ban them altogether as requested by #13290. See also #7398.


************************************************************************
*                                                                      *
                Desugaring evidence
*                                                                      *
************************************************************************

-}

dsHsWrapper :: HsWrapper -> DsM (CoreExpr -> CoreExpr)
dsHsWrapper :: HsWrapper -> DsM (CoreExpr -> CoreExpr)
dsHsWrapper HsWrapper
WpHole            = (CoreExpr -> CoreExpr) -> DsM (CoreExpr -> CoreExpr)
forall (m :: * -> *) a. Monad m => a -> m a
return ((CoreExpr -> CoreExpr) -> DsM (CoreExpr -> CoreExpr))
-> (CoreExpr -> CoreExpr) -> DsM (CoreExpr -> CoreExpr)
forall a b. (a -> b) -> a -> b
$ \CoreExpr
e -> CoreExpr
e
dsHsWrapper (WpTyApp Type
ty)      = (CoreExpr -> CoreExpr) -> DsM (CoreExpr -> CoreExpr)
forall (m :: * -> *) a. Monad m => a -> m a
return ((CoreExpr -> CoreExpr) -> DsM (CoreExpr -> CoreExpr))
-> (CoreExpr -> CoreExpr) -> DsM (CoreExpr -> CoreExpr)
forall a b. (a -> b) -> a -> b
$ \CoreExpr
e -> CoreExpr -> CoreExpr -> CoreExpr
forall b. Expr b -> Expr b -> Expr b
App CoreExpr
e (Type -> CoreExpr
forall b. Type -> Expr b
Type Type
ty)
dsHsWrapper (WpEvLam Id
ev)      = (CoreExpr -> CoreExpr) -> DsM (CoreExpr -> CoreExpr)
forall (m :: * -> *) a. Monad m => a -> m a
return ((CoreExpr -> CoreExpr) -> DsM (CoreExpr -> CoreExpr))
-> (CoreExpr -> CoreExpr) -> DsM (CoreExpr -> CoreExpr)
forall a b. (a -> b) -> a -> b
$ Id -> CoreExpr -> CoreExpr
forall b. b -> Expr b -> Expr b
Lam Id
ev
dsHsWrapper (WpTyLam Id
tv)      = (CoreExpr -> CoreExpr) -> DsM (CoreExpr -> CoreExpr)
forall (m :: * -> *) a. Monad m => a -> m a
return ((CoreExpr -> CoreExpr) -> DsM (CoreExpr -> CoreExpr))
-> (CoreExpr -> CoreExpr) -> DsM (CoreExpr -> CoreExpr)
forall a b. (a -> b) -> a -> b
$ Id -> CoreExpr -> CoreExpr
forall b. b -> Expr b -> Expr b
Lam Id
tv
dsHsWrapper (WpLet TcEvBinds
ev_binds)  = do { [CoreBind]
bs <- TcEvBinds -> DsM [CoreBind]
dsTcEvBinds TcEvBinds
ev_binds
                                   ; (CoreExpr -> CoreExpr) -> DsM (CoreExpr -> CoreExpr)
forall (m :: * -> *) a. Monad m => a -> m a
return ([CoreBind] -> CoreExpr -> CoreExpr
mkCoreLets [CoreBind]
bs) }
dsHsWrapper (WpCompose HsWrapper
c1 HsWrapper
c2) = do { CoreExpr -> CoreExpr
w1 <- HsWrapper -> DsM (CoreExpr -> CoreExpr)
dsHsWrapper HsWrapper
c1
                                   ; CoreExpr -> CoreExpr
w2 <- HsWrapper -> DsM (CoreExpr -> CoreExpr)
dsHsWrapper HsWrapper
c2
                                   ; (CoreExpr -> CoreExpr) -> DsM (CoreExpr -> CoreExpr)
forall (m :: * -> *) a. Monad m => a -> m a
return (CoreExpr -> CoreExpr
w1 (CoreExpr -> CoreExpr)
-> (CoreExpr -> CoreExpr) -> CoreExpr -> CoreExpr
forall b c a. (b -> c) -> (a -> b) -> a -> c
. CoreExpr -> CoreExpr
w2) }
 -- See comments on WpFun in GHC.Tc.Types.Evidence for an explanation of what
 -- the specification of this clause is
dsHsWrapper (WpFun HsWrapper
c1 HsWrapper
c2 (Scaled Type
w Type
t1))
                              = do { Id
x <- Type -> Type -> DsM Id
newSysLocalDs Type
w Type
t1
                                   ; CoreExpr -> CoreExpr
w1 <- HsWrapper -> DsM (CoreExpr -> CoreExpr)
dsHsWrapper HsWrapper
c1
                                   ; CoreExpr -> CoreExpr
w2 <- HsWrapper -> DsM (CoreExpr -> CoreExpr)
dsHsWrapper HsWrapper
c2
                                   ; let app :: CoreExpr -> CoreExpr -> CoreExpr
app CoreExpr
f CoreExpr
a = SDoc -> CoreExpr -> CoreExpr -> CoreExpr
mkCoreAppDs (String -> SDoc
text String
"dsHsWrapper") CoreExpr
f CoreExpr
a
                                         arg :: CoreExpr
arg     = CoreExpr -> CoreExpr
w1 (Id -> CoreExpr
forall b. Id -> Expr b
Var Id
x)
                                   ; (CoreExpr -> CoreExpr) -> DsM (CoreExpr -> CoreExpr)
forall (m :: * -> *) a. Monad m => a -> m a
return (\CoreExpr
e -> (Id -> CoreExpr -> CoreExpr
forall b. b -> Expr b -> Expr b
Lam Id
x (CoreExpr -> CoreExpr
w2 (CoreExpr -> CoreExpr -> CoreExpr
app CoreExpr
e CoreExpr
arg)))) }
dsHsWrapper (WpCast TcCoercionR
co)       = Bool -> DsM (CoreExpr -> CoreExpr) -> DsM (CoreExpr -> CoreExpr)
forall a. HasCallStack => Bool -> a -> a
assert (TcCoercionR -> Role
coercionRole TcCoercionR
co Role -> Role -> Bool
forall a. Eq a => a -> a -> Bool
== Role
Representational) (DsM (CoreExpr -> CoreExpr) -> DsM (CoreExpr -> CoreExpr))
-> DsM (CoreExpr -> CoreExpr) -> DsM (CoreExpr -> CoreExpr)
forall a b. (a -> b) -> a -> b
$
                                (CoreExpr -> CoreExpr) -> DsM (CoreExpr -> CoreExpr)
forall (m :: * -> *) a. Monad m => a -> m a
return ((CoreExpr -> CoreExpr) -> DsM (CoreExpr -> CoreExpr))
-> (CoreExpr -> CoreExpr) -> DsM (CoreExpr -> CoreExpr)
forall a b. (a -> b) -> a -> b
$ \CoreExpr
e -> CoreExpr -> TcCoercionR -> CoreExpr
mkCastDs CoreExpr
e TcCoercionR
co
dsHsWrapper (WpEvApp EvTerm
tm)      = do { CoreExpr
core_tm <- EvTerm -> DsM CoreExpr
dsEvTerm EvTerm
tm
                                   ; (CoreExpr -> CoreExpr) -> DsM (CoreExpr -> CoreExpr)
forall (m :: * -> *) a. Monad m => a -> m a
return (\CoreExpr
e -> CoreExpr -> CoreExpr -> CoreExpr
forall b. Expr b -> Expr b -> Expr b
App CoreExpr
e CoreExpr
core_tm) }
  -- See Note [Wrapper returned from tcSubMult] in GHC.Tc.Utils.Unify.
dsHsWrapper (WpMultCoercion TcCoercionR
co) = do { Bool
-> IOEnv (Env DsGblEnv DsLclEnv) ()
-> IOEnv (Env DsGblEnv DsLclEnv) ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
when (Bool -> Bool
not (TcCoercionR -> Bool
isReflexiveCo TcCoercionR
co)) (IOEnv (Env DsGblEnv DsLclEnv) ()
 -> IOEnv (Env DsGblEnv DsLclEnv) ())
-> IOEnv (Env DsGblEnv DsLclEnv) ()
-> IOEnv (Env DsGblEnv DsLclEnv) ()
forall a b. (a -> b) -> a -> b
$
                                         DsMessage -> IOEnv (Env DsGblEnv DsLclEnv) ()
diagnosticDs DsMessage
DsMultiplicityCoercionsNotSupported
                                     ; (CoreExpr -> CoreExpr) -> DsM (CoreExpr -> CoreExpr)
forall (m :: * -> *) a. Monad m => a -> m a
return ((CoreExpr -> CoreExpr) -> DsM (CoreExpr -> CoreExpr))
-> (CoreExpr -> CoreExpr) -> DsM (CoreExpr -> CoreExpr)
forall a b. (a -> b) -> a -> b
$ \CoreExpr
e -> CoreExpr
e }
--------------------------------------
dsTcEvBinds_s :: [TcEvBinds] -> DsM [CoreBind]
dsTcEvBinds_s :: [TcEvBinds] -> DsM [CoreBind]
dsTcEvBinds_s []       = [CoreBind] -> DsM [CoreBind]
forall (m :: * -> *) a. Monad m => a -> m a
return []
dsTcEvBinds_s (TcEvBinds
b:[TcEvBinds]
rest) = Bool -> DsM [CoreBind] -> DsM [CoreBind]
forall a. HasCallStack => Bool -> a -> a
assert ([TcEvBinds] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null [TcEvBinds]
rest) (DsM [CoreBind] -> DsM [CoreBind])
-> DsM [CoreBind] -> DsM [CoreBind]
forall a b. (a -> b) -> a -> b
$  -- Zonker ensures null
                         TcEvBinds -> DsM [CoreBind]
dsTcEvBinds TcEvBinds
b

dsTcEvBinds :: TcEvBinds -> DsM [CoreBind]
dsTcEvBinds :: TcEvBinds -> DsM [CoreBind]
dsTcEvBinds (TcEvBinds {}) = String -> DsM [CoreBind]
forall a. String -> a
panic String
"dsEvBinds"    -- Zonker has got rid of this
dsTcEvBinds (EvBinds Bag EvBind
bs)   = Bag EvBind -> DsM [CoreBind]
dsEvBinds Bag EvBind
bs

dsEvBinds :: Bag EvBind -> DsM [CoreBind]
dsEvBinds :: Bag EvBind -> DsM [CoreBind]
dsEvBinds Bag EvBind
bs
  = do { Bag (Id, CoreExpr)
ds_bs <- (EvBind -> DsM (Id, CoreExpr))
-> Bag EvBind -> IOEnv (Env DsGblEnv DsLclEnv) (Bag (Id, CoreExpr))
forall (m :: * -> *) a b.
Monad m =>
(a -> m b) -> Bag a -> m (Bag b)
mapBagM EvBind -> DsM (Id, CoreExpr)
dsEvBind Bag EvBind
bs
       ; [CoreBind] -> DsM [CoreBind]
forall (m :: * -> *) a. Monad m => a -> m a
return (Bag (Id, CoreExpr) -> [CoreBind]
mk_ev_binds Bag (Id, CoreExpr)
ds_bs) }

mk_ev_binds :: Bag (Id,CoreExpr) -> [CoreBind]
-- We do SCC analysis of the evidence bindings, /after/ desugaring
-- them. This is convenient: it means we can use the GHC.Core
-- free-variable functions rather than having to do accurate free vars
-- for EvTerm.
mk_ev_binds :: Bag (Id, CoreExpr) -> [CoreBind]
mk_ev_binds Bag (Id, CoreExpr)
ds_binds
  = (SCC (Id, CoreExpr) -> CoreBind)
-> [SCC (Id, CoreExpr)] -> [CoreBind]
forall a b. (a -> b) -> [a] -> [b]
map SCC (Id, CoreExpr) -> CoreBind
forall b. SCC (b, Expr b) -> Bind b
ds_scc ([Node Id (Id, CoreExpr)] -> [SCC (Id, CoreExpr)]
forall key payload.
Uniquable key =>
[Node key payload] -> [SCC payload]
stronglyConnCompFromEdgedVerticesUniq [Node Id (Id, CoreExpr)]
edges)
  where
    edges :: [ Node EvVar (EvVar,CoreExpr) ]
    edges :: [Node Id (Id, CoreExpr)]
edges = ((Id, CoreExpr)
 -> [Node Id (Id, CoreExpr)] -> [Node Id (Id, CoreExpr)])
-> [Node Id (Id, CoreExpr)]
-> Bag (Id, CoreExpr)
-> [Node Id (Id, CoreExpr)]
forall (t :: * -> *) a b.
Foldable t =>
(a -> b -> b) -> b -> t a -> b
foldr ((:) (Node Id (Id, CoreExpr)
 -> [Node Id (Id, CoreExpr)] -> [Node Id (Id, CoreExpr)])
-> ((Id, CoreExpr) -> Node Id (Id, CoreExpr))
-> (Id, CoreExpr)
-> [Node Id (Id, CoreExpr)]
-> [Node Id (Id, CoreExpr)]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (Id, CoreExpr) -> Node Id (Id, CoreExpr)
mk_node) [] Bag (Id, CoreExpr)
ds_binds

    mk_node :: (Id, CoreExpr) -> Node EvVar (EvVar,CoreExpr)
    mk_node :: (Id, CoreExpr) -> Node Id (Id, CoreExpr)
mk_node b :: (Id, CoreExpr)
b@(Id
var, CoreExpr
rhs)
      = DigraphNode :: forall key payload. payload -> key -> [key] -> Node key payload
DigraphNode { node_payload :: (Id, CoreExpr)
node_payload = (Id, CoreExpr)
b
                    , node_key :: Id
node_key = Id
var
                    , node_dependencies :: [Id]
node_dependencies = VarSet -> [Id]
forall elt. UniqSet elt -> [elt]
nonDetEltsUniqSet (VarSet -> [Id]) -> VarSet -> [Id]
forall a b. (a -> b) -> a -> b
$
                                          CoreExpr -> VarSet
exprFreeVars CoreExpr
rhs VarSet -> VarSet -> VarSet
`unionVarSet`
                                          Type -> VarSet
coVarsOfType (Id -> Type
varType Id
var) }
      -- It's OK to use nonDetEltsUniqSet here as stronglyConnCompFromEdgedVertices
      -- is still deterministic even if the edges are in nondeterministic order
      -- as explained in Note [Deterministic SCC] in GHC.Data.Graph.Directed.

    ds_scc :: SCC (b, Expr b) -> Bind b
ds_scc (AcyclicSCC (b
v,Expr b
r)) = b -> Expr b -> Bind b
forall b. b -> Expr b -> Bind b
NonRec b
v Expr b
r
    ds_scc (CyclicSCC [(b, Expr b)]
prs)    = [(b, Expr b)] -> Bind b
forall b. [(b, Expr b)] -> Bind b
Rec [(b, Expr b)]
prs

dsEvBind :: EvBind -> DsM (Id, CoreExpr)
dsEvBind :: EvBind -> DsM (Id, CoreExpr)
dsEvBind (EvBind { eb_lhs :: EvBind -> Id
eb_lhs = Id
v, eb_rhs :: EvBind -> EvTerm
eb_rhs = EvTerm
r}) = (CoreExpr -> (Id, CoreExpr)) -> DsM CoreExpr -> DsM (Id, CoreExpr)
forall (m :: * -> *) a1 r. Monad m => (a1 -> r) -> m a1 -> m r
liftM ((,) Id
v) (EvTerm -> DsM CoreExpr
dsEvTerm EvTerm
r)


{-**********************************************************************
*                                                                      *
           Desugaring EvTerms
*                                                                      *
**********************************************************************-}

dsEvTerm :: EvTerm -> DsM CoreExpr
dsEvTerm :: EvTerm -> DsM CoreExpr
dsEvTerm (EvExpr CoreExpr
e)          = CoreExpr -> DsM CoreExpr
forall (m :: * -> *) a. Monad m => a -> m a
return CoreExpr
e
dsEvTerm (EvTypeable Type
ty EvTypeable
ev)  = Type -> EvTypeable -> DsM CoreExpr
dsEvTypeable Type
ty EvTypeable
ev
dsEvTerm (EvFun { et_tvs :: EvTerm -> [Id]
et_tvs = [Id]
tvs, et_given :: EvTerm -> [Id]
et_given = [Id]
given
                , et_binds :: EvTerm -> TcEvBinds
et_binds = TcEvBinds
ev_binds, et_body :: EvTerm -> Id
et_body = Id
wanted_id })
  = do { [CoreBind]
ds_ev_binds <- TcEvBinds -> DsM [CoreBind]
dsTcEvBinds TcEvBinds
ev_binds
       ; CoreExpr -> DsM CoreExpr
forall (m :: * -> *) a. Monad m => a -> m a
return (CoreExpr -> DsM CoreExpr) -> CoreExpr -> DsM CoreExpr
forall a b. (a -> b) -> a -> b
$ ([Id] -> CoreExpr -> CoreExpr
forall b. [b] -> Expr b -> Expr b
mkLams ([Id]
tvs [Id] -> [Id] -> [Id]
forall a. [a] -> [a] -> [a]
++ [Id]
given) (CoreExpr -> CoreExpr) -> CoreExpr -> CoreExpr
forall a b. (a -> b) -> a -> b
$
                   [CoreBind] -> CoreExpr -> CoreExpr
mkCoreLets [CoreBind]
ds_ev_binds (CoreExpr -> CoreExpr) -> CoreExpr -> CoreExpr
forall a b. (a -> b) -> a -> b
$
                   Id -> CoreExpr
forall b. Id -> Expr b
Var Id
wanted_id) }


{-**********************************************************************
*                                                                      *
           Desugaring Typeable dictionaries
*                                                                      *
**********************************************************************-}

dsEvTypeable :: Type -> EvTypeable -> DsM CoreExpr
-- Return a CoreExpr :: Typeable ty
-- This code is tightly coupled to the representation
-- of TypeRep, in base library Data.Typeable.Internal
dsEvTypeable :: Type -> EvTypeable -> DsM CoreExpr
dsEvTypeable Type
ty EvTypeable
ev
  = do { TyCon
tyCl <- Name -> DsM TyCon
dsLookupTyCon Name
typeableClassName    -- Typeable
       ; let kind :: Type
kind = HasDebugCallStack => Type -> Type
Type -> Type
typeKind Type
ty
             Just DataCon
typeable_data_con
                 = TyCon -> Maybe DataCon
tyConSingleDataCon_maybe TyCon
tyCl    -- "Data constructor"
                                                    -- for Typeable

       ; CoreExpr
rep_expr <- Type -> EvTypeable -> DsM CoreExpr
ds_ev_typeable Type
ty EvTypeable
ev           -- :: TypeRep a

       -- Package up the method as `Typeable` dictionary
       ; CoreExpr -> DsM CoreExpr
forall (m :: * -> *) a. Monad m => a -> m a
return (CoreExpr -> DsM CoreExpr) -> CoreExpr -> DsM CoreExpr
forall a b. (a -> b) -> a -> b
$ DataCon -> [CoreExpr] -> CoreExpr
forall b. DataCon -> [Arg b] -> Arg b
mkConApp DataCon
typeable_data_con [Type -> CoreExpr
forall b. Type -> Expr b
Type Type
kind, Type -> CoreExpr
forall b. Type -> Expr b
Type Type
ty, CoreExpr
rep_expr] }

type TypeRepExpr = CoreExpr

-- | Returns a @CoreExpr :: TypeRep ty@
ds_ev_typeable :: Type -> EvTypeable -> DsM CoreExpr
ds_ev_typeable :: Type -> EvTypeable -> DsM CoreExpr
ds_ev_typeable Type
ty (EvTypeableTyCon TyCon
tc [EvTerm]
kind_ev)
  = do { Id
mkTrCon <- Name -> DsM Id
dsLookupGlobalId Name
mkTrConName
                    -- mkTrCon :: forall k (a :: k). TyCon -> TypeRep k -> TypeRep a
       ; TyCon
someTypeRepTyCon <- Name -> DsM TyCon
dsLookupTyCon Name
someTypeRepTyConName
       ; DataCon
someTypeRepDataCon <- Name -> DsM DataCon
dsLookupDataCon Name
someTypeRepDataConName
                    -- SomeTypeRep :: forall k (a :: k). TypeRep a -> SomeTypeRep

       ; CoreExpr
tc_rep <- TyCon -> DsM CoreExpr
tyConRep TyCon
tc                      -- :: TyCon
       ; let ks :: [Type]
ks = Type -> [Type]
tyConAppArgs Type
ty
             -- Construct a SomeTypeRep
             toSomeTypeRep :: Type -> EvTerm -> DsM CoreExpr
             toSomeTypeRep :: Type -> EvTerm -> DsM CoreExpr
toSomeTypeRep Type
t EvTerm
ev = do
                 CoreExpr
rep <- EvTerm -> Type -> DsM CoreExpr
getRep EvTerm
ev Type
t
                 CoreExpr -> DsM CoreExpr
forall (m :: * -> *) a. Monad m => a -> m a
return (CoreExpr -> DsM CoreExpr) -> CoreExpr -> DsM CoreExpr
forall a b. (a -> b) -> a -> b
$ DataCon -> [CoreExpr] -> CoreExpr
mkCoreConApps DataCon
someTypeRepDataCon [Type -> CoreExpr
forall b. Type -> Expr b
Type (HasDebugCallStack => Type -> Type
Type -> Type
typeKind Type
t), Type -> CoreExpr
forall b. Type -> Expr b
Type Type
t, CoreExpr
rep]
       ; [CoreExpr]
kind_arg_reps <- [DsM CoreExpr] -> IOEnv (Env DsGblEnv DsLclEnv) [CoreExpr]
forall (t :: * -> *) (m :: * -> *) a.
(Traversable t, Monad m) =>
t (m a) -> m (t a)
sequence ([DsM CoreExpr] -> IOEnv (Env DsGblEnv DsLclEnv) [CoreExpr])
-> [DsM CoreExpr] -> IOEnv (Env DsGblEnv DsLclEnv) [CoreExpr]
forall a b. (a -> b) -> a -> b
$ (Type -> EvTerm -> DsM CoreExpr)
-> [Type] -> [EvTerm] -> [DsM CoreExpr]
forall a b c. (a -> b -> c) -> [a] -> [b] -> [c]
zipWith Type -> EvTerm -> DsM CoreExpr
toSomeTypeRep [Type]
ks [EvTerm]
kind_ev   -- :: TypeRep t
       ; let -- :: [SomeTypeRep]
             kind_args :: CoreExpr
kind_args = Type -> [CoreExpr] -> CoreExpr
mkListExpr (TyCon -> Type
mkTyConTy TyCon
someTypeRepTyCon) [CoreExpr]
kind_arg_reps

         -- Note that we use the kind of the type, not the TyCon from which it
         -- is constructed since the latter may be kind polymorphic whereas the
         -- former we know is not (we checked in the solver).
       ; let expr :: CoreExpr
expr = CoreExpr -> [CoreExpr] -> CoreExpr
forall b. Expr b -> [Expr b] -> Expr b
mkApps (Id -> CoreExpr
forall b. Id -> Expr b
Var Id
mkTrCon) [ Type -> CoreExpr
forall b. Type -> Expr b
Type (HasDebugCallStack => Type -> Type
Type -> Type
typeKind Type
ty)
                                         , Type -> CoreExpr
forall b. Type -> Expr b
Type Type
ty
                                         , CoreExpr
tc_rep
                                         , CoreExpr
kind_args ]
       -- ; pprRuntimeTrace "Trace mkTrTyCon" (ppr expr) expr
       ; CoreExpr -> DsM CoreExpr
forall (m :: * -> *) a. Monad m => a -> m a
return CoreExpr
expr
       }

ds_ev_typeable Type
ty (EvTypeableTyApp EvTerm
ev1 EvTerm
ev2)
  | Just (Type
t1,Type
t2) <- Type -> Maybe (Type, Type)
splitAppTy_maybe Type
ty
  = do { CoreExpr
e1  <- EvTerm -> Type -> DsM CoreExpr
getRep EvTerm
ev1 Type
t1
       ; CoreExpr
e2  <- EvTerm -> Type -> DsM CoreExpr
getRep EvTerm
ev2 Type
t2
       ; Id
mkTrApp <- Name -> DsM Id
dsLookupGlobalId Name
mkTrAppName
                    -- mkTrApp :: forall k1 k2 (a :: k1 -> k2) (b :: k1).
                    --            TypeRep a -> TypeRep b -> TypeRep (a b)
       ; let (Type
_, Type
k1, Type
k2) = Type -> (Type, Type, Type)
splitFunTy (HasDebugCallStack => Type -> Type
Type -> Type
typeKind Type
t1)  -- drop the multiplicity,
                                                     -- since it's a kind
       ; let expr :: CoreExpr
expr =  CoreExpr -> [CoreExpr] -> CoreExpr
forall b. Expr b -> [Expr b] -> Expr b
mkApps (CoreExpr -> [Type] -> CoreExpr
forall b. Expr b -> [Type] -> Expr b
mkTyApps (Id -> CoreExpr
forall b. Id -> Expr b
Var Id
mkTrApp) [ Type
k1, Type
k2, Type
t1, Type
t2 ])
                            [ CoreExpr
e1, CoreExpr
e2 ]
       -- ; pprRuntimeTrace "Trace mkTrApp" (ppr expr) expr
       ; CoreExpr -> DsM CoreExpr
forall (m :: * -> *) a. Monad m => a -> m a
return CoreExpr
expr
       }

ds_ev_typeable Type
ty (EvTypeableTrFun EvTerm
evm EvTerm
ev1 EvTerm
ev2)
  | Just (Type
m,Type
t1,Type
t2) <- Type -> Maybe (Type, Type, Type)
splitFunTy_maybe Type
ty
  = do { CoreExpr
e1 <- EvTerm -> Type -> DsM CoreExpr
getRep EvTerm
ev1 Type
t1
       ; CoreExpr
e2 <- EvTerm -> Type -> DsM CoreExpr
getRep EvTerm
ev2 Type
t2
       ; CoreExpr
em <- EvTerm -> Type -> DsM CoreExpr
getRep EvTerm
evm Type
m
       ; Id
mkTrFun <- Name -> DsM Id
dsLookupGlobalId Name
mkTrFunName
                    -- mkTrFun :: forall (m :: Multiplicity) r1 r2 (a :: TYPE r1) (b :: TYPE r2).
                    --            TypeRep m -> TypeRep a -> TypeRep b -> TypeRep (a % m -> b)
       ; let r1 :: Type
r1 = HasDebugCallStack => Type -> Type
Type -> Type
getRuntimeRep Type
t1
             r2 :: Type
r2 = HasDebugCallStack => Type -> Type
Type -> Type
getRuntimeRep Type
t2
       ; CoreExpr -> DsM CoreExpr
forall (m :: * -> *) a. Monad m => a -> m a
return (CoreExpr -> DsM CoreExpr) -> CoreExpr -> DsM CoreExpr
forall a b. (a -> b) -> a -> b
$ CoreExpr -> [CoreExpr] -> CoreExpr
forall b. Expr b -> [Expr b] -> Expr b
mkApps (CoreExpr -> [Type] -> CoreExpr
forall b. Expr b -> [Type] -> Expr b
mkTyApps (Id -> CoreExpr
forall b. Id -> Expr b
Var Id
mkTrFun) [Type
m, Type
r1, Type
r2, Type
t1, Type
t2])
                         [ CoreExpr
em, CoreExpr
e1, CoreExpr
e2 ]
       }

ds_ev_typeable Type
ty (EvTypeableTyLit EvTerm
ev)
  = -- See Note [Typeable for Nat and Symbol] in GHC.Tc.Solver.Interact
    do { Id
fun  <- Name -> DsM Id
dsLookupGlobalId Name
tr_fun
       ; CoreExpr
dict <- EvTerm -> DsM CoreExpr
dsEvTerm EvTerm
ev       -- Of type KnownNat/KnownSymbol
       ; CoreExpr -> DsM CoreExpr
forall (m :: * -> *) a. Monad m => a -> m a
return (CoreExpr -> [CoreExpr] -> CoreExpr
forall b. Expr b -> [Expr b] -> Expr b
mkApps (CoreExpr -> [Type] -> CoreExpr
forall b. Expr b -> [Type] -> Expr b
mkTyApps (Id -> CoreExpr
forall b. Id -> Expr b
Var Id
fun) [Type
ty]) [ CoreExpr
dict ]) }
  where
    ty_kind :: Type
ty_kind = HasDebugCallStack => Type -> Type
Type -> Type
typeKind Type
ty

    -- tr_fun is the Name of
    --       typeNatTypeRep    :: KnownNat    a => TypeRep a
    -- of    typeSymbolTypeRep :: KnownSymbol a => TypeRep a
    tr_fun :: Name
tr_fun | Type
ty_kind Type -> Type -> Bool
`eqType` Type
naturalTy      = Name
typeNatTypeRepName
           | Type
ty_kind Type -> Type -> Bool
`eqType` Type
typeSymbolKind = Name
typeSymbolTypeRepName
           | Type
ty_kind Type -> Type -> Bool
`eqType` Type
charTy         = Name
typeCharTypeRepName
           | Bool
otherwise = String -> Name
forall a. String -> a
panic String
"dsEvTypeable: unknown type lit kind"

ds_ev_typeable Type
ty EvTypeable
ev
  = String -> SDoc -> DsM CoreExpr
forall a. HasCallStack => String -> SDoc -> a
pprPanic String
"dsEvTypeable" (Type -> SDoc
forall a. Outputable a => a -> SDoc
ppr Type
ty SDoc -> SDoc -> SDoc
$$ EvTypeable -> SDoc
forall a. Outputable a => a -> SDoc
ppr EvTypeable
ev)

getRep :: EvTerm          -- ^ EvTerm for @Typeable ty@
       -> Type            -- ^ The type @ty@
       -> DsM TypeRepExpr -- ^ Return @CoreExpr :: TypeRep ty@
                          -- namely @typeRep# dict@
-- Remember that
--   typeRep# :: forall k (a::k). Typeable k a -> TypeRep a
getRep :: EvTerm -> Type -> DsM CoreExpr
getRep EvTerm
ev Type
ty
  = do { CoreExpr
typeable_expr <- EvTerm -> DsM CoreExpr
dsEvTerm EvTerm
ev
       ; Id
typeRepId     <- Name -> DsM Id
dsLookupGlobalId Name
typeRepIdName
       ; let ty_args :: [Type]
ty_args = [HasDebugCallStack => Type -> Type
Type -> Type
typeKind Type
ty, Type
ty]
       ; CoreExpr -> DsM CoreExpr
forall (m :: * -> *) a. Monad m => a -> m a
return (CoreExpr -> [CoreExpr] -> CoreExpr
forall b. Expr b -> [Expr b] -> Expr b
mkApps (CoreExpr -> [Type] -> CoreExpr
forall b. Expr b -> [Type] -> Expr b
mkTyApps (Id -> CoreExpr
forall b. Id -> Expr b
Var Id
typeRepId) [Type]
ty_args) [ CoreExpr
typeable_expr ]) }

tyConRep :: TyCon -> DsM CoreExpr
-- Returns CoreExpr :: TyCon
tyConRep :: TyCon -> DsM CoreExpr
tyConRep TyCon
tc
  | Just Name
tc_rep_nm <- TyCon -> Maybe Name
tyConRepName_maybe TyCon
tc
  = do { Id
tc_rep_id <- Name -> DsM Id
dsLookupGlobalId Name
tc_rep_nm
       ; CoreExpr -> DsM CoreExpr
forall (m :: * -> *) a. Monad m => a -> m a
return (Id -> CoreExpr
forall b. Id -> Expr b
Var Id
tc_rep_id) }
  | Bool
otherwise
  = String -> SDoc -> DsM CoreExpr
forall a. HasCallStack => String -> SDoc -> a
pprPanic String
"tyConRep" (TyCon -> SDoc
forall a. Outputable a => a -> SDoc
ppr TyCon
tc)