Make 'improvement' work properly in TcSimplify
[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, 
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 tcInstType inst_tyvars ty
108   = case tcSplitForAllTys ty of
109         ([],     rho) -> let    -- There may be overloading despite no type variables;
110                                 --      (?x :: Int) => Int -> Int
111                            (theta, tau) = tcSplitPhiTy rho
112                          in
113                          return ([], theta, tau)
114
115         (tyvars, rho) -> do { tyvars' <- inst_tyvars tyvars
116
117                             ; let  tenv = zipTopTvSubst tyvars (mkTyVarTys tyvars')
118                                 -- Either the tyvars are freshly made, by inst_tyvars,
119                                 -- or (in the call from tcSkolSigType) any nested foralls
120                                 -- have different binders.  Either way, zipTopTvSubst is ok
121
122                             ; let  (theta, tau) = tcSplitPhiTy (substTy tenv rho)
123                             ; return (tyvars', theta, tau) }
124 \end{code}
125
126
127 %************************************************************************
128 %*                                                                      *
129         Updating tau types
130 %*                                                                      *
131 %************************************************************************
132
133 Can't be in TcUnify, as we also need it in TcTyFuns.
134
135 \begin{code}
136 type SwapFlag = Bool
137         -- False <=> the two args are (actual, expected) respectively
138         -- True  <=> the two args are (expected, actual) respectively
139
140 checkUpdateMeta :: SwapFlag
141                 -> TcTyVar -> IORef MetaDetails -> TcType -> TcM ()
142 -- Update tv1, which is flexi; occurs check is alrady done
143 -- The 'check' version does a kind check too
144 -- We do a sub-kind check here: we might unify (a b) with (c d) 
145 --      where b::*->* and d::*; this should fail
146
147 checkUpdateMeta swapped tv1 ref1 ty2
148   = do  { checkKinds swapped tv1 ty2
149         ; updateMeta tv1 ref1 ty2 }
150
151 updateMeta :: TcTyVar -> IORef MetaDetails -> TcType -> TcM ()
152 updateMeta tv1 ref1 ty2
153   = ASSERT( isMetaTyVar tv1 )
154     ASSERT( isBoxyTyVar tv1 || isTauTy ty2 )
155     do  { ASSERTM2( do { details <- readMetaTyVar tv1; return (isFlexi details) }, ppr tv1 )
156         ; traceTc (text "updateMeta" <+> ppr tv1 <+> text ":=" <+> ppr ty2)
157         ; writeMutVar ref1 (Indirect ty2) 
158         }
159
160 ----------------
161 checkKinds swapped tv1 ty2
162 -- We're about to unify a type variable tv1 with a non-tyvar-type ty2.
163 -- ty2 has been zonked at this stage, which ensures that
164 -- its kind has as much boxity information visible as possible.
165   | tk2 `isSubKind` tk1 = returnM ()
166
167   | otherwise
168         -- Either the kinds aren't compatible
169         --      (can happen if we unify (a b) with (c d))
170         -- or we are unifying a lifted type variable with an
171         --      unlifted type: e.g.  (id 3#) is illegal
172   = addErrCtxtM (unifyKindCtxt swapped tv1 ty2) $
173     unifyKindMisMatch k1 k2
174   where
175     (k1,k2) | swapped   = (tk2,tk1)
176             | otherwise = (tk1,tk2)
177     tk1 = tyVarKind tv1
178     tk2 = typeKind ty2
179
180 ----------------
181 checkTauTvUpdate :: TcTyVar -> TcType -> TcM (Maybe TcType)
182 --    (checkTauTvUpdate tv ty)
183 -- We are about to update the TauTv tv with ty.
184 -- Check (a) that tv doesn't occur in ty (occurs check)
185 --       (b) that ty is a monotype
186 -- Furthermore, in the interest of (b), if you find an
187 -- empty box (BoxTv that is Flexi), fill it in with a TauTv
188 -- 
189 -- We have three possible outcomes:
190 -- (1) Return the (non-boxy) type to update the type variable with, 
191 --     [we know the update is ok!]
192 -- (2) return Nothing, or 
193 --     [we cannot tell whether the update is ok right now]
194 -- (3) fails.
195 --     [the update is definitely invalid]
196 -- We return Nothing in case the tv occurs in ty *under* a type family
197 -- application.  In this case, we must not update tv (to avoid a cyclic type
198 -- term), but we also cannot fail claiming an infinite type.  Given
199 --   type family F a
200 --   type instance F Int = Int
201 -- consider
202 --   a ~ F a
203 -- This is perfectly reasonable, if we later get a ~ Int.
204
205 checkTauTvUpdate orig_tv orig_ty
206   = do { result <- go orig_ty
207        ; case result of 
208            Right ty    -> return $ Just ty
209            Left  True  -> return $ Nothing
210            Left  False -> occurCheckErr (mkTyVarTy orig_tv) orig_ty
211        }
212   where
213     go :: TcType -> TcM (Either Bool TcType)
214     -- go returns
215     --   Right ty    if everything is fine
216     --   Left True   if orig_tv occurs in orig_ty, but under a type family app
217     --   Left False  if orig_tv occurs in orig_ty (with no type family app)
218     -- It fails if it encounters a forall type, except as an argument for a
219     -- closed type synonym that expands to a tau type.
220     go (TyConApp tc tys)
221         | isSynTyCon tc  = go_syn tc tys
222         | otherwise      = do { tys' <- mappM go tys
223                               ; return $ occurs (TyConApp tc) tys' }
224     go (NoteTy _ ty2)    = go ty2       -- Discard free-tyvar annotations
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
347   = zonkTcKind ty1      `thenM` \ ty1' ->
348     zonkTcKind ty2      `thenM` \ 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     in
355     failWithTc msg
356
357 unifyKindCtxt swapped tv1 ty2 tidy_env  -- not swapped => tv1 expected, ty2 inferred
358         -- tv1 and ty2 are zonked already
359   = returnM msg
360   where
361     msg = (env2, ptext SLIT("When matching the kinds of") <+> 
362                  sep [quotes pp_expected <+> ptext SLIT("and"), quotes pp_actual])
363
364     (pp_expected, pp_actual) | swapped   = (pp2, pp1)
365                              | otherwise = (pp1, pp2)
366     (env1, tv1') = tidyOpenTyVar tidy_env tv1
367     (env2, ty2') = tidyOpenType  env1 ty2
368     pp1 = ppr tv1' <+> dcolon <+> ppr (tyVarKind tv1)
369     pp2 = ppr ty2' <+> dcolon <+> ppr (typeKind ty2)
370 \end{code}
371
372 Error message for failure due to an occurs check.
373
374 \begin{code}
375 occurCheckErr :: TcType -> TcType -> TcM a
376 occurCheckErr ty containingTy
377   = do  { env0 <- tcInitTidyEnv
378         ; ty'           <- zonkTcType ty
379         ; containingTy' <- zonkTcType containingTy
380         ; let (env1, tidy_ty1) = tidyOpenType env0 ty'
381               (env2, tidy_ty2) = tidyOpenType env1 containingTy'
382               extra = sep [ppr tidy_ty1, char '=', ppr tidy_ty2]
383         ; failWithTcM (env2, hang msg 2 extra) }
384   where
385     msg = ptext SLIT("Occurs check: cannot construct the infinite type:")
386 \end{code}
387
388 %************************************************************************
389 %*                                                                      *
390         Kind variables
391 %*                                                                      *
392 %************************************************************************
393
394 \begin{code}
395 newCoVars :: [(TcType,TcType)] -> TcM [CoVar]
396 newCoVars spec
397   = do  { us <- newUniqueSupply 
398         ; return [ mkCoVar (mkSysTvName uniq FSLIT("co"))
399                            (mkCoKind ty1 ty2)
400                  | ((ty1,ty2), uniq) <- spec `zip` uniqsFromSupply us] }
401
402 newMetaCoVar :: TcType -> TcType -> TcM TcTyVar
403 newMetaCoVar ty1 ty2 = newMetaTyVar TauTv (mkCoKind ty1 ty2)
404
405 newKindVar :: TcM TcKind
406 newKindVar = do { uniq <- newUnique
407                 ; ref <- newMutVar Flexi
408                 ; return (mkTyVarTy (mkKindVar uniq ref)) }
409
410 newKindVars :: Int -> TcM [TcKind]
411 newKindVars n = mappM (\ _ -> newKindVar) (nOfThem n ())
412 \end{code}
413
414
415 %************************************************************************
416 %*                                                                      *
417         SkolemTvs (immutable)
418 %*                                                                      *
419 %************************************************************************
420
421 \begin{code}
422 mkSkolTyVar :: Name -> Kind -> SkolemInfo -> TcTyVar
423 mkSkolTyVar name kind info = mkTcTyVar name kind (SkolemTv info)
424
425 tcSkolSigType :: SkolemInfo -> Type -> TcM ([TcTyVar], TcThetaType, TcType)
426 -- Instantiate a type signature with skolem constants, but 
427 -- do *not* give them fresh names, because we want the name to
428 -- be in the type environment -- it is lexically scoped.
429 tcSkolSigType info ty = tcInstType (\tvs -> return (tcSkolSigTyVars info tvs)) ty
430
431 tcSkolSigTyVars :: SkolemInfo -> [TyVar] -> [TcTyVar]
432 -- Make skolem constants, but do *not* give them new names, as above
433 tcSkolSigTyVars info tyvars = [ mkSkolTyVar (tyVarName tv) (tyVarKind tv) info
434                               | tv <- tyvars ]
435
436 tcInstSkolTyVar :: SkolemInfo -> Maybe SrcSpan -> TyVar -> TcM TcTyVar
437 -- Instantiate the tyvar, using 
438 --      * the occ-name and kind of the supplied tyvar, 
439 --      * the unique from the monad,
440 --      * the location either from the tyvar (mb_loc = Nothing)
441 --        or from mb_loc (Just loc)
442 tcInstSkolTyVar info mb_loc tyvar
443   = do  { uniq <- newUnique
444         ; let old_name = tyVarName tyvar
445               kind     = tyVarKind tyvar
446               loc      = mb_loc `orElse` getSrcSpan old_name
447               new_name = mkInternalName uniq (nameOccName old_name) loc
448         ; return (mkSkolTyVar new_name kind info) }
449
450 tcInstSkolTyVars :: SkolemInfo -> [TyVar] -> TcM [TcTyVar]
451 -- Get the location from the monad
452 tcInstSkolTyVars info tyvars 
453   = do  { span <- getSrcSpanM
454         ; mapM (tcInstSkolTyVar info (Just span)) tyvars }
455
456 tcInstSkolType :: SkolemInfo -> TcType -> TcM ([TcTyVar], TcThetaType, TcType)
457 -- Instantiate a type with fresh skolem constants
458 -- Binding location comes from the monad
459 tcInstSkolType info ty = tcInstType (tcInstSkolTyVars info) ty
460 \end{code}
461
462
463 %************************************************************************
464 %*                                                                      *
465         MetaTvs (meta type variables; mutable)
466 %*                                                                      *
467 %************************************************************************
468
469 \begin{code}
470 newMetaTyVar :: BoxInfo -> Kind -> TcM TcTyVar
471 -- Make a new meta tyvar out of thin air
472 newMetaTyVar box_info kind
473   = do  { uniq <- newUnique
474         ; ref <- newMutVar Flexi
475         ; let name = mkSysTvName uniq fs 
476               fs = case box_info of
477                         BoxTv   -> FSLIT("t")
478                         TauTv   -> FSLIT("t")
479                         SigTv _ -> FSLIT("a")
480                 -- We give BoxTv and TauTv the same string, because
481                 -- otherwise we get user-visible differences in error
482                 -- messages, which are confusing.  If you want to see
483                 -- the box_info of each tyvar, use -dppr-debug
484         ; return (mkTcTyVar name kind (MetaTv box_info ref)) }
485
486 instMetaTyVar :: BoxInfo -> TyVar -> TcM TcTyVar
487 -- Make a new meta tyvar whose Name and Kind 
488 -- come from an existing TyVar
489 instMetaTyVar box_info tyvar
490   = do  { uniq <- newUnique
491         ; ref <- newMutVar Flexi
492         ; let name = setNameUnique (tyVarName tyvar) uniq
493               kind = tyVarKind tyvar
494         ; return (mkTcTyVar name kind (MetaTv box_info ref)) }
495
496 readMetaTyVar :: TyVar -> TcM MetaDetails
497 readMetaTyVar tyvar = ASSERT2( isMetaTyVar tyvar, ppr tyvar )
498                       readMutVar (metaTvRef tyvar)
499
500 isFilledMetaTyVar :: TyVar -> TcM Bool
501 -- True of a filled-in (Indirect) meta type variable
502 isFilledMetaTyVar tv
503   | not (isTcTyVar tv) = return False
504   | MetaTv _ ref <- tcTyVarDetails tv
505   = do  { details <- readMutVar ref
506         ; return (isIndirect details) }
507   | otherwise = return False
508
509 writeMetaTyVar :: TcTyVar -> TcType -> TcM ()
510 #ifndef DEBUG
511 writeMetaTyVar tyvar ty = writeMutVar (metaTvRef tyvar) (Indirect ty)
512 #else
513 writeMetaTyVar tyvar ty
514   | not (isMetaTyVar tyvar)
515   = pprTrace "writeMetaTyVar" (ppr tyvar) $
516     returnM ()
517
518   | otherwise
519   = ASSERT( isMetaTyVar tyvar )
520     -- TOM: It should also work for coercions
521     -- ASSERT2( k2 `isSubKind` k1, (ppr tyvar <+> ppr k1) $$ (ppr ty <+> ppr k2) )
522     do  { ASSERTM2( do { details <- readMetaTyVar tyvar; return (isFlexi details) }, ppr tyvar )
523         ; writeMutVar (metaTvRef tyvar) (Indirect ty) }
524   where
525     k1 = tyVarKind tyvar
526     k2 = typeKind ty
527 #endif
528 \end{code}
529
530
531 %************************************************************************
532 %*                                                                      *
533         MetaTvs: TauTvs
534 %*                                                                      *
535 %************************************************************************
536
537 \begin{code}
538 newFlexiTyVar :: Kind -> TcM TcTyVar
539 newFlexiTyVar kind = newMetaTyVar TauTv kind
540
541 newFlexiTyVarTy  :: Kind -> TcM TcType
542 newFlexiTyVarTy kind
543   = newFlexiTyVar kind  `thenM` \ tc_tyvar ->
544     returnM (TyVarTy tc_tyvar)
545
546 newFlexiTyVarTys :: Int -> Kind -> TcM [TcType]
547 newFlexiTyVarTys n kind = mappM newFlexiTyVarTy (nOfThem n kind)
548
549 tcInstTyVar :: TyVar -> TcM TcTyVar
550 -- Instantiate with a META type variable
551 tcInstTyVar tyvar = instMetaTyVar TauTv tyvar
552
553 tcInstTyVars :: [TyVar] -> TcM ([TcTyVar], [TcType], TvSubst)
554 -- Instantiate with META type variables
555 tcInstTyVars tyvars
556   = do  { tc_tvs <- mapM tcInstTyVar tyvars
557         ; let tys = mkTyVarTys tc_tvs
558         ; returnM (tc_tvs, tys, zipTopTvSubst tyvars tys) }
559                 -- Since the tyvars are freshly made,
560                 -- they cannot possibly be captured by
561                 -- any existing for-alls.  Hence zipTopTvSubst
562 \end{code}
563
564
565 %************************************************************************
566 %*                                                                      *
567         MetaTvs: SigTvs
568 %*                                                                      *
569 %************************************************************************
570
571 \begin{code}
572 tcInstSigTyVars :: Bool -> SkolemInfo -> [TyVar] -> TcM [TcTyVar]
573 -- Instantiate with skolems or meta SigTvs; depending on use_skols
574 -- Always take location info from the supplied tyvars
575 tcInstSigTyVars use_skols skol_info tyvars 
576   | use_skols
577   = mapM (tcInstSkolTyVar skol_info Nothing) tyvars
578
579   | otherwise
580   = mapM (instMetaTyVar (SigTv skol_info)) tyvars
581
582 zonkSigTyVar :: TcTyVar -> TcM TcTyVar
583 zonkSigTyVar sig_tv 
584   | isSkolemTyVar sig_tv 
585   = return sig_tv       -- Happens in the call in TcBinds.checkDistinctTyVars
586   | otherwise
587   = ASSERT( isSigTyVar sig_tv )
588     do { ty <- zonkTcTyVar sig_tv
589        ; return (tcGetTyVar "zonkSigTyVar" ty) }
590         -- 'ty' is bound to be a type variable, because SigTvs
591         -- can only be unified with type variables
592 \end{code}
593
594
595 %************************************************************************
596 %*                                                                      *
597         MetaTvs: BoxTvs
598 %*                                                                      *
599 %************************************************************************
600
601 \begin{code}
602 newBoxyTyVar :: Kind -> TcM BoxyTyVar
603 newBoxyTyVar kind = newMetaTyVar BoxTv kind
604
605 newBoxyTyVars :: [Kind] -> TcM [BoxyTyVar]
606 newBoxyTyVars kinds = mapM newBoxyTyVar kinds
607
608 newBoxyTyVarTys :: [Kind] -> TcM [BoxyType]
609 newBoxyTyVarTys kinds = do { tvs <- mapM newBoxyTyVar kinds; return (mkTyVarTys tvs) }
610
611 readFilledBox :: BoxyTyVar -> TcM TcType
612 -- Read the contents of the box, which should be filled in by now
613 readFilledBox box_tv = ASSERT( isBoxyTyVar box_tv )
614                        do { cts <- readMetaTyVar box_tv
615                           ; case cts of
616                                 Flexi -> pprPanic "readFilledBox" (ppr box_tv)
617                                 Indirect ty -> return ty }
618
619 tcInstBoxyTyVar :: TyVar -> TcM BoxyTyVar
620 -- Instantiate with a BOXY type variable
621 tcInstBoxyTyVar tyvar = instMetaTyVar BoxTv tyvar
622 \end{code}
623
624
625 %************************************************************************
626 %*                                                                      *
627 \subsection{Putting and getting  mutable type variables}
628 %*                                                                      *
629 %************************************************************************
630
631 But it's more fun to short out indirections on the way: If this
632 version returns a TyVar, then that TyVar is unbound.  If it returns
633 any other type, then there might be bound TyVars embedded inside it.
634
635 We return Nothing iff the original box was unbound.
636
637 \begin{code}
638 data LookupTyVarResult  -- The result of a lookupTcTyVar call
639   = DoneTv TcTyVarDetails       -- SkolemTv or virgin MetaTv
640   | IndirectTv TcType
641
642 lookupTcTyVar :: TcTyVar -> TcM LookupTyVarResult
643 lookupTcTyVar tyvar 
644   = ASSERT2( isTcTyVar tyvar, ppr tyvar )
645     case details of
646       SkolemTv _   -> return (DoneTv details)
647       MetaTv _ ref -> do { meta_details <- readMutVar ref
648                          ; case meta_details of
649                             Indirect ty -> return (IndirectTv ty)
650                             Flexi -> return (DoneTv details) }
651   where
652     details =  tcTyVarDetails tyvar
653
654 {- 
655 -- gaw 2004 We aren't shorting anything out anymore, at least for now
656 getTcTyVar tyvar
657   | not (isTcTyVar tyvar)
658   = pprTrace "getTcTyVar" (ppr tyvar) $
659     returnM (Just (mkTyVarTy tyvar))
660
661   | otherwise
662   = ASSERT2( isTcTyVar tyvar, ppr tyvar )
663     readMetaTyVar tyvar                         `thenM` \ maybe_ty ->
664     case maybe_ty of
665         Just ty -> short_out ty                         `thenM` \ ty' ->
666                    writeMetaTyVar tyvar (Just ty')      `thenM_`
667                    returnM (Just ty')
668
669         Nothing    -> returnM Nothing
670
671 short_out :: TcType -> TcM TcType
672 short_out ty@(TyVarTy tyvar)
673   | not (isTcTyVar tyvar)
674   = returnM ty
675
676   | otherwise
677   = readMetaTyVar tyvar `thenM` \ maybe_ty ->
678     case maybe_ty of
679         Just ty' -> short_out ty'                       `thenM` \ ty' ->
680                     writeMetaTyVar tyvar (Just ty')     `thenM_`
681                     returnM ty'
682
683         other    -> returnM ty
684
685 short_out other_ty = returnM other_ty
686 -}
687 \end{code}
688
689
690 %************************************************************************
691 %*                                                                      *
692 \subsection{Zonking -- the exernal interfaces}
693 %*                                                                      *
694 %************************************************************************
695
696 -----------------  Type variables
697
698 \begin{code}
699 zonkTcTyVars :: [TcTyVar] -> TcM [TcType]
700 zonkTcTyVars tyvars = mappM zonkTcTyVar tyvars
701
702 zonkTcTyVarsAndFV :: [TcTyVar] -> TcM TcTyVarSet
703 zonkTcTyVarsAndFV tyvars = mappM zonkTcTyVar tyvars     `thenM` \ tys ->
704                            returnM (tyVarsOfTypes tys)
705
706 zonkTcTyVar :: TcTyVar -> TcM TcType
707 zonkTcTyVar tyvar = ASSERT2( isTcTyVar tyvar, ppr tyvar)
708                     zonk_tc_tyvar (\ tv -> returnM (TyVarTy tv)) tyvar
709 \end{code}
710
711 -----------------  Types
712
713 \begin{code}
714 zonkTcType :: TcType -> TcM TcType
715 zonkTcType ty = zonkType (\ tv -> returnM (TyVarTy tv)) ty
716
717 zonkTcTypes :: [TcType] -> TcM [TcType]
718 zonkTcTypes tys = mappM zonkTcType tys
719
720 zonkTcClassConstraints cts = mappM zonk cts
721     where zonk (clas, tys)
722             = zonkTcTypes tys   `thenM` \ new_tys ->
723               returnM (clas, new_tys)
724
725 zonkTcThetaType :: TcThetaType -> TcM TcThetaType
726 zonkTcThetaType theta = mappM zonkTcPredType theta
727
728 zonkTcPredType :: TcPredType -> TcM TcPredType
729 zonkTcPredType (ClassP c ts)
730   = zonkTcTypes ts      `thenM` \ new_ts ->
731     returnM (ClassP c new_ts)
732 zonkTcPredType (IParam n t)
733   = zonkTcType t        `thenM` \ new_t ->
734     returnM (IParam n new_t)
735 zonkTcPredType (EqPred t1 t2)
736   = zonkTcType t1       `thenM` \ new_t1 ->
737     zonkTcType t2       `thenM` \ new_t2 ->
738     returnM (EqPred new_t1 new_t2)
739 \end{code}
740
741 -------------------  These ...ToType, ...ToKind versions
742                      are used at the end of type checking
743
744 \begin{code}
745 zonkTopTyVar :: TcTyVar -> TcM TcTyVar
746 -- zonkTopTyVar is used, at the top level, on any un-instantiated meta type variables
747 -- to default the kind of ? and ?? etc to *.  This is important to ensure that
748 -- instance declarations match.  For example consider
749 --      instance Show (a->b)
750 --      foo x = show (\_ -> True)
751 -- Then we'll get a constraint (Show (p ->q)) where p has argTypeKind (printed ??), 
752 -- and that won't match the typeKind (*) in the instance decl.
753 --
754 -- Because we are at top level, no further constraints are going to affect these
755 -- type variables, so it's time to do it by hand.  However we aren't ready
756 -- to default them fully to () or whatever, because the type-class defaulting
757 -- rules have yet to run.
758
759 zonkTopTyVar tv
760   | k `eqKind` default_k = return tv
761   | otherwise
762   = do  { tv' <- newFlexiTyVar default_k
763         ; writeMetaTyVar tv (mkTyVarTy tv') 
764         ; return tv' }
765   where
766     k = tyVarKind tv
767     default_k = defaultKind k
768
769 zonkQuantifiedTyVars :: [TcTyVar] -> TcM [TcTyVar]
770 zonkQuantifiedTyVars = mappM zonkQuantifiedTyVar
771
772 zonkQuantifiedTyVar :: TcTyVar -> TcM TcTyVar
773 -- zonkQuantifiedTyVar is applied to the a TcTyVar when quantifying over it.
774 --
775 -- The quantified type variables often include meta type variables
776 -- we want to freeze them into ordinary type variables, and
777 -- default their kind (e.g. from OpenTypeKind to TypeKind)
778 --                      -- see notes with Kind.defaultKind
779 -- The meta tyvar is updated to point to the new skolem TyVar.  Now any 
780 -- bound occurences of the original type variable will get zonked to 
781 -- the immutable version.
782 --
783 -- We leave skolem TyVars alone; they are immutable.
784 zonkQuantifiedTyVar tv
785   | ASSERT( isTcTyVar tv ) 
786     isSkolemTyVar tv = return tv
787         -- It might be a skolem type variable, 
788         -- for example from a user type signature
789
790   | otherwise   -- It's a meta-type-variable
791   = do  { details <- readMetaTyVar tv
792
793         -- Create the new, frozen, skolem type variable
794         -- We zonk to a skolem, not to a regular TcVar
795         -- See Note [Zonking to Skolem]
796         ; let final_kind = defaultKind (tyVarKind tv)
797               final_tv   = mkSkolTyVar (tyVarName tv) final_kind UnkSkol
798
799         -- Bind the meta tyvar to the new tyvar
800         ; case details of
801             Indirect ty -> WARN( True, ppr tv $$ ppr ty ) 
802                            return ()
803                 -- [Sept 04] I don't think this should happen
804                 -- See note [Silly Type Synonym]
805
806             Flexi -> writeMetaTyVar tv (mkTyVarTy final_tv)
807
808         -- Return the new tyvar
809         ; return final_tv }
810 \end{code}
811
812 Note [Silly Type Synonyms]
813 ~~~~~~~~~~~~~~~~~~~~~~~~~~
814 Consider this:
815         type C u a = u  -- Note 'a' unused
816
817         foo :: (forall a. C u a -> C u a) -> u
818         foo x = ...
819
820         bar :: Num u => u
821         bar = foo (\t -> t + t)
822
823 * From the (\t -> t+t) we get type  {Num d} =>  d -> d
824   where d is fresh.
825
826 * Now unify with type of foo's arg, and we get:
827         {Num (C d a)} =>  C d a -> C d a
828   where a is fresh.
829
830 * Now abstract over the 'a', but float out the Num (C d a) constraint
831   because it does not 'really' mention a.  (see exactTyVarsOfType)
832   The arg to foo becomes
833         /\a -> \t -> t+t
834
835 * So we get a dict binding for Num (C d a), which is zonked to give
836         a = ()
837   [Note Sept 04: now that we are zonking quantified type variables
838   on construction, the 'a' will be frozen as a regular tyvar on
839   quantification, so the floated dict will still have type (C d a).
840   Which renders this whole note moot; happily!]
841
842 * Then the /\a abstraction has a zonked 'a' in it.
843
844 All very silly.   I think its harmless to ignore the problem.  We'll end up with
845 a /\a in the final result but all the occurrences of a will be zonked to ()
846
847 Note [Zonking to Skolem]
848 ~~~~~~~~~~~~~~~~~~~~~~~~
849 We used to zonk quantified type variables to regular TyVars.  However, this
850 leads to problems.  Consider this program from the regression test suite:
851
852   eval :: Int -> String -> String -> String
853   eval 0 root actual = evalRHS 0 root actual
854
855   evalRHS :: Int -> a
856   evalRHS 0 root actual = eval 0 root actual
857
858 It leads to the deferral of an equality
859
860   (String -> String -> String) ~ a
861
862 which is propagated up to the toplevel (see TcSimplify.tcSimplifyInferCheck).
863 In the meantime `a' is zonked and quantified to form `evalRHS's signature.
864 This has the *side effect* of also zonking the `a' in the deferred equality
865 (which at this point is being handed around wrapped in an implication
866 constraint).
867
868 Finally, the equality (with the zonked `a') will be handed back to the
869 simplifier by TcRnDriver.tcRnSrcDecls calling TcSimplify.tcSimplifyTop.
870 If we zonk `a' with a regular type variable, we will have this regular type
871 variable now floating around in the simplifier, which in many places assumes to
872 only see proper TcTyVars.
873
874 We can avoid this problem by zonking with a skolem.  The skolem is rigid
875 (which we requirefor a quantified variable), but is still a TcTyVar that the
876 simplifier knows how to deal with.
877
878
879 %************************************************************************
880 %*                                                                      *
881 \subsection{Zonking -- the main work-horses: zonkType, zonkTyVar}
882 %*                                                                      *
883 %*              For internal use only!                                  *
884 %*                                                                      *
885 %************************************************************************
886
887 \begin{code}
888 -- For unbound, mutable tyvars, zonkType uses the function given to it
889 -- For tyvars bound at a for-all, zonkType zonks them to an immutable
890 --      type variable and zonks the kind too
891
892 zonkType :: (TcTyVar -> TcM Type)       -- What to do with unbound mutable type variables
893                                         -- see zonkTcType, and zonkTcTypeToType
894          -> TcType
895          -> TcM Type
896 zonkType unbound_var_fn ty
897   = go ty
898   where
899     go (NoteTy _ ty2)    = go ty2       -- Discard free-tyvar annotations
900                          
901     go (TyConApp tc tys) = mappM go tys `thenM` \ tys' ->
902                            returnM (TyConApp tc tys')
903                             
904     go (PredTy p)        = go_pred p            `thenM` \ p' ->
905                            returnM (PredTy p')
906                          
907     go (FunTy arg res)   = go arg               `thenM` \ arg' ->
908                            go res               `thenM` \ res' ->
909                            returnM (FunTy arg' res')
910                          
911     go (AppTy fun arg)   = go fun               `thenM` \ fun' ->
912                            go arg               `thenM` \ arg' ->
913                            returnM (mkAppTy fun' arg')
914                 -- NB the mkAppTy; we might have instantiated a
915                 -- type variable to a type constructor, so we need
916                 -- to pull the TyConApp to the top.
917
918         -- The two interesting cases!
919     go (TyVarTy tyvar) | isTcTyVar tyvar = zonk_tc_tyvar unbound_var_fn tyvar
920                        | otherwise       = return (TyVarTy tyvar)
921                 -- Ordinary (non Tc) tyvars occur inside quantified types
922
923     go (ForAllTy tyvar ty) = ASSERT( isImmutableTyVar tyvar )
924                              go ty              `thenM` \ ty' ->
925                              returnM (ForAllTy tyvar ty')
926
927     go_pred (ClassP c tys)   = mappM go tys     `thenM` \ tys' ->
928                                returnM (ClassP c tys')
929     go_pred (IParam n ty)    = go ty            `thenM` \ ty' ->
930                                returnM (IParam n ty')
931     go_pred (EqPred ty1 ty2) = go ty1           `thenM` \ ty1' ->
932                                go ty2           `thenM` \ ty2' ->
933                                returnM (EqPred ty1' ty2')
934
935 zonk_tc_tyvar :: (TcTyVar -> TcM Type)          -- What to do for an unbound mutable variable
936               -> TcTyVar -> TcM TcType
937 zonk_tc_tyvar unbound_var_fn tyvar 
938   | not (isMetaTyVar tyvar)     -- Skolems
939   = returnM (TyVarTy tyvar)
940
941   | otherwise                   -- Mutables
942   = do  { cts <- readMetaTyVar tyvar
943         ; case cts of
944             Flexi       -> unbound_var_fn tyvar    -- Unbound meta type variable
945             Indirect ty -> zonkType unbound_var_fn ty  }
946 \end{code}
947
948
949
950 %************************************************************************
951 %*                                                                      *
952                         Zonking kinds
953 %*                                                                      *
954 %************************************************************************
955
956 \begin{code}
957 readKindVar  :: KindVar -> TcM (MetaDetails)
958 writeKindVar :: KindVar -> TcKind -> TcM ()
959 readKindVar  kv = readMutVar (kindVarRef kv)
960 writeKindVar kv val = writeMutVar (kindVarRef kv) (Indirect val)
961
962 -------------
963 zonkTcKind :: TcKind -> TcM TcKind
964 zonkTcKind k = zonkTcType k
965
966 -------------
967 zonkTcKindToKind :: TcKind -> TcM Kind
968 -- When zonking a TcKind to a kind, we need to instantiate kind variables,
969 -- Haskell specifies that * is to be used, so we follow that.
970 zonkTcKindToKind k = zonkType (\ _ -> return liftedTypeKind) k
971 \end{code}
972                         
973 %************************************************************************
974 %*                                                                      *
975 \subsection{Checking a user type}
976 %*                                                                      *
977 %************************************************************************
978
979 When dealing with a user-written type, we first translate it from an HsType
980 to a Type, performing kind checking, and then check various things that should 
981 be true about it.  We don't want to perform these checks at the same time
982 as the initial translation because (a) they are unnecessary for interface-file
983 types and (b) when checking a mutually recursive group of type and class decls,
984 we can't "look" at the tycons/classes yet.  Also, the checks are are rather
985 diverse, and used to really mess up the other code.
986
987 One thing we check for is 'rank'.  
988
989         Rank 0:         monotypes (no foralls)
990         Rank 1:         foralls at the front only, Rank 0 inside
991         Rank 2:         foralls at the front, Rank 1 on left of fn arrow,
992
993         basic ::= tyvar | T basic ... basic
994
995         r2  ::= forall tvs. cxt => r2a
996         r2a ::= r1 -> r2a | basic
997         r1  ::= forall tvs. cxt => r0
998         r0  ::= r0 -> r0 | basic
999         
1000 Another thing is to check that type synonyms are saturated. 
1001 This might not necessarily show up in kind checking.
1002         type A i = i
1003         data T k = MkT (k Int)
1004         f :: T A        -- BAD!
1005
1006         
1007 \begin{code}
1008 checkValidType :: UserTypeCtxt -> Type -> TcM ()
1009 -- Checks that the type is valid for the given context
1010 checkValidType ctxt ty
1011   = traceTc (text "checkValidType" <+> ppr ty)  `thenM_`
1012     doptM Opt_UnboxedTuples `thenM` \ unboxed ->
1013     doptM Opt_Rank2Types        `thenM` \ rank2 ->
1014     doptM Opt_RankNTypes        `thenM` \ rankn ->
1015     doptM Opt_PolymorphicComponents     `thenM` \ polycomp ->
1016     let 
1017         rank | rankn = Arbitrary
1018              | rank2 = Rank 2
1019              | otherwise
1020              = case ctxt of     -- Haskell 98
1021                  GenPatCtxt     -> Rank 0
1022                  LamPatSigCtxt  -> Rank 0
1023                  BindPatSigCtxt -> Rank 0
1024                  DefaultDeclCtxt-> Rank 0
1025                  ResSigCtxt     -> Rank 0
1026                  TySynCtxt _    -> Rank 0
1027                  ExprSigCtxt    -> Rank 1
1028                  FunSigCtxt _   -> Rank 1
1029                  ConArgCtxt _   -> if polycomp
1030                            then Rank 2
1031                                 -- We are given the type of the entire
1032                                 -- constructor, hence rank 1
1033                            else Rank 1
1034                  ForSigCtxt _   -> Rank 1
1035                  SpecInstCtxt   -> Rank 1
1036
1037         actual_kind = typeKind ty
1038
1039         kind_ok = case ctxt of
1040                         TySynCtxt _  -> True    -- Any kind will do
1041                         ResSigCtxt   -> isSubOpenTypeKind        actual_kind
1042                         ExprSigCtxt  -> isSubOpenTypeKind        actual_kind
1043                         GenPatCtxt   -> isLiftedTypeKind actual_kind
1044                         ForSigCtxt _ -> isLiftedTypeKind actual_kind
1045                         other        -> isSubArgTypeKind    actual_kind
1046         
1047         ubx_tup = case ctxt of
1048                       TySynCtxt _ | unboxed -> UT_Ok
1049                       ExprSigCtxt | unboxed -> UT_Ok
1050                       _                     -> UT_NotOk
1051     in
1052         -- Check that the thing has kind Type, and is lifted if necessary
1053     checkTc kind_ok (kindErr actual_kind)       `thenM_`
1054
1055         -- Check the internal validity of the type itself
1056     check_poly_type rank ubx_tup ty             `thenM_`
1057
1058     traceTc (text "checkValidType done" <+> ppr ty)
1059 \end{code}
1060
1061
1062 \begin{code}
1063 data Rank = Rank Int | Arbitrary
1064
1065 decRank :: Rank -> Rank
1066 decRank Arbitrary = Arbitrary
1067 decRank (Rank n)  = Rank (n-1)
1068
1069 ----------------------------------------
1070 data UbxTupFlag = UT_Ok | UT_NotOk
1071         -- The "Ok" version means "ok if -fglasgow-exts is on"
1072
1073 ----------------------------------------
1074 check_poly_type :: Rank -> UbxTupFlag -> Type -> TcM ()
1075 check_poly_type (Rank 0) ubx_tup ty 
1076   = check_tau_type (Rank 0) ubx_tup ty
1077
1078 check_poly_type rank ubx_tup ty 
1079   | null tvs && null theta
1080   = check_tau_type rank ubx_tup ty
1081   | otherwise
1082   = do  { check_valid_theta SigmaCtxt theta
1083         ; check_poly_type rank ubx_tup tau      -- Allow foralls to right of arrow
1084         ; checkFreeness tvs theta
1085         ; checkAmbiguity tvs theta (tyVarsOfType tau) }
1086   where
1087     (tvs, theta, tau) = tcSplitSigmaTy ty
1088    
1089 ----------------------------------------
1090 check_arg_type :: Type -> TcM ()
1091 -- The sort of type that can instantiate a type variable,
1092 -- or be the argument of a type constructor.
1093 -- Not an unboxed tuple, but now *can* be a forall (since impredicativity)
1094 -- Other unboxed types are very occasionally allowed as type
1095 -- arguments depending on the kind of the type constructor
1096 -- 
1097 -- For example, we want to reject things like:
1098 --
1099 --      instance Ord a => Ord (forall s. T s a)
1100 -- and
1101 --      g :: T s (forall b.b)
1102 --
1103 -- NB: unboxed tuples can have polymorphic or unboxed args.
1104 --     This happens in the workers for functions returning
1105 --     product types with polymorphic components.
1106 --     But not in user code.
1107 -- Anyway, they are dealt with by a special case in check_tau_type
1108
1109 check_arg_type ty 
1110   = check_poly_type Arbitrary UT_NotOk ty       `thenM_` 
1111     checkTc (not (isUnLiftedType ty)) (unliftedArgErr ty)
1112
1113 ----------------------------------------
1114 check_tau_type :: Rank -> UbxTupFlag -> Type -> TcM ()
1115 -- Rank is allowed rank for function args
1116 -- No foralls otherwise
1117
1118 check_tau_type rank ubx_tup ty@(ForAllTy _ _)       = failWithTc (forAllTyErr ty)
1119 check_tau_type rank ubx_tup ty@(FunTy (PredTy _) _) = failWithTc (forAllTyErr ty)
1120         -- Reject e.g. (Maybe (?x::Int => Int)), with a decent error message
1121
1122 -- Naked PredTys don't usually show up, but they can as a result of
1123 --      {-# SPECIALISE instance Ord Char #-}
1124 -- The Right Thing would be to fix the way that SPECIALISE instance pragmas
1125 -- are handled, but the quick thing is just to permit PredTys here.
1126 check_tau_type rank ubx_tup (PredTy sty) = getDOpts             `thenM` \ dflags ->
1127                                            check_pred_ty dflags TypeCtxt sty
1128
1129 check_tau_type rank ubx_tup (TyVarTy _)       = returnM ()
1130 check_tau_type rank ubx_tup ty@(FunTy arg_ty res_ty)
1131   = check_poly_type (decRank rank) UT_NotOk arg_ty      `thenM_`
1132     check_poly_type rank           UT_Ok    res_ty
1133
1134 check_tau_type rank ubx_tup (AppTy ty1 ty2)
1135   = check_arg_type ty1 `thenM_` check_arg_type ty2
1136
1137 check_tau_type rank ubx_tup (NoteTy other_note ty)
1138   = check_tau_type rank ubx_tup ty
1139
1140 check_tau_type rank ubx_tup ty@(TyConApp tc tys)
1141   | isSynTyCon tc
1142   = do  {       -- Check that the synonym has enough args
1143                 -- This applies equally to open and closed synonyms
1144                 -- It's OK to have an *over-applied* type synonym
1145                 --      data Tree a b = ...
1146                 --      type Foo a = Tree [a]
1147                 --      f :: Foo a b -> ...
1148           checkTc (tyConArity tc <= length tys) arity_msg
1149
1150         -- See Note [Liberal type synonyms]
1151         ; liberal <- doptM Opt_LiberalTypeSynonyms
1152         ; if not liberal || isOpenSynTyCon tc then
1153                 -- For H98 and synonym families, do check the type args
1154                 mappM_ check_arg_type tys
1155
1156           else  -- In the liberal case (only for closed syns), expand then check
1157           case tcView ty of   
1158              Just ty' -> check_tau_type rank ubx_tup ty' 
1159              Nothing  -> pprPanic "check_tau_type" (ppr ty)
1160     }
1161     
1162   | isUnboxedTupleTyCon tc
1163   = doptM Opt_UnboxedTuples `thenM` \ ub_tuples_allowed ->
1164     checkTc (ubx_tup_ok ub_tuples_allowed) ubx_tup_msg  `thenM_`
1165     mappM_ (check_tau_type (Rank 0) UT_Ok) tys  
1166                 -- Args are allowed to be unlifted, or
1167                 -- more unboxed tuples, so can't use check_arg_ty
1168
1169   | otherwise
1170   = mappM_ check_arg_type tys
1171
1172   where
1173     ubx_tup_ok ub_tuples_allowed = case ubx_tup of { UT_Ok -> ub_tuples_allowed; other -> False }
1174
1175     n_args    = length tys
1176     tc_arity  = tyConArity tc
1177
1178     arity_msg   = arityErr "Type synonym" (tyConName tc) tc_arity n_args
1179     ubx_tup_msg = ubxArgTyErr ty
1180
1181 ----------------------------------------
1182 forAllTyErr     ty = ptext SLIT("Illegal polymorphic or qualified type:") <+> ppr ty
1183 unliftedArgErr  ty = ptext SLIT("Illegal unlifted type argument:") <+> ppr ty
1184 ubxArgTyErr     ty = ptext SLIT("Illegal unboxed tuple type as function argument:") <+> ppr ty
1185 kindErr kind       = ptext SLIT("Expecting an ordinary type, but found a type of kind") <+> ppr kind
1186 \end{code}
1187
1188 Note [Liberal type synonyms]
1189 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1190 If -XLiberalTypeSynonyms is on, expand closed type synonyms *before*
1191 doing validity checking.  This allows us to instantiate a synonym defn
1192 with a for-all type, or with a partially-applied type synonym.
1193         e.g.   type T a b = a
1194                type S m   = m ()
1195                f :: S (T Int)
1196 Here, T is partially applied, so it's illegal in H98.  But if you
1197 expand S first, then T we get just
1198                f :: Int
1199 which is fine.
1200
1201 IMPORTANT: suppose T is a type synonym.  Then we must do validity
1202 checking on an appliation (T ty1 ty2)
1203
1204         *either* before expansion (i.e. check ty1, ty2)
1205         *or* after expansion (i.e. expand T ty1 ty2, and then check)
1206         BUT NOT BOTH
1207
1208 If we do both, we get exponential behaviour!!
1209
1210   data TIACons1 i r c = c i ::: r c
1211   type TIACons2 t x = TIACons1 t (TIACons1 t x)
1212   type TIACons3 t x = TIACons2 t (TIACons1 t x)
1213   type TIACons4 t x = TIACons2 t (TIACons2 t x)
1214   type TIACons7 t x = TIACons4 t (TIACons3 t x)
1215
1216
1217 %************************************************************************
1218 %*                                                                      *
1219 \subsection{Checking a theta or source type}
1220 %*                                                                      *
1221 %************************************************************************
1222
1223 \begin{code}
1224 -- Enumerate the contexts in which a "source type", <S>, can occur
1225 --      Eq a 
1226 -- or   ?x::Int
1227 -- or   r <: {x::Int}
1228 -- or   (N a) where N is a newtype
1229
1230 data SourceTyCtxt
1231   = ClassSCCtxt Name    -- Superclasses of clas
1232                         --      class <S> => C a where ...
1233   | SigmaCtxt           -- Theta part of a normal for-all type
1234                         --      f :: <S> => a -> a
1235   | DataTyCtxt Name     -- Theta part of a data decl
1236                         --      data <S> => T a = MkT a
1237   | TypeCtxt            -- Source type in an ordinary type
1238                         --      f :: N a -> N a
1239   | InstThetaCtxt       -- Context of an instance decl
1240                         --      instance <S> => C [a] where ...
1241                 
1242 pprSourceTyCtxt (ClassSCCtxt c) = ptext SLIT("the super-classes of class") <+> quotes (ppr c)
1243 pprSourceTyCtxt SigmaCtxt       = ptext SLIT("the context of a polymorphic type")
1244 pprSourceTyCtxt (DataTyCtxt tc) = ptext SLIT("the context of the data type declaration for") <+> quotes (ppr tc)
1245 pprSourceTyCtxt InstThetaCtxt   = ptext SLIT("the context of an instance declaration")
1246 pprSourceTyCtxt TypeCtxt        = ptext SLIT("the context of a type")
1247 \end{code}
1248
1249 \begin{code}
1250 checkValidTheta :: SourceTyCtxt -> ThetaType -> TcM ()
1251 checkValidTheta ctxt theta 
1252   = addErrCtxt (checkThetaCtxt ctxt theta) (check_valid_theta ctxt theta)
1253
1254 -------------------------
1255 check_valid_theta ctxt []
1256   = returnM ()
1257 check_valid_theta ctxt theta
1258   = getDOpts                                    `thenM` \ dflags ->
1259     warnTc (notNull dups) (dupPredWarn dups)    `thenM_`
1260     mappM_ (check_pred_ty dflags ctxt) theta
1261   where
1262     (_,dups) = removeDups tcCmpPred theta
1263
1264 -------------------------
1265 check_pred_ty :: DynFlags -> SourceTyCtxt -> PredType -> TcM ()
1266 check_pred_ty dflags ctxt pred@(ClassP cls tys)
1267   = do {        -- Class predicates are valid in all contexts
1268        ; checkTc (arity == n_tys) arity_err
1269
1270                 -- Check the form of the argument types
1271        ; mappM_ check_arg_type tys
1272        ; checkTc (check_class_pred_tys dflags ctxt tys)
1273                  (predTyVarErr pred $$ how_to_allow)
1274        }
1275   where
1276     class_name = className cls
1277     arity      = classArity cls
1278     n_tys      = length tys
1279     arity_err  = arityErr "Class" class_name arity n_tys
1280     how_to_allow = parens (ptext SLIT("Use -XFlexibleContexts to permit this"))
1281
1282 check_pred_ty dflags ctxt pred@(EqPred ty1 ty2)
1283   = do {        -- Equational constraints are valid in all contexts if type
1284                 -- families are permitted
1285        ; checkTc (dopt Opt_TypeFamilies dflags) (eqPredTyErr pred)
1286
1287                 -- Check the form of the argument types
1288        ; check_eq_arg_type ty1
1289        ; check_eq_arg_type ty2
1290        }
1291   where 
1292     check_eq_arg_type = check_poly_type (Rank 0) UT_NotOk
1293
1294 check_pred_ty dflags SigmaCtxt (IParam _ ty) = check_arg_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   = mappM_ 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 $ mappM_ 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) ->
1471
1472     getDOpts                                    `thenM` \ dflags ->
1473     mappM_ check_arg_type tys                   `thenM_`
1474     check_inst_head dflags clas tys             `thenM_`
1475     returnM (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_one tys
1490   where
1491     head_type_synonym_msg = parens (
1492                 text "All instance types must be of the form (T t1 ... tn)" $$
1493                 text "where T is not a synonym." $$
1494                 text "Use -XTypeSynonymInstances if you want to disable this.")
1495
1496     head_type_args_tyvars_msg = parens (
1497                 text "All instance types must be of the form (T a1 ... an)" $$
1498                 text "where a1 ... an are distinct type *variables*" $$
1499                 text "Use -XFlexibleInstances if you want to disable this.")
1500
1501     head_one_type_msg = parens (
1502                 text "Only one type can be given in an instance head." $$
1503                 text "Use -XMultiParamTypeClasses if you want to allow more.")
1504
1505         -- For now, I only allow tau-types (not polytypes) in 
1506         -- the head of an instance decl.  
1507         --      E.g.  instance C (forall a. a->a) is rejected
1508         -- One could imagine generalising that, but I'm not sure
1509         -- what all the consequences might be
1510     check_one ty = do { check_tau_type (Rank 0) UT_NotOk ty
1511                       ; checkTc (not (isUnLiftedType ty)) (unliftedArgErr ty) }
1512
1513 instTypeErr pp_ty msg
1514   = sep [ptext SLIT("Illegal instance declaration for") <+> quotes pp_ty, 
1515          nest 4 msg]
1516 \end{code}
1517
1518
1519 %************************************************************************
1520 %*                                                                      *
1521 \subsection{Checking instance for termination}
1522 %*                                                                      *
1523 %************************************************************************
1524
1525
1526 \begin{code}
1527 checkValidInstance :: [TyVar] -> ThetaType -> Class -> [TcType] -> TcM ()
1528 checkValidInstance tyvars theta clas inst_tys
1529   = do  { undecidable_ok <- doptM Opt_UndecidableInstances
1530
1531         ; checkValidTheta InstThetaCtxt theta
1532         ; checkAmbiguity tyvars theta (tyVarsOfTypes inst_tys)
1533
1534         -- Check that instance inference will terminate (if we care)
1535         -- For Haskell 98 this will already have been done by checkValidTheta,
1536         -- but as we may be using other extensions we need to check.
1537         ; unless undecidable_ok $
1538           mapM_ addErrTc (checkInstTermination inst_tys theta)
1539         
1540         -- The Coverage Condition
1541         ; checkTc (undecidable_ok || checkInstCoverage clas inst_tys)
1542                   (instTypeErr (pprClassPred clas inst_tys) msg)
1543         }
1544   where
1545     msg  = parens (vcat [ptext SLIT("the Coverage Condition fails for one of the functional dependencies;"),
1546                          undecidableMsg])
1547 \end{code}
1548
1549 Termination test: the so-called "Paterson conditions" (see Section 5 of
1550 "Understanding functionsl dependencies via Constraint Handling Rules, 
1551 JFP Jan 2007).
1552
1553 We check that each assertion in the context satisfies:
1554  (1) no variable has more occurrences in the assertion than in the head, and
1555  (2) the assertion has fewer constructors and variables (taken together
1556      and counting repetitions) than the head.
1557 This is only needed with -fglasgow-exts, as Haskell 98 restrictions
1558 (which have already been checked) guarantee termination. 
1559
1560 The underlying idea is that 
1561
1562     for any ground substitution, each assertion in the
1563     context has fewer type constructors than the head.
1564
1565
1566 \begin{code}
1567 checkInstTermination :: [TcType] -> ThetaType -> [Message]
1568 checkInstTermination tys theta
1569   = mapCatMaybes check theta
1570   where
1571    fvs  = fvTypes tys
1572    size = sizeTypes tys
1573    check pred 
1574       | not (null (fvPred pred \\ fvs)) 
1575       = Just (predUndecErr pred nomoreMsg $$ parens undecidableMsg)
1576       | sizePred pred >= size
1577       = Just (predUndecErr pred smallerMsg $$ parens undecidableMsg)
1578       | otherwise
1579       = Nothing
1580
1581 predUndecErr pred msg = sep [msg,
1582                         nest 2 (ptext SLIT("in the constraint:") <+> pprPred pred)]
1583
1584 nomoreMsg = ptext SLIT("Variable occurs more often in a constraint than in the instance head")
1585 smallerMsg = ptext SLIT("Constraint is no smaller than the instance head")
1586 undecidableMsg = ptext SLIT("Use -fallow-undecidable-instances to permit this")
1587 \end{code}
1588
1589
1590 %************************************************************************
1591 %*                                                                      *
1592         Checking the context of a derived instance declaration
1593 %*                                                                      *
1594 %************************************************************************
1595
1596 Note [Exotic derived instance contexts]
1597 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1598 In a 'derived' instance declaration, we *infer* the context.  It's a
1599 bit unclear what rules we should apply for this; the Haskell report is
1600 silent.  Obviously, constraints like (Eq a) are fine, but what about
1601         data T f a = MkT (f a) deriving( Eq )
1602 where we'd get an Eq (f a) constraint.  That's probably fine too.
1603
1604 One could go further: consider
1605         data T a b c = MkT (Foo a b c) deriving( Eq )
1606         instance (C Int a, Eq b, Eq c) => Eq (Foo a b c)
1607
1608 Notice that this instance (just) satisfies the Paterson termination 
1609 conditions.  Then we *could* derive an instance decl like this:
1610
1611         instance (C Int a, Eq b, Eq c) => Eq (T a b c) 
1612
1613 even though there is no instance for (C Int a), because there just
1614 *might* be an instance for, say, (C Int Bool) at a site where we
1615 need the equality instance for T's.  
1616
1617 However, this seems pretty exotic, and it's quite tricky to allow
1618 this, and yet give sensible error messages in the (much more common)
1619 case where we really want that instance decl for C.
1620
1621 So for now we simply require that the derived instance context
1622 should have only type-variable constraints.
1623
1624 Here is another example:
1625         data Fix f = In (f (Fix f)) deriving( Eq )
1626 Here, if we are prepared to allow -fallow-undecidable-instances we
1627 could derive the instance
1628         instance Eq (f (Fix f)) => Eq (Fix f)
1629 but this is so delicate that I don't think it should happen inside
1630 'deriving'. If you want this, write it yourself!
1631
1632 NB: if you want to lift this condition, make sure you still meet the
1633 termination conditions!  If not, the deriving mechanism generates
1634 larger and larger constraints.  Example:
1635   data Succ a = S a
1636   data Seq a = Cons a (Seq (Succ a)) | Nil deriving Show
1637
1638 Note the lack of a Show instance for Succ.  First we'll generate
1639   instance (Show (Succ a), Show a) => Show (Seq a)
1640 and then
1641   instance (Show (Succ (Succ a)), Show (Succ a), Show a) => Show (Seq a)
1642 and so on.  Instead we want to complain of no instance for (Show (Succ a)).
1643
1644 The bottom line
1645 ~~~~~~~~~~~~~~~
1646 Allow constraints which consist only of type variables, with no repeats.
1647
1648 \begin{code}
1649 validDerivPred :: PredType -> Bool
1650 validDerivPred (ClassP cls tys) = hasNoDups fvs && sizeTypes tys == length fvs
1651                                 where fvs = fvTypes tys
1652 validDerivPred otehr            = False
1653 \end{code}
1654
1655 %************************************************************************
1656 %*                                                                      *
1657         Checking type instance well-formedness and termination
1658 %*                                                                      *
1659 %************************************************************************
1660
1661 \begin{code}
1662 -- Check that a "type instance" is well-formed (which includes decidability
1663 -- unless -fallow-undecidable-instances is given).
1664 --
1665 checkValidTypeInst :: [Type] -> Type -> TcM ()
1666 checkValidTypeInst typats rhs
1667   = do { -- left-hand side contains no type family applications
1668          -- (vanilla synonyms are fine, though)
1669        ; mappM_ checkTyFamFreeness typats
1670
1671          -- the right-hand side is a tau type
1672        ; checkTc (isTauTy rhs) $ 
1673            polyTyErr rhs
1674
1675          -- we have a decidable instance unless otherwise permitted
1676        ; undecidable_ok <- doptM Opt_UndecidableInstances
1677        ; unless undecidable_ok $
1678            mapM_ addErrTc (checkFamInst typats (tyFamInsts rhs))
1679        }
1680
1681 -- Make sure that each type family instance is 
1682 --   (1) strictly smaller than the lhs,
1683 --   (2) mentions no type variable more often than the lhs, and
1684 --   (3) does not contain any further type family instances.
1685 --
1686 checkFamInst :: [Type]                  -- lhs
1687              -> [(TyCon, [Type])]       -- type family instances
1688              -> [Message]
1689 checkFamInst lhsTys famInsts
1690   = mapCatMaybes check famInsts
1691   where
1692    size = sizeTypes lhsTys
1693    fvs  = fvTypes lhsTys
1694    check (tc, tys)
1695       | not (all isTyFamFree tys)
1696       = Just (famInstUndecErr famInst nestedMsg $$ parens undecidableMsg)
1697       | not (null (fvTypes tys \\ fvs))
1698       = Just (famInstUndecErr famInst nomoreVarMsg $$ parens undecidableMsg)
1699       | size <= sizeTypes tys
1700       = Just (famInstUndecErr famInst smallerAppMsg $$ parens undecidableMsg)
1701       | otherwise
1702       = Nothing
1703       where
1704         famInst = TyConApp tc tys
1705
1706 -- Ensure that no type family instances occur in a type.
1707 --
1708 checkTyFamFreeness :: Type -> TcM ()
1709 checkTyFamFreeness ty
1710   = checkTc (isTyFamFree ty) $
1711       tyFamInstInIndexErr ty
1712
1713 -- Check that a type does not contain any type family applications.
1714 --
1715 isTyFamFree :: Type -> Bool
1716 isTyFamFree = null . tyFamInsts
1717
1718 -- Error messages
1719
1720 tyFamInstInIndexErr ty
1721   = hang (ptext SLIT("Illegal type family application in type instance") <> 
1722          colon) 4 $
1723       ppr ty
1724
1725 polyTyErr ty 
1726   = hang (ptext SLIT("Illegal polymorphic type in type instance") <> colon) 4 $
1727       ppr ty
1728
1729 famInstUndecErr ty msg 
1730   = sep [msg, 
1731          nest 2 (ptext SLIT("in the type family application:") <+> 
1732                  pprType ty)]
1733
1734 nestedMsg     = ptext SLIT("Nested type family application")
1735 nomoreVarMsg  = ptext SLIT("Variable occurs more often than in instance head")
1736 smallerAppMsg = ptext SLIT("Application is no smaller than the instance head")
1737 \end{code}
1738
1739
1740 %************************************************************************
1741 %*                                                                      *
1742 \subsection{Auxiliary functions}
1743 %*                                                                      *
1744 %************************************************************************
1745
1746 \begin{code}
1747 -- Free variables of a type, retaining repetitions, and expanding synonyms
1748 fvType :: Type -> [TyVar]
1749 fvType ty | Just exp_ty <- tcView ty = fvType exp_ty
1750 fvType (TyVarTy tv)        = [tv]
1751 fvType (TyConApp _ tys)    = fvTypes tys
1752 fvType (NoteTy _ ty)       = fvType ty
1753 fvType (PredTy pred)       = fvPred pred
1754 fvType (FunTy arg res)     = fvType arg ++ fvType res
1755 fvType (AppTy fun arg)     = fvType fun ++ fvType arg
1756 fvType (ForAllTy tyvar ty) = filter (/= tyvar) (fvType ty)
1757
1758 fvTypes :: [Type] -> [TyVar]
1759 fvTypes tys                = concat (map fvType tys)
1760
1761 fvPred :: PredType -> [TyVar]
1762 fvPred (ClassP _ tys')     = fvTypes tys'
1763 fvPred (IParam _ ty)       = fvType ty
1764 fvPred (EqPred ty1 ty2)    = fvType ty1 ++ fvType ty2
1765
1766 -- Size of a type: the number of variables and constructors
1767 sizeType :: Type -> Int
1768 sizeType ty | Just exp_ty <- tcView ty = sizeType exp_ty
1769 sizeType (TyVarTy _)       = 1
1770 sizeType (TyConApp _ tys)  = sizeTypes tys + 1
1771 sizeType (NoteTy _ ty)     = sizeType ty
1772 sizeType (PredTy pred)     = sizePred pred
1773 sizeType (FunTy arg res)   = sizeType arg + sizeType res + 1
1774 sizeType (AppTy fun arg)   = sizeType fun + sizeType arg
1775 sizeType (ForAllTy _ ty)   = sizeType ty
1776
1777 sizeTypes :: [Type] -> Int
1778 sizeTypes xs               = sum (map sizeType xs)
1779
1780 sizePred :: PredType -> Int
1781 sizePred (ClassP _ tys')   = sizeTypes tys'
1782 sizePred (IParam _ ty)     = sizeType ty
1783 sizePred (EqPred ty1 ty2)  = sizeType ty1 + sizeType ty2
1784 \end{code}