{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE ViewPatterns #-}
{-# LANGUAGE MultiWayIf #-}

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

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


Desugaring expressions.
-}

module GHC.HsToCore.Expr
   ( dsExpr, dsLExpr, dsLocalBinds
   , dsValBinds, dsLit, dsSyntaxExpr
   )
where

import GHC.Prelude

import GHC.HsToCore.Match
import GHC.HsToCore.Match.Literal
import GHC.HsToCore.Binds
import GHC.HsToCore.GuardedRHSs
import GHC.HsToCore.ListComp
import GHC.HsToCore.Utils
import GHC.HsToCore.Arrows
import GHC.HsToCore.Monad
import GHC.HsToCore.Pmc
import GHC.HsToCore.Pmc.Utils
import GHC.HsToCore.Errors.Types
import GHC.HsToCore.Quote
import GHC.HsToCore.Ticks (stripTicksTopHsExpr)
import GHC.Hs


-- NB: The desugarer, which straddles the source and Core worlds, sometimes
--     needs to see source types
import GHC.Tc.Utils.TcType
import GHC.Tc.Types.Evidence
import GHC.Tc.Utils.Monad
import GHC.Tc.Instance.Class (lookupHasFieldLabel)

import GHC.Core
import GHC.Core.FVs( exprsFreeVarsList )
import GHC.Core.FamInstEnv( topNormaliseType )
import GHC.Core.Type
import GHC.Core.TyCo.Rep
import GHC.Core.Utils
import GHC.Core.Make
import GHC.Core.PatSyn

import GHC.Driver.Session

import GHC.Types.SourceText
import GHC.Types.Name hiding (varName)
import GHC.Types.CostCentre
import GHC.Types.Id
import GHC.Types.Id.Info
import GHC.Types.Id.Make
import GHC.Types.Var( isInvisibleAnonPiTyBinder )
import GHC.Types.Basic
import GHC.Types.SrcLoc
import GHC.Types.Tickish

import GHC.Unit.Module
import GHC.Core.ConLike
import GHC.Core.DataCon
import GHC.Builtin.Types
import GHC.Builtin.Names

import GHC.Utils.Misc
import GHC.Utils.Outputable as Outputable
import GHC.Utils.Panic
import Control.Monad
import qualified Data.Set as S

{-
************************************************************************
*                                                                      *
                dsLocalBinds, dsValBinds
*                                                                      *
************************************************************************
-}

dsLocalBinds :: HsLocalBinds GhcTc -> CoreExpr -> DsM CoreExpr
dsLocalBinds :: HsLocalBinds GhcTc -> CoreExpr -> DsM CoreExpr
dsLocalBinds (EmptyLocalBinds XEmptyLocalBinds GhcTc GhcTc
_)  CoreExpr
body = CoreExpr -> DsM CoreExpr
forall a. a -> IOEnv (Env DsGblEnv DsLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return CoreExpr
body
dsLocalBinds b :: HsLocalBinds GhcTc
b@(HsValBinds XHsValBinds GhcTc GhcTc
_ HsValBindsLR GhcTc GhcTc
binds) CoreExpr
body = SrcSpan -> DsM CoreExpr -> DsM CoreExpr
forall a. SrcSpan -> DsM a -> DsM a
putSrcSpanDs (HsLocalBinds GhcTc -> SrcSpan
forall (p :: Pass). HsLocalBinds (GhcPass p) -> SrcSpan
spanHsLocaLBinds HsLocalBinds GhcTc
b) (DsM CoreExpr -> DsM CoreExpr) -> DsM CoreExpr -> DsM CoreExpr
forall a b. (a -> b) -> a -> b
$
                                           HsValBindsLR GhcTc GhcTc -> CoreExpr -> DsM CoreExpr
dsValBinds HsValBindsLR GhcTc GhcTc
binds CoreExpr
body
dsLocalBinds (HsIPBinds XHsIPBinds GhcTc GhcTc
_ HsIPBinds GhcTc
binds)  CoreExpr
body = HsIPBinds GhcTc -> CoreExpr -> DsM CoreExpr
dsIPBinds  HsIPBinds GhcTc
binds CoreExpr
body

-------------------------
-- caller sets location
dsValBinds :: HsValBinds GhcTc -> CoreExpr -> DsM CoreExpr
dsValBinds :: HsValBindsLR GhcTc GhcTc -> CoreExpr -> DsM CoreExpr
dsValBinds (XValBindsLR (NValBinds [(RecFlag, LHsBinds GhcTc)]
binds [LSig GhcRn]
_)) CoreExpr
body
  = do { dflags <- IOEnv (Env DsGblEnv DsLclEnv) DynFlags
forall (m :: * -> *). HasDynFlags m => m DynFlags
getDynFlags
       ; foldrM (ds_val_bind dflags) body binds }
dsValBinds (ValBinds {})       CoreExpr
_    = String -> DsM CoreExpr
forall a. HasCallStack => String -> a
panic String
"dsValBinds ValBindsIn"

-------------------------
dsIPBinds :: HsIPBinds GhcTc -> CoreExpr -> DsM CoreExpr
dsIPBinds :: HsIPBinds GhcTc -> CoreExpr -> DsM CoreExpr
dsIPBinds (IPBinds XIPBinds GhcTc
ev_binds [LIPBind GhcTc]
ip_binds) CoreExpr
body
  = do  { TcEvBinds -> ([CoreBind] -> DsM CoreExpr) -> DsM CoreExpr
forall a. TcEvBinds -> ([CoreBind] -> DsM a) -> DsM a
dsTcEvBinds XIPBinds GhcTc
TcEvBinds
ev_binds (([CoreBind] -> DsM CoreExpr) -> DsM CoreExpr)
-> ([CoreBind] -> DsM CoreExpr) -> DsM CoreExpr
forall a b. (a -> b) -> a -> b
$ \ [CoreBind]
ds_binds -> do
        { let inner :: CoreExpr
inner = [CoreBind] -> CoreExpr -> CoreExpr
mkCoreLets [CoreBind]
ds_binds CoreExpr
body
                -- The dict bindings may not be in
                -- dependency order; hence Rec
        ; (GenLocated SrcSpanAnnA (IPBind GhcTc) -> CoreExpr -> DsM CoreExpr)
-> CoreExpr
-> [GenLocated SrcSpanAnnA (IPBind GhcTc)]
-> DsM CoreExpr
forall (t :: * -> *) (m :: * -> *) a b.
(Foldable t, Monad m) =>
(a -> b -> m b) -> b -> t a -> m b
foldrM LIPBind GhcTc -> CoreExpr -> DsM CoreExpr
GenLocated SrcSpanAnnA (IPBind GhcTc) -> CoreExpr -> DsM CoreExpr
ds_ip_bind CoreExpr
inner [LIPBind GhcTc]
[GenLocated SrcSpanAnnA (IPBind GhcTc)]
ip_binds } }
  where
    ds_ip_bind :: LIPBind GhcTc -> CoreExpr -> DsM CoreExpr
    ds_ip_bind :: LIPBind GhcTc -> CoreExpr -> DsM CoreExpr
ds_ip_bind (L SrcSpanAnnA
_ (IPBind XCIPBind GhcTc
n XRec GhcTc HsIPName
_ LHsExpr GhcTc
e)) CoreExpr
body
      = do e' <- LHsExpr GhcTc -> DsM CoreExpr
dsLExpr LHsExpr GhcTc
e
           return (Let (NonRec n e') body)

-------------------------
-- caller sets location
ds_val_bind :: DynFlags -> (RecFlag, LHsBinds GhcTc) -> CoreExpr -> DsM CoreExpr
-- Special case for bindings which bind unlifted variables
-- We need to do a case right away, rather than building
-- a tuple and doing selections.
-- Silently ignore INLINE and SPECIALISE pragmas...
ds_val_bind :: DynFlags -> (RecFlag, LHsBinds GhcTc) -> CoreExpr -> DsM CoreExpr
ds_val_bind DynFlags
_ (RecFlag
NonRecursive, LHsBinds GhcTc
hsbinds) CoreExpr
body
  | [L SrcSpanAnnA
loc HsBind GhcTc
bind] <- LHsBinds GhcTc
hsbinds
        -- Non-recursive, non-overloaded bindings only come in ones
        -- ToDo: in some bizarre case it's conceivable that there
        --       could be dict binds in the 'binds'.  (See the notes
        --       below.  Then pattern-match would fail.  Urk.)
  , HsBind GhcTc -> Bool
isUnliftedHsBind HsBind GhcTc
bind
  = SrcSpan -> DsM CoreExpr -> DsM CoreExpr
forall a. SrcSpan -> DsM a -> DsM a
putSrcSpanDs (SrcSpanAnnA -> SrcSpan
forall a. HasLoc a => a -> SrcSpan
locA SrcSpanAnnA
loc) (DsM CoreExpr -> DsM CoreExpr) -> DsM CoreExpr -> DsM CoreExpr
forall a b. (a -> b) -> a -> b
$
     -- see Note [Strict binds checks] in GHC.HsToCore.Binds
    if HsBind GhcTc -> Bool
forall {idL} {idR}.
(XXHsBindsLR idL idR ~ AbsBinds) =>
HsBindLR idL idR -> Bool
is_polymorphic HsBind GhcTc
bind
    then DsMessage -> DsM CoreExpr
errDsCoreExpr (HsBind GhcTc -> DsMessage
DsCannotMixPolyAndUnliftedBindings HsBind GhcTc
bind)
            -- data Ptr a = Ptr Addr#
            -- f x = let p@(Ptr y) = ... in ...
            -- Here the binding for 'p' is polymorphic, but does
            -- not mix with an unlifted binding for 'y'.  You should
            -- use a bang pattern.  #6078.

    else do { Bool
-> IOEnv (Env DsGblEnv DsLclEnv) ()
-> IOEnv (Env DsGblEnv DsLclEnv) ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
when (HsBind GhcTc -> Bool
looksLazyPatBind HsBind GhcTc
bind) (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 (HsBind GhcTc -> DsMessage
DsUnbangedStrictPatterns HsBind GhcTc
bind)
        -- Complain about a binding that looks lazy
        --    e.g.    let I# y = x in ...
        -- Remember, in checkStrictBinds we are going to do strict
        -- matching, so (for software engineering reasons) we insist
        -- that the strictness is manifest on each binding
        -- However, lone (unboxed) variables are ok


            ; HsBind GhcTc -> CoreExpr -> DsM CoreExpr
dsUnliftedBind HsBind GhcTc
bind CoreExpr
body }
  where
    is_polymorphic :: HsBindLR idL idR -> Bool
is_polymorphic (XHsBindsLR (AbsBinds { abs_tvs :: AbsBinds -> [EvId]
abs_tvs = [EvId]
tvs, abs_ev_vars :: AbsBinds -> [EvId]
abs_ev_vars = [EvId]
evs }))
                     = Bool -> Bool
not ([EvId] -> Bool
forall a. [a] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null [EvId]
tvs Bool -> Bool -> Bool
&& [EvId] -> Bool
forall a. [a] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null [EvId]
evs)
    is_polymorphic HsBindLR idL idR
_ = Bool
False


ds_val_bind DynFlags
_ (RecFlag
is_rec, LHsBinds GhcTc
binds) CoreExpr
_body
  | (GenLocated SrcSpanAnnA (HsBind GhcTc) -> Bool)
-> [GenLocated SrcSpanAnnA (HsBind GhcTc)] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
any (HsBind GhcTc -> Bool
isUnliftedHsBind (HsBind GhcTc -> Bool)
-> (GenLocated SrcSpanAnnA (HsBind GhcTc) -> HsBind GhcTc)
-> GenLocated SrcSpanAnnA (HsBind GhcTc)
-> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. GenLocated SrcSpanAnnA (HsBind GhcTc) -> HsBind GhcTc
forall l e. GenLocated l e -> e
unLoc) LHsBinds GhcTc
[GenLocated SrcSpanAnnA (HsBind GhcTc)]
binds  -- see Note [Strict binds checks] in GHC.HsToCore.Binds
  = Bool -> (DsMessage -> DsM CoreExpr) -> DsMessage -> DsM CoreExpr
forall a. HasCallStack => Bool -> a -> a
assert (RecFlag -> Bool
isRec RecFlag
is_rec )
    DsMessage -> DsM CoreExpr
errDsCoreExpr (DsMessage -> DsM CoreExpr) -> DsMessage -> DsM CoreExpr
forall a b. (a -> b) -> a -> b
$ LHsBinds GhcTc -> DsMessage
DsRecBindsNotAllowedForUnliftedTys LHsBinds GhcTc
binds

-- Special case: a non-recursive PatBind. No dancing about with lets and seqs,
-- we make a case immediately. Very important for linear types: let !pat can be
-- linear, but selectors as used in the general case aren't. So the general case
-- would transform a linear definition into a non-linear one. See Wrinkle 2
-- Note [Desugar Strict binds] in GHC.HsToCore.Binds.
ds_val_bind DynFlags
dflags (RecFlag
NonRecursive, LHsBinds GhcTc
hsbinds) CoreExpr
body
  | [L SrcSpanAnnA
_loc (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_mult :: forall idL idR. HsBindLR idL idR -> HsMultAnn idL
pat_mult = HsMultAnn GhcTc
mult_ann
                     , pat_ext :: forall idL idR. HsBindLR idL idR -> XPatBind idL idR
pat_ext = (Type
ty, ([CoreTickish]
rhs_tick, [[CoreTickish]]
_var_ticks))})] <- LHsBinds GhcTc
hsbinds
        -- Non-recursive, non-overloaded bindings only come in ones
  , LPat GhcTc
pat' <- DynFlags -> LPat GhcTc -> LPat GhcTc
decideBangHood DynFlags
dflags LPat GhcTc
pat
  , LPat GhcTc -> Bool
forall (p :: Pass). LPat (GhcPass p) -> Bool
isBangedLPat LPat GhcTc
pat'
  = do { rhss_nablas <- HsMatchContextRn
-> GRHSs GhcTc (LHsExpr GhcTc) -> DsM (NonEmpty Nablas)
pmcGRHSs HsMatchContextRn
HsMatchContext (GenLocated SrcSpanAnnN Name)
forall fn. HsMatchContext fn
PatBindGuards GRHSs GhcTc (LHsExpr GhcTc)
grhss
        ; rhs_expr <- dsGuarded grhss ty rhss_nablas
        ; let rhs' = [CoreTickish] -> CoreExpr -> CoreExpr
mkOptTickBox [CoreTickish]
rhs_tick CoreExpr
rhs_expr
        ; let body_ty = HasDebugCallStack => CoreExpr -> Type
CoreExpr -> Type
exprType CoreExpr
body
        ; let mult = HsMultAnn GhcTc -> Type
getTcMultAnn HsMultAnn GhcTc
mult_ann
        ; error_expr <- mkErrorAppDs pAT_ERROR_ID body_ty (ppr pat')
        ; matchSimply rhs' PatBindRhs mult pat' body error_expr }
    -- This is the one place where matchSimply is given a non-ManyTy
    -- multiplicity argument.
    --
    -- In this form, there isn't a natural place for the var_ticks. In
    -- mkSelectorBinds, the ticks are around the selector function but there
    -- aren't any selection functions as we make a single pattern-match. Is this a
    -- problem?

-- Ordinary case for bindings; none should be unlifted
ds_val_bind DynFlags
_ (RecFlag
is_rec, LHsBinds GhcTc
binds) CoreExpr
body
  = do  { Bool -> IOEnv (Env DsGblEnv DsLclEnv) ()
forall (m :: * -> *). (HasCallStack, Applicative m) => Bool -> m ()
massert (RecFlag -> Bool
isRec RecFlag
is_rec Bool -> Bool -> Bool
|| [GenLocated SrcSpanAnnA (HsBind GhcTc)] -> Bool
forall a. [a] -> Bool
isSingleton LHsBinds GhcTc
[GenLocated SrcSpanAnnA (HsBind GhcTc)]
binds)
               -- we should never produce a non-recursive list of multiple binds

        ; (force_vars,prs) <- LHsBinds GhcTc -> DsM ([EvId], [(EvId, CoreExpr)])
dsLHsBinds LHsBinds GhcTc
binds
        ; let body' = (EvId -> CoreExpr -> CoreExpr) -> CoreExpr -> [EvId] -> CoreExpr
forall a b. (a -> b -> b) -> b -> [a] -> b
forall (t :: * -> *) a b.
Foldable t =>
(a -> b -> b) -> b -> t a -> b
foldr EvId -> CoreExpr -> CoreExpr
seqVar CoreExpr
body [EvId]
force_vars
        ; assertPpr (not (any (isUnliftedType . idType . fst) prs)) (ppr is_rec $$ ppr binds) $
          -- NB: bindings have a fixed RuntimeRep, so it's OK to call isUnliftedType
          case prs of
            [] -> CoreExpr -> DsM CoreExpr
forall a. a -> IOEnv (Env DsGblEnv DsLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return CoreExpr
body
            [(EvId, CoreExpr)]
_  -> CoreExpr -> DsM CoreExpr
forall a. a -> IOEnv (Env DsGblEnv DsLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return ([CoreBind] -> CoreExpr -> CoreExpr
forall b. [Bind b] -> Expr b -> Expr b
mkLets (RecFlag -> [(EvId, CoreExpr)] -> [CoreBind]
forall b. RecFlag -> [(b, Expr b)] -> [Bind b]
mk_binds RecFlag
is_rec [(EvId, CoreExpr)]
prs) CoreExpr
body') }
            -- We can make a non-recursive let because we make sure to return
            -- the bindings in dependency order in dsLHsBinds,
            -- see Note [Return non-recursive bindings in dependency order] in
            -- GHC.HsToCore.Binds

-- | Helper function. You can use the result of 'mk_binds' with 'mkLets' for
-- instance.
--
--   * @'mk_binds' 'Recursive' binds@ makes a single mutually-recursive
--     bindings with all the rhs/lhs pairs in @binds@
--   * @'mk_binds' 'NonRecursive' binds@ makes one non-recursive binding
--     for each rhs/lhs pairs in @binds@
mk_binds :: RecFlag -> [(b, (Expr b))] -> [Bind b]
mk_binds :: forall b. RecFlag -> [(b, Expr b)] -> [Bind b]
mk_binds RecFlag
Recursive [(b, Expr b)]
binds = [[(b, Expr b)] -> Bind b
forall b. [(b, Expr b)] -> Bind b
Rec [(b, Expr b)]
binds]
mk_binds RecFlag
NonRecursive [(b, Expr b)]
binds = ((b, Expr b) -> Bind b) -> [(b, Expr b)] -> [Bind b]
forall a b. (a -> b) -> [a] -> [b]
map ((b -> Expr b -> Bind b) -> (b, Expr b) -> Bind b
forall a b c. (a -> b -> c) -> (a, b) -> c
uncurry b -> Expr b -> Bind b
forall b. b -> Expr b -> Bind b
NonRec) [(b, Expr b)]
binds

------------------
dsUnliftedBind :: HsBind GhcTc -> CoreExpr -> DsM CoreExpr
dsUnliftedBind :: HsBind GhcTc -> CoreExpr -> DsM CoreExpr
dsUnliftedBind (XHsBindsLR (AbsBinds { abs_tvs :: AbsBinds -> [EvId]
abs_tvs = [], abs_ev_vars :: AbsBinds -> [EvId]
abs_ev_vars = []
                                     , abs_exports :: AbsBinds -> [ABExport]
abs_exports = [ABExport]
exports
                                     , abs_ev_binds :: AbsBinds -> [TcEvBinds]
abs_ev_binds = [TcEvBinds]
ev_binds
                                     , abs_binds :: AbsBinds -> LHsBinds GhcTc
abs_binds = LHsBinds GhcTc
lbinds })) CoreExpr
body
  = do { let body1 :: CoreExpr
body1 = (ABExport -> CoreExpr -> CoreExpr)
-> CoreExpr -> [ABExport] -> CoreExpr
forall a b. (a -> b -> b) -> b -> [a] -> b
forall (t :: * -> *) a b.
Foldable t =>
(a -> b -> b) -> b -> t a -> b
foldr ABExport -> CoreExpr -> CoreExpr
bind_export CoreExpr
body [ABExport]
exports
             bind_export :: ABExport -> CoreExpr -> CoreExpr
bind_export ABExport
export CoreExpr
b = HasDebugCallStack => EvId -> CoreExpr -> CoreExpr -> CoreExpr
EvId -> CoreExpr -> CoreExpr -> CoreExpr
bindNonRec (ABExport -> EvId
abe_poly ABExport
export) (EvId -> CoreExpr
forall b. EvId -> Expr b
Var (ABExport -> EvId
abe_mono ABExport
export)) CoreExpr
b
       ; body2 <- (CoreExpr -> GenLocated SrcSpanAnnA (HsBind GhcTc) -> DsM CoreExpr)
-> CoreExpr
-> [GenLocated SrcSpanAnnA (HsBind GhcTc)]
-> DsM CoreExpr
forall (t :: * -> *) (m :: * -> *) b a.
(Foldable t, Monad m) =>
(b -> a -> m b) -> b -> t a -> m b
foldlM (\CoreExpr
body GenLocated SrcSpanAnnA (HsBind GhcTc)
lbind -> HsBind GhcTc -> CoreExpr -> DsM CoreExpr
dsUnliftedBind (GenLocated SrcSpanAnnA (HsBind GhcTc) -> HsBind GhcTc
forall l e. GenLocated l e -> e
unLoc GenLocated SrcSpanAnnA (HsBind GhcTc)
lbind) CoreExpr
body)
                            CoreExpr
body1 LHsBinds GhcTc
[GenLocated SrcSpanAnnA (HsBind GhcTc)]
lbinds
       ; dsTcEvBinds_s ev_binds $ \ [CoreBind]
ds_binds -> do
       { CoreExpr -> DsM CoreExpr
forall a. a -> IOEnv (Env DsGblEnv DsLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return ([CoreBind] -> CoreExpr -> CoreExpr
mkCoreLets [CoreBind]
ds_binds CoreExpr
body2) } }

dsUnliftedBind (FunBind { fun_id :: forall idL idR. HsBindLR idL idR -> LIdP idL
fun_id = L SrcSpanAnnN
l EvId
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 = (HsWrapper
co_fn, [CoreTickish]
tick)
                        }) CoreExpr
body
               -- Can't be a bang pattern (that looks like a PatBind)
               -- so must be simply unboxed
  = do { (args, rhs) <- HsMatchContextRn
-> Maybe [LHsExpr GhcTc]
-> MatchGroup GhcTc (LHsExpr GhcTc)
-> DsM ([EvId], CoreExpr)
matchWrapper (GenLocated SrcSpanAnnN Name
-> AnnFunRhs -> HsMatchContext (GenLocated SrcSpanAnnN Name)
forall fn. fn -> AnnFunRhs -> HsMatchContext fn
mkPrefixFunRhs (SrcSpanAnnN -> Name -> GenLocated SrcSpanAnnN Name
forall l e. l -> e -> GenLocated l e
L SrcSpanAnnN
l (Name -> GenLocated SrcSpanAnnN Name)
-> Name -> GenLocated SrcSpanAnnN Name
forall a b. (a -> b) -> a -> b
$ EvId -> Name
idName EvId
fun) AnnFunRhs
forall a. NoAnn a => a
noAnn) Maybe [LHsExpr GhcTc]
Maybe [LocatedA (HsExpr GhcTc)]
forall a. Maybe a
Nothing MatchGroup GhcTc (LHsExpr GhcTc)
matches
       ; massert (null args) -- Functions aren't unlifted
       ; dsHsWrapper co_fn $ \CoreExpr -> CoreExpr
core_wrap ->  -- Can be non-identity (#21516)
    do { let rhs' :: CoreExpr
rhs' = CoreExpr -> CoreExpr
core_wrap ([CoreTickish] -> CoreExpr -> CoreExpr
mkOptTickBox [CoreTickish]
tick CoreExpr
rhs)
       ; CoreExpr -> DsM CoreExpr
forall a. a -> IOEnv (Env DsGblEnv DsLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return (HasDebugCallStack => EvId -> CoreExpr -> CoreExpr -> CoreExpr
EvId -> CoreExpr -> CoreExpr -> CoreExpr
bindNonRec EvId
fun CoreExpr
rhs' CoreExpr
body) } }

dsUnliftedBind (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 = (Type
ty, ([CoreTickish], [[CoreTickish]])
_) }) CoreExpr
body
  =     -- let C x# y# = rhs in body
        -- ==> case rhs of C x# y# -> body
    do { match_nablas <- HsMatchContextRn
-> GRHSs GhcTc (LHsExpr GhcTc) -> DsM (NonEmpty Nablas)
pmcGRHSs HsMatchContextRn
HsMatchContext (GenLocated SrcSpanAnnN Name)
forall fn. HsMatchContext fn
PatBindGuards GRHSs GhcTc (LHsExpr GhcTc)
grhss
       ; rhs          <- dsGuarded grhss ty match_nablas
       ; let eqn = EqnMatch { eqn_pat :: LPat GhcTc
eqn_pat = LPat GhcTc
pat, eqn_rest :: EquationInfo
eqn_rest = MatchResult CoreExpr -> EquationInfo
EqnDone (CoreExpr -> MatchResult CoreExpr
cantFailMatchResult CoreExpr
body) }
       ; var    <- selectMatchVar ManyTy (unLoc pat)
                    -- `var` will end up in a let binder, so the multiplicity
                    -- doesn't matter.
       ; result <- matchEquations PatBindRhs [var] [eqn] (exprType body)
       ; return (bindNonRec var rhs result) }

dsUnliftedBind HsBind GhcTc
bind CoreExpr
body = String -> SDoc -> DsM CoreExpr
forall a. HasCallStack => String -> SDoc -> a
pprPanic String
"dsLet: unlifted" (HsBind GhcTc -> SDoc
forall a. Outputable a => a -> SDoc
ppr HsBind GhcTc
bind SDoc -> SDoc -> SDoc
forall doc. IsDoc doc => doc -> doc -> doc
$$ CoreExpr -> SDoc
forall a. Outputable a => a -> SDoc
ppr CoreExpr
body)

{-
************************************************************************
*                                                                      *
*              Variables, constructors, literals                       *
*                                                                      *
************************************************************************
-}

-- | Desugar a located typechecked expression.
dsLExpr :: LHsExpr GhcTc -> DsM CoreExpr
dsLExpr :: LHsExpr GhcTc -> DsM CoreExpr
dsLExpr (L SrcSpanAnnA
loc HsExpr GhcTc
e) = SrcSpanAnnA -> DsM CoreExpr -> DsM CoreExpr
forall ann a. EpAnn ann -> DsM a -> DsM a
putSrcSpanDsA SrcSpanAnnA
loc (DsM CoreExpr -> DsM CoreExpr) -> DsM CoreExpr -> DsM CoreExpr
forall a b. (a -> b) -> a -> b
$ HsExpr GhcTc -> DsM CoreExpr
dsExpr HsExpr GhcTc
e

-- | Desugar a typechecked expression.
dsExpr :: HsExpr GhcTc -> DsM CoreExpr

dsExpr :: HsExpr GhcTc -> DsM CoreExpr
dsExpr e :: HsExpr GhcTc
e@(HsVar {})                 = HsExpr GhcTc -> DsM CoreExpr
dsApp HsExpr GhcTc
e
dsExpr e :: HsExpr GhcTc
e@(HsApp {})                 = HsExpr GhcTc -> DsM CoreExpr
dsApp HsExpr GhcTc
e
dsExpr e :: HsExpr GhcTc
e@(HsAppType {})             = HsExpr GhcTc -> DsM CoreExpr
dsApp HsExpr GhcTc
e

dsExpr (HsUnboundVar (HER IORef EvTerm
ref Type
_ Unique
_) RdrName
_)  = EvTerm -> DsM CoreExpr
dsEvTerm (EvTerm -> DsM CoreExpr)
-> IOEnv (Env DsGblEnv DsLclEnv) EvTerm -> DsM CoreExpr
forall (m :: * -> *) a b. Monad m => (a -> m b) -> m a -> m b
=<< IORef EvTerm -> IOEnv (Env DsGblEnv DsLclEnv) EvTerm
forall a env. IORef a -> IOEnv env a
readMutVar IORef EvTerm
ref
        -- See Note [Holes] in GHC.Tc.Types.Constraint

dsExpr (HsPar XPar GhcTc
_ LHsExpr GhcTc
e)            = LHsExpr GhcTc -> DsM CoreExpr
dsLExpr LHsExpr GhcTc
e
dsExpr (ExprWithTySig XExprWithTySig GhcTc
_ LHsExpr GhcTc
e LHsSigWcType (NoGhcTc GhcTc)
_)  = LHsExpr GhcTc -> DsM CoreExpr
dsLExpr LHsExpr GhcTc
e

dsExpr (HsLit XLitE GhcTc
_ HsLit GhcTc
lit)
  = do { HsLit GhcTc -> IOEnv (Env DsGblEnv DsLclEnv) ()
warnAboutOverflowedLit HsLit GhcTc
lit
       ; HsLit GhcTc -> DsM CoreExpr
forall (p :: Pass). IsPass p => HsLit (GhcPass p) -> DsM CoreExpr
dsLit HsLit GhcTc
lit }

dsExpr (HsOverLit XOverLitE GhcTc
_ HsOverLit GhcTc
lit)
  = do { HsOverLit GhcTc -> IOEnv (Env DsGblEnv DsLclEnv) ()
warnAboutOverflowedOverLit HsOverLit GhcTc
lit
       ; HsOverLit GhcTc -> DsM CoreExpr
dsOverLit HsOverLit GhcTc
lit }

dsExpr e :: HsExpr GhcTc
e@(XExpr XXExpr GhcTc
ext_expr_tc)
  = case XXExpr GhcTc
ext_expr_tc of
      HsRecSelTc {} -> HsExpr GhcTc -> DsM CoreExpr
dsApp HsExpr GhcTc
e
      WrapExpr {}   -> HsExpr GhcTc -> DsM CoreExpr
dsApp HsExpr GhcTc
e
      ConLikeTc {}  -> HsExpr GhcTc -> DsM CoreExpr
dsApp HsExpr GhcTc
e

      ExpandedThingTc HsThingRn
o HsExpr GhcTc
e
        | OrigStmt (L SrcSpanAnnA
loc StmtLR GhcRn GhcRn (GenLocated SrcSpanAnnA (HsExpr GhcRn))
_) <- HsThingRn
o
        -> SrcSpanAnnA -> DsM CoreExpr -> DsM CoreExpr
forall ann a. EpAnn ann -> DsM a -> DsM a
putSrcSpanDsA SrcSpanAnnA
loc (DsM CoreExpr -> DsM CoreExpr) -> DsM CoreExpr -> DsM CoreExpr
forall a b. (a -> b) -> a -> b
$ HsExpr GhcTc -> DsM CoreExpr
dsExpr HsExpr GhcTc
e
        | Bool
otherwise -> HsExpr GhcTc -> DsM CoreExpr
dsExpr HsExpr GhcTc
e
      -- Hpc Support
      HsTick CoreTickish
tickish LHsExpr GhcTc
e -> do
        e' <- LHsExpr GhcTc -> DsM CoreExpr
dsLExpr LHsExpr GhcTc
e
        return (Tick tickish e')

      -- There is a problem here. The then and else branches
      -- have no free variables, so they are open to lifting.
      -- We need someway of stopping this.
      -- This will make no difference to binary coverage
      -- (did you go here: YES or NO), but will effect accurate
      -- tick counting.

      HsBinTick Int
ixT Int
ixF LHsExpr GhcTc
e -> do
        e2 <- LHsExpr GhcTc -> DsM CoreExpr
dsLExpr LHsExpr GhcTc
e
        do { assert (exprType e2 `eqType` boolTy)
            mkBinaryTickBox ixT ixF e2
          }


-- Strip ticks due to #21701, need to be invariant about warnings we produce whether
-- this is enabled or not.
dsExpr (NegApp XNegApp GhcTc
_ (L SrcSpanAnnA
loc
                    (HsExpr GhcTc -> ([CoreTickish], HsExpr GhcTc)
stripTicksTopHsExpr -> ([CoreTickish]
ts, (HsOverLit XOverLitE GhcTc
_ lit :: HsOverLit GhcTc
lit@(OverLit { ol_val :: forall p. HsOverLit p -> OverLitVal
ol_val = HsIntegral IntegralLit
i})))))
              SyntaxExpr GhcTc
neg_expr)
  = do { expr' <- SrcSpanAnnA -> DsM CoreExpr -> DsM CoreExpr
forall ann a. EpAnn ann -> DsM a -> DsM a
putSrcSpanDsA SrcSpanAnnA
loc (DsM CoreExpr -> DsM CoreExpr) -> DsM CoreExpr -> DsM CoreExpr
forall a b. (a -> b) -> a -> b
$ do
          { HsOverLit GhcTc -> IOEnv (Env DsGblEnv DsLclEnv) ()
warnAboutOverflowedOverLit
                -- See Note [Checking "negative literals"]
              (HsOverLit GhcTc
lit { ol_val = HsIntegral (negateIntegralLit i) })
          ; HsOverLit GhcTc -> DsM CoreExpr
dsOverLit HsOverLit GhcTc
lit }
       ; dsSyntaxExpr neg_expr [mkTicks ts expr'] }

dsExpr (NegApp XNegApp GhcTc
_ LHsExpr GhcTc
expr SyntaxExpr GhcTc
neg_expr)
  = do { expr' <- LHsExpr GhcTc -> DsM CoreExpr
dsLExpr LHsExpr GhcTc
expr
       ; dsSyntaxExpr neg_expr [expr'] }

dsExpr (HsLam XLam GhcTc
_ HsLamVariant
variant MatchGroup GhcTc (LHsExpr GhcTc)
a_Match)
  = ([EvId] -> CoreExpr -> CoreExpr) -> ([EvId], CoreExpr) -> CoreExpr
forall a b c. (a -> b -> c) -> (a, b) -> c
uncurry [EvId] -> CoreExpr -> CoreExpr
mkCoreLams (([EvId], CoreExpr) -> CoreExpr)
-> DsM ([EvId], CoreExpr) -> DsM CoreExpr
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> HsMatchContextRn
-> Maybe [LHsExpr GhcTc]
-> MatchGroup GhcTc (LHsExpr GhcTc)
-> DsM ([EvId], CoreExpr)
matchWrapper (HsLamVariant -> HsMatchContext (GenLocated SrcSpanAnnN Name)
forall fn. HsLamVariant -> HsMatchContext fn
LamAlt HsLamVariant
variant) Maybe [LHsExpr GhcTc]
Maybe [LocatedA (HsExpr GhcTc)]
forall a. Maybe a
Nothing MatchGroup GhcTc (LHsExpr GhcTc)
a_Match


{-
Note [Checking "negative literals"]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

As observed in #13257 it's desirable to warn about overflowing negative literals
in some situations where the user thinks they are writing a negative literal (ie -1)
but without `-XNegativeLiterals` enabled.

This catches cases such as (-1 :: Word8) which overflow, because (negate 1 == 255) but
which we desugar to `negate (fromIntegral 1)`.

Notice it's crucial we still desugar to the correct (negate (fromIntegral ...)) despite
performing the negation in order to check whether the application of negate will overflow.
For a user written Integer instance we can't predict the interaction of negate and fromIntegral.

Also note that this works for detecting the right result for `-128 :: Int8`.. which is
in-range for Int8 but the correct result is achieved via two overflows.

negate (fromIntegral 128 :: Int8)
= negate (-128 :: Int8)
= -128 :: Int8

Note [Desugaring vars]
~~~~~~~~~~~~~~~~~~~~~~
In one situation we can get a *coercion* variable in a HsVar, namely
the support method for an equality superclass:
   class (a~b) => C a b where ...
   instance (blah) => C (T a) (T b) where ..
Then we get
   $dfCT :: forall ab. blah => C (T a) (T b)
   $dfCT ab blah = MkC ($c$p1C a blah) ($cop a blah)

   $c$p1C :: forall ab. blah => (T a ~ T b)
   $c$p1C ab blah = let ...; g :: T a ~ T b = ... } in g

That 'g' in the 'in' part is an evidence variable, and when
converting to core it must become a CO.
-}

dsExpr (ExplicitTuple XExplicitTuple GhcTc
_ [HsTupArg GhcTc]
tup_args Boxity
boxity)
  = do { let go :: ([EvId], [CoreExpr])
-> HsTupArg GhcTc
-> IOEnv (Env DsGblEnv DsLclEnv) ([EvId], [CoreExpr])
go ([EvId]
lam_vars, [CoreExpr]
args) (Missing XMissing GhcTc
st)
                    -- For every missing expression, we need
                    -- another lambda in the desugaring.
               = do { lam_var <- Scaled Type -> DsM EvId
newSysLocalDs XMissing GhcTc
Scaled Type
st
                    ; return (lam_var : lam_vars, Var lam_var : args) }
             go ([EvId]
lam_vars, [CoreExpr]
args) (Present XPresent GhcTc
_ LHsExpr GhcTc
expr)
                    -- Expressions that are present don't generate
                    -- lambdas, just arguments.
               = do { core_expr <- LHsExpr GhcTc -> DsM CoreExpr
dsLExpr LHsExpr GhcTc
expr
                    ; return (lam_vars, core_expr : args) }

       ; (lam_vars, args) <- (([EvId], [CoreExpr])
 -> HsTupArg GhcTc
 -> IOEnv (Env DsGblEnv DsLclEnv) ([EvId], [CoreExpr]))
-> ([EvId], [CoreExpr])
-> [HsTupArg GhcTc]
-> IOEnv (Env DsGblEnv DsLclEnv) ([EvId], [CoreExpr])
forall (t :: * -> *) (m :: * -> *) b a.
(Foldable t, Monad m) =>
(b -> a -> m b) -> b -> t a -> m b
foldM ([EvId], [CoreExpr])
-> HsTupArg GhcTc
-> IOEnv (Env DsGblEnv DsLclEnv) ([EvId], [CoreExpr])
go ([], []) ([HsTupArg GhcTc] -> [HsTupArg GhcTc]
forall a. [a] -> [a]
reverse [HsTupArg GhcTc]
tup_args)
                -- The reverse is because foldM goes left-to-right
       ; return $ mkCoreLams lam_vars (mkCoreTupBoxity boxity args) }
                        -- See Note [Don't flatten tuples from HsSyn] in GHC.Core.Make

dsExpr (ExplicitSum XExplicitSum GhcTc
types Int
alt Int
arity LHsExpr GhcTc
expr)
  = Int -> Int -> [Type] -> CoreExpr -> CoreExpr
mkCoreUnboxedSum Int
arity Int
alt [Type]
XExplicitSum GhcTc
types (CoreExpr -> CoreExpr) -> DsM CoreExpr -> DsM CoreExpr
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> LHsExpr GhcTc -> DsM CoreExpr
dsLExpr LHsExpr GhcTc
expr

dsExpr (HsPragE XPragE GhcTc
_ (HsPragSCC XSCC GhcTc
_ StringLiteral
cc) LHsExpr GhcTc
expr)
  = do { dflags <- IOEnv (Env DsGblEnv DsLclEnv) DynFlags
forall (m :: * -> *). HasDynFlags m => m DynFlags
getDynFlags
       ; if sccProfilingEnabled dflags && gopt Opt_ProfManualCcs dflags
         then do
            mod_name <- getModule
            count <- goptM Opt_ProfCountEntries
            let nm = StringLiteral -> FastString
sl_fs StringLiteral
cc
            flavour <- mkExprCCFlavour <$> getCCIndexDsM nm
            Tick (ProfNote (mkUserCC nm mod_name (getLocA expr) flavour) count True)
                 <$> dsLExpr expr
         else dsLExpr expr }

dsExpr (HsCase XCase GhcTc
ctxt LHsExpr GhcTc
discrim MatchGroup GhcTc (LHsExpr GhcTc)
matches)
  = do { core_discrim <- LHsExpr GhcTc -> DsM CoreExpr
dsLExpr LHsExpr GhcTc
discrim
       ; ([discrim_var], matching_code) <- matchWrapper ctxt (Just [discrim]) matches
       ; return (bindNonRec discrim_var core_discrim matching_code) }

-- Pepe: The binds are in scope in the body but NOT in the binding group
--       This is to avoid silliness in breakpoints
dsExpr (HsLet XLet GhcTc
_ HsLocalBinds GhcTc
binds LHsExpr GhcTc
body) = do
    body' <- LHsExpr GhcTc -> DsM CoreExpr
dsLExpr LHsExpr GhcTc
body
    dsLocalBinds binds body'

-- We need the `ListComp' form to use `deListComp' (rather than the "do" form)
-- because the interpretation of `stmts' depends on what sort of thing it is.
--
dsExpr (HsDo XDo GhcTc
res_ty HsDoFlavour
ListComp          (L SrcSpanAnnLW
_ [GenLocated
   SrcSpanAnnA (StmtLR GhcTc GhcTc (LocatedA (HsExpr GhcTc)))]
stmts)) = [ExprLStmt GhcTc] -> Type -> DsM CoreExpr
dsListComp [ExprLStmt GhcTc]
[GenLocated
   SrcSpanAnnA (StmtLR GhcTc GhcTc (LocatedA (HsExpr GhcTc)))]
stmts XDo GhcTc
Type
res_ty
dsExpr (HsDo XDo GhcTc
_      HsDoFlavour
MonadComp         (L SrcSpanAnnLW
_ [GenLocated
   SrcSpanAnnA (StmtLR GhcTc GhcTc (LocatedA (HsExpr GhcTc)))]
stmts)) = [ExprLStmt GhcTc] -> DsM CoreExpr
dsMonadComp [ExprLStmt GhcTc]
[GenLocated
   SrcSpanAnnA (StmtLR GhcTc GhcTc (LocatedA (HsExpr GhcTc)))]
stmts
dsExpr (HsDo XDo GhcTc
res_ty ctx :: HsDoFlavour
ctx@DoExpr{}      (L SrcSpanAnnLW
_ [GenLocated
   SrcSpanAnnA (StmtLR GhcTc GhcTc (LocatedA (HsExpr GhcTc)))]
stmts)) = HsDoFlavour -> [ExprLStmt GhcTc] -> Type -> DsM CoreExpr
dsDo HsDoFlavour
ctx [ExprLStmt GhcTc]
[GenLocated
   SrcSpanAnnA (StmtLR GhcTc GhcTc (LocatedA (HsExpr GhcTc)))]
stmts XDo GhcTc
Type
res_ty
dsExpr (HsDo XDo GhcTc
res_ty ctx :: HsDoFlavour
ctx@HsDoFlavour
GhciStmtCtxt  (L SrcSpanAnnLW
_ [GenLocated
   SrcSpanAnnA (StmtLR GhcTc GhcTc (LocatedA (HsExpr GhcTc)))]
stmts)) = HsDoFlavour -> [ExprLStmt GhcTc] -> Type -> DsM CoreExpr
dsDo HsDoFlavour
ctx [ExprLStmt GhcTc]
[GenLocated
   SrcSpanAnnA (StmtLR GhcTc GhcTc (LocatedA (HsExpr GhcTc)))]
stmts XDo GhcTc
Type
res_ty
dsExpr (HsDo XDo GhcTc
res_ty ctx :: HsDoFlavour
ctx@MDoExpr{}     (L SrcSpanAnnLW
_ [GenLocated
   SrcSpanAnnA (StmtLR GhcTc GhcTc (LocatedA (HsExpr GhcTc)))]
stmts)) = HsDoFlavour -> [ExprLStmt GhcTc] -> Type -> DsM CoreExpr
dsDo HsDoFlavour
ctx [ExprLStmt GhcTc]
[GenLocated
   SrcSpanAnnA (StmtLR GhcTc GhcTc (LocatedA (HsExpr GhcTc)))]
stmts XDo GhcTc
Type
res_ty

dsExpr (HsIf XIf GhcTc
_ LHsExpr GhcTc
guard_expr LHsExpr GhcTc
then_expr LHsExpr GhcTc
else_expr)
  = do { pred <- LHsExpr GhcTc -> DsM CoreExpr
dsLExpr LHsExpr GhcTc
guard_expr
       ; b1 <- dsLExpr then_expr
       ; b2 <- dsLExpr else_expr
       ; return $ mkIfThenElse pred b1 b2 }

dsExpr (HsMultiIf XMultiIf GhcTc
res_ty [LGRHS GhcTc (LHsExpr GhcTc)]
alts)
  | [GenLocated
   (EpAnn NoEpAnns) (GRHS GhcTc (LocatedA (HsExpr GhcTc)))]
-> Bool
forall a. [a] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null [LGRHS GhcTc (LHsExpr GhcTc)]
[GenLocated
   (EpAnn NoEpAnns) (GRHS GhcTc (LocatedA (HsExpr GhcTc)))]
alts
  = DsM CoreExpr
mkErrorExpr

  | Bool
otherwise
  = do { let grhss :: GRHSs GhcTc (LocatedA (HsExpr GhcTc))
grhss = XCGRHSs GhcTc (LocatedA (HsExpr GhcTc))
-> [LGRHS GhcTc (LocatedA (HsExpr GhcTc))]
-> HsLocalBinds GhcTc
-> GRHSs GhcTc (LocatedA (HsExpr GhcTc))
forall p body.
XCGRHSs p body -> [LGRHS p body] -> HsLocalBinds p -> GRHSs p body
GRHSs XCGRHSs GhcTc (LocatedA (HsExpr GhcTc))
EpAnnComments
emptyComments  [LGRHS GhcTc (LHsExpr GhcTc)]
[LGRHS GhcTc (LocatedA (HsExpr GhcTc))]
alts HsLocalBinds GhcTc
forall (a :: Pass) (b :: Pass).
HsLocalBindsLR (GhcPass a) (GhcPass b)
emptyLocalBinds
       ; rhss_nablas  <- HsMatchContextRn
-> GRHSs GhcTc (LHsExpr GhcTc) -> DsM (NonEmpty Nablas)
pmcGRHSs HsMatchContextRn
HsMatchContext (GenLocated SrcSpanAnnN Name)
forall fn. HsMatchContext fn
IfAlt GRHSs GhcTc (LHsExpr GhcTc)
GRHSs GhcTc (LocatedA (HsExpr GhcTc))
grhss
       ; match_result <- dsGRHSs IfAlt grhss res_ty rhss_nablas
       ; error_expr   <- mkErrorExpr
       ; extractMatchResult match_result error_expr }
  where
    mkErrorExpr :: DsM CoreExpr
mkErrorExpr = EvId -> Type -> SDoc -> DsM CoreExpr
mkErrorAppDs EvId
nON_EXHAUSTIVE_GUARDS_ERROR_ID XMultiIf GhcTc
Type
res_ty
                               (String -> SDoc
forall doc. IsLine doc => String -> doc
text String
"multi-way if")

dsExpr (ExplicitList XExplicitList GhcTc
elt_ty [LHsExpr GhcTc]
xs) = Type -> [LHsExpr GhcTc] -> DsM CoreExpr
dsExplicitList XExplicitList GhcTc
Type
elt_ty [LHsExpr GhcTc]
xs

dsExpr (ArithSeq XArithSeq GhcTc
expr Maybe (SyntaxExpr GhcTc)
witness ArithSeqInfo GhcTc
seq)
  = case Maybe (SyntaxExpr GhcTc)
witness of
     Maybe (SyntaxExpr GhcTc)
Nothing -> HsExpr GhcTc -> ArithSeqInfo GhcTc -> DsM CoreExpr
dsArithSeq XArithSeq GhcTc
HsExpr GhcTc
expr ArithSeqInfo GhcTc
seq
     Just SyntaxExpr GhcTc
fl -> do { newArithSeq <- HsExpr GhcTc -> ArithSeqInfo GhcTc -> DsM CoreExpr
dsArithSeq XArithSeq GhcTc
HsExpr GhcTc
expr ArithSeqInfo GhcTc
seq
                   ; dsSyntaxExpr fl [newArithSeq] }

{- Note [Desugaring static pointers]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
See Note [Grand plan for static forms] in GHC.Iface.Tidy.StaticPtrTable
for an overview.
    g = ... static f ...
==>
    g = ... makeStatic loc f ...
-}

dsExpr (HsStatic (NameSet
_, Type
whole_ty) expr :: LHsExpr GhcTc
expr@(L SrcSpanAnnA
loc HsExpr GhcTc
_))
  = do { expr_ds <- LHsExpr GhcTc -> DsM CoreExpr
dsLExpr LHsExpr GhcTc
expr
       ; let (_, [ty]) = splitTyConApp whole_ty
       ; makeStaticId <- dsLookupGlobalId makeStaticName

       ; dflags <- getDynFlags
       ;  let platform = DynFlags -> Platform
targetPlatform DynFlags
dflags
              (line, col) = case locA loc of
                  RealSrcSpan RealSrcSpan
r Maybe BufSpan
_ -> ( RealSrcLoc -> Int
srcLocLine (RealSrcLoc -> Int) -> RealSrcLoc -> Int
forall a b. (a -> b) -> a -> b
$ RealSrcSpan -> RealSrcLoc
realSrcSpanStart RealSrcSpan
r
                                     , RealSrcLoc -> Int
srcLocCol  (RealSrcLoc -> Int) -> RealSrcLoc -> Int
forall a b. (a -> b) -> a -> b
$ RealSrcSpan -> RealSrcLoc
realSrcSpanStart RealSrcSpan
r )
                  SrcSpan
_               -> (Int
0, Int
0)
              srcLoc = [CoreExpr] -> CoreExpr
mkCoreTup [ Platform -> Int -> CoreExpr
mkIntExprInt Platform
platform Int
line
                                 , Platform -> Int -> CoreExpr
mkIntExprInt Platform
platform Int
col
                                 ]

       ; putSrcSpanDsA loc $ return $
         mkCoreApps (Var makeStaticId) [ Type ty, srcLoc, expr_ds ] }

{- Note [Desugaring record construction]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
For record construction we do this (assuming T has three arguments)
\begin{verbatim}
        T { op2 = e }
==>
        let err = /\a -> recConError a
        T (recConError t1 "M.hs/230/op1")
          e
          (recConError t1 "M.hs/230/op3")
\end{verbatim}
@recConError@ then converts its argument string into a proper message
before printing it as
\begin{verbatim}
        M.hs, line 230: missing field op1 was evaluated
\end{verbatim}

We also handle @C{}@ as valid construction syntax for an unlabelled
constructor @C@, setting all of @C@'s fields to bottom.
-}

dsExpr (RecordCon { rcon_con :: forall p. HsExpr p -> XRec p (ConLikeP p)
rcon_con  = L SrcSpanAnnN
_ ConLike
con_like
                  , rcon_flds :: forall p. HsExpr p -> HsRecordBinds p
rcon_flds = HsRecordBinds GhcTc
rbinds
                  , rcon_ext :: forall p. HsExpr p -> XRecordCon p
rcon_ext  = XRecordCon GhcTc
con_expr })
-- See Note [Desugaring record construction]
  = do { con_expr' <- HsExpr GhcTc -> DsM CoreExpr
dsExpr XRecordCon GhcTc
HsExpr GhcTc
con_expr
       ; let
             (arg_tys, _) = tcSplitFunTys (exprType con_expr')
             -- A newtype in the corner should be opaque;
             -- hence TcType.tcSplitFunTys

             mk_arg (Type
arg_ty, FieldLabel
fl)
               = case [LHsRecField GhcTc (LocatedA (HsExpr GhcTc))]
-> Name -> [LocatedA (HsExpr GhcTc)]
forall arg. [LHsRecField GhcTc arg] -> Name -> [arg]
findField (HsRecFields GhcTc (LocatedA (HsExpr GhcTc))
-> [LHsRecField GhcTc (LocatedA (HsExpr GhcTc))]
forall p arg. HsRecFields p arg -> [LHsRecField p arg]
rec_flds HsRecordBinds GhcTc
HsRecFields GhcTc (LocatedA (HsExpr GhcTc))
rbinds) (FieldLabel -> Name
flSelector FieldLabel
fl) of
                   (LocatedA (HsExpr GhcTc)
rhs:[LocatedA (HsExpr GhcTc)]
rhss) -> Bool
-> (LocatedA (HsExpr GhcTc) -> DsM CoreExpr)
-> LocatedA (HsExpr GhcTc)
-> DsM CoreExpr
forall a. HasCallStack => Bool -> a -> a
assert ([LocatedA (HsExpr GhcTc)] -> Bool
forall a. [a] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null [LocatedA (HsExpr GhcTc)]
rhss)
                                 LHsExpr GhcTc -> DsM CoreExpr
LocatedA (HsExpr GhcTc) -> DsM CoreExpr
dsLExpr LocatedA (HsExpr GhcTc)
rhs
                   []         -> EvId -> Type -> SDoc -> DsM CoreExpr
mkErrorAppDs EvId
rEC_CON_ERROR_ID Type
arg_ty (FieldLabelString -> SDoc
forall a. Outputable a => a -> SDoc
ppr (FieldLabel -> FieldLabelString
flLabel FieldLabel
fl))
             unlabelled_bottom Type
arg_ty = EvId -> Type -> SDoc -> DsM CoreExpr
mkErrorAppDs EvId
rEC_CON_ERROR_ID Type
arg_ty SDoc
forall doc. IsOutput doc => doc
Outputable.empty

             labels = ConLike -> [FieldLabel]
conLikeFieldLabels ConLike
con_like

       ; con_args <- if null labels
                     then mapM unlabelled_bottom (map scaledThing arg_tys)
                     else mapM mk_arg (zipEqual "dsExpr:RecordCon" (map scaledThing arg_tys) labels)

       ; return (mkCoreApps con_expr' con_args) }


-- Here is where we desugar the Template Haskell brackets and escapes

-- Template Haskell stuff
-- See Note [The life cycle of a TH quotation]

dsExpr (HsTypedBracket   XTypedBracket GhcTc
bracket_tc LHsExpr GhcTc
_) = HsBracketTc -> DsM CoreExpr
dsBracket XTypedBracket GhcTc
HsBracketTc
bracket_tc
dsExpr (HsUntypedBracket XUntypedBracket GhcTc
bracket_tc HsQuote GhcTc
_) = HsBracketTc -> DsM CoreExpr
dsBracket XUntypedBracket GhcTc
HsBracketTc
bracket_tc
dsExpr (HsTypedSplice   XTypedSplice GhcTc
_   LHsExpr GhcTc
s) = String -> SDoc -> DsM CoreExpr
forall a. HasCallStack => String -> SDoc -> a
pprPanic String
"dsExpr:typed splice" (Maybe Name -> LHsExpr GhcTc -> SDoc
forall (p :: Pass).
OutputableBndrId p =>
Maybe Name -> LHsExpr (GhcPass p) -> SDoc
pprTypedSplice Maybe Name
forall a. Maybe a
Nothing LHsExpr GhcTc
s)
dsExpr (HsUntypedSplice XUntypedSplice GhcTc
ext HsUntypedSplice GhcTc
_) = DataConCantHappen -> DsM CoreExpr
forall a. DataConCantHappen -> a
dataConCantHappen XUntypedSplice GhcTc
DataConCantHappen
ext

-- Arrow notation extension
dsExpr (HsProc XProc GhcTc
_ LPat GhcTc
pat LHsCmdTop GhcTc
cmd) = LPat GhcTc -> LHsCmdTop GhcTc -> DsM CoreExpr
dsProcExpr LPat GhcTc
pat LHsCmdTop GhcTc
cmd

-- HsSyn constructs that just shouldn't be here, because
-- the renamer or typechecker removed them.  See GHC.Rename.Expr.
-- Note [Handling overloaded and rebindable constructs]
dsExpr (HsIPVar XIPVar GhcTc
x HsIPName
_)      = DataConCantHappen -> DsM CoreExpr
forall a. DataConCantHappen -> a
dataConCantHappen XIPVar GhcTc
DataConCantHappen
x
dsExpr (HsGetField XGetField GhcTc
x LHsExpr GhcTc
_ XRec GhcTc (DotFieldOcc GhcTc)
_) = DataConCantHappen -> DsM CoreExpr
forall a. DataConCantHappen -> a
dataConCantHappen XGetField GhcTc
DataConCantHappen
x
dsExpr (HsProjection XProjection GhcTc
x NonEmpty (DotFieldOcc GhcTc)
_) = DataConCantHappen -> DsM CoreExpr
forall a. DataConCantHappen -> a
dataConCantHappen XProjection GhcTc
DataConCantHappen
x
dsExpr (RecordUpd XRecordUpd GhcTc
x LHsExpr GhcTc
_ LHsRecUpdFields GhcTc
_)  = DataConCantHappen -> DsM CoreExpr
forall a. DataConCantHappen -> a
dataConCantHappen XRecordUpd GhcTc
DataConCantHappen
x
dsExpr (HsEmbTy XEmbTy GhcTc
x LHsWcType (NoGhcTc GhcTc)
_)      = DataConCantHappen -> DsM CoreExpr
forall a. DataConCantHappen -> a
dataConCantHappen XEmbTy GhcTc
DataConCantHappen
x
dsExpr (HsQual XQual GhcTc
x XRec GhcTc [LHsExpr GhcTc]
_ LHsExpr GhcTc
_)     = DataConCantHappen -> DsM CoreExpr
forall a. DataConCantHappen -> a
dataConCantHappen XQual GhcTc
DataConCantHappen
x
dsExpr (HsForAll XForAll GhcTc
x HsForAllTelescope GhcTc
_ LHsExpr GhcTc
_)   = DataConCantHappen -> DsM CoreExpr
forall a. DataConCantHappen -> a
dataConCantHappen XForAll GhcTc
DataConCantHappen
x
dsExpr (HsFunArr XFunArr GhcTc
x HsArrowOf (LHsExpr GhcTc) GhcTc
_ LHsExpr GhcTc
_ LHsExpr GhcTc
_) = DataConCantHappen -> DsM CoreExpr
forall a. DataConCantHappen -> a
dataConCantHappen XFunArr GhcTc
DataConCantHappen
x
dsExpr (HsOverLabel XOverLabel GhcTc
x FastString
_)  = DataConCantHappen -> DsM CoreExpr
forall a. DataConCantHappen -> a
dataConCantHappen XOverLabel GhcTc
DataConCantHappen
x
dsExpr (OpApp XOpApp GhcTc
x LHsExpr GhcTc
_ LHsExpr GhcTc
_ LHsExpr GhcTc
_)    = DataConCantHappen -> DsM CoreExpr
forall a. DataConCantHappen -> a
dataConCantHappen XOpApp GhcTc
DataConCantHappen
x
dsExpr (SectionL XSectionL GhcTc
x LHsExpr GhcTc
_ LHsExpr GhcTc
_)   = DataConCantHappen -> DsM CoreExpr
forall a. DataConCantHappen -> a
dataConCantHappen XSectionL GhcTc
DataConCantHappen
x
dsExpr (SectionR XSectionR GhcTc
x LHsExpr GhcTc
_ LHsExpr GhcTc
_)   = DataConCantHappen -> DsM CoreExpr
forall a. DataConCantHappen -> a
dataConCantHappen XSectionR GhcTc
DataConCantHappen
x


{- *********************************************************************
*                                                                      *
*              Desugaring applications
*                                                                      *
********************************************************************* -}

{- Note [Desugaring applications]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
When we come across an application (f e1 .. en) we collect up
all the desugared arguments, and then dispatch on the function f.
(Including the nullary case where n=0.)

There are several special cases to handle

* HsRecSel: a record selector gets warnings if it might fail.
* HsVar:    special magic for `noinline`
* HsVar:    special magic for `seq`

Note [Desugaring seq]
~~~~~~~~~~~~~~~~~~~~~
There are a few subtleties in the desugaring of `seq`, all
implemented in the `seqId` case of `ds_app_var`:

 1. (as described in #1031)

    Consider,
       f x y = x `seq` (y `seq` (# x,y #))

    Because the argument to the outer 'seq' has an unlifted type, we'll use
    call-by-value, and compile it as if we had

       f x y = case (y `seq` (# x,y #)) of v -> x `seq` v

    But that is bad, because we now evaluate y before x!

    Seq is very, very special!  So we recognise it right here, and desugar to
            case x of _ -> case y of _ -> (# x,y #)

 2. (as described in #2273)

    Consider
       let chp = case b of { True -> fst x; False -> 0 }
       in chp `seq` ...chp...
    Here the seq is designed to plug the space leak of retaining (snd x)
    for too long.

    If we rely on the ordinary inlining of seq, we'll get
       let chp = case b of { True -> fst x; False -> 0 }
       case chp of _ { I# -> ...chp... }

    But since chp is cheap, and the case is an alluring context, we'll
    inline chp into the case scrutinee.  Now there is only one use of chp,
    so we'll inline a second copy.  Alas, we've now ruined the purpose of
    the seq, by re-introducing the space leak:
        case (case b of {True -> fst x; False -> 0}) of
          I# _ -> ...case b of {True -> fst x; False -> 0}...

    We can try to avoid doing this by ensuring that the binder-swap in the
    case happens, so we get this at an early stage:
       case chp of chp2 { I# -> ...chp2... }
    But this is fragile.  The real culprit is the source program.  Perhaps we
    should have said explicitly
       let !chp2 = chp in ...chp2...

    But that's painful.  So the code here does a little hack to make seq
    more robust: a saturated application of 'seq' is turned *directly* into
    the case expression, thus:
       x  `seq` e2 ==> case x of x -> e2    -- Note shadowing!
       e1 `seq` e2 ==> case x of _ -> e2

    So we desugar our example to:
       let chp = case b of { True -> fst x; False -> 0 }
       case chp of chp { I# -> ...chp... }
    And now all is well.

    The reason it's a hack is because if you define mySeq=seq, the hack
    won't work on mySeq.

 3. (as described in #2409)

    The isInternalName ensures that we don't turn
            True `seq` e
    into
            case True of True { ... }
    which stupidly tries to bind the datacon 'True'.
-}

dsApp :: HsExpr GhcTc -> DsM CoreExpr
dsApp :: HsExpr GhcTc -> DsM CoreExpr
dsApp HsExpr GhcTc
e = HsExpr GhcTc -> [LHsExpr GhcTc] -> [CoreExpr] -> DsM CoreExpr
ds_app HsExpr GhcTc
e [] []

----------------------
ds_lapp :: LHsExpr GhcTc -> [LHsExpr GhcTc] -> [CoreExpr] -> DsM CoreExpr
-- The [LHsExpr] args correspond to the [CoreExpr] args,
-- but there may be more of the latter because they include
-- type and dictionary arguments
ds_lapp :: LHsExpr GhcTc -> [LHsExpr GhcTc] -> [CoreExpr] -> DsM CoreExpr
ds_lapp (L SrcSpanAnnA
loc HsExpr GhcTc
e) [LHsExpr GhcTc]
hs_args [CoreExpr]
core_args
  = SrcSpanAnnA -> DsM CoreExpr -> DsM CoreExpr
forall ann a. EpAnn ann -> DsM a -> DsM a
putSrcSpanDsA SrcSpanAnnA
loc (DsM CoreExpr -> DsM CoreExpr) -> DsM CoreExpr -> DsM CoreExpr
forall a b. (a -> b) -> a -> b
$
    HsExpr GhcTc -> [LHsExpr GhcTc] -> [CoreExpr] -> DsM CoreExpr
ds_app HsExpr GhcTc
e [LHsExpr GhcTc]
hs_args [CoreExpr]
core_args

ds_app :: HsExpr GhcTc -> [LHsExpr GhcTc] -> [CoreExpr] -> DsM CoreExpr
-- The work-horse
ds_app :: HsExpr GhcTc -> [LHsExpr GhcTc] -> [CoreExpr] -> DsM CoreExpr
ds_app (HsPar XPar GhcTc
_ LHsExpr GhcTc
e) [LHsExpr GhcTc]
hs_args [CoreExpr]
core_args = LHsExpr GhcTc -> [LHsExpr GhcTc] -> [CoreExpr] -> DsM CoreExpr
ds_lapp LHsExpr GhcTc
e [LHsExpr GhcTc]
hs_args [CoreExpr]
core_args

ds_app (HsApp XApp GhcTc
_ LHsExpr GhcTc
fun LHsExpr GhcTc
arg) [LHsExpr GhcTc]
hs_args [CoreExpr]
core_args
  = do { core_arg <- LHsExpr GhcTc -> DsM CoreExpr
dsLExpr LHsExpr GhcTc
arg
       ; ds_lapp fun (arg : hs_args) (core_arg : core_args) }

ds_app (HsAppType XAppTypeE GhcTc
arg_ty LHsExpr GhcTc
fun LHsWcType (NoGhcTc GhcTc)
_) [LHsExpr GhcTc]
hs_args [CoreExpr]
core_args
  = LHsExpr GhcTc -> [LHsExpr GhcTc] -> [CoreExpr] -> DsM CoreExpr
ds_lapp LHsExpr GhcTc
fun [LHsExpr GhcTc]
hs_args (Type -> CoreExpr
forall b. Type -> Expr b
Type XAppTypeE GhcTc
Type
arg_ty CoreExpr -> [CoreExpr] -> [CoreExpr]
forall a. a -> [a] -> [a]
: [CoreExpr]
core_args)

ds_app (XExpr (WrapExpr HsWrapper
hs_wrap HsExpr GhcTc
fun)) [LHsExpr GhcTc]
hs_args [CoreExpr]
core_args
  = do { (fun_wrap, all_args) <- HsWrapper -> [CoreExpr] -> DsM (HsWrapper, [CoreExpr])
splitHsWrapperArgs HsWrapper
hs_wrap [CoreExpr]
core_args
       ; if isIdHsWrapper fun_wrap
         then ds_app fun hs_args all_args
         else do { core_fun <- dsHsWrapper fun_wrap $ \CoreExpr -> CoreExpr
core_wrap ->
                               do { core_fun <- HsExpr GhcTc -> DsM CoreExpr
dsExpr HsExpr GhcTc
fun
                                  ; return (core_wrap core_fun) }
                 ; return (mkCoreApps core_fun all_args) } }

ds_app (XExpr (ConLikeTc ConLike
con [EvId]
tvs [Scaled Type]
tys)) [LHsExpr GhcTc]
_hs_args [CoreExpr]
core_args
-- Desugar desugars 'ConLikeTc': it eta-expands
-- data constructors to make linear types work.
-- See Note [Typechecking data constructors] in GHC.Tc.Gen.Head
  = do { ds_con <- ConLike -> DsM CoreExpr
dsHsConLike ConLike
con
       ; ids    <- newSysLocalsDs tys
           -- NB: these 'Id's may be representation-polymorphic;
           -- see Wrinkle [Representation-polymorphic lambda] in
           -- Note [Typechecking data constructors] in GHC.Tc.Gen.Head.
       ; let core_fun = [EvId] -> CoreExpr -> CoreExpr
forall b. [b] -> Expr b -> Expr b
mkLams [EvId]
tvs (CoreExpr -> CoreExpr) -> CoreExpr -> CoreExpr
forall a b. (a -> b) -> a -> b
$ [EvId] -> CoreExpr -> CoreExpr
forall b. [b] -> Expr b -> Expr b
mkLams [EvId]
ids (CoreExpr -> CoreExpr) -> CoreExpr -> CoreExpr
forall a b. (a -> b) -> a -> b
$
                        CoreExpr
ds_con CoreExpr -> [Type] -> CoreExpr
forall b. Expr b -> [Type] -> Expr b
`mkTyApps` [EvId] -> [Type]
mkTyVarTys [EvId]
tvs
                               CoreExpr -> [EvId] -> CoreExpr
forall b. Expr b -> [EvId] -> Expr b
`mkVarApps` [EvId]
ids
       ; return (mkApps core_fun core_args) }

ds_app (XExpr (HsRecSelTc (FieldOcc { foLabel :: forall pass. FieldOcc pass -> LIdP pass
foLabel = L SrcSpanAnnN
_ EvId
sel_id }))) [LHsExpr GhcTc]
_hs_args [CoreExpr]
core_args
  = EvId -> EvId -> [CoreExpr] -> DsM CoreExpr
ds_app_rec_sel EvId
sel_id EvId
sel_id [CoreExpr]
core_args

ds_app (HsVar XVar GhcTc
_ LIdP GhcTc
lfun) [LHsExpr GhcTc]
hs_args [CoreExpr]
core_args
  = do { String -> SDoc -> IOEnv (Env DsGblEnv DsLclEnv) ()
tracePm String
"ds_app" (GenLocated SrcSpanAnnN EvId -> SDoc
forall a. Outputable a => a -> SDoc
ppr LIdP GhcTc
GenLocated SrcSpanAnnN EvId
lfun SDoc -> SDoc -> SDoc
forall doc. IsLine doc => doc -> doc -> doc
<+> [CoreExpr] -> SDoc
forall a. Outputable a => a -> SDoc
ppr [CoreExpr]
core_args)
       ; GenLocated SrcSpanAnnN EvId
-> [LHsExpr GhcTc] -> [CoreExpr] -> DsM CoreExpr
ds_app_var LIdP GhcTc
GenLocated SrcSpanAnnN EvId
lfun [LHsExpr GhcTc]
hs_args [CoreExpr]
core_args }

ds_app HsExpr GhcTc
e [LHsExpr GhcTc]
_hs_args [CoreExpr]
core_args
  = do { core_e <- HsExpr GhcTc -> DsM CoreExpr
dsExpr HsExpr GhcTc
e
       ; return (mkCoreApps core_e core_args) }

---------------
ds_app_var :: LocatedN Id -> [LHsExpr GhcTc] -> [CoreExpr] -> DsM CoreExpr
-- Desugar an application with HsVar at the head
ds_app_var :: GenLocated SrcSpanAnnN EvId
-> [LHsExpr GhcTc] -> [CoreExpr] -> DsM CoreExpr
ds_app_var (L SrcSpanAnnN
loc EvId
fun_id) [LHsExpr GhcTc]
hs_args [CoreExpr]
core_args

  -----------------------
  -- Deal with getField applications. General form:
  --   getField
  --     @GHC.Types.Symbol                        {k}
  --     @"sel"                                   x_ty
  --     @T                                       r_ty
  --     @Int                                     a_ty
  --     ($dHasField :: HasField "sel" T Int)     dict
  --     :: T -> Int
  -- where
  --  $dHasField = sel |> (co :: T -> Int ~R# HasField "sel" T Int)
  -- Alas, we cannot simply look at the unfolding of $dHasField below because it
  -- has not been set yet, so we have to reconstruct the selector Id from the types.
  | EvId
fun_id EvId -> Unique -> Bool
forall a. Uniquable a => a -> Unique -> Bool
`hasKey` Unique
getFieldClassOpKey
  = do {  -- Look up the field named x/"sel" in the type r/T
         fam_inst_envs <- DsM FamInstEnvs
dsGetFamInstEnvs
       ; rdr_env       <- dsGetGlobalRdrEnv
       ; let core_arg_tys :: [Type] = [ty | Type ty <- core_args]
       ; case lookupHasFieldLabel fam_inst_envs rdr_env core_arg_tys of
           Just (Name
sel_name,GlobalRdrElt
_,Type
_,Type
_)
             -> do { sel_id <- Name -> DsM EvId
dsLookupGlobalId Name
sel_name
                   ; tracePm "getfield2" (ppr sel_id)
                   ; ds_app_rec_sel sel_id fun_id core_args }
           Maybe (Name, GlobalRdrElt, Type, Type)
_ -> EvId -> [CoreExpr] -> DsM CoreExpr
ds_app_finish EvId
fun_id [CoreExpr]
core_args }

  -----------------------
  -- Warn about identities for (fromInteger :: Integer -> Integer) etc
  -- They all have a type like:  forall <tvs>. <cxt> => arg_ty -> res_ty
  | EvId -> Name
idName EvId
fun_id Name -> [Name] -> Bool
forall a. Eq a => a -> [a] -> Bool
forall (t :: * -> *) a. (Foldable t, Eq a) => a -> t a -> Bool
`elem` [Name]
numericConversionNames
  , let (Type
conv_ty, [CoreExpr]
_) = EvId -> [CoreExpr] -> (Type, [CoreExpr])
apply_invis_args EvId
fun_id [CoreExpr]
core_args
  , Just (Type
arg_ty, Type
res_ty) <- Type -> Maybe (Type, Type)
splitVisibleFunTy_maybe Type
conv_ty
  = do { dflags <- IOEnv (Env DsGblEnv DsLclEnv) DynFlags
forall (m :: * -> *). HasDynFlags m => m DynFlags
getDynFlags
       ; when (wopt Opt_WarnIdentities dflags
               && arg_ty `eqType` res_ty)  $
         -- So we are converting  ty -> ty
         diagnosticDs (DsIdentitiesFound fun_id conv_ty)

       ; ds_app_finish fun_id core_args }

  -----------------------
  -- Warn about unused return value in
  --    do { ...; e; ... } when e returns (say) an Int
  | EvId
fun_id EvId -> Unique -> Bool
forall a. Uniquable a => a -> Unique -> Bool
`hasKey` Unique
thenMClassOpKey    -- It is the built-in Prelude.(>>)
    -- (>>) :: forall m. Monad m => forall a b. m a -> (b->m b) -> m b
  , Type Type
m_ty : CoreExpr
_dict : Type Type
arg_ty : [CoreExpr]
_ <- [CoreExpr]
core_args
  , LHsExpr GhcTc
hs_arg : [LHsExpr GhcTc]
_ <- [LHsExpr GhcTc]
hs_args
  = do { String -> SDoc -> IOEnv (Env DsGblEnv DsLclEnv) ()
tracePm String
">>" (SrcSpanAnnN -> SDoc
forall a. Outputable a => a -> SDoc
ppr SrcSpanAnnN
loc SDoc -> SDoc -> SDoc
forall doc. IsDoc doc => doc -> doc -> doc
$$ Type -> SDoc
forall a. Outputable a => a -> SDoc
ppr Type
arg_ty SDoc -> SDoc -> SDoc
forall doc. IsDoc doc => doc -> doc -> doc
$$ Bool -> SDoc
forall a. Outputable a => a -> SDoc
ppr (SrcSpan -> Bool
isGeneratedSrcSpan (SrcSpanAnnN -> SrcSpan
forall a. HasLoc a => a -> SrcSpan
locA SrcSpanAnnN
loc)))
       ; Bool
-> IOEnv (Env DsGblEnv DsLclEnv) ()
-> IOEnv (Env DsGblEnv DsLclEnv) ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
when (SrcSpan -> Bool
isGeneratedSrcSpan (SrcSpanAnnN -> SrcSpan
forall a. HasLoc a => a -> SrcSpan
locA SrcSpanAnnN
loc)) (IOEnv (Env DsGblEnv DsLclEnv) ()
 -> IOEnv (Env DsGblEnv DsLclEnv) ())
-> IOEnv (Env DsGblEnv DsLclEnv) ()
-> IOEnv (Env DsGblEnv DsLclEnv) ()
forall a b. (a -> b) -> a -> b
$      -- It is a compiler-generated (>>)
         LHsExpr GhcTc -> Type -> Type -> IOEnv (Env DsGblEnv DsLclEnv) ()
warnDiscardedDoBindings LHsExpr GhcTc
hs_arg Type
m_ty Type
arg_ty
       ; EvId -> [CoreExpr] -> DsM CoreExpr
ds_app_finish EvId
fun_id [CoreExpr]
core_args }

  -----------------------
  -- Deal with `noinline`
  -- See Note [noinlineId magic] in GHC.Types.Id.Make
  | EvId
fun_id EvId -> Unique -> Bool
forall a. Uniquable a => a -> Unique -> Bool
`hasKey` Unique
noinlineIdKey
  , Type Type
_ : CoreExpr
arg1 : [CoreExpr]
rest_args <- [CoreExpr]
core_args
  , (CoreExpr
inner_fun, [CoreExpr]
inner_args) <- CoreExpr -> (CoreExpr, [CoreExpr])
forall b. Expr b -> (Expr b, [Expr b])
collectArgs CoreExpr
arg1
  = CoreExpr -> DsM CoreExpr
forall a. a -> IOEnv (Env DsGblEnv DsLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return (EvId -> CoreExpr
forall b. EvId -> Expr b
Var EvId
fun_id CoreExpr -> CoreExpr -> CoreExpr
forall b. Expr b -> Expr b -> Expr b
`App` Type -> CoreExpr
forall b. Type -> Expr b
Type (HasDebugCallStack => CoreExpr -> Type
CoreExpr -> Type
exprType CoreExpr
inner_fun) CoreExpr -> CoreExpr -> CoreExpr
forall b. Expr b -> Expr b -> Expr b
`App` CoreExpr
inner_fun
            CoreExpr -> [CoreExpr] -> CoreExpr
`mkCoreApps` [CoreExpr]
inner_args CoreExpr -> [CoreExpr] -> CoreExpr
`mkCoreApps` [CoreExpr]
rest_args)

  -----------------------
  -- Deal with `seq`
  -- See Note [Desugaring seq], points (1) and (2)
  | EvId
fun_id EvId -> Unique -> Bool
forall a. Uniquable a => a -> Unique -> Bool
`hasKey` Unique
seqIdKey
  , Type Type
_r : Type Type
ty1 : Type Type
ty2 : CoreExpr
arg1 : CoreExpr
arg2 : [CoreExpr]
rest_args <- [CoreExpr]
core_args
  , let case_bndr :: EvId
case_bndr = case CoreExpr
arg1 of
            Var EvId
v1 | Name -> Bool
isInternalName (EvId -> Name
idName EvId
v1)
                  -> EvId
v1        -- Note [Desugaring seq], points (2) and (3)
            CoreExpr
_     -> Type -> Type -> EvId
mkWildValBinder Type
ManyTy Type
ty1
  = CoreExpr -> DsM CoreExpr
forall a. a -> IOEnv (Env DsGblEnv DsLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return (CoreExpr -> EvId -> Type -> [Alt EvId] -> CoreExpr
forall b. Expr b -> b -> Type -> [Alt b] -> Expr b
Case CoreExpr
arg1 EvId
case_bndr Type
ty2 [AltCon -> [EvId] -> CoreExpr -> Alt EvId
forall b. AltCon -> [b] -> Expr b -> Alt b
Alt AltCon
DEFAULT [] CoreExpr
arg2]
            CoreExpr -> [CoreExpr] -> CoreExpr
`mkCoreApps` [CoreExpr]
rest_args)

  -----------------------
  -- Phew!  No more special cases.  Just build an applications
  | Bool
otherwise
  = EvId -> [CoreExpr] -> DsM CoreExpr
ds_app_finish EvId
fun_id [CoreExpr]
core_args

---------------
ds_app_finish :: Id -> [CoreExpr] -> DsM CoreExpr
-- We are about to construct an application that may include evidence applications
-- `f dict`.  If the dictionary is non-specialisable, instead construct
--     nospec f dict
-- See Note [nospecId magic] in GHC.Types.Id.Make for what `nospec` does.
-- See Note [Desugaring non-canonical evidence]
ds_app_finish :: EvId -> [CoreExpr] -> DsM CoreExpr
ds_app_finish EvId
fun_id [CoreExpr]
core_args
  = do { unspecables <- DsM (Set EvId)
getUnspecables
       ; let fun_ty = EvId -> Type
idType EvId
fun_id
             free_dicts = [CoreExpr] -> [EvId]
exprsFreeVarsList
                            [ CoreExpr
e | (CoreExpr
e,PiTyBinder
pi_bndr) <- [CoreExpr]
core_args [CoreExpr] -> [PiTyBinder] -> [(CoreExpr, PiTyBinder)]
forall a b. [a] -> [b] -> [(a, b)]
`zip` ([PiTyBinder], Type) -> [PiTyBinder]
forall a b. (a, b) -> a
fst (Type -> ([PiTyBinder], Type)
splitPiTys Type
fun_ty)
                                , PiTyBinder -> Bool
isInvisibleAnonPiTyBinder PiTyBinder
pi_bndr ]
             is_unspecable_var EvId
v = EvId
v EvId -> Set EvId -> Bool
forall a. Ord a => a -> Set a -> Bool
`S.member` Set EvId
unspecables

             fun | Bool -> Bool
not (Set EvId -> Bool
forall a. Set a -> Bool
S.null Set EvId
unspecables)  -- Fast path
                 , (EvId -> Bool) -> [EvId] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
any (EvId -> Bool
is_unspecable_var) [EvId]
free_dicts
                 = EvId -> CoreExpr
forall b. EvId -> Expr b
Var EvId
nospecId CoreExpr -> CoreExpr -> CoreExpr
forall b. Expr b -> Expr b -> Expr b
`App` Type -> CoreExpr
forall b. Type -> Expr b
Type Type
fun_ty CoreExpr -> CoreExpr -> CoreExpr
forall b. Expr b -> Expr b -> Expr b
`App` EvId -> CoreExpr
forall b. EvId -> Expr b
Var EvId
fun_id
                 | Bool
otherwise
                 = EvId -> CoreExpr
forall b. EvId -> Expr b
Var EvId
fun_id

       ; return (mkCoreApps fun core_args) }

---------------
ds_app_rec_sel :: Id             -- The record selector Id itself
               -> Id             -- The function at the the head
               -> [CoreExpr]     -- Its arguments
               -> DsM CoreExpr
-- Desugar an application with HsRecSelId at the head
ds_app_rec_sel :: EvId -> EvId -> [CoreExpr] -> DsM CoreExpr
ds_app_rec_sel EvId
sel_id EvId
fun_id [CoreExpr]
core_args
  | RecSelId{ sel_cons :: IdDetails -> RecSelInfo
sel_cons = RecSelInfo
rec_sel_info } <- EvId -> IdDetails
idDetails EvId
sel_id
  , RSI { rsi_undef :: RecSelInfo -> [ConLike]
rsi_undef = [ConLike]
cons_wo_field } <- RecSelInfo
rec_sel_info
  = do { -- Record selectors are warned about if they are not present in all of the
         -- parent data type's constructors, or always in case of pattern synonym record
         -- selectors (regulated by a flag). However, this only produces a warning if
         -- it's not a part of a record selector application. For example:
         --         data T = T1 | T2 {s :: Bool}
         --         g y = map s y   -- Warn here
         --         f x = s x       -- No warning here
       ; let (Type
fun_ty, [CoreExpr]
val_args) = EvId -> [CoreExpr] -> (Type, [CoreExpr])
apply_invis_args EvId
fun_id [CoreExpr]
core_args

       ; String -> SDoc -> IOEnv (Env DsGblEnv DsLclEnv) ()
tracePm String
"ds_app_rec_sel" (Type -> SDoc
forall a. Outputable a => a -> SDoc
ppr Type
fun_ty SDoc -> SDoc -> SDoc
forall doc. IsDoc doc => doc -> doc -> doc
$$ [CoreExpr] -> SDoc
forall a. Outputable a => a -> SDoc
ppr [CoreExpr]
val_args)
       ; case [CoreExpr]
val_args of

           -- There is a value argument
           -- See (IRS2) of Note [Detecting incomplete record selectors] in GHC.HsToCore.Pmc
           (CoreExpr
arg:[CoreExpr]
_) -> EvId -> CoreExpr -> IOEnv (Env DsGblEnv DsLclEnv) ()
pmcRecSel EvId
sel_id CoreExpr
arg

           -- No value argument, but the selector is
           -- applied to all its type arguments
           -- See (IRS3) of Note [Detecting incomplete record selectors] in GHC.HsToCore.Pmc
           [] | Just (Type
val_arg_ty, Type
_) <- Type -> Maybe (Type, Type)
splitVisibleFunTy_maybe Type
fun_ty
              -> do { dummy <- Scaled Type -> DsM EvId
newSysLocalDs (Type -> Type -> Scaled Type
forall a. Type -> a -> Scaled a
Scaled Type
ManyTy Type
val_arg_ty)
                    ; pmcRecSel sel_id (Var dummy) }

           -- Not even applied to all its type args
           -- See (IRS4) of Note [Detecting incomplete record selectors] in GHC.HsToCore.Pmc
           [CoreExpr]
_ -> Bool
-> IOEnv (Env DsGblEnv DsLclEnv) ()
-> IOEnv (Env DsGblEnv DsLclEnv) ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
unless ([ConLike] -> Bool
forall a. [a] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null [ConLike]
cons_wo_field) (IOEnv (Env DsGblEnv DsLclEnv) ()
 -> IOEnv (Env DsGblEnv DsLclEnv) ())
-> IOEnv (Env DsGblEnv DsLclEnv) ()
-> IOEnv (Env DsGblEnv DsLclEnv) ()
forall a b. (a -> b) -> a -> b
$
                do { dflags <- IOEnv (Env DsGblEnv DsLclEnv) DynFlags
forall (m :: * -> *). HasDynFlags m => m DynFlags
getDynFlags
                   ; let maxCons = DynFlags -> Int
maxUncoveredPatterns DynFlags
dflags
                   ; diagnosticDs $ DsIncompleteRecordSelector (idName sel_id) cons_wo_field maxCons }

       ; EvId -> [CoreExpr] -> DsM CoreExpr
ds_app_finish EvId
fun_id [CoreExpr]
core_args }

  | Bool
otherwise
  = String -> SDoc -> DsM CoreExpr
forall a. HasCallStack => String -> SDoc -> a
pprPanic String
"ds_app_rec_sel" (EvId -> SDoc
forall a. Outputable a => a -> SDoc
ppr EvId
sel_id SDoc -> SDoc -> SDoc
forall doc. IsDoc doc => doc -> doc -> doc
$$ IdDetails -> SDoc
forall a. Outputable a => a -> SDoc
ppr (EvId -> IdDetails
idDetails EvId
sel_id))
  where

apply_invis_args :: Id -> [CoreExpr] -> (Type, [CoreExpr])
-- Apply function to the initial /type/ args;
-- return the type of the instantiated function,
-- and the remaining args
--   e.g.  apply_type_args (++) [Type Int, Var xs]
--         = ([Int] -> [Int] -> [Int], [Var xs])
apply_invis_args :: EvId -> [CoreExpr] -> (Type, [CoreExpr])
apply_invis_args EvId
fun_id [CoreExpr]
args
  = (HasDebugCallStack => Type -> [CoreExpr] -> Type
Type -> [CoreExpr] -> Type
applyTypeToArgs Type
fun_ty [CoreExpr]
invis_args, [CoreExpr]
rest_args)
  where
    fun_ty :: Type
fun_ty = EvId -> Type
idType EvId
fun_id
    ([CoreExpr]
invis_args, [CoreExpr]
rest_args) = Int -> [CoreExpr] -> ([CoreExpr], [CoreExpr])
forall a. Int -> [a] -> ([a], [a])
splitAt (Type -> Int
invisibleBndrCount Type
fun_ty) [CoreExpr]
args

------------------------------
splitHsWrapperArgs :: HsWrapper -> [CoreArg] -> DsM (HsWrapper, [CoreArg])
-- Splits the wrapper into the trailing arguments, and leftover bit
splitHsWrapperArgs :: HsWrapper -> [CoreExpr] -> DsM (HsWrapper, [CoreExpr])
splitHsWrapperArgs HsWrapper
wrap [CoreExpr]
args = HsWrapper -> [CoreExpr] -> DsM (HsWrapper, [CoreExpr])
go HsWrapper
wrap [CoreExpr]
args
  where
    go :: HsWrapper -> [CoreExpr] -> DsM (HsWrapper, [CoreExpr])
go (WpTyApp Type
ty) [CoreExpr]
args = (HsWrapper, [CoreExpr]) -> DsM (HsWrapper, [CoreExpr])
forall a. a -> IOEnv (Env DsGblEnv DsLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return (HsWrapper
WpHole, Type -> CoreExpr
forall b. Type -> Expr b
Type Type
ty CoreExpr -> [CoreExpr] -> [CoreExpr]
forall a. a -> [a] -> [a]
: [CoreExpr]
args)
    go (WpEvApp EvTerm
tm) [CoreExpr]
args = do { core_tm <- EvTerm -> DsM CoreExpr
dsEvTerm EvTerm
tm
                              ; return (WpHole, core_tm : args)}
    go (WpCompose HsWrapper
w1 HsWrapper
w2) [CoreExpr]
args
      = do { (w1', args') <- HsWrapper -> [CoreExpr] -> DsM (HsWrapper, [CoreExpr])
go HsWrapper
w1 [CoreExpr]
args
           ; if isIdHsWrapper w1'
             then go w2 args'
             else return (w1' <.> w2, args') }
    go HsWrapper
wrap [CoreExpr]
args = (HsWrapper, [CoreExpr]) -> DsM (HsWrapper, [CoreExpr])
forall a. a -> IOEnv (Env DsGblEnv DsLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return (HsWrapper
wrap, [CoreExpr]
args)

------------------------------
dsHsConLike :: ConLike -> DsM CoreExpr
dsHsConLike :: ConLike -> DsM CoreExpr
dsHsConLike (RealDataCon DataCon
dc)
  = CoreExpr -> DsM CoreExpr
forall a. a -> IOEnv (Env DsGblEnv DsLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return (EvId -> CoreExpr
forall b. EvId -> Expr b
varToCoreExpr (DataCon -> EvId
dataConWrapId DataCon
dc))
dsHsConLike (PatSynCon PatSyn
ps)
  | Just (Name
builder_name, Type
_, Bool
add_void) <- PatSyn -> Maybe (Name, Type, Bool)
patSynBuilder PatSyn
ps
  = do { builder_id <- Name -> DsM EvId
dsLookupGlobalId Name
builder_name
       ; return (if add_void
                 then mkCoreApp (text "dsConLike" <+> ppr ps)
                                (Var builder_id) unboxedUnitExpr
                 else Var builder_id) }
  | Bool
otherwise
  = String -> SDoc -> DsM CoreExpr
forall a. HasCallStack => String -> SDoc -> a
pprPanic String
"dsConLike" (PatSyn -> SDoc
forall a. Outputable a => a -> SDoc
ppr PatSyn
ps)

------------------------------
dsSyntaxExpr :: SyntaxExpr GhcTc -> [CoreExpr] -> DsM CoreExpr
dsSyntaxExpr :: SyntaxExpr GhcTc -> [CoreExpr] -> DsM CoreExpr
dsSyntaxExpr (SyntaxExprTc { syn_expr :: SyntaxExprTc -> HsExpr GhcTc
syn_expr      = HsExpr GhcTc
expr
                           , syn_arg_wraps :: SyntaxExprTc -> [HsWrapper]
syn_arg_wraps = [HsWrapper]
arg_wraps
                           , syn_res_wrap :: SyntaxExprTc -> HsWrapper
syn_res_wrap  = HsWrapper
res_wrap })
             [CoreExpr]
arg_exprs
  = do { fun <- HsExpr GhcTc -> DsM CoreExpr
dsExpr HsExpr GhcTc
expr
       ; dsHsWrappers arg_wraps $ \[CoreExpr -> CoreExpr]
core_arg_wraps ->
         HsWrapper
-> ((CoreExpr -> CoreExpr) -> DsM CoreExpr) -> DsM CoreExpr
forall a. HsWrapper -> ((CoreExpr -> CoreExpr) -> DsM a) -> DsM a
dsHsWrapper HsWrapper
res_wrap   (((CoreExpr -> CoreExpr) -> DsM CoreExpr) -> DsM CoreExpr)
-> ((CoreExpr -> CoreExpr) -> DsM CoreExpr) -> DsM CoreExpr
forall a b. (a -> b) -> a -> b
$ \CoreExpr -> CoreExpr
core_res_wrap ->
    do { let wrapped_args :: [CoreExpr]
wrapped_args = String
-> ((CoreExpr -> CoreExpr) -> CoreExpr -> CoreExpr)
-> [CoreExpr -> CoreExpr]
-> [CoreExpr]
-> [CoreExpr]
forall a b c.
HasDebugCallStack =>
String -> (a -> b -> c) -> [a] -> [b] -> [c]
zipWithEqual String
"dsSyntaxExpr" (CoreExpr -> CoreExpr) -> CoreExpr -> CoreExpr
forall a b. (a -> b) -> a -> b
($) [CoreExpr -> CoreExpr]
core_arg_wraps [CoreExpr]
arg_exprs
       ; CoreExpr -> DsM CoreExpr
forall a. a -> IOEnv (Env DsGblEnv DsLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return (CoreExpr -> DsM CoreExpr) -> CoreExpr -> DsM CoreExpr
forall a b. (a -> b) -> a -> b
$ CoreExpr -> CoreExpr
core_res_wrap (CoreExpr -> [CoreExpr] -> CoreExpr
mkCoreApps CoreExpr
fun [CoreExpr]
wrapped_args) } }
dsSyntaxExpr SyntaxExpr GhcTc
SyntaxExprTc
NoSyntaxExprTc [CoreExpr]
_ = String -> DsM CoreExpr
forall a. HasCallStack => String -> a
panic String
"dsSyntaxExpr"

findField :: [LHsRecField GhcTc arg] -> Name -> [arg]
findField :: forall arg. [LHsRecField GhcTc arg] -> Name -> [arg]
findField [LHsRecField GhcTc arg]
rbinds Name
sel
  = [HsFieldBind (GenLocated SrcSpanAnnA (FieldOcc GhcTc)) arg -> arg
forall lhs rhs. HsFieldBind lhs rhs -> rhs
hfbRHS HsFieldBind (GenLocated SrcSpanAnnA (FieldOcc GhcTc)) arg
fld | L SrcSpanAnnA
_ HsFieldBind (GenLocated SrcSpanAnnA (FieldOcc GhcTc)) arg
fld <- [LHsRecField GhcTc arg]
[GenLocated
   SrcSpanAnnA
   (HsFieldBind (GenLocated SrcSpanAnnA (FieldOcc GhcTc)) arg)]
rbinds
                , Name
sel Name -> Name -> Bool
forall a. Eq a => a -> a -> Bool
== EvId -> Name
idName (HsRecField GhcTc arg -> EvId
forall arg. HsRecField GhcTc arg -> EvId
hsRecFieldId HsRecField GhcTc arg
HsFieldBind (GenLocated SrcSpanAnnA (FieldOcc GhcTc)) arg
fld) ]

{-
%--------------------------------------------------------------------

Note [Desugaring non-canonical evidence]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
When constructing an application
    f @ty1 ty2 .. dict1 dict2 .. arg1 arg2 ..
if the evidence `dict_i` is canonical, we simply build that application.
But if any of the `dict_i` are /non-canonical/, we wrap the appication in `nospec`,
thus
    nospec @fty f @ty1 @ty2 .. dict1 dict2 .. arg1 arg2 ..
where  nospec :: forall a. a -> a  ensures that the typeclass specialiser
doesn't attempt to common up this evidence term with other evidence terms
of the same type (see Note [nospecId magic] in GHC.Types.Id.Make).

See Note [Coherence and specialisation: overview] in GHC.Core.InstEnv for
what a "non-canonical" dictionary is, and whe shouldn't specialise on it.

How do we decide if the arguments are non-canonical dictionaries?

* In `ds_app_finish` we look for dictionary arguments (invisible value args)

* In the DsM monad we track the "unspecables" (i.e. non-canonical dictionaries)
  in the `dsl_unspecable` field of `DsLclEnv`

* We extend that unspecable set via `addUnspecables`, in `dsEvBinds`.
  A dictionary is non-canonical if its own resolution was incoherent (see
  Note [Incoherent instances]), or if its definition refers to other non-canonical
  evidence. `dsEvBinds` is the convenient place to compute this, since it already
  needs to do inter-evidence dependency analysis to generate well-scoped
  bindings.

Wrinkle:

(NC1) We don't do this in the LHS of a RULE.  In paritcular, if we have
     f :: (Num a, HasCallStack) => a -> a
     {-# SPECIALISE f :: Int -> Int #-}
  then making a rule like
        RULE   forall d1:Num Int, d2:HasCallStack.
               f @Int d1 d2 = $sf
  is pretty dodgy, because $sf won't get the call stack passed in d2.
  But that's what you asked for in the SPECIALISE pragma, so we'll obey.

  We definitely can't desugar that LHS into this!
      nospec (f @Int d1) d2

  This is done by zapping the unspecables in `dsRule`.


Note [Desugaring explicit lists]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Explicit lists are desugared in a cleverer way to prevent some
fruitless allocations.  Essentially, whenever we see a list literal
[x_1, ..., x_n] we generate the corresponding expression in terms of
build:

Explicit lists (literals) are desugared to allow build/foldr fusion when
beneficial. This is a bit of a trade-off,

 * build/foldr fusion can generate far larger code than the corresponding
   cons-chain (e.g. see #11707)

 * even when it doesn't produce more code, build can still fail to fuse,
   requiring that the simplifier do more work to bring the expression
   back into cons-chain form; this costs compile time

 * when it works, fusion can be a significant win. Allocations are reduced
   by up to 25% in some nofib programs. Specifically,

        Program           Size    Allocs   Runtime  CompTime
        rewrite          +0.0%    -26.3%      0.02     -1.8%
           ansi          -0.3%    -13.8%      0.00     +0.0%
           lift          +0.0%     -8.7%      0.00     -2.3%

At the moment we use a simple heuristic to determine whether build will be
fruitful: for small lists we assume the benefits of fusion will be worthwhile;
for long lists we assume that the benefits will be outweighed by the cost of
code duplication. This magic length threshold is @maxBuildLength@. Also, fusion
won't work at all if rewrite rules are disabled, so we don't use the build-based
desugaring in this case.

We used to have a more complex heuristic which would try to break the list into
"static" and "dynamic" parts and only build-desugar the dynamic part.
Unfortunately, determining "static-ness" reliably is a bit tricky and the
heuristic at times produced surprising behavior (see #11710) so it was dropped.
-}

{- | The longest list length which we will desugar using @build@.

This is essentially a magic number and its setting is unfortunate rather
arbitrary. The idea here, as mentioned in Note [Desugaring explicit lists],
is to avoid deforesting large static data into large(r) code. Ideally we'd
want a smaller threshold with larger consumers and vice-versa, but we have no
way of knowing what will be consuming our list in the desugaring impossible to
set generally correctly.

The effect of reducing this number will be that 'build' fusion is applied
less often. From a runtime performance perspective, applying 'build' more
liberally on "moderately" sized lists should rarely hurt and will often it can
only expose further optimization opportunities; if no fusion is possible it will
eventually get rule-rewritten back to a list). We do, however, pay in compile
time.
-}
maxBuildLength :: Int
maxBuildLength :: Int
maxBuildLength = Int
32

dsExplicitList :: Type -> [LHsExpr GhcTc]
               -> DsM CoreExpr
-- See Note [Desugaring explicit lists]
dsExplicitList :: Type -> [LHsExpr GhcTc] -> DsM CoreExpr
dsExplicitList Type
elt_ty [LHsExpr GhcTc]
xs
  = do { dflags <- IOEnv (Env DsGblEnv DsLclEnv) DynFlags
forall (m :: * -> *). HasDynFlags m => m DynFlags
getDynFlags
       ; xs' <- mapM dsLExpr xs
       ; if xs' `lengthExceeds` maxBuildLength
                -- Don't generate builds if the list is very long.
         || null xs'
                -- Don't generate builds when the [] constructor will do
         || not (gopt Opt_EnableRewriteRules dflags)  -- Rewrite rules off
                -- Don't generate a build if there are no rules to eliminate it!
                -- See Note [Desugaring RULE left hand sides] in GHC.HsToCore
         then return $ mkListExpr elt_ty xs'
         else mkBuildExpr elt_ty (mk_build_list xs') }
  where
    mk_build_list :: t (Arg b) -> (EvId, b) -> (EvId, b) -> m (Arg b)
mk_build_list t (Arg b)
xs' (EvId
cons, b
_) (EvId
nil, b
_)
      = Arg b -> m (Arg b)
forall a. a -> m a
forall (m :: * -> *) a. Monad m => a -> m a
return ((Arg b -> Arg b -> Arg b) -> Arg b -> t (Arg b) -> Arg b
forall a b. (a -> b -> b) -> b -> t a -> b
forall (t :: * -> *) a b.
Foldable t =>
(a -> b -> b) -> b -> t a -> b
foldr (Arg b -> Arg b -> Arg b
forall b. Expr b -> Expr b -> Expr b
App (Arg b -> Arg b -> Arg b)
-> (Arg b -> Arg b) -> Arg b -> Arg b -> Arg b
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Arg b -> Arg b -> Arg b
forall b. Expr b -> Expr b -> Expr b
App (EvId -> Arg b
forall b. EvId -> Expr b
Var EvId
cons)) (EvId -> Arg b
forall b. EvId -> Expr b
Var EvId
nil) t (Arg b)
xs')

dsArithSeq :: PostTcExpr -> (ArithSeqInfo GhcTc) -> DsM CoreExpr
dsArithSeq :: HsExpr GhcTc -> ArithSeqInfo GhcTc -> DsM CoreExpr
dsArithSeq HsExpr GhcTc
expr (From LHsExpr GhcTc
from)
  = CoreExpr -> CoreExpr -> CoreExpr
forall b. Expr b -> Expr b -> Expr b
App (CoreExpr -> CoreExpr -> CoreExpr)
-> DsM CoreExpr
-> IOEnv (Env DsGblEnv DsLclEnv) (CoreExpr -> CoreExpr)
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> HsExpr GhcTc -> DsM CoreExpr
dsExpr HsExpr GhcTc
expr IOEnv (Env DsGblEnv DsLclEnv) (CoreExpr -> CoreExpr)
-> DsM CoreExpr -> DsM CoreExpr
forall a b.
IOEnv (Env DsGblEnv DsLclEnv) (a -> b)
-> IOEnv (Env DsGblEnv DsLclEnv) a
-> IOEnv (Env DsGblEnv DsLclEnv) b
forall (f :: * -> *) a b. Applicative f => f (a -> b) -> f a -> f b
<*> LHsExpr GhcTc -> DsM CoreExpr
dsLExpr LHsExpr GhcTc
from
dsArithSeq HsExpr GhcTc
expr (FromTo LHsExpr GhcTc
from LHsExpr GhcTc
to)
  = do fam_envs <- DsM FamInstEnvs
dsGetFamInstEnvs
       dflags <- getDynFlags
       warnAboutEmptyEnumerations fam_envs dflags from Nothing to
       expr' <- dsExpr expr
       from' <- dsLExpr from
       to'   <- dsLExpr to
       return $ mkApps expr' [from', to']
dsArithSeq HsExpr GhcTc
expr (FromThen LHsExpr GhcTc
from LHsExpr GhcTc
thn)
  = CoreExpr -> [CoreExpr] -> CoreExpr
forall b. Expr b -> [Expr b] -> Expr b
mkApps (CoreExpr -> [CoreExpr] -> CoreExpr)
-> DsM CoreExpr
-> IOEnv (Env DsGblEnv DsLclEnv) ([CoreExpr] -> CoreExpr)
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> HsExpr GhcTc -> DsM CoreExpr
dsExpr HsExpr GhcTc
expr IOEnv (Env DsGblEnv DsLclEnv) ([CoreExpr] -> CoreExpr)
-> IOEnv (Env DsGblEnv DsLclEnv) [CoreExpr] -> DsM CoreExpr
forall a b.
IOEnv (Env DsGblEnv DsLclEnv) (a -> b)
-> IOEnv (Env DsGblEnv DsLclEnv) a
-> IOEnv (Env DsGblEnv DsLclEnv) b
forall (f :: * -> *) a b. Applicative f => f (a -> b) -> f a -> f b
<*> (LocatedA (HsExpr GhcTc) -> DsM CoreExpr)
-> [LocatedA (HsExpr GhcTc)]
-> IOEnv (Env DsGblEnv DsLclEnv) [CoreExpr]
forall (t :: * -> *) (m :: * -> *) a b.
(Traversable t, Monad m) =>
(a -> m b) -> t a -> m (t b)
forall (m :: * -> *) a b. Monad m => (a -> m b) -> [a] -> m [b]
mapM LHsExpr GhcTc -> DsM CoreExpr
LocatedA (HsExpr GhcTc) -> DsM CoreExpr
dsLExpr [LHsExpr GhcTc
LocatedA (HsExpr GhcTc)
from, LHsExpr GhcTc
LocatedA (HsExpr GhcTc)
thn]
dsArithSeq HsExpr GhcTc
expr (FromThenTo LHsExpr GhcTc
from LHsExpr GhcTc
thn LHsExpr GhcTc
to)
  = do fam_envs <- DsM FamInstEnvs
dsGetFamInstEnvs
       dflags <- getDynFlags
       warnAboutEmptyEnumerations fam_envs dflags from (Just thn) to
       expr' <- dsExpr expr
       from' <- dsLExpr from
       thn'  <- dsLExpr thn
       to'   <- dsLExpr to
       return $ mkApps expr' [from', thn', to']

{-
Desugar 'do' and 'mdo' expressions (NOT list comprehensions, they're
handled in GHC.HsToCore.ListComp).  Basically does the translation given in the
Haskell 98 report:
-}

dsDo :: HsDoFlavour -> [ExprLStmt GhcTc] -> Type -> DsM CoreExpr
-- This code path seems inactive for regular Do,
--     which is expanded in GHC.Tc.Gen.Do.
-- It is used only for ApplicativeDo (even the BindStmt case), which is *very*
--     annoying because it is a lot of duplicated code that is seldomly tested.
-- But we are on course to expane Applicative in GHC.Tc.Gen.Do, at which
-- point all this will go away
dsDo :: HsDoFlavour -> [ExprLStmt GhcTc] -> Type -> DsM CoreExpr
dsDo HsDoFlavour
ctx [ExprLStmt GhcTc]
stmts Type
res_ty
  = [GenLocated
   SrcSpanAnnA (StmtLR GhcTc GhcTc (LocatedA (HsExpr GhcTc)))]
-> DsM CoreExpr
goL [ExprLStmt GhcTc]
[GenLocated
   SrcSpanAnnA (StmtLR GhcTc GhcTc (LocatedA (HsExpr GhcTc)))]
stmts
  where
    goL :: [GenLocated
   SrcSpanAnnA (StmtLR GhcTc GhcTc (LocatedA (HsExpr GhcTc)))]
-> DsM CoreExpr
goL [] = String -> DsM CoreExpr
forall a. HasCallStack => String -> a
panic String
"dsDo"
    goL ((L SrcSpanAnnA
loc StmtLR GhcTc GhcTc (LocatedA (HsExpr GhcTc))
stmt):[GenLocated
   SrcSpanAnnA (StmtLR GhcTc GhcTc (LocatedA (HsExpr GhcTc)))]
lstmts) = SrcSpanAnnA -> DsM CoreExpr -> DsM CoreExpr
forall ann a. EpAnn ann -> DsM a -> DsM a
putSrcSpanDsA SrcSpanAnnA
loc (SrcSpanAnnA
-> StmtLR GhcTc GhcTc (LocatedA (HsExpr GhcTc))
-> [GenLocated
      SrcSpanAnnA (StmtLR GhcTc GhcTc (LocatedA (HsExpr GhcTc)))]
-> DsM CoreExpr
go SrcSpanAnnA
loc StmtLR GhcTc GhcTc (LocatedA (HsExpr GhcTc))
stmt [GenLocated
   SrcSpanAnnA (StmtLR GhcTc GhcTc (LocatedA (HsExpr GhcTc)))]
lstmts)

    go :: SrcSpanAnnA
-> StmtLR GhcTc GhcTc (LocatedA (HsExpr GhcTc))
-> [GenLocated
      SrcSpanAnnA (StmtLR GhcTc GhcTc (LocatedA (HsExpr GhcTc)))]
-> DsM CoreExpr
go SrcSpanAnnA
_ (LastStmt XLastStmt GhcTc GhcTc (LocatedA (HsExpr GhcTc))
_ LocatedA (HsExpr GhcTc)
body Maybe Bool
_ SyntaxExpr GhcTc
_) [GenLocated
   SrcSpanAnnA (StmtLR GhcTc GhcTc (LocatedA (HsExpr GhcTc)))]
stmts
      = Bool
-> (LocatedA (HsExpr GhcTc) -> DsM CoreExpr)
-> LocatedA (HsExpr GhcTc)
-> DsM CoreExpr
forall a. HasCallStack => Bool -> a -> a
assert ([GenLocated
   SrcSpanAnnA (StmtLR GhcTc GhcTc (LocatedA (HsExpr GhcTc)))]
-> Bool
forall a. [a] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null [GenLocated
   SrcSpanAnnA (StmtLR GhcTc GhcTc (LocatedA (HsExpr GhcTc)))]
stmts ) LHsExpr GhcTc -> DsM CoreExpr
LocatedA (HsExpr GhcTc) -> DsM CoreExpr
dsLExpr LocatedA (HsExpr GhcTc)
body
        -- The 'return' op isn't used for 'do' expressions

    go SrcSpanAnnA
_ (BodyStmt XBodyStmt GhcTc GhcTc (LocatedA (HsExpr GhcTc))
_ LocatedA (HsExpr GhcTc)
rhs SyntaxExpr GhcTc
then_expr SyntaxExpr GhcTc
_) [GenLocated
   SrcSpanAnnA (StmtLR GhcTc GhcTc (LocatedA (HsExpr GhcTc)))]
stmts
      = do { rhs2 <- LHsExpr GhcTc -> DsM CoreExpr
dsLExpr LHsExpr GhcTc
LocatedA (HsExpr GhcTc)
rhs
           ; case  tcSplitAppTy_maybe (exprType rhs2) of
               Just (Type
m_ty, Type
elt_ty) -> LHsExpr GhcTc -> Type -> Type -> IOEnv (Env DsGblEnv DsLclEnv) ()
warnDiscardedDoBindings LHsExpr GhcTc
LocatedA (HsExpr GhcTc)
rhs Type
m_ty Type
elt_ty
               Maybe (Type, Type)
Nothing             -> () -> IOEnv (Env DsGblEnv DsLclEnv) ()
forall a. a -> IOEnv (Env DsGblEnv DsLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return ()  -- Odd, but not warning
           ; rest <- goL stmts
           ; dsSyntaxExpr then_expr [rhs2, rest] }

    go SrcSpanAnnA
_ (LetStmt XLetStmt GhcTc GhcTc (LocatedA (HsExpr GhcTc))
_ HsLocalBinds GhcTc
binds) [GenLocated
   SrcSpanAnnA (StmtLR GhcTc GhcTc (LocatedA (HsExpr GhcTc)))]
stmts
      = do { rest <- [GenLocated
   SrcSpanAnnA (StmtLR GhcTc GhcTc (LocatedA (HsExpr GhcTc)))]
-> DsM CoreExpr
goL [GenLocated
   SrcSpanAnnA (StmtLR GhcTc GhcTc (LocatedA (HsExpr GhcTc)))]
stmts
           ; dsLocalBinds binds rest }

    go SrcSpanAnnA
_ (BindStmt XBindStmt GhcTc GhcTc (LocatedA (HsExpr GhcTc))
xbs LPat GhcTc
pat LocatedA (HsExpr GhcTc)
rhs) [GenLocated
   SrcSpanAnnA (StmtLR GhcTc GhcTc (LocatedA (HsExpr GhcTc)))]
stmts
      -- SG: As far as I can tell, this code path is only triggered when ApplicativeDo fails, e.g.
      --   do blah <- action1; action2 (blah * 2)
      -- It is reached when compiling GHC.Parser.PostProcess.Haddock.addHaddockToModule
      = do  { var   <- Type -> LPat GhcTc -> DsM EvId
selectSimpleMatchVarL (XBindStmtTc -> Type
xbstc_boundResultMult XBindStmt GhcTc GhcTc (LocatedA (HsExpr GhcTc))
XBindStmtTc
xbs) LPat GhcTc
pat
            ; rhs'  <- dsLExpr rhs
            ; match <- matchSinglePatVar var Nothing (StmtCtxt (HsDoStmt ctx)) pat
                                 (xbstc_boundResultType xbs) (MR_Infallible $ goL stmts)
            -- NB: "goL stmts" needs to happen inside matchSinglePatVar, and not
            -- before it, so that long-distance information is properly threaded.
            -- See Note [Long-distance information in do notation].
            ; match_code <- dsHandleMonadicFailure ctx pat res_ty match (xbstc_failOp xbs)
            ; dsSyntaxExpr (xbstc_bindOp xbs) [rhs', Lam var match_code] }

    go SrcSpanAnnA
loc (RecStmt { recS_stmts :: forall idL idR body.
StmtLR idL idR body -> XRec idR [LStmtLR idL idR body]
recS_stmts = L SrcSpanAnnLW
_ [GenLocated
   SrcSpanAnnA (StmtLR GhcTc GhcTc (LocatedA (HsExpr GhcTc)))]
rec_stmts, recS_later_ids :: forall idL idR body. StmtLR idL idR body -> [IdP idR]
recS_later_ids = [IdP GhcTc]
later_ids
                    , recS_rec_ids :: forall idL idR body. StmtLR idL idR body -> [IdP idR]
recS_rec_ids = [IdP GhcTc]
rec_ids, recS_ret_fn :: forall idL idR body. StmtLR idL idR body -> SyntaxExpr idR
recS_ret_fn = SyntaxExpr GhcTc
return_op
                    , recS_mfix_fn :: forall idL idR body. StmtLR idL idR body -> SyntaxExpr idR
recS_mfix_fn = SyntaxExpr GhcTc
mfix_op, recS_bind_fn :: forall idL idR body. StmtLR idL idR body -> SyntaxExpr idR
recS_bind_fn = SyntaxExpr GhcTc
bind_op
                    , recS_ext :: forall idL idR body. StmtLR idL idR body -> XRecStmt idL idR body
recS_ext = RecStmtTc
                        { recS_bind_ty :: RecStmtTc -> Type
recS_bind_ty = Type
bind_ty
                        , recS_rec_rets :: RecStmtTc -> [HsExpr GhcTc]
recS_rec_rets = [HsExpr GhcTc]
rec_rets
                        , recS_ret_ty :: RecStmtTc -> Type
recS_ret_ty = Type
body_ty} }) [GenLocated
   SrcSpanAnnA (StmtLR GhcTc GhcTc (LocatedA (HsExpr GhcTc)))]
stmts
      = [GenLocated
   SrcSpanAnnA (StmtLR GhcTc GhcTc (LocatedA (HsExpr GhcTc)))]
-> DsM CoreExpr
goL (GenLocated
  SrcSpanAnnA (StmtLR GhcTc GhcTc (LocatedA (HsExpr GhcTc)))
new_bind_stmt GenLocated
  SrcSpanAnnA (StmtLR GhcTc GhcTc (LocatedA (HsExpr GhcTc)))
-> [GenLocated
      SrcSpanAnnA (StmtLR GhcTc GhcTc (LocatedA (HsExpr GhcTc)))]
-> [GenLocated
      SrcSpanAnnA (StmtLR GhcTc GhcTc (LocatedA (HsExpr GhcTc)))]
forall a. a -> [a] -> [a]
: [GenLocated
   SrcSpanAnnA (StmtLR GhcTc GhcTc (LocatedA (HsExpr GhcTc)))]
stmts)  -- rec_ids can be empty; eg  rec { print 'x' }
      where
        new_bind_stmt :: GenLocated
  SrcSpanAnnA (StmtLR GhcTc GhcTc (LocatedA (HsExpr GhcTc)))
new_bind_stmt = SrcSpanAnnA
-> StmtLR GhcTc GhcTc (LocatedA (HsExpr GhcTc))
-> GenLocated
     SrcSpanAnnA (StmtLR GhcTc GhcTc (LocatedA (HsExpr GhcTc)))
forall l e. l -> e -> GenLocated l e
L SrcSpanAnnA
loc (StmtLR GhcTc GhcTc (LocatedA (HsExpr GhcTc))
 -> GenLocated
      SrcSpanAnnA (StmtLR GhcTc GhcTc (LocatedA (HsExpr GhcTc))))
-> StmtLR GhcTc GhcTc (LocatedA (HsExpr GhcTc))
-> GenLocated
     SrcSpanAnnA (StmtLR GhcTc GhcTc (LocatedA (HsExpr GhcTc)))
forall a b. (a -> b) -> a -> b
$ XBindStmt GhcTc GhcTc (LocatedA (HsExpr GhcTc))
-> LPat GhcTc
-> LocatedA (HsExpr GhcTc)
-> StmtLR GhcTc GhcTc (LocatedA (HsExpr GhcTc))
forall idL idR body.
XBindStmt idL idR body -> LPat idL -> body -> StmtLR idL idR body
BindStmt
          XBindStmtTc
            { xbstc_bindOp :: SyntaxExpr GhcTc
xbstc_bindOp          = SyntaxExpr GhcTc
bind_op
            , xbstc_boundResultType :: Type
xbstc_boundResultType = Type
bind_ty
            , xbstc_boundResultMult :: Type
xbstc_boundResultMult = Type
ManyTy
            , xbstc_failOp :: Maybe (SyntaxExpr GhcTc)
xbstc_failOp          = Maybe (SyntaxExpr GhcTc)
Maybe SyntaxExprTc
forall a. Maybe a
Nothing -- Tuple cannot fail
            }
          ([LPat GhcTc] -> LPat GhcTc
mkBigLHsPatTupId [LPat GhcTc]
[GenLocated SrcSpanAnnA (Pat GhcTc)]
later_pats)
          LHsExpr GhcTc
LocatedA (HsExpr GhcTc)
mfix_app

        tup_ids :: [IdP GhcTc]
tup_ids      = [IdP GhcTc]
rec_ids [IdP GhcTc] -> [IdP GhcTc] -> [IdP GhcTc]
forall a. [a] -> [a] -> [a]
++ (IdP GhcTc -> Bool) -> [IdP GhcTc] -> [IdP GhcTc]
forall a. (a -> Bool) -> [a] -> [a]
filterOut (IdP GhcTc -> [IdP GhcTc] -> Bool
forall a. Eq a => a -> [a] -> Bool
forall (t :: * -> *) a. (Foldable t, Eq a) => a -> t a -> Bool
`elem` [IdP GhcTc]
rec_ids) [IdP GhcTc]
later_ids
        tup_ty :: Type
tup_ty       = [Type] -> Type
HasDebugCallStack => [Type] -> Type
mkBigCoreTupTy ((EvId -> Type) -> [EvId] -> [Type]
forall a b. (a -> b) -> [a] -> [b]
map EvId -> Type
idType [IdP GhcTc]
[EvId]
tup_ids) -- Deals with singleton case
        rec_tup_pats :: [GenLocated SrcSpanAnnA (Pat GhcTc)]
rec_tup_pats = (IdGhcP 'Typechecked -> GenLocated SrcSpanAnnA (Pat GhcTc))
-> [IdGhcP 'Typechecked] -> [GenLocated SrcSpanAnnA (Pat GhcTc)]
forall a b. (a -> b) -> [a] -> [b]
map IdP GhcTc -> LPat GhcTc
IdGhcP 'Typechecked -> GenLocated SrcSpanAnnA (Pat GhcTc)
forall (p :: Pass) a.
IsSrcSpanAnn p a =>
IdP (GhcPass p) -> LPat (GhcPass p)
nlVarPat [IdP GhcTc]
[IdGhcP 'Typechecked]
tup_ids
        later_pats :: [GenLocated SrcSpanAnnA (Pat GhcTc)]
later_pats   = [GenLocated SrcSpanAnnA (Pat GhcTc)]
rec_tup_pats
        rets :: [LocatedA (HsExpr GhcTc)]
rets         = (HsExpr GhcTc -> LocatedA (HsExpr GhcTc))
-> [HsExpr GhcTc] -> [LocatedA (HsExpr GhcTc)]
forall a b. (a -> b) -> [a] -> [b]
map HsExpr GhcTc -> LocatedA (HsExpr GhcTc)
forall e a. HasAnnotation e => a -> GenLocated e a
noLocA [HsExpr GhcTc]
rec_rets
        mfix_app :: LHsExpr GhcTc
mfix_app     = SyntaxExprTc -> [LHsExpr GhcTc] -> LHsExpr GhcTc
nlHsSyntaxApps SyntaxExpr GhcTc
SyntaxExprTc
mfix_op [LHsExpr GhcTc
LocatedA (HsExpr GhcTc)
mfix_arg]
        match_group :: MatchGroupTc
match_group  = [Scaled Type] -> Type -> Origin -> MatchGroupTc
MatchGroupTc [Type -> Scaled Type
forall a. a -> Scaled a
unrestricted Type
tup_ty] Type
body_ty (GenReason -> DoPmc -> Origin
Generated GenReason
OtherExpansion DoPmc
SkipPmc)
        mfix_arg :: LocatedA (HsExpr GhcTc)
mfix_arg     = HsExpr GhcTc -> LocatedA (HsExpr GhcTc)
forall e a. HasAnnotation e => a -> GenLocated e a
noLocA (HsExpr GhcTc -> LocatedA (HsExpr GhcTc))
-> HsExpr GhcTc -> LocatedA (HsExpr GhcTc)
forall a b. (a -> b) -> a -> b
$ XLam GhcTc
-> HsLamVariant -> MatchGroup GhcTc (LHsExpr GhcTc) -> HsExpr GhcTc
forall p.
XLam p -> HsLamVariant -> MatchGroup p (LHsExpr p) -> HsExpr p
HsLam XLam GhcTc
forall a. NoAnn a => a
noAnn HsLamVariant
LamSingle
                           (MG { mg_alts :: XRec GhcTc [LMatch GhcTc (LocatedA (HsExpr GhcTc))]
mg_alts = [LMatch GhcTc (LocatedA (HsExpr GhcTc))]
-> GenLocated SrcSpanAnnLW [LMatch GhcTc (LocatedA (HsExpr GhcTc))]
forall e a. HasAnnotation e => a -> GenLocated e a
noLocA [HsMatchContext (LIdP (NoGhcTc GhcTc))
-> LocatedE [LPat GhcTc]
-> LocatedA (HsExpr GhcTc)
-> LMatch GhcTc (LocatedA (HsExpr GhcTc))
forall (p :: Pass) (body :: * -> *).
(Anno (Match (GhcPass p) (LocatedA (body (GhcPass p))))
 ~ SrcSpanAnnA,
 Anno (GRHS (GhcPass p) (LocatedA (body (GhcPass p))))
 ~ EpAnn NoEpAnns) =>
HsMatchContext (LIdP (NoGhcTc (GhcPass p)))
-> LocatedE [LPat (GhcPass p)]
-> LocatedA (body (GhcPass p))
-> LMatch (GhcPass p) (LocatedA (body (GhcPass p)))
mkSimpleMatch
                                                    (HsLamVariant -> HsMatchContext (GenLocated SrcSpanAnnN Name)
forall fn. HsLamVariant -> HsMatchContext fn
LamAlt HsLamVariant
LamSingle)
                                                    ([GenLocated SrcSpanAnnA (Pat GhcTc)]
-> GenLocated EpaLocation [GenLocated SrcSpanAnnA (Pat GhcTc)]
forall e a. HasAnnotation e => a -> GenLocated e a
noLocA [GenLocated SrcSpanAnnA (Pat GhcTc)
mfix_pat]) LocatedA (HsExpr GhcTc)
body]
                               , mg_ext :: XMG GhcTc (LocatedA (HsExpr GhcTc))
mg_ext = XMG GhcTc (LocatedA (HsExpr GhcTc))
MatchGroupTc
match_group
                               })
        mfix_pat :: GenLocated SrcSpanAnnA (Pat GhcTc)
mfix_pat     = Pat GhcTc -> GenLocated SrcSpanAnnA (Pat GhcTc)
forall e a. HasAnnotation e => a -> GenLocated e a
noLocA (Pat GhcTc -> GenLocated SrcSpanAnnA (Pat GhcTc))
-> Pat GhcTc -> GenLocated SrcSpanAnnA (Pat GhcTc)
forall a b. (a -> b) -> a -> b
$ XLazyPat GhcTc -> LPat GhcTc -> Pat GhcTc
forall p. XLazyPat p -> LPat p -> Pat p
LazyPat XLazyPat GhcTc
NoExtField
noExtField (LPat GhcTc -> Pat GhcTc) -> LPat GhcTc -> Pat GhcTc
forall a b. (a -> b) -> a -> b
$ [LPat GhcTc] -> LPat GhcTc
mkBigLHsPatTupId [LPat GhcTc]
[GenLocated SrcSpanAnnA (Pat GhcTc)]
rec_tup_pats
        body :: LocatedA (HsExpr GhcTc)
body         = HsExpr GhcTc -> LocatedA (HsExpr GhcTc)
forall e a. HasAnnotation e => a -> GenLocated e a
noLocA (HsExpr GhcTc -> LocatedA (HsExpr GhcTc))
-> HsExpr GhcTc -> LocatedA (HsExpr GhcTc)
forall a b. (a -> b) -> a -> b
$ XDo GhcTc
-> HsDoFlavour -> XRec GhcTc [ExprLStmt GhcTc] -> HsExpr GhcTc
forall p. XDo p -> HsDoFlavour -> XRec p [ExprLStmt p] -> HsExpr p
HsDo XDo GhcTc
Type
body_ty
                                HsDoFlavour
ctx ([GenLocated
   SrcSpanAnnA (StmtLR GhcTc GhcTc (LocatedA (HsExpr GhcTc)))]
-> GenLocated
     SrcSpanAnnLW
     [GenLocated
        SrcSpanAnnA (StmtLR GhcTc GhcTc (LocatedA (HsExpr GhcTc)))]
forall e a. HasAnnotation e => a -> GenLocated e a
noLocA ([GenLocated
   SrcSpanAnnA (StmtLR GhcTc GhcTc (LocatedA (HsExpr GhcTc)))]
rec_stmts [GenLocated
   SrcSpanAnnA (StmtLR GhcTc GhcTc (LocatedA (HsExpr GhcTc)))]
-> [GenLocated
      SrcSpanAnnA (StmtLR GhcTc GhcTc (LocatedA (HsExpr GhcTc)))]
-> [GenLocated
      SrcSpanAnnA (StmtLR GhcTc GhcTc (LocatedA (HsExpr GhcTc)))]
forall a. [a] -> [a] -> [a]
++ [GenLocated
  SrcSpanAnnA (StmtLR GhcTc GhcTc (LocatedA (HsExpr GhcTc)))
ret_stmt]))
        ret_app :: LHsExpr GhcTc
ret_app      = SyntaxExprTc -> [LHsExpr GhcTc] -> LHsExpr GhcTc
nlHsSyntaxApps SyntaxExpr GhcTc
SyntaxExprTc
return_op [[LHsExpr GhcTc] -> LHsExpr GhcTc
mkBigLHsTupId [LHsExpr GhcTc]
[LocatedA (HsExpr GhcTc)]
rets]
        ret_stmt :: GenLocated
  SrcSpanAnnA (StmtLR GhcTc GhcTc (LocatedA (HsExpr GhcTc)))
ret_stmt     = StmtLR GhcTc GhcTc (LocatedA (HsExpr GhcTc))
-> GenLocated
     SrcSpanAnnA (StmtLR GhcTc GhcTc (LocatedA (HsExpr GhcTc)))
forall e a. HasAnnotation e => a -> GenLocated e a
noLocA (StmtLR GhcTc GhcTc (LocatedA (HsExpr GhcTc))
 -> GenLocated
      SrcSpanAnnA (StmtLR GhcTc GhcTc (LocatedA (HsExpr GhcTc))))
-> StmtLR GhcTc GhcTc (LocatedA (HsExpr GhcTc))
-> GenLocated
     SrcSpanAnnA (StmtLR GhcTc GhcTc (LocatedA (HsExpr GhcTc)))
forall a b. (a -> b) -> a -> b
$ LocatedA (HsExpr GhcTc)
-> StmtLR GhcTc GhcTc (LocatedA (HsExpr GhcTc))
forall (idR :: Pass) (bodyR :: * -> *) (idL :: Pass).
IsPass idR =>
LocatedA (bodyR (GhcPass idR))
-> StmtLR
     (GhcPass idL) (GhcPass idR) (LocatedA (bodyR (GhcPass idR)))
mkLastStmt LHsExpr GhcTc
LocatedA (HsExpr GhcTc)
ret_app
                     -- This LastStmt will be desugared with dsDo,
                     -- which ignores the return_op in the LastStmt,
                     -- so we must apply the return_op explicitly

    go SrcSpanAnnA
_ (XStmtLR (ApplicativeStmt XApplicativeStmt GhcTc GhcTc
body_ty [(SyntaxExpr GhcTc, ApplicativeArg GhcTc)]
args Maybe (SyntaxExpr GhcTc)
mb_join)) [GenLocated
   SrcSpanAnnA (StmtLR GhcTc GhcTc (LocatedA (HsExpr GhcTc)))]
stmts
      = do {
             let
               ([(GenLocated SrcSpanAnnA (Pat GhcTc), Maybe SyntaxExprTc)]
pats, [DsM CoreExpr]
rhss) = [((GenLocated SrcSpanAnnA (Pat GhcTc), Maybe SyntaxExprTc),
  DsM CoreExpr)]
-> ([(GenLocated SrcSpanAnnA (Pat GhcTc), Maybe SyntaxExprTc)],
    [DsM CoreExpr])
forall a b. [(a, b)] -> ([a], [b])
unzip (((SyntaxExprTc, ApplicativeArg GhcTc)
 -> ((GenLocated SrcSpanAnnA (Pat GhcTc), Maybe SyntaxExprTc),
     DsM CoreExpr))
-> [(SyntaxExprTc, ApplicativeArg GhcTc)]
-> [((GenLocated SrcSpanAnnA (Pat GhcTc), Maybe SyntaxExprTc),
     DsM CoreExpr)]
forall a b. (a -> b) -> [a] -> [b]
map (ApplicativeArg GhcTc
-> ((GenLocated SrcSpanAnnA (Pat GhcTc), Maybe SyntaxExprTc),
    DsM CoreExpr)
do_arg (ApplicativeArg GhcTc
 -> ((GenLocated SrcSpanAnnA (Pat GhcTc), Maybe SyntaxExprTc),
     DsM CoreExpr))
-> ((SyntaxExprTc, ApplicativeArg GhcTc) -> ApplicativeArg GhcTc)
-> (SyntaxExprTc, ApplicativeArg GhcTc)
-> ((GenLocated SrcSpanAnnA (Pat GhcTc), Maybe SyntaxExprTc),
    DsM CoreExpr)
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (SyntaxExprTc, ApplicativeArg GhcTc) -> ApplicativeArg GhcTc
forall a b. (a, b) -> b
snd) [(SyntaxExpr GhcTc, ApplicativeArg GhcTc)]
[(SyntaxExprTc, ApplicativeArg GhcTc)]
args)

               do_arg :: ApplicativeArg GhcTc
-> ((GenLocated SrcSpanAnnA (Pat GhcTc), Maybe SyntaxExprTc),
    DsM CoreExpr)
do_arg (ApplicativeArgOne XApplicativeArgOne GhcTc
fail_op LPat GhcTc
pat LHsExpr GhcTc
expr Bool
_) =
                 ((LPat GhcTc
GenLocated SrcSpanAnnA (Pat GhcTc)
pat, Maybe SyntaxExprTc
XApplicativeArgOne GhcTc
fail_op), LHsExpr GhcTc -> DsM CoreExpr
dsLExpr LHsExpr GhcTc
expr)
               do_arg (ApplicativeArgMany XApplicativeArgMany GhcTc
_ [ExprLStmt GhcTc]
stmts HsExpr GhcTc
ret LPat GhcTc
pat HsDoFlavour
_) =
                 ((LPat GhcTc
GenLocated SrcSpanAnnA (Pat GhcTc)
pat, Maybe SyntaxExprTc
forall a. Maybe a
Nothing), HsDoFlavour -> [ExprLStmt GhcTc] -> Type -> DsM CoreExpr
dsDo HsDoFlavour
ctx ([ExprLStmt GhcTc]
[GenLocated
   SrcSpanAnnA (StmtLR GhcTc GhcTc (LocatedA (HsExpr GhcTc)))]
stmts [GenLocated
   SrcSpanAnnA (StmtLR GhcTc GhcTc (LocatedA (HsExpr GhcTc)))]
-> [GenLocated
      SrcSpanAnnA (StmtLR GhcTc GhcTc (LocatedA (HsExpr GhcTc)))]
-> [GenLocated
      SrcSpanAnnA (StmtLR GhcTc GhcTc (LocatedA (HsExpr GhcTc)))]
forall a. [a] -> [a] -> [a]
++ [StmtLR GhcTc GhcTc (LocatedA (HsExpr GhcTc))
-> GenLocated
     SrcSpanAnnA (StmtLR GhcTc GhcTc (LocatedA (HsExpr GhcTc)))
forall e a. HasAnnotation e => a -> GenLocated e a
noLocA (StmtLR GhcTc GhcTc (LocatedA (HsExpr GhcTc))
 -> GenLocated
      SrcSpanAnnA (StmtLR GhcTc GhcTc (LocatedA (HsExpr GhcTc))))
-> StmtLR GhcTc GhcTc (LocatedA (HsExpr GhcTc))
-> GenLocated
     SrcSpanAnnA (StmtLR GhcTc GhcTc (LocatedA (HsExpr GhcTc)))
forall a b. (a -> b) -> a -> b
$ LocatedA (HsExpr GhcTc)
-> StmtLR GhcTc GhcTc (LocatedA (HsExpr GhcTc))
forall (idR :: Pass) (bodyR :: * -> *) (idL :: Pass).
IsPass idR =>
LocatedA (bodyR (GhcPass idR))
-> StmtLR
     (GhcPass idL) (GhcPass idR) (LocatedA (bodyR (GhcPass idR)))
mkLastStmt (HsExpr GhcTc -> LocatedA (HsExpr GhcTc)
forall e a. HasAnnotation e => a -> GenLocated e a
noLocA HsExpr GhcTc
ret)]) Type
res_ty)

           ; rhss' <- [DsM CoreExpr] -> IOEnv (Env DsGblEnv DsLclEnv) [CoreExpr]
forall (t :: * -> *) (m :: * -> *) a.
(Traversable t, Monad m) =>
t (m a) -> m (t a)
forall (m :: * -> *) a. Monad m => [m a] -> m [a]
sequence [DsM CoreExpr]
rhss

           ; body' <- dsLExpr $ noLocA $ HsDo body_ty ctx (noLocA stmts)

           ; let match_args (GenLocated SrcSpanAnnA (Pat GhcTc)
pat, Maybe SyntaxExprTc
fail_op) ([EvId]
vs,CoreExpr
body)
                   = SrcSpan -> DsM ([EvId], CoreExpr) -> DsM ([EvId], CoreExpr)
forall a. SrcSpan -> DsM a -> DsM a
putSrcSpanDs (GenLocated SrcSpanAnnA (Pat GhcTc) -> SrcSpan
forall a e. HasLoc a => GenLocated a e -> SrcSpan
getLocA GenLocated SrcSpanAnnA (Pat GhcTc)
pat) (DsM ([EvId], CoreExpr) -> DsM ([EvId], CoreExpr))
-> DsM ([EvId], CoreExpr) -> DsM ([EvId], CoreExpr)
forall a b. (a -> b) -> a -> b
$
                     do { var   <- Type -> LPat GhcTc -> DsM EvId
selectSimpleMatchVarL Type
ManyTy LPat GhcTc
GenLocated SrcSpanAnnA (Pat GhcTc)
pat
                        ; match <- matchSinglePatVar var Nothing (StmtCtxt (HsDoStmt ctx)) pat
                                   body_ty (cantFailMatchResult body)
                        ; match_code <- dsHandleMonadicFailure ctx pat body_ty match fail_op
                        ; return (var:vs, match_code)
                        }

           ; (vars, body) <- foldrM match_args ([],body') pats
           ; let fun' = [EvId] -> CoreExpr -> CoreExpr
forall b. [b] -> Expr b -> Expr b
mkLams [EvId]
vars CoreExpr
body
           ; let mk_ap_call CoreExpr
l (SyntaxExprTc
op,CoreExpr
r) = SyntaxExpr GhcTc -> [CoreExpr] -> DsM CoreExpr
dsSyntaxExpr SyntaxExpr GhcTc
SyntaxExprTc
op [CoreExpr
l,CoreExpr
r]
           ; expr <- foldlM mk_ap_call fun' (zip (map fst args) rhss')
           ; case mb_join of
               Maybe (SyntaxExpr GhcTc)
Nothing -> CoreExpr -> DsM CoreExpr
forall a. a -> IOEnv (Env DsGblEnv DsLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return CoreExpr
expr
               Just SyntaxExpr GhcTc
join_op -> SyntaxExpr GhcTc -> [CoreExpr] -> DsM CoreExpr
dsSyntaxExpr SyntaxExpr GhcTc
join_op [CoreExpr
expr] }

    go SrcSpanAnnA
_ (ParStmt   {}) [GenLocated
   SrcSpanAnnA (StmtLR GhcTc GhcTc (LocatedA (HsExpr GhcTc)))]
_ = String -> DsM CoreExpr
forall a. HasCallStack => String -> a
panic String
"dsDo ParStmt"
    go SrcSpanAnnA
_ (TransStmt {}) [GenLocated
   SrcSpanAnnA (StmtLR GhcTc GhcTc (LocatedA (HsExpr GhcTc)))]
_ = String -> DsM CoreExpr
forall a. HasCallStack => String -> a
panic String
"dsDo TransStmt"

{- Note [Long-distance information in do notation]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider T21360:

  data Foo = A Int | B

  swooble :: Foo -> Maybe Foo
  swooble foo = do
    bar@A{} <- Just foo
    return $ case bar of { A _ -> A 9 }

The pattern-match checker **should not** complain that the case statement
is incomplete, because we know that 'bar' is headed by the constructor 'A',
due to the pattern match in the line above. However, we need to ensure that we
propagate this long-distance information; failing to do so lead to #21360.

To do this, we use "matchSinglePatVar" to handle the first pattern match

  bar@A{} <- Just foo

"matchSinglePatVar" then threads through the long-distance information to the
desugaring of the remaining statements by using updPmNablasMatchResult.
This avoids any spurious pattern-match warnings when handling the case
statement on the last line.

Other places that requires from the same treatment:

  - monad comprehensions, e.g.

     blorble :: Foo -> Maybe Foo
     blorble foo = [ case bar of { A _ -> A 9 } | bar@A{} <- Just foo ]

     See GHC.HsToCore.ListComp.dsMcBindStmt. Also tested in T21360.

  - guards, e.g.

      giddy :: Maybe Char -> Char
      giddy x
        | y@(Just _) <- x
        , let z = case y of { Just w -> w }
        = z

    We don't want any inexhaustive pattern match warnings for the case statement,
    because we already know 'y' is of the form "Just ...".
    See test case T21360b.


************************************************************************
*                                                                      *
\subsection{Errors and contexts}
*                                                                      *
************************************************************************
-}

-- Warn about certain types of values discarded in monadic bindings (#3263)
warnDiscardedDoBindings :: LHsExpr GhcTc -> Type -> Type -> DsM ()
warnDiscardedDoBindings :: LHsExpr GhcTc -> Type -> Type -> IOEnv (Env DsGblEnv DsLclEnv) ()
warnDiscardedDoBindings LHsExpr GhcTc
rhs Type
m_ty Type
elt_ty
  = do { warn_unused <- WarningFlag -> TcRnIf DsGblEnv DsLclEnv Bool
forall gbl lcl. WarningFlag -> TcRnIf gbl lcl Bool
woptM WarningFlag
Opt_WarnUnusedDoBind
       ; warn_wrong <- woptM Opt_WarnWrongDoBind
       ; when (warn_unused || warn_wrong) $
    do { fam_inst_envs <- dsGetFamInstEnvs
       ; let norm_elt_ty = FamInstEnvs -> Type -> Type
topNormaliseType FamInstEnvs
fam_inst_envs Type
elt_ty

           -- Warn about discarding non-() things in 'monadic' binding
       ; if warn_unused && not (isUnitTy norm_elt_ty)
         then diagnosticDs (DsUnusedDoBind rhs elt_ty)
         else

           -- Warn about discarding m a things in 'monadic' binding of the same type,
           -- but only if we didn't already warn due to Opt_WarnUnusedDoBind
           -- Example:   do { return 3; blah }
           -- We get   (>>) @m d @(m Int) (return 3) blah
           when warn_wrong $
           case tcSplitAppTy_maybe norm_elt_ty of
             Just (Type
elt_m_ty, Type
_)
                | Type
m_ty HasCallStack => Type -> Type -> Bool
Type -> Type -> Bool
`eqType` FamInstEnvs -> Type -> Type
topNormaliseType FamInstEnvs
fam_inst_envs Type
elt_m_ty
                -> DsMessage -> IOEnv (Env DsGblEnv DsLclEnv) ()
diagnosticDs (LHsExpr GhcTc -> Type -> DsMessage
DsWrongDoBind LHsExpr GhcTc
rhs Type
elt_ty)
             Maybe (Type, Type)
_ -> () -> IOEnv (Env DsGblEnv DsLclEnv) ()
forall a. a -> IOEnv (Env DsGblEnv DsLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return () } }