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