diff options
| author | Simon Peyton Jones <simon.peytonjones@gmail.com> | 2022-01-02 23:50:03 +0000 |
|---|---|---|
| committer | Simon Peyton Jones <simon.peytonjones@gmail.com> | 2022-01-03 23:44:14 +0000 |
| commit | 232e11b96fea59409ff112899d1f9fa0871ff195 (patch) | |
| tree | 13be4ad673b2471372a6fff0c1e91e9e0046aa0a | |
| parent | 32c27e57e850c9a32a7192593a6d60e18135ed68 (diff) | |
| download | haskell-232e11b96fea59409ff112899d1f9fa0871ff195.tar.gz | |
Completely refactor kcCheckDeclHeader_sig
This substantial commit refactors kcCheckDeclHeader_sig, which kept
doing my head in. Plus, it wasn't right because it wasn't skolemising
the binders as it decomposed the kind signature.
The new story is described in Note [kcCheckDeclHeader_sig]. The code
is considerably shorter than before (roughly 240 lines turns into 150
lines).
It still has the same awkward complexity around computing arity as
before, but that is a language design issue.
See Note [Arity inference in kcCheckDeclHeader_sig]
Other points
* I added new type synonyms MonoTcTyCon and PolyTcTyCon, and used
them to be clear which TcTyCons have "finished" kinds etc, and
which are monomorphic.
* I renamed etaExpandAlgTyCon to splitTyConKind, becuase that's a
better name, and it is very useful in kcCheckDeclHeader_sig, where
eta-expansion isn't an issue.
24 files changed, 484 insertions, 502 deletions
diff --git a/compiler/GHC/Core/TyCon.hs b/compiler/GHC/Core/TyCon.hs index 18a01226d7..ac6eca7ff1 100644 --- a/compiler/GHC/Core/TyCon.hs +++ b/compiler/GHC/Core/TyCon.hs @@ -25,7 +25,7 @@ module GHC.Core.TyCon( mkRequiredTyConBinder, mkAnonTyConBinder, mkAnonTyConBinders, tyConBinderArgFlag, tyConBndrVisArgFlag, isNamedTyConBinder, - isVisibleTyConBinder, isInvisibleTyConBinder, + isVisibleTyConBinder, isInvisibleTyConBinder, isVisibleTcbVis, -- ** Field labels tyConFieldLabels, lookupTyConFieldLabel, @@ -668,7 +668,7 @@ They fit together like so: * For an algebraic data type, or data instance, the tyConResKind is always (TYPE r); that is, the tyConBinders are enough to saturate the type constructor. I'm not quite sure why we have this invariant, - but it's enforced by etaExpandAlgTyCon + but it's enforced by splitTyConKind -} instance OutputableBndr tv => Outputable (VarBndr tv TyConBndrVis) where @@ -947,8 +947,9 @@ data TyCon -- arguments to the type constructor; see the use -- of tyConArity in generaliseTcTyCon - tcTyConScopedTyVars :: [(Name,TyVar)], + tcTyConScopedTyVars :: [(Name,TcTyVar)], -- ^ Scoped tyvars over the tycon's body + -- The range is always a skolem or TcTyVar, be -- See Note [Scoped tyvars in a TcTyCon] tcTyConIsPoly :: Bool, -- ^ Is this TcTyCon already generalized? diff --git a/compiler/GHC/Tc/Deriv.hs b/compiler/GHC/Tc/Deriv.hs index b03aaea65b..6729458f1d 100644 --- a/compiler/GHC/Tc/Deriv.hs +++ b/compiler/GHC/Tc/Deriv.hs @@ -474,15 +474,8 @@ deriveClause rep_tc scoped_tvs mb_lderiv_strat deriv_preds err_ctxt , text "tys" <+> ppr tys , text "mb_lderiv_strat" <+> ppr mb_lderiv_strat ] tcExtendNameTyVarEnv scoped_tvs $ do - (mb_lderiv_strat', mvia_tvs) <- tcDerivStrategy mb_lderiv_strat - - (extend_by, via_tvs) <- case mvia_tvs of - Just (tvs, ty) -> do - skol_info <- mkSkolemInfo (DerivSkol ty) - return $ (tcExtendTyVarEnv skol_info tvs, tvs) - Nothing -> return (\f -> f emptyTCvSubst [], []) - - extend_by $ \_subst _vars -> + (mb_lderiv_strat', via_tvs) <- tcDerivStrategy mb_lderiv_strat + tcExtendTyVarEnv via_tvs $ -- Moreover, when using DerivingVia one can bind type variables in -- the `via` type as well, so these type variables must also be -- brought into scope. @@ -640,14 +633,9 @@ deriveStandalone (L loc (DerivDecl _ deriv_ty mb_lderiv_strat overlap_mode)) ; let ctxt = GHC.Tc.Types.Origin.InstDeclCtxt True ; traceTc "Deriving strategy (standalone deriving)" $ vcat [ppr mb_lderiv_strat, ppr deriv_ty] - ; (mb_lderiv_strat, mvia_tvs) <- tcDerivStrategy mb_lderiv_strat - ; (extend_by, via_tvs) <- case mvia_tvs of - Just (tvs, ty) -> do - skol_info <- mkSkolemInfo (DerivSkol ty) - return $ (tcExtendTyVarEnv skol_info tvs, tvs) - Nothing -> return (\f -> f emptyTCvSubst [], []) + ; (mb_lderiv_strat, via_tvs) <- tcDerivStrategy mb_lderiv_strat ; (cls_tvs, deriv_ctxt, cls, inst_tys) - <- extend_by $ \_subst _vars -> + <- tcExtendTyVarEnv via_tvs $ tcStandaloneDerivInstType ctxt deriv_ty ; let mb_deriv_strat = fmap unLoc mb_lderiv_strat tvs = via_tvs ++ cls_tvs diff --git a/compiler/GHC/Tc/Gen/HsType.hs b/compiler/GHC/Tc/Gen/HsType.hs index 11d9ffede3..faa19ec924 100644 --- a/compiler/GHC/Tc/Gen/HsType.hs +++ b/compiler/GHC/Tc/Gen/HsType.hs @@ -114,7 +114,6 @@ import GHC.Types.Basic import GHC.Types.SrcLoc import GHC.Types.Unique import GHC.Types.Unique.FM -import GHC.Types.Unique.Set import GHC.Utils.Misc import GHC.Types.Unique.Supply import GHC.Utils.Outputable @@ -129,7 +128,6 @@ import GHC.Data.Maybe import GHC.Data.Bag( unitBag ) import Data.List ( find ) import Control.Monad -import Data.Bifunctor {- ---------------------------- @@ -474,7 +472,7 @@ tc_lhs_sig_type skol_info full_hs_ty@(L loc (HsSig { sig_bndrs = hs_outer_bndrs -- Build an implication for any as-yet-unsolved kind equalities -- See Note [Skolem escape in type signatures] - ; implic <- buildTvImplication skol_info kvs tc_lvl wanted + ; implic <- buildTvImplication (getSkolemInfo skol_info) kvs tc_lvl wanted ; return (implic, mkInfForAllTys kvs ty1) } where @@ -637,7 +635,7 @@ tcHsDeriv hs_ty tcDerivStrategy :: Maybe (LDerivStrategy GhcRn) -- ^ The deriving strategy - -> TcM (Maybe (LDerivStrategy GhcTc), Maybe ([TyVar], Type)) + -> TcM (Maybe (LDerivStrategy GhcTc), [TyVar]) -- ^ The typechecked deriving strategy and the tyvars that it binds -- (if using 'ViaStrategy'). tcDerivStrategy mb_lds @@ -649,7 +647,7 @@ tcDerivStrategy mb_lds pure (Just (L loc ds'), tvs) where tc_deriv_strategy :: DerivStrategy GhcRn - -> TcM (DerivStrategy GhcTc, Maybe ([TyVar], Type)) + -> TcM (DerivStrategy GhcTc, [TyVar]) tc_deriv_strategy (StockStrategy _) = boring_case (StockStrategy noExtField) tc_deriv_strategy (AnyclassStrategy _) @@ -659,10 +657,10 @@ tcDerivStrategy mb_lds tc_deriv_strategy (ViaStrategy ty) = do ty' <- checkNoErrs $ tcTopLHsType DerivClauseCtxt ty let (via_tvs, via_pred) = splitForAllTyCoVars ty' - pure (ViaStrategy via_pred, Just (via_tvs, via_pred)) + pure (ViaStrategy via_pred, via_tvs) - boring_case :: ds -> TcM (ds, Maybe a) - boring_case ds = pure (ds, Nothing) + boring_case :: ds -> TcM (ds, [a]) + boring_case ds = pure (ds, []) tcHsClsInstType :: UserTypeCtxt -- InstDeclCtxt or SpecInstCtxt -> LHsSigType GhcRn @@ -2363,7 +2361,7 @@ kcCheckDeclHeader -> TyConFlavour -- ^ What sort of 'TyCon' is being checked -> LHsQTyVars GhcRn -- ^ Binders in the header -> TcM ContextKind -- ^ The result kind. AnyKind == no result signature - -> TcM TcTyCon -- ^ A suitably-kinded generalized TcTyCon + -> TcM PolyTcTyCon -- ^ A suitably-kinded generalized TcTyCon kcCheckDeclHeader (SAKS sig) = kcCheckDeclHeader_sig sig kcCheckDeclHeader CUSK = kcCheckDeclHeader_cusk @@ -2372,7 +2370,7 @@ kcCheckDeclHeader_cusk -> TyConFlavour -- ^ What sort of 'TyCon' is being checked -> LHsQTyVars GhcRn -- ^ Binders in the header -> TcM ContextKind -- ^ The result kind - -> TcM TcTyCon -- ^ A suitably-kinded generalized TcTyCon + -> TcM PolyTcTyCon -- ^ A suitably-kinded generalized TcTyCon kcCheckDeclHeader_cusk name flav (HsQTvs { hsq_ext = kv_ns , hsq_explicit = hs_tvs }) kc_res_ki @@ -2391,20 +2389,20 @@ kcCheckDeclHeader_cusk name flav ; let spec_req_tkvs = scoped_kvs ++ tc_tvs all_kinds = res_kind : map tyVarKind spec_req_tkvs - ; candidates' <- candidateQTyVarsOfKinds all_kinds + ; candidates <- candidateQTyVarsOfKinds all_kinds -- 'candidates' are all the variables that we are going to -- skolemise and then quantify over. We do not include spec_req_tvs -- because they are /already/ skolems - ; let non_tc_candidates = filter (not . isTcTyVar) (nonDetEltsUniqSet (tyCoVarsOfTypes all_kinds)) - candidates = candidates' { dv_kvs = dv_kvs candidates' `extendDVarSetList` non_tc_candidates } + ; let -- non_tc_candidates = filter (not . isTcTyVar) (nonDetEltsUniqSet (tyCoVarsOfTypes all_kinds)) + -- candidates = candidates' { dv_kvs = dv_kvs candidates' `extendDVarSetList` non_tc_candidates } inf_candidates = candidates `delCandidates` spec_req_tkvs ; inferred <- quantifyTyVars skol_info DefaultNonStandardTyVars inf_candidates -- NB: 'inferred' comes back sorted in dependency order - ; scoped_kvs <- mapM zonkTyCoVarKind scoped_kvs - ; tc_tvs <- mapM zonkTyCoVarKind tc_tvs + ; scoped_kvs <- mapM zonkTyCoVarKind scoped_kvs -- scoped_kvs and tc_tvs are skolems, + ; tc_tvs <- mapM zonkTyCoVarKind tc_tvs -- so zonkTyCoVarKind suffices ; res_kind <- zonkTcType res_kind ; let mentioned_kv_set = candidateKindVars candidates @@ -2430,12 +2428,15 @@ kcCheckDeclHeader_cusk name flav ; traceTc "kcCheckDeclHeader_cusk " $ vcat [ text "name" <+> ppr name + , text "candidates" <+> ppr candidates + , text "mentioned_kv_set" <+> ppr mentioned_kv_set , text "kv_ns" <+> ppr kv_ns , text "hs_tvs" <+> ppr hs_tvs , text "scoped_kvs" <+> ppr scoped_kvs + , text "spec_req_tvs" <+> ppr spec_req_tkvs + , text "all_kinds" <+> ppr all_kinds , text "tc_tvs" <+> ppr tc_tvs , text "res_kind" <+> ppr res_kind - , text "candidates" <+> ppr candidates , text "inferred" <+> ppr inferred , text "specified" <+> ppr specified , text "final_tc_binders" <+> ppr final_tc_binders @@ -2458,7 +2459,7 @@ kcInferDeclHeader -> TyConFlavour -- ^ What sort of 'TyCon' is being checked -> LHsQTyVars GhcRn -> TcM ContextKind -- ^ The result kind - -> TcM TcTyCon -- ^ A suitably-kinded non-generalized TcTyCon + -> TcM MonoTcTyCon -- ^ A suitably-kinded non-generalized TcTyCon kcInferDeclHeader name flav (HsQTvs { hsq_ext = kv_ns , hsq_explicit = hs_tvs }) kc_res_ki @@ -2505,254 +2506,169 @@ kcInferDeclHeader name flav | otherwise = AnyKind -- | Kind-check a declaration header against a standalone kind signature. --- See Note [Arity inference in kcCheckDeclHeader_sig] +-- See Note [kcCheckDeclHeader_sig] kcCheckDeclHeader_sig :: Kind -- ^ Standalone kind signature, fully zonked! (zonkTcTypeToType) -> Name -- ^ of the thing being checked -> TyConFlavour -- ^ What sort of 'TyCon' is being checked -> LHsQTyVars GhcRn -- ^ Binders in the header -> TcM ContextKind -- ^ The result kind. AnyKind == no result signature - -> TcM TcTyCon -- ^ A suitably-kinded TcTyCon -kcCheckDeclHeader_sig kisig name flav + -> TcM PolyTcTyCon -- ^ A suitably-kinded, fully generalised TcTyCon +-- Postcondition to (kcCheckDeclHeader_sig sig_kind n f hs_tvs kc_res_ki): +-- kind(returned PolyTcTyCon) = sig_kind +-- +kcCheckDeclHeader_sig sig_kind name flav (HsQTvs { hsq_ext = implicit_nms , hsq_explicit = explicit_nms }) kc_res_ki = addTyConFlavCtxt name flav $ - do { -- Step 1: zip user-written binders with quantifiers from the kind signature. - -- For example: - -- - -- type F :: forall k -> k -> forall j. j -> Type - -- data F i a b = ... - -- - -- Results in the following 'zipped_binders': - -- - -- TyBinder LHsTyVarBndr - -- --------------------------------------- - -- ZippedBinder forall k -> i - -- ZippedBinder k -> a - -- ZippedBinder forall j. - -- ZippedBinder j -> b - -- - let (zipped_binders, excess_bndrs, kisig') = zipBinders kisig explicit_nms - - -- Report binders that don't have a corresponding quantifier. - -- For example: - -- - -- type T :: Type -> Type - -- data T b1 b2 b3 = ... - -- - -- Here, b1 is zipped with Type->, while b2 and b3 are excess binders. - -- - ; unless (null excess_bndrs) $ failWithTc (tooManyBindersErr kisig' excess_bndrs) - - -- Convert each ZippedBinder to TyConBinder for tyConBinders - -- and to [(Name, TcTyVar)] for tcTyConScopedTyVars - ; skol_info <- mkSkolemInfo (TyConSkol flav name) - ; (vis_tcbs, concat -> explicit_tv_prs) <- mapAndUnzipM (zipped_to_tcb skol_info) zipped_binders - ; skol_info <- mkSkolemInfo (TyConSkol flav name) - - ; (tclvl, wanted, (implicit_tvs, (invis_binders, skol_tvs, r_ki))) - <- pushLevelAndSolveEqualitiesX "kcCheckDeclHeader_sig" $ -- #16687 - bindImplicitTKBndrs_Tv implicit_nms $ - tcExtendNameTyVarEnv explicit_tv_prs $ - do { -- Check that inline kind annotations on binders are valid. - -- For example: - -- - -- type T :: Maybe k -> Type - -- data T (a :: Maybe j) = ... - -- - -- Here we unify Maybe k ~ Maybe j - mapM_ check_zipped_binder zipped_binders - - -- Kind-check the result kind annotation, if present: - -- - -- data T a b :: res_ki where - -- ^^^^^^^^^ - -- We do it here because at this point the environment has been - -- extended with both 'implicit_tcv_prs' and 'explicit_tv_prs'. - ; ctx_k <- kc_res_ki - ; m_res_ki <- case ctx_k of - AnyKind -> return Nothing - _ -> Just <$> newExpectedKind ctx_k - - -- Step 2: split off invisible binders. - -- For example: - -- - -- type F :: forall k1 k2. (k1, k2) -> Type - -- type family F - -- - -- Does 'forall k1 k2' become a part of 'tyConBinders' or 'tyConResKind'? - -- See Note [Arity inference in kcCheckDeclHeader_sig] - ; let (invis_binders, r_ki) = split_invis kisig' m_res_ki - - -- Check that the inline result kind annotation is valid. - -- For example: - -- - -- type T :: Type -> Maybe k - -- type family T a :: Maybe j where - -- - -- Here we unify Maybe k ~ Maybe j - - ; - tcExtendTyVarEnv skol_info (mapMaybe tyCoBinderVar_maybe invis_binders) $ \subst skol_tvs -> do - -- See Note [discardResult in kcCheckDeclHeader_sig] - whenIsJust m_res_ki $ \res_ki -> do - discardResult $ - unifyKind Nothing (substTy subst r_ki) res_ki - - return (invis_binders, skol_tvs, r_ki) } - - -- Convert each invisible TyCoBinder to TyConBinder for tyConBinders. - ; invis_tcbs <- mapM invis_to_tcb invis_binders - - -- Zonk the implicitly quantified variables. - ; implicit_tvs <- mapM zonkTcTyVarToTyVar implicit_tvs - - -- Build the final, generalized TcTyCon - ; let tcbs = vis_tcbs ++ invis_tcbs - implicit_tv_prs = implicit_nms `zip` implicit_tvs + do { skol_info <- mkSkolemInfo (TyConSkol flav name) + ; (sig_tcbs :: [TyConBinder], sig_res_kind :: Kind) + <- splitTyConKind emptyInScopeSet (map getOccName explicit_nms) sig_kind + + ; traceTc "kcCheckDeclHeader_sig {" $ + vcat [ text "sig_kind:" <+> ppr sig_kind + , text "sig_tcbs:" <+> ppr sig_tcbs + , text "sig_res_kind:" <+> ppr sig_res_kind ] + + ; (tclvl, wanted, (implicit_tvs, (skol_tcbs, (extra_tcbs, tycon_res_kind)))) + <- pushLevelAndSolveEqualitiesX "kcCheckDeclHeader_sig" $ -- #16687 + bindImplicitTKBndrs_Tv implicit_nms $ + matchUpSigWithDecl skol_info sig_res_kind + sig_tcbs explicit_nms $ \ subst excess_sig_tcbs -> + do { -- Kind-check the result kind annotation, if present: + -- data T a b :: res_ki where ... + -- ^^^^^^^^^ + -- We do it here because at this point the environment has been + -- extended with both 'implicit_tcv_prs' and 'explicit_tv_prs'. + ; ctx_k <- kc_res_ki + + -- Work out extra_arity, the number of extra invisible binders from + -- the kind signature that should be part of the TyCon's arity. + -- See Note [Arity inference in kcCheckDeclHeader_sig] + ; let n_invis_tcbs = countWhile isInvisibleTyConBinder excess_sig_tcbs + extra_arity = case ctx_k of + AnyKind -> n_invis_tcbs -- No kind signature, so make all the invisible binders + -- the signature into part of the arity of the TyCon + OpenKind -> n_invis_tcbs -- Result kind is (TYPE rr), so again make all the + -- invisible binders part of the arity of the TyCon + TheKind ki -> 0 `max` (n_invis_tcbs - invisibleTyBndrCount ki) + + ; let (extra_tcbs, residual_tcbs) = splitAt extra_arity excess_sig_tcbs + ; (subst', extra_skol_tcbs) <- mapAccumLM (makeInvisibleSkolemTcb skol_info) + subst extra_tcbs + ; let sig_res_kind' = substTy subst' (mkTyConKind residual_tcbs sig_res_kind) + + ; traceTc "kcCheckDeclHeader_sig 2" $ vcat [ ppr excess_sig_tcbs, ppr extra_arity, ppr extra_tcbs + , ppr n_invis_tcbs ] + + -- Unify res_ki (from the type declaration) with the residual kind from + -- the kind signature. Don't forget to apply the skolemising 'subst' first. + ; case ctx_k of + AnyKind -> return () -- No signature + _ -> do { res_ki <- newExpectedKind ctx_k + ; discardResult (unifyKind Nothing sig_res_kind' res_ki) } + + ; return (extra_skol_tcbs, sig_res_kind') } + + ; implicit_tvs <- mapM zonkTcTyVarToTcTyVar implicit_tvs + -- This zonk is essential to maintain the invariants for PolyTcTyCon + -- See Note [TcTyCon, MonoTcTyCon, and PolyTcTyCon] in GHC.Tc.Utils.TcType + ; let implicit_tv_prs = implicit_nms `zip` implicit_tvs + explicit_tv_prs = mkTyVarNamePairs (binderVars skol_tcbs) all_tv_prs = implicit_tv_prs ++ explicit_tv_prs - tc = mkTcTyCon name tcbs r_ki all_tv_prs True flav + all_tcbs = skol_tcbs ++ extra_tcbs -- Check that there are no unsolved equalities - ; reportUnsolvedEqualities skol_info skol_tvs tclvl wanted + ; reportUnsolvedEqualities skol_info (binderVars all_tcbs) tclvl wanted + + -- Zonk everything back to TyVars + ; ze <- mkEmptyZonkEnv NoFlexi + ; (ze, all_tcbs) <- zonkTyVarBindersX ze all_tcbs + ; tycon_res_kind <- zonkTcTypeToTypeX ze tycon_res_kind + + -- Build the final, generalized PolyTcTyCon + -- NB: all_tcbs must bind the tyvars in the range of all_tv_prs + -- because the tv_prs is used when (say) typechecking the RHS of + -- a type synonym. + ; let tc = mkTcTyCon name all_tcbs tycon_res_kind all_tv_prs True flav - ; traceTc "kcCheckDeclHeader_sig done:" $ vcat + ; traceTc "kcCheckDeclHeader_sig }" $ vcat [ text "tyConName = " <+> ppr (tyConName tc) - , text "kisig =" <+> debugPprType kisig + , text "sig_kind =" <+> debugPprType sig_kind , text "tyConKind =" <+> debugPprType (tyConKind tc) , text "tyConBinders = " <+> ppr (tyConBinders tc) , text "tcTyConScopedTyVars" <+> ppr (tcTyConScopedTyVars tc) , text "tyConResKind" <+> debugPprType (tyConResKind tc) ] ; return tc } + +matchUpSigWithDecl + :: SkolemInfo + -> Kind -- The tail end of the kind signature; just for error messages + -> [TyConBinder] -- TyConBinders from the separate kind signature + -> [LHsTyVarBndr () GhcRn] -- User-written binders in decl + -> (TCvSubst -> [TyConBinder] -> TcM a) -- All user-written binders are in scope + -- Argument is excess TyConBinders + -> TcM ( [TyConBinder] -- Skolemised binders, with TcTyVars + , a ) +-- See Note [Matching a kind sigature with a declaration] +-- Invariant: Length of returned TyConBinders + length of excess TyConBinders +-- = length of incoming TyConBinders +matchUpSigWithDecl skol_info kisig tc_tcbs hs_bndrs thing_inside + = go emptyTCvSubst tc_tcbs hs_bndrs where - -- Consider this declaration: - -- - -- type T :: forall a. forall b -> (a~b) => Proxy a -> Type - -- data T x p = MkT - -- - -- Here, we have every possible variant of ZippedBinder: - -- - -- TyBinder LHsTyVarBndr - -- ---------------------------------------------- - -- ZippedBinder forall {k}. - -- ZippedBinder forall (a::k). - -- ZippedBinder forall (b::k) -> x - -- ZippedBinder (a~b) => - -- ZippedBinder Proxy a -> p - -- - -- Given a ZippedBinder zipped_to_tcb produces: - -- - -- * TyConBinder for tyConBinders - -- * (Name, TcTyVar) for tcTyConScopedTyVars, if there's a user-written LHsTyVarBndr - -- - zipped_to_tcb :: SkolemInfo -> ZippedBinder -> TcM (TyConBinder, [(Name, TcTyVar)]) - zipped_to_tcb skol_info zb = case zb of - - -- Inferred variable, no user-written binder. - -- Example: forall {k}. - ZippedBinder (Named (Bndr v Specified)) Nothing -> - return (mkNamedTyConBinder Specified v, []) - - -- Specified variable, no user-written binder. - -- Example: forall (a::k). - ZippedBinder (Named (Bndr v Inferred)) Nothing -> - return (mkNamedTyConBinder Inferred v, []) - - -- Constraint, no user-written binder. - -- Example: (a~b) => - ZippedBinder (Anon InvisArg bndr_ki) Nothing -> do - name <- newSysName (mkTyVarOccFS (fsLit "ev")) - let tv = mkTyVar name (scaledThing bndr_ki) - return (mkAnonTyConBinder InvisArg tv, []) - - -- Non-dependent visible argument with a user-written binder. - -- Example: Proxy a -> - ZippedBinder (Anon VisArg bndr_ki) (Just b) -> - return $ - let v_name = getName b - skol_details = vanillaSkolemTv skol_info - tv = mkTcTyVar v_name (scaledThing bndr_ki) skol_details - tcb = mkAnonTyConBinder VisArg tv - in (tcb, [(v_name, tv)]) - - -- Dependent visible argument with a user-written binder. - -- Example: forall (b::k) -> - ZippedBinder (Named (Bndr v Required)) (Just b) -> - return $ - let v_name = getName b - tcb = mkNamedTyConBinder Required v - in (tcb, [(v_name, v)]) - - -- 'zipBinders' does not produce any other variants of ZippedBinder. - _ -> panic "goVis: invalid ZippedBinder" - - -- Given an invisible binder that comes from 'split_invis', - -- convert it to TyConBinder. - invis_to_tcb :: TyCoBinder -> TcM TyConBinder - invis_to_tcb tb = do - -- unkSkol is not used. - (tcb, stv) <- zipped_to_tcb unkSkol (ZippedBinder tb Nothing) - massert (null stv) - return tcb - - -- Check that the inline kind annotation on a binder is valid - -- by unifying it with the kind of the quantifier. - check_zipped_binder :: ZippedBinder -> TcM () - check_zipped_binder (ZippedBinder _ Nothing) = return () - check_zipped_binder (ZippedBinder tb (Just b)) = - case unLoc b of - UserTyVar _ _ _ -> return () - KindedTyVar _ _ v v_hs_ki -> do - v_ki <- tcLHsKindSig (TyVarBndrKindCtxt (unLoc v)) v_hs_ki - discardResult $ -- See Note [discardResult in kcCheckDeclHeader_sig] - unifyKind (Just (ppr v)) - (tyBinderType tb) - v_ki - - -- Split the invisible binders that should become a part of 'tyConBinders' - -- rather than 'tyConResKind'. - -- See Note [Arity inference in kcCheckDeclHeader_sig] - split_invis :: Kind -> Maybe Kind -> ([TyCoBinder], Kind) - split_invis sig_ki Nothing = - -- instantiate all invisible binders - splitInvisPiTys sig_ki - split_invis sig_ki (Just res_ki) = - -- subtraction a la checkExpectedKind - let n_res_invis_bndrs = invisibleTyBndrCount res_ki - n_sig_invis_bndrs = invisibleTyBndrCount sig_ki - n_inst = n_sig_invis_bndrs - n_res_invis_bndrs - in splitInvisPiTysN n_inst sig_ki - --- A quantifier from a kind signature zipped with a user-written binder for it. -data ZippedBinder = ZippedBinder TyBinder (Maybe (LHsTyVarBndr () GhcRn)) - --- See Note [Arity inference in kcCheckDeclHeader_sig] -zipBinders - :: Kind -- Kind signature - -> [LHsTyVarBndr () GhcRn] -- User-written binders - -> ( [ZippedBinder] -- Zipped binders - , [LHsTyVarBndr () GhcRn] -- Leftover user-written binders - , Kind ) -- Remainder of the kind signature -zipBinders = zip_binders [] emptyTCvSubst - where - -- subst: we substitute as we go, to ensure that the resulting - -- binders in the [ZippedBndr] all have distinct uniques. - -- If not, the TyCon may get multiple binders with the same unique, - -- which results in chaos (see #19092,3,4) - -- (The incoming kind might be forall k. k -> forall k. k -> Type - -- where those two k's have the same unique. Without the substitution - -- we'd get a repeated 'k'.) - zip_binders acc subst ki bs - | (b:bs') <- bs -- Stop as soon as 'bs' becomes empty - , Just (tb,ki') <- tcSplitPiTy_maybe ki - , let (subst', tb') = substTyCoBndr subst tb - = if isInvisibleBinder tb - then zip_binders (ZippedBinder tb' Nothing : acc) subst' ki' bs - else zip_binders (ZippedBinder tb' (Just b) : acc) subst' ki' bs' + go subst tcbs [] + = do { res <- thing_inside subst tcbs + ; return ([], res) } + + go _ [] hs_bndrs + = failWithTc (tooManyBindersErr kisig hs_bndrs) + + go subst (tcb : tcbs') hs_bndrs + | isVisibleTyConBinder tcb + , (L _ hs_bndr : hs_bndrs') <- hs_bndrs -- hs_bndrs is non-empty + , let hs_nm = getName hs_bndr + = -- Visible TyConBinder, so match up with the hs_bndrs + do { (subst', skol_tcb) <- makeSkolemTcb skol_info subst tcb hs_nm + -- Give the skolem the Name of the HsTyVarBndr, so that if it + -- appears in an error message it has a name and binding site + -- that come from the type declaration, not the kind signature + ; let skol_tv = binderVar skol_tcb + ; tc_hs_bndr hs_bndr (tyVarKind skol_tv) + ; (skol_tcbs, res) <- tcExtendTyVarEnv [skol_tv] $ + go subst' tcbs' hs_bndrs' + ; return (skol_tcb:skol_tcbs, res) } | otherwise - = (reverse acc, bs, substTy subst ki) + = -- Invisible TyConBinder, so do not consume one of the hs_bndrs + do { (subst', skol_tcb) <- makeInvisibleSkolemTcb skol_info subst tcb + ; (skol_tcbs, res) <- go subst' tcbs' hs_bndrs + -- NB: pass on hs_bndrs unchanged; we do not consume a + -- HsTyVarBndr for an invisible TyConBinder + ; return (skol_tcb:skol_tcbs, res) } + + tc_hs_bndr :: HsTyVarBndr () GhcRn -> TcKind -> TcM () + tc_hs_bndr (UserTyVar _ _ _) _ + = return () + tc_hs_bndr (KindedTyVar _ _ (L _ hs_nm) lhs_kind) expected_kind + = do { sig_kind <- tcLHsKindSig (TyVarBndrKindCtxt hs_nm) lhs_kind + ; discardResult $ -- See Note [discardResult in kcCheckDeclHeader_sig] + unifyKind (Just (ppr hs_nm)) sig_kind expected_kind } + +makeInvisibleSkolemTcb :: SkolemInfo -> TCvSubst -> TyConBinder -> TcM (TCvSubst, TyConBinder) +makeInvisibleSkolemTcb skol_info subst tcb + = makeSkolemTcb skol_info subst tcb (getName tcb) + +makeSkolemTcb :: SkolemInfo -> TCvSubst -> TyConBinder -> Name -> TcM (TCvSubst, TyConBinder) +-- Skolemise a TyConBinder to contain a TcTyVar, with the specified Name +-- This is a simpler version of newTyVarBndr, in this module +makeSkolemTcb skol_info subst (Bndr tv vis) skol_name + = do { lvl <- getTcLevel + ; let details = SkolemTv skol_info lvl False + kind' = substTy subst (tyVarKind tv) + skol_tv = mkTcTyVar skol_name kind' details + subst' = extendTCvSubstWithClone subst tv skol_tv + ; return (subst', Bndr skol_tv vis) } tooManyBindersErr :: Kind -> [LHsTyVarBndr () GhcRn] -> TcRnMessage tooManyBindersErr ki bndrs = TcRnUnknownMessage $ mkPlainError noHints $ @@ -2761,52 +2677,95 @@ tooManyBindersErr ki bndrs = TcRnUnknownMessage $ mkPlainError noHints $ hang (text "but extra binders found:") 4 (fsep (map ppr bndrs)) -{- Note [Arity inference in kcCheckDeclHeader_sig] -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -Given a kind signature 'kisig' and a declaration header, kcCheckDeclHeader_sig -verifies that the declaration conforms to the signature. The end result is a -TcTyCon 'tc' such that: - - tyConKind tc == kisig - -This TcTyCon would be rather easy to produce if we didn't have to worry about -arity. Consider these declarations: - - type family S1 :: forall k. k -> Type - type family S2 (a :: k) :: Type +{- See Note [kcCheckDeclHeader_sig] +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +Given a kind signature 'sig_kind' and a declaration header, +kcCheckDeclHeader_sig verifies that the declaration conforms to the +signature. The end result is a PolyTcTyCon 'tc' such that: + tyConKind tc == sig_kind + +Basic plan is this: + * splitTyConKind: Take the Kind from the separate kind signature, and + decompose it all the way to a [TyConBinder] and a Kind in the corner. + + NB: these TyConBinders contain TyVars, not TcTyVars. + + * matchUpSigWithDecl: match the [TyConBinder] from the signature with + the [LHsTyVarBndr () GhcRn] from the declaration. The latter are the + explicit, user-written binders. e.g. + data T (a :: k) b = .... + There may be more of the former than the latter, because the former + include invisible binders. matchUpSigWithDecl uses isVisibleTcbVis + to decide which TyConBinders are visible. + + * matchUpSigWithDecl also skolemises the [TyConBinder] to produce + a [TyConBinder], corresponding 1-1 with the consumed [TyConBinder]. + Each new TyConBinder + - Uses the Name from the LHsTyVarBndr, if available, both because that's + what the user expects, and because the binding site accurately comes + from the data/type declaration. + - Uses a skolem TcTyVar. We need these to allow unification. + + * machUpSigWithDecl also unifies the user-supplied kind signature for each + LHsTyVarBndr with the kind that comes from the TyConBinder (itself coming + from the separate kind signature). + + * Finally, kcCheckDeclHeader_sig unifies the return kind of the separate + signature with the kind signature (if any) in the data/type declaration. + E.g. + type S :: forall k. k -> k -> Type + type family S (a :: j) :: j -> Type + Here we match up the 'k ->' with (a :: j); and then must unify the leftover + part of the signature (k -> Type) with the kind signature of the decl, + (j -> Type). This unification, done in kcCheckDeclHeader, needs TcTyVars. + + * The tricky extra_arity part is described in + Note [Arity inference in kcCheckDeclHeader_sig] + +Note [Arity inference in kcCheckDeclHeader_sig] +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +Consider these declarations: + type family S1 :: forall k2. k1 -> k2 -> Type + type family S2 (a :: k1) (b :: k2) :: Type Both S1 and S2 can be given the same standalone kind signature: + type S1 :: forall k1 k2. k1 -> k2 -> Type + type S2 :: forall k1 k2. k1 -> k2 -> Type - type S2 :: forall k. k -> Type +And, indeed, tyConKind S1 == tyConKind S2. However, +tyConBinders and tyConResKind for S1 and S2 are different: -And, indeed, tyConKind S1 == tyConKind S2. However, tyConKind is built from -tyConBinders and tyConResKind, such that + tyConBinders S1 == [spec k1] + tyConResKind S1 == forall k2. k1 -> k2 -> Type + tyConKind S1 == forall k1 k2. k1 -> k2 -> Type - tyConKind tc == mkTyConKind (tyConBinders tc) (tyConResKind tc) - -For S1 and S2, tyConBinders and tyConResKind are different: - - tyConBinders S1 == [] - tyConResKind S1 == forall k. k -> Type - tyConKind S1 == forall k. k -> Type - - tyConBinders S2 == [spec k, anon-vis (a :: k)] + tyConBinders S2 == [spec k1, spec k2, anon-vis (a :: k1), anon-vis (b :: k2)] tyConResKind S2 == Type - tyConKind S1 == forall k. k -> Type - -This difference determines the arity: + tyConKind S1 == forall k1 k2. k1 -> k2 -> Type +This difference determines the /arity/: tyConArity tc == length (tyConBinders tc) +That is, the arity of S1 is 1, while the arity of S2 is 4. -That is, the arity of S1 is 0, while the arity of S2 is 2. +'kcCheckDeclHeader_sig' needs to infer the desired arity, to split the +standalone kind signature into binders and the result kind. It does so +in two rounds: -'kcCheckDeclHeader_sig' needs to infer the desired arity to split the standalone -kind signature into binders and the result kind. It does so in two rounds: +1. matchUpSigWithDecl matches up + - the [TyConBinder] from (applying splitTyConKind to) the kind signature + - with the [LHsTyVarBndr] from the type declaration. + That may leave some excess TyConBinder: in the case of S2 there are + no excess TyConBinders, but in the case of S1 there are two (since + there are no LHsTYVarBndrs. -1. zip user-written binders (vis_tcbs) -2. split off invisible binders (invis_tcbs) +2. Split off further TyConBinders (in the case of S1, one more) to + make it possible to unify the residual return kind with the + signature in the type declaration. More precisely, split off such + enough invisible that the remainder of the standalone kind + signature and the user-written result kind signature have the same + number of invisible quantifiers. -Consider the following declarations: +As another example consider the following declarations: type F :: Type -> forall j. j -> forall k1 k2. (k1, k2) -> Type type family F a b @@ -2814,66 +2773,34 @@ Consider the following declarations: type G :: Type -> forall j. j -> forall k1 k2. (k1, k2) -> Type type family G a b :: forall r2. (r1, r2) -> Type -In step 1 (zip user-written binders), we zip the quantifiers in the signature -with the binders in the header using 'zipBinders'. In both F and G, this results in -the following zipped binders: - - TyBinder LHsTyVarBndr - --------------------------------------- - ZippedBinder Type -> a - ZippedBinder forall j. - ZippedBinder j -> b - - -At this point, we have accumulated three zipped binders which correspond to a -prefix of the standalone kind signature: - - Type -> forall j. j -> ... - -In step 2 (split off invisible binders), we have to decide how much remaining -invisible binders of the standalone kind signature to split off: - - forall k1 k2. (k1, k2) -> Type - ^^^^^^^^^^^^^ - split off or not? - -This decision is made in 'split_invis': +For both F and G, the signature (after splitTyConKind) has + sig_tcbs :: [TyConBinder] + = [ anon-vis (@a_aBq), spec (@j_auA), anon-vis (@(b_aBr :: j_auA)) + , spec (@k1_auB), spec (@k2_auC) + , anon-vis (@(c_aBs :: (k1_auB, k2_auC)))] -* If a user-written result kind signature is not provided, as in F, - then split off all invisible binders. This is why we need special treatment - for AnyKind. -* If a user-written result kind signature is provided, as in G, - then do as checkExpectedKind does and split off (n_sig - n_res) binders. - That is, split off such an amount of binders that the remainder of the - standalone kind signature and the user-written result kind signature have the - same amount of invisible quantifiers. +matchUpSigWithDecl will consume the first three of these, passing on + excess_sig_tcbs + = [ spec (@k1_auB), spec (@k2_auC) + , anon-vis (@(c_aBs :: (k1_auB, k2_auC)))] -For F, split_invis splits away all invisible binders, and we have 2: +For F, there is no result kind signature in the declaration for F, so +we absorb all invisible binders into F's arity. The resulting arity of +F is 3+2=5. - forall k1 k2. (k1, k2) -> Type - ^^^^^^^^^^^^^ - split away both binders - -The resulting arity of F is 3+2=5. (length vis_tcbs = 3, - length invis_tcbs = 2, - length tcbs = 5) - -For G, split_invis decides to split off 1 invisible binder, so that we have the -same amount of invisible quantifiers left: +Now, in the case of G, we have a result kind sig 'forall r2. (r2,r2)->Type'. +This has one invisible binder, so we split of enough extra binders from +our excess_sig_tcbs to leave just one to match 'r2'. res_ki = forall r2. (r1, r2) -> Type kisig = forall k1 k2. (k1, k2) -> Type ^^^ split off this one. -The resulting arity of G is 3+1=4. (length vis_tcbs = 3, - length invis_tcbs = 1, - length tcbs = 4) +The resulting arity of G is 3+1=4. --} - -{- Note [discardResult in kcCheckDeclHeader_sig] -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +Note [discardResult in kcCheckDeclHeader_sig] +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ We use 'unifyKind' to check inline kind annotations in declaration headers against the signature. @@ -3479,24 +3406,20 @@ When we /must/ clone. -- kind-checking and typechecking phases -------------------------------------- -bindTyClTyVars :: SkolemInfo - -> Name - -> (TcTyCon -> [TyConBinder] -> [TcTyVar] -> TcKind -> TcM a) -> TcM a +bindTyClTyVars :: Name -> (TcTyCon -> [TyConBinder] -> TcKind -> TcM a) -> TcM a -- ^ Used for the type variables of a type or class decl -- in the "kind checking" and "type checking" pass, -- but not in the initial-kind run. -bindTyClTyVars skol_info tycon_name thing_inside +bindTyClTyVars tycon_name thing_inside = do { tycon <- tcLookupTcTyCon tycon_name ; let scoped_prs = tcTyConScopedTyVars tycon res_kind = tyConResKind tycon binders = tyConBinders tycon - ; tcExtendTyVarEnv skol_info (binderVars binders) $ \subst tc_vars -> - let scoped_prs' = map (second (expect_tv . substTyVar subst)) scoped_prs - in tcExtendNameTyVarEnv scoped_prs' $ - thing_inside tycon binders tc_vars res_kind } - where - expect_tv (TyVarTy tv ) = tv - expect_tv _ = panic "expect_tv" + ; traceTc "bindTyClTyVars" (ppr tycon_name $$ ppr scoped_prs) + ; tcExtendNameTyVarEnv scoped_prs $ + thing_inside tycon binders res_kind } + -- Passing binders and res_kind is redundant, of course, but + -- saves calling tyConBinders and tyConResKind in every caller {- ********************************************************************* @@ -3507,7 +3430,7 @@ bindTyClTyVars skol_info tycon_name thing_inside zonkAndScopedSort :: [TcTyVar] -> TcM [TcTyVar] zonkAndScopedSort spec_tkvs - = do { spec_tkvs <- mapM zonkTcTyVarToTyVar spec_tkvs + = do { spec_tkvs <- mapM zonkTcTyVarToTcTyVar spec_tkvs -- Zonk the kinds, to we can do the dependency analayis -- Do a stable topological sort, following @@ -3655,19 +3578,27 @@ Hence using zonked_kinds when forming tvs'. -} ----------------------------------- -etaExpandAlgTyCon :: [TyVar] -- Doesn't matter if these are TcTyVar or TyVar - -> Kind -- must be zonked - -> TcM ([TyConBinder], Kind) +etaExpandAlgTyCon :: [TyConBinder] -> Kind -> TcM ([TyConBinder], Kind) +etaExpandAlgTyCon tcbs res_kind + = splitTyConKind in_scope avoid_occs res_kind + where + tyvars = binderVars tcbs + in_scope = mkInScopeSet (mkVarSet tyvars) + avoid_occs = map getOccName tyvars + +splitTyConKind :: InScopeSet + -> [OccName] -- Avoid these OccNames + -> Kind -- Must be zonked + -> TcM ([TyConBinder], Kind) -- GADT decls can have a (perhaps partial) kind signature -- e.g. data T a :: * -> * -> * where ... -- This function makes up suitable (kinded) TyConBinders for the -- argument kinds. E.g. in this case it might return -- ([b::*, c::*], *) -- Never emits constraints. --- It's a little trickier than you might think: see --- Note [TyConBinders for the result kind signature of a data type] --- See Note [Datatype return kinds] in GHC.Tc.TyCl -etaExpandAlgTyCon lhs_tvs kind +-- It's a little trickier than you might think: see Note [splitTyConKind] +-- See also Note [Datatype return kinds] in GHC.Tc.TyCl +splitTyConKind in_scope avoid_occs kind = do { loc <- getSrcSpanM ; uniqs <- newUniqueSupply ; rdr_env <- getLocalRdrEnv @@ -3676,13 +3607,11 @@ etaExpandAlgTyCon lhs_tvs kind , let occ = mkOccName tvName str , isNothing (lookupLocalRdrOcc rdr_env occ) -- Note [Avoid name clashes for associated data types] - , not (occ `elem` lhs_occs) ] + , not (occ `elem` avoid_occs) ] new_uniqs = uniqsFromSupply uniqs - subst = mkEmptyTCvSubst (mkInScopeSet (mkVarSet lhs_tvs)) + subst = mkEmptyTCvSubst in_scope ; return (go loc new_occs new_uniqs subst [] kind) } where - lhs_occs = map getOccName lhs_tvs - go loc occs uniqs subst acc kind = case splitPiTy_maybe kind of Nothing -> (reverse acc, substTy subst kind) @@ -3886,18 +3815,21 @@ tcbVisibilities tc orig_args = pprPanic "addTcbVisibilities" (ppr tc <+> ppr orig_args) -{- Note [TyConBinders for the result kind signature of a data type] -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +{- Note [splitTyConKind] +~~~~~~~~~~~~~~~~~~~~~~~~ Given data T (a::*) :: * -> forall k. k -> * we want to generate the extra TyConBinders for T, so we finally get (a::*) (b::*) (k::*) (c::k) -The function etaExpandAlgTyCon generates these extra TyConBinders from -the result kind signature. +The function splitTyConKind generates these extra TyConBinders from +the result kind signature. The same function is also used by +kcCheckDeclHeader_sig to get the [TyConBinder] from the Kind of +the TyCon given in a standalone kind signature. E.g. + type T :: forall (a::*). * -> forall k. k -> * We need to take care to give the TyConBinders (a) OccNames that are fresh (because the TyConBinders of a TyCon - must have distinct OccNames + must have distinct OccNames) (b) Uniques that are fresh (obviously) @@ -3908,7 +3840,7 @@ And also see Note [Avoid name clashes for associated data types]. For (b) suppose we have data T :: forall k. k -> forall k. k -> * where the two k's are identical even up to their uniques. Surprisingly, -this can happen: see #14515. +this can happen: see #14515, #19092,3,4. It's reasonably easy to solve all this; just run down the list with a substitution; hence the recursive 'go' function. But it has to be diff --git a/compiler/GHC/Tc/Solver.hs b/compiler/GHC/Tc/Solver.hs index d82111ba28..16980c796b 100644 --- a/compiler/GHC/Tc/Solver.hs +++ b/compiler/GHC/Tc/Solver.hs @@ -58,6 +58,7 @@ import GHC.Core.Predicate import GHC.Tc.Types.Origin import GHC.Tc.Utils.TcType import GHC.Core.Type +import GHC.Core.TyCon ( TyConBinder ) import GHC.Builtin.Types ( liftedRepTy, manyDataConTy, liftedDataConTy ) import GHC.Core.Unify ( tcMatchTyKi ) import GHC.Utils.Misc @@ -163,17 +164,17 @@ simplifyTop wanteds ; return (evBindMapBinds binds1 `unionBags` binds2) } -pushLevelAndSolveEqualities :: SkolemInfo -> [TcTyVar] -> TcM a -> TcM a +pushLevelAndSolveEqualities :: SkolemInfoAnon -> [TyConBinder] -> TcM a -> TcM a -- Push level, and solve all resulting equalities -- If there are any unsolved equalities, report them -- and fail (in the monad) -- -- Panics if we solve any non-equality constraints. (In runTCSEqualities -- we use an error thunk for the evidence bindings.) -pushLevelAndSolveEqualities skol_info skol_tvs thing_inside +pushLevelAndSolveEqualities skol_info_anon tcbs thing_inside = do { (tclvl, wanted, res) <- pushLevelAndSolveEqualitiesX "pushLevelAndSolveEqualities" thing_inside - ; reportUnsolvedEqualities skol_info skol_tvs tclvl wanted + ; report_unsolved_equalities skol_info_anon (binderVars tcbs) tclvl wanted ; return res } pushLevelAndSolveEqualitiesX :: String -> TcM a @@ -227,11 +228,11 @@ simplifyAndEmitFlatConstraints wanted -- Emit the bad constraints, wrapped in an implication -- See Note [Wrapping failing kind equalities] ; tclvl <- TcM.getTcLevel - ; implic <- buildTvImplication unkSkol [] (pushTcLevel tclvl) wanted - -- ^^^^^^ | ^^^^^^^^^^^^^^^^^ - -- it's OK to use unkSkol | we must increase the TcLevel, - -- because we don't bind | as explained in - -- any skolem variables here | Note [Wrapping failing kind equalities] + ; implic <- buildTvImplication unkSkolAnon [] (pushTcLevel tclvl) wanted + -- ^^^^^^ | ^^^^^^^^^^^^^^^^^ + -- it's OK to use unkSkol | we must increase the TcLevel, + -- because we don't bind | as explained in + -- any skolem variables here | Note [Wrapping failing kind equalities] ; emitImplication implic ; failM } Just (simples, holes) @@ -460,13 +461,17 @@ reportUnsolvedEqualities :: SkolemInfo -> [TcTyVar] -> TcLevel -- -- The provided SkolemInfo and [TcTyVar] arguments are used in an implication to -- provide skolem info for any errors. --- reportUnsolvedEqualities skol_info skol_tvs tclvl wanted + = report_unsolved_equalities (getSkolemInfo skol_info) skol_tvs tclvl wanted + +report_unsolved_equalities :: SkolemInfoAnon -> [TcTyVar] -> TcLevel + -> WantedConstraints -> TcM () +report_unsolved_equalities skol_info_anon skol_tvs tclvl wanted | isEmptyWC wanted = return () | otherwise = checkNoErrs $ -- Fail - do { implic <- buildTvImplication skol_info skol_tvs tclvl wanted + do { implic <- buildTvImplication skol_info_anon skol_tvs tclvl wanted ; reportAllUnsolved (mkImplicWC (unitBag implic)) } @@ -1383,7 +1388,7 @@ decideMonoTyVars infer_mode name_taus psigs candidates -- If possible, we quantify over partial-sig qtvs, so they are -- not mono. Need to zonk them because they are meta-tyvar TyVarTvs - ; psig_qtvs <- mapM zonkTcTyVarToTyVar $ binderVars $ + ; psig_qtvs <- mapM zonkTcTyVarToTcTyVar $ binderVars $ concatMap (map snd . sig_inst_skols) psigs ; psig_theta <- mapM TcM.zonkTcType $ diff --git a/compiler/GHC/Tc/TyCl.hs b/compiler/GHC/Tc/TyCl.hs index d511834f18..f67ee8b157 100644 --- a/compiler/GHC/Tc/TyCl.hs +++ b/compiler/GHC/Tc/TyCl.hs @@ -417,24 +417,43 @@ TcTyCons are used for two distinct purposes see makeRecoveryTyCon. 2. When checking a type/class declaration (in module GHC.Tc.TyCl), we come - upon knowledge of the eventual tycon in bits and pieces. - - S1) First, we use inferInitialKinds to look over the user-provided - kind signature of a tycon (including, for example, the number - of parameters written to the tycon) to get an initial shape of - the tycon's kind. We record that shape in a TcTyCon. - - For CUSK tycons, the TcTyCon has the final, generalised kind. - For non-CUSK tycons, the TcTyCon has as its tyConBinders only - the explicit arguments given -- no kind variables, etc. - - S2) Then, using these initial kinds, we kind-check the body of the - tycon (class methods, data constructors, etc.), filling in the + upon knowledge of the eventual tycon in bits and pieces, and we use + a TcTyCon to record what we know before we are ready to build the + final TyCon. + + We first build a MonoTcTyCon, then generalise to a PolyTcTyCon + See Note [TcTyCon, MonoTcTyCon, and PolyTcTyCon] in GHC.Tc.Utils.TcType + Specifically: + + S1) In kcTyClGroup, we use checkInitialKinds to get the + utterly-final Kind of all TyCons in the group that + (a) have a kind signature or + (b) have a CUSK. + This produces a PolyTcTyCon, that is, a TcTyCon in which the binders + and result kind are full of TyVars (not TcTyVars). No unification + variables here; everything is in its final form. + + S2) In kcTyClGroup, we use inferInitialKinds to look over the + declaration of any TyCon that lacks a kinds signature or + CUSK, to determine its "shape"; for example, the number of + parameters, and any kind signatures. + + We record that shape record that shape in a MonoTcTyCon; it is + "mono" because it has not been been generalised, and its binders + and result kind may have free unification variables. + + S3) Still in kcTyClGroup, we use kcLTyClDecl to kind-check the + body (class methods, data constructors, etc.) of each of + these MonoTcTyCons, which has the effect of filling in the metavariables in the tycon's initial kind. - S3) We then generalize to get the (non-CUSK) tycon's final, fixed - kind. Finally, once this has happened for all tycons in a - mutually recursive group, we can desugar the lot. + S4) Still in kcTyClGroup, we use generaliseTyClDecl to generalize + each MonoTcTyCon to get a PolyTcTyCon, with final TyVars in it, + and a final, fixed kind. + + S5) Finally, back in TcTyClDecls, we extend the environment with + the PolyTcTyCons, and typecheck each declaration (regardless + of kind signatures etc) to get final TyCon. For convenience, we store partially-known tycons in TcTyCons, which might store meta-variables. These TcTyCons are stored in the local @@ -655,7 +674,7 @@ been generalized. -} -kcTyClGroup :: KindSigEnv -> [LTyClDecl GhcRn] -> TcM ([TcTyCon], NameSet) +kcTyClGroup :: KindSigEnv -> [LTyClDecl GhcRn] -> TcM ([PolyTcTyCon], NameSet) -- Kind check this group, kind generalize, and return the resulting local env -- This binds the TyCons and Classes of the group, but not the DataCons @@ -699,7 +718,7 @@ kcTyClGroup kisig_env decls ; inferred_tcs <- tcExtendKindEnvWithTyCons checked_tcs $ - pushLevelAndSolveEqualities unkSkol [] $ + pushLevelAndSolveEqualities unkSkolAnon [] $ -- We are going to kind-generalise, so unification -- variables in here must be one level in do { -- Step 1: Bind kind variables for all decls @@ -739,7 +758,7 @@ type ScopedPairs = [(Name, TcTyVar)] -- specified-tvs ++ required-tvs -- You can distinguish them because there are tyConArity required-tvs -generaliseTyClDecl :: NameEnv TcTyCon -> LTyClDecl GhcRn -> TcM [TcTyCon] +generaliseTyClDecl :: NameEnv MonoTcTyCon -> LTyClDecl GhcRn -> TcM [PolyTcTyCon] -- See Note [Swizzling the tyvars before generaliseTcTyCon] generaliseTyClDecl inferred_tc_env (L _ decl) = do { let names_in_this_decl :: [Name] @@ -779,7 +798,7 @@ generaliseTyClDecl inferred_tc_env (L _ decl) zonk_tc_tycon :: (TcTyCon, ScopedPairs) -> TcM (TcTyCon, ScopedPairs, TcKind) zonk_tc_tycon (tc, scoped_prs) - = do { scoped_prs <- mapSndM zonkTcTyVarToTyVar scoped_prs + = do { scoped_prs <- mapSndM zonkTcTyVarToTcTyVar scoped_prs -- We really have to do this again, even though -- we have just done zonkAndSkolemise ; res_kind <- zonkTcType (tyConResKind tc) @@ -885,7 +904,7 @@ swizzleTcTyConBndrs tc_infos swizzle_ty ty = runIdentity (map_type ty) -generaliseTcTyCon :: (TcTyCon, ScopedPairs, TcKind) -> TcM TcTyCon +generaliseTcTyCon :: (MonoTcTyCon, ScopedPairs, TcKind) -> TcM PolyTcTyCon generaliseTcTyCon (tc, scoped_prs, tc_res_kind) -- See Note [Required, Specified, and Inferred for types] = setSrcSpan (getSrcSpan tc) $ @@ -1306,7 +1325,7 @@ mk_prom_err_env decl -- Works for family declarations too -------------- -inferInitialKinds :: [LTyClDecl GhcRn] -> TcM [TcTyCon] +inferInitialKinds :: [LTyClDecl GhcRn] -> TcM [MonoTcTyCon] -- Returns a TcTyCon for each TyCon bound by the decls, -- each with its initial kind @@ -1320,7 +1339,7 @@ inferInitialKinds decls -- Check type/class declarations against their standalone kind signatures or -- CUSKs, producing a generalized TcTyCon for each. -checkInitialKinds :: [(LTyClDecl GhcRn, SAKS_or_CUSK)] -> TcM [TcTyCon] +checkInitialKinds :: [(LTyClDecl GhcRn, SAKS_or_CUSK)] -> TcM [PolyTcTyCon] checkInitialKinds decls = do { traceTc "checkInitialKinds {" $ ppr (mapFst (tcdName . unLoc) decls) ; tcs <- concatMapM check_initial_kind decls @@ -1353,16 +1372,15 @@ getInitialKind strategy , tcdATs = ats }) = do { cls <- kcDeclHeader strategy name ClassFlavour ktvs $ return (TheKind constraintKind) - ; let parent_tv_prs = tcTyConScopedTyVars cls -- See Note [Don't process associated types in getInitialKind] - ; inner_tcs <- - tcExtendNameTyVarEnv parent_tv_prs $ - mapM (addLocMA (getAssocFamInitialKind cls)) ats + + ; inner_tcs <- tcExtendNameTyVarEnv (tcTyConScopedTyVars cls) $ + mapM (addLocMA (getAssocFamInitialKind cls)) ats ; return (cls : inner_tcs) } where getAssocFamInitialKind cls = case strategy of - InitialKindInfer -> get_fam_decl_initial_kind (Just cls) + InitialKindInfer -> get_fam_decl_initial_kind (Just cls) InitialKindCheck _ -> check_initial_kind_assoc_fam cls getInitialKind strategy @@ -2190,7 +2208,7 @@ newtype instance Foo 'Red = FooRedC Int# Note that, in the GADT case, we might have a kind signature with arrows (newtype XYZ a b :: Type -> Type where ...). We want only the final -component of the kind for checking in kcConDecl, so we call etaExpandAlgTyCon +component of the kind for checking in kcConDecl, so we call etaExpanAlgTyCon in kcTyClDecl. STEP 3: Type-checking (desugaring), as done by tcTyClDecl. The key function @@ -2429,17 +2447,15 @@ tcClassDecl1 :: RolesInfo -> Name -> Maybe (LHsContext GhcRn) -> [LFamilyDecl GhcRn] -> [LTyFamDefltDecl GhcRn] -> TcM Class tcClassDecl1 roles_info class_name hs_ctxt meths fundeps sigs ats at_defs - = fixM $ \ clas -> - -- We need the knot because 'clas' is passed into tcClassATs - mkSkolemInfo skol_info_anon >>= \skol_info -> - bindTyClTyVars skol_info class_name $ \ _ binders binder_sks res_kind -> + = fixM $ \ clas -> -- We need the knot because 'clas' is passed into tcClassATs + bindTyClTyVars class_name $ \ _ binders res_kind -> do { checkClassKindSig res_kind ; traceTc "tcClassDecl 1" (ppr class_name $$ ppr binders) ; let tycon_name = class_name -- We use the same name roles = roles_info tycon_name -- for TyCon and Class ; (ctxt, fds, sig_stuff, at_stuff) - <- pushLevelAndSolveEqualities skol_info binder_sks $ + <- pushLevelAndSolveEqualities skol_info binders $ -- The (binderVars binders) is needed bring into scope the -- skolems bound by the class decl header (#17841) do { ctxt <- tcHsContext hs_ctxt @@ -2494,7 +2510,8 @@ tcClassDecl1 roles_info class_name hs_ctxt meths fundeps sigs ats at_defs ppr fds) ; return clas } where - skol_info_anon = TyConSkol ClassFlavour class_name + skol_info = TyConSkol ClassFlavour class_name + tc_fundep :: GHC.Hs.FunDep GhcRn -> TcM ([Var],[Var]) tc_fundep (FunDep _ tvs1 tvs2) = do { tvs1' <- mapM (tcLookupTyVar . unLoc) tvs1 ; @@ -2718,8 +2735,7 @@ tcFamDecl1 parent (FamilyDecl { fdInfo = fam_info , fdResultSig = L _ sig , fdInjectivityAnn = inj }) | DataFamily <- fam_info - = mkSkolemInfo (TyConSkol (DataFamilyFlavour Nothing) tc_name) >>= \skol_info -> - bindTyClTyVars skol_info tc_name $ \ _ binders _skol_tvs res_kind -> do + = bindTyClTyVars tc_name $ \ _ binders res_kind -> do { traceTc "tcFamDecl1 data family:" (ppr tc_name) ; checkFamFlag tc_name @@ -2745,9 +2761,7 @@ tcFamDecl1 parent (FamilyDecl { fdInfo = fam_info ; return tycon } | OpenTypeFamily <- fam_info - = - mkSkolemInfo (TyConSkol (OpenTypeFamilyFlavour Nothing) tc_name) >>= \skol_info -> - bindTyClTyVars skol_info tc_name $ \ _ binders _skol_tvs res_kind -> do + = bindTyClTyVars tc_name $ \ _ binders res_kind -> do { traceTc "tcFamDecl1 open type family:" (ppr tc_name) ; checkFamFlag tc_name ; inj' <- tcInjectivity binders inj @@ -2764,7 +2778,7 @@ tcFamDecl1 parent (FamilyDecl { fdInfo = fam_info -- the variables in the header scope only over the injectivity -- declaration but this is not involved here ; (inj', binders, res_kind) - <- bindTyClTyVars unkSkol tc_name $ \ _ binders _skol_tvs res_kind -> + <- bindTyClTyVars tc_name $ \ _ binders res_kind -> do { inj' <- tcInjectivity binders inj ; return (inj', binders, res_kind) } @@ -2851,7 +2865,7 @@ tcInjectivity tcbs (Just (L loc (InjectivityAnn _ _ lInjNames))) text "Illegal injectivity annotation" $$ text "Use TypeFamilyDependencies to allow this") ; inj_tvs <- mapM (tcLookupTyVar . unLoc) lInjNames - ; inj_tvs <- mapM zonkTcTyVarToTyVar inj_tvs -- zonk the kinds + ; inj_tvs <- mapM zonkTcTyVarToTcTyVar inj_tvs -- zonk the kinds ; let inj_ktvs = filterVarSet isTyVar $ -- no injective coercion vars closeOverKinds (mkVarSet inj_tvs) ; let inj_bools = map (`elemVarSet` inj_ktvs) tvs @@ -2862,10 +2876,10 @@ tcInjectivity tcbs (Just (L loc (InjectivityAnn _ _ lInjNames))) tcTySynRhs :: RolesInfo -> Name -> LHsType GhcRn -> TcM TyCon tcTySynRhs roles_info tc_name hs_ty - = mkSkolemInfo skol_info_anon >>= \skol_info -> bindTyClTyVars skol_info tc_name $ \ _ binders skol_tvs res_kind -> + = bindTyClTyVars tc_name $ \ _ binders res_kind -> do { env <- getLclEnv ; traceTc "tc-syn" (ppr tc_name $$ ppr (tcl_env env)) - ; rhs_ty <- pushLevelAndSolveEqualities skol_info skol_tvs $ + ; rhs_ty <- pushLevelAndSolveEqualities skol_info binders $ --TODO: MP I think this should be TcKind, not Kind tcCheckLHsType hs_ty (TheKind res_kind) @@ -2885,7 +2899,7 @@ tcTySynRhs roles_info tc_name hs_ty ; let roles = roles_info tc_name ; return (buildSynTyCon tc_name binders res_kind roles rhs_ty) } where - skol_info_anon = TyConSkol TypeSynonymFlavour tc_name + skol_info = TyConSkol TypeSynonymFlavour tc_name tcDataDefn :: SDoc -> RolesInfo -> Name -> HsDataDefn GhcRn -> TcM (TyCon, [DerivInfo]) @@ -2897,9 +2911,7 @@ tcDataDefn err_ctxt roles_info tc_name -- via inferInitialKinds , dd_cons = cons , dd_derivs = derivs }) - = - mkSkolemInfo skol_info_anon >>= \skol_info -> - bindTyClTyVars skol_info tc_name $ \ tctc tycon_binders skol_tvs res_kind -> + = bindTyClTyVars tc_name $ \ tctc tycon_binders res_kind -> -- 'tctc' is a 'TcTyCon' and has the 'tcTyConScopedTyVars' that we need -- unlike the finalized 'tycon' defined above which is an 'AlgTyCon' -- @@ -2910,15 +2922,14 @@ tcDataDefn err_ctxt roles_info tc_name -- over GADT ConDecls as well; and it's awkward not to do { gadt_syntax <- dataDeclChecks tc_name new_or_data ctxt cons -- see Note [Datatype return kinds] - ; (extra_bndrs, final_res_kind) <- etaExpandAlgTyCon (binderVars tycon_binders) res_kind - ; tcExtendTyVarEnv skol_info (binderVars extra_bndrs) $ \_subst extra_tvs -> do { + ; (extra_bndrs, final_res_kind) <- etaExpandAlgTyCon tycon_binders res_kind ; tcg_env <- getGblEnv ; let hsc_src = tcg_src tcg_env ; unless (mk_permissive_kind hsc_src cons) $ checkDataKindSig (DataDeclSort new_or_data) final_res_kind - ; stupid_tc_theta <- pushLevelAndSolveEqualities skol_info skol_tvs $ + ; stupid_tc_theta <- pushLevelAndSolveEqualities skol_info tycon_binders $ tcHsContext ctxt -- See Note [Error on unconstrained meta-variables] in GHC.Tc.Utils.TcMType @@ -2943,11 +2954,10 @@ tcDataDefn err_ctxt roles_info tc_name ; tycon <- fixM $ \ rec_tycon -> do { let final_bndrs = tycon_binders `chkAppend` extra_bndrs - final_tvs = skol_tvs `chkAppend` extra_tvs roles = roles_info tc_name ; data_cons <- tcConDecls new_or_data DDataType - rec_tycon final_bndrs final_tvs final_res_kind + rec_tycon final_bndrs final_res_kind cons ; tc_rhs <- mk_tc_rhs hsc_src rec_tycon data_cons ; tc_rep_nm <- newTyConRepName tc_name @@ -2964,9 +2974,9 @@ tcDataDefn err_ctxt roles_info tc_name , di_clauses = derivs , di_ctxt = err_ctxt } ; traceTc "tcDataDefn" (ppr tc_name $$ ppr tycon_binders $$ ppr extra_bndrs) - ; return (tycon, [deriv_info]) } } + ; return (tycon, [deriv_info]) } where - skol_info_anon = TyConSkol flav tc_name + skol_info = TyConSkol flav tc_name flav = newOrDataToFlavour new_or_data -- Abstract data types in hsig files can have arbitrary kinds, @@ -3380,12 +3390,11 @@ tcConDecls :: NewOrData -> DataDeclInfo -> KnotTied TyCon -- Representation TyCon -> [TyConBinder] -- Binders of representation TyCon - -> [TcTyVar] -- Skolemised binder vars (use these when typechecking things) -> TcKind -- Result kind -> [LConDecl GhcRn] -> TcM [DataCon] -tcConDecls new_or_data dd_info rep_tycon tmpl_bndrs skol_tvs res_kind +tcConDecls new_or_data dd_info rep_tycon tmpl_bndrs res_kind = concatMapM $ addLocMA $ - tcConDecl new_or_data dd_info rep_tycon tmpl_bndrs skol_tvs res_kind + tcConDecl new_or_data dd_info rep_tycon tmpl_bndrs res_kind (mkTyConTagMap rep_tycon) -- mkTyConTagMap: it's important that we pay for tag allocation here, -- once per TyCon. See Note [Constructor tag allocation], fixes #14657 @@ -3394,13 +3403,12 @@ tcConDecl :: NewOrData -> DataDeclInfo -> KnotTied TyCon -- Representation tycon. Knot-tied! -> [TyConBinder] -- Binders of representation TyCon - -> [TcTyVar] -- Skolemised binders -> TcKind -- Result kind -> NameEnv ConTag -> ConDecl GhcRn -> TcM [DataCon] -tcConDecl new_or_data dd_info rep_tycon tc_bndrs skol_tvs res_kind tag_map +tcConDecl new_or_data dd_info rep_tycon tc_bndrs res_kind tag_map (ConDeclH98 { con_name = lname@(L _ name) , con_ex_tvs = explicit_tkv_nms , con_mb_cxt = hs_ctxt @@ -3448,7 +3456,7 @@ tcConDecl new_or_data dd_info rep_tycon tc_bndrs skol_tvs res_kind tag_map ; kvs <- kindGeneralizeAll skol_info fake_ty - ; let all_skol_tvs = skol_tvs ++ kvs ++ binderVars exp_tvbndrs + ; let all_skol_tvs = tc_tvs ++ kvs ++ binderVars exp_tvbndrs ; reportUnsolvedEqualities skol_info all_skol_tvs tclvl wanted -- The skol_info claims that all the variables are bound -- by the data constructor decl, whereas actually the @@ -3490,7 +3498,7 @@ tcConDecl new_or_data dd_info rep_tycon tc_bndrs skol_tvs res_kind tag_map ; return [dc] } -tcConDecl new_or_data dd_info rep_tycon tc_bndrs _skol_tvs _res_kind tag_map +tcConDecl new_or_data dd_info rep_tycon tc_bndrs _res_kind tag_map -- NB: don't use res_kind here, as it's ill-scoped. Instead, -- we get the res_kind by typechecking the result type. (ConDeclGADT { con_names = names @@ -4644,7 +4652,8 @@ checkValidClass cls pred_tvs = tyCoVarsOfType pred check_at (ATI fam_tc m_dflt_rhs) - = do { checkTc (cls_arity == 0 || any (`elemVarSet` cls_tv_set) fam_tvs) + = do { traceTc "ati" (ppr fam_tc $$ ppr tyvars $$ ppr fam_tvs) + ; checkTc (cls_arity == 0 || any (`elemVarSet` cls_tv_set) fam_tvs) (noClassTyVarErr cls fam_tc) -- Check that the associated type mentions at least -- one of the class type variables diff --git a/compiler/GHC/Tc/TyCl/Instance.hs b/compiler/GHC/Tc/TyCl/Instance.hs index 0a5f2c09ef..659190d3cb 100644 --- a/compiler/GHC/Tc/TyCl/Instance.hs +++ b/compiler/GHC/Tc/TyCl/Instance.hs @@ -691,7 +691,7 @@ tcDataFamInstDecl mb_clsinfo tv_skol_env ; gadt_syntax <- dataDeclChecks fam_name new_or_data hs_ctxt hs_cons -- Do /not/ check that the number of patterns = tyConArity fam_tc -- See [Arity of data families] in GHC.Core.FamInstEnv - ; (qtvs, pats, res_kind, stupid_theta) + ; (qtvs, scoped_tvs, pats, res_kind, stupid_theta) <- tcDataFamInstHeader mb_clsinfo fam_tc outer_bndrs fixity hs_ctxt hs_pats m_ksig new_or_data -- Eta-reduce the axiom if possible @@ -717,7 +717,7 @@ tcDataFamInstDecl mb_clsinfo tv_skol_env -- we did it before the "extra" tvs from etaExpandAlgTyCon -- would always be eta-reduced -- - ; (extra_tcbs, final_res_kind) <- etaExpandAlgTyCon (binderVars full_tcbs) res_kind + ; (extra_tcbs, final_res_kind) <- etaExpandAlgTyCon full_tcbs res_kind -- Check the result kind; it may come from a user-written signature. -- See Note [Datatype return kinds] in GHC.Tc.TyCl point 4(a) @@ -737,13 +737,12 @@ tcDataFamInstDecl mb_clsinfo tv_skol_env , text "final_res_kind:" <+> ppr final_res_kind , text "eta_pats" <+> ppr eta_pats , text "eta_tcbs" <+> ppr eta_tcbs ] - ; skol_info <- mkSkolemInfo FamInstSkol ; (rep_tc, axiom) <- fixM $ \ ~(rec_rep_tc, _) -> - do { data_cons <- tcExtendTyVarEnv skol_info qtvs $ \subst tvs -> + do { data_cons <- tcExtendTyVarEnv scoped_tvs $ -- For H98 decls, the tyvars scope -- over the data constructors tcConDecls new_or_data (DDataInstance orig_res_ty) - rec_rep_tc ty_binders tvs (substTy subst final_res_kind) + rec_rep_tc ty_binders final_res_kind hs_cons ; rep_tc_name <- newFamInstTyConName lfam_name pats @@ -865,7 +864,7 @@ tcDataFamInstHeader -> LexicalFixity -> Maybe (LHsContext GhcRn) -> HsTyPats GhcRn -> Maybe (LHsKind GhcRn) -> NewOrData - -> TcM ([TyVar], [Type], Kind, ThetaType) + -> TcM ([TyVar], [TcTyVar], [Type], Kind, ThetaType) -- The "header" of a data family instance is the part other than -- the data constructors themselves -- e.g. data instance D [a] :: * -> * where ... @@ -941,7 +940,7 @@ tcDataFamInstHeader mb_clsinfo fam_tc outer_bndrs fixity Just (_, pats) -> pure pats Nothing -> pprPanic "tcDataFamInstHeader" (ppr lhs_ty) - ; return (qtvs, pats, master_res_kind, stupid_theta) } + ; return (qtvs, scoped_tvs, pats, master_res_kind, stupid_theta) } where fam_name = tyConName fam_tc data_ctxt = DataKindCtxt fam_name diff --git a/compiler/GHC/Tc/Types/Constraint.hs b/compiler/GHC/Tc/Types/Constraint.hs index d2552d3d88..10cbb633c8 100644 --- a/compiler/GHC/Tc/Types/Constraint.hs +++ b/compiler/GHC/Tc/Types/Constraint.hs @@ -1306,6 +1306,15 @@ data Implication -- allocated /inside/ this implication ic_skols :: [TcTyVar], -- Introduced skolems + -- ic_skols are usually skolem TcTyVars, but can also be TyVars. + -- For example in tcClassDecl1 we do pushLevelAndSolveEqualities + -- with (binderVars binders) which are TyVars. It is /very/ inconvenient + -- to skolemise these TyVar binders. + -- + -- But in any case, having TyVars here is fine because + -- all that matters about ic_skols is their /identity/; + -- we could pretty much use a [Name] instead. + ic_info :: SkolemInfoAnon, -- See Note [Skolems in an implication] -- See Note [Shadowing in a constraint] diff --git a/compiler/GHC/Tc/Types/Origin.hs b/compiler/GHC/Tc/Types/Origin.hs index 64a6a04466..4fc977ee14 100644 --- a/compiler/GHC/Tc/Types/Origin.hs +++ b/compiler/GHC/Tc/Types/Origin.hs @@ -13,7 +13,8 @@ module GHC.Tc.Types.Origin ( redundantConstraintsSpan, -- SkolemInfo - SkolemInfo(..), SkolemInfoAnon(..), mkSkolemInfo, getSkolemInfo, pprSigSkolInfo, pprSkolInfo, unkSkol, + SkolemInfo(..), SkolemInfoAnon(..), mkSkolemInfo, getSkolemInfo, pprSigSkolInfo, pprSkolInfo, + unkSkol, unkSkolAnon, -- CtOrigin CtOrigin(..), exprCtOrigin, lexprCtOrigin, matchesCtOrigin, grhssCtOrigin, @@ -291,7 +292,10 @@ data SkolemInfoAnon -- We're hoping to be able to get rid of this entirely, but for the moment -- it's still needed. unkSkol :: HasCallStack => SkolemInfo -unkSkol = SkolemInfo (mkUniqueGrimily 0) (UnkSkol callStack) +unkSkol = SkolemInfo (mkUniqueGrimily 0) unkSkolAnon + +unkSkolAnon :: HasCallStack => SkolemInfoAnon +unkSkolAnon = UnkSkol callStack -- | Wrap up the origin of a skolem type variable with a new 'Unique', -- so that we can common up skolem type variables whose 'SkolemInfo' diff --git a/compiler/GHC/Tc/Utils/Env.hs b/compiler/GHC/Tc/Utils/Env.hs index 0ebe0c5e5d..d4705677a8 100644 --- a/compiler/GHC/Tc/Utils/Env.hs +++ b/compiler/GHC/Tc/Utils/Env.hs @@ -91,7 +91,7 @@ import GHC.Tc.Utils.TcMType import GHC.Tc.Utils.TcType import GHC.Tc.Types.Evidence (HsWrapper, idHsWrapper) import {-# SOURCE #-} GHC.Tc.Utils.Unify ( tcSubMult ) -import GHC.Tc.Types.Origin ( CtOrigin(UsageEnvironmentOf), SkolemInfo () ) +import GHC.Tc.Types.Origin ( CtOrigin(UsageEnvironmentOf) ) import GHC.Core.UsageEnv import GHC.Core.InstEnv @@ -133,7 +133,7 @@ import GHC.Types.Error import qualified GHC.LanguageExtensions as LangExt import Data.IORef -import Data.List (intercalate, mapAccumL) +import Data.List (intercalate) import Control.Monad import GHC.Driver.Env.KnotVars @@ -534,16 +534,9 @@ tcExtendKindEnv extra_env thing_inside ----------------------- -- Scoped type and kind variables -tcExtendTyVarEnv :: SkolemInfo -> [TyVar] -> (TCvSubst -> [TcTyVar] -> TcM r) -> TcM r -tcExtendTyVarEnv skol_info tvs thing_inside - = let (subst, tvs') = mapAccumL go emptyTCvSubst tvs - in tcExtendNameTyVarEnv tvs' (thing_inside subst (map snd tvs')) - where - -- Perhaps should use tcInstSkolTyVars here, that does a lot more though. - go subst tv = - let tv' = mkTcTyVar (tyVarName tv) (substTy subst (tyVarKind tv)) (vanillaSkolemTv skol_info) - in (extendTvSubstWithClone subst tv tv', (tyVarName tv, tv')) - +tcExtendTyVarEnv :: [TyVar] -> TcM r -> TcM r +tcExtendTyVarEnv tvs thing_inside + = tcExtendNameTyVarEnv (mkTyVarNamePairs tvs) thing_inside tcExtendNameTyVarEnv :: [(Name,TcTyVar)] -> TcM r -> TcM r tcExtendNameTyVarEnv binds thing_inside @@ -753,7 +746,7 @@ tcInitTidyEnv = do { let (env', occ') = tidyOccName env (nameOccName name) name' = tidyNameOcc name occ' tyvar1 = setTyVarName tyvar name' - ; tyvar2 <- zonkTcTyVarToTyVar tyvar1 + ; tyvar2 <- zonkTcTyVarToTcTyVar tyvar1 -- Be sure to zonk here! Tidying applies to zonked -- types, so if we don't zonk we may create an -- ill-kinded type (#14175) diff --git a/compiler/GHC/Tc/Utils/TcMType.hs b/compiler/GHC/Tc/Utils/TcMType.hs index 3e0ff7adb5..6dfcb89b09 100644 --- a/compiler/GHC/Tc/Utils/TcMType.hs +++ b/compiler/GHC/Tc/Utils/TcMType.hs @@ -70,7 +70,7 @@ module GHC.Tc.Utils.TcMType ( zonkTidyTcType, zonkTidyTcTypes, zonkTidyOrigin, zonkTidyOrigins, tidyEvVar, tidyCt, tidyHole, tidySkolemInfo, tidySkolemInfoAnon, zonkTcTyVar, zonkTcTyVars, - zonkTcTyVarToTyVar, zonkInvisTVBinder, + zonkTcTyVarToTcTyVar, zonkInvisTVBinder, zonkTyCoVarsAndFV, zonkTcTypeAndFV, zonkDTyCoVarSetAndFV, zonkTyCoVarsAndFVList, @@ -1767,7 +1767,7 @@ zonkAndSkolemise skol_info tyvar -- We want to preserve the binding location of the original TyVarTv. -- This is important for error messages. If we don't do this, then -- we get bad locations in, e.g., typecheck/should_fail/T2688 - = do { zonked_tyvar <- zonkTcTyVarToTyVar tyvar + = do { zonked_tyvar <- zonkTcTyVarToTcTyVar tyvar ; skolemiseQuantifiedTyVar skol_info zonked_tyvar } | otherwise @@ -2498,22 +2498,21 @@ zonkTcTyVar tv = zonk_kind_and_return where zonk_kind_and_return = do { z_tv <- zonkTyCoVarKind tv - ; return (mkTyVarTy z_tv) - } + ; return (mkTyVarTy z_tv) } -- Variant that assumes that any result of zonking is still a TyVar. -- Should be used only on skolems and TyVarTvs -zonkTcTyVarToTyVar :: HasDebugCallStack => TcTyVar -> TcM TcTyVar -zonkTcTyVarToTyVar tv +zonkTcTyVarToTcTyVar :: HasDebugCallStack => TcTyVar -> TcM TcTyVar +zonkTcTyVarToTcTyVar tv = do { ty <- zonkTcTyVar tv ; let tv' = case tcGetTyVar_maybe ty of Just tv' -> tv' - Nothing -> pprPanic "zonkTcTyVarToTyVar" + Nothing -> pprPanic "zonkTcTyVarToTcTyVar" (ppr tv $$ ppr ty) ; return tv' } -zonkInvisTVBinder :: VarBndr TcTyVar spec -> TcM (VarBndr TyVar spec) -zonkInvisTVBinder (Bndr tv spec) = do { tv' <- zonkTcTyVarToTyVar tv +zonkInvisTVBinder :: VarBndr TcTyVar spec -> TcM (VarBndr TcTyVar spec) +zonkInvisTVBinder (Bndr tv spec) = do { tv' <- zonkTcTyVarToTcTyVar tv ; return (Bndr tv' spec) } -- zonkId is used *during* typechecking just to zonk the Id's type @@ -2703,7 +2702,7 @@ naughtyQuantification :: TcType -- original type user wanted to quantify naughtyQuantification orig_ty tv escapees = do { orig_ty1 <- zonkTcType orig_ty -- in case it's not zonked - ; escapees' <- mapM zonkTcTyVarToTyVar $ + ; escapees' <- mapM zonkTcTyVarToTcTyVar $ nonDetEltsUniqSet escapees -- we'll just be printing, so no harmful non-determinism diff --git a/compiler/GHC/Tc/Utils/TcType.hs b/compiler/GHC/Tc/Utils/TcType.hs index 569a7b8363..346a9f8396 100644 --- a/compiler/GHC/Tc/Utils/TcType.hs +++ b/compiler/GHC/Tc/Utils/TcType.hs @@ -25,7 +25,7 @@ module GHC.Tc.Utils.TcType ( TcType, TcSigmaType, TcRhoType, TcTauType, TcPredType, TcThetaType, TcTyVar, TcTyVarSet, TcDTyVarSet, TcTyCoVarSet, TcDTyCoVarSet, TcKind, TcCoVar, TcTyCoVar, TcTyVarBinder, TcInvisTVBinder, TcReqTVBinder, - TcTyCon, KnotTied, + TcTyCon, MonoTcTyCon, PolyTcTyCon, KnotTied, ExpType(..), InferResult(..), ExpSigmaType, ExpRhoType, mkCheckExpType, @@ -343,7 +343,11 @@ type TcTyCoVar = Var -- Either a TcTyVar or a CoVar type TcTyVarBinder = TyVarBinder type TcInvisTVBinder = InvisTVBinder type TcReqTVBinder = ReqTVBinder -type TcTyCon = TyCon -- these can be the TcTyCon constructor + +-- See Note [TcTyCon, MonoTcTyCon, and PolyTcTyCon] +type TcTyCon = TyCon +type MonoTcTyCon = TcTyCon +type PolyTcTyCon = TcTyCon -- These types do not have boxy type variables in them type TcPredType = PredType @@ -357,6 +361,24 @@ type TcTyCoVarSet = TyCoVarSet type TcDTyVarSet = DTyVarSet type TcDTyCoVarSet = DTyCoVarSet +{- Note [TcTyCon, MonoTcTyCon, and PolyTcTyCon] +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +See Note [How TcTyCons work] in GHC.Tc.TyCl + +Invariants: +* TcTyCon: a TyCon built with the TcTyCon constructor + +* MonoTcTyCon: + - tyConBinders and tyConResultKind use TcTyVars + - their kinds may mention unification variables + +* PolyTcTyCon: + - tyConBinders and tyConResultKind use completely-final TyVars + No unification variables here + - The range of the tcTyConScopedTyVars are all /skolem/ TcTyVars, + not meta TyVarTvs +-} + {- ********************************************************************* * * ExpType: an "expected type" in the type checker diff --git a/compiler/GHC/Tc/Utils/Unify.hs b/compiler/GHC/Tc/Utils/Unify.hs index 9e822da9b6..e475c697d5 100644 --- a/compiler/GHC/Tc/Utils/Unify.hs +++ b/compiler/GHC/Tc/Utils/Unify.hs @@ -943,22 +943,23 @@ emitResidualTvConstraint :: SkolemInfo -> [TcTyVar] -> TcLevel -> WantedConstraints -> TcM () emitResidualTvConstraint skol_info skol_tvs tclvl wanted | not (isEmptyWC wanted) || - checkTelescopeSkol (getSkolemInfo skol_info) + checkTelescopeSkol skol_info_anon = -- checkTelescopeSkol: in this case, /always/ emit this implication -- even if 'wanted' is empty. We need the implication so that we check -- for a bad telescope. See Note [Skolem escape and forall-types] in -- GHC.Tc.Gen.HsType - do { implic <- buildTvImplication skol_info skol_tvs tclvl wanted + do { implic <- buildTvImplication skol_info_anon skol_tvs tclvl wanted ; emitImplication implic } | otherwise -- Empty 'wanted', emit nothing = return () + where + skol_info_anon = getSkolemInfo skol_info -buildTvImplication :: SkolemInfo -> [TcTyVar] +buildTvImplication :: SkolemInfoAnon -> [TcTyVar] -> TcLevel -> WantedConstraints -> TcM Implication buildTvImplication skol_info skol_tvs tclvl wanted - = - assertPpr (all (isSkolemTyVar <||> isTyVarTyVar) skol_tvs) (ppr skol_tvs) $ + = assertPpr (all (isSkolemTyVar <||> isTyVarTyVar) skol_tvs) (ppr skol_tvs) $ do { ev_binds <- newNoTcEvBinds -- Used for equalities only, so all the constraints -- are solved by filling in coercion holes, not -- by creating a value-level evidence binding @@ -969,7 +970,7 @@ buildTvImplication skol_info skol_tvs tclvl wanted , ic_given_eqs = NoGivenEqs , ic_wanted = wanted , ic_binds = ev_binds - , ic_info = getSkolemInfo skol_info }) } + , ic_info = skol_info }) } implicationNeeded :: SkolemInfoAnon -> [TcTyVar] -> [EvVar] -> TcM Bool -- See Note [When to build an implication] diff --git a/compiler/GHC/Tc/Utils/Zonk.hs b/compiler/GHC/Tc/Utils/Zonk.hs index fec8d90d5d..bbb6aaf38b 100644 --- a/compiler/GHC/Tc/Utils/Zonk.hs +++ b/compiler/GHC/Tc/Utils/Zonk.hs @@ -1775,7 +1775,7 @@ change. But in some cases it makes a HUGE difference: see test T9198 and #19668. So yes, it seems worth it. -} -zonkTyVarOcc :: ZonkEnv -> TyVar -> TcM TcType +zonkTyVarOcc :: ZonkEnv -> TcTyVar -> TcM Type zonkTyVarOcc env@(ZonkEnv { ze_flexi = flexi , ze_tv_env = tv_env , ze_meta_tv_env = mtv_env_ref }) tv @@ -1790,13 +1790,16 @@ zonkTyVarOcc env@(ZonkEnv { ze_flexi = flexi Just ty -> return ty Nothing -> do { mtv_details <- readTcRef ref ; zonk_meta ref mtv_details } } - | otherwise + | otherwise -- This should never really happen; + -- TyVars should not occur in the typechecker = lookup_in_tv_env where lookup_in_tv_env -- Look up in the env just as we do for Ids = case lookupVarEnv tv_env tv of - Nothing -> mkTyVarTy <$> updateTyVarKindM (zonkTcTypeToTypeX env) tv + Nothing -> -- A skolem TcTyVar that isn't in the ZonkEnv + do { kind <- zonkTcTypeToTypeX env (tyVarKind tv) + ; return (mkTyVarTy (mkTyVar (tyVarName tv) kind)) } Just tv' -> return (mkTyVarTy tv') zonk_meta ref Flexi diff --git a/testsuite/tests/saks/should_fail/T16758.stderr b/testsuite/tests/saks/should_fail/T16758.stderr index f74241a706..066a4f106a 100644 --- a/testsuite/tests/saks/should_fail/T16758.stderr +++ b/testsuite/tests/saks/should_fail/T16758.stderr @@ -3,6 +3,6 @@ T16758.hs:14:8: error: • Couldn't match expected kind ‘Int’ with actual kind ‘a’ ‘a’ is a rigid type variable bound by the class declaration for ‘C’ - at T16758.hs:12:19 + at T16758.hs:13:9 • In the type signature: f :: C a => a -> Int In the class declaration for ‘C’ diff --git a/testsuite/tests/saks/should_fail/all.T b/testsuite/tests/saks/should_fail/all.T index 7e2194a21f..093e48133e 100644 --- a/testsuite/tests/saks/should_fail/all.T +++ b/testsuite/tests/saks/should_fail/all.T @@ -24,6 +24,7 @@ test('saks_fail022', normal, compile_fail, ['']) test('saks_fail023', normal, compile_fail, ['']) test('saks_fail024', normal, compile_fail, ['']) test('saks_fail025', normal, compile_fail, ['']) +test('saks_fail026', normal, compile_fail, ['']) test('T16722', normal, compile_fail, ['']) test('T16727a', normal, compile_fail, ['']) test('T16727b', normal, compile_fail, ['']) diff --git a/testsuite/tests/saks/should_fail/saks_fail009.hs b/testsuite/tests/saks/should_fail/saks_fail009.hs index 317c0e7644..21394ada56 100644 --- a/testsuite/tests/saks/should_fail/saks_fail009.hs +++ b/testsuite/tests/saks/should_fail/saks_fail009.hs @@ -5,5 +5,5 @@ module SAKS_Fail009 where import Data.Kind (Type) -type T :: forall k -> k -> Type +type T :: forall j -> j -> Type data T (k :: Type -> Type) (a :: k) diff --git a/testsuite/tests/saks/should_fail/saks_fail009.stderr b/testsuite/tests/saks/should_fail/saks_fail009.stderr index 8ce43f6d5d..22b66b421b 100644 --- a/testsuite/tests/saks/should_fail/saks_fail009.stderr +++ b/testsuite/tests/saks/should_fail/saks_fail009.stderr @@ -1,4 +1,5 @@ saks_fail009.hs:9:1: error: - • Expected kind ‘* -> *’, but ‘k’ has kind ‘*’ + • Expecting one more argument to ‘k’ + Expected a type, but ‘k’ has kind ‘* -> *’ • In the data type declaration for ‘T’ diff --git a/testsuite/tests/saks/should_fail/saks_fail019.hs b/testsuite/tests/saks/should_fail/saks_fail019.hs index 51cdd54ca2..ddd20d099c 100644 --- a/testsuite/tests/saks/should_fail/saks_fail019.hs +++ b/testsuite/tests/saks/should_fail/saks_fail019.hs @@ -6,6 +6,6 @@ module SAKS_Fail019 where import Data.Kind (Type) type T :: Type -> Type -> Type -data T a :: a -> Type +data T x :: x -> Type -- Should not panic with: - -- GHC internal error: ‘a’ is not in scope during type checking, but it passed the renamer + -- GHC internal error: ‘x’ is not in scope during type checking, but it passed the renamer diff --git a/testsuite/tests/saks/should_fail/saks_fail019.stderr b/testsuite/tests/saks/should_fail/saks_fail019.stderr index b34a7e1905..a824ab118c 100644 --- a/testsuite/tests/saks/should_fail/saks_fail019.stderr +++ b/testsuite/tests/saks/should_fail/saks_fail019.stderr @@ -1,9 +1,9 @@ saks_fail019.hs:9:1: error: - • Couldn't match kind ‘a’ with ‘*’ - Expected: a -> * + • Couldn't match kind ‘x’ with ‘*’ + Expected: x -> * Actual: * -> * - ‘a’ is a rigid type variable bound by + ‘x’ is a rigid type variable bound by the data type declaration for ‘T’ at saks_fail019.hs:9:8 • In the data type declaration for ‘T’ diff --git a/testsuite/tests/saks/should_fail/saks_fail021.stderr b/testsuite/tests/saks/should_fail/saks_fail021.stderr index 6128aff165..fa20ccc826 100644 --- a/testsuite/tests/saks/should_fail/saks_fail021.stderr +++ b/testsuite/tests/saks/should_fail/saks_fail021.stderr @@ -1,4 +1,4 @@ saks_fail021.hs:10:1: error: - • Expected kind ‘k’, but ‘a’ has kind ‘*’ + • Expected a type, but ‘a’ has kind ‘k’ • In the class declaration for ‘C’ diff --git a/testsuite/tests/saks/should_fail/saks_fail022.stderr b/testsuite/tests/saks/should_fail/saks_fail022.stderr index e0cc222344..0591eced95 100644 --- a/testsuite/tests/saks/should_fail/saks_fail022.stderr +++ b/testsuite/tests/saks/should_fail/saks_fail022.stderr @@ -1,4 +1,4 @@ saks_fail022.hs:10:1: error: - • Expected kind ‘k’, but ‘a’ has kind ‘(x, y)’ + • Expected kind ‘(x, y)’, but ‘a’ has kind ‘k’ • In the class declaration for ‘C’ diff --git a/testsuite/tests/saks/should_fail/saks_fail023.stderr b/testsuite/tests/saks/should_fail/saks_fail023.stderr index 3af24c7abb..36144f6d9d 100644 --- a/testsuite/tests/saks/should_fail/saks_fail023.stderr +++ b/testsuite/tests/saks/should_fail/saks_fail023.stderr @@ -1,4 +1,4 @@ saks_fail023.hs:10:1: error: - • Expected kind ‘k’, but ‘a’ has kind ‘*’ + • Expected a type, but ‘a’ has kind ‘k’ • In the class declaration for ‘C’ diff --git a/testsuite/tests/saks/should_fail/saks_fail026.hs b/testsuite/tests/saks/should_fail/saks_fail026.hs new file mode 100644 index 0000000000..1d47a06d6e --- /dev/null +++ b/testsuite/tests/saks/should_fail/saks_fail026.hs @@ -0,0 +1,8 @@ +{-# LANGUAGE TypeFamilies #-} + +module SAKS_Fail026 where + +import Data.Kind (Type) + +type F3 :: forall kx. kx -> Type +type family F3 (b :: Type) where diff --git a/testsuite/tests/saks/should_fail/saks_fail026.stderr b/testsuite/tests/saks/should_fail/saks_fail026.stderr new file mode 100644 index 0000000000..ceeeaa01c7 --- /dev/null +++ b/testsuite/tests/saks/should_fail/saks_fail026.stderr @@ -0,0 +1,7 @@ + +saks_fail026.hs:8:1: error: + • Expected kind ‘kx’, but ‘b’ has kind ‘*’ + ‘kx’ is a rigid type variable bound by + the type family declaration for ‘F3’ + at saks_fail026.hs:7:19-20 + • In the type family declaration for ‘F3’ |
