4a125364758d2ed2ca9b32efc2654ed4698d939c
[ghc-hetmet.git] / compiler / typecheck / TcMType.lhs
1 %
2 % (c) The University of Glasgow 2006
3 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4 %
5
6 Monadic type operations
7
8 This module contains monadic operations over types that contain
9 mutable type variables
10
11 \begin{code}
12 module TcMType (
13   TcTyVar, TcKind, TcType, TcTauType, TcThetaType, TcTyVarSet,
14
15   --------------------------------
16   -- Creating new mutable type variables
17   newFlexiTyVar,
18   newFlexiTyVarTy,              -- Kind -> TcM TcType
19   newFlexiTyVarTys,             -- Int -> Kind -> TcM [TcType]
20   newKindVar, newKindVars, 
21   lookupTcTyVar, LookupTyVarResult(..),
22   newMetaTyVar, readMetaTyVar, writeMetaTyVar, 
23
24   --------------------------------
25   -- Boxy type variables
26   newBoxyTyVar, newBoxyTyVars, newBoxyTyVarTys, readFilledBox, 
27
28   --------------------------------
29   -- Creating new coercion variables
30   newCoVars,
31
32   --------------------------------
33   -- Instantiation
34   tcInstTyVar, tcInstType, tcInstTyVars, tcInstBoxyTyVar,
35   tcInstSigTyVars, zonkSigTyVar,
36   tcInstSkolTyVar, tcInstSkolTyVars, tcInstSkolType, 
37   tcSkolSigType, tcSkolSigTyVars,
38
39   --------------------------------
40   -- Checking type validity
41   Rank, UserTypeCtxt(..), checkValidType, 
42   SourceTyCtxt(..), checkValidTheta, checkFreeness,
43   checkValidInstHead, checkValidInstance, checkAmbiguity,
44   checkInstTermination,
45   arityErr, 
46
47   --------------------------------
48   -- Zonking
49   zonkType, zonkTcPredType, 
50   zonkTcTyVar, zonkTcTyVars, zonkTcTyVarsAndFV, zonkQuantifiedTyVar,
51   zonkTcType, zonkTcTypes, zonkTcClassConstraints, zonkTcThetaType,
52   zonkTcKindToKind, zonkTcKind, zonkTopTyVar,
53
54   readKindVar, writeKindVar
55
56   ) where
57
58 #include "HsVersions.h"
59
60 -- friends:
61 import TypeRep
62 import TcType
63 import Type
64 import Type
65 import Coercion
66 import Class
67 import TyCon
68 import Var
69
70 -- others:
71 import TcRnMonad          -- TcType, amongst others
72 import FunDeps
73 import Name
74 import VarSet
75 import ErrUtils
76 import DynFlags
77 import Util
78 import Maybes
79 import ListSetOps
80 import UniqSupply
81 import SrcLoc
82 import Outputable
83
84 import Control.Monad    ( when )
85 import Data.List        ( (\\) )
86 \end{code}
87
88
89 %************************************************************************
90 %*                                                                      *
91         Instantiation in general
92 %*                                                                      *
93 %************************************************************************
94
95 \begin{code}
96 tcInstType :: ([TyVar] -> TcM [TcTyVar])                -- How to instantiate the type variables
97            -> TcType                                    -- Type to instantiate
98            -> TcM ([TcTyVar], TcThetaType, TcType)      -- Result
99 tcInstType inst_tyvars ty
100   = case tcSplitForAllTys ty of
101         ([],     rho) -> let    -- There may be overloading despite no type variables;
102                                 --      (?x :: Int) => Int -> Int
103                            (theta, tau) = tcSplitPhiTy rho
104                          in
105                          return ([], theta, tau)
106
107         (tyvars, rho) -> do { tyvars' <- inst_tyvars tyvars
108
109                             ; let  tenv = zipTopTvSubst tyvars (mkTyVarTys tyvars')
110                                 -- Either the tyvars are freshly made, by inst_tyvars,
111                                 -- or (in the call from tcSkolSigType) any nested foralls
112                                 -- have different binders.  Either way, zipTopTvSubst is ok
113
114                             ; let  (theta, tau) = tcSplitPhiTy (substTy tenv rho)
115                             ; return (tyvars', theta, tau) }
116 \end{code}
117
118
119 %************************************************************************
120 %*                                                                      *
121         Kind variables
122 %*                                                                      *
123 %************************************************************************
124
125 \begin{code}
126 newCoVars :: [(TcType,TcType)] -> TcM [CoVar]
127 newCoVars spec
128   = do  { us <- newUniqueSupply 
129         ; return [ mkCoVar (mkSysTvName uniq FSLIT("co"))
130                            (mkCoKind ty1 ty2)
131                  | ((ty1,ty2), uniq) <- spec `zip` uniqsFromSupply us] }
132
133 newKindVar :: TcM TcKind
134 newKindVar = do { uniq <- newUnique
135                 ; ref <- newMutVar Flexi
136                 ; return (mkTyVarTy (mkKindVar uniq ref)) }
137
138 newKindVars :: Int -> TcM [TcKind]
139 newKindVars n = mappM (\ _ -> newKindVar) (nOfThem n ())
140 \end{code}
141
142
143 %************************************************************************
144 %*                                                                      *
145         SkolemTvs (immutable)
146 %*                                                                      *
147 %************************************************************************
148
149 \begin{code}
150 mkSkolTyVar :: Name -> Kind -> SkolemInfo -> TcTyVar
151 mkSkolTyVar name kind info = mkTcTyVar name kind (SkolemTv info)
152
153 tcSkolSigType :: SkolemInfo -> Type -> TcM ([TcTyVar], TcThetaType, TcType)
154 -- Instantiate a type signature with skolem constants, but 
155 -- do *not* give them fresh names, because we want the name to
156 -- be in the type environment -- it is lexically scoped.
157 tcSkolSigType info ty = tcInstType (\tvs -> return (tcSkolSigTyVars info tvs)) ty
158
159 tcSkolSigTyVars :: SkolemInfo -> [TyVar] -> [TcTyVar]
160 -- Make skolem constants, but do *not* give them new names, as above
161 tcSkolSigTyVars info tyvars = [ mkSkolTyVar (tyVarName tv) (tyVarKind tv) info
162                               | tv <- tyvars ]
163
164 tcInstSkolTyVar :: SkolemInfo -> Maybe SrcLoc -> TyVar -> TcM TcTyVar
165 -- Instantiate the tyvar, using 
166 --      * the occ-name and kind of the supplied tyvar, 
167 --      * the unique from the monad,
168 --      * the location either from the tyvar (mb_loc = Nothing)
169 --        or from mb_loc (Just loc)
170 tcInstSkolTyVar info mb_loc tyvar
171   = do  { uniq <- newUnique
172         ; let old_name = tyVarName tyvar
173               kind     = tyVarKind tyvar
174               loc      = mb_loc `orElse` getSrcLoc old_name
175               new_name = mkInternalName uniq (nameOccName old_name) loc
176         ; return (mkSkolTyVar new_name kind info) }
177
178 tcInstSkolTyVars :: SkolemInfo -> [TyVar] -> TcM [TcTyVar]
179 -- Get the location from the monad
180 tcInstSkolTyVars info tyvars 
181   = do  { span <- getSrcSpanM
182         ; mapM (tcInstSkolTyVar info (Just (srcSpanStart span))) tyvars }
183
184 tcInstSkolType :: SkolemInfo -> TcType -> TcM ([TcTyVar], TcThetaType, TcType)
185 -- Instantiate a type with fresh skolem constants
186 -- Binding location comes from the monad
187 tcInstSkolType info ty = tcInstType (tcInstSkolTyVars info) ty
188 \end{code}
189
190
191 %************************************************************************
192 %*                                                                      *
193         MetaTvs (meta type variables; mutable)
194 %*                                                                      *
195 %************************************************************************
196
197 \begin{code}
198 newMetaTyVar :: BoxInfo -> Kind -> TcM TcTyVar
199 -- Make a new meta tyvar out of thin air
200 newMetaTyVar box_info kind
201   = do  { uniq <- newUnique
202         ; ref <- newMutVar Flexi ;
203         ; let name = mkSysTvName uniq fs 
204               fs = case box_info of
205                         BoxTv   -> FSLIT("t")
206                         TauTv   -> FSLIT("t")
207                         SigTv _ -> FSLIT("a")
208                 -- We give BoxTv and TauTv the same string, because
209                 -- otherwise we get user-visible differences in error
210                 -- messages, which are confusing.  If you want to see
211                 -- the box_info of each tyvar, use -dppr-debug
212         ; return (mkTcTyVar name kind (MetaTv box_info ref)) }
213
214 instMetaTyVar :: BoxInfo -> TyVar -> TcM TcTyVar
215 -- Make a new meta tyvar whose Name and Kind 
216 -- come from an existing TyVar
217 instMetaTyVar box_info tyvar
218   = do  { uniq <- newUnique
219         ; ref <- newMutVar Flexi ;
220         ; let name = setNameUnique (tyVarName tyvar) uniq
221               kind = tyVarKind tyvar
222         ; return (mkTcTyVar name kind (MetaTv box_info ref)) }
223
224 readMetaTyVar :: TyVar -> TcM MetaDetails
225 readMetaTyVar tyvar = ASSERT2( isMetaTyVar tyvar, ppr tyvar )
226                       readMutVar (metaTvRef tyvar)
227
228 writeMetaTyVar :: TcTyVar -> TcType -> TcM ()
229 #ifndef DEBUG
230 writeMetaTyVar tyvar ty = writeMutVar (metaTvRef tyvar) (Indirect ty)
231 #else
232 writeMetaTyVar tyvar ty
233   | not (isMetaTyVar tyvar)
234   = pprTrace "writeMetaTyVar" (ppr tyvar) $
235     returnM ()
236
237   | otherwise
238   = ASSERT( isMetaTyVar tyvar )
239     ASSERT2( k2 `isSubKind` k1, (ppr tyvar <+> ppr k1) $$ (ppr ty <+> ppr k2) )
240     do  { ASSERTM2( do { details <- readMetaTyVar tyvar; return (isFlexi details) }, ppr tyvar )
241         ; writeMutVar (metaTvRef tyvar) (Indirect ty) }
242   where
243     k1 = tyVarKind tyvar
244     k2 = typeKind ty
245 #endif
246 \end{code}
247
248
249 %************************************************************************
250 %*                                                                      *
251         MetaTvs: TauTvs
252 %*                                                                      *
253 %************************************************************************
254
255 \begin{code}
256 newFlexiTyVar :: Kind -> TcM TcTyVar
257 newFlexiTyVar kind = newMetaTyVar TauTv kind
258
259 newFlexiTyVarTy  :: Kind -> TcM TcType
260 newFlexiTyVarTy kind
261   = newFlexiTyVar kind  `thenM` \ tc_tyvar ->
262     returnM (TyVarTy tc_tyvar)
263
264 newFlexiTyVarTys :: Int -> Kind -> TcM [TcType]
265 newFlexiTyVarTys n kind = mappM newFlexiTyVarTy (nOfThem n kind)
266
267 tcInstTyVar :: TyVar -> TcM TcTyVar
268 -- Instantiate with a META type variable
269 tcInstTyVar tyvar = instMetaTyVar TauTv tyvar
270
271 tcInstTyVars :: [TyVar] -> TcM ([TcTyVar], [TcType], TvSubst)
272 -- Instantiate with META type variables
273 tcInstTyVars tyvars
274   = do  { tc_tvs <- mapM tcInstTyVar tyvars
275         ; let tys = mkTyVarTys tc_tvs
276         ; returnM (tc_tvs, tys, zipTopTvSubst tyvars tys) }
277                 -- Since the tyvars are freshly made,
278                 -- they cannot possibly be captured by
279                 -- any existing for-alls.  Hence zipTopTvSubst
280 \end{code}
281
282
283 %************************************************************************
284 %*                                                                      *
285         MetaTvs: SigTvs
286 %*                                                                      *
287 %************************************************************************
288
289 \begin{code}
290 tcInstSigTyVars :: Bool -> SkolemInfo -> [TyVar] -> TcM [TcTyVar]
291 -- Instantiate with skolems or meta SigTvs; depending on use_skols
292 -- Always take location info from the supplied tyvars
293 tcInstSigTyVars use_skols skol_info tyvars 
294   | use_skols
295   = mapM (tcInstSkolTyVar skol_info Nothing) tyvars
296
297   | otherwise
298   = mapM (instMetaTyVar (SigTv skol_info)) tyvars
299
300 zonkSigTyVar :: TcTyVar -> TcM TcTyVar
301 zonkSigTyVar sig_tv 
302   | isSkolemTyVar sig_tv 
303   = return sig_tv       -- Happens in the call in TcBinds.checkDistinctTyVars
304   | otherwise
305   = ASSERT( isSigTyVar sig_tv )
306     do { ty <- zonkTcTyVar sig_tv
307        ; return (tcGetTyVar "zonkSigTyVar" ty) }
308         -- 'ty' is bound to be a type variable, because SigTvs
309         -- can only be unified with type variables
310 \end{code}
311
312
313 %************************************************************************
314 %*                                                                      *
315         MetaTvs: BoxTvs
316 %*                                                                      *
317 %************************************************************************
318
319 \begin{code}
320 newBoxyTyVar :: Kind -> TcM BoxyTyVar
321 newBoxyTyVar kind = newMetaTyVar BoxTv kind
322
323 newBoxyTyVars :: [Kind] -> TcM [BoxyTyVar]
324 newBoxyTyVars kinds = mapM newBoxyTyVar kinds
325
326 newBoxyTyVarTys :: [Kind] -> TcM [BoxyType]
327 newBoxyTyVarTys kinds = do { tvs <- mapM newBoxyTyVar kinds; return (mkTyVarTys tvs) }
328
329 readFilledBox :: BoxyTyVar -> TcM TcType
330 -- Read the contents of the box, which should be filled in by now
331 readFilledBox box_tv = ASSERT( isBoxyTyVar box_tv )
332                        do { cts <- readMetaTyVar box_tv
333                           ; case cts of
334                                 Flexi       -> pprPanic "readFilledBox" (ppr box_tv)
335                                 Indirect ty -> return ty }
336
337 tcInstBoxyTyVar :: TyVar -> TcM BoxyTyVar
338 -- Instantiate with a BOXY type variable
339 tcInstBoxyTyVar tyvar = instMetaTyVar BoxTv tyvar
340 \end{code}
341
342
343 %************************************************************************
344 %*                                                                      *
345 \subsection{Putting and getting  mutable type variables}
346 %*                                                                      *
347 %************************************************************************
348
349 But it's more fun to short out indirections on the way: If this
350 version returns a TyVar, then that TyVar is unbound.  If it returns
351 any other type, then there might be bound TyVars embedded inside it.
352
353 We return Nothing iff the original box was unbound.
354
355 \begin{code}
356 data LookupTyVarResult  -- The result of a lookupTcTyVar call
357   = DoneTv TcTyVarDetails       -- SkolemTv or virgin MetaTv
358   | IndirectTv TcType
359
360 lookupTcTyVar :: TcTyVar -> TcM LookupTyVarResult
361 lookupTcTyVar tyvar 
362   = ASSERT( isTcTyVar tyvar )
363     case details of
364       SkolemTv _   -> return (DoneTv details)
365       MetaTv _ ref -> do { meta_details <- readMutVar ref
366                          ; case meta_details of
367                             Indirect ty -> return (IndirectTv ty)
368                             Flexi       -> return (DoneTv details) }
369   where
370     details =  tcTyVarDetails tyvar
371
372 {- 
373 -- gaw 2004 We aren't shorting anything out anymore, at least for now
374 getTcTyVar tyvar
375   | not (isTcTyVar tyvar)
376   = pprTrace "getTcTyVar" (ppr tyvar) $
377     returnM (Just (mkTyVarTy tyvar))
378
379   | otherwise
380   = ASSERT2( isTcTyVar tyvar, ppr tyvar )
381     readMetaTyVar tyvar                         `thenM` \ maybe_ty ->
382     case maybe_ty of
383         Just ty -> short_out ty                         `thenM` \ ty' ->
384                    writeMetaTyVar tyvar (Just ty')      `thenM_`
385                    returnM (Just ty')
386
387         Nothing    -> returnM Nothing
388
389 short_out :: TcType -> TcM TcType
390 short_out ty@(TyVarTy tyvar)
391   | not (isTcTyVar tyvar)
392   = returnM ty
393
394   | otherwise
395   = readMetaTyVar tyvar `thenM` \ maybe_ty ->
396     case maybe_ty of
397         Just ty' -> short_out ty'                       `thenM` \ ty' ->
398                     writeMetaTyVar tyvar (Just ty')     `thenM_`
399                     returnM ty'
400
401         other    -> returnM ty
402
403 short_out other_ty = returnM other_ty
404 -}
405 \end{code}
406
407
408 %************************************************************************
409 %*                                                                      *
410 \subsection{Zonking -- the exernal interfaces}
411 %*                                                                      *
412 %************************************************************************
413
414 -----------------  Type variables
415
416 \begin{code}
417 zonkTcTyVars :: [TcTyVar] -> TcM [TcType]
418 zonkTcTyVars tyvars = mappM zonkTcTyVar tyvars
419
420 zonkTcTyVarsAndFV :: [TcTyVar] -> TcM TcTyVarSet
421 zonkTcTyVarsAndFV tyvars = mappM zonkTcTyVar tyvars     `thenM` \ tys ->
422                            returnM (tyVarsOfTypes tys)
423
424 zonkTcTyVar :: TcTyVar -> TcM TcType
425 zonkTcTyVar tyvar = ASSERT( isTcTyVar tyvar )
426                     zonk_tc_tyvar (\ tv -> returnM (TyVarTy tv)) tyvar
427 \end{code}
428
429 -----------------  Types
430
431 \begin{code}
432 zonkTcType :: TcType -> TcM TcType
433 zonkTcType ty = zonkType (\ tv -> returnM (TyVarTy tv)) ty
434
435 zonkTcTypes :: [TcType] -> TcM [TcType]
436 zonkTcTypes tys = mappM zonkTcType tys
437
438 zonkTcClassConstraints cts = mappM zonk cts
439     where zonk (clas, tys)
440             = zonkTcTypes tys   `thenM` \ new_tys ->
441               returnM (clas, new_tys)
442
443 zonkTcThetaType :: TcThetaType -> TcM TcThetaType
444 zonkTcThetaType theta = mappM zonkTcPredType theta
445
446 zonkTcPredType :: TcPredType -> TcM TcPredType
447 zonkTcPredType (ClassP c ts)
448   = zonkTcTypes ts      `thenM` \ new_ts ->
449     returnM (ClassP c new_ts)
450 zonkTcPredType (IParam n t)
451   = zonkTcType t        `thenM` \ new_t ->
452     returnM (IParam n new_t)
453 zonkTcPredType (EqPred t1 t2)
454   = zonkTcType t1       `thenM` \ new_t1 ->
455     zonkTcType t2       `thenM` \ new_t2 ->
456     returnM (EqPred new_t1 new_t2)
457 \end{code}
458
459 -------------------  These ...ToType, ...ToKind versions
460                      are used at the end of type checking
461
462 \begin{code}
463 zonkTopTyVar :: TcTyVar -> TcM TcTyVar
464 -- zonkTopTyVar is used, at the top level, on any un-instantiated meta type variables
465 -- to default the kind of ? and ?? etc to *.  This is important to ensure that
466 -- instance declarations match.  For example consider
467 --      instance Show (a->b)
468 --      foo x = show (\_ -> True)
469 -- Then we'll get a constraint (Show (p ->q)) where p has argTypeKind (printed ??), 
470 -- and that won't match the typeKind (*) in the instance decl.
471 --
472 -- Because we are at top level, no further constraints are going to affect these
473 -- type variables, so it's time to do it by hand.  However we aren't ready
474 -- to default them fully to () or whatever, because the type-class defaulting
475 -- rules have yet to run.
476
477 zonkTopTyVar tv
478   | k `eqKind` default_k = return tv
479   | otherwise
480   = do  { tv' <- newFlexiTyVar default_k
481         ; writeMetaTyVar tv (mkTyVarTy tv') 
482         ; return tv' }
483   where
484     k = tyVarKind tv
485     default_k = defaultKind k
486
487 zonkQuantifiedTyVar :: TcTyVar -> TcM TyVar
488 -- zonkQuantifiedTyVar is applied to the a TcTyVar when quantifying over it.
489 -- It might be a meta TyVar, in which case we freeze it into an ordinary TyVar.
490 -- When we do this, we also default the kind -- see notes with Kind.defaultKind
491 -- The meta tyvar is updated to point to the new regular TyVar.  Now any 
492 -- bound occurences of the original type variable will get zonked to 
493 -- the immutable version.
494 --
495 -- We leave skolem TyVars alone; they are immutable.
496 zonkQuantifiedTyVar tv
497   | isSkolemTyVar tv = return tv
498         -- It might be a skolem type variable, 
499         -- for example from a user type signature
500
501   | otherwise   -- It's a meta-type-variable
502   = do  { details <- readMetaTyVar tv
503
504         -- Create the new, frozen, regular type variable
505         ; let final_kind = defaultKind (tyVarKind tv)
506               final_tv   = mkTyVar (tyVarName tv) final_kind
507
508         -- Bind the meta tyvar to the new tyvar
509         ; case details of
510             Indirect ty -> WARN( True, ppr tv $$ ppr ty ) 
511                            return ()
512                 -- [Sept 04] I don't think this should happen
513                 -- See note [Silly Type Synonym]
514
515             Flexi -> writeMetaTyVar tv (mkTyVarTy final_tv)
516
517         -- Return the new tyvar
518         ; return final_tv }
519 \end{code}
520
521 [Silly Type Synonyms]
522
523 Consider this:
524         type C u a = u  -- Note 'a' unused
525
526         foo :: (forall a. C u a -> C u a) -> u
527         foo x = ...
528
529         bar :: Num u => u
530         bar = foo (\t -> t + t)
531
532 * From the (\t -> t+t) we get type  {Num d} =>  d -> d
533   where d is fresh.
534
535 * Now unify with type of foo's arg, and we get:
536         {Num (C d a)} =>  C d a -> C d a
537   where a is fresh.
538
539 * Now abstract over the 'a', but float out the Num (C d a) constraint
540   because it does not 'really' mention a.  (see exactTyVarsOfType)
541   The arg to foo becomes
542         /\a -> \t -> t+t
543
544 * So we get a dict binding for Num (C d a), which is zonked to give
545         a = ()
546   [Note Sept 04: now that we are zonking quantified type variables
547   on construction, the 'a' will be frozen as a regular tyvar on
548   quantification, so the floated dict will still have type (C d a).
549   Which renders this whole note moot; happily!]
550
551 * Then the /\a abstraction has a zonked 'a' in it.
552
553 All very silly.   I think its harmless to ignore the problem.  We'll end up with
554 a /\a in the final result but all the occurrences of a will be zonked to ()
555
556
557 %************************************************************************
558 %*                                                                      *
559 \subsection{Zonking -- the main work-horses: zonkType, zonkTyVar}
560 %*                                                                      *
561 %*              For internal use only!                                  *
562 %*                                                                      *
563 %************************************************************************
564
565 \begin{code}
566 -- For unbound, mutable tyvars, zonkType uses the function given to it
567 -- For tyvars bound at a for-all, zonkType zonks them to an immutable
568 --      type variable and zonks the kind too
569
570 zonkType :: (TcTyVar -> TcM Type)       -- What to do with unbound mutable type variables
571                                         -- see zonkTcType, and zonkTcTypeToType
572          -> TcType
573          -> TcM Type
574 zonkType unbound_var_fn ty
575   = go ty
576   where
577     go (NoteTy _ ty2)    = go ty2       -- Discard free-tyvar annotations
578                          
579     go (TyConApp tc tys) = mappM go tys `thenM` \ tys' ->
580                            returnM (TyConApp tc tys')
581                             
582     go (PredTy p)        = go_pred p            `thenM` \ p' ->
583                            returnM (PredTy p')
584                          
585     go (FunTy arg res)   = go arg               `thenM` \ arg' ->
586                            go res               `thenM` \ res' ->
587                            returnM (FunTy arg' res')
588                          
589     go (AppTy fun arg)   = go fun               `thenM` \ fun' ->
590                            go arg               `thenM` \ arg' ->
591                            returnM (mkAppTy fun' arg')
592                 -- NB the mkAppTy; we might have instantiated a
593                 -- type variable to a type constructor, so we need
594                 -- to pull the TyConApp to the top.
595
596         -- The two interesting cases!
597     go (TyVarTy tyvar) | isTcTyVar tyvar = zonk_tc_tyvar unbound_var_fn tyvar
598                        | otherwise       = return (TyVarTy tyvar)
599                 -- Ordinary (non Tc) tyvars occur inside quantified types
600
601     go (ForAllTy tyvar ty) = ASSERT( isImmutableTyVar tyvar )
602                              go ty              `thenM` \ ty' ->
603                              returnM (ForAllTy tyvar ty')
604
605     go_pred (ClassP c tys)   = mappM go tys     `thenM` \ tys' ->
606                                returnM (ClassP c tys')
607     go_pred (IParam n ty)    = go ty            `thenM` \ ty' ->
608                                returnM (IParam n ty')
609     go_pred (EqPred ty1 ty2) = go ty1           `thenM` \ ty1' ->
610                                go ty2           `thenM` \ ty2' ->
611                                returnM (EqPred ty1' ty2')
612
613 zonk_tc_tyvar :: (TcTyVar -> TcM Type)          -- What to do for an unbound mutable variable
614               -> TcTyVar -> TcM TcType
615 zonk_tc_tyvar unbound_var_fn tyvar 
616   | not (isMetaTyVar tyvar)     -- Skolems
617   = returnM (TyVarTy tyvar)
618
619   | otherwise                   -- Mutables
620   = do  { cts <- readMetaTyVar tyvar
621         ; case cts of
622             Flexi       -> unbound_var_fn tyvar    -- Unbound meta type variable
623             Indirect ty -> zonkType unbound_var_fn ty  }
624 \end{code}
625
626
627
628 %************************************************************************
629 %*                                                                      *
630                         Zonking kinds
631 %*                                                                      *
632 %************************************************************************
633
634 \begin{code}
635 readKindVar  :: KindVar -> TcM (MetaDetails)
636 writeKindVar :: KindVar -> TcKind -> TcM ()
637 readKindVar  kv = readMutVar (kindVarRef kv)
638 writeKindVar kv val = writeMutVar (kindVarRef kv) (Indirect val)
639
640 -------------
641 zonkTcKind :: TcKind -> TcM TcKind
642 zonkTcKind k = zonkTcType k
643
644 -------------
645 zonkTcKindToKind :: TcKind -> TcM Kind
646 -- When zonking a TcKind to a kind, we need to instantiate kind variables,
647 -- Haskell specifies that * is to be used, so we follow that.
648 zonkTcKindToKind k = zonkType (\ _ -> return liftedTypeKind) k
649 \end{code}
650                         
651 %************************************************************************
652 %*                                                                      *
653 \subsection{Checking a user type}
654 %*                                                                      *
655 %************************************************************************
656
657 When dealing with a user-written type, we first translate it from an HsType
658 to a Type, performing kind checking, and then check various things that should 
659 be true about it.  We don't want to perform these checks at the same time
660 as the initial translation because (a) they are unnecessary for interface-file
661 types and (b) when checking a mutually recursive group of type and class decls,
662 we can't "look" at the tycons/classes yet.  Also, the checks are are rather
663 diverse, and used to really mess up the other code.
664
665 One thing we check for is 'rank'.  
666
667         Rank 0:         monotypes (no foralls)
668         Rank 1:         foralls at the front only, Rank 0 inside
669         Rank 2:         foralls at the front, Rank 1 on left of fn arrow,
670
671         basic ::= tyvar | T basic ... basic
672
673         r2  ::= forall tvs. cxt => r2a
674         r2a ::= r1 -> r2a | basic
675         r1  ::= forall tvs. cxt => r0
676         r0  ::= r0 -> r0 | basic
677         
678 Another thing is to check that type synonyms are saturated. 
679 This might not necessarily show up in kind checking.
680         type A i = i
681         data T k = MkT (k Int)
682         f :: T A        -- BAD!
683
684         
685 \begin{code}
686 checkValidType :: UserTypeCtxt -> Type -> TcM ()
687 -- Checks that the type is valid for the given context
688 checkValidType ctxt ty
689   = traceTc (text "checkValidType" <+> ppr ty)  `thenM_`
690     doptM Opt_GlasgowExts       `thenM` \ gla_exts ->
691     let 
692         rank | gla_exts = Arbitrary
693              | otherwise
694              = case ctxt of     -- Haskell 98
695                  GenPatCtxt     -> Rank 0
696                  LamPatSigCtxt  -> Rank 0
697                  BindPatSigCtxt -> Rank 0
698                  DefaultDeclCtxt-> Rank 0
699                  ResSigCtxt     -> Rank 0
700                  TySynCtxt _    -> Rank 0
701                  ExprSigCtxt    -> Rank 1
702                  FunSigCtxt _   -> Rank 1
703                  ConArgCtxt _   -> Rank 1       -- We are given the type of the entire
704                                                 -- constructor, hence rank 1
705                  ForSigCtxt _   -> Rank 1
706                  SpecInstCtxt   -> Rank 1
707
708         actual_kind = typeKind ty
709
710         kind_ok = case ctxt of
711                         TySynCtxt _  -> True    -- Any kind will do
712                         ResSigCtxt   -> isSubOpenTypeKind        actual_kind
713                         ExprSigCtxt  -> isSubOpenTypeKind        actual_kind
714                         GenPatCtxt   -> isLiftedTypeKind actual_kind
715                         ForSigCtxt _ -> isLiftedTypeKind actual_kind
716                         other        -> isSubArgTypeKind    actual_kind
717         
718         ubx_tup | not gla_exts = UT_NotOk
719                 | otherwise    = case ctxt of
720                                    TySynCtxt _ -> UT_Ok
721                                    ExprSigCtxt -> UT_Ok
722                                    other       -> UT_NotOk
723                 -- Unboxed tuples ok in function results,
724                 -- but for type synonyms we allow them even at
725                 -- top level
726     in
727         -- Check that the thing has kind Type, and is lifted if necessary
728     checkTc kind_ok (kindErr actual_kind)       `thenM_`
729
730         -- Check the internal validity of the type itself
731     check_poly_type rank ubx_tup ty             `thenM_`
732
733     traceTc (text "checkValidType done" <+> ppr ty)
734 \end{code}
735
736
737 \begin{code}
738 data Rank = Rank Int | Arbitrary
739
740 decRank :: Rank -> Rank
741 decRank Arbitrary = Arbitrary
742 decRank (Rank n)  = Rank (n-1)
743
744 ----------------------------------------
745 data UbxTupFlag = UT_Ok | UT_NotOk
746         -- The "Ok" version means "ok if -fglasgow-exts is on"
747
748 ----------------------------------------
749 check_poly_type :: Rank -> UbxTupFlag -> Type -> TcM ()
750 check_poly_type (Rank 0) ubx_tup ty 
751   = check_tau_type (Rank 0) ubx_tup ty
752
753 check_poly_type rank ubx_tup ty 
754   | null tvs && null theta
755   = check_tau_type rank ubx_tup ty
756   | otherwise
757   = do  { check_valid_theta SigmaCtxt theta
758         ; check_poly_type rank ubx_tup tau      -- Allow foralls to right of arrow
759         ; checkFreeness tvs theta
760         ; checkAmbiguity tvs theta (tyVarsOfType tau) }
761   where
762     (tvs, theta, tau) = tcSplitSigmaTy ty
763    
764 ----------------------------------------
765 check_arg_type :: Type -> TcM ()
766 -- The sort of type that can instantiate a type variable,
767 -- or be the argument of a type constructor.
768 -- Not an unboxed tuple, but now *can* be a forall (since impredicativity)
769 -- Other unboxed types are very occasionally allowed as type
770 -- arguments depending on the kind of the type constructor
771 -- 
772 -- For example, we want to reject things like:
773 --
774 --      instance Ord a => Ord (forall s. T s a)
775 -- and
776 --      g :: T s (forall b.b)
777 --
778 -- NB: unboxed tuples can have polymorphic or unboxed args.
779 --     This happens in the workers for functions returning
780 --     product types with polymorphic components.
781 --     But not in user code.
782 -- Anyway, they are dealt with by a special case in check_tau_type
783
784 check_arg_type ty 
785   = check_poly_type Arbitrary UT_NotOk ty       `thenM_` 
786     checkTc (not (isUnLiftedType ty)) (unliftedArgErr ty)
787
788 ----------------------------------------
789 check_tau_type :: Rank -> UbxTupFlag -> Type -> TcM ()
790 -- Rank is allowed rank for function args
791 -- No foralls otherwise
792
793 check_tau_type rank ubx_tup ty@(ForAllTy _ _)       = failWithTc (forAllTyErr ty)
794 check_tau_type rank ubx_tup ty@(FunTy (PredTy _) _) = failWithTc (forAllTyErr ty)
795         -- Reject e.g. (Maybe (?x::Int => Int)), with a decent error message
796
797 -- Naked PredTys don't usually show up, but they can as a result of
798 --      {-# SPECIALISE instance Ord Char #-}
799 -- The Right Thing would be to fix the way that SPECIALISE instance pragmas
800 -- are handled, but the quick thing is just to permit PredTys here.
801 check_tau_type rank ubx_tup (PredTy sty) = getDOpts             `thenM` \ dflags ->
802                                            check_pred_ty dflags TypeCtxt sty
803
804 check_tau_type rank ubx_tup (TyVarTy _)       = returnM ()
805 check_tau_type rank ubx_tup ty@(FunTy arg_ty res_ty)
806   = check_poly_type (decRank rank) UT_NotOk arg_ty      `thenM_`
807     check_poly_type rank           UT_Ok    res_ty
808
809 check_tau_type rank ubx_tup (AppTy ty1 ty2)
810   = check_arg_type ty1 `thenM_` check_arg_type ty2
811
812 check_tau_type rank ubx_tup (NoteTy other_note ty)
813   = check_tau_type rank ubx_tup ty
814
815 check_tau_type rank ubx_tup ty@(TyConApp tc tys)
816   | isSynTyCon tc       
817   = do  {       -- It's OK to have an *over-applied* type synonym
818                 --      data Tree a b = ...
819                 --      type Foo a = Tree [a]
820                 --      f :: Foo a b -> ...
821         ; case tcView ty of
822              Just ty' -> check_tau_type rank ubx_tup ty'        -- Check expansion
823              Nothing  -> failWithTc arity_msg
824
825         ; gla_exts <- doptM Opt_GlasgowExts
826         ; if gla_exts then
827         -- If -fglasgow-exts then don't check the type arguments
828         -- This allows us to instantiate a synonym defn with a 
829         -- for-all type, or with a partially-applied type synonym.
830         --      e.g.   type T a b = a
831         --             type S m   = m ()
832         --             f :: S (T Int)
833         -- Here, T is partially applied, so it's illegal in H98.
834         -- But if you expand S first, then T we get just 
835         --             f :: Int
836         -- which is fine.
837                 returnM ()
838           else
839                 -- For H98, do check the type args
840                 mappM_ check_arg_type tys
841         }
842     
843   | isUnboxedTupleTyCon tc
844   = doptM Opt_GlasgowExts                       `thenM` \ gla_exts ->
845     checkTc (ubx_tup_ok gla_exts) ubx_tup_msg   `thenM_`
846     mappM_ (check_tau_type (Rank 0) UT_Ok) tys  
847                 -- Args are allowed to be unlifted, or
848                 -- more unboxed tuples, so can't use check_arg_ty
849
850   | otherwise
851   = mappM_ check_arg_type tys
852
853   where
854     ubx_tup_ok gla_exts = case ubx_tup of { UT_Ok -> gla_exts; other -> False }
855
856     n_args    = length tys
857     tc_arity  = tyConArity tc
858
859     arity_msg   = arityErr "Type synonym" (tyConName tc) tc_arity n_args
860     ubx_tup_msg = ubxArgTyErr ty
861
862 ----------------------------------------
863 forAllTyErr     ty = ptext SLIT("Illegal polymorphic or qualified type:") <+> ppr ty
864 unliftedArgErr  ty = ptext SLIT("Illegal unlifted type argument:") <+> ppr ty
865 ubxArgTyErr     ty = ptext SLIT("Illegal unboxed tuple type as function argument:") <+> ppr ty
866 kindErr kind       = ptext SLIT("Expecting an ordinary type, but found a type of kind") <+> ppr kind
867 \end{code}
868
869
870
871 %************************************************************************
872 %*                                                                      *
873 \subsection{Checking a theta or source type}
874 %*                                                                      *
875 %************************************************************************
876
877 \begin{code}
878 -- Enumerate the contexts in which a "source type", <S>, can occur
879 --      Eq a 
880 -- or   ?x::Int
881 -- or   r <: {x::Int}
882 -- or   (N a) where N is a newtype
883
884 data SourceTyCtxt
885   = ClassSCCtxt Name    -- Superclasses of clas
886                         --      class <S> => C a where ...
887   | SigmaCtxt           -- Theta part of a normal for-all type
888                         --      f :: <S> => a -> a
889   | DataTyCtxt Name     -- Theta part of a data decl
890                         --      data <S> => T a = MkT a
891   | TypeCtxt            -- Source type in an ordinary type
892                         --      f :: N a -> N a
893   | InstThetaCtxt       -- Context of an instance decl
894                         --      instance <S> => C [a] where ...
895                 
896 pprSourceTyCtxt (ClassSCCtxt c) = ptext SLIT("the super-classes of class") <+> quotes (ppr c)
897 pprSourceTyCtxt SigmaCtxt       = ptext SLIT("the context of a polymorphic type")
898 pprSourceTyCtxt (DataTyCtxt tc) = ptext SLIT("the context of the data type declaration for") <+> quotes (ppr tc)
899 pprSourceTyCtxt InstThetaCtxt   = ptext SLIT("the context of an instance declaration")
900 pprSourceTyCtxt TypeCtxt        = ptext SLIT("the context of a type")
901 \end{code}
902
903 \begin{code}
904 checkValidTheta :: SourceTyCtxt -> ThetaType -> TcM ()
905 checkValidTheta ctxt theta 
906   = addErrCtxt (checkThetaCtxt ctxt theta) (check_valid_theta ctxt theta)
907
908 -------------------------
909 check_valid_theta ctxt []
910   = returnM ()
911 check_valid_theta ctxt theta
912   = getDOpts                                    `thenM` \ dflags ->
913     warnTc (notNull dups) (dupPredWarn dups)    `thenM_`
914     mappM_ (check_pred_ty dflags ctxt) theta
915   where
916     (_,dups) = removeDups tcCmpPred theta
917
918 -------------------------
919 check_pred_ty dflags ctxt pred@(ClassP cls tys)
920   =     -- Class predicates are valid in all contexts
921     checkTc (arity == n_tys) arity_err          `thenM_`
922
923         -- Check the form of the argument types
924     mappM_ check_arg_type tys                           `thenM_`
925     checkTc (check_class_pred_tys dflags ctxt tys)
926             (predTyVarErr pred $$ how_to_allow)
927
928   where
929     class_name = className cls
930     arity      = classArity cls
931     n_tys      = length tys
932     arity_err  = arityErr "Class" class_name arity n_tys
933     how_to_allow = parens (ptext SLIT("Use -fglasgow-exts to permit this"))
934
935 check_pred_ty dflags SigmaCtxt (IParam _ ty) = check_arg_type ty
936         -- Implicit parameters only allows in type
937         -- signatures; not in instance decls, superclasses etc
938         -- The reason for not allowing implicit params in instances is a bit subtle
939         -- If we allowed        instance (?x::Int, Eq a) => Foo [a] where ...
940         -- then when we saw (e :: (?x::Int) => t) it would be unclear how to 
941         -- discharge all the potential usas of the ?x in e.   For example, a
942         -- constraint Foo [Int] might come out of e,and applying the
943         -- instance decl would show up two uses of ?x.
944
945 -- Catch-all
946 check_pred_ty dflags ctxt sty = failWithTc (badPredTyErr sty)
947
948 -------------------------
949 check_class_pred_tys dflags ctxt tys 
950   = case ctxt of
951         TypeCtxt      -> True   -- {-# SPECIALISE instance Eq (T Int) #-} is fine
952         InstThetaCtxt -> gla_exts || undecidable_ok || all tcIsTyVarTy tys
953                                 -- Further checks on head and theta in
954                                 -- checkInstTermination
955         other         -> gla_exts || all tyvar_head tys
956   where
957     gla_exts       = dopt Opt_GlasgowExts dflags
958     undecidable_ok = dopt Opt_AllowUndecidableInstances dflags
959
960 -------------------------
961 tyvar_head ty                   -- Haskell 98 allows predicates of form 
962   | tcIsTyVarTy ty = True       --      C (a ty1 .. tyn)
963   | otherwise                   -- where a is a type variable
964   = case tcSplitAppTy_maybe ty of
965         Just (ty, _) -> tyvar_head ty
966         Nothing      -> False
967 \end{code}
968
969 Check for ambiguity
970 ~~~~~~~~~~~~~~~~~~~
971           forall V. P => tau
972 is ambiguous if P contains generic variables
973 (i.e. one of the Vs) that are not mentioned in tau
974
975 However, we need to take account of functional dependencies
976 when we speak of 'mentioned in tau'.  Example:
977         class C a b | a -> b where ...
978 Then the type
979         forall x y. (C x y) => x
980 is not ambiguous because x is mentioned and x determines y
981
982 NB; the ambiguity check is only used for *user* types, not for types
983 coming from inteface files.  The latter can legitimately have
984 ambiguous types. Example
985
986    class S a where s :: a -> (Int,Int)
987    instance S Char where s _ = (1,1)
988    f:: S a => [a] -> Int -> (Int,Int)
989    f (_::[a]) x = (a*x,b)
990         where (a,b) = s (undefined::a)
991
992 Here the worker for f gets the type
993         fw :: forall a. S a => Int -> (# Int, Int #)
994
995 If the list of tv_names is empty, we have a monotype, and then we
996 don't need to check for ambiguity either, because the test can't fail
997 (see is_ambig).
998
999 \begin{code}
1000 checkAmbiguity :: [TyVar] -> ThetaType -> TyVarSet -> TcM ()
1001 checkAmbiguity forall_tyvars theta tau_tyvars
1002   = mappM_ complain (filter is_ambig theta)
1003   where
1004     complain pred     = addErrTc (ambigErr pred)
1005     extended_tau_vars = grow theta tau_tyvars
1006
1007         -- Only a *class* predicate can give rise to ambiguity
1008         -- An *implicit parameter* cannot.  For example:
1009         --      foo :: (?x :: [a]) => Int
1010         --      foo = length ?x
1011         -- is fine.  The call site will suppply a particular 'x'
1012     is_ambig pred     = isClassPred  pred &&
1013                         any ambig_var (varSetElems (tyVarsOfPred pred))
1014
1015     ambig_var ct_var  = (ct_var `elem` forall_tyvars) &&
1016                         not (ct_var `elemVarSet` extended_tau_vars)
1017
1018 ambigErr pred
1019   = sep [ptext SLIT("Ambiguous constraint") <+> quotes (pprPred pred),
1020          nest 4 (ptext SLIT("At least one of the forall'd type variables mentioned by the constraint") $$
1021                  ptext SLIT("must be reachable from the type after the '=>'"))]
1022 \end{code}
1023     
1024 In addition, GHC insists that at least one type variable
1025 in each constraint is in V.  So we disallow a type like
1026         forall a. Eq b => b -> b
1027 even in a scope where b is in scope.
1028
1029 \begin{code}
1030 checkFreeness forall_tyvars theta
1031   = do  { gla_exts <- doptM Opt_GlasgowExts
1032         ; if gla_exts then return ()    -- New!  Oct06
1033           else mappM_ complain (filter is_free theta) }
1034   where    
1035     is_free pred     =  not (isIPPred pred)
1036                      && not (any bound_var (varSetElems (tyVarsOfPred pred)))
1037     bound_var ct_var = ct_var `elem` forall_tyvars
1038     complain pred    = addErrTc (freeErr pred)
1039
1040 freeErr pred
1041   = sep [ptext SLIT("All of the type variables in the constraint") <+> quotes (pprPred pred) <+>
1042                    ptext SLIT("are already in scope"),
1043          nest 4 (ptext SLIT("(at least one must be universally quantified here)"))
1044     ]
1045 \end{code}
1046
1047 \begin{code}
1048 checkThetaCtxt ctxt theta
1049   = vcat [ptext SLIT("In the context:") <+> pprTheta theta,
1050           ptext SLIT("While checking") <+> pprSourceTyCtxt ctxt ]
1051
1052 badPredTyErr sty = ptext SLIT("Illegal constraint") <+> pprPred sty
1053 predTyVarErr pred  = sep [ptext SLIT("Non type-variable argument"),
1054                           nest 2 (ptext SLIT("in the constraint:") <+> pprPred pred)]
1055 dupPredWarn dups   = ptext SLIT("Duplicate constraint(s):") <+> pprWithCommas pprPred (map head dups)
1056
1057 arityErr kind name n m
1058   = hsep [ text kind, quotes (ppr name), ptext SLIT("should have"),
1059            n_arguments <> comma, text "but has been given", int m]
1060     where
1061         n_arguments | n == 0 = ptext SLIT("no arguments")
1062                     | n == 1 = ptext SLIT("1 argument")
1063                     | True   = hsep [int n, ptext SLIT("arguments")]
1064 \end{code}
1065
1066
1067 %************************************************************************
1068 %*                                                                      *
1069 \subsection{Checking for a decent instance head type}
1070 %*                                                                      *
1071 %************************************************************************
1072
1073 @checkValidInstHead@ checks the type {\em and} its syntactic constraints:
1074 it must normally look like: @instance Foo (Tycon a b c ...) ...@
1075
1076 The exceptions to this syntactic checking: (1)~if the @GlasgowExts@
1077 flag is on, or (2)~the instance is imported (they must have been
1078 compiled elsewhere). In these cases, we let them go through anyway.
1079
1080 We can also have instances for functions: @instance Foo (a -> b) ...@.
1081
1082 \begin{code}
1083 checkValidInstHead :: Type -> TcM (Class, [TcType])
1084
1085 checkValidInstHead ty   -- Should be a source type
1086   = case tcSplitPredTy_maybe ty of {
1087         Nothing -> failWithTc (instTypeErr (ppr ty) empty) ;
1088         Just pred -> 
1089
1090     case getClassPredTys_maybe pred of {
1091         Nothing -> failWithTc (instTypeErr (pprPred pred) empty) ;
1092         Just (clas,tys) ->
1093
1094     getDOpts                                    `thenM` \ dflags ->
1095     mappM_ check_arg_type tys                   `thenM_`
1096     check_inst_head dflags clas tys             `thenM_`
1097     returnM (clas, tys)
1098     }}
1099
1100 check_inst_head dflags clas tys
1101         -- If GlasgowExts then check at least one isn't a type variable
1102   | dopt Opt_GlasgowExts dflags
1103   = mapM_ check_one tys
1104
1105         -- WITH HASKELL 98, MUST HAVE C (T a b c)
1106   | otherwise
1107   = checkTc (isSingleton tys && tcValidInstHeadTy first_ty)
1108             (instTypeErr (pprClassPred clas tys) head_shape_msg)
1109
1110   where
1111     (first_ty : _) = tys
1112
1113     head_shape_msg = parens (text "The instance type must be of form (T a b c)" $$
1114                              text "where T is not a synonym, and a,b,c are distinct type variables")
1115
1116         -- For now, I only allow tau-types (not polytypes) in 
1117         -- the head of an instance decl.  
1118         --      E.g.  instance C (forall a. a->a) is rejected
1119         -- One could imagine generalising that, but I'm not sure
1120         -- what all the consequences might be
1121     check_one ty = do { check_tau_type (Rank 0) UT_NotOk ty
1122                       ; checkTc (not (isUnLiftedType ty)) (unliftedArgErr ty) }
1123
1124 instTypeErr pp_ty msg
1125   = sep [ptext SLIT("Illegal instance declaration for") <+> quotes pp_ty, 
1126          nest 4 msg]
1127 \end{code}
1128
1129
1130 %************************************************************************
1131 %*                                                                      *
1132 \subsection{Checking instance for termination}
1133 %*                                                                      *
1134 %************************************************************************
1135
1136
1137 \begin{code}
1138 checkValidInstance :: [TyVar] -> ThetaType -> Class -> [TcType] -> TcM ()
1139 checkValidInstance tyvars theta clas inst_tys
1140   = do  { gla_exts <- doptM Opt_GlasgowExts
1141         ; undecidable_ok <- doptM Opt_AllowUndecidableInstances
1142
1143         ; checkValidTheta InstThetaCtxt theta
1144         ; checkAmbiguity tyvars theta (tyVarsOfTypes inst_tys)
1145
1146         -- Check that instance inference will terminate (if we care)
1147         -- For Haskell 98, checkValidTheta has already done that
1148         ; when (gla_exts && not undecidable_ok) $
1149           mapM_ failWithTc (checkInstTermination inst_tys theta)
1150         
1151         -- The Coverage Condition
1152         ; checkTc (undecidable_ok || checkInstCoverage clas inst_tys)
1153                   (instTypeErr (pprClassPred clas inst_tys) msg)
1154         }
1155   where
1156     msg  = parens (vcat [ptext SLIT("the Coverage Condition fails for one of the functional dependencies;"),
1157                          undecidableMsg])
1158 \end{code}
1159
1160 Termination test: each assertion in the context satisfies
1161  (1) no variable has more occurrences in the assertion than in the head, and
1162  (2) the assertion has fewer constructors and variables (taken together
1163      and counting repetitions) than the head.
1164 This is only needed with -fglasgow-exts, as Haskell 98 restrictions
1165 (which have already been checked) guarantee termination. 
1166
1167 The underlying idea is that 
1168
1169     for any ground substitution, each assertion in the
1170     context has fewer type constructors than the head.
1171
1172
1173 \begin{code}
1174 checkInstTermination :: [TcType] -> ThetaType -> [Message]
1175 checkInstTermination tys theta
1176   = mapCatMaybes check theta
1177   where
1178    fvs  = fvTypes tys
1179    size = sizeTypes tys
1180    check pred 
1181       | not (null (fvPred pred \\ fvs)) 
1182       = Just (predUndecErr pred nomoreMsg $$ parens undecidableMsg)
1183       | sizePred pred >= size
1184       = Just (predUndecErr pred smallerMsg $$ parens undecidableMsg)
1185       | otherwise
1186       = Nothing
1187
1188 predUndecErr pred msg = sep [msg,
1189                         nest 2 (ptext SLIT("in the constraint:") <+> pprPred pred)]
1190
1191 nomoreMsg = ptext SLIT("Variable occurs more often in a constraint than in the instance head")
1192 smallerMsg = ptext SLIT("Constraint is no smaller than the instance head")
1193 undecidableMsg = ptext SLIT("Use -fallow-undecidable-instances to permit this")
1194
1195 -- Free variables of a type, retaining repetitions, and expanding synonyms
1196 fvType :: Type -> [TyVar]
1197 fvType ty | Just exp_ty <- tcView ty = fvType exp_ty
1198 fvType (TyVarTy tv)        = [tv]
1199 fvType (TyConApp _ tys)    = fvTypes tys
1200 fvType (NoteTy _ ty)       = fvType ty
1201 fvType (PredTy pred)       = fvPred pred
1202 fvType (FunTy arg res)     = fvType arg ++ fvType res
1203 fvType (AppTy fun arg)     = fvType fun ++ fvType arg
1204 fvType (ForAllTy tyvar ty) = filter (/= tyvar) (fvType ty)
1205
1206 fvTypes :: [Type] -> [TyVar]
1207 fvTypes tys                = concat (map fvType tys)
1208
1209 fvPred :: PredType -> [TyVar]
1210 fvPred (ClassP _ tys')     = fvTypes tys'
1211 fvPred (IParam _ ty)       = fvType ty
1212 fvPred (EqPred ty1 ty2)    = fvType ty1 ++ fvType ty2
1213
1214 -- Size of a type: the number of variables and constructors
1215 sizeType :: Type -> Int
1216 sizeType ty | Just exp_ty <- tcView ty = sizeType exp_ty
1217 sizeType (TyVarTy _)       = 1
1218 sizeType (TyConApp _ tys)  = sizeTypes tys + 1
1219 sizeType (NoteTy _ ty)     = sizeType ty
1220 sizeType (PredTy pred)     = sizePred pred
1221 sizeType (FunTy arg res)   = sizeType arg + sizeType res + 1
1222 sizeType (AppTy fun arg)   = sizeType fun + sizeType arg
1223 sizeType (ForAllTy _ ty)   = sizeType ty
1224
1225 sizeTypes :: [Type] -> Int
1226 sizeTypes xs               = sum (map sizeType xs)
1227
1228 sizePred :: PredType -> Int
1229 sizePred (ClassP _ tys')   = sizeTypes tys'
1230 sizePred (IParam _ ty)     = sizeType ty
1231 sizePred (EqPred ty1 ty2)  = sizeType ty1 + sizeType ty2
1232 \end{code}