2 % (c) The University of Glasgow 2006
3 % (c) The AQUA Project, Glasgow University, 1996-1998
6 TcTyClsDecls: Typecheck type and class declarations
10 tcTyAndClassDecls, tcFamInstDecl
13 #include "HsVersions.h"
50 import Control.Monad ( mplus )
54 %************************************************************************
56 \subsection{Type checking for type and class declarations}
58 %************************************************************************
62 Consider a mutually-recursive group, binding
63 a type constructor T and a class C.
65 Step 1: getInitialKind
66 Construct a KindEnv by binding T and C to a kind variable
69 In that environment, do a kind check
71 Step 3: Zonk the kinds
73 Step 4: buildTyConOrClass
74 Construct an environment binding T to a TyCon and C to a Class.
75 a) Their kinds comes from zonking the relevant kind variable
76 b) Their arity (for synonyms) comes direct from the decl
77 c) The funcional dependencies come from the decl
78 d) The rest comes a knot-tied binding of T and C, returned from Step 4
79 e) The variances of the tycons in the group is calculated from
83 In this environment, walk over the decls, constructing the TyCons and Classes.
84 This uses in a strict way items (a)-(c) above, which is why they must
85 be constructed in Step 4. Feed the results back to Step 4.
86 For this step, pass the is-recursive flag as the wimp-out flag
90 Step 6: Extend environment
91 We extend the type environment with bindings not only for the TyCons and Classes,
92 but also for their "implicit Ids" like data constructors and class selectors
94 Step 7: checkValidTyCl
95 For a recursive group only, check all the decls again, just
96 to check all the side conditions on validity. We could not
97 do this before because we were in a mutually recursive knot.
99 Identification of recursive TyCons
100 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
101 The knot-tying parameters: @rec_details_list@ is an alist mapping @Name@s to
104 Identifying a TyCon as recursive serves two purposes
106 1. Avoid infinite types. Non-recursive newtypes are treated as
107 "transparent", like type synonyms, after the type checker. If we did
108 this for all newtypes, we'd get infinite types. So we figure out for
109 each newtype whether it is "recursive", and add a coercion if so. In
110 effect, we are trying to "cut the loops" by identifying a loop-breaker.
112 2. Avoid infinite unboxing. This is nothing to do with newtypes.
116 Well, this function diverges, but we don't want the strictness analyser
117 to diverge. But the strictness analyser will diverge because it looks
118 deeper and deeper into the structure of T. (I believe there are
119 examples where the function does something sane, and the strictness
120 analyser still diverges, but I can't see one now.)
122 Now, concerning (1), the FC2 branch currently adds a coercion for ALL
123 newtypes. I did this as an experiment, to try to expose cases in which
124 the coercions got in the way of optimisations. If it turns out that we
125 can indeed always use a coercion, then we don't risk recursive types,
126 and don't need to figure out what the loop breakers are.
128 For newtype *families* though, we will always have a coercion, so they
129 are always loop breakers! So you can easily adjust the current
130 algorithm by simply treating all newtype families as loop breakers (and
131 indeed type families). I think.
134 tcTyAndClassDecls :: ModDetails -> [LTyClDecl Name]
135 -> TcM TcGblEnv -- Input env extended by types and classes
136 -- and their implicit Ids,DataCons
137 -- Fails if there are any errors
139 tcTyAndClassDecls boot_details allDecls
140 = checkNoErrs $ -- The code recovers internally, but if anything gave rise to
141 -- an error we'd better stop now, to avoid a cascade
142 do { -- Omit instances of type families; they are handled together
143 -- with the *heads* of class instances
144 ; let decls = filter (not . isFamInstDecl . unLoc) allDecls
146 -- First check for cyclic type synonysm or classes
147 -- See notes with checkCycleErrs
148 ; checkCycleErrs decls
150 ; traceTc (text "tcTyAndCl" <+> ppr mod)
151 ; (syn_tycons, alg_tyclss) <- fixM (\ ~(_rec_syn_tycons, rec_alg_tyclss) ->
152 do { let { -- Seperate ordinary synonyms from all other type and
153 -- class declarations and add all associated type
154 -- declarations from type classes. The latter is
155 -- required so that the temporary environment for the
156 -- knot includes all associated family declarations.
157 ; (syn_decls, alg_decls) = partition (isSynDecl . unLoc)
159 ; alg_at_decls = concatMap addATs alg_decls
161 -- Extend the global env with the knot-tied results
162 -- for data types and classes
164 -- We must populate the environment with the loop-tied
165 -- T's right away, because the kind checker may "fault
166 -- in" some type constructors that recursively
168 ; let gbl_things = mkGlobalThings alg_at_decls rec_alg_tyclss
169 ; tcExtendRecEnv gbl_things $ do
171 -- Kind-check the declarations
172 { (kc_syn_decls, kc_alg_decls) <- kcTyClDecls syn_decls alg_decls
174 ; let { -- Calculate rec-flag
175 ; calc_rec = calcRecFlags boot_details rec_alg_tyclss
176 ; tc_decl = addLocM (tcTyClDecl calc_rec) }
178 -- Type-check the type synonyms, and extend the envt
179 ; syn_tycons <- tcSynDecls kc_syn_decls
180 ; tcExtendGlobalEnv syn_tycons $ do
182 -- Type-check the data types and classes
183 { alg_tyclss <- mapM tc_decl kc_alg_decls
184 ; return (syn_tycons, concat alg_tyclss)
186 -- Finished with knot-tying now
187 -- Extend the environment with the finished things
188 ; tcExtendGlobalEnv (syn_tycons ++ alg_tyclss) $ do
190 -- Perform the validity check
191 { traceTc (text "ready for validity check")
192 ; mapM_ (addLocM checkValidTyCl) decls
193 ; traceTc (text "done")
195 -- Add the implicit things;
196 -- we want them in the environment because
197 -- they may be mentioned in interface files
198 -- NB: All associated types and their implicit things will be added a
199 -- second time here. This doesn't matter as the definitions are
201 ; let { implicit_things = concatMap implicitTyThings alg_tyclss }
202 ; traceTc ((text "Adding" <+> ppr alg_tyclss)
203 $$ (text "and" <+> ppr implicit_things))
204 ; tcExtendGlobalEnv implicit_things getGblEnv
207 -- Pull associated types out of class declarations, to tie them into the
209 -- NB: We put them in the same place in the list as `tcTyClDecl' will
210 -- eventually put the matching `TyThing's. That's crucial; otherwise,
211 -- the two argument lists of `mkGlobalThings' don't match up.
212 addATs decl@(L _ (ClassDecl {tcdATs = ats})) = decl : ats
215 mkGlobalThings :: [LTyClDecl Name] -- The decls
216 -> [TyThing] -- Knot-tied, in 1-1 correspondence with the decls
218 -- Driven by the Decls, and treating the TyThings lazily
219 -- make a TypeEnv for the new things
220 mkGlobalThings decls things
221 = map mk_thing (decls `zipLazy` things)
223 mk_thing (L _ (ClassDecl {tcdLName = L _ name}), ~(AClass cl))
225 mk_thing (L _ decl, ~(ATyCon tc))
226 = (tcdName decl, ATyCon tc)
227 #if __GLASGOW_HASKELL__ < 605
228 -- Old GHCs don't understand that ~... matches anything
229 mk_thing _ = panic "mkGlobalThings: Can't happen"
234 %************************************************************************
236 \subsection{Type checking family instances}
238 %************************************************************************
240 Family instances are somewhat of a hybrid. They are processed together with
241 class instance heads, but can contain data constructors and hence they share a
242 lot of kinding and type checking code with ordinary algebraic data types (and
246 tcFamInstDecl :: LTyClDecl Name -> TcM (Maybe TyThing) -- Nothing if error
247 tcFamInstDecl (L loc decl)
248 = -- Prime error recovery, set source location
249 recoverM (return Nothing) $
252 do { -- type families require -XTypeFamilies and can't be in an
254 ; type_families <- doptM Opt_TypeFamilies
255 ; is_boot <- tcIsHsBoot -- Are we compiling an hs-boot file?
256 ; checkTc type_families $ badFamInstDecl (tcdLName decl)
257 ; checkTc (not is_boot) $ badBootFamInstDeclErr
259 -- Perform kind and type checking
260 ; tc <- tcFamInstDecl1 decl
261 ; checkValidTyCon tc -- Remember to check validity;
262 -- no recursion to worry about here
263 ; return (Just (ATyCon tc))
266 tcFamInstDecl1 :: TyClDecl Name -> TcM TyCon
269 tcFamInstDecl1 (decl@TySynonym {tcdLName = L loc tc_name})
270 = kcIdxTyPats decl $ \k_tvs k_typats resKind family ->
271 do { -- check that the family declaration is for a synonym
272 unless (isSynTyCon family) $
273 addErr (wrongKindOfFamily family)
275 ; -- (1) kind check the right-hand side of the type equation
276 ; k_rhs <- kcCheckHsType (tcdSynRhs decl) resKind
278 -- we need the exact same number of type parameters as the family
280 ; let famArity = tyConArity family
281 ; checkTc (length k_typats == famArity) $
282 wrongNumberOfParmsErr famArity
284 -- (2) type check type equation
285 ; tcTyVarBndrs k_tvs $ \t_tvs -> do { -- turn kinded into proper tyvars
286 ; t_typats <- mapM tcHsKindedType k_typats
287 ; t_rhs <- tcHsKindedType k_rhs
289 -- (3) check the well-formedness of the instance
290 ; checkValidTypeInst t_typats t_rhs
292 -- (4) construct representation tycon
293 ; rep_tc_name <- newFamInstTyConName tc_name loc
294 ; buildSynTyCon rep_tc_name t_tvs (SynonymTyCon t_rhs)
295 (Just (family, t_typats))
298 -- "newtype instance" and "data instance"
299 tcFamInstDecl1 (decl@TyData {tcdND = new_or_data, tcdLName = L loc tc_name,
301 = kcIdxTyPats decl $ \k_tvs k_typats resKind family ->
302 do { -- check that the family declaration is for the right kind
303 unless (isAlgTyCon family) $
304 addErr (wrongKindOfFamily family)
306 ; -- (1) kind check the data declaration as usual
307 ; k_decl <- kcDataDecl decl k_tvs
308 ; let k_ctxt = tcdCtxt k_decl
309 k_cons = tcdCons k_decl
311 -- result kind must be '*' (otherwise, we have too few patterns)
312 ; checkTc (isLiftedTypeKind resKind) $ tooFewParmsErr (tyConArity family)
314 -- (2) type check indexed data type declaration
315 ; tcTyVarBndrs k_tvs $ \t_tvs -> do { -- turn kinded into proper tyvars
316 ; unbox_strict <- doptM Opt_UnboxStrictFields
318 -- kind check the type indexes and the context
319 ; t_typats <- mapM tcHsKindedType k_typats
320 ; stupid_theta <- tcHsKindedContext k_ctxt
323 -- - left-hand side contains no type family applications
324 -- (vanilla synonyms are fine, though, and we checked for
326 ; mapM_ checkTyFamFreeness t_typats
328 -- - we don't use GADT syntax for indexed types
329 ; checkTc h98_syntax (badGadtIdxTyDecl tc_name)
331 -- - a newtype has exactly one constructor
332 ; checkTc (new_or_data == DataType || isSingleton k_cons) $
333 newtypeConError tc_name (length k_cons)
335 -- (4) construct representation tycon
336 ; rep_tc_name <- newFamInstTyConName tc_name loc
337 ; let ex_ok = True -- Existentials ok for type families!
338 ; fixM (\ tycon -> do
339 { data_cons <- mapM (addLocM (tcConDecl unbox_strict ex_ok tycon t_tvs))
343 DataType -> return (mkDataTyConRhs data_cons)
344 NewType -> ASSERT( not (null data_cons) )
345 mkNewTyConRhs rep_tc_name tycon (head data_cons)
346 ; buildAlgTyCon rep_tc_name t_tvs stupid_theta tc_rhs Recursive
347 False h98_syntax (Just (family, t_typats))
348 -- We always assume that indexed types are recursive. Why?
349 -- (1) Due to their open nature, we can never be sure that a
350 -- further instance might not introduce a new recursive
351 -- dependency. (2) They are always valid loop breakers as
352 -- they involve a coercion.
356 h98_syntax = case cons of -- All constructors have same shape
357 L _ (ConDecl { con_res = ResTyGADT _ }) : _ -> False
360 tcFamInstDecl1 d = pprPanic "tcFamInstDecl1" (ppr d)
362 -- Kind checking of indexed types
365 -- Kind check type patterns and kind annotate the embedded type variables.
367 -- * Here we check that a type instance matches its kind signature, but we do
368 -- not check whether there is a pattern for each type index; the latter
369 -- check is only required for type synonym instances.
371 kcIdxTyPats :: TyClDecl Name
372 -> ([LHsTyVarBndr Name] -> [LHsType Name] -> Kind -> TyCon -> TcM a)
373 -- ^^kinded tvs ^^kinded ty pats ^^res kind
375 kcIdxTyPats decl thing_inside
376 = kcHsTyVars (tcdTyVars decl) $ \tvs ->
377 do { family <- tcLookupLocatedTyCon (tcdLName decl)
378 ; let { (kinds, resKind) = splitKindFunTys (tyConKind family)
379 ; hs_typats = fromJust $ tcdTyPats decl }
381 -- we may not have more parameters than the kind indicates
382 ; checkTc (length kinds >= length hs_typats) $
383 tooManyParmsErr (tcdLName decl)
385 -- type functions can have a higher-kinded result
386 ; let resultKind = mkArrowKinds (drop (length hs_typats) kinds) resKind
387 ; typats <- zipWithM kcCheckHsType hs_typats kinds
388 ; thing_inside tvs typats resultKind family
394 %************************************************************************
398 %************************************************************************
400 We need to kind check all types in the mutually recursive group
401 before we know the kind of the type variables. For example:
404 op :: D b => a -> b -> b
407 bop :: (Monad c) => ...
409 Here, the kind of the locally-polymorphic type variable "b"
410 depends on *all the uses of class D*. For example, the use of
411 Monad c in bop's type signature means that D must have kind Type->Type.
413 However type synonyms work differently. They can have kinds which don't
414 just involve (->) and *:
415 type R = Int# -- Kind #
416 type S a = Array# a -- Kind * -> #
417 type T a b = (# a,b #) -- Kind * -> * -> (# a,b #)
418 So we must infer their kinds from their right-hand sides *first* and then
419 use them, whereas for the mutually recursive data types D we bring into
420 scope kind bindings D -> k, where k is a kind variable, and do inference.
424 This treatment of type synonyms only applies to Haskell 98-style synonyms.
425 General type functions can be recursive, and hence, appear in `alg_decls'.
427 The kind of a type family is solely determinded by its kind signature;
428 hence, only kind signatures participate in the construction of the initial
429 kind environment (as constructed by `getInitialKind'). In fact, we ignore
430 instances of families altogether in the following. However, we need to
431 include the kinds of associated families into the construction of the
432 initial kind environment. (This is handled by `allDecls').
435 kcTyClDecls :: [LTyClDecl Name] -> [Located (TyClDecl Name)]
436 -> TcM ([LTyClDecl Name], [Located (TyClDecl Name)])
437 kcTyClDecls syn_decls alg_decls
438 = do { -- First extend the kind env with each data type, class, and
439 -- indexed type, mapping them to a type variable
440 let initialKindDecls = concat [allDecls decl | L _ decl <- alg_decls]
441 ; alg_kinds <- mapM getInitialKind initialKindDecls
442 ; tcExtendKindEnv alg_kinds $ do
444 -- Now kind-check the type synonyms, in dependency order
445 -- We do these differently to data type and classes,
446 -- because a type synonym can be an unboxed type
448 -- and a kind variable can't unify with UnboxedTypeKind
449 -- So we infer their kinds in dependency order
450 { (kc_syn_decls, syn_kinds) <- kcSynDecls (calcSynCycles syn_decls)
451 ; tcExtendKindEnv syn_kinds $ do
453 -- Now kind-check the data type, class, and kind signatures,
454 -- returning kind-annotated decls; we don't kind-check
455 -- instances of indexed types yet, but leave this to
457 { kc_alg_decls <- mapM (wrapLocM kcTyClDecl)
458 (filter (not . isFamInstDecl . unLoc) alg_decls)
460 ; return (kc_syn_decls, kc_alg_decls) }}}
462 -- get all declarations relevant for determining the initial kind
464 allDecls (decl@ClassDecl {tcdATs = ats}) = decl : [ at
467 allDecls decl | isFamInstDecl decl = []
470 ------------------------------------------------------------------------
471 getInitialKind :: TyClDecl Name -> TcM (Name, TcKind)
472 -- Only for data type, class, and indexed type declarations
473 -- Get as much info as possible from the data, class, or indexed type decl,
474 -- so as to maximise usefulness of error messages
476 = do { arg_kinds <- mapM (mk_arg_kind . unLoc) (tyClDeclTyVars decl)
477 ; res_kind <- mk_res_kind decl
478 ; return (tcdName decl, mkArrowKinds arg_kinds res_kind) }
480 mk_arg_kind (UserTyVar _) = newKindVar
481 mk_arg_kind (KindedTyVar _ kind) = return kind
483 mk_res_kind (TyFamily { tcdKind = Just kind }) = return kind
484 mk_res_kind (TyData { tcdKindSig = Just kind }) = return kind
485 -- On GADT-style declarations we allow a kind signature
486 -- data T :: *->* where { ... }
487 mk_res_kind _ = return liftedTypeKind
491 kcSynDecls :: [SCC (LTyClDecl Name)]
492 -> TcM ([LTyClDecl Name], -- Kind-annotated decls
493 [(Name,TcKind)]) -- Kind bindings
496 kcSynDecls (group : groups)
497 = do { (decl, nk) <- kcSynDecl group
498 ; (decls, nks) <- tcExtendKindEnv [nk] (kcSynDecls groups)
499 ; return (decl:decls, nk:nks) }
502 kcSynDecl :: SCC (LTyClDecl Name)
503 -> TcM (LTyClDecl Name, -- Kind-annotated decls
504 (Name,TcKind)) -- Kind bindings
505 kcSynDecl (AcyclicSCC (L loc decl))
506 = tcAddDeclCtxt decl $
507 kcHsTyVars (tcdTyVars decl) (\ k_tvs ->
508 do { traceTc (text "kcd1" <+> ppr (unLoc (tcdLName decl)) <+> brackets (ppr (tcdTyVars decl))
509 <+> brackets (ppr k_tvs))
510 ; (k_rhs, rhs_kind) <- kcHsType (tcdSynRhs decl)
511 ; traceTc (text "kcd2" <+> ppr (unLoc (tcdLName decl)))
512 ; let tc_kind = foldr (mkArrowKind . kindedTyVarKind) rhs_kind k_tvs
513 ; return (L loc (decl { tcdTyVars = k_tvs, tcdSynRhs = k_rhs }),
514 (unLoc (tcdLName decl), tc_kind)) })
516 kcSynDecl (CyclicSCC decls)
517 = do { recSynErr decls; failM } -- Fail here to avoid error cascade
518 -- of out-of-scope tycons
520 kindedTyVarKind :: LHsTyVarBndr Name -> Kind
521 kindedTyVarKind (L _ (KindedTyVar _ k)) = k
522 kindedTyVarKind x = pprPanic "kindedTyVarKind" (ppr x)
524 ------------------------------------------------------------------------
525 kcTyClDecl :: TyClDecl Name -> TcM (TyClDecl Name)
526 -- Not used for type synonyms (see kcSynDecl)
528 kcTyClDecl decl@(TyData {})
529 = ASSERT( not . isFamInstDecl $ decl ) -- must not be a family instance
530 kcTyClDeclBody decl $
533 kcTyClDecl decl@(TyFamily {})
534 = kcFamilyDecl [] decl -- the empty list signals a toplevel decl
536 kcTyClDecl decl@(ClassDecl {tcdCtxt = ctxt, tcdSigs = sigs, tcdATs = ats})
537 = kcTyClDeclBody decl $ \ tvs' ->
538 do { ctxt' <- kcHsContext ctxt
539 ; ats' <- mapM (wrapLocM (kcFamilyDecl tvs')) ats
540 ; sigs' <- mapM (wrapLocM kc_sig) sigs
541 ; return (decl {tcdTyVars = tvs', tcdCtxt = ctxt', tcdSigs = sigs',
544 kc_sig (TypeSig nm op_ty) = do { op_ty' <- kcHsLiftedSigType op_ty
545 ; return (TypeSig nm op_ty') }
546 kc_sig other_sig = return other_sig
548 kcTyClDecl decl@(ForeignType {})
551 kcTyClDecl (TySynonym {}) = panic "kcTyClDecl TySynonym"
553 kcTyClDeclBody :: TyClDecl Name
554 -> ([LHsTyVarBndr Name] -> TcM a)
556 -- getInitialKind has made a suitably-shaped kind for the type or class
557 -- Unpack it, and attribute those kinds to the type variables
558 -- Extend the env with bindings for the tyvars, taken from
559 -- the kind of the tycon/class. Give it to the thing inside, and
560 -- check the result kind matches
561 kcTyClDeclBody decl thing_inside
562 = tcAddDeclCtxt decl $
563 do { tc_ty_thing <- tcLookupLocated (tcdLName decl)
564 ; let tc_kind = case tc_ty_thing of
566 _ -> pprPanic "kcTyClDeclBody" (ppr tc_ty_thing)
567 (kinds, _) = splitKindFunTys tc_kind
568 hs_tvs = tcdTyVars decl
569 kinded_tvs = ASSERT( length kinds >= length hs_tvs )
570 [ L loc (KindedTyVar (hsTyVarName tv) k)
571 | (L loc tv, k) <- zip hs_tvs kinds]
572 ; tcExtendKindEnvTvs kinded_tvs (thing_inside kinded_tvs) }
574 -- Kind check a data declaration, assuming that we already extended the
575 -- kind environment with the type variables of the left-hand side (these
576 -- kinded type variables are also passed as the second parameter).
578 kcDataDecl :: TyClDecl Name -> [LHsTyVarBndr Name] -> TcM (TyClDecl Name)
579 kcDataDecl decl@(TyData {tcdND = new_or_data, tcdCtxt = ctxt, tcdCons = cons})
581 = do { ctxt' <- kcHsContext ctxt
582 ; cons' <- mapM (wrapLocM kc_con_decl) cons
583 ; return (decl {tcdTyVars = tvs, tcdCtxt = ctxt', tcdCons = cons'}) }
585 -- doc comments are typechecked to Nothing here
586 kc_con_decl (ConDecl name expl ex_tvs ex_ctxt details res _) = do
587 kcHsTyVars ex_tvs $ \ex_tvs' -> do
588 ex_ctxt' <- kcHsContext ex_ctxt
589 details' <- kc_con_details details
591 ResTyH98 -> return ResTyH98
592 ResTyGADT ty -> do { ty' <- kcHsSigType ty; return (ResTyGADT ty') }
593 return (ConDecl name expl ex_tvs' ex_ctxt' details' res' Nothing)
595 kc_con_details (PrefixCon btys)
596 = do { btys' <- mapM kc_larg_ty btys
597 ; return (PrefixCon btys') }
598 kc_con_details (InfixCon bty1 bty2)
599 = do { bty1' <- kc_larg_ty bty1
600 ; bty2' <- kc_larg_ty bty2
601 ; return (InfixCon bty1' bty2') }
602 kc_con_details (RecCon fields)
603 = do { fields' <- mapM kc_field fields
604 ; return (RecCon fields') }
606 kc_field (ConDeclField fld bty d) = do { bty' <- kc_larg_ty bty
607 ; return (ConDeclField fld bty' d) }
609 kc_larg_ty bty = case new_or_data of
610 DataType -> kcHsSigType bty
611 NewType -> kcHsLiftedSigType bty
612 -- Can't allow an unlifted type for newtypes, because we're effectively
613 -- going to remove the constructor while coercing it to a lifted type.
614 -- And newtypes can't be bang'd
615 kcDataDecl d _ = pprPanic "kcDataDecl" (ppr d)
617 -- Kind check a family declaration or type family default declaration.
619 kcFamilyDecl :: [LHsTyVarBndr Name] -- tyvars of enclosing class decl if any
620 -> TyClDecl Name -> TcM (TyClDecl Name)
621 kcFamilyDecl classTvs decl@(TyFamily {tcdKind = kind})
622 = kcTyClDeclBody decl $ \tvs' ->
623 do { mapM_ unifyClassParmKinds tvs'
624 ; return (decl {tcdTyVars = tvs',
625 tcdKind = kind `mplus` Just liftedTypeKind})
626 -- default result kind is '*'
629 unifyClassParmKinds (L _ (KindedTyVar n k))
630 | Just classParmKind <- lookup n classTyKinds = unifyKind k classParmKind
631 | otherwise = return ()
632 unifyClassParmKinds x = pprPanic "kcFamilyDecl/unifyClassParmKinds" (ppr x)
633 classTyKinds = [(n, k) | L _ (KindedTyVar n k) <- classTvs]
634 kcFamilyDecl _ (TySynonym {}) -- type family defaults
635 = panic "TcTyClsDecls.kcFamilyDecl: not implemented yet"
636 kcFamilyDecl _ d = pprPanic "kcFamilyDecl" (ppr d)
640 %************************************************************************
642 \subsection{Type checking}
644 %************************************************************************
647 tcSynDecls :: [LTyClDecl Name] -> TcM [TyThing]
648 tcSynDecls [] = return []
649 tcSynDecls (decl : decls)
650 = do { syn_tc <- addLocM tcSynDecl decl
651 ; syn_tcs <- tcExtendGlobalEnv [syn_tc] (tcSynDecls decls)
652 ; return (syn_tc : syn_tcs) }
655 tcSynDecl :: TyClDecl Name -> TcM TyThing
657 (TySynonym {tcdLName = L _ tc_name, tcdTyVars = tvs, tcdSynRhs = rhs_ty})
658 = tcTyVarBndrs tvs $ \ tvs' -> do
659 { traceTc (text "tcd1" <+> ppr tc_name)
660 ; rhs_ty' <- tcHsKindedType rhs_ty
661 ; tycon <- buildSynTyCon tc_name tvs' (SynonymTyCon rhs_ty') Nothing
662 ; return (ATyCon tycon)
664 tcSynDecl d = pprPanic "tcSynDecl" (ppr d)
667 tcTyClDecl :: (Name -> RecFlag) -> TyClDecl Name -> TcM [TyThing]
669 tcTyClDecl calc_isrec decl
670 = tcAddDeclCtxt decl (tcTyClDecl1 calc_isrec decl)
672 -- "type family" declarations
673 tcTyClDecl1 :: (Name -> RecFlag) -> TyClDecl Name -> TcM [TyThing]
674 tcTyClDecl1 _calc_isrec
675 (TyFamily {tcdFlavour = TypeFamily,
676 tcdLName = L _ tc_name, tcdTyVars = tvs, tcdKind = Just kind})
677 -- NB: kind at latest
680 = tcTyVarBndrs tvs $ \ tvs' -> do
681 { traceTc (text "type family: " <+> ppr tc_name)
682 ; idx_tys <- doptM Opt_TypeFamilies
684 -- Check that we don't use families without -XTypeFamilies
685 ; checkTc idx_tys $ badFamInstDecl tc_name
687 ; tycon <- buildSynTyCon tc_name tvs' (OpenSynTyCon kind Nothing) Nothing
688 ; return [ATyCon tycon]
691 -- "data family" declaration
692 tcTyClDecl1 _calc_isrec
693 (TyFamily {tcdFlavour = DataFamily,
694 tcdLName = L _ tc_name, tcdTyVars = tvs, tcdKind = mb_kind})
695 = tcTyVarBndrs tvs $ \ tvs' -> do
696 { traceTc (text "data family: " <+> ppr tc_name)
697 ; extra_tvs <- tcDataKindSig mb_kind
698 ; let final_tvs = tvs' ++ extra_tvs -- we may not need these
700 ; idx_tys <- doptM Opt_TypeFamilies
702 -- Check that we don't use families without -XTypeFamilies
703 ; checkTc idx_tys $ badFamInstDecl tc_name
705 ; tycon <- buildAlgTyCon tc_name final_tvs []
706 mkOpenDataTyConRhs Recursive False True Nothing
707 ; return [ATyCon tycon]
710 -- "newtype" and "data"
711 -- NB: not used for newtype/data instances (whether associated or not)
712 tcTyClDecl1 calc_isrec
713 (TyData {tcdND = new_or_data, tcdCtxt = ctxt, tcdTyVars = tvs,
714 tcdLName = L _ tc_name, tcdKindSig = mb_ksig, tcdCons = cons})
715 = tcTyVarBndrs tvs $ \ tvs' -> do
716 { extra_tvs <- tcDataKindSig mb_ksig
717 ; let final_tvs = tvs' ++ extra_tvs
718 ; stupid_theta <- tcHsKindedContext ctxt
719 ; want_generic <- doptM Opt_Generics
720 ; unbox_strict <- doptM Opt_UnboxStrictFields
721 ; empty_data_decls <- doptM Opt_EmptyDataDecls
722 ; kind_signatures <- doptM Opt_KindSignatures
723 ; existential_ok <- doptM Opt_ExistentialQuantification
724 ; gadt_ok <- doptM Opt_GADTs
725 ; is_boot <- tcIsHsBoot -- Are we compiling an hs-boot file?
726 ; let ex_ok = existential_ok || gadt_ok -- Data cons can have existential context
728 -- Check that we don't use GADT syntax in H98 world
729 ; checkTc (gadt_ok || h98_syntax) (badGadtDecl tc_name)
731 -- Check that we don't use kind signatures without Glasgow extensions
732 ; checkTc (kind_signatures || isNothing mb_ksig) (badSigTyDecl tc_name)
734 -- Check that the stupid theta is empty for a GADT-style declaration
735 ; checkTc (null stupid_theta || h98_syntax) (badStupidTheta tc_name)
737 -- Check that a newtype has exactly one constructor
738 -- Do this before checking for empty data decls, so that
739 -- we don't suggest -XEmptyDataDecls for newtypes
740 ; checkTc (new_or_data == DataType || isSingleton cons)
741 (newtypeConError tc_name (length cons))
743 -- Check that there's at least one condecl,
744 -- or else we're reading an hs-boot file, or -XEmptyDataDecls
745 ; checkTc (not (null cons) || empty_data_decls || is_boot)
746 (emptyConDeclsErr tc_name)
748 ; tycon <- fixM (\ tycon -> do
749 { data_cons <- mapM (addLocM (tcConDecl unbox_strict ex_ok tycon final_tvs))
752 if null cons && is_boot -- In a hs-boot file, empty cons means
753 then return AbstractTyCon -- "don't know"; hence Abstract
754 else case new_or_data of
755 DataType -> return (mkDataTyConRhs data_cons)
757 ASSERT( not (null data_cons) )
758 mkNewTyConRhs tc_name tycon (head data_cons)
759 ; buildAlgTyCon tc_name final_tvs stupid_theta tc_rhs is_rec
760 (want_generic && canDoGenerics data_cons) h98_syntax Nothing
762 ; return [ATyCon tycon]
765 is_rec = calc_isrec tc_name
766 h98_syntax = case cons of -- All constructors have same shape
767 L _ (ConDecl { con_res = ResTyGADT _ }) : _ -> False
770 tcTyClDecl1 calc_isrec
771 (ClassDecl {tcdLName = L _ class_name, tcdTyVars = tvs,
772 tcdCtxt = ctxt, tcdMeths = meths,
773 tcdFDs = fundeps, tcdSigs = sigs, tcdATs = ats} )
774 = tcTyVarBndrs tvs $ \ tvs' -> do
775 { ctxt' <- tcHsKindedContext ctxt
776 ; fds' <- mapM (addLocM tc_fundep) fundeps
777 ; atss <- mapM (addLocM (tcTyClDecl1 (const Recursive))) ats
778 -- NB: 'ats' only contains "type family" and "data family"
779 -- declarations as well as type family defaults
780 ; let ats' = zipWith setTyThingPoss atss (map (tcdTyVars . unLoc) ats)
781 ; sig_stuff <- tcClassSigs class_name sigs meths
782 ; clas <- fixM (\ clas ->
783 let -- This little knot is just so we can get
784 -- hold of the name of the class TyCon, which we
785 -- need to look up its recursiveness
786 tycon_name = tyConName (classTyCon clas)
787 tc_isrec = calc_isrec tycon_name
789 buildClass False {- Must include unfoldings for selectors -}
790 class_name tvs' ctxt' fds' ats'
792 ; return (AClass clas : ats')
793 -- NB: Order is important due to the call to `mkGlobalThings' when
794 -- tying the the type and class declaration type checking knot.
797 tc_fundep (tvs1, tvs2) = do { tvs1' <- mapM tcLookupTyVar tvs1 ;
798 ; tvs2' <- mapM tcLookupTyVar tvs2 ;
799 ; return (tvs1', tvs2') }
801 -- For each AT argument compute the position of the corresponding class
802 -- parameter in the class head. This will later serve as a permutation
803 -- vector when checking the validity of instance declarations.
804 setTyThingPoss [ATyCon tycon] atTyVars =
805 let classTyVars = hsLTyVarNames tvs
807 . map (`elemIndex` classTyVars)
810 -- There will be no Nothing, as we already passed renaming
812 ATyCon (setTyConArgPoss tycon poss)
813 setTyThingPoss _ _ = panic "TcTyClsDecls.setTyThingPoss"
816 (ForeignType {tcdLName = L _ tc_name, tcdExtName = tc_ext_name})
817 = return [ATyCon (mkForeignTyCon tc_name tc_ext_name liftedTypeKind 0)]
819 tcTyClDecl1 _ d = pprPanic "tcTyClDecl1" (ppr d)
821 -----------------------------------
822 tcConDecl :: Bool -- True <=> -funbox-strict_fields
823 -> Bool -- True <=> -XExistentialQuantificaton or -XGADTs
828 tcConDecl unbox_strict existential_ok tycon tc_tvs -- Data types
829 (ConDecl name _ tvs ctxt details res_ty _)
830 = addErrCtxt (dataConCtxt name) $
831 tcTyVarBndrs tvs $ \ tvs' -> do
832 { ctxt' <- tcHsKindedContext ctxt
833 ; checkTc (existential_ok || (null tvs && null (unLoc ctxt)))
834 (badExistential name)
835 ; (univ_tvs, ex_tvs, eq_preds, data_tc) <- tcResultType tycon tc_tvs tvs' res_ty
837 -- Tiresome: tidy the tyvar binders, since tc_tvs and tvs' may have the same OccNames
838 tc_datacon is_infix field_lbls btys
839 = do { let bangs = map getBangStrictness btys
840 ; arg_tys <- mapM tcHsBangType btys
841 ; buildDataCon (unLoc name) is_infix
842 (argStrictness unbox_strict bangs arg_tys)
843 (map unLoc field_lbls)
844 univ_tvs ex_tvs eq_preds ctxt' arg_tys
846 -- NB: we put data_tc, the type constructor gotten from the
847 -- constructor type signature into the data constructor;
848 -- that way checkValidDataCon can complain if it's wrong.
851 PrefixCon btys -> tc_datacon False [] btys
852 InfixCon bty1 bty2 -> tc_datacon True [] [bty1,bty2]
853 RecCon fields -> tc_datacon False field_names btys
855 field_names = map cd_fld_name fields
856 btys = map cd_fld_type fields
859 tcResultType :: TyCon
860 -> [TyVar] -- data T a b c = ...
861 -> [TyVar] -- where MkT :: forall a b c. ...
863 -> TcM ([TyVar], -- Universal
864 [TyVar], -- Existential (distinct OccNames from univs)
865 [(TyVar,Type)], -- Equality predicates
866 TyCon) -- TyCon given in the ResTy
867 -- We don't check that the TyCon given in the ResTy is
868 -- the same as the parent tycon, becuase we are in the middle
869 -- of a recursive knot; so it's postponed until checkValidDataCon
871 tcResultType decl_tycon tc_tvs dc_tvs ResTyH98
872 = return (tc_tvs, dc_tvs, [], decl_tycon)
873 -- In H98 syntax the dc_tvs are the existential ones
874 -- data T a b c = forall d e. MkT ...
875 -- The {a,b,c} are tc_tvs, and {d,e} are dc_tvs
877 tcResultType _ tc_tvs dc_tvs (ResTyGADT res_ty)
878 -- E.g. data T a b c where
879 -- MkT :: forall x y z. T (x,y) z z
881 -- ([a,z,c], [x,y], [a:=:(x,y), c:=:z], T)
883 = do { (dc_tycon, res_tys) <- tcLHsConResTy res_ty
885 ; let univ_tvs = choose_univs [] tidy_tc_tvs res_tys
886 -- Each univ_tv is either a dc_tv or a tc_tv
887 ex_tvs = dc_tvs `minusList` univ_tvs
888 eq_spec = [ (tv, ty) | (tv,ty) <- univ_tvs `zip` res_tys,
890 ; return (univ_tvs, ex_tvs, eq_spec, dc_tycon) }
892 -- choose_univs uses the res_ty itself if it's a type variable
893 -- and hasn't already been used; otherwise it uses one of the tc_tvs
894 choose_univs _ tc_tvs []
895 = ASSERT( null tc_tvs ) []
896 choose_univs used (tc_tv:tc_tvs) (res_ty:res_tys)
897 | Just tv <- tcGetTyVar_maybe res_ty, not (tv `elem` used)
898 = tv : choose_univs (tv:used) tc_tvs res_tys
900 = tc_tv : choose_univs used tc_tvs res_tys
902 -- NB: tc_tvs and dc_tvs are distinct, but
903 -- we want them to be *visibly* distinct, both for
904 -- interface files and general confusion. So rename
905 -- the tc_tvs, since they are not used yet (no
906 -- consequential renaming needed)
907 choose_univs _ _ _ = panic "tcResultType/choose_univs"
908 init_occ_env = initTidyOccEnv (map getOccName dc_tvs)
909 (_, tidy_tc_tvs) = mapAccumL tidy_one init_occ_env tc_tvs
910 tidy_one env tv = (env', setTyVarName tv (tidyNameOcc name occ'))
913 (env', occ') = tidyOccName env (getOccName name)
916 argStrictness :: Bool -- True <=> -funbox-strict_fields
918 -> [TcType] -> [StrictnessMark]
919 argStrictness unbox_strict bangs arg_tys
920 = ASSERT( length bangs == length arg_tys )
921 zipWith (chooseBoxingStrategy unbox_strict) arg_tys bangs
923 -- We attempt to unbox/unpack a strict field when either:
924 -- (i) The field is marked '!!', or
925 -- (ii) The field is marked '!', and the -funbox-strict-fields flag is on.
927 -- We have turned off unboxing of newtypes because coercions make unboxing
928 -- and reboxing more complicated
929 chooseBoxingStrategy :: Bool -> TcType -> HsBang -> StrictnessMark
930 chooseBoxingStrategy unbox_strict_fields arg_ty bang
932 HsNoBang -> NotMarkedStrict
933 HsStrict | unbox_strict_fields
934 && can_unbox arg_ty -> MarkedUnboxed
935 HsUnbox | can_unbox arg_ty -> MarkedUnboxed
938 -- we can unbox if the type is a chain of newtypes with a product tycon
940 can_unbox arg_ty = case splitTyConApp_maybe arg_ty of
942 Just (arg_tycon, tycon_args) ->
943 not (isRecursiveTyCon arg_tycon) && -- Note [Recusive unboxing]
944 isProductTyCon arg_tycon &&
945 (if isNewTyCon arg_tycon then
946 can_unbox (newTyConInstRhs arg_tycon tycon_args)
950 Note [Recursive unboxing]
951 ~~~~~~~~~~~~~~~~~~~~~~~~~
952 Be careful not to try to unbox this!
954 But it's the *argument* type that matters. This is fine:
956 because Int is non-recursive.
958 %************************************************************************
960 \subsection{Dependency analysis}
962 %************************************************************************
964 Validity checking is done once the mutually-recursive knot has been
965 tied, so we can look at things freely.
968 checkCycleErrs :: [LTyClDecl Name] -> TcM ()
969 checkCycleErrs tyclss
973 = do { mapM_ recClsErr cls_cycles
974 ; failM } -- Give up now, because later checkValidTyCl
975 -- will loop if the synonym is recursive
977 cls_cycles = calcClassCycles tyclss
979 checkValidTyCl :: TyClDecl Name -> TcM ()
980 -- We do the validity check over declarations, rather than TyThings
981 -- only so that we can add a nice context with tcAddDeclCtxt
983 = tcAddDeclCtxt decl $
984 do { thing <- tcLookupLocatedGlobal (tcdLName decl)
985 ; traceTc (text "Validity of" <+> ppr thing)
987 ATyCon tc -> checkValidTyCon tc
988 AClass cl -> checkValidClass cl
989 _ -> panic "checkValidTyCl"
990 ; traceTc (text "Done validity of" <+> ppr thing)
993 -------------------------
994 -- For data types declared with record syntax, we require
995 -- that each constructor that has a field 'f'
996 -- (a) has the same result type
997 -- (b) has the same type for 'f'
998 -- module alpha conversion of the quantified type variables
999 -- of the constructor.
1001 checkValidTyCon :: TyCon -> TcM ()
1004 = case synTyConRhs tc of
1005 OpenSynTyCon _ _ -> return ()
1006 SynonymTyCon ty -> checkValidType syn_ctxt ty
1008 = do -- Check the context on the data decl
1009 checkValidTheta (DataTyCtxt name) (tyConStupidTheta tc)
1011 -- Check arg types of data constructors
1012 mapM_ (checkValidDataCon tc) data_cons
1014 -- Check that fields with the same name share a type
1015 mapM_ check_fields groups
1018 syn_ctxt = TySynCtxt name
1020 data_cons = tyConDataCons tc
1022 groups = equivClasses cmp_fld (concatMap get_fields data_cons)
1023 cmp_fld (f1,_) (f2,_) = f1 `compare` f2
1024 get_fields con = dataConFieldLabels con `zip` repeat con
1025 -- dataConFieldLabels may return the empty list, which is fine
1027 -- See Note [GADT record selectors] in MkId.lhs
1028 -- We must check (a) that the named field has the same
1029 -- type in each constructor
1030 -- (b) that those constructors have the same result type
1032 -- However, the constructors may have differently named type variable
1033 -- and (worse) we don't know how the correspond to each other. E.g.
1034 -- C1 :: forall a b. { f :: a, g :: b } -> T a b
1035 -- C2 :: forall d c. { f :: c, g :: c } -> T c d
1037 -- So what we do is to ust Unify.tcMatchTys to compare the first candidate's
1038 -- result type against other candidates' types BOTH WAYS ROUND.
1039 -- If they magically agrees, take the substitution and
1040 -- apply them to the latter ones, and see if they match perfectly.
1041 check_fields ((label, con1) : other_fields)
1042 -- These fields all have the same name, but are from
1043 -- different constructors in the data type
1044 = recoverM (return ()) $ mapM_ checkOne other_fields
1045 -- Check that all the fields in the group have the same type
1046 -- NB: this check assumes that all the constructors of a given
1047 -- data type use the same type variables
1049 (tvs1, _, _, res1) = dataConSig con1
1051 fty1 = dataConFieldType con1 label
1053 checkOne (_, con2) -- Do it bothways to ensure they are structurally identical
1054 = do { checkFieldCompat label con1 con2 ts1 res1 res2 fty1 fty2
1055 ; checkFieldCompat label con2 con1 ts2 res2 res1 fty2 fty1 }
1057 (tvs2, _, _, res2) = dataConSig con2
1059 fty2 = dataConFieldType con2 label
1060 check_fields [] = panic "checkValidTyCon/check_fields []"
1062 checkFieldCompat :: Name -> DataCon -> DataCon -> TyVarSet
1063 -> Type -> Type -> Type -> Type -> TcM ()
1064 checkFieldCompat fld con1 con2 tvs1 res1 res2 fty1 fty2
1065 = do { checkTc (isJust mb_subst1) (resultTypeMisMatch fld con1 con2)
1066 ; checkTc (isJust mb_subst2) (fieldTypeMisMatch fld con1 con2) }
1068 mb_subst1 = tcMatchTy tvs1 res1 res2
1069 mb_subst2 = tcMatchTyX tvs1 (expectJust "checkFieldCompat" mb_subst1) fty1 fty2
1071 -------------------------------
1072 checkValidDataCon :: TyCon -> DataCon -> TcM ()
1073 checkValidDataCon tc con
1074 = setSrcSpan (srcLocSpan (getSrcLoc con)) $
1075 addErrCtxt (dataConCtxt con) $
1076 do { checkTc (dataConTyCon con == tc) (badDataConTyCon con)
1077 ; checkValidType ctxt (dataConUserType con)
1078 ; checkValidMonoType (dataConOrigResTy con)
1079 -- Disallow MkT :: T (forall a. a->a)
1080 -- Reason: it's really the argument of an equality constraint
1081 ; when (isNewTyCon tc) (checkNewDataCon con)
1084 ctxt = ConArgCtxt (dataConName con)
1086 -------------------------------
1087 checkNewDataCon :: DataCon -> TcM ()
1088 -- Checks for the data constructor of a newtype
1090 = do { checkTc (isSingleton arg_tys) (newtypeFieldErr con (length arg_tys))
1092 ; checkTc (null eq_spec) (newtypePredError con)
1093 -- Return type is (T a b c)
1094 ; checkTc (null ex_tvs && null eq_theta && null dict_theta) (newtypeExError con)
1096 ; checkTc (not (any isMarkedStrict (dataConStrictMarks con)))
1097 (newtypeStrictError con)
1101 (_univ_tvs, ex_tvs, eq_spec, eq_theta, dict_theta, arg_tys, _res_ty) = dataConFullSig con
1103 -------------------------------
1104 checkValidClass :: Class -> TcM ()
1106 = do { constrained_class_methods <- doptM Opt_ConstrainedClassMethods
1107 ; multi_param_type_classes <- doptM Opt_MultiParamTypeClasses
1108 ; fundep_classes <- doptM Opt_FunctionalDependencies
1110 -- Check that the class is unary, unless GlaExs
1111 ; checkTc (notNull tyvars) (nullaryClassErr cls)
1112 ; checkTc (multi_param_type_classes || unary) (classArityErr cls)
1113 ; checkTc (fundep_classes || null fundeps) (classFunDepsErr cls)
1115 -- Check the super-classes
1116 ; checkValidTheta (ClassSCCtxt (className cls)) theta
1118 -- Check the class operations
1119 ; mapM_ (check_op constrained_class_methods) op_stuff
1121 -- Check that if the class has generic methods, then the
1122 -- class has only one parameter. We can't do generic
1123 -- multi-parameter type classes!
1124 ; checkTc (unary || no_generics) (genericMultiParamErr cls)
1127 (tyvars, fundeps, theta, _, _, op_stuff) = classExtraBigSig cls
1128 unary = isSingleton tyvars
1129 no_generics = null [() | (_, GenDefMeth) <- op_stuff]
1131 check_op constrained_class_methods (sel_id, dm)
1132 = addErrCtxt (classOpCtxt sel_id tau) $ do
1133 { checkValidTheta SigmaCtxt (tail theta)
1134 -- The 'tail' removes the initial (C a) from the
1135 -- class itself, leaving just the method type
1137 ; traceTc (text "class op type" <+> ppr op_ty <+> ppr tau)
1138 ; checkValidType (FunSigCtxt op_name) tau
1140 -- Check that the type mentions at least one of
1141 -- the class type variables...or at least one reachable
1142 -- from one of the class variables. Example: tc223
1143 -- class Error e => Game b mv e | b -> mv e where
1144 -- newBoard :: MonadState b m => m ()
1145 -- Here, MonadState has a fundep m->b, so newBoard is fine
1146 ; let grown_tyvars = grow theta (mkVarSet tyvars)
1147 ; checkTc (tyVarsOfType tau `intersectsVarSet` grown_tyvars)
1148 (noClassTyVarErr cls sel_id)
1150 -- Check that for a generic method, the type of
1151 -- the method is sufficiently simple
1152 ; checkTc (dm /= GenDefMeth || validGenericMethodType tau)
1153 (badGenericMethodType op_name op_ty)
1156 op_name = idName sel_id
1157 op_ty = idType sel_id
1158 (_,theta1,tau1) = tcSplitSigmaTy op_ty
1159 (_,theta2,tau2) = tcSplitSigmaTy tau1
1160 (theta,tau) | constrained_class_methods = (theta1 ++ theta2, tau2)
1161 | otherwise = (theta1, mkPhiTy (tail theta1) tau1)
1162 -- Ugh! The function might have a type like
1163 -- op :: forall a. C a => forall b. (Eq b, Eq a) => tau2
1164 -- With -XConstrainedClassMethods, we want to allow this, even though the inner
1165 -- forall has an (Eq a) constraint. Whereas in general, each constraint
1166 -- in the context of a for-all must mention at least one quantified
1167 -- type variable. What a mess!
1170 ---------------------------------------------------------------------
1171 resultTypeMisMatch :: Name -> DataCon -> DataCon -> SDoc
1172 resultTypeMisMatch field_name con1 con2
1173 = vcat [sep [ptext (sLit "Constructors") <+> ppr con1 <+> ptext (sLit "and") <+> ppr con2,
1174 ptext (sLit "have a common field") <+> quotes (ppr field_name) <> comma],
1175 nest 2 $ ptext (sLit "but have different result types")]
1177 fieldTypeMisMatch :: Name -> DataCon -> DataCon -> SDoc
1178 fieldTypeMisMatch field_name con1 con2
1179 = sep [ptext (sLit "Constructors") <+> ppr con1 <+> ptext (sLit "and") <+> ppr con2,
1180 ptext (sLit "give different types for field"), quotes (ppr field_name)]
1182 dataConCtxt :: Outputable a => a -> SDoc
1183 dataConCtxt con = ptext (sLit "In the definition of data constructor") <+> quotes (ppr con)
1185 classOpCtxt :: Var -> Type -> SDoc
1186 classOpCtxt sel_id tau = sep [ptext (sLit "When checking the class method:"),
1187 nest 2 (ppr sel_id <+> dcolon <+> ppr tau)]
1189 nullaryClassErr :: Class -> SDoc
1191 = ptext (sLit "No parameters for class") <+> quotes (ppr cls)
1193 classArityErr :: Class -> SDoc
1195 = vcat [ptext (sLit "Too many parameters for class") <+> quotes (ppr cls),
1196 parens (ptext (sLit "Use -XMultiParamTypeClasses to allow multi-parameter classes"))]
1198 classFunDepsErr :: Class -> SDoc
1200 = vcat [ptext (sLit "Fundeps in class") <+> quotes (ppr cls),
1201 parens (ptext (sLit "Use -XFunctionalDependencies to allow fundeps"))]
1203 noClassTyVarErr :: Class -> Var -> SDoc
1204 noClassTyVarErr clas op
1205 = sep [ptext (sLit "The class method") <+> quotes (ppr op),
1206 ptext (sLit "mentions none of the type variables of the class") <+>
1207 ppr clas <+> hsep (map ppr (classTyVars clas))]
1209 genericMultiParamErr :: Class -> SDoc
1210 genericMultiParamErr clas
1211 = ptext (sLit "The multi-parameter class") <+> quotes (ppr clas) <+>
1212 ptext (sLit "cannot have generic methods")
1214 badGenericMethodType :: Name -> Kind -> SDoc
1215 badGenericMethodType op op_ty
1216 = hang (ptext (sLit "Generic method type is too complex"))
1217 4 (vcat [ppr op <+> dcolon <+> ppr op_ty,
1218 ptext (sLit "You can only use type variables, arrows, lists, and tuples")])
1220 recSynErr :: [LTyClDecl Name] -> TcRn ()
1222 = setSrcSpan (getLoc (head sorted_decls)) $
1223 addErr (sep [ptext (sLit "Cycle in type synonym declarations:"),
1224 nest 2 (vcat (map ppr_decl sorted_decls))])
1226 sorted_decls = sortLocated syn_decls
1227 ppr_decl (L loc decl) = ppr loc <> colon <+> ppr decl
1229 recClsErr :: [Located (TyClDecl Name)] -> TcRn ()
1231 = setSrcSpan (getLoc (head sorted_decls)) $
1232 addErr (sep [ptext (sLit "Cycle in class declarations (via superclasses):"),
1233 nest 2 (vcat (map ppr_decl sorted_decls))])
1235 sorted_decls = sortLocated cls_decls
1236 ppr_decl (L loc decl) = ppr loc <> colon <+> ppr (decl { tcdSigs = [] })
1238 sortLocated :: [Located a] -> [Located a]
1239 sortLocated things = sortLe le things
1241 le (L l1 _) (L l2 _) = l1 <= l2
1243 badDataConTyCon :: DataCon -> SDoc
1244 badDataConTyCon data_con
1245 = hang (ptext (sLit "Data constructor") <+> quotes (ppr data_con) <+>
1246 ptext (sLit "returns type") <+> quotes (ppr (dataConTyCon data_con)))
1247 2 (ptext (sLit "instead of its parent type"))
1249 badGadtDecl :: Name -> SDoc
1251 = vcat [ ptext (sLit "Illegal generalised algebraic data declaration for") <+> quotes (ppr tc_name)
1252 , nest 2 (parens $ ptext (sLit "Use -XGADTs to allow GADTs")) ]
1254 badExistential :: Located Name -> SDoc
1255 badExistential con_name
1256 = hang (ptext (sLit "Data constructor") <+> quotes (ppr con_name) <+>
1257 ptext (sLit "has existential type variables, or a context"))
1258 2 (parens $ ptext (sLit "Use -XExistentialQuantification or -XGADTs to allow this"))
1260 badStupidTheta :: Name -> SDoc
1261 badStupidTheta tc_name
1262 = ptext (sLit "A data type declared in GADT style cannot have a context:") <+> quotes (ppr tc_name)
1264 newtypeConError :: Name -> Int -> SDoc
1265 newtypeConError tycon n
1266 = sep [ptext (sLit "A newtype must have exactly one constructor,"),
1267 nest 2 $ ptext (sLit "but") <+> quotes (ppr tycon) <+> ptext (sLit "has") <+> speakN n ]
1269 newtypeExError :: DataCon -> SDoc
1271 = sep [ptext (sLit "A newtype constructor cannot have an existential context,"),
1272 nest 2 $ ptext (sLit "but") <+> quotes (ppr con) <+> ptext (sLit "does")]
1274 newtypeStrictError :: DataCon -> SDoc
1275 newtypeStrictError con
1276 = sep [ptext (sLit "A newtype constructor cannot have a strictness annotation,"),
1277 nest 2 $ ptext (sLit "but") <+> quotes (ppr con) <+> ptext (sLit "does")]
1279 newtypePredError :: DataCon -> SDoc
1280 newtypePredError con
1281 = sep [ptext (sLit "A newtype constructor must have a return type of form T a1 ... an"),
1282 nest 2 $ ptext (sLit "but") <+> quotes (ppr con) <+> ptext (sLit "does not")]
1284 newtypeFieldErr :: DataCon -> Int -> SDoc
1285 newtypeFieldErr con_name n_flds
1286 = sep [ptext (sLit "The constructor of a newtype must have exactly one field"),
1287 nest 2 $ ptext (sLit "but") <+> quotes (ppr con_name) <+> ptext (sLit "has") <+> speakN n_flds]
1289 badSigTyDecl :: Name -> SDoc
1290 badSigTyDecl tc_name
1291 = vcat [ ptext (sLit "Illegal kind signature") <+>
1292 quotes (ppr tc_name)
1293 , nest 2 (parens $ ptext (sLit "Use -XKindSignatures to allow kind signatures")) ]
1295 badFamInstDecl :: Outputable a => a -> SDoc
1296 badFamInstDecl tc_name
1297 = vcat [ ptext (sLit "Illegal family instance for") <+>
1298 quotes (ppr tc_name)
1299 , nest 2 (parens $ ptext (sLit "Use -XTypeFamilies to allow indexed type families")) ]
1301 badGadtIdxTyDecl :: Name -> SDoc
1302 badGadtIdxTyDecl tc_name
1303 = vcat [ ptext (sLit "Illegal generalised algebraic data declaration for") <+>
1304 quotes (ppr tc_name)
1305 , nest 2 (parens $ ptext (sLit "Family instances can not yet use GADT declarations")) ]
1307 tooManyParmsErr :: Located Name -> SDoc
1308 tooManyParmsErr tc_name
1309 = ptext (sLit "Family instance has too many parameters:") <+>
1310 quotes (ppr tc_name)
1312 tooFewParmsErr :: Arity -> SDoc
1313 tooFewParmsErr arity
1314 = ptext (sLit "Family instance has too few parameters; expected") <+>
1317 wrongNumberOfParmsErr :: Arity -> SDoc
1318 wrongNumberOfParmsErr exp_arity
1319 = ptext (sLit "Number of parameters must match family declaration; expected")
1322 badBootFamInstDeclErr :: SDoc
1323 badBootFamInstDeclErr =
1324 ptext (sLit "Illegal family instance in hs-boot file")
1326 wrongKindOfFamily :: TyCon -> SDoc
1327 wrongKindOfFamily family =
1328 ptext (sLit "Wrong category of family instance; declaration was for a") <+>
1331 kindOfFamily | isSynTyCon family = ptext (sLit "type synonym")
1332 | isAlgTyCon family = ptext (sLit "data type")
1333 | otherwise = pprPanic "wrongKindOfFamily" (ppr family)
1335 emptyConDeclsErr :: Name -> SDoc
1336 emptyConDeclsErr tycon
1337 = sep [quotes (ppr tycon) <+> ptext (sLit "has no constructors"),
1338 nest 2 $ ptext (sLit "(-XEmptyDataDecls permits this)")]