47592f53898796d024ab54bca76acab194be40e7
[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
23   newMetaTyVar, readMetaTyVar, writeMetaTyVar, isFilledMetaTyVar,
24
25   --------------------------------
26   -- Boxy type variables
27   newBoxyTyVar, newBoxyTyVars, newBoxyTyVarTys, readFilledBox, 
28
29   --------------------------------
30   -- Creating new coercion variables
31   newCoVars, newMetaCoVar,
32
33   --------------------------------
34   -- Instantiation
35   tcInstTyVar, tcInstType, tcInstTyVars, tcInstBoxyTyVar,
36   tcInstSigType,
37   tcInstSkolTyVars, tcInstSkolType, 
38   tcSkolSigType, tcSkolSigTyVars, occurCheckErr,
39
40   --------------------------------
41   -- Checking type validity
42   Rank, UserTypeCtxt(..), checkValidType, checkValidMonoType,
43   SourceTyCtxt(..), checkValidTheta, checkFreeness,
44   checkValidInstHead, checkValidInstance, 
45   checkInstTermination, checkValidTypeInst, checkTyFamFreeness,
46   checkUpdateMeta, updateMeta, checkTauTvUpdate, fillBoxWithTau, unifyKindCtxt,
47   unifyKindMisMatch, validDerivPred, arityErr, notMonoType, notMonoArgs,
48
49   --------------------------------
50   -- Zonking
51   zonkType, zonkTcPredType, 
52   zonkTcTyVar, zonkTcTyVars, zonkTcTyVarsAndFV, zonkSigTyVar,
53   zonkQuantifiedTyVar, zonkQuantifiedTyVars,
54   zonkTcType, zonkTcTypes, zonkTcThetaType,
55   zonkTcKindToKind, zonkTcKind, zonkTopTyVar,
56
57   readKindVar, writeKindVar
58   ) where
59
60 #include "HsVersions.h"
61
62 -- friends:
63 import TypeRep
64 import TcType
65 import Type
66 import Coercion
67 import Class
68 import TyCon
69 import Var
70
71 -- others:
72 import TcRnMonad          -- TcType, amongst others
73 import FunDeps
74 import Name
75 import VarEnv
76 import VarSet
77 import ErrUtils
78 import DynFlags
79 import Util
80 import Maybes
81 import ListSetOps
82 import UniqSupply
83 import SrcLoc
84 import Outputable
85 import FastString
86
87 import Control.Monad
88 import Data.List        ( (\\) )
89 \end{code}
90
91
92 %************************************************************************
93 %*                                                                      *
94         Instantiation in general
95 %*                                                                      *
96 %************************************************************************
97
98 \begin{code}
99 tcInstType :: ([TyVar] -> TcM [TcTyVar])                -- How to instantiate the type variables
100            -> TcType                                    -- Type to instantiate
101            -> TcM ([TcTyVar], TcThetaType, TcType)      -- Result
102                 -- (type vars (excl coercion vars), preds (incl equalities), rho)
103 tcInstType inst_tyvars ty
104   = case tcSplitForAllTys ty of
105         ([],     rho) -> let    -- There may be overloading despite no type variables;
106                                 --      (?x :: Int) => Int -> Int
107                            (theta, tau) = tcSplitPhiTy rho
108                          in
109                          return ([], theta, tau)
110
111         (tyvars, rho) -> do { tyvars' <- inst_tyvars tyvars
112
113                             ; let  tenv = zipTopTvSubst tyvars (mkTyVarTys tyvars')
114                                 -- Either the tyvars are freshly made, by inst_tyvars,
115                                 -- or (in the call from tcSkolSigType) any nested foralls
116                                 -- have different binders.  Either way, zipTopTvSubst is ok
117
118                             ; let  (theta, tau) = tcSplitPhiTy (substTy tenv rho)
119                             ; return (tyvars', theta, tau) }
120 \end{code}
121
122
123 %************************************************************************
124 %*                                                                      *
125         Updating tau types
126 %*                                                                      *
127 %************************************************************************
128
129 Can't be in TcUnify, as we also need it in TcTyFuns.
130
131 \begin{code}
132 type SwapFlag = Bool
133         -- False <=> the two args are (actual, expected) respectively
134         -- True  <=> the two args are (expected, actual) respectively
135
136 checkUpdateMeta :: SwapFlag
137                 -> TcTyVar -> IORef MetaDetails -> TcType -> TcM ()
138 -- Update tv1, which is flexi; occurs check is alrady done
139 -- The 'check' version does a kind check too
140 -- We do a sub-kind check here: we might unify (a b) with (c d) 
141 --      where b::*->* and d::*; this should fail
142
143 checkUpdateMeta swapped tv1 ref1 ty2
144   = do  { checkKinds swapped tv1 ty2
145         ; updateMeta tv1 ref1 ty2 }
146
147 updateMeta :: TcTyVar -> IORef MetaDetails -> TcType -> TcM ()
148 updateMeta tv1 ref1 ty2
149   = ASSERT( isMetaTyVar tv1 )
150     ASSERT( isBoxyTyVar tv1 || isTauTy ty2 )
151     do  { ASSERTM2( do { details <- readMetaTyVar tv1; return (isFlexi details) }, ppr tv1 )
152         ; traceTc (text "updateMeta" <+> ppr tv1 <+> text ":=" <+> ppr ty2)
153         ; writeMutVar ref1 (Indirect ty2) 
154         }
155
156 ----------------
157 checkKinds :: Bool -> TyVar -> Type -> TcM ()
158 checkKinds swapped tv1 ty2
159 -- We're about to unify a type variable tv1 with a non-tyvar-type ty2.
160 -- ty2 has been zonked at this stage, which ensures that
161 -- its kind has as much boxity information visible as possible.
162   | tk2 `isSubKind` tk1 = return ()
163
164   | otherwise
165         -- Either the kinds aren't compatible
166         --      (can happen if we unify (a b) with (c d))
167         -- or we are unifying a lifted type variable with an
168         --      unlifted type: e.g.  (id 3#) is illegal
169   = addErrCtxtM (unifyKindCtxt swapped tv1 ty2) $
170     unifyKindMisMatch k1 k2
171   where
172     (k1,k2) | swapped   = (tk2,tk1)
173             | otherwise = (tk1,tk2)
174     tk1 = tyVarKind tv1
175     tk2 = typeKind ty2
176
177 ----------------
178 checkTauTvUpdate :: TcTyVar -> TcType -> TcM (Maybe TcType)
179 --    (checkTauTvUpdate tv ty)
180 -- We are about to update the TauTv tv with ty.
181 -- Check (a) that tv doesn't occur in ty (occurs check)
182 --       (b) that ty is a monotype
183 -- Furthermore, in the interest of (b), if you find an
184 -- empty box (BoxTv that is Flexi), fill it in with a TauTv
185 -- 
186 -- We have three possible outcomes:
187 -- (1) Return the (non-boxy) type to update the type variable with, 
188 --     [we know the update is ok!]
189 -- (2) return Nothing, or 
190 --     [we cannot tell whether the update is ok right now]
191 -- (3) fails.
192 --     [the update is definitely invalid]
193 -- We return Nothing in case the tv occurs in ty *under* a type family
194 -- application.  In this case, we must not update tv (to avoid a cyclic type
195 -- term), but we also cannot fail claiming an infinite type.  Given
196 --   type family F a
197 --   type instance F Int = Int
198 -- consider
199 --   a ~ F a
200 -- This is perfectly reasonable, if we later get a ~ Int.
201
202 checkTauTvUpdate orig_tv orig_ty
203   = do { result <- go orig_ty
204        ; case result of 
205            Right ty    -> return $ Just ty
206            Left  True  -> return $ Nothing
207            Left  False -> occurCheckErr (mkTyVarTy orig_tv) orig_ty
208        }
209   where
210     go :: TcType -> TcM (Either Bool TcType)
211     -- go returns
212     --   Right ty    if everything is fine
213     --   Left True   if orig_tv occurs in orig_ty, but under a type family app
214     --   Left False  if orig_tv occurs in orig_ty (with no type family app)
215     -- It fails if it encounters a forall type, except as an argument for a
216     -- closed type synonym that expands to a tau type.
217     go (TyConApp tc tys)
218         | isSynTyCon tc  = go_syn tc tys
219         | otherwise      = do { tys' <- mapM go tys
220                               ; return $ occurs (TyConApp tc) tys' }
221     go (PredTy p)             = do { p' <- go_pred p
222                               ; return $ occurs1 PredTy p' }
223     go (FunTy arg res)   = do { arg' <- go arg
224                               ; res' <- go res
225                               ; return $ occurs2 FunTy arg' res' }
226     go (AppTy fun arg)   = do { fun' <- go fun
227                               ; arg' <- go arg
228                               ; return $ occurs2 mkAppTy fun' arg' }
229                 -- NB the mkAppTy; we might have instantiated a
230                 -- type variable to a type constructor, so we need
231                 -- to pull the TyConApp to the top.
232     go (ForAllTy _ _) = notMonoType orig_ty             -- (b)
233
234     go (TyVarTy tv)
235         | orig_tv == tv = return $ Left False           -- (a)
236         | isTcTyVar tv  = go_tyvar tv (tcTyVarDetails tv)
237         | otherwise     = return $ Right (TyVarTy tv)
238                  -- Ordinary (non Tc) tyvars
239                  -- occur inside quantified types
240
241     go_pred (ClassP c tys) = do { tys' <- mapM go tys
242                                 ; return $ occurs (ClassP c) tys' }
243     go_pred (IParam n ty)  = do { ty' <- go ty
244                                 ; return $ occurs1 (IParam n) ty' }
245     go_pred (EqPred t1 t2) = do { t1' <- go t1
246                                 ; t2' <- go t2
247                                 ; return $ occurs2 EqPred t1' t2' }
248
249     go_tyvar tv (SkolemTv _) = return $ Right (TyVarTy tv)
250     go_tyvar tv (MetaTv box ref)
251         = do { cts <- readMutVar ref
252              ; case cts of
253                   Indirect ty -> go ty 
254                   Flexi -> case box of
255                                 BoxTv -> do { ty <- fillBoxWithTau tv ref
256                                             ; return $ Right ty }
257                                 _     -> return $ Right (TyVarTy tv)
258              }
259
260         -- go_syn is called for synonyms only
261         -- See Note [Type synonyms and the occur check]
262     go_syn tc tys
263         | not (isTauTyCon tc)
264         = notMonoType orig_ty   -- (b) again
265         | otherwise
266         = do { (_msgs, mb_tys') <- tryTc (mapM go tys)
267              ; case mb_tys' of
268
269                 -- we had a type error => forall in type parameters
270                 Nothing 
271                   | isOpenTyCon tc -> notMonoArgs (TyConApp tc tys)
272                         -- Synonym families must have monotype args
273                   | otherwise      -> go (expectJust "checkTauTvUpdate(1)" 
274                                             (tcView (TyConApp tc tys)))
275                         -- Try again, expanding the synonym
276
277                 -- no type error, but need to test whether occurs check happend
278                 Just tys' -> 
279                   case occurs id tys' of
280                     Left _ 
281                       | isOpenTyCon tc -> return $ Left True
282                         -- Variable occured under type family application
283                       | otherwise      -> go (expectJust "checkTauTvUpdate(2)" 
284                                                (tcView (TyConApp tc tys)))
285                         -- Try again, expanding the synonym
286                     Right raw_tys'     -> return $ Right (TyConApp tc raw_tys')
287                         -- Retain the synonym (the common case)
288              }
289
290     -- Left results (= occurrence of orig_ty) dominate and
291     -- (Left False) (= fatal occurrence) dominates over (Left True)
292     occurs :: ([a] -> b) -> [Either Bool a] -> Either Bool b
293     occurs c = either Left (Right . c) . foldr combine (Right [])
294       where
295         combine (Left famInst1) (Left famInst2) = Left (famInst1 && famInst2)
296         combine (Right _      ) (Left famInst)  = Left famInst
297         combine (Left famInst)  (Right _)       = Left famInst
298         combine (Right arg)     (Right args)    = Right (arg:args)
299
300     occurs1 c x   = occurs (\[x']     -> c x')    [x]
301     occurs2 c x y = occurs (\[x', y'] -> c x' y') [x, y]
302
303 fillBoxWithTau :: BoxyTyVar -> IORef MetaDetails -> TcM TcType
304 -- (fillBoxWithTau tv ref) fills ref with a freshly allocated 
305 --  tau-type meta-variable, whose print-name is the same as tv
306 -- Choosing the same name is good: when we instantiate a function
307 -- we allocate boxy tyvars with the same print-name as the quantified
308 -- tyvar; and then we often fill the box with a tau-tyvar, and again
309 -- we want to choose the same name.
310 fillBoxWithTau tv ref 
311   = do  { tv' <- tcInstTyVar tv         -- Do not gratuitously forget
312         ; let tau = mkTyVarTy tv'       -- name of the type variable
313         ; writeMutVar ref (Indirect tau)
314         ; return tau }
315 \end{code}
316
317 Note [Type synonyms and the occur check]
318 ~~~~~~~~~~~~~~~~~~~~
319 Basically we want to update     tv1 := ps_ty2
320 because ps_ty2 has type-synonym info, which improves later error messages
321
322 But consider 
323         type A a = ()
324
325         f :: (A a -> a -> ()) -> ()
326         f = \ _ -> ()
327
328         x :: ()
329         x = f (\ x p -> p x)
330
331 In the application (p x), we try to match "t" with "A t".  If we go
332 ahead and bind t to A t (= ps_ty2), we'll lead the type checker into 
333 an infinite loop later.
334 But we should not reject the program, because A t = ().
335 Rather, we should bind t to () (= non_var_ty2).
336
337 --------------
338
339 Error mesages in case of kind mismatch.
340
341 \begin{code}
342 unifyKindMisMatch :: TcKind -> TcKind -> TcM ()
343 unifyKindMisMatch ty1 ty2 = do
344     ty1' <- zonkTcKind ty1
345     ty2' <- zonkTcKind ty2
346     let
347         msg = hang (ptext (sLit "Couldn't match kind"))
348                    2 (sep [quotes (ppr ty1'), 
349                            ptext (sLit "against"), 
350                            quotes (ppr ty2')])
351     failWithTc msg
352
353 unifyKindCtxt :: Bool -> TyVar -> Type -> TidyEnv -> TcM (TidyEnv, SDoc)
354 unifyKindCtxt swapped tv1 ty2 tidy_env  -- not swapped => tv1 expected, ty2 inferred
355         -- tv1 and ty2 are zonked already
356   = return msg
357   where
358     msg = (env2, ptext (sLit "When matching the kinds of") <+> 
359                  sep [quotes pp_expected <+> ptext (sLit "and"), quotes pp_actual])
360
361     (pp_expected, pp_actual) | swapped   = (pp2, pp1)
362                              | otherwise = (pp1, pp2)
363     (env1, tv1') = tidyOpenTyVar tidy_env tv1
364     (env2, ty2') = tidyOpenType  env1 ty2
365     pp1 = ppr tv1' <+> dcolon <+> ppr (tyVarKind tv1)
366     pp2 = ppr ty2' <+> dcolon <+> ppr (typeKind ty2)
367 \end{code}
368
369 Error message for failure due to an occurs check.
370
371 \begin{code}
372 occurCheckErr :: TcType -> TcType -> TcM a
373 occurCheckErr ty containingTy
374   = do  { env0 <- tcInitTidyEnv
375         ; ty'           <- zonkTcType ty
376         ; containingTy' <- zonkTcType containingTy
377         ; let (env1, tidy_ty1) = tidyOpenType env0 ty'
378               (env2, tidy_ty2) = tidyOpenType env1 containingTy'
379               extra = sep [ppr tidy_ty1, char '=', ppr tidy_ty2]
380         ; failWithTcM (env2, hang msg 2 extra) }
381   where
382     msg = ptext (sLit "Occurs check: cannot construct the infinite type:")
383 \end{code}
384
385 %************************************************************************
386 %*                                                                      *
387         Kind variables
388 %*                                                                      *
389 %************************************************************************
390
391 \begin{code}
392 newCoVars :: [(TcType,TcType)] -> TcM [CoVar]
393 newCoVars spec
394   = do  { us <- newUniqueSupply 
395         ; return [ mkCoVar (mkSysTvName uniq (fsLit "co"))
396                            (mkCoKind ty1 ty2)
397                  | ((ty1,ty2), uniq) <- spec `zip` uniqsFromSupply us] }
398
399 newMetaCoVar :: TcType -> TcType -> TcM TcTyVar
400 newMetaCoVar ty1 ty2 = newMetaTyVar TauTv (mkCoKind ty1 ty2)
401
402 newKindVar :: TcM TcKind
403 newKindVar = do { uniq <- newUnique
404                 ; ref <- newMutVar Flexi
405                 ; return (mkTyVarTy (mkKindVar uniq ref)) }
406
407 newKindVars :: Int -> TcM [TcKind]
408 newKindVars n = mapM (\ _ -> newKindVar) (nOfThem n ())
409 \end{code}
410
411
412 %************************************************************************
413 %*                                                                      *
414         SkolemTvs (immutable)
415 %*                                                                      *
416 %************************************************************************
417
418 \begin{code}
419 mkSkolTyVar :: Name -> Kind -> SkolemInfo -> TcTyVar
420 mkSkolTyVar name kind info = mkTcTyVar name kind (SkolemTv info)
421
422 tcSkolSigType :: SkolemInfo -> Type -> TcM ([TcTyVar], TcThetaType, TcType)
423 -- Instantiate a type signature with skolem constants, but 
424 -- do *not* give them fresh names, because we want the name to
425 -- be in the type environment -- it is lexically scoped.
426 tcSkolSigType info ty = tcInstType (\tvs -> return (tcSkolSigTyVars info tvs)) ty
427
428 tcSkolSigTyVars :: SkolemInfo -> [TyVar] -> [TcTyVar]
429 -- Make skolem constants, but do *not* give them new names, as above
430 tcSkolSigTyVars info tyvars = [ mkSkolTyVar (tyVarName tv) (tyVarKind tv) info
431                               | tv <- tyvars ]
432
433 tcInstSkolTyVar :: SkolemInfo -> (Name -> SrcSpan) -> TyVar -> TcM TcTyVar
434 -- Instantiate the tyvar, using 
435 --      * the occ-name and kind of the supplied tyvar, 
436 --      * the unique from the monad,
437 --      * the location either from the tyvar (mb_loc = Nothing)
438 --        or from mb_loc (Just loc)
439 tcInstSkolTyVar info get_loc tyvar
440   = do  { uniq <- newUnique
441         ; let old_name = tyVarName tyvar
442               kind     = tyVarKind tyvar
443               loc      = get_loc old_name
444               new_name = mkInternalName uniq (nameOccName old_name) loc
445         ; return (mkSkolTyVar new_name kind info) }
446
447 tcInstSkolTyVars :: SkolemInfo -> [TyVar] -> TcM [TcTyVar]
448 -- Get the location from the monad
449 tcInstSkolTyVars info tyvars 
450   = do  { span <- getSrcSpanM
451         ; mapM (tcInstSkolTyVar info (const span)) tyvars }
452
453 tcInstSkolType :: SkolemInfo -> TcType -> TcM ([TcTyVar], TcThetaType, TcType)
454 -- Instantiate a type with fresh skolem constants
455 -- Binding location comes from the monad
456 tcInstSkolType info ty = tcInstType (tcInstSkolTyVars info) ty
457
458 tcInstSigType :: Bool -> SkolemInfo -> TcType -> TcM ([TcTyVar], TcThetaType, TcRhoType)
459 -- Instantiate with skolems or meta SigTvs; depending on use_skols
460 -- Always take location info from the supplied tyvars
461 tcInstSigType use_skols skol_info ty
462   = tcInstType (mapM inst_tyvar) ty
463   where
464     inst_tyvar | use_skols = tcInstSkolTyVar skol_info getSrcSpan
465                | otherwise = instMetaTyVar (SigTv skol_info)
466 \end{code}
467
468
469 %************************************************************************
470 %*                                                                      *
471         MetaTvs (meta type variables; mutable)
472 %*                                                                      *
473 %************************************************************************
474
475 \begin{code}
476 newMetaTyVar :: BoxInfo -> Kind -> TcM TcTyVar
477 -- Make a new meta tyvar out of thin air
478 newMetaTyVar box_info kind
479   = do  { uniq <- newUnique
480         ; ref <- newMutVar Flexi
481         ; let name = mkSysTvName uniq fs 
482               fs = case box_info of
483                         BoxTv   -> fsLit "t"
484                         TauTv   -> fsLit "t"
485                         SigTv _ -> fsLit "a"
486                 -- We give BoxTv and TauTv the same string, because
487                 -- otherwise we get user-visible differences in error
488                 -- messages, which are confusing.  If you want to see
489                 -- the box_info of each tyvar, use -dppr-debug
490         ; return (mkTcTyVar name kind (MetaTv box_info ref)) }
491
492 instMetaTyVar :: BoxInfo -> TyVar -> TcM TcTyVar
493 -- Make a new meta tyvar whose Name and Kind 
494 -- come from an existing TyVar
495 instMetaTyVar box_info tyvar
496   = do  { uniq <- newUnique
497         ; ref <- newMutVar Flexi
498         ; let name = setNameUnique (tyVarName tyvar) uniq
499               kind = tyVarKind tyvar
500         ; return (mkTcTyVar name kind (MetaTv box_info ref)) }
501
502 readMetaTyVar :: TyVar -> TcM MetaDetails
503 readMetaTyVar tyvar = ASSERT2( isMetaTyVar tyvar, ppr tyvar )
504                       readMutVar (metaTvRef tyvar)
505
506 isFilledMetaTyVar :: TyVar -> TcM Bool
507 -- True of a filled-in (Indirect) meta type variable
508 isFilledMetaTyVar tv
509   | not (isTcTyVar tv) = return False
510   | MetaTv _ ref <- tcTyVarDetails tv
511   = do  { details <- readMutVar ref
512         ; return (isIndirect details) }
513   | otherwise = return False
514
515 writeMetaTyVar :: TcTyVar -> TcType -> TcM ()
516 writeMetaTyVar tyvar ty
517   | not debugIsOn = writeMutVar (metaTvRef tyvar) (Indirect ty)
518 writeMetaTyVar tyvar ty
519   | not (isMetaTyVar tyvar)
520   = pprTrace "writeMetaTyVar" (ppr tyvar) $
521     return ()
522   | otherwise
523   = ASSERT( isMetaTyVar tyvar )
524     -- TOM: It should also work for coercions
525     -- ASSERT2( k2 `isSubKind` k1, (ppr tyvar <+> ppr k1) $$ (ppr ty <+> ppr k2) )
526     do  { if debugIsOn then do { details <- readMetaTyVar tyvar; 
527                                ; WARN( not (isFlexi details), ppr tyvar )
528                                  return () }
529                         else return () 
530                 -- Temporarily make this a warning, until we fix Trac #2999
531
532         ; traceTc (text "writeMetaTyVar" <+> ppr tyvar <+> text ":=" <+> ppr ty)
533         ; writeMutVar (metaTvRef tyvar) (Indirect ty) }
534   where
535     _k1 = tyVarKind tyvar
536     _k2 = typeKind ty
537 \end{code}
538
539
540 %************************************************************************
541 %*                                                                      *
542         MetaTvs: TauTvs
543 %*                                                                      *
544 %************************************************************************
545
546 \begin{code}
547 newFlexiTyVar :: Kind -> TcM TcTyVar
548 newFlexiTyVar kind = newMetaTyVar TauTv kind
549
550 newFlexiTyVarTy  :: Kind -> TcM TcType
551 newFlexiTyVarTy kind = do
552     tc_tyvar <- newFlexiTyVar kind
553     return (TyVarTy tc_tyvar)
554
555 newFlexiTyVarTys :: Int -> Kind -> TcM [TcType]
556 newFlexiTyVarTys n kind = mapM newFlexiTyVarTy (nOfThem n kind)
557
558 tcInstTyVar :: TyVar -> TcM TcTyVar
559 -- Instantiate with a META type variable
560 tcInstTyVar tyvar = instMetaTyVar TauTv tyvar
561
562 tcInstTyVars :: [TyVar] -> TcM ([TcTyVar], [TcType], TvSubst)
563 -- Instantiate with META type variables
564 tcInstTyVars tyvars
565   = do  { tc_tvs <- mapM tcInstTyVar tyvars
566         ; let tys = mkTyVarTys tc_tvs
567         ; return (tc_tvs, tys, zipTopTvSubst tyvars tys) }
568                 -- Since the tyvars are freshly made,
569                 -- they cannot possibly be captured by
570                 -- any existing for-alls.  Hence zipTopTvSubst
571 \end{code}
572
573
574 %************************************************************************
575 %*                                                                      *
576         MetaTvs: SigTvs
577 %*                                                                      *
578 %************************************************************************
579
580 \begin{code}
581 zonkSigTyVar :: TcTyVar -> TcM TcTyVar
582 zonkSigTyVar sig_tv 
583   | isSkolemTyVar sig_tv 
584   = return sig_tv       -- Happens in the call in TcBinds.checkDistinctTyVars
585   | otherwise
586   = ASSERT( isSigTyVar sig_tv )
587     do { ty <- zonkTcTyVar sig_tv
588        ; return (tcGetTyVar "zonkSigTyVar" ty) }
589         -- 'ty' is bound to be a type variable, because SigTvs
590         -- can only be unified with type variables
591 \end{code}
592
593
594 %************************************************************************
595 %*                                                                      *
596         MetaTvs: BoxTvs
597 %*                                                                      *
598 %************************************************************************
599
600 \begin{code}
601 newBoxyTyVar :: Kind -> TcM BoxyTyVar
602 newBoxyTyVar kind = newMetaTyVar BoxTv kind
603
604 newBoxyTyVars :: [Kind] -> TcM [BoxyTyVar]
605 newBoxyTyVars kinds = mapM newBoxyTyVar kinds
606
607 newBoxyTyVarTys :: [Kind] -> TcM [BoxyType]
608 newBoxyTyVarTys kinds = do { tvs <- mapM newBoxyTyVar kinds; return (mkTyVarTys tvs) }
609
610 readFilledBox :: BoxyTyVar -> TcM TcType
611 -- Read the contents of the box, which should be filled in by now
612 readFilledBox box_tv = ASSERT( isBoxyTyVar box_tv )
613                        do { cts <- readMetaTyVar box_tv
614                           ; case cts of
615                                 Flexi -> pprPanic "readFilledBox" (ppr box_tv)
616                                 Indirect ty -> return ty }
617
618 tcInstBoxyTyVar :: TyVar -> TcM BoxyTyVar
619 -- Instantiate with a BOXY type variable
620 tcInstBoxyTyVar tyvar = instMetaTyVar BoxTv tyvar
621 \end{code}
622
623
624 %************************************************************************
625 %*                                                                      *
626 \subsection{Putting and getting  mutable type variables}
627 %*                                                                      *
628 %************************************************************************
629
630 But it's more fun to short out indirections on the way: If this
631 version returns a TyVar, then that TyVar is unbound.  If it returns
632 any other type, then there might be bound TyVars embedded inside it.
633
634 We return Nothing iff the original box was unbound.
635
636 \begin{code}
637 data LookupTyVarResult  -- The result of a lookupTcTyVar call
638   = DoneTv TcTyVarDetails       -- SkolemTv or virgin MetaTv
639   | IndirectTv TcType
640
641 lookupTcTyVar :: TcTyVar -> TcM LookupTyVarResult
642 lookupTcTyVar tyvar 
643   = ASSERT2( isTcTyVar tyvar, ppr tyvar )
644     case details of
645       SkolemTv _   -> return (DoneTv details)
646       MetaTv _ ref -> do { meta_details <- readMutVar ref
647                          ; case meta_details of
648                             Indirect ty -> return (IndirectTv ty)
649                             Flexi -> return (DoneTv details) }
650   where
651     details =  tcTyVarDetails tyvar
652
653 {- 
654 -- gaw 2004 We aren't shorting anything out anymore, at least for now
655 getTcTyVar tyvar
656   | not (isTcTyVar tyvar)
657   = pprTrace "getTcTyVar" (ppr tyvar) $
658     return (Just (mkTyVarTy tyvar))
659
660   | otherwise
661   = ASSERT2( isTcTyVar tyvar, ppr tyvar ) do
662     maybe_ty <- readMetaTyVar tyvar
663     case maybe_ty of
664         Just ty -> do ty' <- short_out ty
665                       writeMetaTyVar tyvar (Just ty')
666                       return (Just ty')
667
668         Nothing    -> return Nothing
669
670 short_out :: TcType -> TcM TcType
671 short_out ty@(TyVarTy tyvar)
672   | not (isTcTyVar tyvar)
673   = return ty
674
675   | otherwise = do
676     maybe_ty <- readMetaTyVar tyvar
677     case maybe_ty of
678         Just ty' -> do ty' <- short_out ty'
679                        writeMetaTyVar tyvar (Just ty')
680                        return ty'
681
682         other    -> return ty
683
684 short_out other_ty = return other_ty
685 -}
686 \end{code}
687
688
689 %************************************************************************
690 %*                                                                      *
691 \subsection{Zonking -- the exernal interfaces}
692 %*                                                                      *
693 %************************************************************************
694
695 -----------------  Type variables
696
697 \begin{code}
698 zonkTcTyVars :: [TcTyVar] -> TcM [TcType]
699 zonkTcTyVars tyvars = mapM zonkTcTyVar tyvars
700
701 zonkTcTyVarsAndFV :: [TcTyVar] -> TcM TcTyVarSet
702 zonkTcTyVarsAndFV tyvars = tyVarsOfTypes <$> mapM zonkTcTyVar tyvars
703
704 zonkTcTyVar :: TcTyVar -> TcM TcType
705 zonkTcTyVar tyvar = ASSERT2( isTcTyVar tyvar, ppr tyvar)
706                     zonk_tc_tyvar (\ tv -> return (TyVarTy tv)) tyvar
707 \end{code}
708
709 -----------------  Types
710
711 \begin{code}
712 zonkTcType :: TcType -> TcM TcType
713 zonkTcType ty = zonkType (\ tv -> return (TyVarTy tv)) ty
714
715 zonkTcTypes :: [TcType] -> TcM [TcType]
716 zonkTcTypes tys = mapM zonkTcType tys
717
718 zonkTcThetaType :: TcThetaType -> TcM TcThetaType
719 zonkTcThetaType theta = mapM zonkTcPredType theta
720
721 zonkTcPredType :: TcPredType -> TcM TcPredType
722 zonkTcPredType (ClassP c ts)  = ClassP c <$> zonkTcTypes ts
723 zonkTcPredType (IParam n t)   = IParam n <$> zonkTcType t
724 zonkTcPredType (EqPred t1 t2) = EqPred <$> zonkTcType t1 <*> zonkTcType t2
725 \end{code}
726
727 -------------------  These ...ToType, ...ToKind versions
728                      are used at the end of type checking
729
730 \begin{code}
731 zonkTopTyVar :: TcTyVar -> TcM TcTyVar
732 -- zonkTopTyVar is used, at the top level, on any un-instantiated meta type variables
733 -- to default the kind of ? and ?? etc to *.  This is important to ensure that
734 -- instance declarations match.  For example consider
735 --      instance Show (a->b)
736 --      foo x = show (\_ -> True)
737 -- Then we'll get a constraint (Show (p ->q)) where p has argTypeKind (printed ??), 
738 -- and that won't match the typeKind (*) in the instance decl.
739 --
740 -- Because we are at top level, no further constraints are going to affect these
741 -- type variables, so it's time to do it by hand.  However we aren't ready
742 -- to default them fully to () or whatever, because the type-class defaulting
743 -- rules have yet to run.
744
745 zonkTopTyVar tv
746   | k `eqKind` default_k = return tv
747   | otherwise
748   = do  { tv' <- newFlexiTyVar default_k
749         ; writeMetaTyVar tv (mkTyVarTy tv') 
750         ; return tv' }
751   where
752     k = tyVarKind tv
753     default_k = defaultKind k
754
755 zonkQuantifiedTyVars :: [TcTyVar] -> TcM [TcTyVar]
756 zonkQuantifiedTyVars = mapM zonkQuantifiedTyVar
757
758 zonkQuantifiedTyVar :: TcTyVar -> TcM TcTyVar
759 -- zonkQuantifiedTyVar is applied to the a TcTyVar when quantifying over it.
760 --
761 -- The quantified type variables often include meta type variables
762 -- we want to freeze them into ordinary type variables, and
763 -- default their kind (e.g. from OpenTypeKind to TypeKind)
764 --                      -- see notes with Kind.defaultKind
765 -- The meta tyvar is updated to point to the new skolem TyVar.  Now any 
766 -- bound occurences of the original type variable will get zonked to 
767 -- the immutable version.
768 --
769 -- We leave skolem TyVars alone; they are immutable.
770 zonkQuantifiedTyVar tv
771   | ASSERT2( isTcTyVar tv, ppr tv ) 
772     isSkolemTyVar tv 
773   = do { kind <- zonkTcType (tyVarKind tv)
774        ; return $ setTyVarKind tv kind
775        }
776         -- It might be a skolem type variable, 
777         -- for example from a user type signature
778
779   | otherwise   -- It's a meta-type-variable
780   = do  { details <- readMetaTyVar tv
781
782         -- Create the new, frozen, skolem type variable
783         -- We zonk to a skolem, not to a regular TcVar
784         -- See Note [Zonking to Skolem]
785         ; let final_kind = defaultKind (tyVarKind tv)
786               final_tv   = mkSkolTyVar (tyVarName tv) final_kind UnkSkol
787
788         -- Bind the meta tyvar to the new tyvar
789         ; case details of
790             Indirect ty -> WARN( True, ppr tv $$ ppr ty ) 
791                            return ()
792                 -- [Sept 04] I don't think this should happen
793                 -- See note [Silly Type Synonym]
794
795             Flexi -> writeMetaTyVar tv (mkTyVarTy final_tv)
796
797         -- Return the new tyvar
798         ; return final_tv }
799 \end{code}
800
801 Note [Silly Type Synonyms]
802 ~~~~~~~~~~~~~~~~~~~~~~~~~~
803 Consider this:
804         type C u a = u  -- Note 'a' unused
805
806         foo :: (forall a. C u a -> C u a) -> u
807         foo x = ...
808
809         bar :: Num u => u
810         bar = foo (\t -> t + t)
811
812 * From the (\t -> t+t) we get type  {Num d} =>  d -> d
813   where d is fresh.
814
815 * Now unify with type of foo's arg, and we get:
816         {Num (C d a)} =>  C d a -> C d a
817   where a is fresh.
818
819 * Now abstract over the 'a', but float out the Num (C d a) constraint
820   because it does not 'really' mention a.  (see exactTyVarsOfType)
821   The arg to foo becomes
822         \/\a -> \t -> t+t
823
824 * So we get a dict binding for Num (C d a), which is zonked to give
825         a = ()
826   [Note Sept 04: now that we are zonking quantified type variables
827   on construction, the 'a' will be frozen as a regular tyvar on
828   quantification, so the floated dict will still have type (C d a).
829   Which renders this whole note moot; happily!]
830
831 * Then the \/\a abstraction has a zonked 'a' in it.
832
833 All very silly.   I think its harmless to ignore the problem.  We'll end up with
834 a \/\a in the final result but all the occurrences of a will be zonked to ()
835
836 Note [Zonking to Skolem]
837 ~~~~~~~~~~~~~~~~~~~~~~~~
838 We used to zonk quantified type variables to regular TyVars.  However, this
839 leads to problems.  Consider this program from the regression test suite:
840
841   eval :: Int -> String -> String -> String
842   eval 0 root actual = evalRHS 0 root actual
843
844   evalRHS :: Int -> a
845   evalRHS 0 root actual = eval 0 root actual
846
847 It leads to the deferral of an equality
848
849   (String -> String -> String) ~ a
850
851 which is propagated up to the toplevel (see TcSimplify.tcSimplifyInferCheck).
852 In the meantime `a' is zonked and quantified to form `evalRHS's signature.
853 This has the *side effect* of also zonking the `a' in the deferred equality
854 (which at this point is being handed around wrapped in an implication
855 constraint).
856
857 Finally, the equality (with the zonked `a') will be handed back to the
858 simplifier by TcRnDriver.tcRnSrcDecls calling TcSimplify.tcSimplifyTop.
859 If we zonk `a' with a regular type variable, we will have this regular type
860 variable now floating around in the simplifier, which in many places assumes to
861 only see proper TcTyVars.
862
863 We can avoid this problem by zonking with a skolem.  The skolem is rigid
864 (which we requirefor a quantified variable), but is still a TcTyVar that the
865 simplifier knows how to deal with.
866
867
868 %************************************************************************
869 %*                                                                      *
870 \subsection{Zonking -- the main work-horses: zonkType, zonkTyVar}
871 %*                                                                      *
872 %*              For internal use only!                                  *
873 %*                                                                      *
874 %************************************************************************
875
876 \begin{code}
877 -- For unbound, mutable tyvars, zonkType uses the function given to it
878 -- For tyvars bound at a for-all, zonkType zonks them to an immutable
879 --      type variable and zonks the kind too
880
881 zonkType :: (TcTyVar -> TcM Type)       -- What to do with unbound mutable type variables
882                                         -- see zonkTcType, and zonkTcTypeToType
883          -> TcType
884          -> TcM Type
885 zonkType unbound_var_fn ty
886   = go ty
887   where
888     go (TyConApp tc tys) = do tys' <- mapM go tys
889                               return (TyConApp tc tys')
890
891     go (PredTy p)        = do p' <- go_pred p
892                               return (PredTy p')
893
894     go (FunTy arg res)   = do arg' <- go arg
895                               res' <- go res
896                               return (FunTy arg' res')
897
898     go (AppTy fun arg)   = do fun' <- go fun
899                               arg' <- go arg
900                               return (mkAppTy fun' arg')
901                 -- NB the mkAppTy; we might have instantiated a
902                 -- type variable to a type constructor, so we need
903                 -- to pull the TyConApp to the top.
904
905         -- The two interesting cases!
906     go (TyVarTy tyvar) | isTcTyVar tyvar = zonk_tc_tyvar unbound_var_fn tyvar
907                        | otherwise       = liftM TyVarTy $ 
908                                              zonkTyVar unbound_var_fn tyvar
909                 -- Ordinary (non Tc) tyvars occur inside quantified types
910
911     go (ForAllTy tyvar ty) = ASSERT( isImmutableTyVar tyvar ) do
912                              ty' <- go ty
913                              tyvar' <- zonkTyVar unbound_var_fn tyvar
914                              return (ForAllTy tyvar' ty')
915
916     go_pred (ClassP c tys)   = do tys' <- mapM go tys
917                                   return (ClassP c tys')
918     go_pred (IParam n ty)    = do ty' <- go ty
919                                   return (IParam n ty')
920     go_pred (EqPred ty1 ty2) = do ty1' <- go ty1
921                                   ty2' <- go ty2
922                                   return (EqPred ty1' ty2')
923
924 zonk_tc_tyvar :: (TcTyVar -> TcM Type)  -- What to do for an unbound mutable var
925               -> TcTyVar -> TcM TcType
926 zonk_tc_tyvar unbound_var_fn tyvar 
927   | not (isMetaTyVar tyvar)     -- Skolems
928   = return (TyVarTy tyvar)
929
930   | otherwise                   -- Mutables
931   = do  { cts <- readMetaTyVar tyvar
932         ; case cts of
933             Flexi       -> unbound_var_fn tyvar    -- Unbound meta type variable
934             Indirect ty -> zonkType unbound_var_fn ty  }
935
936 -- Zonk the kind of a non-TC tyvar in case it is a coercion variable (their
937 -- kind contains types).
938 --
939 zonkTyVar :: (TcTyVar -> TcM Type)      -- What to do for an unbound mutable var
940           -> TyVar -> TcM TyVar
941 zonkTyVar unbound_var_fn tv 
942   | isCoVar tv
943   = do { kind <- zonkType unbound_var_fn (tyVarKind tv)
944        ; return $ setTyVarKind tv kind
945        }
946   | otherwise = return tv
947 \end{code}
948
949
950
951 %************************************************************************
952 %*                                                                      *
953                         Zonking kinds
954 %*                                                                      *
955 %************************************************************************
956
957 \begin{code}
958 readKindVar  :: KindVar -> TcM (MetaDetails)
959 writeKindVar :: KindVar -> TcKind -> TcM ()
960 readKindVar  kv = readMutVar (kindVarRef kv)
961 writeKindVar kv val = writeMutVar (kindVarRef kv) (Indirect val)
962
963 -------------
964 zonkTcKind :: TcKind -> TcM TcKind
965 zonkTcKind k = zonkTcType k
966
967 -------------
968 zonkTcKindToKind :: TcKind -> TcM Kind
969 -- When zonking a TcKind to a kind, we need to instantiate kind variables,
970 -- Haskell specifies that * is to be used, so we follow that.
971 zonkTcKindToKind k = zonkType (\ _ -> return liftedTypeKind) k
972 \end{code}
973                         
974 %************************************************************************
975 %*                                                                      *
976 \subsection{Checking a user type}
977 %*                                                                      *
978 %************************************************************************
979
980 When dealing with a user-written type, we first translate it from an HsType
981 to a Type, performing kind checking, and then check various things that should 
982 be true about it.  We don't want to perform these checks at the same time
983 as the initial translation because (a) they are unnecessary for interface-file
984 types and (b) when checking a mutually recursive group of type and class decls,
985 we can't "look" at the tycons/classes yet.  Also, the checks are are rather
986 diverse, and used to really mess up the other code.
987
988 One thing we check for is 'rank'.  
989
990         Rank 0:         monotypes (no foralls)
991         Rank 1:         foralls at the front only, Rank 0 inside
992         Rank 2:         foralls at the front, Rank 1 on left of fn arrow,
993
994         basic ::= tyvar | T basic ... basic
995
996         r2  ::= forall tvs. cxt => r2a
997         r2a ::= r1 -> r2a | basic
998         r1  ::= forall tvs. cxt => r0
999         r0  ::= r0 -> r0 | basic
1000         
1001 Another thing is to check that type synonyms are saturated. 
1002 This might not necessarily show up in kind checking.
1003         type A i = i
1004         data T k = MkT (k Int)
1005         f :: T A        -- BAD!
1006
1007         
1008 \begin{code}
1009 checkValidType :: UserTypeCtxt -> Type -> TcM ()
1010 -- Checks that the type is valid for the given context
1011 checkValidType ctxt ty = do
1012     traceTc (text "checkValidType" <+> ppr ty)
1013     unboxed  <- doptM Opt_UnboxedTuples
1014     rank2    <- doptM Opt_Rank2Types
1015     rankn    <- doptM Opt_RankNTypes
1016     polycomp <- doptM Opt_PolymorphicComponents
1017     let 
1018         gen_rank n | rankn     = ArbitraryRank
1019                    | rank2     = Rank 2
1020                    | otherwise = Rank n
1021         rank
1022           = case ctxt of
1023                  DefaultDeclCtxt-> MustBeMonoType
1024                  ResSigCtxt     -> MustBeMonoType
1025                  LamPatSigCtxt  -> gen_rank 0
1026                  BindPatSigCtxt -> gen_rank 0
1027                  TySynCtxt _    -> gen_rank 0
1028                  GenPatCtxt     -> gen_rank 1
1029                         -- This one is a bit of a hack
1030                         -- See the forall-wrapping in TcClassDcl.mkGenericInstance              
1031
1032                  ExprSigCtxt    -> gen_rank 1
1033                  FunSigCtxt _   -> gen_rank 1
1034                  ConArgCtxt _   | polycomp -> gen_rank 2
1035                                 -- We are given the type of the entire
1036                                 -- constructor, hence rank 1
1037                                 | otherwise -> gen_rank 1
1038
1039                  ForSigCtxt _   -> gen_rank 1
1040                  SpecInstCtxt   -> gen_rank 1
1041
1042         actual_kind = typeKind ty
1043
1044         kind_ok = case ctxt of
1045                         TySynCtxt _  -> True -- Any kind will do
1046                         ResSigCtxt   -> isSubOpenTypeKind actual_kind
1047                         ExprSigCtxt  -> isSubOpenTypeKind actual_kind
1048                         GenPatCtxt   -> isLiftedTypeKind actual_kind
1049                         ForSigCtxt _ -> isLiftedTypeKind actual_kind
1050                         _            -> isSubArgTypeKind actual_kind
1051         
1052         ubx_tup = case ctxt of
1053                       TySynCtxt _ | unboxed -> UT_Ok
1054                       ExprSigCtxt | unboxed -> UT_Ok
1055                       _                     -> UT_NotOk
1056
1057         -- Check that the thing has kind Type, and is lifted if necessary
1058     checkTc kind_ok (kindErr actual_kind)
1059
1060         -- Check the internal validity of the type itself
1061     check_type rank ubx_tup ty
1062
1063     traceTc (text "checkValidType done" <+> ppr ty)
1064
1065 checkValidMonoType :: Type -> TcM ()
1066 checkValidMonoType ty = check_mono_type MustBeMonoType ty
1067 \end{code}
1068
1069
1070 \begin{code}
1071 data Rank = ArbitraryRank         -- Any rank ok
1072           | MustBeMonoType        -- Monotype regardless of flags
1073           | TyConArgMonoType      -- Monotype but could be poly if -XImpredicativeTypes
1074           | SynArgMonoType        -- Monotype but could be poly if -XLiberalTypeSynonyms
1075           | Rank Int              -- Rank n, but could be more with -XRankNTypes
1076
1077 decRank :: Rank -> Rank           -- Function arguments
1078 decRank (Rank 0)   = Rank 0
1079 decRank (Rank n)   = Rank (n-1)
1080 decRank other_rank = other_rank
1081
1082 nonZeroRank :: Rank -> Bool
1083 nonZeroRank ArbitraryRank = True
1084 nonZeroRank (Rank n)      = n>0
1085 nonZeroRank _             = False
1086
1087 ----------------------------------------
1088 data UbxTupFlag = UT_Ok | UT_NotOk
1089         -- The "Ok" version means "ok if UnboxedTuples is on"
1090
1091 ----------------------------------------
1092 check_mono_type :: Rank -> Type -> TcM ()       -- No foralls anywhere
1093                                                 -- No unlifted types of any kind
1094 check_mono_type rank ty
1095    = do { check_type rank UT_NotOk ty
1096         ; checkTc (not (isUnLiftedType ty)) (unliftedArgErr ty) }
1097
1098 check_type :: Rank -> UbxTupFlag -> Type -> TcM ()
1099 -- The args say what the *type context* requires, independent
1100 -- of *flag* settings.  You test the flag settings at usage sites.
1101 -- 
1102 -- Rank is allowed rank for function args
1103 -- Rank 0 means no for-alls anywhere
1104
1105 check_type rank ubx_tup ty
1106   | not (null tvs && null theta)
1107   = do  { checkTc (nonZeroRank rank) (forAllTyErr rank ty)
1108                 -- Reject e.g. (Maybe (?x::Int => Int)), 
1109                 -- with a decent error message
1110         ; check_valid_theta SigmaCtxt theta
1111         ; check_type rank ubx_tup tau   -- Allow foralls to right of arrow
1112         ; checkFreeness tvs theta
1113         ; checkAmbiguity tvs theta (tyVarsOfType tau) }
1114   where
1115     (tvs, theta, tau) = tcSplitSigmaTy ty
1116    
1117 -- Naked PredTys don't usually show up, but they can as a result of
1118 --      {-# SPECIALISE instance Ord Char #-}
1119 -- The Right Thing would be to fix the way that SPECIALISE instance pragmas
1120 -- are handled, but the quick thing is just to permit PredTys here.
1121 check_type _ _ (PredTy sty)
1122   = do  { dflags <- getDOpts
1123         ; check_pred_ty dflags TypeCtxt sty }
1124
1125 check_type _ _ (TyVarTy _) = return ()
1126 check_type rank _ (FunTy arg_ty res_ty)
1127   = do  { check_type (decRank rank) UT_NotOk arg_ty
1128         ; check_type rank           UT_Ok    res_ty }
1129
1130 check_type rank _ (AppTy ty1 ty2)
1131   = do  { check_arg_type rank ty1
1132         ; check_arg_type rank ty2 }
1133
1134 check_type rank ubx_tup ty@(TyConApp tc tys)
1135   | isSynTyCon tc
1136   = do  {       -- Check that the synonym has enough args
1137                 -- This applies equally to open and closed synonyms
1138                 -- It's OK to have an *over-applied* type synonym
1139                 --      data Tree a b = ...
1140                 --      type Foo a = Tree [a]
1141                 --      f :: Foo a b -> ...
1142           checkTc (tyConArity tc <= length tys) arity_msg
1143
1144         -- See Note [Liberal type synonyms]
1145         ; liberal <- doptM Opt_LiberalTypeSynonyms
1146         ; if not liberal || isOpenSynTyCon tc then
1147                 -- For H98 and synonym families, do check the type args
1148                 mapM_ (check_mono_type SynArgMonoType) tys
1149
1150           else  -- In the liberal case (only for closed syns), expand then check
1151           case tcView ty of   
1152              Just ty' -> check_type rank ubx_tup ty' 
1153              Nothing  -> pprPanic "check_tau_type" (ppr ty)
1154     }
1155     
1156   | isUnboxedTupleTyCon tc
1157   = do  { ub_tuples_allowed <- doptM Opt_UnboxedTuples
1158         ; checkTc (ubx_tup_ok ub_tuples_allowed) ubx_tup_msg
1159
1160         ; impred <- doptM Opt_ImpredicativeTypes        
1161         ; let rank' = if impred then ArbitraryRank else TyConArgMonoType
1162                 -- c.f. check_arg_type
1163                 -- However, args are allowed to be unlifted, or
1164                 -- more unboxed tuples, so can't use check_arg_ty
1165         ; mapM_ (check_type rank' UT_Ok) tys }
1166
1167   | otherwise
1168   = mapM_ (check_arg_type rank) tys
1169
1170   where
1171     ubx_tup_ok ub_tuples_allowed = case ubx_tup of
1172                                    UT_Ok -> ub_tuples_allowed
1173                                    _     -> False
1174
1175     n_args    = length tys
1176     tc_arity  = tyConArity tc
1177
1178     arity_msg   = arityErr "Type synonym" (tyConName tc) tc_arity n_args
1179     ubx_tup_msg = ubxArgTyErr ty
1180
1181 check_type _ _ ty = pprPanic "check_type" (ppr ty)
1182
1183 ----------------------------------------
1184 check_arg_type :: Rank -> Type -> TcM ()
1185 -- The sort of type that can instantiate a type variable,
1186 -- or be the argument of a type constructor.
1187 -- Not an unboxed tuple, but now *can* be a forall (since impredicativity)
1188 -- Other unboxed types are very occasionally allowed as type
1189 -- arguments depending on the kind of the type constructor
1190 -- 
1191 -- For example, we want to reject things like:
1192 --
1193 --      instance Ord a => Ord (forall s. T s a)
1194 -- and
1195 --      g :: T s (forall b.b)
1196 --
1197 -- NB: unboxed tuples can have polymorphic or unboxed args.
1198 --     This happens in the workers for functions returning
1199 --     product types with polymorphic components.
1200 --     But not in user code.
1201 -- Anyway, they are dealt with by a special case in check_tau_type
1202
1203 check_arg_type rank ty 
1204   = do  { impred <- doptM Opt_ImpredicativeTypes
1205         ; let rank' = if impred then ArbitraryRank  -- Arg of tycon can have arby rank, regardless
1206                       else case rank of             -- Predictive => must be monotype
1207                         MustBeMonoType -> MustBeMonoType 
1208                         _              -> TyConArgMonoType
1209                         -- Make sure that MustBeMonoType is propagated, 
1210                         -- so that we don't suggest -XImpredicativeTypes in
1211                         --    (Ord (forall a.a)) => a -> a
1212
1213         ; check_type rank' UT_NotOk ty
1214         ; checkTc (not (isUnLiftedType ty)) (unliftedArgErr ty) }
1215
1216 ----------------------------------------
1217 forAllTyErr :: Rank -> Type -> SDoc
1218 forAllTyErr rank ty 
1219    = vcat [ hang (ptext (sLit "Illegal polymorphic or qualified type:")) 2 (ppr ty)
1220           , suggestion ]
1221   where
1222     suggestion = case rank of
1223                    Rank _ -> ptext (sLit "Perhaps you intended to use -XRankNTypes or -XRank2Types")
1224                    TyConArgMonoType -> ptext (sLit "Perhaps you intended to use -XImpredicativeTypes")
1225                    SynArgMonoType -> ptext (sLit "Perhaps you intended to use -XLiberalTypeSynonyms")
1226                    _ -> empty      -- Polytype is always illegal
1227
1228 unliftedArgErr, ubxArgTyErr :: Type -> SDoc
1229 unliftedArgErr  ty = sep [ptext (sLit "Illegal unlifted type:"), ppr ty]
1230 ubxArgTyErr     ty = sep [ptext (sLit "Illegal unboxed tuple type as function argument:"), ppr ty]
1231
1232 kindErr :: Kind -> SDoc
1233 kindErr kind       = sep [ptext (sLit "Expecting an ordinary type, but found a type of kind"), ppr kind]
1234 \end{code}
1235
1236 Note [Liberal type synonyms]
1237 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1238 If -XLiberalTypeSynonyms is on, expand closed type synonyms *before*
1239 doing validity checking.  This allows us to instantiate a synonym defn
1240 with a for-all type, or with a partially-applied type synonym.
1241         e.g.   type T a b = a
1242                type S m   = m ()
1243                f :: S (T Int)
1244 Here, T is partially applied, so it's illegal in H98.  But if you
1245 expand S first, then T we get just
1246                f :: Int
1247 which is fine.
1248
1249 IMPORTANT: suppose T is a type synonym.  Then we must do validity
1250 checking on an appliation (T ty1 ty2)
1251
1252         *either* before expansion (i.e. check ty1, ty2)
1253         *or* after expansion (i.e. expand T ty1 ty2, and then check)
1254         BUT NOT BOTH
1255
1256 If we do both, we get exponential behaviour!!
1257
1258   data TIACons1 i r c = c i ::: r c
1259   type TIACons2 t x = TIACons1 t (TIACons1 t x)
1260   type TIACons3 t x = TIACons2 t (TIACons1 t x)
1261   type TIACons4 t x = TIACons2 t (TIACons2 t x)
1262   type TIACons7 t x = TIACons4 t (TIACons3 t x)
1263
1264
1265 %************************************************************************
1266 %*                                                                      *
1267 \subsection{Checking a theta or source type}
1268 %*                                                                      *
1269 %************************************************************************
1270
1271 \begin{code}
1272 -- Enumerate the contexts in which a "source type", <S>, can occur
1273 --      Eq a 
1274 -- or   ?x::Int
1275 -- or   r <: {x::Int}
1276 -- or   (N a) where N is a newtype
1277
1278 data SourceTyCtxt
1279   = ClassSCCtxt Name    -- Superclasses of clas
1280                         --      class <S> => C a where ...
1281   | SigmaCtxt           -- Theta part of a normal for-all type
1282                         --      f :: <S> => a -> a
1283   | DataTyCtxt Name     -- Theta part of a data decl
1284                         --      data <S> => T a = MkT a
1285   | TypeCtxt            -- Source type in an ordinary type
1286                         --      f :: N a -> N a
1287   | InstThetaCtxt       -- Context of an instance decl
1288                         --      instance <S> => C [a] where ...
1289                 
1290 pprSourceTyCtxt :: SourceTyCtxt -> SDoc
1291 pprSourceTyCtxt (ClassSCCtxt c) = ptext (sLit "the super-classes of class") <+> quotes (ppr c)
1292 pprSourceTyCtxt SigmaCtxt       = ptext (sLit "the context of a polymorphic type")
1293 pprSourceTyCtxt (DataTyCtxt tc) = ptext (sLit "the context of the data type declaration for") <+> quotes (ppr tc)
1294 pprSourceTyCtxt InstThetaCtxt   = ptext (sLit "the context of an instance declaration")
1295 pprSourceTyCtxt TypeCtxt        = ptext (sLit "the context of a type")
1296 \end{code}
1297
1298 \begin{code}
1299 checkValidTheta :: SourceTyCtxt -> ThetaType -> TcM ()
1300 checkValidTheta ctxt theta 
1301   = addErrCtxt (checkThetaCtxt ctxt theta) (check_valid_theta ctxt theta)
1302
1303 -------------------------
1304 check_valid_theta :: SourceTyCtxt -> [PredType] -> TcM ()
1305 check_valid_theta _ []
1306   = return ()
1307 check_valid_theta ctxt theta = do
1308     dflags <- getDOpts
1309     warnTc (notNull dups) (dupPredWarn dups)
1310     mapM_ (check_pred_ty dflags ctxt) theta
1311   where
1312     (_,dups) = removeDups tcCmpPred theta
1313
1314 -------------------------
1315 check_pred_ty :: DynFlags -> SourceTyCtxt -> PredType -> TcM ()
1316 check_pred_ty dflags ctxt pred@(ClassP cls tys)
1317   = do {        -- Class predicates are valid in all contexts
1318        ; checkTc (arity == n_tys) arity_err
1319
1320                 -- Check the form of the argument types
1321        ; mapM_ checkValidMonoType tys
1322        ; checkTc (check_class_pred_tys dflags ctxt tys)
1323                  (predTyVarErr pred $$ how_to_allow)
1324        }
1325   where
1326     class_name = className cls
1327     arity      = classArity cls
1328     n_tys      = length tys
1329     arity_err  = arityErr "Class" class_name arity n_tys
1330     how_to_allow = parens (ptext (sLit "Use -XFlexibleContexts to permit this"))
1331
1332 check_pred_ty _ (ClassSCCtxt _) (EqPred _ _)
1333   =   -- We do not yet support superclass equalities.
1334     failWithTc $
1335       sep [ ptext (sLit "The current implementation of type families does not")
1336           , ptext (sLit "support equality constraints in superclass contexts.")
1337           , ptext (sLit "They are planned for a future release.")
1338           ]
1339
1340 check_pred_ty dflags _ pred@(EqPred ty1 ty2)
1341   = do {        -- Equational constraints are valid in all contexts if type
1342                 -- families are permitted
1343        ; checkTc (dopt Opt_TypeFamilies dflags) (eqPredTyErr pred)
1344
1345                 -- Check the form of the argument types
1346        ; checkValidMonoType ty1
1347        ; checkValidMonoType ty2
1348        }
1349
1350 check_pred_ty _ SigmaCtxt (IParam _ ty) = checkValidMonoType ty
1351         -- Implicit parameters only allowed in type
1352         -- signatures; not in instance decls, superclasses etc
1353         -- The reason for not allowing implicit params in instances is a bit
1354         -- subtle.
1355         -- If we allowed        instance (?x::Int, Eq a) => Foo [a] where ...
1356         -- then when we saw (e :: (?x::Int) => t) it would be unclear how to 
1357         -- discharge all the potential usas of the ?x in e.   For example, a
1358         -- constraint Foo [Int] might come out of e,and applying the
1359         -- instance decl would show up two uses of ?x.
1360
1361 -- Catch-all
1362 check_pred_ty _ _ sty = failWithTc (badPredTyErr sty)
1363
1364 -------------------------
1365 check_class_pred_tys :: DynFlags -> SourceTyCtxt -> [Type] -> Bool
1366 check_class_pred_tys dflags ctxt tys 
1367   = case ctxt of
1368         TypeCtxt      -> True   -- {-# SPECIALISE instance Eq (T Int) #-} is fine
1369         InstThetaCtxt -> flexible_contexts || undecidable_ok || all tcIsTyVarTy tys
1370                                 -- Further checks on head and theta in
1371                                 -- checkInstTermination
1372         _             -> flexible_contexts || all tyvar_head tys
1373   where
1374     flexible_contexts = dopt Opt_FlexibleContexts dflags
1375     undecidable_ok = dopt Opt_UndecidableInstances dflags
1376
1377 -------------------------
1378 tyvar_head :: Type -> Bool
1379 tyvar_head ty                   -- Haskell 98 allows predicates of form 
1380   | tcIsTyVarTy ty = True       --      C (a ty1 .. tyn)
1381   | otherwise                   -- where a is a type variable
1382   = case tcSplitAppTy_maybe ty of
1383         Just (ty, _) -> tyvar_head ty
1384         Nothing      -> False
1385 \end{code}
1386
1387 Check for ambiguity
1388 ~~~~~~~~~~~~~~~~~~~
1389           forall V. P => tau
1390 is ambiguous if P contains generic variables
1391 (i.e. one of the Vs) that are not mentioned in tau
1392
1393 However, we need to take account of functional dependencies
1394 when we speak of 'mentioned in tau'.  Example:
1395         class C a b | a -> b where ...
1396 Then the type
1397         forall x y. (C x y) => x
1398 is not ambiguous because x is mentioned and x determines y
1399
1400 NB; the ambiguity check is only used for *user* types, not for types
1401 coming from inteface files.  The latter can legitimately have
1402 ambiguous types. Example
1403
1404    class S a where s :: a -> (Int,Int)
1405    instance S Char where s _ = (1,1)
1406    f:: S a => [a] -> Int -> (Int,Int)
1407    f (_::[a]) x = (a*x,b)
1408         where (a,b) = s (undefined::a)
1409
1410 Here the worker for f gets the type
1411         fw :: forall a. S a => Int -> (# Int, Int #)
1412
1413 If the list of tv_names is empty, we have a monotype, and then we
1414 don't need to check for ambiguity either, because the test can't fail
1415 (see is_ambig).
1416
1417
1418 \begin{code}
1419 checkAmbiguity :: [TyVar] -> ThetaType -> TyVarSet -> TcM ()
1420 checkAmbiguity forall_tyvars theta tau_tyvars
1421   = mapM_ complain (filter is_ambig theta)
1422   where
1423     complain pred     = addErrTc (ambigErr pred)
1424     extended_tau_vars = grow theta tau_tyvars
1425
1426         -- See Note [Implicit parameters and ambiguity] in TcSimplify
1427     is_ambig pred     = isClassPred  pred &&
1428                         any ambig_var (varSetElems (tyVarsOfPred pred))
1429
1430     ambig_var ct_var  = (ct_var `elem` forall_tyvars) &&
1431                         not (ct_var `elemVarSet` extended_tau_vars)
1432
1433 ambigErr :: PredType -> SDoc
1434 ambigErr pred
1435   = sep [ptext (sLit "Ambiguous constraint") <+> quotes (pprPred pred),
1436          nest 4 (ptext (sLit "At least one of the forall'd type variables mentioned by the constraint") $$
1437                  ptext (sLit "must be reachable from the type after the '=>'"))]
1438 \end{code}
1439     
1440 In addition, GHC insists that at least one type variable
1441 in each constraint is in V.  So we disallow a type like
1442         forall a. Eq b => b -> b
1443 even in a scope where b is in scope.
1444
1445 \begin{code}
1446 checkFreeness :: [Var] -> [PredType] -> TcM ()
1447 checkFreeness forall_tyvars theta
1448   = do  { flexible_contexts <- doptM Opt_FlexibleContexts
1449         ; unless flexible_contexts $ mapM_ complain (filter is_free theta) }
1450   where    
1451     is_free pred     =  not (isIPPred pred)
1452                      && not (any bound_var (varSetElems (tyVarsOfPred pred)))
1453     bound_var ct_var = ct_var `elem` forall_tyvars
1454     complain pred    = addErrTc (freeErr pred)
1455
1456 freeErr :: PredType -> SDoc
1457 freeErr pred
1458   = sep [ ptext (sLit "All of the type variables in the constraint") <+> 
1459           quotes (pprPred pred)
1460         , ptext (sLit "are already in scope") <+>
1461           ptext (sLit "(at least one must be universally quantified here)")
1462         , nest 4 $
1463             ptext (sLit "(Use -XFlexibleContexts to lift this restriction)")
1464         ]
1465 \end{code}
1466
1467 \begin{code}
1468 checkThetaCtxt :: SourceTyCtxt -> ThetaType -> SDoc
1469 checkThetaCtxt ctxt theta
1470   = vcat [ptext (sLit "In the context:") <+> pprTheta theta,
1471           ptext (sLit "While checking") <+> pprSourceTyCtxt ctxt ]
1472
1473 badPredTyErr, eqPredTyErr, predTyVarErr :: PredType -> SDoc
1474 badPredTyErr sty = ptext (sLit "Illegal constraint") <+> pprPred sty
1475 eqPredTyErr  sty = ptext (sLit "Illegal equational constraint") <+> pprPred sty
1476                    $$
1477                    parens (ptext (sLit "Use -XTypeFamilies to permit this"))
1478 predTyVarErr pred  = sep [ptext (sLit "Non type-variable argument"),
1479                           nest 2 (ptext (sLit "in the constraint:") <+> pprPred pred)]
1480 dupPredWarn :: [[PredType]] -> SDoc
1481 dupPredWarn dups   = ptext (sLit "Duplicate constraint(s):") <+> pprWithCommas pprPred (map head dups)
1482
1483 arityErr :: Outputable a => String -> a -> Int -> Int -> SDoc
1484 arityErr kind name n m
1485   = hsep [ text kind, quotes (ppr name), ptext (sLit "should have"),
1486            n_arguments <> comma, text "but has been given", int m]
1487     where
1488         n_arguments | n == 0 = ptext (sLit "no arguments")
1489                     | n == 1 = ptext (sLit "1 argument")
1490                     | True   = hsep [int n, ptext (sLit "arguments")]
1491
1492 -----------------
1493 notMonoType :: TcType -> TcM a
1494 notMonoType ty
1495   = do  { ty' <- zonkTcType ty
1496         ; env0 <- tcInitTidyEnv
1497         ; let (env1, tidy_ty) = tidyOpenType env0 ty'
1498               msg = ptext (sLit "Cannot match a monotype with") <+> quotes (ppr tidy_ty)
1499         ; failWithTcM (env1, msg) }
1500
1501 notMonoArgs :: TcType -> TcM a
1502 notMonoArgs ty
1503   = do  { ty' <- zonkTcType ty
1504         ; env0 <- tcInitTidyEnv
1505         ; let (env1, tidy_ty) = tidyOpenType env0 ty'
1506               msg = ptext (sLit "Arguments of type synonym families must be monotypes") <+> quotes (ppr tidy_ty)
1507         ; failWithTcM (env1, msg) }
1508 \end{code}
1509
1510
1511 %************************************************************************
1512 %*                                                                      *
1513 \subsection{Checking for a decent instance head type}
1514 %*                                                                      *
1515 %************************************************************************
1516
1517 @checkValidInstHead@ checks the type {\em and} its syntactic constraints:
1518 it must normally look like: @instance Foo (Tycon a b c ...) ...@
1519
1520 The exceptions to this syntactic checking: (1)~if the @GlasgowExts@
1521 flag is on, or (2)~the instance is imported (they must have been
1522 compiled elsewhere). In these cases, we let them go through anyway.
1523
1524 We can also have instances for functions: @instance Foo (a -> b) ...@.
1525
1526 \begin{code}
1527 checkValidInstHead :: Type -> TcM (Class, [TcType])
1528
1529 checkValidInstHead ty   -- Should be a source type
1530   = case tcSplitPredTy_maybe ty of {
1531         Nothing -> failWithTc (instTypeErr (ppr ty) empty) ;
1532         Just pred -> 
1533
1534     case getClassPredTys_maybe pred of {
1535         Nothing -> failWithTc (instTypeErr (pprPred pred) empty) ;
1536         Just (clas,tys) -> do
1537
1538     dflags <- getDOpts
1539     check_inst_head dflags clas tys
1540     return (clas, tys)
1541     }}
1542
1543 check_inst_head :: DynFlags -> Class -> [Type] -> TcM ()
1544 check_inst_head dflags clas tys
1545   = do { -- If GlasgowExts then check at least one isn't a type variable
1546        ; checkTc (dopt Opt_TypeSynonymInstances dflags ||
1547                   all tcInstHeadTyNotSynonym tys)
1548                  (instTypeErr (pprClassPred clas tys) head_type_synonym_msg)
1549        ; checkTc (dopt Opt_FlexibleInstances dflags ||
1550                   all tcInstHeadTyAppAllTyVars tys)
1551                  (instTypeErr (pprClassPred clas tys) head_type_args_tyvars_msg)
1552        ; checkTc (dopt Opt_MultiParamTypeClasses dflags ||
1553                   isSingleton tys)
1554                  (instTypeErr (pprClassPred clas tys) head_one_type_msg)
1555          -- May not contain type family applications
1556        ; mapM_ checkTyFamFreeness tys
1557
1558        ; mapM_ checkValidMonoType tys
1559         -- For now, I only allow tau-types (not polytypes) in 
1560         -- the head of an instance decl.  
1561         --      E.g.  instance C (forall a. a->a) is rejected
1562         -- One could imagine generalising that, but I'm not sure
1563         -- what all the consequences might be
1564        }
1565
1566   where
1567     head_type_synonym_msg = parens (
1568                 text "All instance types must be of the form (T t1 ... tn)" $$
1569                 text "where T is not a synonym." $$
1570                 text "Use -XTypeSynonymInstances if you want to disable this.")
1571
1572     head_type_args_tyvars_msg = parens (vcat [
1573                 text "All instance types must be of the form (T a1 ... an)",
1574                 text "where a1 ... an are type *variables*,",
1575                 text "and each type variable appears at most once in the instance head.",
1576                 text "Use -XFlexibleInstances if you want to disable this."])
1577
1578     head_one_type_msg = parens (
1579                 text "Only one type can be given in an instance head." $$
1580                 text "Use -XMultiParamTypeClasses if you want to allow more.")
1581
1582 instTypeErr :: SDoc -> SDoc -> SDoc
1583 instTypeErr pp_ty msg
1584   = sep [ptext (sLit "Illegal instance declaration for") <+> quotes pp_ty, 
1585          nest 4 msg]
1586 \end{code}
1587
1588
1589 %************************************************************************
1590 %*                                                                      *
1591 \subsection{Checking instance for termination}
1592 %*                                                                      *
1593 %************************************************************************
1594
1595
1596 \begin{code}
1597 checkValidInstance :: [TyVar] -> ThetaType -> Class -> [TcType] -> TcM ()
1598 checkValidInstance tyvars theta clas inst_tys
1599   = do  { undecidable_ok <- doptM Opt_UndecidableInstances
1600
1601         ; checkValidTheta InstThetaCtxt theta
1602         ; checkAmbiguity tyvars theta (tyVarsOfTypes inst_tys)
1603
1604         -- Check that instance inference will terminate (if we care)
1605         -- For Haskell 98 this will already have been done by checkValidTheta,
1606         -- but as we may be using other extensions we need to check.
1607         ; unless undecidable_ok $
1608           mapM_ addErrTc (checkInstTermination inst_tys theta)
1609         
1610         -- The Coverage Condition
1611         ; checkTc (undecidable_ok || checkInstCoverage clas inst_tys)
1612                   (instTypeErr (pprClassPred clas inst_tys) msg)
1613         }
1614   where
1615     msg  = parens (vcat [ptext (sLit "the Coverage Condition fails for one of the functional dependencies;"),
1616                          undecidableMsg])
1617 \end{code}
1618
1619 Termination test: the so-called "Paterson conditions" (see Section 5 of
1620 "Understanding functionsl dependencies via Constraint Handling Rules, 
1621 JFP Jan 2007).
1622
1623 We check that each assertion in the context satisfies:
1624  (1) no variable has more occurrences in the assertion than in the head, and
1625  (2) the assertion has fewer constructors and variables (taken together
1626      and counting repetitions) than the head.
1627 This is only needed with -fglasgow-exts, as Haskell 98 restrictions
1628 (which have already been checked) guarantee termination. 
1629
1630 The underlying idea is that 
1631
1632     for any ground substitution, each assertion in the
1633     context has fewer type constructors than the head.
1634
1635
1636 \begin{code}
1637 checkInstTermination :: [TcType] -> ThetaType -> [Message]
1638 checkInstTermination tys theta
1639   = mapCatMaybes check theta
1640   where
1641    fvs  = fvTypes tys
1642    size = sizeTypes tys
1643    check pred 
1644       | not (null (fvPred pred \\ fvs)) 
1645       = Just (predUndecErr pred nomoreMsg $$ parens undecidableMsg)
1646       | sizePred pred >= size
1647       = Just (predUndecErr pred smallerMsg $$ parens undecidableMsg)
1648       | otherwise
1649       = Nothing
1650
1651 predUndecErr :: PredType -> SDoc -> SDoc
1652 predUndecErr pred msg = sep [msg,
1653                         nest 2 (ptext (sLit "in the constraint:") <+> pprPred pred)]
1654
1655 nomoreMsg, smallerMsg, undecidableMsg :: SDoc
1656 nomoreMsg = ptext (sLit "Variable occurs more often in a constraint than in the instance head")
1657 smallerMsg = ptext (sLit "Constraint is no smaller than the instance head")
1658 undecidableMsg = ptext (sLit "Use -XUndecidableInstances to permit this")
1659 \end{code}
1660
1661
1662 %************************************************************************
1663 %*                                                                      *
1664         Checking the context of a derived instance declaration
1665 %*                                                                      *
1666 %************************************************************************
1667
1668 Note [Exotic derived instance contexts]
1669 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1670 In a 'derived' instance declaration, we *infer* the context.  It's a
1671 bit unclear what rules we should apply for this; the Haskell report is
1672 silent.  Obviously, constraints like (Eq a) are fine, but what about
1673         data T f a = MkT (f a) deriving( Eq )
1674 where we'd get an Eq (f a) constraint.  That's probably fine too.
1675
1676 One could go further: consider
1677         data T a b c = MkT (Foo a b c) deriving( Eq )
1678         instance (C Int a, Eq b, Eq c) => Eq (Foo a b c)
1679
1680 Notice that this instance (just) satisfies the Paterson termination 
1681 conditions.  Then we *could* derive an instance decl like this:
1682
1683         instance (C Int a, Eq b, Eq c) => Eq (T a b c) 
1684
1685 even though there is no instance for (C Int a), because there just
1686 *might* be an instance for, say, (C Int Bool) at a site where we
1687 need the equality instance for T's.  
1688
1689 However, this seems pretty exotic, and it's quite tricky to allow
1690 this, and yet give sensible error messages in the (much more common)
1691 case where we really want that instance decl for C.
1692
1693 So for now we simply require that the derived instance context
1694 should have only type-variable constraints.
1695
1696 Here is another example:
1697         data Fix f = In (f (Fix f)) deriving( Eq )
1698 Here, if we are prepared to allow -XUndecidableInstances we
1699 could derive the instance
1700         instance Eq (f (Fix f)) => Eq (Fix f)
1701 but this is so delicate that I don't think it should happen inside
1702 'deriving'. If you want this, write it yourself!
1703
1704 NB: if you want to lift this condition, make sure you still meet the
1705 termination conditions!  If not, the deriving mechanism generates
1706 larger and larger constraints.  Example:
1707   data Succ a = S a
1708   data Seq a = Cons a (Seq (Succ a)) | Nil deriving Show
1709
1710 Note the lack of a Show instance for Succ.  First we'll generate
1711   instance (Show (Succ a), Show a) => Show (Seq a)
1712 and then
1713   instance (Show (Succ (Succ a)), Show (Succ a), Show a) => Show (Seq a)
1714 and so on.  Instead we want to complain of no instance for (Show (Succ a)).
1715
1716 The bottom line
1717 ~~~~~~~~~~~~~~~
1718 Allow constraints which consist only of type variables, with no repeats.
1719
1720 \begin{code}
1721 validDerivPred :: PredType -> Bool
1722 validDerivPred (ClassP _ tys) = hasNoDups fvs && sizeTypes tys == length fvs
1723                               where fvs = fvTypes tys
1724 validDerivPred _              = False
1725 \end{code}
1726
1727 %************************************************************************
1728 %*                                                                      *
1729         Checking type instance well-formedness and termination
1730 %*                                                                      *
1731 %************************************************************************
1732
1733 \begin{code}
1734 -- Check that a "type instance" is well-formed (which includes decidability
1735 -- unless -XUndecidableInstances is given).
1736 --
1737 checkValidTypeInst :: [Type] -> Type -> TcM ()
1738 checkValidTypeInst typats rhs
1739   = do { -- left-hand side contains no type family applications
1740          -- (vanilla synonyms are fine, though)
1741        ; mapM_ checkTyFamFreeness typats
1742
1743          -- the right-hand side is a tau type
1744        ; checkValidMonoType rhs
1745
1746          -- we have a decidable instance unless otherwise permitted
1747        ; undecidable_ok <- doptM Opt_UndecidableInstances
1748        ; unless undecidable_ok $
1749            mapM_ addErrTc (checkFamInst typats (tyFamInsts rhs))
1750        }
1751
1752 -- Make sure that each type family instance is 
1753 --   (1) strictly smaller than the lhs,
1754 --   (2) mentions no type variable more often than the lhs, and
1755 --   (3) does not contain any further type family instances.
1756 --
1757 checkFamInst :: [Type]                  -- lhs
1758              -> [(TyCon, [Type])]       -- type family instances
1759              -> [Message]
1760 checkFamInst lhsTys famInsts
1761   = mapCatMaybes check famInsts
1762   where
1763    size = sizeTypes lhsTys
1764    fvs  = fvTypes lhsTys
1765    check (tc, tys)
1766       | not (all isTyFamFree tys)
1767       = Just (famInstUndecErr famInst nestedMsg $$ parens undecidableMsg)
1768       | not (null (fvTypes tys \\ fvs))
1769       = Just (famInstUndecErr famInst nomoreVarMsg $$ parens undecidableMsg)
1770       | size <= sizeTypes tys
1771       = Just (famInstUndecErr famInst smallerAppMsg $$ parens undecidableMsg)
1772       | otherwise
1773       = Nothing
1774       where
1775         famInst = TyConApp tc tys
1776
1777 -- Ensure that no type family instances occur in a type.
1778 --
1779 checkTyFamFreeness :: Type -> TcM ()
1780 checkTyFamFreeness ty
1781   = checkTc (isTyFamFree ty) $
1782       tyFamInstIllegalErr ty
1783
1784 -- Check that a type does not contain any type family applications.
1785 --
1786 isTyFamFree :: Type -> Bool
1787 isTyFamFree = null . tyFamInsts
1788
1789 -- Error messages
1790
1791 tyFamInstIllegalErr :: Type -> SDoc
1792 tyFamInstIllegalErr ty
1793   = hang (ptext (sLit "Illegal type synonym family application in instance") <> 
1794          colon) 4 $
1795       ppr ty
1796
1797 famInstUndecErr :: Type -> SDoc -> SDoc
1798 famInstUndecErr ty msg 
1799   = sep [msg, 
1800          nest 2 (ptext (sLit "in the type family application:") <+> 
1801                  pprType ty)]
1802
1803 nestedMsg, nomoreVarMsg, smallerAppMsg :: SDoc
1804 nestedMsg     = ptext (sLit "Nested type family application")
1805 nomoreVarMsg  = ptext (sLit "Variable occurs more often than in instance head")
1806 smallerAppMsg = ptext (sLit "Application is no smaller than the instance head")
1807 \end{code}
1808
1809
1810 %************************************************************************
1811 %*                                                                      *
1812 \subsection{Auxiliary functions}
1813 %*                                                                      *
1814 %************************************************************************
1815
1816 \begin{code}
1817 -- Free variables of a type, retaining repetitions, and expanding synonyms
1818 fvType :: Type -> [TyVar]
1819 fvType ty | Just exp_ty <- tcView ty = fvType exp_ty
1820 fvType (TyVarTy tv)        = [tv]
1821 fvType (TyConApp _ tys)    = fvTypes tys
1822 fvType (PredTy pred)       = fvPred pred
1823 fvType (FunTy arg res)     = fvType arg ++ fvType res
1824 fvType (AppTy fun arg)     = fvType fun ++ fvType arg
1825 fvType (ForAllTy tyvar ty) = filter (/= tyvar) (fvType ty)
1826
1827 fvTypes :: [Type] -> [TyVar]
1828 fvTypes tys                = concat (map fvType tys)
1829
1830 fvPred :: PredType -> [TyVar]
1831 fvPred (ClassP _ tys')     = fvTypes tys'
1832 fvPred (IParam _ ty)       = fvType ty
1833 fvPred (EqPred ty1 ty2)    = fvType ty1 ++ fvType ty2
1834
1835 -- Size of a type: the number of variables and constructors
1836 sizeType :: Type -> Int
1837 sizeType ty | Just exp_ty <- tcView ty = sizeType exp_ty
1838 sizeType (TyVarTy _)       = 1
1839 sizeType (TyConApp _ tys)  = sizeTypes tys + 1
1840 sizeType (PredTy pred)     = sizePred pred
1841 sizeType (FunTy arg res)   = sizeType arg + sizeType res + 1
1842 sizeType (AppTy fun arg)   = sizeType fun + sizeType arg
1843 sizeType (ForAllTy _ ty)   = sizeType ty
1844
1845 sizeTypes :: [Type] -> Int
1846 sizeTypes xs               = sum (map sizeType xs)
1847
1848 sizePred :: PredType -> Int
1849 sizePred (ClassP _ tys')   = sizeTypes tys'
1850 sizePred (IParam _ ty)     = sizeType ty
1851 sizePred (EqPred ty1 ty2)  = sizeType ty1 + sizeType ty2
1852 \end{code}