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