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