TcCanonical.lhs 40.4 KB
Newer Older
1 2
\begin{code}
module TcCanonical(
3 4
    mkCanonical, mkCanonicals, mkCanonicalFEV, canWanteds, canGivens,
    canOccursCheck, canEq
5 6 7 8
 ) where

#include "HsVersions.h"

9
import BasicTypes
10 11 12 13 14 15 16 17 18 19 20 21
import Type
import TcRnTypes

import TcType
import TcErrors
import Coercion
import Class
import TyCon
import TypeRep
import Name
import Var
import Outputable
22
import Control.Monad    ( unless, when, zipWithM, zipWithM_ )
23 24 25 26 27 28
import MonadUtils
import Control.Applicative ( (<|>) )

import VarSet
import Bag

29 30
import HsBinds
import TcSMonad
31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92
\end{code}

Note [Canonicalisation]
~~~~~~~~~~~~~~~~~~~~~~~
* Converts (Constraint f) _which_does_not_contain_proper_implications_ to CanonicalCts
* Unary: treats individual constraints one at a time
* Does not do any zonking
* Lives in TcS monad so that it can create new skolem variables


%************************************************************************
%*                                                                      *
%*        Flattening (eliminating all function symbols)                 *
%*                                                                      *
%************************************************************************

Note [Flattening]
~~~~~~~~~~~~~~~~~~~~
  flatten ty  ==>   (xi, cc)
    where
      xi has no type functions
      cc = Auxiliary given (equality) constraints constraining
           the fresh type variables in xi.  Evidence for these 
           is always the identity coercion, because internally the
           fresh flattening skolem variables are actually identified
           with the types they have been generated to stand in for.

Note that it is flatten's job to flatten *every type function it sees*.
flatten is only called on *arguments* to type functions, by canEqGiven.

Recall that in comments we use alpha[flat = ty] to represent a
flattening skolem variable alpha which has been generated to stand in
for ty.

----- Example of flattening a constraint: ------
  flatten (List (F (G Int)))  ==>  (xi, cc)
    where
      xi  = List alpha
      cc  = { G Int ~ beta[flat = G Int],
              F beta ~ alpha[flat = F beta] }
Here
  * alpha and beta are 'flattening skolem variables'.
  * All the constraints in cc are 'given', and all their coercion terms 
    are the identity.

NB: Flattening Skolems only occur in canonical constraints, which
are never zonked, so we don't need to worry about zonking doing
accidental unflattening.

Note that we prefer to leave type synonyms unexpanded when possible,
so when the flattener encounters one, it first asks whether its
transitive expansion contains any type function applications.  If so,
it expands the synonym and proceeds; if not, it simply returns the
unexpanded synonym.

TODO: caching the information about whether transitive synonym
expansions contain any type function applications would speed things
up a bit; right now we waste a lot of energy traversing the same types
multiple times.

\begin{code}
-- Flatten a bunch of types all at once.
93 94
flattenMany :: CtFlavor -> [Type] -> TcS ([Xi], [Coercion], CanonicalCts)
-- Coercions :: Xi ~ Type 
95
flattenMany ctxt tys 
96 97
  = do { (xis, cos, cts_s) <- mapAndUnzip3M (flatten ctxt) tys
       ; return (xis, cos, andCCans cts_s) }
98 99 100

-- Flatten a type to get rid of type function applications, returning
-- the new type-function-free type, and a collection of new equality
101 102 103
-- constraints.  See Note [Flattening] for more detail.
flatten :: CtFlavor -> TcType -> TcS (Xi, Coercion, CanonicalCts)
-- Postcondition: Coercion :: Xi ~ TcType 
104 105
flatten ctxt ty 
  | Just ty' <- tcView ty
106
  = do { (xi, co, ccs) <- flatten ctxt ty'
107
	-- Preserve type synonyms if possible
108
	-- We can tell if ty' is function-free by
109 110
	-- whether there are any floated constraints
       ; if isEmptyCCan ccs then
111
             return (ty, ty, emptyCCan)  
112
         else
113
             return (xi, co, ccs) }
114 115

flatten _ v@(TyVarTy _)
116
  = return (v, v, emptyCCan)
117 118

flatten ctxt (AppTy ty1 ty2)
119 120 121
  = do { (xi1,co1,c1) <- flatten ctxt ty1
       ; (xi2,co2,c2) <- flatten ctxt ty2
       ; return (mkAppTy xi1 xi2, mkAppCoercion co1 co2, c1 `andCCan` c2) }
122 123

flatten ctxt (FunTy ty1 ty2)
124 125 126
  = do { (xi1,co1,c1) <- flatten ctxt ty1
       ; (xi2,co2,c2) <- flatten ctxt ty2
       ; return (mkFunTy xi1 xi2, mkFunCoercion co1 co2, c1 `andCCan` c2) }
127 128 129 130 131

flatten fl (TyConApp tc tys)
  -- For a normal type constructor or data family application, we just
  -- recursively flatten the arguments.
  | not (isSynFamilyTyCon tc)
132 133
    = do { (xis,cos,ccs) <- flattenMany fl tys
         ; return (mkTyConApp tc xis, mkTyConCoercion tc cos, ccs) }
134 135 136 137

  -- Otherwise, it's a type function application, and we have to
  -- flatten it away as well, and generate a new given equality constraint
  -- between the application and a newly generated flattening skolem variable.
138 139 140 141 142
  | otherwise 
  = ASSERT( tyConArity tc <= length tys )	-- Type functions are saturated
      do { (xis, cos, ccs) <- flattenMany fl tys
         ; let (xi_args, xi_rest)  = splitAt (tyConArity tc) xis
               (cos_args, cos_rest) = splitAt (tyConArity tc) cos 
143 144 145 146 147 148
	       	 -- The type function might be *over* saturated
		 -- in which case the remaining arguments should
		 -- be dealt with by AppTys
               fam_ty = mkTyConApp tc xi_args 
               fam_co = fam_ty -- identity 

149 150 151
         ; (ret_co, rhs_var, ct) <- 
             if isGiven fl then
               do { rhs_var <- newFlattenSkolemTy fam_ty
152
                  ; cv <- newGivenCoVar fam_ty rhs_var fam_co
153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173
                  ; let ct = CFunEqCan { cc_id     = cv
                                       , cc_flavor = fl -- Given
                                       , cc_fun    = tc 
                                       , cc_tyargs = xi_args 
                                       , cc_rhs    = rhs_var }
                  ; return $ (mkCoVarCoercion cv, rhs_var, ct) }
             else -- Derived or Wanted: make a new *unification* flatten variable
               do { rhs_var <- newFlexiTcSTy (typeKind fam_ty)
                  ; cv <- newWantedCoVar fam_ty rhs_var
                  ; let ct = CFunEqCan { cc_id = cv
                                       , cc_flavor = mkWantedFlavor fl
                                           -- Always Wanted, not Derived
                                       , cc_fun = tc
                                       , cc_tyargs = xi_args
                                       , cc_rhs    = rhs_var }
                  ; return $ (mkCoVarCoercion cv, rhs_var, ct) }

         ; return ( foldl AppTy rhs_var xi_rest
                  , foldl AppTy (mkSymCoercion ret_co 
                                    `mkTransCoercion` mkTyConCoercion tc cos_args) cos_rest
                  , ccs `extendCCans` ct) }
174 175 176


flatten ctxt (PredTy pred) 
177 178
  = do { (pred', co, ccs) <- flattenPred ctxt pred
       ; return (PredTy pred', co, ccs) }
179 180 181 182

flatten ctxt ty@(ForAllTy {})
-- We allow for-alls when, but only when, no type function
-- applications inside the forall involve the bound type variables
183 184
-- TODO: What if it is a (t1 ~ t2) => t3
--       Must revisit when the New Coercion API is here! 
185
  = do { let (tvs, rho) = splitForAllTys ty
186
       ; (rho', co, ccs) <- flatten ctxt rho
187 188 189 190 191
       ; let bad_eqs  = filterBag is_bad ccs
             is_bad c = tyVarsOfCanonical c `intersectsVarSet` tv_set
             tv_set   = mkVarSet tvs
       ; unless (isEmptyBag bad_eqs)
                (flattenForAllErrorTcS ctxt ty bad_eqs)
192
       ; return (mkForAllTys tvs rho', mkForAllTys tvs co, ccs)  }
193 194

---------------
195
flattenPred :: CtFlavor -> TcPredType -> TcS (TcPredType, Coercion, CanonicalCts)
196
flattenPred ctxt (ClassP cls tys)
197 198
  = do { (tys', cos, ccs) <- flattenMany ctxt tys
       ; return (ClassP cls tys', mkClassPPredCo cls cos, ccs) }
199
flattenPred ctxt (IParam nm ty)
200 201 202
  = do { (ty', co, ccs) <- flatten ctxt ty
       ; return (IParam nm ty', mkIParamPredCo nm co, ccs) }
-- TODO: Handling of coercions between EqPreds must be revisited once the New Coercion API is ready!
203
flattenPred ctxt (EqPred ty1 ty2)
204 205 206 207
  = do { (ty1', co1, ccs1) <- flatten ctxt ty1
       ; (ty2', co2, ccs2) <- flatten ctxt ty2
       ; return (EqPred ty1' ty2', mkEqPredCo co1 co2, ccs1 `andCCan` ccs2) }

208 209 210 211 212 213 214 215 216 217
\end{code}

%************************************************************************
%*                                                                      *
%*                Canonicalising given constraints                      *
%*                                                                      *
%************************************************************************

\begin{code}
canWanteds :: [WantedEvVar] -> TcS CanonicalCts 
218
canWanteds = fmap andCCans . mapM (\(EvVarX ev loc) -> mkCanonical (Wanted loc) ev)
219 220 221 222 223 224 225 226

canGivens :: GivenLoc -> [EvVar] -> TcS CanonicalCts
canGivens loc givens = do { ccs <- mapM (mkCanonical (Given loc)) givens
                          ; return (andCCans ccs) }

mkCanonicals :: CtFlavor -> [EvVar] -> TcS CanonicalCts 
mkCanonicals fl vs = fmap andCCans (mapM (mkCanonical fl) vs)

227 228 229 230
mkCanonicalFEV :: FlavoredEvVar -> TcS CanonicalCts
mkCanonicalFEV (EvVarX ev fl) = mkCanonical fl ev

mkCanonical :: CtFlavor -> EvVar -> TcS CanonicalCts
231 232 233 234 235 236 237 238
mkCanonical fl ev = case evVarPred ev of 
                        ClassP clas tys -> canClass fl ev clas tys 
                        IParam ip ty    -> canIP    fl ev ip ty
                        EqPred ty1 ty2  -> canEq    fl ev ty1 ty2 
                         

canClass :: CtFlavor -> EvVar -> Class -> [TcType] -> TcS CanonicalCts 
canClass fl v cn tys 
239 240 241 242 243 244 245 246
  = do { (xis,cos,ccs) <- flattenMany fl tys  -- cos :: xis ~ tys
       ; let no_flattening_happened = isEmptyCCan ccs
             dict_co = mkTyConCoercion (classTyCon cn) cos
       ; v_new <- if no_flattening_happened then return v
                  else if isGiven fl        then return v
                         -- The cos are all identities if fl=Given,
                         -- hence nothing to do
                  else do { v' <- newDictVar cn xis  -- D xis
247 248 249
                          ; when (isWanted fl) $ setDictBind v  (EvCast v' dict_co)
                          ; when (isGiven fl)  $ setDictBind v' (EvCast v (mkSymCoercion dict_co))
                                 -- NB: No more setting evidence for derived now 
250 251
                          ; return v' }

252 253 254 255 256
       -- Add the superclasses of this one here, See Note [Adding superclasses]. 
       -- But only if we are not simplifying the LHS of a rule. 
       ; sctx <- getTcSContext
       ; sc_cts <- if simplEqsOnly sctx then return emptyCCan 
                   else newSCWorkFromFlavored v_new fl cn xis
257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275

       ; return (sc_cts `andCCan` ccs `extendCCans` CDictCan { cc_id     = v_new
                                                             , cc_flavor = fl
                                                             , cc_class  = cn 
                                                             , cc_tyargs = xis }) }
\end{code}

Note [Adding superclasses]
~~~~~~~~~~~~~~~~~~~~~~~~~~ 
Since dictionaries are canonicalized only once in their lifetime, the
place to add their superclasses is canonicalisation (The alternative
would be to do it during constraint solving, but we'd have to be
extremely careful to not repeatedly introduced the same superclass in
our worklist). Here is what we do:

For Givens: 
       We add all their superclasses as Givens. 

For Wanteds: 
276 277
       Generally speaking we want to be able to add superclasses of 
       wanteds for two reasons:
278

279 280 281 282 283 284 285 286 287
       (1) Oportunities for improvement. Example: 
                  class (a ~ b) => C a b 
           Wanted constraint is: C alpha beta 
           We'd like to simply have C alpha alpha. Similar 
           situations arise in relation to functional dependencies. 
           
       (2) To have minimal constraints to quantify over: 
           For instance, if our wanted constraint is (Eq a, Ord a) 
           we'd only like to quantify over Ord a. 
288

289 290 291 292 293 294 295 296 297 298 299 300
       To deal with (1) above we only add the superclasses of wanteds
       which may lead to improvement, that is: equality superclasses or 
       superclasses with functional dependencies. 

       We deal with (2) completely independently in TcSimplify. See 
       Note [Minimize by SuperClasses] in TcSimplify. 


       Moreover, in all cases the extra improvement constraints are 
       Derived. Derived constraints have an identity (for now), but 
       we don't do anything with their evidence. For instance they 
       are never used to rewrite other constraints. 
301

302
       See also [New Wanted Superclass Work] in TcInteract. 
303

304 305 306

For Deriveds: 
       We do nothing.
307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327

Here's an example that demonstrates why we chose to NOT add
superclasses during simplification: [Comes from ticket #4497]

   class Num (RealOf t) => Normed t
   type family RealOf x

Assume the generated wanted constraint is: 
   RealOf e ~ e, Normed e 
If we were to be adding the superclasses during simplification we'd get: 
   Num uf, Normed e, RealOf e ~ e, RealOf e ~ uf 
==> 
   e ~ uf, Num uf, Normed e, RealOf e ~ e 
==> [Spontaneous solve] 
   Num uf, Normed uf, RealOf uf ~ uf 

While looks exactly like our original constraint. If we add the superclass again we'd loop. 
By adding superclasses definitely only once, during canonicalisation, this situation can't 
happen.

\begin{code}
328

329 330 331
newSCWorkFromFlavored :: EvVar -> CtFlavor -> Class -> [Xi] -> TcS CanonicalCts
-- Returns superclasses, see Note [Adding superclasses]
newSCWorkFromFlavored ev orig_flavor cls xis 
332 333 334 335 336 337 338 339 340
  | isDerived orig_flavor 
  = return emptyCCan  -- Deriveds don't yield more superclasses because we will
                      -- add them transitively in the case of wanteds. 

  | isGiven orig_flavor 
  = do { let sc_theta = immSuperClasses cls xis 
             flavor   = orig_flavor
       ; sc_vars <- mapM newEvVar sc_theta
       ; _ <- zipWithM_ setEvBind sc_vars [EvSuperClass ev n | n <- [0..]]
341
       ; mkCanonicals flavor sc_vars }
342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363

  | isEmptyVarSet (tyVarsOfTypes xis) 
  = return emptyCCan -- Wanteds with no variables yield no deriveds.
                     -- See Note [Improvement from Ground Wanteds]

  | otherwise -- Wanted case, just add those SC that can lead to improvement. 
  = do { let sc_rec_theta = transSuperClasses cls xis 
             impr_theta   = filter is_improvement_pty sc_rec_theta 
             Wanted wloc  = orig_flavor
       ; der_ids <- mapM newDerivedId impr_theta
       ; mkCanonicals (Derived wloc) der_ids }


is_improvement_pty :: PredType -> Bool 
-- Either it's an equality, or has some functional dependency
is_improvement_pty (EqPred {})      = True 
is_improvement_pty (ClassP cls _ty) = not $ null fundeps
 where (_,fundeps,_,_,_,_) = classExtraBigSig cls
is_improvement_pty _ = False



364 365 366 367

canIP :: CtFlavor -> EvVar -> IPName Name -> TcType -> TcS CanonicalCts
-- See Note [Canonical implicit parameter constraints] to see why we don't 
-- immediately canonicalize (flatten) IP constraints. 
368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383
canIP fl v nm ty 
  = return $ singleCCan $ CIPCan { cc_id = v
                                 , cc_flavor = fl
                                 , cc_ip_nm = nm
                                 , cc_ip_ty = ty } 

-----------------
canEq :: CtFlavor -> EvVar -> Type -> Type -> TcS CanonicalCts 
canEq fl cv ty1 ty2 
  | tcEqType ty1 ty2	-- Dealing with equality here avoids
    	     	 	-- later spurious occurs checks for a~a
  = do { when (isWanted fl) (setWantedCoBind cv ty1)
       ; return emptyCCan }

-- If one side is a variable, orient and flatten, 
-- WITHOUT expanding type synonyms, so that we tend to 
384 385 386 387 388 389 390 391
-- substitute a ~ Age rather than a ~ Int when @type Age = Int@
canEq fl cv ty1@(TyVarTy {}) ty2 
  = do { untch <- getUntouchables 
       ; canEqLeaf untch fl cv (classify ty1) (classify ty2) }
canEq fl cv ty1 ty2@(TyVarTy {}) 
  = do { untch <- getUntouchables 
       ; canEqLeaf untch fl cv (classify ty1) (classify ty2) }
      -- NB: don't use VarCls directly because tv1 or tv2 may be scolems!
392 393 394

canEq fl cv (TyConApp fn tys) ty2 
  | isSynFamilyTyCon fn, length tys == tyConArity fn
395 396
  = do { untch <- getUntouchables 
       ; canEqLeaf untch fl cv (FunCls fn tys) (classify ty2) }
397 398
canEq fl cv ty1 (TyConApp fn tys)
  | isSynFamilyTyCon fn, length tys == tyConArity fn
399 400
  = do { untch <- getUntouchables 
       ; canEqLeaf untch fl cv (classify ty1) (FunCls fn tys) }
401

402 403 404
canEq fl cv s1 s2
  | Just (t1a,t1b,t1c) <- splitCoPredTy_maybe s1, 
    Just (t2a,t2b,t2c) <- splitCoPredTy_maybe s2
405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427
  = do { (v1,v2,v3) 
             <- if isWanted fl then                   -- Wanted
                    do { v1 <- newWantedCoVar t1a t2a
                       ; v2 <- newWantedCoVar t1b t2b 
                       ; v3 <- newWantedCoVar t1c t2c 
                       ; let res_co = mkCoPredCo (mkCoVarCoercion v1) 
                                        (mkCoVarCoercion v2) (mkCoVarCoercion v3)
                       ; setWantedCoBind cv res_co
                       ; return (v1,v2,v3) }
                else if isGiven fl then               -- Given 
                         let co_orig = mkCoVarCoercion cv 
                             coa = mkCsel1Coercion co_orig
                             cob = mkCsel2Coercion co_orig
                             coc = mkCselRCoercion co_orig
                         in do { v1 <- newGivenCoVar t1a t2a coa
                               ; v2 <- newGivenCoVar t1b t2b cob
                               ; v3 <- newGivenCoVar t1c t2c coc 
                               ; return (v1,v2,v3) }
                else                                  -- Derived 
                    do { v1 <- newDerivedId (EqPred t1a t2a)
                       ; v2 <- newDerivedId (EqPred t1b t2b)
                       ; v3 <- newDerivedId (EqPred t1c t2c)
                       ; return (v1,v2,v3) }
428 429 430 431 432 433
       ; cc1 <- canEq fl v1 t1a t2a 
       ; cc2 <- canEq fl v2 t1b t2b 
       ; cc3 <- canEq fl v3 t1c t2c 
       ; return (cc1 `andCCan` cc2 `andCCan` cc3) }


434 435 436 437 438 439 440 441 442
-- Split up an equality between function types into two equalities.
canEq fl cv (FunTy s1 t1) (FunTy s2 t2)
  = do { (argv, resv) <- 
             if isWanted fl then 
                 do { argv <- newWantedCoVar s1 s2 
                    ; resv <- newWantedCoVar t1 t2 
                    ; setWantedCoBind cv $ 
                      mkFunCoercion (mkCoVarCoercion argv) (mkCoVarCoercion resv) 
                    ; return (argv,resv) } 
443 444 445 446 447 448 449 450 451 452 453 454

             else if isGiven fl then 
                      let [arg,res] = decomposeCo 2 (mkCoVarCoercion cv) 
                      in do { argv <- newGivenCoVar s1 s2 arg 
                            ; resv <- newGivenCoVar t1 t2 res
                            ; return (argv,resv) } 

             else -- Derived 
                 do { argv <- newDerivedId (EqPred s1 s2)
                    ; resv <- newDerivedId (EqPred t1 t2)
                    ; return (argv,resv) }

455 456 457 458
       ; cc1 <- canEq fl argv s1 s2 -- inherit original kinds and locations
       ; cc2 <- canEq fl resv t1 t2
       ; return (cc1 `andCCan` cc2) }

459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484
canEq fl cv (PredTy (IParam n1 t1)) (PredTy (IParam n2 t2))
  | n1 == n2
  = if isWanted fl then 
        do { v <- newWantedCoVar t1 t2 
           ; setWantedCoBind cv $ mkIParamPredCo n1 (mkCoVarCoercion cv)
           ; canEq fl v t1 t2 } 
    else return emptyCCan -- DV: How to decompose given IP coercions? 

canEq fl cv (PredTy (ClassP c1 tys1)) (PredTy (ClassP c2 tys2))
  | c1 == c2
  = if isWanted fl then 
       do { vs <- zipWithM newWantedCoVar tys1 tys2 
          ; setWantedCoBind cv $ mkClassPPredCo c1 (map mkCoVarCoercion vs) 
          ; andCCans <$> zipWith3M (canEq fl) vs tys1 tys2
          }
    else return emptyCCan 
  -- How to decompose given dictionary (and implicit parameter) coercions? 
  -- You may think that the following is right: 
  --    let cos = decomposeCo (length tys1) (mkCoVarCoercion cv) 
  --    in  zipWith3M newGivOrDerCoVar tys1 tys2 cos
  -- But this assumes that the coercion is a type constructor-based 
  -- coercion, and not a PredTy (ClassP cn cos) coercion. So we chose
  -- to not decompose these coercions. We have to get back to this 
  -- when we clean up the Coercion API.

canEq fl cv (TyConApp tc1 tys1) (TyConApp tc2 tys2)
485 486 487 488
  | isAlgTyCon tc1 && isAlgTyCon tc2
  , tc1 == tc2
  , length tys1 == length tys2
  = -- Generate equalities for each of the corresponding arguments
489 490
    do { argsv 
             <- if isWanted fl then
491
                    do { argsv <- zipWithM newWantedCoVar tys1 tys2
492 493 494 495 496
                       ; setWantedCoBind cv $ 
                         mkTyConCoercion tc1 (map mkCoVarCoercion argsv)
                       ; return argsv } 

                else if isGiven fl then 
497
                    let cos = decomposeCo (length tys1) (mkCoVarCoercion cv) 
498 499 500 501 502
                    in zipWith3M newGivenCoVar tys1 tys2 cos

                else -- Derived 
                    zipWithM (\t1 t2 -> newDerivedId (EqPred t1 t2)) tys1 tys2

503 504 505 506 507 508 509 510 511 512 513 514 515 516
       ; andCCans <$> zipWith3M (canEq fl) argsv tys1 tys2 }

-- See Note [Equality between type applications]
--     Note [Care with type applications] in TcUnify
canEq fl cv ty1 ty2
  | Just (s1,t1) <- tcSplitAppTy_maybe ty1
  , Just (s2,t2) <- tcSplitAppTy_maybe ty2
    = do { (cv1,cv2) <- 
             if isWanted fl 
             then do { cv1 <- newWantedCoVar s1 s2 
                     ; cv2 <- newWantedCoVar t1 t2 
                     ; setWantedCoBind cv $ 
                       mkAppCoercion (mkCoVarCoercion cv1) (mkCoVarCoercion cv2) 
                     ; return (cv1,cv2) } 
517 518 519 520 521 522 523 524 525 526 527 528

             else if isGiven fl then 
                    let co1 = mkLeftCoercion  $ mkCoVarCoercion cv 
                        co2 = mkRightCoercion $ mkCoVarCoercion cv
                    in do { cv1 <- newGivenCoVar s1 s2 co1 
                          ; cv2 <- newGivenCoVar t1 t2 co2 
                          ; return (cv1,cv2) } 
             else -- Derived
                 do { cv1 <- newDerivedId (EqPred s1 s2)
                    ; cv2 <- newDerivedId (EqPred t1 t2)
                    ; return (cv1,cv2) }

529 530 531 532
         ; cc1 <- canEq fl cv1 s1 s2 
         ; cc2 <- canEq fl cv2 t1 t2 
         ; return (cc1 `andCCan` cc2) } 

533
canEq fl cv s1@(ForAllTy {}) s2@(ForAllTy {})
534 535
 | tcIsForAllTy s1, tcIsForAllTy s2, 
   Wanted {} <- fl 
536
 = canEqFailure fl cv
537
 | otherwise
538 539 540 541 542 543
 = do { traceTcS "Ommitting decomposition of given polytype equality" (pprEq s1 s2)
      ; return emptyCCan }

-- Finally expand any type synonym applications.
canEq fl cv ty1 ty2 | Just ty1' <- tcView ty1 = canEq fl cv ty1' ty2
canEq fl cv ty1 ty2 | Just ty2' <- tcView ty2 = canEq fl cv ty1 ty2'
544
canEq fl cv _ _                               = canEqFailure fl cv
545

546 547
canEqFailure :: CtFlavor -> EvVar -> TcS CanonicalCts
canEqFailure fl cv = return (singleCCan (mkFrozenError fl cv))
548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657
\end{code}

Note [Equality between type applications]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
If we see an equality of the form s1 t1 ~ s2 t2 we can always split
it up into s1 ~ s2 /\ t1 ~ t2, since s1 and s2 can't be type
functions (type functions use the TyConApp constructor, which never
shows up as the LHS of an AppTy).  Other than type functions, types
in Haskell are always 

  (1) generative: a b ~ c d implies a ~ c, since different type
      constructors always generate distinct types

  (2) injective: a b ~ a d implies b ~ d; we never generate the
      same type from different type arguments.


Note [Canonical ordering for equality constraints]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Implemented as (<+=) below:

  - Type function applications always come before anything else.  
  - Variables always come before non-variables (other than type
      function applications).

Note that we don't need to unfold type synonyms on the RHS to check
the ordering; that is, in the rules above it's OK to consider only
whether something is *syntactically* a type function application or
not.  To illustrate why this is OK, suppose we have an equality of the
form 'tv ~ S a b c', where S is a type synonym which expands to a
top-level application of the type function F, something like

  type S a b c = F d e

Then to canonicalize 'tv ~ S a b c' we flatten the RHS, and since S's
expansion contains type function applications the flattener will do
the expansion and then generate a skolem variable for the type
function application, so we end up with something like this:

  tv ~ x
  F d e ~ x

where x is the skolem variable.  This is one extra equation than
absolutely necessary (we could have gotten away with just 'F d e ~ tv'
if we had noticed that S expanded to a top-level type function
application and flipped it around in the first place) but this way
keeps the code simpler.

Unlike the OutsideIn(X) draft of May 7, 2010, we do not care about the
ordering of tv ~ tv constraints.  There are several reasons why we
might:

  (1) In order to be able to extract a substitution that doesn't
      mention untouchable variables after we are done solving, we might
      prefer to put touchable variables on the left. However, in and
      of itself this isn't necessary; we can always re-orient equality
      constraints at the end if necessary when extracting a substitution.

  (2) To ensure termination we might think it necessary to put
      variables in lexicographic order. However, this isn't actually 
      necessary as outlined below.

While building up an inert set of canonical constraints, we maintain
the invariant that the equality constraints in the inert set form an
acyclic rewrite system when viewed as L-R rewrite rules.  Moreover,
the given constraints form an idempotent substitution (i.e. none of
the variables on the LHS occur in any of the RHS's, and type functions
never show up in the RHS at all), the wanted constraints also form an
idempotent substitution, and finally the LHS of a given constraint
never shows up on the RHS of a wanted constraint.  There may, however,
be a wanted LHS that shows up in a given RHS, since we do not rewrite
given constraints with wanted constraints.

Suppose we have an inert constraint set


  tg_1 ~ xig_1         -- givens
  tg_2 ~ xig_2
  ...
  tw_1 ~ xiw_1         -- wanteds
  tw_2 ~ xiw_2
  ...

where each t_i can be either a type variable or a type function
application. Now suppose we take a new canonical equality constraint,
t' ~ xi' (note among other things this means t' does not occur in xi')
and try to react it with the existing inert set.  We show by induction
on the number of t_i which occur in t' ~ xi' that this process will
terminate.

There are several ways t' ~ xi' could react with an existing constraint:

TODO: finish this proof.  The below was for the case where the entire
inert set is an idempotent subustitution...

(b) We could have t' = t_j for some j.  Then we obtain the new
    equality xi_j ~ xi'; note that neither xi_j or xi' contain t_j.  We
    now canonicalize the new equality, which may involve decomposing it
    into several canonical equalities, and recurse on these.  However,
    none of the new equalities will contain t_j, so they have fewer
    occurrences of the t_i than the original equation.

(a) We could have t_j occurring in xi' for some j, with t' /=
    t_j. Then we substitute xi_j for t_j in xi' and continue.  However,
    since none of the t_i occur in xi_j, we have decreased the
    number of t_i that occur in xi', since we eliminated t_j and did not
    introduce any new ones.

\begin{code}
data TypeClassifier 
Ian Lynagh's avatar
Ian Lynagh committed
658
  = FskCls TcTyVar      -- ^ Flatten skolem 
simonpj@microsoft.com's avatar
simonpj@microsoft.com committed
659
  | VarCls TcTyVar      -- ^ Non-flatten-skolem variable 
Ian Lynagh's avatar
Ian Lynagh committed
660 661
  | FunCls TyCon [Type] -- ^ Type function, exactly saturated
  | OtherCls TcType     -- ^ Neither of the above
662 663

unClassify :: TypeClassifier -> TcType
664 665 666 667
unClassify (VarCls tv)      = TyVarTy tv
unClassify (FskCls tv) = TyVarTy tv 
unClassify (FunCls fn tys)  = TyConApp fn tys
unClassify (OtherCls ty)    = ty
668 669

classify :: TcType -> TypeClassifier
670 671 672 673 674

classify (TyVarTy tv) 
  | isTcTyVar tv, 
    FlatSkol {} <- tcTyVarDetails tv = FskCls tv
  | otherwise                        = VarCls tv
675 676 677 678 679 680 681 682 683 684 685
classify (TyConApp tc tys) | isSynFamilyTyCon tc
                           , tyConArity tc == length tys
                           = FunCls tc tys
classify ty                | Just ty' <- tcView ty
	                   = case classify ty' of
                               OtherCls {} -> OtherCls ty
                               var_or_fn   -> var_or_fn
                           | otherwise 
                           = OtherCls ty

-- See note [Canonical ordering for equality constraints].
686
reOrient :: TcsUntouchables -> TypeClassifier -> TypeClassifier -> Bool	
687 688 689 690 691
-- (t1 `reOrient` t2) responds True 
--   iff we should flip to (t2~t1)
-- We try to say False if possible, to minimise evidence generation
--
-- Postcondition: After re-orienting, first arg is not OTherCls
692 693 694 695
reOrient _untch (OtherCls {}) (FunCls {})   = True
reOrient _untch (OtherCls {}) (FskCls {})   = True
reOrient _untch (OtherCls {}) (VarCls {})   = True
reOrient _untch (OtherCls {}) (OtherCls {}) = panic "reOrient"  -- One must be Var/Fun
696

697
reOrient _untch (FunCls {})   (VarCls {})    = False
698
  -- See Note [No touchables as FunEq RHS] in TcSMonad
699
reOrient _untch (FunCls {}) _                = False             -- Fun/Other on rhs
700

701
reOrient _untch (VarCls {}) (FunCls {})      = True 
702

703
reOrient _untch (VarCls {}) (FskCls {})      = False
704

705 706 707 708 709
reOrient _untch (VarCls {})  (OtherCls {})   = False
reOrient _untch (VarCls tv1)  (VarCls tv2)  
  | isMetaTyVar tv2 && not (isMetaTyVar tv1) = True 
  | otherwise                                = False 
  -- Just for efficiency, see CTyEqCan invariants 
710

711 712
reOrient _untch (FskCls {}) (VarCls tv2)     = isMetaTyVar tv2 
  -- Just for efficiency, see CTyEqCan invariants
713

714 715 716
reOrient _untch (FskCls {}) (FskCls {})     = False
reOrient _untch (FskCls {}) (FunCls {})     = True 
reOrient _untch (FskCls {}) (OtherCls {})   = False 
717 718

------------------
719
canEqLeaf :: TcsUntouchables 
720
          -> CtFlavor -> CoVar 
721 722 723 724 725 726 727 728
          -> TypeClassifier -> TypeClassifier -> TcS CanonicalCts 
-- Canonicalizing "leaf" equality constraints which cannot be
-- decomposed further (ie one of the types is a variable or
-- saturated type function application).  

  -- Preconditions: 
  --    * one of the two arguments is not OtherCls
  --    * the two types are not equal (looking through synonyms)
729 730
canEqLeaf untch fl cv cls1 cls2 
  | cls1 `re_orient` cls2
731 732 733 734
  = do { cv' <- if isWanted fl 
                then do { cv' <- newWantedCoVar s2 s1 
                        ; setWantedCoBind cv $ mkSymCoercion (mkCoVarCoercion cv') 
                        ; return cv' } 
735 736 737 738
                else if isGiven fl then 
                         newGivenCoVar s2 s1 (mkSymCoercion (mkCoVarCoercion cv))
                else -- Derived
                    newDerivedId (EqPred s2 s1)
739 740 741
       ; canEqLeafOriented fl cv' cls2 s1 }

  | otherwise
742 743
  = do { traceTcS "canEqLeaf" (ppr (unClassify cls1) $$ ppr (unClassify cls2))
       ; canEqLeafOriented fl cv cls1 s2 }
744
  where
745
    re_orient = reOrient untch 
746 747 748 749 750 751 752
    s1 = unClassify cls1  
    s2 = unClassify cls2  

------------------
canEqLeafOriented :: CtFlavor -> CoVar 
                  -> TypeClassifier -> TcType -> TcS CanonicalCts 
-- First argument is not OtherCls
753 754
canEqLeafOriented fl cv cls1@(FunCls fn tys1) s2         -- cv : F tys1
  | let k1 = kindAppResult (tyConKind fn) tys1,
755
    let k2 = typeKind s2, 
756 757
    not (k1 `compatKind` k2) -- Establish the kind invariant for CFunEqCan
  = canEqFailure fl cv
758 759
    -- Eagerly fails, see Note [Kind errors] in TcInteract

760 761
  | otherwise 
  = ASSERT2( isSynFamilyTyCon fn, ppr (unClassify cls1) )
762 763 764 765 766 767 768 769
    do { (xis1,cos1,ccs1) <- flattenMany fl tys1 -- Flatten type function arguments
                                                 -- cos1 :: xis1 ~ tys1
       ; (xi2, co2, ccs2) <- flatten fl s2       -- Flatten entire RHS
                                                 -- co2  :: xi2 ~ s2
       ; let ccs = ccs1 `andCCan` ccs2
             no_flattening_happened = isEmptyCCan ccs
       ; cv_new <- if no_flattening_happened then return cv
                   else if isGiven fl        then return cv
770 771
                   else if isWanted fl then 
                         do { cv' <- newWantedCoVar (unClassify (FunCls fn xis1)) xi2
772
                                 -- cv' : F xis ~ xi2
773
                            ; let -- fun_co :: F xis1 ~ F tys1
774 775 776 777 778
                                 fun_co = mkTyConCoercion fn cos1
                                 -- want_co :: F tys1 ~ s2
                                 want_co = mkSymCoercion fun_co
                                           `mkTransCoercion` mkCoVarCoercion cv'
                                           `mkTransCoercion` co2
779 780 781 782
                            ; setWantedCoBind cv  want_co
                            ; return cv' }
                   else -- Derived 
                       newDerivedId (EqPred (unClassify (FunCls fn xis1)) xi2)
783 784 785

       ; let final_cc = CFunEqCan { cc_id     = cv_new
                                  , cc_flavor = fl
786 787 788
                                  , cc_fun    = fn
                                  , cc_tyargs = xis1 
                                  , cc_rhs    = xi2 }
789
       ; return $ ccs `extendCCans` final_cc }
790

791 792
-- Otherwise, we have a variable on the left, so call canEqLeafTyVarLeft
canEqLeafOriented fl cv (FskCls tv) s2 
793
  = canEqLeafTyVarLeft fl cv tv s2 
794
canEqLeafOriented fl cv (VarCls tv) s2 
795
  = canEqLeafTyVarLeft fl cv tv s2 
796 797 798
canEqLeafOriented _ cv (OtherCls ty1) ty2 
  = pprPanic "canEqLeaf" (ppr cv $$ ppr ty1 $$ ppr ty2)

799
canEqLeafTyVarLeft :: CtFlavor -> CoVar -> TcTyVar -> TcType -> TcS CanonicalCts
800
-- Establish invariants of CTyEqCans 
801
canEqLeafTyVarLeft fl cv tv s2       -- cv : tv ~ s2
802 803
  | not (k1 `compatKind` k2) -- Establish the kind invariant for CTyEqCan
  = canEqFailure fl cv
804
       -- Eagerly fails, see Note [Kind errors] in TcInteract
805
  | otherwise
806 807 808 809 810
  = do { (xi2, co, ccs2) <- flatten fl s2  -- Flatten RHS   co : xi2 ~ s2
       ; mxi2' <- canOccursCheck fl tv xi2 -- Do an occurs check, and return a possibly
                                           -- unfolded version of the RHS, if we had to 
                                           -- unfold any type synonyms to get rid of tv.
       ; case mxi2' of {
811
           Nothing   -> canEqFailure fl cv ;
812 813 814 815
           Just xi2' ->
    do { let no_flattening_happened = isEmptyCCan ccs2
       ; cv_new <- if no_flattening_happened then return cv
                   else if isGiven fl        then return cv
816 817 818 819 820 821
                   else if isWanted fl then 
                         do { cv' <- newWantedCoVar (mkTyVarTy tv) xi2'  -- cv' : tv ~ xi2
                            ; setWantedCoBind cv  (mkCoVarCoercion cv' `mkTransCoercion` co)
                            ; return cv' }
                   else -- Derived
                       newDerivedId (EqPred (mkTyVarTy tv) xi2')
822 823 824 825 826

       ; return $ ccs2 `extendCCans` CTyEqCan { cc_id     = cv_new
                                              , cc_flavor = fl
                                              , cc_tyvar  = tv
                                              , cc_rhs    = xi2' } } } }
827 828 829 830 831 832 833 834 835 836 837 838 839
  where
    k1 = tyVarKind tv
    k2 = typeKind s2

-- See Note [Type synonyms and canonicalization].
-- Check whether the given variable occurs in the given type.  We may
-- have needed to do some type synonym unfolding in order to get rid
-- of the variable, so we also return the unfolded version of the
-- type, which is guaranteed to be syntactically free of the given
-- type variable.  If the type is already syntactically free of the
-- variable, then the same type is returned.
--
-- Precondition: the two types are not equal (looking though synonyms)
840 841
canOccursCheck :: CtFlavor -> TcTyVar -> Xi -> TcS (Maybe Xi)
canOccursCheck _gw tv xi = return (expandAway tv xi)
842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869
\end{code}

@expandAway tv xi@ expands synonyms in xi just enough to get rid of
occurrences of tv, if that is possible; otherwise, it returns Nothing.
For example, suppose we have
  type F a b = [a]
Then
  expandAway b (F Int b) = Just [Int]
but
  expandAway a (F a Int) = Nothing

We don't promise to do the absolute minimum amount of expanding
necessary, but we try not to do expansions we don't need to.  We
prefer doing inner expansions first.  For example,
  type F a b = (a, Int, a, [a])
  type G b   = Char
We have
  expandAway b (F (G b)) = F Char
even though we could also expand F to get rid of b.

\begin{code}
expandAway :: TcTyVar -> Xi -> Maybe Xi
expandAway tv t@(TyVarTy tv') 
  | tv == tv' = Nothing
  | otherwise = Just t
expandAway tv xi
  | not (tv `elemVarSet` tyVarsOfType xi) = Just xi
expandAway tv (AppTy ty1 ty2) 
870 871 872 873
  = do { ty1' <- expandAway tv ty1
       ; ty2' <- expandAway tv ty2 
       ; return (mkAppTy ty1' ty2') }
-- mkAppTy <$> expandAway tv ty1 <*> expandAway tv ty2
874
expandAway tv (FunTy ty1 ty2)
875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890
  = do { ty1' <- expandAway tv ty1 
       ; ty2' <- expandAway tv ty2 
       ; return (mkFunTy ty1' ty2') } 
-- mkFunTy <$> expandAway tv ty1 <*> expandAway tv ty2
expandAway tv ty@(ForAllTy {}) 
  = let (tvs,rho) = splitForAllTys ty
        tvs_knds  = map tyVarKind tvs 
    in if tv `elemVarSet` tyVarsOfTypes tvs_knds then 
       -- Can't expand away the kinds unless we create 
       -- fresh variables which we don't want to do at this point.
           Nothing 
       else do { rho' <- expandAway tv rho
               ; return (mkForAllTys tvs rho') }
expandAway tv (PredTy pred) 
  = do { pred' <- expandAwayPred tv pred  
       ; return (PredTy pred') }
891 892 893 894 895
-- For a type constructor application, first try expanding away the
-- offending variable from the arguments.  If that doesn't work, next
-- see if the type constructor is a type synonym, and if so, expand
-- it and try again.
expandAway tv ty@(TyConApp tc tys)
896 897 898 899 900 901 902 903 904 905 906 907 908 909 910
  = (mkTyConApp tc <$> mapM (expandAway tv) tys) <|> (tcView ty >>= expandAway tv)

expandAwayPred :: TcTyVar -> TcPredType -> Maybe TcPredType 
expandAwayPred tv (ClassP cls tys) 
  = do { tys' <- mapM (expandAway tv) tys; return (ClassP cls tys') } 
expandAwayPred tv (EqPred ty1 ty2)
  = do { ty1' <- expandAway tv ty1
       ; ty2' <- expandAway tv ty2 
       ; return (EqPred ty1' ty2') }
expandAwayPred tv (IParam nm ty) 
  = do { ty' <- expandAway tv ty
       ; return (IParam nm ty') }

                

911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992
\end{code}

Note [Type synonyms and canonicalization]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

We treat type synonym applications as xi types, that is, they do not
count as type function applications.  However, we do need to be a bit
careful with type synonyms: like type functions they may not be
generative or injective.  However, unlike type functions, they are
parametric, so there is no problem in expanding them whenever we see
them, since we do not need to know anything about their arguments in
order to expand them; this is what justifies not having to treat them
as specially as type function applications.  The thing that causes
some subtleties is that we prefer to leave type synonym applications
*unexpanded* whenever possible, in order to generate better error
messages.

If we encounter an equality constraint with type synonym applications
on both sides, or a type synonym application on one side and some sort
of type application on the other, we simply must expand out the type
synonyms in order to continue decomposing the equality constraint into
primitive equality constraints.  For example, suppose we have

  type F a = [Int]

and we encounter the equality

  F a ~ [b]

In order to continue we must expand F a into [Int], giving us the
equality

  [Int] ~ [b]

which we can then decompose into the more primitive equality
constraint

  Int ~ b.

However, if we encounter an equality constraint with a type synonym
application on one side and a variable on the other side, we should
NOT (necessarily) expand the type synonym, since for the purpose of
good error messages we want to leave type synonyms unexpanded as much
as possible.

However, there is a subtle point with type synonyms and the occurs
check that takes place for equality constraints of the form tv ~ xi.
As an example, suppose we have

  type F a = Int

and we come across the equality constraint

  a ~ F a

This should not actually fail the occurs check, since expanding out
the type synonym results in the legitimate equality constraint a ~
Int.  We must actually do this expansion, because unifying a with F a
will lead the type checker into infinite loops later.  Put another
way, canonical equality constraints should never *syntactically*
contain the LHS variable in the RHS type.  However, we don't always
need to expand type synonyms when doing an occurs check; for example,
the constraint

  a ~ F b

is obviously fine no matter what F expands to. And in this case we
would rather unify a with F b (rather than F b's expansion) in order
to get better error messages later.

So, when doing an occurs check with a type synonym application on the
RHS, we use some heuristics to find an expansion of the RHS which does
not contain the variable from the LHS.  In particular, given

  a ~ F t1 ... tn

we first try expanding each of the ti to types which no longer contain
a.  If this turns out to be impossible, we next try expanding F
itself, and so on.