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