Simon Peyton Jones pushed to branch wip/T27994 at Glasgow Haskell Compiler / GHC

Commits:

7 changed files:

Changes:

  • compiler/GHC/Core/Coercion/Axiom.hs
    ... ... @@ -277,8 +277,8 @@ data CoAxBranch
    277 277
            -- See Note [CoAxBranch type variables]
    
    278 278
         , cab_eta_tvs  :: [TyVar]
    
    279 279
            -- ^ Eta-reduced tyvars
    
    280
    -       -- cab_tvs and cab_lhs may be eta-reduced; see
    
    281
    -       -- Note [Eta reduction for data families]
    
    280
    +       -- For a data family (only) cab_tvs and cab_lhs may be eta-reduced
    
    281
    +       -- See Note [Eta reduction for data families]
    
    282 282
         , cab_cvs      :: [CoVar]
    
    283 283
           -- ^ Bound coercion variables
    
    284 284
            -- Always empty, for now.
    
    ... ... @@ -286,8 +286,14 @@ data CoAxBranch
    286 286
            -- in GHC.Tc.TyCl
    
    287 287
         , cab_roles    :: [Role]
    
    288 288
            -- ^ See Note [CoAxBranch roles]
    
    289
    +
    
    289 290
         , cab_lhs      :: [Type]
    
    290 291
            -- ^ Type patterns to match against
    
    292
    +       -- For a data family `cab_lhs` may be shorter than the arity
    
    293
    +       --     of the data type
    
    294
    +       -- For a type family `cab_lhs` is exactly the family arity
    
    295
    +       -- See Note [Eta reduction for data families]
    
    296
    +
    
    291 297
         , cab_rhs      :: Type
    
    292 298
            -- ^ Right-hand side of the equality
    
    293 299
            -- See Note [CoAxioms are homogeneous]
    

  • compiler/GHC/Core/Predicate.hs
    ... ... @@ -36,7 +36,7 @@ module GHC.Core.Predicate (
    36 36
     
    
    37 37
       -- Equality left-hand sides
    
    38 38
       CanEqLHS(..), canEqLHS_maybe, canTyFamEqLHS_maybe,
    
    39
    -  canEqLHSKind, canEqLHSType, eqCanEqLHS
    
    39
    +  canEqLHSKind, canEqLHSType, eqCanEqLHS, saturatedFamApp_maybe
    
    40 40
     
    
    41 41
       ) where
    
    42 42
     
    
    ... ... @@ -61,6 +61,8 @@ import GHC.Utils.Misc
    61 61
     import GHC.Utils.Panic
    
    62 62
     import GHC.Data.FastString
    
    63 63
     
    
    64
    +import GHC.Exts( inline )
    
    65
    +
    
    64 66
     
    
    65 67
     {- *********************************************************************
    
    66 68
     *                                                                      *
    
    ... ... @@ -700,7 +702,9 @@ types/kinds are fully settled and zonked.
    700 702
     -- See also Note [Ordering of implicit variables] in "GHC.Rename.HsType"
    
    701 703
     
    
    702 704
     scopedSort :: [Var] -> [Var]
    
    703
    -scopedSort = go [] []
    
    705
    +scopedSort xs
    
    706
    +  | null xs   = []
    
    707
    +  | otherwise = go [] [] xs
    
    704 708
       where
    
    705 709
         go :: [Var] -- already sorted, in reverse order
    
    706 710
            -> [TyCoVarSet] -- each set contains all the variables which must be placed
    
    ... ... @@ -781,13 +785,19 @@ canEqLHS_maybe xi
    781 785
       | otherwise
    
    782 786
       = canTyFamEqLHS_maybe xi
    
    783 787
     
    
    784
    -canTyFamEqLHS_maybe :: Type -> Maybe CanEqLHS
    
    785
    -canTyFamEqLHS_maybe xi
    
    788
    +saturatedFamApp_maybe :: Type -> Maybe (TyCon,[Type])
    
    789
    +saturatedFamApp_maybe xi
    
    786 790
       | Just (tc, args) <- tcSplitTyConApp_maybe xi
    
    787 791
       , isTypeFamilyTyCon tc
    
    788 792
       , args `lengthIs` tyConArity tc
    
    789
    -  = Just $ TyFamLHS tc args
    
    793
    +  = Just (tc,args)
    
    794
    +  | otherwise
    
    795
    +  = Nothing
    
    790 796
     
    
    797
    +canTyFamEqLHS_maybe :: Type -> Maybe CanEqLHS
    
    798
    +canTyFamEqLHS_maybe xi
    
    799
    +  | Just (tc, args) <- inline saturatedFamApp_maybe xi
    
    800
    +  = Just $ TyFamLHS tc args
    
    791 801
       | otherwise
    
    792 802
       = Nothing
    
    793 803
     
    

  • compiler/GHC/Tc/Instance/Family.hs
    ... ... @@ -16,6 +16,7 @@ import GHC.Prelude
    16 16
     import GHC.Driver.DynFlags
    
    17 17
     import GHC.Driver.Env
    
    18 18
     
    
    19
    +import GHC.Core.Predicate( saturatedFamApp_maybe )
    
    19 20
     import GHC.Core.FamInstEnv
    
    20 21
     import GHC.Core.Coercion
    
    21 22
     import GHC.Core.TyCon
    
    ... ... @@ -715,15 +716,9 @@ reportInjectivityErrors dflags fi_ax axiom inj
    715 716
            when wrong_bare_rhs $ reportBareVariableInRHSErr   fam_tc bare_variables axiom
    
    716 717
     
    
    717 718
     -- | Is type headed by a type family application?
    
    718
    -isTFHeaded :: Type -> Bool
    
    719 719
     -- See Note [Verifying injectivity annotation], case 3.
    
    720
    -isTFHeaded ty | Just ty' <- coreView ty
    
    721
    -              = isTFHeaded ty'
    
    722
    -isTFHeaded ty | (TyConApp tc args) <- ty
    
    723
    -              , isTypeFamilyTyCon tc
    
    724
    -              = args `lengthIs` tyConArity tc
    
    725
    -isTFHeaded _  = False
    
    726
    -
    
    720
    +isTFHeaded :: Type -> Bool
    
    721
    +isTFHeaded ty = isJust (saturatedFamApp_maybe ty)
    
    727 722
     
    
    728 723
     -- | If a RHS is a bare type variable return a set of LHS patterns that are not
    
    729 724
     -- bare type variables.
    

  • compiler/GHC/Tc/Solver/FunDeps.hs
    ... ... @@ -24,16 +24,16 @@ import GHC.Tc.Types.Constraint
    24 24
     import GHC.Core.FamInstEnv
    
    25 25
     import GHC.Core.Coercion
    
    26 26
     import GHC.Core.TyCo.Rep( Type(..) )
    
    27
    -import GHC.Core.Predicate( EqRel(..) )
    
    27
    +import GHC.Core.TyCo.Subst( deepSubstTy, elemSubst )
    
    28
    +import GHC.Core.Predicate( EqRel(..), saturatedFamApp_maybe )
    
    28 29
     import GHC.Core.TyCon
    
    29 30
     import GHC.Core.Unify( AmIUnifying(..)
    
    30 31
                          , tcUnifyTysForInjectivity, typeListsAreApart )
    
    31 32
     import GHC.Core.Coercion.Axiom
    
    32
    -import GHC.Core.TyCo.Subst( elemSubst, extendTvSubstWithClone )
    
    33 33
     
    
    34 34
     import GHC.Builtin.WiredIn.TypeLits( tryInteractTopFam, tryInteractInertFam )
    
    35 35
     
    
    36
    -import GHC.Types.Var( TyVar, tyVarKind, setTyVarKind )
    
    36
    +import GHC.Types.Var( tyVarKind )
    
    37 37
     import GHC.Types.Var.Set
    
    38 38
     import GHC.Types.Var.Env( mkInScopeSet )
    
    39 39
     
    
    ... ... @@ -57,7 +57,6 @@ Here is our plan for dealing with functional dependencies
    57 57
            * send the current constraint back to the start of the pipeline;
    
    58 58
              it might now be soluble, and it probably isn't inert
    
    59 59
     
    
    60
    -
    
    61 60
     * Once a unification is done, it can't be un-done.  So we must be very careful
    
    62 61
       not to threaten completeness by doing a unification when there might be
    
    63 62
       another way to solve the constraint.
    
    ... ... @@ -613,6 +612,7 @@ tryFamEqFunDeps mode eqs_for_me fam_tc work_args
    613 612
     
    
    614 613
     mkTopFamEqFDs :: TyCon -> [TcType] -> EqCt -> SolverStage [FunDepEqns]
    
    615 614
     mkTopFamEqFDs fam_tc work_args work_item
    
    615
    +  -- NB: work_args exactly saturate fam_tc
    
    616 616
       | isOpenTypeFamilyTyCon fam_tc
    
    617 617
       , Injective inj_flags <- tyConInjectivityInfo fam_tc
    
    618 618
       = -- Open, injective type families
    
    ... ... @@ -709,24 +709,24 @@ getRelevantBranches ax work_args work_rhs
    709 709
                                             , cab_lhs = lhs_tys
    
    710 710
                                             , cab_rhs = rhs_ty })
    
    711 711
                 | Just subst <- tcUnifyTysForInjectivity Unifying (rhs_ty:lhs_tys) work_tys
    
    712
    -              -- See (RW1)-(RW3) in Note [Relevance]
    
    713
    -              -- This is a pre-/unification/ check (not matching)
    
    714
    -              -- so `subst` can bind both `qtvs` and fvs(work_tys)
    
    715
    -            , let (subst',qtvs') = trim_qtvs subst qtvs
    
    716
    -                  lhs_tys'       = substTys subst' lhs_tys
    
    717
    -                  rhs_ty'        = substTy  subst' rhs_ty
    
    718
    -                  branch_tys'    = rhs_ty' : lhs_tys'
    
    712
    +                            -- See (RW1)-(RW3) in Note [Relevance]
    
    713
    +            , let lhs_tys' = map (deepSubstTy subst) lhs_tys
    
    714
    +                  -- deepSubstTy: see (CF8) in Note [Exploiting closed type families]
    
    719 715
                 , noEarlierMatchCheck lhs_tys' branch  -- See (RW4) in Note [Relevance]
    
    720
    -            = Just (FDEqns { fd_qtvs = qtvs'
    
    721
    -                           , fd_eqs  = zipWith Pair branch_tys' work_tys })
    
    722
    -                              -- Do not apply the substition to `work_tys`;
    
    723
    -                              -- See (CF7) in Note [Exploiting closed type families]
    
    716
    +            = -- Ignore the substitution, except for `noEarlierMatchCheck`
    
    717
    +              -- See (CF7) in Note [Exploiting closed type families]
    
    718
    +                Just (FDEqns { fd_qtvs = qtvs
    
    719
    +                           , fd_eqs  = zipWith Pair (rhs_ty:lhs_tys) work_tys })
    
    720
    +              -- Do not apply the substitution to `work_tys`;
    
    721
    +              -- See (CF9) in Note [Exploiting closed type families]
    
    722
    +
    
    724 723
                 | otherwise
    
    725 724
                 = Nothing
    
    726 725
     
    
    727 726
     mkTopOpenFamEqFDs :: TyCon -> [Bool] -> [TcType] -> EqCt -> TcS [FunDepEqns]
    
    728 727
     -- Implements (INJFAM:Wanted/top-open)
    
    729 728
     -- See Note [Exploiting open type families]
    
    729
    +-- NB: work_args exactly saturate fam_tc
    
    730 730
     mkTopOpenFamEqFDs fam_tc inj_flags work_args (EqCt { eq_rhs = work_rhs })
    
    731 731
       = do { fam_envs <- getFamInstEnvs
    
    732 732
            ; let branches :: [CoAxBranch]
    
    ... ... @@ -739,11 +739,17 @@ mkTopOpenFamEqFDs fam_tc inj_flags work_args (EqCt { eq_rhs = work_rhs })
    739 739
                            , cab_lhs = branch_lhs_tys
    
    740 740
                            , cab_rhs = branch_rhs })
    
    741 741
           | Just subst <- tcUnifyTysForInjectivity Matching [branch_rhs] [work_rhs]
    
    742
    -      , let (subst', qtvs') = trim_qtvs subst branch_qtvs
    
    743
    -            branch_lhs_tys' = substTys subst' branch_lhs_tys
    
    744
    -        -- No need for an apartness check here; for open type families
    
    745
    -        -- there are no "preceding" equations
    
    746
    -      = Just (mkInjectivityFDEqn inj_flags qtvs' branch_lhs_tys' work_args)
    
    742
    +        -- No need for an apartness check here;
    
    743
    +        -- for open type families there are no "preceding" equations
    
    744
    +        -- Both branch_lhs_tys and work_args exactly saturate fam_tc
    
    745
    +      = Just $
    
    746
    +        if all (`elemSubst` subst) branch_qtvs -- See (OTF1)
    
    747
    +        then mkInjectivityFDEqn []          inj_flags
    
    748
    +                                            (substTys subst branch_lhs_tys)
    
    749
    +                                            work_args
    
    750
    +        else mkInjectivityFDEqn branch_qtvs (True:       inj_flags)
    
    751
    +                                            (branch_rhs: branch_lhs_tys)
    
    752
    +                                            (work_rhs:   work_args)
    
    747 753
     
    
    748 754
           | otherwise
    
    749 755
           = Nothing
    
    ... ... @@ -756,9 +762,9 @@ mkLocalFamEqFDs eqs_for_me fam_tc inj_flags work_args work_rhs
    756 762
       = do { let -- eqns_from_inerts: see (INJFAM:Wanted/other)
    
    757 763
                  eqns_from_inerts = mapMaybe do_one eqs_for_me
    
    758 764
                  -- eqns_from_self: see (INJFAM:Wanted/Self)
    
    759
    -             eqns_from_self   = case tcSplitTyConApp_maybe work_rhs of
    
    760
    -                                  Just (tc,rhs_tys) | tc==fam_tc -> [mk_eqn rhs_tys]
    
    761
    -                                  _                              -> []
    
    765
    +             eqns_from_self = case saturatedFamApp_maybe work_rhs of
    
    766
    +                                Just (tc, rhs_tys) | fam_tc == tc -> [mk_eqn rhs_tys]
    
    767
    +                                _                                 -> []
    
    762 768
     
    
    763 769
            ; return (eqns_from_inerts ++ eqns_from_self) }
    
    764 770
       where
    
    ... ... @@ -768,7 +774,10 @@ mkLocalFamEqFDs eqs_for_me fam_tc inj_flags work_args work_rhs
    768 774
           | otherwise                     = Nothing
    
    769 775
         do_one _ = pprPanic "interactFunEq 2" (ppr fam_tc)  -- TyVarLHS
    
    770 776
     
    
    771
    -    mk_eqn iargs = mkInjectivityFDEqn inj_flags [] work_args iargs
    
    777
    +    mk_eqn iargs = mkInjectivityFDEqn [] inj_flags work_args iargs
    
    778
    +
    
    779
    +
    
    780
    +{- See Historical Note [trim_qtvs]
    
    772 781
     
    
    773 782
     trim_qtvs :: Subst -> [TyVar] -> (Subst, [TyVar])
    
    774 783
     -- Tricky stuff: see (OF1) in Note [Exploiting open type families]
    
    ... ... @@ -790,7 +799,7 @@ trim_qtvs unif_subst qtvs
    790 799
             subst' = extendTvSubstWithClone subst tv tv'
    
    791 800
                      -- extendTvSubstWithClone: see (OF1b) in
    
    792 801
                      -- Note [Exploiting open type families]
    
    793
    -
    
    802
    +-}
    
    794 803
     
    
    795 804
     -----------------------------------------
    
    796 805
     --  Built-in type families
    
    ... ... @@ -883,15 +892,22 @@ mkLocalBuiltinFamEqFDs eqs_for_me fam_tc ops work_args work_rhs
    883 892
            ; return (eqns_from_inerts ++ eqns_from_self) }
    
    884 893
     
    
    885 894
     --------------------
    
    886
    -mkInjectivityFDEqn :: [Bool]       -- Injectivity flags
    
    887
    -                   -> [TcTyVar]    -- Quantify these
    
    895
    +mkInjectivityFDEqn :: [TcTyVar]             -- Quantify these
    
    896
    +                   -> [Bool]                -- Injectivity flags
    
    888 897
                        -> [TcType] -> [TcType]  -- Make these equal
    
    889 898
                        -> FunDepEqns
    
    890 899
     -- When F s1 s2 s3 ~ F t1 t2 t3, and F has injectivity info [True,False,True]
    
    891 900
     --   return the FDEqns { fd_eqs = [Pair s1 t1, Pair s3 t3] }
    
    892
    --- The injectivity flags [Bool] will not all be False, but nothing goes wrong if they are
    
    893
    -mkInjectivityFDEqn inj_args qtvs lhs_args rhs_args
    
    894
    -  = FDEqns { fd_qtvs = qtvs, fd_eqs = eqs }
    
    901
    +-- The injectivity flags [Bool] will not all be False,
    
    902
    +--   but nothing goes wrong if they are
    
    903
    +mkInjectivityFDEqn qtvs inj_args lhs_args rhs_args
    
    904
    +  = assertPpr (let len = length inj_args in
    
    905
    +               len == length lhs_args && len == length rhs_args)
    
    906
    +              (vcat [ text "inj_args:" <+> ppr inj_args
    
    907
    +                    , text "lhs_args:" <+> ppr lhs_args
    
    908
    +                    , text "rhs_args:" <+> ppr rhs_args ]) $
    
    909
    +    -- Need inj_args lhs_args and rhs_args to be same length for zip3
    
    910
    +    FDEqns { fd_qtvs = qtvs, fd_eqs = eqs }
    
    895 911
       where
    
    896 912
         eqs = [ Pair lhs_arg rhs_arg
    
    897 913
               | (True, lhs_arg, rhs_arg) <- zip3 inj_args lhs_args rhs_args ]
    
    ... ... @@ -1104,7 +1120,7 @@ the Injective Type Families paper. For open type families, suppose we have
    1104 1120
     
    
    1105 1121
        [W] F alpha ~ Int->Int
    
    1106 1122
     
    
    1107
    -Then, since F has been checked as injective, and the RHS `a->a` (pre-)unifies
    
    1123
    +Then, since F has been checked as injective, and the RHS `a->a` (pre-)matches
    
    1108 1124
     with the `Int->Int` in the Wanted with substitution [a :-> Int], we can
    
    1109 1125
     add a derived FunDepEqns
    
    1110 1126
        FDEqns{ fd_qtvs = [], fd_eqs = [ [Int] ~ alpha ] }
    
    ... ... @@ -1119,7 +1135,7 @@ instance are bound by the pre-unification step. Suppose we have
    1119 1135
     
    
    1120 1136
        [W] F alpha ~ [ty]
    
    1121 1137
     
    
    1122
    -Then, the RHS [G a] pre-unifies with the RHS of the Wanted, but with an
    
    1138
    +Then, the RHS [G a] pre-matches with the RHS of the Wanted, but with an
    
    1123 1139
     empty substitution, which does not fix `a`.  So we get this FunDepEqns:
    
    1124 1140
        FDEqns{ fd_qtvs = a, fd_eqs = [ Maybe a ~ alpha ] }
    
    1125 1141
     (note the fd_qtvs=a) and thereby emit (via `instantiateFunDepEqns`)
    
    ... ... @@ -1127,42 +1143,65 @@ empty substitution, which does not fix `a`. So we get this FunDepEqns:
    1127 1143
     We have learned that `alpha` must be a list, but that is all; we don't
    
    1128 1144
     know what is inside it, hence the fresh `gamma`.
    
    1129 1145
     
    
    1130
    -In general we have:
    
    1131
    -
    
    1132
    -  type family F x1 ... xn = r | r -> x1 x3     (say)
    
    1133
    -  type instance forall qs. F t1 ... tn = rhs
    
    1134
    -  [W] F a1 ... an ~ b
    
    1135
    -
    
    1136
    -Suppose `b` pre-unifies with `rhs`, with substitution `S` that binds
    
    1137
    -some (but perhaps not all) of the `qs`.  Lets say
    
    1138
    -   unbound_qs = qs \ dom(S)
    
    1139
    -
    
    1140
    -Then we generate the FunDepEqs
    
    1141
    -   FDEqns{ fd_qtvs = unbound_qs
    
    1142
    -         , fd_eqs = [ S(t1) ~ S(a1), S(t3) ~ S(a3) ]
    
    1143
    -
    
    1144
    -These 'fd_qtvs' are subsequently instantiated to fresh metavariables by
    
    1145
    -'instantiateFunDepEqns'.
    
    1146
    -
    
    1147
    -(OF1) The computation of `unbound_qs` is done by `trim_qtvs`, but we
    
    1148
    -   have to be careful.   Suppose (OF1a)
    
    1149
    -       qs = [ k::*, a::k ]
    
    1150
    -       S  = [ k :-> UnliftedType ]
    
    1151
    -   Then we want
    
    1152
    -       unbound_qs = [ a::UnliftedType ]    -- Must apply S to q's kind!!
    
    1153
    -
    
    1154
    -   And (OF1b), although I'm not sure if this can acutally happen:
    
    1155
    -        qs = [ k::*, a::(k::*), b::(a::k) ]
    
    1156
    -        S  = [ k :-> UnliftedType ]
    
    1157
    -   We want
    
    1158
    -        unbound_qs = [ a::UnliftedType, b::(a::UnliftedType) ]
    
    1159
    -   Note that the occurrence of `a` in b's kind should be replaced by the
    
    1160
    -   newly-kinded `a` not the original `a::k`.
    
    1161
    -
    
    1162
    -   This fancy footwork for `fd_qtvs` is done by `trim_qtvs`.  It
    
    1163
    -    * Drops a quantified tyvar that /is/ matched
    
    1164
    -    * Substitutes in the kind of a quantified tyvar `a` that is /not/ matched
    
    1165
    -    * Adds the substitution [a::k :-> a::S(k)] to the substitution
    
    1146
    +It gets tricker.  Suppose we have
    
    1147
    +   type family F @k a = r | r -> k,a
    
    1148
    +   type instance F @k (Proxy @k (a::k)) = T k
    
    1149
    +   [W] F alpha beta ~ T Type
    
    1150
    +Matching the RHS gives substitution [k :-> Type].   But we do /not/ want
    
    1151
    +to end up with this:
    
    1152
    +   FDEqns{ fd_qtvs = (a::k), fd_eqs = [ Proxy @Type (a::k) ~ alpha ] }
    
    1153
    +becuase that `k`, hidden inside the kind of `a`, escapes into the solver.
    
    1154
    +
    
    1155
    +Previously we tried fancy footwork -- see Historical Note [trim_qtvs].
    
    1156
    +But now we do the following, given
    
    1157
    +   type family F a b = r | r -> b
    
    1158
    +   type instance F lhs1 lhs2 = rhs
    
    1159
    +   [W] F wlhs1 wlhs2 ~ wrhs
    
    1160
    +
    
    1161
    +* We can safely abandon the sustitution entirely and generate
    
    1162
    +      FDEqns{ fd_qtvs = [a,b], fd_eqs = [ lhs2 ~ wlhs2, rhs ~ wrhs ] }
    
    1163
    +  By generating (rhs ~ wrhs) we effectively make the solver re-generate the
    
    1164
    +  substitution.  This is also what we do for closed type families; see (CF7).
    
    1165
    +  These 'fd_qtvs' are subsequently instantiated to fresh meta-variables by
    
    1166
    +  'instantiateFunDepEqns'.  See Historical Note [trim_qtvs].
    
    1167
    +
    
    1168
    +* As a fast-path optimisation, if the substitution (a /matching/ substition only,
    
    1169
    +  remember) covers all the `qtvs` of the type instance, there's no hidden-kind problem.
    
    1170
    +  Just apply the substitution and equate, with fd_qtvs = []:
    
    1171
    +      FDEqns{ fd_qtvs = [], fd_eqs = [ S(lhs2) ~ wlhs2 }
    
    1172
    +
    
    1173
    +Historical Note [trim_qtvs]
    
    1174
    +~~~~~~~~~~~~~~~~~~~~~~~~~~~
    
    1175
    +In Note [Exploiting open type families], we previously tried to make use of
    
    1176
    +the matching substitution `S`, by defining
    
    1177
    +     unbound_qs = qs \ dom(S)
    
    1178
    +so that we could make fresh meta-variables for only the unbound `qs`.
    
    1179
    +But it turned out to be tricky.  Suppose (TQ1)
    
    1180
    +    qs = [ k::*, a::k ]
    
    1181
    +    S  = [ k :-> UnliftedType ]
    
    1182
    +Then we want
    
    1183
    +    unbound_qs = [ a::UnliftedType ]    -- Must apply S to q's kind!!
    
    1184
    +
    
    1185
    +And (TQ2), although I'm not sure if this can actually happen:
    
    1186
    +     qs = [ k::*, a::(k::*), b::(a::k) ]
    
    1187
    +     S  = [ k :-> UnliftedType ]
    
    1188
    +We want
    
    1189
    +     unbound_qs = [ a::UnliftedType, b::(a::UnliftedType) ]
    
    1190
    +Note that the occurrence of `a` in b's kind should be replaced by the
    
    1191
    +newly-kinded `a` not the original `a::k`.
    
    1192
    +
    
    1193
    +This fancy footwork for `fd_qtvs` used to be done by `trim_qtvs`.  It
    
    1194
    + * Drops a quantified tyvar that /is/ matched
    
    1195
    + * Substitutes in the kind of a quantified tyvar `a` that is /not/ matched
    
    1196
    + * Adds the substitution [a::k :-> a::S(k)] to the substitution
    
    1197
    +
    
    1198
    +(TQ3) This was hard enough for open type type families, which use matching.
    
    1199
    +But it was ridiculously hard for /closed/ type families which use pre-/unification/
    
    1200
    +so that the substitution `S` has both meta-tyvars and instance-head tyvars in
    
    1201
    +the range.
    
    1202
    +
    
    1203
    +It's much easier to drop all this and just make fresh meta-tyvars for
    
    1204
    +all the quantified type variables.
    
    1166 1205
     
    
    1167 1206
     Note [Exploiting closed type families] see `mkTopClosedFamEqFDs`
    
    1168 1207
     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    
    ... ... @@ -1194,9 +1233,6 @@ More precisely, here is the very clever Closed Family Fundep Algorithm (CFFA)
    1194 1233
         with fresh unification vars in lhs and rhs for the quantified variables of the
    
    1195 1234
         equation.
    
    1196 1235
     
    
    1197
    -    Actually we take advantage of the substitution generated by the relevance
    
    1198
    -    check, see (CF7) below.
    
    1199
    -
    
    1200 1236
     See Note [Relevance] for what "relevant" means.
    
    1201 1237
     We need to take care about non-termination; see (CF3).
    
    1202 1238
     
    
    ... ... @@ -1391,26 +1427,59 @@ Key point: equations that are not relevant do not need to be considered for fund
    1391 1427
     (CF7) Relevance.  When computing relevance in the Closed Family Fundep Algorithm,
    
    1392 1428
       for [W] F wlhs1 wlhs2 ~ wrhs, against an equation   F lhs1 lhs2 ~ rhs
    
    1393 1429
       we get back a pre-unifying substitution S that makes the two as equal as poss.
    
    1394
    -  Then we use `trim_qtvs` in exactly the same way as in
    
    1395
    -       (OF1) of Note [Exploiting open type families], to generate qtvs' and S'
    
    1396
    -  Then we generate
    
    1397
    -      FDEqns { fd_qtvs = qtvs', fd_eqs [ S'(lhs1) ~ wlhs1
    
    1398
    -                                       , S'(lhs2) ~ wlhs2
    
    1399
    -                                       , S'(rhs)  ~ wrhs ] }
    
    1400
    -  Notice that we do /not/ apply S' to wlhs/wrhs.  These type contain unification
    
    1401
    -  variables that we must actually unify! Example
    
    1430
    +  This substitution can bind both /quantified/ type variables from the instance,
    
    1431
    +  and /unification variables/ from the solver. Moreover, both kind of type variable
    
    1432
    +  can appear in the range of the substitution.
    
    1433
    +
    
    1434
    +  That's pretty complicated, so we are very cautious about using the returned
    
    1435
    +  substitution.  I had a long struggle (#27994) when we were previously trying to
    
    1436
    +  apply that returned substitution as an optimisation.  But because type variables
    
    1437
    +  can occur in kinds, it was a losing battle -- I ended up with TyVars from the
    
    1438
    +  instance head escaping into the solver.   Consider
    
    1439
    +
    
    1440
    +      type F :: forall k. k -> *
    
    1441
    +      type instance F k a where
    
    1442
    +         F (k->*) (b::k->*) = Int
    
    1443
    +
    
    1444
    +      [W] F kappa (alpha::kappa) ~ Int
    
    1445
    +
    
    1446
    +  We unify the Wanted with the equation to get the substitution
    
    1447
    +      [ kappa :-> k->*,  b :-> alpha ]
    
    1448
    +  I tried using `trim_qtvs` (see Historical Note [trim_qtvs]) but my head hurt
    
    1449
    +  FAR too much: #27994 is an excellent example.  I gave up and now just ignore
    
    1450
    +  the substitution, making a fresh meta-var for each quantified variable.
    
    1451
    +
    
    1452
    +(CF8) When computing relevance (Note [Relevance] (R2)) we use `noEarlierMatch`
    
    1453
    +  on S(lhs).  But we must use /deep/ substitution on LHS. Consider
    
    1454
    +     type family F (a :: k) r where
    
    1455
    +       F @Type (Maybe Bool)              r = r      -- B0
    
    1456
    +       F @Type ((f :: Type -> Type) Int) r = Bool   -- B1
    
    1457
    +       F @k    ((g :: Type -> k) Int)    r = r      -- B2
    
    1458
    +
    
    1459
    +     [W] F @Type alpha Char ~ Char
    
    1460
    +  The `tcUnifyTysForInjectivity` will return substitution
    
    1461
    +      [k :-> Type, r :-> Char, alpha :-> (g :: Type->Type) Int], with g unbound
    
    1462
    +  If we used `substTy` on the LHS-tys for B2 we'd get
    
    1463
    +      lhs_tys' = [Type, (g :: Type -> k) Int, Char]
    
    1464
    +  That's ill-kinded because of the free `k`; and (worse) when `noEarlierMatch` matches
    
    1465
    +  lhs_tys' against earlier equations, (B1) will fail to match. So (B2) will be
    
    1466
    +  judged relevant, even though it isn't.  Bad, bad. Use deep substitution.
    
    1467
    +
    
    1468
    +(CF9)  Notice that, when generating the fundep equations for the solver to deal
    
    1469
    +  with, we do /not/ apply the pre-unifying substitution S. The types wlhs,wrhs
    
    1470
    +  contain meta-variables that we must actually unify! Example
    
    1402 1471
          type family F a b where
    
    1403 1472
            F [a] (Maybe b) = (a,  G b)
    
    1404 1473
          [W] F alpha beta ~ (Int, [gamma])
    
    1405 1474
       Pre-unification gives [alpha :-> [a], beta :-> Maybe b, a :-> Int]
    
    1406
    -  This substitution eliminates the quantified variable `a` but not `b`, so we
    
    1407
    -  want this:
    
    1408
    -     FDEqns { fd_qtvs = [b], fd_eqs [ [Int] ~ alpha
    
    1409
    -                                    , Maybe b ~ beta
    
    1410
    -                                    , (Int,G b) ~ (Int, [gamma]) ] }
    
    1411
    -
    
    1412
    -  Notice also that by applying the substitution to the template but not to the
    
    1413
    -  Wanted, we uphold the `fd_eqs` invariant in `FDEqns` (see its data type decl)
    
    1475
    +  We don't want to substitute `alpha` away! In fact we just generate these eqns:
    
    1476
    +     FDEqns { fd_qtvs = [a,b], fd_eqs [ [a] ~ alpha
    
    1477
    +                                      , Maybe b ~ beta
    
    1478
    +                                      , (a, G b) ~ (Int, [gamma]) ] }
    
    1479
    +  with `fd_qtvs` being the quantified variables of the equation, the LHSs
    
    1480
    +  being the types from the equation and the RHSs being the types from the Wanted.
    
    1481
    +  Notice that we thereby uphold the `fd_eqs` invariant in `FDEqns` (see its data
    
    1482
    +  type decl).
    
    1414 1483
     
    
    1415 1484
     Note [Cache-caused loops]
    
    1416 1485
     ~~~~~~~~~~~~~~~~~~~~~~~~~
    
    ... ... @@ -1517,8 +1586,8 @@ instantiateFunDepEqns (FDEqns { fd_qtvs = qtvs, fd_eqs = eqs })
    1517 1586
         rev_eqs = reverse eqs
    
    1518 1587
            -- (reverse eqs): See Note [Reverse order of fundep equations]
    
    1519 1588
     
    
    1520
    -    -- The kinds of `qtvs` can have free variables, because of `trim_qtvs`
    
    1521
    -    -- Example: T27828b
    
    1589
    +    -- The kinds of `qtvs` can have free variables;
    
    1590
    +    -- in the FDEqns produced by GHC.Tc.Instance.FunDeps.improveFromInstEnv
    
    1522 1591
         empty_subst = mkEmptySubst $ mkInScopeSet $
    
    1523 1592
                       tyCoVarsOfTypes (map tyVarKind qtvs)
    
    1524 1593
     
    

  • testsuite/tests/typecheck/should_compile/T27994.hs
    1
    +{-# LANGUAGE AllowAmbiguousTypes #-}
    
    2
    +{-# LANGUAGE DataKinds #-}
    
    3
    +{-# LANGUAGE FunctionalDependencies #-}
    
    4
    +{-# LANGUAGE GADTs #-}
    
    5
    +{-# LANGUAGE TypeFamilies #-}
    
    6
    +module  T27994a (l2) where
    
    7
    +
    
    8
    +import Data.Kind (Constraint, Type)
    
    9
    +
    
    10
    +l1 :: [String]
    
    11
    +l1 = ["hello", "world!"]
    
    12
    +
    
    13
    +l2 :: [Int]
    
    14
    +l2 = gmap (HCons length HNil) l1
    
    15
    +
    
    16
    +-----
    
    17
    +
    
    18
    +type HList :: [Type] -> Type
    
    19
    +data HList p where
    
    20
    +  HNil :: HList '[]
    
    21
    +  HCons :: x -> HList xs -> HList (x:xs)
    
    22
    +
    
    23
    +type ($$) :: k -> [Type] -> Type
    
    24
    +type family s $$ p where
    
    25
    +  (s :: Type)      $$ '[]   = s
    
    26
    +  (s :: Type -> k) $$ (a:b) = s a $$ b
    
    27
    +
    
    28
    +type Doms :: [Type] -> [Type]
    
    29
    +type family Doms t where
    
    30
    +  Doms '[]            = '[]
    
    31
    +  Doms ((a -> b) : t) = a : Doms t
    
    32
    +
    
    33
    +type Codoms :: [Type] -> [Type]
    
    34
    +type family Codoms t where
    
    35
    +  Codoms '[]            = '[]
    
    36
    +  Codoms ((a -> b) : t) = b : Codoms t
    
    37
    +
    
    38
    +type GMap :: k -> [Type] -> Constraint
    
    39
    +class GMap (s :: k) t | t -> k where
    
    40
    +  gmap :: HList t -> s $$ Doms t -> s $$ Codoms t
    
    41
    +
    
    42
    +instance GMap [] '[a -> b] where
    
    43
    +  gmap :: HList '[a -> b] -> [a] -> [b]
    
    44
    +  gmap (HCons f HNil) = go
    
    45
    +    where
    
    46
    +      go :: [a] -> [b]
    
    47
    +      go []     = []
    
    48
    +      go (x:xs) = f x : go xs

  • testsuite/tests/typecheck/should_compile/T27994a.hs
    1
    +{-# LANGUAGE DataKinds, TypeFamilies, PolyKinds, GADTs, AllowAmbiguousTypes #-}
    
    2
    +module T27994 where
    
    3
    +
    
    4
    +import Data.Kind (Type)
    
    5
    +import Data.Proxy (Proxy)
    
    6
    +
    
    7
    +type F :: forall{k}. k -> Type -> Type
    
    8
    +type family F s x where
    
    9
    +   F (s :: Type -> k) (Proxy s) = Int
    
    10
    +
    
    11
    +f :: forall k (s :: k) x. F s x -> x
    
    12
    +f _ = undefined
    
    13
    +
    
    14
    +g :: Proxy Maybe -> ()
    
    15
    +g _ = ()
    
    16
    +
    
    17
    +data T a where
    
    18
    +  MkT :: T Int
    
    19
    +
    
    20
    +test :: T a -> ()
    
    21
    +test t = (\y -> case t of MkT -> g y) (f (3 :: Int))
    
    22
    +
    
    23
    +{- [W] F @k_azX (s_azY::k_azX) p_azN ~ Int
    
    24
    +
    
    25
    +unify   [*->k,      s::*->k,  Proxy @(*->k) (s::*->k), Int]
    
    26
    +          ~ [k_azX, s_azY::k_azX, p_azN,                   Int]
    
    27
    +
    
    28
    +  -->   [ k_azX :-> (* -> k)
    
    29
    +        , s     :-> s_azY::k_azX
    
    30
    +        , p_azN :-> Proxy @(*->k) (s::*->k) ]
    
    31
    +
    
    32
    +  fixpt -->   [ k_azX :-> Type -> k
    
    33
    +              , s     :-> s_azY::(Type -> k)
    
    34
    +              , p_azN :-> Proxy @(Type->k) (s::k_azX) ]
    
    35
    +
    
    36
    +Generate a [W] for each pair
    
    37
    +    [W] k ~ k_azX
    
    38
    +    [W] s ~ s_azY
    
    39
    +    [W] Proxy s ~ p_azN
    
    40
    +    [W] Int ~ Int
    
    41
    +As an opt (claim) apply subst first
    
    42
    +    [W] k_azX ~ k_azX
    
    43
    +    [W] s_azY ~ s_azY
    
    44
    +    [W] Proxy s_azY ~ p_azN
    
    45
    +    [W] Int ~ Int
    
    46
    +
    
    47
    +-- [W] F @k_azX s_azY[tau] p_azN ~ Int
    
    48
    +-- Want: fresh k' s'
    
    49
    +-- [W] k' ~ k_azX
    
    50
    +-- [W] s':k' ~ s_azY:k_azX
    
    51
    +-- [W] Proxy s' ~ x
    
    52
    +-}
    
    53
    +

  • testsuite/tests/typecheck/should_compile/all.T
    ... ... @@ -972,4 +972,6 @@ test('T27557', normal, compile, [''])
    972 972
     test('T27664', normal, compile, [''])
    
    973 973
     test('T27916', normal, compile, [''])
    
    974 974
     test('T26543_orig', normal, compile, [''])
    
    975
    +test('T27994',  normal, compile, [''])
    
    976
    +test('T27994a', normal, compile, [''])
    
    975 977