Commit 51fad9e6 authored by Richard Eisenberg's avatar Richard Eisenberg Committed by Marge Bot

Break up TcRnTypes, among other modules.

This introduces three new modules:

 - basicTypes/Predicate.hs describes predicates, moving
   this logic out of Type. Predicates don't really exist
   in Core, and so don't belong in Type.

 - typecheck/TcOrigin.hs describes the origin of constraints
   and types. It was easy to remove from other modules and
   can often be imported instead of other, scarier modules.

 - typecheck/Constraint.hs describes constraints as used in
   the solver. It is taken from TcRnTypes.

No work other than module splitting is in this patch.

This is the first step toward homogeneous equality, which will
rely more strongly on predicates. And homogeneous equality is the
next step toward a dependently typed core language.
parent 798037a1
Pipeline #11475 passed with stages
in 407 minutes and 35 seconds
......@@ -131,8 +131,8 @@ import DynFlags
-- Turgid imports for showTypeCategory
import PrelNames
import TcType
import Type
import TyCon
import Predicate
import Data.Maybe
import qualified Data.Char
......
......@@ -106,7 +106,9 @@ module BasicTypes(
IntWithInf, infinity, treatZeroAsInf, mkIntWithInf, intGtLimit,
SpliceExplicitFlag(..)
SpliceExplicitFlag(..),
TypeOrKind(..), isTypeLevel, isKindLevel
) where
import GhcPrelude
......@@ -1644,3 +1646,25 @@ data SpliceExplicitFlag
= ExplicitSplice | -- ^ <=> $(f x y)
ImplicitSplice -- ^ <=> f x y, i.e. a naked top level expression
deriving Data
{- *********************************************************************
* *
Types vs Kinds
* *
********************************************************************* -}
-- | Flag to see whether we're type-checking terms or kind-checking types
data TypeOrKind = TypeLevel | KindLevel
deriving Eq
instance Outputable TypeOrKind where
ppr TypeLevel = text "TypeLevel"
ppr KindLevel = text "KindLevel"
isTypeLevel :: TypeOrKind -> Bool
isTypeLevel TypeLevel = True
isTypeLevel KindLevel = False
isKindLevel :: TypeOrKind -> Bool
isKindLevel TypeLevel = False
isKindLevel KindLevel = True
......@@ -73,6 +73,7 @@ import FieldLabel
import Class
import Name
import PrelNames
import Predicate
import Var
import VarSet( emptyVarSet )
import Outputable
......
......@@ -73,9 +73,6 @@ module Id (
isConLikeId, isBottomingId, idIsFrom,
hasNoBinding,
-- ** Evidence variables
DictId, isDictId, isEvVar,
-- ** Join variables
JoinId, isJoinId, isJoinId_maybe, idJoinArity,
asJoinId, asJoinId_maybe, zapJoinId,
......@@ -129,7 +126,7 @@ import IdInfo
import BasicTypes
-- Imported and re-exported
import Var( Id, CoVar, DictId, JoinId,
import Var( Id, CoVar, JoinId,
InId, InVar,
OutId, OutVar,
idInfo, idDetails, setIdDetails, globaliseId, varType,
......@@ -584,20 +581,6 @@ isDeadBinder :: Id -> Bool
isDeadBinder bndr | isId bndr = isDeadOcc (idOccInfo bndr)
| otherwise = False -- TyVars count as not dead
{-
************************************************************************
* *
Evidence variables
* *
************************************************************************
-}
isEvVar :: Var -> Bool
isEvVar var = isEvVarType (varType var)
isDictId :: Id -> Bool
isDictId id = isDictTy (idType id)
{-
************************************************************************
* *
......
{-
Describes predicates as they are considered by the solver.
-}
module Predicate (
Pred(..), classifyPredType,
isPredTy, isEvVarType,
-- Equality predicates
EqRel(..), eqRelRole,
isEqPrimPred, isEqPred,
getEqPredTys, getEqPredTys_maybe, getEqPredRole,
predTypeEqRel,
mkPrimEqPred, mkReprPrimEqPred, mkPrimEqPredRole,
mkHeteroPrimEqPred, mkHeteroReprPrimEqPred,
-- Class predicates
mkClassPred, isDictTy,
isClassPred, isEqPredClass, isCTupleClass,
getClassPredTys, getClassPredTys_maybe,
-- Implicit parameters
isIPPred, isIPPred_maybe, isIPTyCon, isIPClass, hasIPPred,
-- Evidence variables
DictId, isEvVar, isDictId
) where
import GhcPrelude
import Type
import Class
import TyCon
import Var
import Coercion
import PrelNames
import FastString
import Outputable
import Util
import Control.Monad ( guard )
-- | A predicate in the solver. The solver tries to prove Wanted predicates
-- from Given ones.
data Pred
= ClassPred Class [Type]
| EqPred EqRel Type Type
| IrredPred PredType
| ForAllPred [TyCoVarBinder] [PredType] PredType
-- ForAllPred: see Note [Quantified constraints] in TcCanonical
-- NB: There is no TuplePred case
-- Tuple predicates like (Eq a, Ord b) are just treated
-- as ClassPred, as if we had a tuple class with two superclasses
-- class (c1, c2) => (%,%) c1 c2
classifyPredType :: PredType -> Pred
classifyPredType ev_ty = case splitTyConApp_maybe ev_ty of
Just (tc, [_, _, ty1, ty2])
| tc `hasKey` eqReprPrimTyConKey -> EqPred ReprEq ty1 ty2
| tc `hasKey` eqPrimTyConKey -> EqPred NomEq ty1 ty2
Just (tc, tys)
| Just clas <- tyConClass_maybe tc
-> ClassPred clas tys
_ | (tvs, rho) <- splitForAllVarBndrs ev_ty
, (theta, pred) <- splitFunTys rho
, not (null tvs && null theta)
-> ForAllPred tvs theta pred
| otherwise
-> IrredPred ev_ty
-- --------------------- Dictionary types ---------------------------------
mkClassPred :: Class -> [Type] -> PredType
mkClassPred clas tys = mkTyConApp (classTyCon clas) tys
isDictTy :: Type -> Bool
isDictTy = isClassPred
getClassPredTys :: HasDebugCallStack => PredType -> (Class, [Type])
getClassPredTys ty = case getClassPredTys_maybe ty of
Just (clas, tys) -> (clas, tys)
Nothing -> pprPanic "getClassPredTys" (ppr ty)
getClassPredTys_maybe :: PredType -> Maybe (Class, [Type])
getClassPredTys_maybe ty = case splitTyConApp_maybe ty of
Just (tc, tys) | Just clas <- tyConClass_maybe tc -> Just (clas, tys)
_ -> Nothing
-- --------------------- Equality predicates ---------------------------------
-- | A choice of equality relation. This is separate from the type 'Role'
-- because 'Phantom' does not define a (non-trivial) equality relation.
data EqRel = NomEq | ReprEq
deriving (Eq, Ord)
instance Outputable EqRel where
ppr NomEq = text "nominal equality"
ppr ReprEq = text "representational equality"
eqRelRole :: EqRel -> Role
eqRelRole NomEq = Nominal
eqRelRole ReprEq = Representational
getEqPredTys :: PredType -> (Type, Type)
getEqPredTys ty
= case splitTyConApp_maybe ty of
Just (tc, [_, _, ty1, ty2])
| tc `hasKey` eqPrimTyConKey
|| tc `hasKey` eqReprPrimTyConKey
-> (ty1, ty2)
_ -> pprPanic "getEqPredTys" (ppr ty)
getEqPredTys_maybe :: PredType -> Maybe (Role, Type, Type)
getEqPredTys_maybe ty
= case splitTyConApp_maybe ty of
Just (tc, [_, _, ty1, ty2])
| tc `hasKey` eqPrimTyConKey -> Just (Nominal, ty1, ty2)
| tc `hasKey` eqReprPrimTyConKey -> Just (Representational, ty1, ty2)
_ -> Nothing
getEqPredRole :: PredType -> Role
getEqPredRole ty = eqRelRole (predTypeEqRel ty)
-- | Get the equality relation relevant for a pred type.
predTypeEqRel :: PredType -> EqRel
predTypeEqRel ty
| Just (tc, _) <- splitTyConApp_maybe ty
, tc `hasKey` eqReprPrimTyConKey
= ReprEq
| otherwise
= NomEq
{-------------------------------------------
Predicates on PredType
--------------------------------------------}
{-
Note [Evidence for quantified constraints]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The superclass mechanism in TcCanonical.makeSuperClasses risks
taking a quantified constraint like
(forall a. C a => a ~ b)
and generate superclass evidence
(forall a. C a => a ~# b)
This is a funny thing: neither isPredTy nor isCoVarType are true
of it. So we are careful not to generate it in the first place:
see Note [Equality superclasses in quantified constraints]
in TcCanonical.
-}
isEvVarType :: Type -> Bool
-- True of (a) predicates, of kind Constraint, such as (Eq a), and (a ~ b)
-- (b) coercion types, such as (t1 ~# t2) or (t1 ~R# t2)
-- See Note [Types for coercions, predicates, and evidence] in TyCoRep
-- See Note [Evidence for quantified constraints]
isEvVarType ty = isCoVarType ty || isPredTy ty
isEqPredClass :: Class -> Bool
-- True of (~) and (~~)
isEqPredClass cls = cls `hasKey` eqTyConKey
|| cls `hasKey` heqTyConKey
isClassPred, isEqPred, isEqPrimPred, isIPPred :: PredType -> Bool
isClassPred ty = case tyConAppTyCon_maybe ty of
Just tyCon | isClassTyCon tyCon -> True
_ -> False
isEqPred ty -- True of (a ~ b) and (a ~~ b)
-- ToDo: should we check saturation?
| Just tc <- tyConAppTyCon_maybe ty
, Just cls <- tyConClass_maybe tc
= isEqPredClass cls
| otherwise
= False
isEqPrimPred ty = isCoVarType ty
-- True of (a ~# b) (a ~R# b)
isIPPred ty = case tyConAppTyCon_maybe ty of
Just tc -> isIPTyCon tc
_ -> False
isIPTyCon :: TyCon -> Bool
isIPTyCon tc = tc `hasKey` ipClassKey
-- Class and its corresponding TyCon have the same Unique
isIPClass :: Class -> Bool
isIPClass cls = cls `hasKey` ipClassKey
isCTupleClass :: Class -> Bool
isCTupleClass cls = isTupleTyCon (classTyCon cls)
isIPPred_maybe :: Type -> Maybe (FastString, Type)
isIPPred_maybe ty =
do (tc,[t1,t2]) <- splitTyConApp_maybe ty
guard (isIPTyCon tc)
x <- isStrLitTy t1
return (x,t2)
hasIPPred :: PredType -> Bool
hasIPPred pred
= case classifyPredType pred of
ClassPred cls tys
| isIPClass cls -> True
| isCTupleClass cls -> any hasIPPred tys
_other -> False
{-
************************************************************************
* *
Evidence variables
* *
************************************************************************
-}
isEvVar :: Var -> Bool
isEvVar var = isEvVarType (varType var)
isDictId :: Id -> Bool
isDictId id = isDictTy (varType id)
......@@ -30,6 +30,7 @@ import VarEnv
import Id
import Type
import TyCon ( initRecTc, checkRecTc )
import Predicate ( isDictTy )
import Coercion
import BasicTypes
import Unique
......@@ -517,7 +518,7 @@ mk_cheap_fn dflags cheap_app
= \e mb_ty -> exprIsCheapX cheap_app e
|| case mb_ty of
Nothing -> False
Just ty -> isDictLikeTy ty
Just ty -> isDictTy ty
----------------------
......@@ -624,9 +625,6 @@ The (foo DInt) is floated out, and makes ineffective a RULE
One could go further and make exprIsCheap reply True to any
dictionary-typed expression, but that's more work.
See Note [Dictionary-like types] in TcType.hs for why we use
isDictLikeTy here rather than isDictTy
Note [Eta expanding thunks]
~~~~~~~~~~~~~~~~~~~~~~~~~~~
We don't eta-expand
......
......@@ -77,6 +77,7 @@ import Id
import IdInfo
import PrelNames( absentErrorIdKey )
import Type
import Predicate
import TyCoRep( TyCoBinder(..), TyBinder )
import Coercion
import TyCon
......
......@@ -41,6 +41,7 @@ import CoreArity ( etaExpand )
import CoreUnfold
import CoreFVs
import Digraph
import Predicate
import PrelNames
import TyCon
......
......@@ -214,6 +214,7 @@ Library
Hooks
Id
IdInfo
Predicate
Lexeme
Literal
Llvm
......@@ -505,6 +506,8 @@ Library
TcRnExports
TcRnMonad
TcRnTypes
Constraint
TcOrigin
TcRules
TcSimplify
TcHoleErrors
......
......@@ -311,6 +311,7 @@ import GhcMonad
import TcRnMonad ( finalSafeMode, fixSafeInstances, initIfaceTcRn )
import LoadIface ( loadSysInterface )
import TcRnTypes
import Predicate
import Packages
import NameSet
import RdrName
......
......@@ -63,6 +63,9 @@ import TyCon
import Type hiding( typeKind )
import RepType
import TcType
import Constraint
import TcOrigin
import Predicate
import Var
import Id
import Name hiding ( varName )
......
......@@ -81,6 +81,7 @@ module TysPrim(
eqPrimTyCon, -- ty1 ~# ty2
eqReprPrimTyCon, -- ty1 ~R# ty2 (at role Representational)
eqPhantPrimTyCon, -- ty1 ~P# ty2 (at role Phantom)
equalityTyCon,
-- * SIMD
#include "primop-vector-tys-exports.hs-incl"
......@@ -919,6 +920,12 @@ eqPhantPrimTyCon = mkPrimTyCon eqPhantPrimTyConName binders res_kind roles
res_kind = unboxedTupleKind []
roles = [Nominal, Nominal, Phantom, Phantom]
-- | Given a Role, what TyCon is the type of equality predicates at that role?
equalityTyCon :: Role -> TyCon
equalityTyCon Nominal = eqPrimTyCon
equalityTyCon Representational = eqReprPrimTyCon
equalityTyCon Phantom = eqPhantPrimTyCon
{- *********************************************************************
* *
The primitive array types
......
......@@ -49,7 +49,7 @@ import NameSet
import RdrName ( RdrName, rdrNameOcc )
import SrcLoc
import ListSetOps ( findDupsEq )
import BasicTypes ( RecFlag(..) )
import BasicTypes ( RecFlag(..), TypeOrKind(..) )
import Digraph ( SCC(..) )
import Bag
import Util
......
......@@ -52,7 +52,7 @@ import NameEnv
import Avail
import Outputable
import Bag
import BasicTypes ( pprRuleName )
import BasicTypes ( pprRuleName, TypeOrKind(..) )
import FastString
import SrcLoc
import DynFlags
......
......@@ -57,8 +57,9 @@ import FieldLabel
import Util
import ListSetOps ( deleteBys )
import BasicTypes ( compareFixity, funTyFixity, negateFixity,
Fixity(..), FixityDirection(..), LexicalFixity(..) )
import BasicTypes ( compareFixity, funTyFixity, negateFixity
, Fixity(..), FixityDirection(..), LexicalFixity(..)
, TypeOrKind(..) )
import Outputable
import FastString
import Maybes
......
......@@ -16,6 +16,7 @@ import GhcPrelude
import Id
import TcType hiding( substTy )
import Type hiding( substTy, extendTvSubstList )
import Predicate
import Module( Module, HasModule(..) )
import Coercion( Coercion )
import CoreMonad
......
......@@ -30,6 +30,7 @@ import Literal ( absentLiteralOf, rubbishLit )
import VarEnv ( mkInScopeSet )
import VarSet ( VarSet )
import Type
import Predicate ( isClassPred )
import RepType ( isVoidTy, typePrimRep )
import Coercion
import FamInstEnv
......
......@@ -17,6 +17,7 @@ import TcType
import TcTypeable
import TcMType
import TcEvidence
import Predicate
import RnEnv( addUsedGRE )
import RdrName( lookupGRE_FieldLabel )
import InstEnv
......
This diff is collapsed.
......@@ -24,6 +24,7 @@ import GhcPrelude
import Name
import Var
import Class
import Predicate
import Type
import TcType( transSuperClasses )
import CoAxiom( TypeEqn )
......
......@@ -42,6 +42,9 @@ import FastString
import GHC.Hs
import TcHsSyn
import TcRnMonad
import Constraint
import Predicate
import TcOrigin
import TcEnv
import TcEvidence
import InstEnv
......@@ -66,6 +69,7 @@ import SrcLoc
import DynFlags
import Util
import Outputable
import BasicTypes ( TypeOrKind(..) )
import qualified GHC.LanguageExtensions as LangExt
import Control.Monad( unless )
......
......@@ -24,6 +24,7 @@ import TcPat
import TcUnify
import TcRnMonad
import TcEnv
import TcOrigin
import TcEvidence
import Id( mkLocalId )
import Inst
......
......@@ -19,7 +19,7 @@ module TcBackpack (
import GhcPrelude
import BasicTypes (defaultFixity)
import BasicTypes (defaultFixity, TypeOrKind(..))
import Packages
import TcRnExports
import DynFlags
......@@ -34,6 +34,8 @@ import TcIface
import TcMType
import TcType
import TcSimplify
import Constraint
import TcOrigin
import LoadIface
import RnNames
import ErrUtils
......
......@@ -27,6 +27,7 @@ import FastString
import GHC.Hs
import TcSigs
import TcRnMonad
import TcOrigin
import TcEnv
import TcUnify
import TcSimplify
......
......@@ -13,7 +13,9 @@ module TcCanonical(
import GhcPrelude
import TcRnTypes
import Constraint
import Predicate
import TcOrigin
import TcUnify( swapOverTyVars, metaTyVarUpdateOK )
import TcType
import Type
......@@ -284,7 +286,7 @@ So here's the plan:
Note [Eagerly expand given superclasses].
3. If we have any remaining unsolved wanteds
(see Note [When superclasses help] in TcRnTypes)
(see Note [When superclasses help] in Constraint)
try harder: take both the Givens and Wanteds, and expand
superclasses again. See the calls to expandSuperClasses in
TcSimplify.simpl_loop and solveWanteds.
......@@ -617,7 +619,7 @@ case. Instead we have a special case in TcInteract.doTopReactOther,
which looks for primitive equalities specially in the quantified
constraints.
See also Note [Evidence for quantified constraints] in Type.
See also Note [Evidence for quantified constraints] in Predicate.
************************************************************************
......@@ -702,7 +704,7 @@ Here are the moving parts
* checkValidType gets some changes to accept forall-constraints
only in the right places.
* Type.PredTree gets a new constructor ForAllPred, and
* Predicate.Pred gets a new constructor ForAllPred, and
and classifyPredType analyses a PredType to decompose
the new forall-constraints
......@@ -2114,7 +2116,7 @@ Int ~ Int. The user thus sees that GHC can't solve Int ~ Int, which
is embarrassing. See #11198 for more tales of destruction.
The reason for this odd behavior is much the same as
Note [Wanteds do not rewrite Wanteds] in TcRnTypes: note that the
Note [Wanteds do not rewrite Wanteds] in Constraint: note that the
new `co` is a Wanted.
The solution is then not to use `co` to "rewrite" -- that is, cast -- `w`, but
......
......@@ -30,7 +30,9 @@ import TcBinds
import TcUnify
import TcHsType
import TcMType
import Type ( getClassPredTys_maybe, piResultTys )
import Type ( piResultTys )
import Predicate
import TcOrigin
import TcType
import TcRnMonad
import DriverPhases (HscSource(..))
......
......@@ -20,6 +20,8 @@ import DynFlags
import TcRnMonad
import FamInst
import TcOrigin
import Predicate
import TcDerivInfer
import TcDerivUtils
import TcValidity( allDistinctTyVars )
......@@ -617,7 +619,7 @@ deriveStandalone (L loc (DerivDecl _ deriv_ty mb_lderiv_strat overlap_mode))
= setSrcSpan loc $
addErrCtxt (standaloneCtxt deriv_ty) $
do { traceTc "Standalone deriving decl for" (ppr deriv_ty)
; let ctxt = TcType.InstDeclCtxt True
; let ctxt = TcOrigin.InstDeclCtxt True
; traceTc "Deriving strategy (standalone deriving)" $
vcat [ppr mb_lderiv_strat, ppr deriv_ty]
; (mb_lderiv_strat, via_tvs) <- tcDerivStrategy mb_lderiv_strat
......
......@@ -31,6 +31,9 @@ import TcGenFunctor
import TcGenGenerics
import TcMType
import TcRnMonad
import TcOrigin
import Constraint
import Predicate
import TcType
import TyCon
import Type
......
......@@ -44,6 +44,7 @@ import SrcLoc
import TcGenDeriv
import TcGenFunctor
import TcGenGenerics
import TcOrigin
import TcRnMonad
import TcType
import THNames (liftClassKey)
......
......@@ -15,10 +15,13 @@ import GhcPrelude
import TcRnTypes
import TcRnMonad
import Constraint
import Predicate
import TcMType
import TcUnify( occCheckForErrors, MetaTyVarUpdateResult(..) )
import TcEnv( tcInitTidyEnv )
import TcType
import TcOrigin
import RnUnbound ( unknownNameSuggestions )
import Type
import TyCoRep
......@@ -415,7 +418,7 @@ reportImplic ctxt implic@(Implic { ic_skols = tvs, ic_telescope = m_telescope
warnRedundantConstraints ctxt' tcl_env info' dead_givens
; when bad_telescope $ reportBadTelescope ctxt tcl_env m_telescope tvs }
where
tcl_env = implicLclEnv implic
tcl_env = ic_env implic
insoluble = isInsolubleStatus status
(env1, tvs') = mapAccumL tidyVarBndr (cec_tidy ctxt) tvs
info' = tidySkolemInfo env1 info
......@@ -580,7 +583,7 @@ reportWanteds ctxt tc_lvl (WC { wc_simple = simples, wc_impl = implics })
-- rigid_nom_eq, rigid_nom_tv_eq,
is_hole, is_dict,
is_equality, is_ip, is_irred :: Ct -> PredTree -> Bool
is_equality, is_ip, is_irred :: Ct -> Pred -> Bool
is_given_eq ct pred
| EqPred {} <- pred = arisesFromGivens ct
......@@ -639,7 +642,7 @@ reportWanteds ctxt tc_lvl (WC { wc_simple = simples, wc_impl = implics })
has_gadt_match (implic : implics)
| PatSkol {} <- ic_info implic
, not (ic_no_eqs implic)
, wopt Opt_WarnInaccessibleCode (implicDynFlags implic)
, ic_warn_inaccessible implic
-- Don't bother doing this if -Winaccessible-code isn't enabled.
-- See Note [Avoid -Winaccessible-code when deriving] in TcInstDcls.
= True
......@@ -672,7 +675,7 @@ type Reporter
= ReportErrCtxt -> [Ct] -> TcM ()
type ReporterSpec
= ( String -- Name
, Ct -> PredTree -> Bool -- Pick these ones
, Ct -> Pred -> Bool -- Pick these ones
, Bool -- True <=> suppress subsequent reporters
, Reporter) -- The reporter itself
......@@ -720,7 +723,7 @@ mkGivenErrorReporter ctxt cts
; dflags <- getDynFlags
; let (implic:_) = cec_encl ctxt
-- Always non-empty when mkGivenErrorReporter is called
ct' = setCtLoc ct (setCtLocEnv (ctLoc ct) (implicLclEnv implic))
ct' = setCtLoc ct (setCtLocEnv (ctLoc ct) (ic_env implic))
-- For given constraints we overwrite the env (and hence src-loc)
-- with one from the immediately-enclosing implication.
-- See Note [Inaccessible code]
......@@ -1218,7 +1221,7 @@ givenConstraintsMsg ctxt =
constraints =
do { implic@Implic{ ic_given = given } <- cec_encl ctxt
; constraint <- given
; return (varType constraint, tcl_loc (implicLclEnv implic)) }
; return (varType constraint, tcl_loc (ic_env implic)) }
pprConstraint (constraint, loc) =
ppr constraint <+> nest 2 (parens (text "from" <+> ppr loc))
......@@ -1571,7 +1574,7 @@ mkTyVarEqErr' dflags ctxt report ct oriented tv1 co1 ty2
<+> text "bound by"
, nest 2 $ ppr skol_info