{-# LANGUAGE CPP #-}

-- | Handy functions for creating much Core syntax
module MkCore (
        -- * Constructing normal syntax
        mkCoreLet, mkCoreLets,
        mkCoreApp, mkCoreApps, mkCoreConApps,
        mkCoreLams, mkWildCase, mkIfThenElse,
        mkWildValBinder, mkWildEvBinder,
        mkSingleAltCase,
        sortQuantVars, castBottomExpr,

        -- * Constructing boxed literals
        mkWordExpr, mkWordExprWord,
        mkIntExpr, mkIntExprInt,
        mkIntegerExpr, mkNaturalExpr,
        mkFloatExpr, mkDoubleExpr,
        mkCharExpr, mkStringExpr, mkStringExprFS, mkStringExprFSWith,

        -- * Floats
        FloatBind(..), wrapFloat, wrapFloats, floatBindings,

        -- * Constructing small tuples
        mkCoreVarTupTy, mkCoreTup, mkCoreUbxTup,
        mkCoreTupBoxity, unitExpr,

        -- * Constructing big tuples
        mkBigCoreVarTup, mkBigCoreVarTup1,
        mkBigCoreVarTupTy, mkBigCoreTupTy,
        mkBigCoreTup,

        -- * Deconstructing small tuples
        mkSmallTupleSelector, mkSmallTupleCase,

        -- * Deconstructing big tuples
        mkTupleSelector, mkTupleSelector1, mkTupleCase,

        -- * Constructing list expressions
        mkNilExpr, mkConsExpr, mkListExpr,
        mkFoldrExpr, mkBuildExpr,

        -- * Constructing Maybe expressions
        mkNothingExpr, mkJustExpr,

        -- * Error Ids
        mkRuntimeErrorApp, mkImpossibleExpr, mkAbsentErrorApp, errorIds,
        rEC_CON_ERROR_ID, rUNTIME_ERROR_ID,
        nON_EXHAUSTIVE_GUARDS_ERROR_ID, nO_METHOD_BINDING_ERROR_ID,
        pAT_ERROR_ID, rEC_SEL_ERROR_ID, aBSENT_ERROR_ID,
        tYPE_ERROR_ID, aBSENT_SUM_FIELD_ERROR_ID
    ) where

#include "GhclibHsVersions.h"

import GhcPrelude

import Id
import Var      ( EvVar, setTyVarUnique )

import CoreSyn
import CoreUtils        ( exprType, needsCaseBinding, mkSingleAltCase, bindNonRec )
import Literal
import HscTypes

import TysWiredIn
import PrelNames

import GHC.Hs.Utils     ( mkChunkified, chunkify )
import Type
import Coercion         ( isCoVar )
import TysPrim
import DataCon          ( DataCon, dataConWorkId )
import IdInfo
import Demand
import Name      hiding ( varName )
import Outputable
import FastString
import UniqSupply
import BasicTypes
import Util
import DynFlags
import Data.List

import Data.Char        ( ord )
import Control.Monad.Fail as MonadFail ( MonadFail )

infixl 4 `mkCoreApp`, `mkCoreApps`

{-
************************************************************************
*                                                                      *
\subsection{Basic CoreSyn construction}
*                                                                      *
************************************************************************
-}
sortQuantVars :: [Var] -> [Var]
-- Sort the variables, putting type and covars first, in scoped order,
-- and then other Ids
-- It is a deterministic sort, meaining it doesn't look at the values of
-- Uniques. For explanation why it's important See Note [Unique Determinism]
-- in Unique.
sortQuantVars :: [Var] -> [Var]
sortQuantVars [Var]
vs = [Var]
sorted_tcvs [Var] -> [Var] -> [Var]
forall a. [a] -> [a] -> [a]
++ [Var]
ids
  where
    ([Var]
tcvs, [Var]
ids) = (Var -> Bool) -> [Var] -> ([Var], [Var])
forall a. (a -> Bool) -> [a] -> ([a], [a])
partition (Var -> Bool
isTyVar (Var -> Bool) -> (Var -> Bool) -> Var -> Bool
forall (f :: * -> *). Applicative f => f Bool -> f Bool -> f Bool
<||> Var -> Bool
isCoVar) [Var]
vs
    sorted_tcvs :: [Var]
sorted_tcvs = [Var] -> [Var]
scopedSort [Var]
tcvs

-- | Bind a binding group over an expression, using a @let@ or @case@ as
-- appropriate (see "CoreSyn#let_app_invariant")
mkCoreLet :: CoreBind -> CoreExpr -> CoreExpr
mkCoreLet :: CoreBind -> CoreExpr -> CoreExpr
mkCoreLet (NonRec Var
bndr CoreExpr
rhs) CoreExpr
body        -- See Note [CoreSyn let/app invariant]
  = Var -> CoreExpr -> CoreExpr -> CoreExpr
bindNonRec Var
bndr CoreExpr
rhs CoreExpr
body
mkCoreLet CoreBind
bind CoreExpr
body
  = CoreBind -> CoreExpr -> CoreExpr
forall b. Bind b -> Expr b -> Expr b
Let CoreBind
bind CoreExpr
body

-- | Create a lambda where the given expression has a number of variables
-- bound over it. The leftmost binder is that bound by the outermost
-- lambda in the result
mkCoreLams :: [CoreBndr] -> CoreExpr -> CoreExpr
mkCoreLams :: [Var] -> CoreExpr -> CoreExpr
mkCoreLams = [Var] -> CoreExpr -> CoreExpr
forall b. [b] -> Expr b -> Expr b
mkLams

-- | Bind a list of binding groups over an expression. The leftmost binding
-- group becomes the outermost group in the resulting expression
mkCoreLets :: [CoreBind] -> CoreExpr -> CoreExpr
mkCoreLets :: [CoreBind] -> CoreExpr -> CoreExpr
mkCoreLets [CoreBind]
binds CoreExpr
body = (CoreBind -> CoreExpr -> CoreExpr)
-> CoreExpr -> [CoreBind] -> CoreExpr
forall (t :: * -> *) a b.
Foldable t =>
(a -> b -> b) -> b -> t a -> b
foldr CoreBind -> CoreExpr -> CoreExpr
mkCoreLet CoreExpr
body [CoreBind]
binds

-- | Construct an expression which represents the application of a number of
-- expressions to that of a data constructor expression. The leftmost expression
-- in the list is applied first
mkCoreConApps :: DataCon -> [CoreExpr] -> CoreExpr
mkCoreConApps :: DataCon -> [CoreExpr] -> CoreExpr
mkCoreConApps DataCon
con [CoreExpr]
args = CoreExpr -> [CoreExpr] -> CoreExpr
mkCoreApps (Var -> CoreExpr
forall b. Var -> Expr b
Var (DataCon -> Var
dataConWorkId DataCon
con)) [CoreExpr]
args

-- | Construct an expression which represents the application of a number of
-- expressions to another. The leftmost expression in the list is applied first
-- Respects the let/app invariant by building a case expression where necessary
--   See CoreSyn Note [CoreSyn let/app invariant]
mkCoreApps :: CoreExpr -> [CoreExpr] -> CoreExpr
mkCoreApps :: CoreExpr -> [CoreExpr] -> CoreExpr
mkCoreApps CoreExpr
fun [CoreExpr]
args
  = (CoreExpr, Type) -> CoreExpr
forall a b. (a, b) -> a
fst ((CoreExpr, Type) -> CoreExpr) -> (CoreExpr, Type) -> CoreExpr
forall a b. (a -> b) -> a -> b
$
    ((CoreExpr, Type) -> CoreExpr -> (CoreExpr, Type))
-> (CoreExpr, Type) -> [CoreExpr] -> (CoreExpr, Type)
forall (t :: * -> *) b a.
Foldable t =>
(b -> a -> b) -> b -> t a -> b
foldl' (SDoc -> (CoreExpr, Type) -> CoreExpr -> (CoreExpr, Type)
mkCoreAppTyped SDoc
doc_string) (CoreExpr
fun, Type
fun_ty) [CoreExpr]
args
  where
    doc_string :: SDoc
doc_string = Type -> SDoc
forall a. Outputable a => a -> SDoc
ppr Type
fun_ty SDoc -> SDoc -> SDoc
$$ CoreExpr -> SDoc
forall a. Outputable a => a -> SDoc
ppr CoreExpr
fun SDoc -> SDoc -> SDoc
$$ [CoreExpr] -> SDoc
forall a. Outputable a => a -> SDoc
ppr [CoreExpr]
args
    fun_ty :: Type
fun_ty = CoreExpr -> Type
exprType CoreExpr
fun

-- | Construct an expression which represents the application of one expression
-- to the other
-- Respects the let/app invariant by building a case expression where necessary
--   See CoreSyn Note [CoreSyn let/app invariant]
mkCoreApp :: SDoc -> CoreExpr -> CoreExpr -> CoreExpr
mkCoreApp :: SDoc -> CoreExpr -> CoreExpr -> CoreExpr
mkCoreApp SDoc
s CoreExpr
fun CoreExpr
arg
  = (CoreExpr, Type) -> CoreExpr
forall a b. (a, b) -> a
fst ((CoreExpr, Type) -> CoreExpr) -> (CoreExpr, Type) -> CoreExpr
forall a b. (a -> b) -> a -> b
$ SDoc -> (CoreExpr, Type) -> CoreExpr -> (CoreExpr, Type)
mkCoreAppTyped SDoc
s (CoreExpr
fun, CoreExpr -> Type
exprType CoreExpr
fun) CoreExpr
arg

-- | Construct an expression which represents the application of one expression
-- paired with its type to an argument. The result is paired with its type. This
-- function is not exported and used in the definition of 'mkCoreApp' and
-- 'mkCoreApps'.
-- Respects the let/app invariant by building a case expression where necessary
--   See CoreSyn Note [CoreSyn let/app invariant]
mkCoreAppTyped :: SDoc -> (CoreExpr, Type) -> CoreExpr -> (CoreExpr, Type)
mkCoreAppTyped :: SDoc -> (CoreExpr, Type) -> CoreExpr -> (CoreExpr, Type)
mkCoreAppTyped SDoc
_ (CoreExpr
fun, Type
fun_ty) (Type Type
ty)
  = (CoreExpr -> CoreExpr -> CoreExpr
forall b. Expr b -> Expr b -> Expr b
App CoreExpr
fun (Type -> CoreExpr
forall b. Type -> Expr b
Type Type
ty), HasDebugCallStack => Type -> Type -> Type
Type -> Type -> Type
piResultTy Type
fun_ty Type
ty)
mkCoreAppTyped SDoc
_ (CoreExpr
fun, Type
fun_ty) (Coercion Coercion
co)
  = (CoreExpr -> CoreExpr -> CoreExpr
forall b. Expr b -> Expr b -> Expr b
App CoreExpr
fun (Coercion -> CoreExpr
forall b. Coercion -> Expr b
Coercion Coercion
co), Type -> Type
funResultTy Type
fun_ty)
mkCoreAppTyped SDoc
d (CoreExpr
fun, Type
fun_ty) CoreExpr
arg
  = ASSERT2( isFunTy fun_ty, ppr fun $$ ppr arg $$ d )
    (CoreExpr -> CoreExpr -> Type -> Type -> CoreExpr
mkValApp CoreExpr
fun CoreExpr
arg Type
arg_ty Type
res_ty, Type
res_ty)
  where
    (Type
arg_ty, Type
res_ty) = Type -> (Type, Type)
splitFunTy Type
fun_ty

mkValApp :: CoreExpr -> CoreExpr -> Type -> Type -> CoreExpr
-- Build an application (e1 e2),
-- or a strict binding  (case e2 of x -> e1 x)
-- using the latter when necessary to respect the let/app invariant
--   See Note [CoreSyn let/app invariant]
mkValApp :: CoreExpr -> CoreExpr -> Type -> Type -> CoreExpr
mkValApp CoreExpr
fun CoreExpr
arg Type
arg_ty Type
res_ty
  | Bool -> Bool
not (Type -> CoreExpr -> Bool
needsCaseBinding Type
arg_ty CoreExpr
arg)
  = CoreExpr -> CoreExpr -> CoreExpr
forall b. Expr b -> Expr b -> Expr b
App CoreExpr
fun CoreExpr
arg                -- The vastly common case
  | Bool
otherwise
  = CoreExpr -> CoreExpr -> Type -> Type -> CoreExpr
mkStrictApp CoreExpr
fun CoreExpr
arg Type
arg_ty Type
res_ty

{- *********************************************************************
*                                                                      *
              Building case expressions
*                                                                      *
********************************************************************* -}

mkWildEvBinder :: PredType -> EvVar
mkWildEvBinder :: Type -> Var
mkWildEvBinder Type
pred = Type -> Var
mkWildValBinder Type
pred

-- | Make a /wildcard binder/. This is typically used when you need a binder
-- that you expect to use only at a *binding* site.  Do not use it at
-- occurrence sites because it has a single, fixed unique, and it's very
-- easy to get into difficulties with shadowing.  That's why it is used so little.
-- See Note [WildCard binders] in SimplEnv
mkWildValBinder :: Type -> Id
mkWildValBinder :: Type -> Var
mkWildValBinder Type
ty = Name -> Type -> Var
mkLocalIdOrCoVar Name
wildCardName Type
ty

mkWildCase :: CoreExpr -> Type -> Type -> [CoreAlt] -> CoreExpr
-- Make a case expression whose case binder is unused
-- The alts and res_ty should not have any occurrences of WildId
mkWildCase :: CoreExpr -> Type -> Type -> [CoreAlt] -> CoreExpr
mkWildCase CoreExpr
scrut Type
scrut_ty Type
res_ty [CoreAlt]
alts
  = CoreExpr -> Var -> Type -> [CoreAlt] -> CoreExpr
forall b. Expr b -> b -> Type -> [Alt b] -> Expr b
Case CoreExpr
scrut (Type -> Var
mkWildValBinder Type
scrut_ty) Type
res_ty [CoreAlt]
alts

mkStrictApp :: CoreExpr -> CoreExpr -> Type -> Type -> CoreExpr
-- Build a strict application (case e2 of x -> e1 x)
mkStrictApp :: CoreExpr -> CoreExpr -> Type -> Type -> CoreExpr
mkStrictApp CoreExpr
fun CoreExpr
arg Type
arg_ty Type
res_ty
  = CoreExpr -> Var -> Type -> [CoreAlt] -> CoreExpr
forall b. Expr b -> b -> Type -> [Alt b] -> Expr b
Case CoreExpr
arg Var
arg_id Type
res_ty [(AltCon
DEFAULT,[],CoreExpr -> CoreExpr -> CoreExpr
forall b. Expr b -> Expr b -> Expr b
App CoreExpr
fun (Var -> CoreExpr
forall b. Var -> Expr b
Var Var
arg_id))]
       -- mkDefaultCase looks attractive here, and would be sound.
       -- But it uses (exprType alt_rhs) to compute the result type,
       -- whereas here we already know that the result type is res_ty
  where
    arg_id :: Var
arg_id = Type -> Var
mkWildValBinder Type
arg_ty
        -- Lots of shadowing, but it doesn't matter,
        -- because 'fun' and 'res_ty' should not have a free wild-id
        --
        -- This is Dangerous.  But this is the only place we play this
        -- game, mkStrictApp returns an expression that does not have
        -- a free wild-id.  So the only way 'fun' could get a free wild-id
        -- would be if you take apart this case expression (or some other
        -- expression that uses mkWildValBinder, of which there are not
        -- many), and pass a fragment of it as the fun part of a 'mkStrictApp'.

mkIfThenElse :: CoreExpr -> CoreExpr -> CoreExpr -> CoreExpr
mkIfThenElse :: CoreExpr -> CoreExpr -> CoreExpr -> CoreExpr
mkIfThenElse CoreExpr
guard CoreExpr
then_expr CoreExpr
else_expr
-- Not going to be refining, so okay to take the type of the "then" clause
  = CoreExpr -> Type -> Type -> [CoreAlt] -> CoreExpr
mkWildCase CoreExpr
guard Type
boolTy (CoreExpr -> Type
exprType CoreExpr
then_expr)
         [ (DataCon -> AltCon
DataAlt DataCon
falseDataCon, [], CoreExpr
else_expr),       -- Increasing order of tag!
           (DataCon -> AltCon
DataAlt DataCon
trueDataCon,  [], CoreExpr
then_expr) ]

castBottomExpr :: CoreExpr -> Type -> CoreExpr
-- (castBottomExpr e ty), assuming that 'e' diverges,
-- return an expression of type 'ty'
-- See Note [Empty case alternatives] in CoreSyn
castBottomExpr :: CoreExpr -> Type -> CoreExpr
castBottomExpr CoreExpr
e Type
res_ty
  | Type
e_ty Type -> Type -> Bool
`eqType` Type
res_ty = CoreExpr
e
  | Bool
otherwise            = CoreExpr -> Var -> Type -> [CoreAlt] -> CoreExpr
forall b. Expr b -> b -> Type -> [Alt b] -> Expr b
Case CoreExpr
e (Type -> Var
mkWildValBinder Type
e_ty) Type
res_ty []
  where
    e_ty :: Type
e_ty = CoreExpr -> Type
exprType CoreExpr
e

{-
************************************************************************
*                                                                      *
\subsection{Making literals}
*                                                                      *
************************************************************************
-}

-- | Create a 'CoreExpr' which will evaluate to the given @Int@
mkIntExpr :: DynFlags -> Integer -> CoreExpr        -- Result = I# i :: Int
mkIntExpr :: DynFlags -> Integer -> CoreExpr
mkIntExpr DynFlags
dflags Integer
i = DataCon -> [CoreExpr] -> CoreExpr
mkCoreConApps DataCon
intDataCon  [DynFlags -> Integer -> CoreExpr
forall b. DynFlags -> Integer -> Expr b
mkIntLit DynFlags
dflags Integer
i]

-- | Create a 'CoreExpr' which will evaluate to the given @Int@
mkIntExprInt :: DynFlags -> Int -> CoreExpr         -- Result = I# i :: Int
mkIntExprInt :: DynFlags -> Int -> CoreExpr
mkIntExprInt DynFlags
dflags Int
i = DataCon -> [CoreExpr] -> CoreExpr
mkCoreConApps DataCon
intDataCon  [DynFlags -> Int -> CoreExpr
forall b. DynFlags -> Int -> Expr b
mkIntLitInt DynFlags
dflags Int
i]

-- | Create a 'CoreExpr' which will evaluate to the a @Word@ with the given value
mkWordExpr :: DynFlags -> Integer -> CoreExpr
mkWordExpr :: DynFlags -> Integer -> CoreExpr
mkWordExpr DynFlags
dflags Integer
w = DataCon -> [CoreExpr] -> CoreExpr
mkCoreConApps DataCon
wordDataCon [DynFlags -> Integer -> CoreExpr
forall b. DynFlags -> Integer -> Expr b
mkWordLit DynFlags
dflags Integer
w]

-- | Create a 'CoreExpr' which will evaluate to the given @Word@
mkWordExprWord :: DynFlags -> Word -> CoreExpr
mkWordExprWord :: DynFlags -> Word -> CoreExpr
mkWordExprWord DynFlags
dflags Word
w = DataCon -> [CoreExpr] -> CoreExpr
mkCoreConApps DataCon
wordDataCon [DynFlags -> Word -> CoreExpr
forall b. DynFlags -> Word -> Expr b
mkWordLitWord DynFlags
dflags Word
w]

-- | Create a 'CoreExpr' which will evaluate to the given @Integer@
mkIntegerExpr  :: MonadThings m => Integer -> m CoreExpr  -- Result :: Integer
mkIntegerExpr :: Integer -> m CoreExpr
mkIntegerExpr Integer
i = do TyCon
t <- Name -> m TyCon
forall (m :: * -> *). MonadThings m => Name -> m TyCon
lookupTyCon Name
integerTyConName
                     CoreExpr -> m CoreExpr
forall (m :: * -> *) a. Monad m => a -> m a
return (Literal -> CoreExpr
forall b. Literal -> Expr b
Lit (Integer -> Type -> Literal
mkLitInteger Integer
i (TyCon -> Type
mkTyConTy TyCon
t)))

-- | Create a 'CoreExpr' which will evaluate to the given @Natural@
mkNaturalExpr  :: MonadThings m => Integer -> m CoreExpr
mkNaturalExpr :: Integer -> m CoreExpr
mkNaturalExpr Integer
i = do TyCon
t <- Name -> m TyCon
forall (m :: * -> *). MonadThings m => Name -> m TyCon
lookupTyCon Name
naturalTyConName
                     CoreExpr -> m CoreExpr
forall (m :: * -> *) a. Monad m => a -> m a
return (Literal -> CoreExpr
forall b. Literal -> Expr b
Lit (Integer -> Type -> Literal
mkLitNatural Integer
i (TyCon -> Type
mkTyConTy TyCon
t)))

-- | Create a 'CoreExpr' which will evaluate to the given @Float@
mkFloatExpr :: Float -> CoreExpr
mkFloatExpr :: Float -> CoreExpr
mkFloatExpr Float
f = DataCon -> [CoreExpr] -> CoreExpr
mkCoreConApps DataCon
floatDataCon [Float -> CoreExpr
forall b. Float -> Expr b
mkFloatLitFloat Float
f]

-- | Create a 'CoreExpr' which will evaluate to the given @Double@
mkDoubleExpr :: Double -> CoreExpr
mkDoubleExpr :: Double -> CoreExpr
mkDoubleExpr Double
d = DataCon -> [CoreExpr] -> CoreExpr
mkCoreConApps DataCon
doubleDataCon [Double -> CoreExpr
forall b. Double -> Expr b
mkDoubleLitDouble Double
d]


-- | Create a 'CoreExpr' which will evaluate to the given @Char@
mkCharExpr     :: Char             -> CoreExpr      -- Result = C# c :: Int
mkCharExpr :: Char -> CoreExpr
mkCharExpr Char
c = DataCon -> [CoreExpr] -> CoreExpr
mkCoreConApps DataCon
charDataCon [Char -> CoreExpr
forall b. Char -> Expr b
mkCharLit Char
c]

-- | Create a 'CoreExpr' which will evaluate to the given @String@
mkStringExpr   :: MonadThings m => String     -> m CoreExpr  -- Result :: String

-- | Create a 'CoreExpr' which will evaluate to a string morally equivalent to the given @FastString@
mkStringExprFS :: MonadThings m => FastString -> m CoreExpr  -- Result :: String

mkStringExpr :: String -> m CoreExpr
mkStringExpr String
str = FastString -> m CoreExpr
forall (m :: * -> *). MonadThings m => FastString -> m CoreExpr
mkStringExprFS (String -> FastString
mkFastString String
str)

mkStringExprFS :: FastString -> m CoreExpr
mkStringExprFS = (Name -> m Var) -> FastString -> m CoreExpr
forall (m :: * -> *).
Monad m =>
(Name -> m Var) -> FastString -> m CoreExpr
mkStringExprFSWith Name -> m Var
forall (m :: * -> *). MonadThings m => Name -> m Var
lookupId

mkStringExprFSWith :: Monad m => (Name -> m Id) -> FastString -> m CoreExpr
mkStringExprFSWith :: (Name -> m Var) -> FastString -> m CoreExpr
mkStringExprFSWith Name -> m Var
lookupM FastString
str
  | FastString -> Bool
nullFS FastString
str
  = CoreExpr -> m CoreExpr
forall (m :: * -> *) a. Monad m => a -> m a
return (Type -> CoreExpr
mkNilExpr Type
charTy)

  | (Char -> Bool) -> String -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
all Char -> Bool
safeChar String
chars
  = do Var
unpack_id <- Name -> m Var
lookupM Name
unpackCStringName
       CoreExpr -> m CoreExpr
forall (m :: * -> *) a. Monad m => a -> m a
return (CoreExpr -> CoreExpr -> CoreExpr
forall b. Expr b -> Expr b -> Expr b
App (Var -> CoreExpr
forall b. Var -> Expr b
Var Var
unpack_id) CoreExpr
forall b. Expr b
lit)

  | Bool
otherwise
  = do Var
unpack_utf8_id <- Name -> m Var
lookupM Name
unpackCStringUtf8Name
       CoreExpr -> m CoreExpr
forall (m :: * -> *) a. Monad m => a -> m a
return (CoreExpr -> CoreExpr -> CoreExpr
forall b. Expr b -> Expr b -> Expr b
App (Var -> CoreExpr
forall b. Var -> Expr b
Var Var
unpack_utf8_id) CoreExpr
forall b. Expr b
lit)

  where
    chars :: String
chars = FastString -> String
unpackFS FastString
str
    safeChar :: Char -> Bool
safeChar Char
c = Char -> Int
ord Char
c Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
>= Int
1 Bool -> Bool -> Bool
&& Char -> Int
ord Char
c Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
<= Int
0x7F
    lit :: Expr b
lit = Literal -> Expr b
forall b. Literal -> Expr b
Lit (ByteString -> Literal
LitString (FastString -> ByteString
bytesFS FastString
str))

{-
************************************************************************
*                                                                      *
\subsection{Tuple constructors}
*                                                                      *
************************************************************************
-}

{-
Creating tuples and their types for Core expressions

@mkBigCoreVarTup@ builds a tuple; the inverse to @mkTupleSelector@.

* If it has only one element, it is the identity function.

* If there are more elements than a big tuple can have, it nests
  the tuples.

Note [Flattening one-tuples]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
This family of functions creates a tuple of variables/expressions/types.
  mkCoreTup [e1,e2,e3] = (e1,e2,e3)
What if there is just one variable/expression/type in the argument?
We could do one of two things:

* Flatten it out, so that
    mkCoreTup [e1] = e1

* Build a one-tuple (see Note [One-tuples] in TysWiredIn)
    mkCoreTup1 [e1] = Unit e1
  We use a suffix "1" to indicate this.

Usually we want the former, but occasionally the latter.

NB: The logic in tupleDataCon knows about () and Unit and (,), etc.

Note [Don't flatten tuples from HsSyn]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
If we get an explicit 1-tuple from HsSyn somehow (likely: Template Haskell),
we should treat it really as a 1-tuple, without flattening. Note that a
1-tuple and a flattened value have different performance and laziness
characteristics, so should just do what we're asked.

This arose from discussions in #16881.

One-tuples that arise internally depend on the circumstance; often flattening
is a good idea. Decisions are made on a case-by-case basis.

-}

-- | Build the type of a small tuple that holds the specified variables
-- One-tuples are flattened; see Note [Flattening one-tuples]
mkCoreVarTupTy :: [Id] -> Type
mkCoreVarTupTy :: [Var] -> Type
mkCoreVarTupTy [Var]
ids = [Type] -> Type
mkBoxedTupleTy ((Var -> Type) -> [Var] -> [Type]
forall a b. (a -> b) -> [a] -> [b]
map Var -> Type
idType [Var]
ids)

-- | Build a small tuple holding the specified expressions
-- One-tuples are flattened; see Note [Flattening one-tuples]
mkCoreTup :: [CoreExpr] -> CoreExpr
mkCoreTup :: [CoreExpr] -> CoreExpr
mkCoreTup [CoreExpr
c] = CoreExpr
c
mkCoreTup [CoreExpr]
cs  = [CoreExpr] -> CoreExpr
mkCoreTup1 [CoreExpr]
cs   -- non-1-tuples are uniform

-- | Build a small tuple holding the specified expressions
-- One-tuples are *not* flattened; see Note [Flattening one-tuples]
-- See also Note [Don't flatten tuples from HsSyn]
mkCoreTup1 :: [CoreExpr] -> CoreExpr
mkCoreTup1 :: [CoreExpr] -> CoreExpr
mkCoreTup1 [CoreExpr]
cs = DataCon -> [CoreExpr] -> CoreExpr
mkCoreConApps (Boxity -> Int -> DataCon
tupleDataCon Boxity
Boxed ([CoreExpr] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length [CoreExpr]
cs))
                              ((CoreExpr -> CoreExpr) -> [CoreExpr] -> [CoreExpr]
forall a b. (a -> b) -> [a] -> [b]
map (Type -> CoreExpr
forall b. Type -> Expr b
Type (Type -> CoreExpr) -> (CoreExpr -> Type) -> CoreExpr -> CoreExpr
forall b c a. (b -> c) -> (a -> b) -> a -> c
. CoreExpr -> Type
exprType) [CoreExpr]
cs [CoreExpr] -> [CoreExpr] -> [CoreExpr]
forall a. [a] -> [a] -> [a]
++ [CoreExpr]
cs)

-- | Build a small unboxed tuple holding the specified expressions,
-- with the given types. The types must be the types of the expressions.
-- Do not include the RuntimeRep specifiers; this function calculates them
-- for you.
-- Does /not/ flatten one-tuples; see Note [Flattening one-tuples]
mkCoreUbxTup :: [Type] -> [CoreExpr] -> CoreExpr
mkCoreUbxTup :: [Type] -> [CoreExpr] -> CoreExpr
mkCoreUbxTup [Type]
tys [CoreExpr]
exps
  = ASSERT( tys `equalLength` exps)
    DataCon -> [CoreExpr] -> CoreExpr
mkCoreConApps (Boxity -> Int -> DataCon
tupleDataCon Boxity
Unboxed ([Type] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length [Type]
tys))
             ((Type -> CoreExpr) -> [Type] -> [CoreExpr]
forall a b. (a -> b) -> [a] -> [b]
map (Type -> CoreExpr
forall b. Type -> Expr b
Type (Type -> CoreExpr) -> (Type -> Type) -> Type -> CoreExpr
forall b c a. (b -> c) -> (a -> b) -> a -> c
. HasDebugCallStack => Type -> Type
Type -> Type
getRuntimeRep) [Type]
tys [CoreExpr] -> [CoreExpr] -> [CoreExpr]
forall a. [a] -> [a] -> [a]
++ (Type -> CoreExpr) -> [Type] -> [CoreExpr]
forall a b. (a -> b) -> [a] -> [b]
map Type -> CoreExpr
forall b. Type -> Expr b
Type [Type]
tys [CoreExpr] -> [CoreExpr] -> [CoreExpr]
forall a. [a] -> [a] -> [a]
++ [CoreExpr]
exps)

-- | Make a core tuple of the given boxity; don't flatten 1-tuples
mkCoreTupBoxity :: Boxity -> [CoreExpr] -> CoreExpr
mkCoreTupBoxity :: Boxity -> [CoreExpr] -> CoreExpr
mkCoreTupBoxity Boxity
Boxed   [CoreExpr]
exps = [CoreExpr] -> CoreExpr
mkCoreTup1 [CoreExpr]
exps
mkCoreTupBoxity Boxity
Unboxed [CoreExpr]
exps = [Type] -> [CoreExpr] -> CoreExpr
mkCoreUbxTup ((CoreExpr -> Type) -> [CoreExpr] -> [Type]
forall a b. (a -> b) -> [a] -> [b]
map CoreExpr -> Type
exprType [CoreExpr]
exps) [CoreExpr]
exps

-- | Build a big tuple holding the specified variables
-- One-tuples are flattened; see Note [Flattening one-tuples]
mkBigCoreVarTup :: [Id] -> CoreExpr
mkBigCoreVarTup :: [Var] -> CoreExpr
mkBigCoreVarTup [Var]
ids = [CoreExpr] -> CoreExpr
mkBigCoreTup ((Var -> CoreExpr) -> [Var] -> [CoreExpr]
forall a b. (a -> b) -> [a] -> [b]
map Var -> CoreExpr
forall b. Var -> Expr b
Var [Var]
ids)

mkBigCoreVarTup1 :: [Id] -> CoreExpr
-- Same as mkBigCoreVarTup, but one-tuples are NOT flattened
--                          see Note [Flattening one-tuples]
mkBigCoreVarTup1 :: [Var] -> CoreExpr
mkBigCoreVarTup1 [Var
id] = DataCon -> [CoreExpr] -> CoreExpr
mkCoreConApps (Boxity -> Int -> DataCon
tupleDataCon Boxity
Boxed Int
1)
                                      [Type -> CoreExpr
forall b. Type -> Expr b
Type (Var -> Type
idType Var
id), Var -> CoreExpr
forall b. Var -> Expr b
Var Var
id]
mkBigCoreVarTup1 [Var]
ids  = [CoreExpr] -> CoreExpr
mkBigCoreTup ((Var -> CoreExpr) -> [Var] -> [CoreExpr]
forall a b. (a -> b) -> [a] -> [b]
map Var -> CoreExpr
forall b. Var -> Expr b
Var [Var]
ids)

-- | Build the type of a big tuple that holds the specified variables
-- One-tuples are flattened; see Note [Flattening one-tuples]
mkBigCoreVarTupTy :: [Id] -> Type
mkBigCoreVarTupTy :: [Var] -> Type
mkBigCoreVarTupTy [Var]
ids = [Type] -> Type
mkBigCoreTupTy ((Var -> Type) -> [Var] -> [Type]
forall a b. (a -> b) -> [a] -> [b]
map Var -> Type
idType [Var]
ids)

-- | Build a big tuple holding the specified expressions
-- One-tuples are flattened; see Note [Flattening one-tuples]
mkBigCoreTup :: [CoreExpr] -> CoreExpr
mkBigCoreTup :: [CoreExpr] -> CoreExpr
mkBigCoreTup = ([CoreExpr] -> CoreExpr) -> [CoreExpr] -> CoreExpr
forall a. ([a] -> a) -> [a] -> a
mkChunkified [CoreExpr] -> CoreExpr
mkCoreTup

-- | Build the type of a big tuple that holds the specified type of thing
-- One-tuples are flattened; see Note [Flattening one-tuples]
mkBigCoreTupTy :: [Type] -> Type
mkBigCoreTupTy :: [Type] -> Type
mkBigCoreTupTy = ([Type] -> Type) -> [Type] -> Type
forall a. ([a] -> a) -> [a] -> a
mkChunkified [Type] -> Type
mkBoxedTupleTy

-- | The unit expression
unitExpr :: CoreExpr
unitExpr :: CoreExpr
unitExpr = Var -> CoreExpr
forall b. Var -> Expr b
Var Var
unitDataConId

{-
************************************************************************
*                                                                      *
\subsection{Tuple destructors}
*                                                                      *
************************************************************************
-}

-- | Builds a selector which scrutises the given
-- expression and extracts the one name from the list given.
-- If you want the no-shadowing rule to apply, the caller
-- is responsible for making sure that none of these names
-- are in scope.
--
-- If there is just one 'Id' in the tuple, then the selector is
-- just the identity.
--
-- If necessary, we pattern match on a \"big\" tuple.
mkTupleSelector, mkTupleSelector1
    :: [Id]         -- ^ The 'Id's to pattern match the tuple against
    -> Id           -- ^ The 'Id' to select
    -> Id           -- ^ A variable of the same type as the scrutinee
    -> CoreExpr     -- ^ Scrutinee
    -> CoreExpr     -- ^ Selector expression

-- mkTupleSelector [a,b,c,d] b v e
--          = case e of v {
--                (p,q) -> case p of p {
--                           (a,b) -> b }}
-- We use 'tpl' vars for the p,q, since shadowing does not matter.
--
-- In fact, it's more convenient to generate it innermost first, getting
--
--        case (case e of v
--                (p,q) -> p) of p
--          (a,b) -> b
mkTupleSelector :: [Var] -> Var -> Var -> CoreExpr -> CoreExpr
mkTupleSelector [Var]
vars Var
the_var Var
scrut_var CoreExpr
scrut
  = [[Var]] -> Var -> CoreExpr
mk_tup_sel ([Var] -> [[Var]]
forall a. [a] -> [[a]]
chunkify [Var]
vars) Var
the_var
  where
    mk_tup_sel :: [[Var]] -> Var -> CoreExpr
mk_tup_sel [[Var]
vars] Var
the_var = [Var] -> Var -> Var -> CoreExpr -> CoreExpr
mkSmallTupleSelector [Var]
vars Var
the_var Var
scrut_var CoreExpr
scrut
    mk_tup_sel [[Var]]
vars_s Var
the_var = [Var] -> Var -> Var -> CoreExpr -> CoreExpr
mkSmallTupleSelector [Var]
group Var
the_var Var
tpl_v (CoreExpr -> CoreExpr) -> CoreExpr -> CoreExpr
forall a b. (a -> b) -> a -> b
$
                                [[Var]] -> Var -> CoreExpr
mk_tup_sel ([Var] -> [[Var]]
forall a. [a] -> [[a]]
chunkify [Var]
tpl_vs) Var
tpl_v
        where
          tpl_tys :: [Type]
tpl_tys = [[Type] -> Type
mkBoxedTupleTy ((Var -> Type) -> [Var] -> [Type]
forall a b. (a -> b) -> [a] -> [b]
map Var -> Type
idType [Var]
gp) | [Var]
gp <- [[Var]]
vars_s]
          tpl_vs :: [Var]
tpl_vs  = [Type] -> [Var]
mkTemplateLocals [Type]
tpl_tys
          [(Var
tpl_v, [Var]
group)] = [(Var
tpl,[Var]
gp) | (Var
tpl,[Var]
gp) <- String -> [Var] -> [[Var]] -> [(Var, [Var])]
forall a b. String -> [a] -> [b] -> [(a, b)]
zipEqual String
"mkTupleSelector" [Var]
tpl_vs [[Var]]
vars_s,
                                         Var
the_var Var -> [Var] -> Bool
forall (t :: * -> *) a. (Foldable t, Eq a) => a -> t a -> Bool
`elem` [Var]
gp ]
-- ^ 'mkTupleSelector1' is like 'mkTupleSelector'
-- but one-tuples are NOT flattened (see Note [Flattening one-tuples])
mkTupleSelector1 :: [Var] -> Var -> Var -> CoreExpr -> CoreExpr
mkTupleSelector1 [Var]
vars Var
the_var Var
scrut_var CoreExpr
scrut
  | [Var
_] <- [Var]
vars
  = [Var] -> Var -> Var -> CoreExpr -> CoreExpr
mkSmallTupleSelector1 [Var]
vars Var
the_var Var
scrut_var CoreExpr
scrut
  | Bool
otherwise
  = [Var] -> Var -> Var -> CoreExpr -> CoreExpr
mkTupleSelector [Var]
vars Var
the_var Var
scrut_var CoreExpr
scrut

-- | Like 'mkTupleSelector' but for tuples that are guaranteed
-- never to be \"big\".
--
-- > mkSmallTupleSelector [x] x v e = [| e |]
-- > mkSmallTupleSelector [x,y,z] x v e = [| case e of v { (x,y,z) -> x } |]
mkSmallTupleSelector, mkSmallTupleSelector1
          :: [Id]        -- The tuple args
          -> Id          -- The selected one
          -> Id          -- A variable of the same type as the scrutinee
          -> CoreExpr    -- Scrutinee
          -> CoreExpr
mkSmallTupleSelector :: [Var] -> Var -> Var -> CoreExpr -> CoreExpr
mkSmallTupleSelector [Var
var] Var
should_be_the_same_var Var
_ CoreExpr
scrut
  = ASSERT(var == should_be_the_same_var)
    CoreExpr
scrut  -- Special case for 1-tuples
mkSmallTupleSelector [Var]
vars Var
the_var Var
scrut_var CoreExpr
scrut
  = [Var] -> Var -> Var -> CoreExpr -> CoreExpr
mkSmallTupleSelector1 [Var]
vars Var
the_var Var
scrut_var CoreExpr
scrut

-- ^ 'mkSmallTupleSelector1' is like 'mkSmallTupleSelector'
-- but one-tuples are NOT flattened (see Note [Flattening one-tuples])
mkSmallTupleSelector1 :: [Var] -> Var -> Var -> CoreExpr -> CoreExpr
mkSmallTupleSelector1 [Var]
vars Var
the_var Var
scrut_var CoreExpr
scrut
  = ASSERT( notNull vars )
    CoreExpr -> Var -> Type -> [CoreAlt] -> CoreExpr
forall b. Expr b -> b -> Type -> [Alt b] -> Expr b
Case CoreExpr
scrut Var
scrut_var (Var -> Type
idType Var
the_var)
         [(DataCon -> AltCon
DataAlt (Boxity -> Int -> DataCon
tupleDataCon Boxity
Boxed ([Var] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length [Var]
vars)), [Var]
vars, Var -> CoreExpr
forall b. Var -> Expr b
Var Var
the_var)]

-- | A generalization of 'mkTupleSelector', allowing the body
-- of the case to be an arbitrary expression.
--
-- To avoid shadowing, we use uniques to invent new variables.
--
-- If necessary we pattern match on a \"big\" tuple.
mkTupleCase :: UniqSupply       -- ^ For inventing names of intermediate variables
            -> [Id]             -- ^ The tuple identifiers to pattern match on
            -> CoreExpr         -- ^ Body of the case
            -> Id               -- ^ A variable of the same type as the scrutinee
            -> CoreExpr         -- ^ Scrutinee
            -> CoreExpr
-- ToDo: eliminate cases where none of the variables are needed.
--
--         mkTupleCase uniqs [a,b,c,d] body v e
--           = case e of v { (p,q) ->
--             case p of p { (a,b) ->
--             case q of q { (c,d) ->
--             body }}}
mkTupleCase :: UniqSupply -> [Var] -> CoreExpr -> Var -> CoreExpr -> CoreExpr
mkTupleCase UniqSupply
uniqs [Var]
vars CoreExpr
body Var
scrut_var CoreExpr
scrut
  = UniqSupply -> [[Var]] -> CoreExpr -> CoreExpr
mk_tuple_case UniqSupply
uniqs ([Var] -> [[Var]]
forall a. [a] -> [[a]]
chunkify [Var]
vars) CoreExpr
body
  where
    -- This is the case where don't need any nesting
    mk_tuple_case :: UniqSupply -> [[Var]] -> CoreExpr -> CoreExpr
mk_tuple_case UniqSupply
_ [[Var]
vars] CoreExpr
body
      = [Var] -> CoreExpr -> Var -> CoreExpr -> CoreExpr
mkSmallTupleCase [Var]
vars CoreExpr
body Var
scrut_var CoreExpr
scrut

    -- This is the case where we must make nest tuples at least once
    mk_tuple_case UniqSupply
us [[Var]]
vars_s CoreExpr
body
      = let (UniqSupply
us', [Var]
vars', CoreExpr
body') = ([Var]
 -> (UniqSupply, [Var], CoreExpr) -> (UniqSupply, [Var], CoreExpr))
-> (UniqSupply, [Var], CoreExpr)
-> [[Var]]
-> (UniqSupply, [Var], CoreExpr)
forall (t :: * -> *) a b.
Foldable t =>
(a -> b -> b) -> b -> t a -> b
foldr [Var]
-> (UniqSupply, [Var], CoreExpr) -> (UniqSupply, [Var], CoreExpr)
one_tuple_case (UniqSupply
us, [], CoreExpr
body) [[Var]]
vars_s
            in UniqSupply -> [[Var]] -> CoreExpr -> CoreExpr
mk_tuple_case UniqSupply
us' ([Var] -> [[Var]]
forall a. [a] -> [[a]]
chunkify [Var]
vars') CoreExpr
body'

    one_tuple_case :: [Var]
-> (UniqSupply, [Var], CoreExpr) -> (UniqSupply, [Var], CoreExpr)
one_tuple_case [Var]
chunk_vars (UniqSupply
us, [Var]
vs, CoreExpr
body)
      = let (Unique
uniq, UniqSupply
us') = UniqSupply -> (Unique, UniqSupply)
takeUniqFromSupply UniqSupply
us
            scrut_var :: Var
scrut_var = FastString -> Unique -> Type -> Var
mkSysLocal (String -> FastString
fsLit String
"ds") Unique
uniq
              ([Type] -> Type
mkBoxedTupleTy ((Var -> Type) -> [Var] -> [Type]
forall a b. (a -> b) -> [a] -> [b]
map Var -> Type
idType [Var]
chunk_vars))
            body' :: CoreExpr
body' = [Var] -> CoreExpr -> Var -> CoreExpr -> CoreExpr
mkSmallTupleCase [Var]
chunk_vars CoreExpr
body Var
scrut_var (Var -> CoreExpr
forall b. Var -> Expr b
Var Var
scrut_var)
        in (UniqSupply
us', Var
scrut_varVar -> [Var] -> [Var]
forall a. a -> [a] -> [a]
:[Var]
vs, CoreExpr
body')

-- | As 'mkTupleCase', but for a tuple that is small enough to be guaranteed
-- not to need nesting.
mkSmallTupleCase
        :: [Id]         -- ^ The tuple args
        -> CoreExpr     -- ^ Body of the case
        -> Id           -- ^ A variable of the same type as the scrutinee
        -> CoreExpr     -- ^ Scrutinee
        -> CoreExpr

mkSmallTupleCase :: [Var] -> CoreExpr -> Var -> CoreExpr -> CoreExpr
mkSmallTupleCase [Var
var] CoreExpr
body Var
_scrut_var CoreExpr
scrut
  = Var -> CoreExpr -> CoreExpr -> CoreExpr
bindNonRec Var
var CoreExpr
scrut CoreExpr
body
mkSmallTupleCase [Var]
vars CoreExpr
body Var
scrut_var CoreExpr
scrut
-- One branch no refinement?
  = CoreExpr -> Var -> Type -> [CoreAlt] -> CoreExpr
forall b. Expr b -> b -> Type -> [Alt b] -> Expr b
Case CoreExpr
scrut Var
scrut_var (CoreExpr -> Type
exprType CoreExpr
body)
         [(DataCon -> AltCon
DataAlt (Boxity -> Int -> DataCon
tupleDataCon Boxity
Boxed ([Var] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length [Var]
vars)), [Var]
vars, CoreExpr
body)]

{-
************************************************************************
*                                                                      *
                Floats
*                                                                      *
************************************************************************
-}

data FloatBind
  = FloatLet  CoreBind
  | FloatCase CoreExpr Id AltCon [Var]
      -- case e of y { C ys -> ... }
      -- See Note [Floating single-alternative cases] in SetLevels

instance Outputable FloatBind where
  ppr :: FloatBind -> SDoc
ppr (FloatLet CoreBind
b) = String -> SDoc
text String
"LET" SDoc -> SDoc -> SDoc
<+> CoreBind -> SDoc
forall a. Outputable a => a -> SDoc
ppr CoreBind
b
  ppr (FloatCase CoreExpr
e Var
b AltCon
c [Var]
bs) = SDoc -> Int -> SDoc -> SDoc
hang (String -> SDoc
text String
"CASE" SDoc -> SDoc -> SDoc
<+> CoreExpr -> SDoc
forall a. Outputable a => a -> SDoc
ppr CoreExpr
e SDoc -> SDoc -> SDoc
<+> PtrString -> SDoc
ptext (String -> PtrString
sLit String
"of") SDoc -> SDoc -> SDoc
<+> Var -> SDoc
forall a. Outputable a => a -> SDoc
ppr Var
b)
                                Int
2 (AltCon -> SDoc
forall a. Outputable a => a -> SDoc
ppr AltCon
c SDoc -> SDoc -> SDoc
<+> [Var] -> SDoc
forall a. Outputable a => a -> SDoc
ppr [Var]
bs)

wrapFloat :: FloatBind -> CoreExpr -> CoreExpr
wrapFloat :: FloatBind -> CoreExpr -> CoreExpr
wrapFloat (FloatLet CoreBind
defns)       CoreExpr
body = CoreBind -> CoreExpr -> CoreExpr
forall b. Bind b -> Expr b -> Expr b
Let CoreBind
defns CoreExpr
body
wrapFloat (FloatCase CoreExpr
e Var
b AltCon
con [Var]
bs) CoreExpr
body = CoreExpr -> Var -> AltCon -> [Var] -> CoreExpr -> CoreExpr
mkSingleAltCase CoreExpr
e Var
b AltCon
con [Var]
bs CoreExpr
body

-- | Applies the floats from right to left. That is @wrapFloats [b1, b2, …, bn]
-- u = let b1 in let b2 in … in let bn in u@
wrapFloats :: [FloatBind] -> CoreExpr -> CoreExpr
wrapFloats :: [FloatBind] -> CoreExpr -> CoreExpr
wrapFloats [FloatBind]
floats CoreExpr
expr = (FloatBind -> CoreExpr -> CoreExpr)
-> CoreExpr -> [FloatBind] -> CoreExpr
forall (t :: * -> *) a b.
Foldable t =>
(a -> b -> b) -> b -> t a -> b
foldr FloatBind -> CoreExpr -> CoreExpr
wrapFloat CoreExpr
expr [FloatBind]
floats

bindBindings :: CoreBind -> [Var]
bindBindings :: CoreBind -> [Var]
bindBindings (NonRec Var
b CoreExpr
_) = [Var
b]
bindBindings (Rec [(Var, CoreExpr)]
bnds) = ((Var, CoreExpr) -> Var) -> [(Var, CoreExpr)] -> [Var]
forall a b. (a -> b) -> [a] -> [b]
map (Var, CoreExpr) -> Var
forall a b. (a, b) -> a
fst [(Var, CoreExpr)]
bnds

floatBindings :: FloatBind -> [Var]
floatBindings :: FloatBind -> [Var]
floatBindings (FloatLet CoreBind
bnd) = CoreBind -> [Var]
bindBindings CoreBind
bnd
floatBindings (FloatCase CoreExpr
_ Var
b AltCon
_ [Var]
bs) = Var
bVar -> [Var] -> [Var]
forall a. a -> [a] -> [a]
:[Var]
bs

{-
************************************************************************
*                                                                      *
\subsection{Common list manipulation expressions}
*                                                                      *
************************************************************************

Call the constructor Ids when building explicit lists, so that they
interact well with rules.
-}

-- | Makes a list @[]@ for lists of the specified type
mkNilExpr :: Type -> CoreExpr
mkNilExpr :: Type -> CoreExpr
mkNilExpr Type
ty = DataCon -> [CoreExpr] -> CoreExpr
mkCoreConApps DataCon
nilDataCon [Type -> CoreExpr
forall b. Type -> Expr b
Type Type
ty]

-- | Makes a list @(:)@ for lists of the specified type
mkConsExpr :: Type -> CoreExpr -> CoreExpr -> CoreExpr
mkConsExpr :: Type -> CoreExpr -> CoreExpr -> CoreExpr
mkConsExpr Type
ty CoreExpr
hd CoreExpr
tl = DataCon -> [CoreExpr] -> CoreExpr
mkCoreConApps DataCon
consDataCon [Type -> CoreExpr
forall b. Type -> Expr b
Type Type
ty, CoreExpr
hd, CoreExpr
tl]

-- | Make a list containing the given expressions, where the list has the given type
mkListExpr :: Type -> [CoreExpr] -> CoreExpr
mkListExpr :: Type -> [CoreExpr] -> CoreExpr
mkListExpr Type
ty [CoreExpr]
xs = (CoreExpr -> CoreExpr -> CoreExpr)
-> CoreExpr -> [CoreExpr] -> CoreExpr
forall (t :: * -> *) a b.
Foldable t =>
(a -> b -> b) -> b -> t a -> b
foldr (Type -> CoreExpr -> CoreExpr -> CoreExpr
mkConsExpr Type
ty) (Type -> CoreExpr
mkNilExpr Type
ty) [CoreExpr]
xs

-- | Make a fully applied 'foldr' expression
mkFoldrExpr :: MonadThings m
            => Type             -- ^ Element type of the list
            -> Type             -- ^ Fold result type
            -> CoreExpr         -- ^ "Cons" function expression for the fold
            -> CoreExpr         -- ^ "Nil" expression for the fold
            -> CoreExpr         -- ^ List expression being folded acress
            -> m CoreExpr
mkFoldrExpr :: Type -> Type -> CoreExpr -> CoreExpr -> CoreExpr -> m CoreExpr
mkFoldrExpr Type
elt_ty Type
result_ty CoreExpr
c CoreExpr
n CoreExpr
list = do
    Var
foldr_id <- Name -> m Var
forall (m :: * -> *). MonadThings m => Name -> m Var
lookupId Name
foldrName
    CoreExpr -> m CoreExpr
forall (m :: * -> *) a. Monad m => a -> m a
return (Var -> CoreExpr
forall b. Var -> Expr b
Var Var
foldr_id CoreExpr -> CoreExpr -> CoreExpr
forall b. Expr b -> Expr b -> Expr b
`App` Type -> CoreExpr
forall b. Type -> Expr b
Type Type
elt_ty
           CoreExpr -> CoreExpr -> CoreExpr
forall b. Expr b -> Expr b -> Expr b
`App` Type -> CoreExpr
forall b. Type -> Expr b
Type Type
result_ty
           CoreExpr -> CoreExpr -> CoreExpr
forall b. Expr b -> Expr b -> Expr b
`App` CoreExpr
c
           CoreExpr -> CoreExpr -> CoreExpr
forall b. Expr b -> Expr b -> Expr b
`App` CoreExpr
n
           CoreExpr -> CoreExpr -> CoreExpr
forall b. Expr b -> Expr b -> Expr b
`App` CoreExpr
list)

-- | Make a 'build' expression applied to a locally-bound worker function
mkBuildExpr :: (MonadFail.MonadFail m, MonadThings m, MonadUnique m)
            => Type                                     -- ^ Type of list elements to be built
            -> ((Id, Type) -> (Id, Type) -> m CoreExpr) -- ^ Function that, given information about the 'Id's
                                                        -- of the binders for the build worker function, returns
                                                        -- the body of that worker
            -> m CoreExpr
mkBuildExpr :: Type -> ((Var, Type) -> (Var, Type) -> m CoreExpr) -> m CoreExpr
mkBuildExpr Type
elt_ty (Var, Type) -> (Var, Type) -> m CoreExpr
mk_build_inside = do
    [Var
n_tyvar] <- [Var] -> m [Var]
forall (m :: * -> *). MonadUnique m => [Var] -> m [Var]
newTyVars [Var
alphaTyVar]
    let n_ty :: Type
n_ty = Var -> Type
mkTyVarTy Var
n_tyvar
        c_ty :: Type
c_ty = [Type] -> Type -> Type
mkVisFunTys [Type
elt_ty, Type
n_ty] Type
n_ty
    [Var
c, Var
n] <- [m Var] -> m [Var]
forall (t :: * -> *) (m :: * -> *) a.
(Traversable t, Monad m) =>
t (m a) -> m (t a)
sequence [FastString -> Type -> m Var
forall (m :: * -> *). MonadUnique m => FastString -> Type -> m Var
mkSysLocalM (String -> FastString
fsLit String
"c") Type
c_ty, FastString -> Type -> m Var
forall (m :: * -> *). MonadUnique m => FastString -> Type -> m Var
mkSysLocalM (String -> FastString
fsLit String
"n") Type
n_ty]

    CoreExpr
build_inside <- (Var, Type) -> (Var, Type) -> m CoreExpr
mk_build_inside (Var
c, Type
c_ty) (Var
n, Type
n_ty)

    Var
build_id <- Name -> m Var
forall (m :: * -> *). MonadThings m => Name -> m Var
lookupId Name
buildName
    CoreExpr -> m CoreExpr
forall (m :: * -> *) a. Monad m => a -> m a
return (CoreExpr -> m CoreExpr) -> CoreExpr -> m CoreExpr
forall a b. (a -> b) -> a -> b
$ Var -> CoreExpr
forall b. Var -> Expr b
Var Var
build_id CoreExpr -> CoreExpr -> CoreExpr
forall b. Expr b -> Expr b -> Expr b
`App` Type -> CoreExpr
forall b. Type -> Expr b
Type Type
elt_ty CoreExpr -> CoreExpr -> CoreExpr
forall b. Expr b -> Expr b -> Expr b
`App` [Var] -> CoreExpr -> CoreExpr
forall b. [b] -> Expr b -> Expr b
mkLams [Var
n_tyvar, Var
c, Var
n] CoreExpr
build_inside
  where
    newTyVars :: [Var] -> m [Var]
newTyVars [Var]
tyvar_tmpls = do
      [Unique]
uniqs <- m [Unique]
forall (m :: * -> *). MonadUnique m => m [Unique]
getUniquesM
      [Var] -> m [Var]
forall (m :: * -> *) a. Monad m => a -> m a
return ((Var -> Unique -> Var) -> [Var] -> [Unique] -> [Var]
forall a b c. (a -> b -> c) -> [a] -> [b] -> [c]
zipWith Var -> Unique -> Var
setTyVarUnique [Var]
tyvar_tmpls [Unique]
uniqs)

{-
************************************************************************
*                                                                      *
             Manipulating Maybe data type
*                                                                      *
************************************************************************
-}


-- | Makes a Nothing for the specified type
mkNothingExpr :: Type -> CoreExpr
mkNothingExpr :: Type -> CoreExpr
mkNothingExpr Type
ty = DataCon -> [CoreExpr] -> CoreExpr
forall b. DataCon -> [Arg b] -> Arg b
mkConApp DataCon
nothingDataCon [Type -> CoreExpr
forall b. Type -> Expr b
Type Type
ty]

-- | Makes a Just from a value of the specified type
mkJustExpr :: Type -> CoreExpr -> CoreExpr
mkJustExpr :: Type -> CoreExpr -> CoreExpr
mkJustExpr Type
ty CoreExpr
val = DataCon -> [CoreExpr] -> CoreExpr
forall b. DataCon -> [Arg b] -> Arg b
mkConApp DataCon
justDataCon [Type -> CoreExpr
forall b. Type -> Expr b
Type Type
ty, CoreExpr
val]


{-
************************************************************************
*                                                                      *
                      Error expressions
*                                                                      *
************************************************************************
-}

mkRuntimeErrorApp
        :: Id           -- Should be of type (forall a. Addr# -> a)
                        --      where Addr# points to a UTF8 encoded string
        -> Type         -- The type to instantiate 'a'
        -> String       -- The string to print
        -> CoreExpr

mkRuntimeErrorApp :: Var -> Type -> String -> CoreExpr
mkRuntimeErrorApp Var
err_id Type
res_ty String
err_msg
  = CoreExpr -> [CoreExpr] -> CoreExpr
forall b. Expr b -> [Expr b] -> Expr b
mkApps (Var -> CoreExpr
forall b. Var -> Expr b
Var Var
err_id) [ Type -> CoreExpr
forall b. Type -> Expr b
Type (HasDebugCallStack => Type -> Type
Type -> Type
getRuntimeRep Type
res_ty)
                        , Type -> CoreExpr
forall b. Type -> Expr b
Type Type
res_ty, CoreExpr
forall b. Expr b
err_string ]
  where
    err_string :: Expr b
err_string = Literal -> Expr b
forall b. Literal -> Expr b
Lit (String -> Literal
mkLitString String
err_msg)

mkImpossibleExpr :: Type -> CoreExpr
mkImpossibleExpr :: Type -> CoreExpr
mkImpossibleExpr Type
res_ty
  = Var -> Type -> String -> CoreExpr
mkRuntimeErrorApp Var
rUNTIME_ERROR_ID Type
res_ty String
"Impossible case alternative"

{-
************************************************************************
*                                                                      *
                     Error Ids
*                                                                      *
************************************************************************

GHC randomly injects these into the code.

@patError@ is just a version of @error@ for pattern-matching
failures.  It knows various ``codes'' which expand to longer
strings---this saves space!

@absentErr@ is a thing we put in for ``absent'' arguments.  They jolly
well shouldn't be yanked on, but if one is, then you will get a
friendly message from @absentErr@ (rather than a totally random
crash).

@parError@ is a special version of @error@ which the compiler does
not know to be a bottoming Id.  It is used in the @_par_@ and @_seq_@
templates, but we don't ever expect to generate code for it.
-}

errorIds :: [Id]
errorIds :: [Var]
errorIds
  = [ Var
rUNTIME_ERROR_ID,
      Var
nON_EXHAUSTIVE_GUARDS_ERROR_ID,
      Var
nO_METHOD_BINDING_ERROR_ID,
      Var
pAT_ERROR_ID,
      Var
rEC_CON_ERROR_ID,
      Var
rEC_SEL_ERROR_ID,
      Var
aBSENT_ERROR_ID,
      Var
tYPE_ERROR_ID   -- Used with Opt_DeferTypeErrors, see #10284
      ]

recSelErrorName, runtimeErrorName, absentErrorName :: Name
recConErrorName, patErrorName :: Name
nonExhaustiveGuardsErrorName, noMethodBindingErrorName :: Name
typeErrorName :: Name
absentSumFieldErrorName :: Name

recSelErrorName :: Name
recSelErrorName     = String -> Unique -> Var -> Name
err_nm String
"recSelError"     Unique
recSelErrorIdKey     Var
rEC_SEL_ERROR_ID
absentErrorName :: Name
absentErrorName     = String -> Unique -> Var -> Name
err_nm String
"absentError"     Unique
absentErrorIdKey     Var
aBSENT_ERROR_ID
absentSumFieldErrorName :: Name
absentSumFieldErrorName = String -> Unique -> Var -> Name
err_nm String
"absentSumFieldError"  Unique
absentSumFieldErrorIdKey
                            Var
aBSENT_SUM_FIELD_ERROR_ID
runtimeErrorName :: Name
runtimeErrorName    = String -> Unique -> Var -> Name
err_nm String
"runtimeError"    Unique
runtimeErrorIdKey    Var
rUNTIME_ERROR_ID
recConErrorName :: Name
recConErrorName     = String -> Unique -> Var -> Name
err_nm String
"recConError"     Unique
recConErrorIdKey     Var
rEC_CON_ERROR_ID
patErrorName :: Name
patErrorName        = String -> Unique -> Var -> Name
err_nm String
"patError"        Unique
patErrorIdKey        Var
pAT_ERROR_ID
typeErrorName :: Name
typeErrorName       = String -> Unique -> Var -> Name
err_nm String
"typeError"       Unique
typeErrorIdKey       Var
tYPE_ERROR_ID

noMethodBindingErrorName :: Name
noMethodBindingErrorName     = String -> Unique -> Var -> Name
err_nm String
"noMethodBindingError"
                                  Unique
noMethodBindingErrorIdKey Var
nO_METHOD_BINDING_ERROR_ID
nonExhaustiveGuardsErrorName :: Name
nonExhaustiveGuardsErrorName = String -> Unique -> Var -> Name
err_nm String
"nonExhaustiveGuardsError"
                                  Unique
nonExhaustiveGuardsErrorIdKey Var
nON_EXHAUSTIVE_GUARDS_ERROR_ID

err_nm :: String -> Unique -> Id -> Name
err_nm :: String -> Unique -> Var -> Name
err_nm String
str Unique
uniq Var
id = Module -> FastString -> Unique -> Var -> Name
mkWiredInIdName Module
cONTROL_EXCEPTION_BASE (String -> FastString
fsLit String
str) Unique
uniq Var
id

rEC_SEL_ERROR_ID, rUNTIME_ERROR_ID, rEC_CON_ERROR_ID :: Id
pAT_ERROR_ID, nO_METHOD_BINDING_ERROR_ID, nON_EXHAUSTIVE_GUARDS_ERROR_ID :: Id
tYPE_ERROR_ID, aBSENT_ERROR_ID, aBSENT_SUM_FIELD_ERROR_ID :: Id
rEC_SEL_ERROR_ID :: Var
rEC_SEL_ERROR_ID                = Name -> Var
mkRuntimeErrorId Name
recSelErrorName
rUNTIME_ERROR_ID :: Var
rUNTIME_ERROR_ID                = Name -> Var
mkRuntimeErrorId Name
runtimeErrorName
rEC_CON_ERROR_ID :: Var
rEC_CON_ERROR_ID                = Name -> Var
mkRuntimeErrorId Name
recConErrorName
pAT_ERROR_ID :: Var
pAT_ERROR_ID                    = Name -> Var
mkRuntimeErrorId Name
patErrorName
nO_METHOD_BINDING_ERROR_ID :: Var
nO_METHOD_BINDING_ERROR_ID      = Name -> Var
mkRuntimeErrorId Name
noMethodBindingErrorName
nON_EXHAUSTIVE_GUARDS_ERROR_ID :: Var
nON_EXHAUSTIVE_GUARDS_ERROR_ID  = Name -> Var
mkRuntimeErrorId Name
nonExhaustiveGuardsErrorName
tYPE_ERROR_ID :: Var
tYPE_ERROR_ID                   = Name -> Var
mkRuntimeErrorId Name
typeErrorName

-- Note [aBSENT_SUM_FIELD_ERROR_ID]
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-- Absent argument error for unused unboxed sum fields are different than absent
-- error used in dummy worker functions (see `mkAbsentErrorApp`):
--
-- - `absentSumFieldError` can't take arguments because it's used in unarise for
--   unused pointer fields in unboxed sums, and applying an argument would
--   require allocating a thunk.
--
-- - `absentSumFieldError` can't be CAFFY because that would mean making some
--   non-CAFFY definitions that use unboxed sums CAFFY in unarise.
--
--   To make `absentSumFieldError` non-CAFFY we get a stable pointer to it in
--   RtsStartup.c and mark it as non-CAFFY here.
--
-- Getting this wrong causes hard-to-debug runtime issues, see #15038.
--
-- TODO: Remove stable pointer hack after fixing #9718.
--       However, we should still be careful about not making things CAFFY just
--       because they use unboxed sums. Unboxed objects are supposed to be
--       efficient, and none of the other unboxed literals make things CAFFY.

aBSENT_SUM_FIELD_ERROR_ID :: Var
aBSENT_SUM_FIELD_ERROR_ID
  = Name -> Type -> IdInfo -> Var
mkVanillaGlobalWithInfo Name
absentSumFieldErrorName
      ([Var] -> Type -> Type
mkSpecForAllTys [Var
alphaTyVar] (Var -> Type
mkTyVarTy Var
alphaTyVar)) -- forall a . a
      (IdInfo
vanillaIdInfo IdInfo -> StrictSig -> IdInfo
`setStrictnessInfo` [Demand] -> DmdResult -> StrictSig
mkClosedStrictSig [] DmdResult
botRes
                     IdInfo -> Int -> IdInfo
`setArityInfo` Int
0
                     IdInfo -> CafInfo -> IdInfo
`setCafInfo` CafInfo
NoCafRefs) -- #15038

mkRuntimeErrorId :: Name -> Id
-- Error function
--   with type:  forall (r:RuntimeRep) (a:TYPE r). Addr# -> a
--   with arity: 1
-- which diverges after being given one argument
-- The Addr# is expected to be the address of
--   a UTF8-encoded error string
mkRuntimeErrorId :: Name -> Var
mkRuntimeErrorId Name
name
 = Name -> Type -> IdInfo -> Var
mkVanillaGlobalWithInfo Name
name Type
runtimeErrorTy IdInfo
bottoming_info
 where
    bottoming_info :: IdInfo
bottoming_info = IdInfo
vanillaIdInfo IdInfo -> StrictSig -> IdInfo
`setStrictnessInfo`    StrictSig
strict_sig
                                   IdInfo -> Int -> IdInfo
`setArityInfo`         Int
1
                        -- Make arity and strictness agree

        -- Do *not* mark them as NoCafRefs, because they can indeed have
        -- CAF refs.  For example, pAT_ERROR_ID calls GHC.Err.untangle,
        -- which has some CAFs
        -- In due course we may arrange that these error-y things are
        -- regarded by the GC as permanently live, in which case we
        -- can give them NoCaf info.  As it is, any function that calls
        -- any pc_bottoming_Id will itself have CafRefs, which bloats
        -- SRTs.

    strict_sig :: StrictSig
strict_sig = [Demand] -> DmdResult -> StrictSig
mkClosedStrictSig [Demand
evalDmd] DmdResult
botRes

runtimeErrorTy :: Type
-- forall (rr :: RuntimeRep) (a :: rr). Addr# -> a
--   See Note [Error and friends have an "open-tyvar" forall]
runtimeErrorTy :: Type
runtimeErrorTy = [Var] -> Type -> Type
mkSpecForAllTys [Var
runtimeRep1TyVar, Var
openAlphaTyVar]
                                 (Type -> Type -> Type
mkVisFunTy Type
addrPrimTy Type
openAlphaTy)

{- Note [Error and friends have an "open-tyvar" forall]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
'error' and 'undefined' have types
        error     :: forall (v :: RuntimeRep) (a :: TYPE v). String -> a
        undefined :: forall (v :: RuntimeRep) (a :: TYPE v). a
Notice the runtime-representation polymorphism. This ensures that
"error" can be instantiated at unboxed as well as boxed types.
This is OK because it never returns, so the return type is irrelevant.


************************************************************************
*                                                                      *
                     aBSENT_ERROR_ID
*                                                                      *
************************************************************************

Note [aBSENT_ERROR_ID]
~~~~~~~~~~~~~~~~~~~~~~
We use aBSENT_ERROR_ID to build dummy values in workers.  E.g.

   f x = (case x of (a,b) -> b) + 1::Int

The demand analyser figures ot that only the second component of x is
used, and does a w/w split thus

   f x = case x of (a,b) -> $wf b

   $wf b = let a = absentError "blah"
               x = (a,b)
           in <the original RHS of f>

After some simplification, the (absentError "blah") thunk goes away.

------ Tricky wrinkle -------
#14285 had, roughly

   data T a = MkT a !a
   {-# INLINABLE f #-}
   f x = case x of MkT a b -> g (MkT b a)

It turned out that g didn't use the second component, and hence f doesn't use
the first.  But the stable-unfolding for f looks like
   \x. case x of MkT a b -> g ($WMkT b a)
where $WMkT is the wrapper for MkT that evaluates its arguments.  We
apply the same w/w split to this unfolding (see Note [Worker-wrapper
for INLINEABLE functions] in WorkWrap) so the template ends up like
   \b. let a = absentError "blah"
           x = MkT a b
        in case x of MkT a b -> g ($WMkT b a)

After doing case-of-known-constructor, and expanding $WMkT we get
   \b -> g (case absentError "blah" of a -> MkT b a)

Yikes!  That bogusly appears to evaluate the absentError!

This is extremely tiresome.  Another way to think of this is that, in
Core, it is an invariant that a strict data contructor, like MkT, must
be applied only to an argument in HNF. So (absentError "blah") had
better be non-bottom.

So the "solution" is to add a special case for absentError to exprIsHNFlike.
This allows Simplify.rebuildCase, in the Note [Case to let transformation]
branch, to convert the case on absentError into a let. We also make
absentError *not* be diverging, unlike the other error-ids, so that we
can be sure not to remove the case branches before converting the case to
a let.

If, by some bug or bizarre happenstance, we ever call absentError, we should
throw an exception.  This should never happen, of course, but we definitely
can't return anything.  e.g. if somehow we had
    case absentError "foo" of
       Nothing -> ...
       Just x  -> ...
then if we return, the case expression will select a field and continue.
Seg fault city. Better to throw an exception. (Even though we've said
it is in HNF :-)

It might seem a bit surprising that seq on absentError is simply erased

    absentError "foo" `seq` x ==> x

but that should be okay; since there's no pattern match we can't really
be relying on anything from it.
-}

aBSENT_ERROR_ID :: Var
aBSENT_ERROR_ID
 = Name -> Type -> IdInfo -> Var
mkVanillaGlobalWithInfo Name
absentErrorName Type
absent_ty IdInfo
arity_info
 where
   absent_ty :: Type
absent_ty = [Var] -> Type -> Type
mkSpecForAllTys [Var
alphaTyVar] (Type -> Type -> Type
mkVisFunTy Type
addrPrimTy Type
alphaTy)
   -- Not runtime-rep polymorphic. aBSENT_ERROR_ID is only used for
   -- lifted-type things; see Note [Absent errors] in WwLib
   arity_info :: IdInfo
arity_info = IdInfo
vanillaIdInfo IdInfo -> Int -> IdInfo
`setArityInfo` Int
1
   -- NB: no bottoming strictness info, unlike other error-ids.
   -- See Note [aBSENT_ERROR_ID]

mkAbsentErrorApp :: Type         -- The type to instantiate 'a'
                 -> String       -- The string to print
                 -> CoreExpr

mkAbsentErrorApp :: Type -> String -> CoreExpr
mkAbsentErrorApp Type
res_ty String
err_msg
  = CoreExpr -> [CoreExpr] -> CoreExpr
forall b. Expr b -> [Expr b] -> Expr b
mkApps (Var -> CoreExpr
forall b. Var -> Expr b
Var Var
aBSENT_ERROR_ID) [ Type -> CoreExpr
forall b. Type -> Expr b
Type Type
res_ty, CoreExpr
forall b. Expr b
err_string ]
  where
    err_string :: Expr b
err_string = Literal -> Expr b
forall b. Literal -> Expr b
Lit (String -> Literal
mkLitString String
err_msg)