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