2 % (c) The University of Glasgow 2006
3 % (c) The AQUA Project, Glasgow University, 1996-1998
6 TcTyClsDecls: Typecheck type and class declarations
10 -- The above warning supression flag is a temporary kludge.
11 -- While working on this module you are encouraged to remove it and fix
12 -- any warnings in the module. See
13 -- http://hackage.haskell.org/trac/ghc/wiki/Commentary/CodingStyle#Warnings
17 tcTyAndClassDecls, tcFamInstDecl
20 #include "HsVersions.h"
56 import Control.Monad ( mplus )
60 %************************************************************************
62 \subsection{Type checking for type and class declarations}
64 %************************************************************************
68 Consider a mutually-recursive group, binding
69 a type constructor T and a class C.
71 Step 1: getInitialKind
72 Construct a KindEnv by binding T and C to a kind variable
75 In that environment, do a kind check
77 Step 3: Zonk the kinds
79 Step 4: buildTyConOrClass
80 Construct an environment binding T to a TyCon and C to a Class.
81 a) Their kinds comes from zonking the relevant kind variable
82 b) Their arity (for synonyms) comes direct from the decl
83 c) The funcional dependencies come from the decl
84 d) The rest comes a knot-tied binding of T and C, returned from Step 4
85 e) The variances of the tycons in the group is calculated from
89 In this environment, walk over the decls, constructing the TyCons and Classes.
90 This uses in a strict way items (a)-(c) above, which is why they must
91 be constructed in Step 4. Feed the results back to Step 4.
92 For this step, pass the is-recursive flag as the wimp-out flag
96 Step 6: Extend environment
97 We extend the type environment with bindings not only for the TyCons and Classes,
98 but also for their "implicit Ids" like data constructors and class selectors
100 Step 7: checkValidTyCl
101 For a recursive group only, check all the decls again, just
102 to check all the side conditions on validity. We could not
103 do this before because we were in a mutually recursive knot.
105 Identification of recursive TyCons
106 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
107 The knot-tying parameters: @rec_details_list@ is an alist mapping @Name@s to
110 Identifying a TyCon as recursive serves two purposes
112 1. Avoid infinite types. Non-recursive newtypes are treated as
113 "transparent", like type synonyms, after the type checker. If we did
114 this for all newtypes, we'd get infinite types. So we figure out for
115 each newtype whether it is "recursive", and add a coercion if so. In
116 effect, we are trying to "cut the loops" by identifying a loop-breaker.
118 2. Avoid infinite unboxing. This is nothing to do with newtypes.
122 Well, this function diverges, but we don't want the strictness analyser
123 to diverge. But the strictness analyser will diverge because it looks
124 deeper and deeper into the structure of T. (I believe there are
125 examples where the function does something sane, and the strictness
126 analyser still diverges, but I can't see one now.)
128 Now, concerning (1), the FC2 branch currently adds a coercion for ALL
129 newtypes. I did this as an experiment, to try to expose cases in which
130 the coercions got in the way of optimisations. If it turns out that we
131 can indeed always use a coercion, then we don't risk recursive types,
132 and don't need to figure out what the loop breakers are.
134 For newtype *families* though, we will always have a coercion, so they
135 are always loop breakers! So you can easily adjust the current
136 algorithm by simply treating all newtype families as loop breakers (and
137 indeed type families). I think.
140 tcTyAndClassDecls :: ModDetails -> [LTyClDecl Name]
141 -> TcM TcGblEnv -- Input env extended by types and classes
142 -- and their implicit Ids,DataCons
143 tcTyAndClassDecls boot_details allDecls
144 = do { -- Omit instances of type families; they are handled together
145 -- with the *heads* of class instances
146 ; let decls = filter (not . isFamInstDecl . unLoc) allDecls
148 -- First check for cyclic type synonysm or classes
149 -- See notes with checkCycleErrs
150 ; checkCycleErrs decls
152 ; traceTc (text "tcTyAndCl" <+> ppr mod)
153 ; (syn_tycons, alg_tyclss) <- fixM (\ ~(rec_syn_tycons, rec_alg_tyclss) ->
154 do { let { -- Seperate ordinary synonyms from all other type and
155 -- class declarations and add all associated type
156 -- declarations from type classes. The latter is
157 -- required so that the temporary environment for the
158 -- knot includes all associated family declarations.
159 ; (syn_decls, alg_decls) = partition (isSynDecl . unLoc)
161 ; alg_at_decls = concatMap addATs alg_decls
163 -- Extend the global env with the knot-tied results
164 -- for data types and classes
166 -- We must populate the environment with the loop-tied
167 -- T's right away, because the kind checker may "fault
168 -- in" some type constructors that recursively
170 ; let gbl_things = mkGlobalThings alg_at_decls rec_alg_tyclss
171 ; tcExtendRecEnv gbl_things $ do
173 -- Kind-check the declarations
174 { (kc_syn_decls, kc_alg_decls) <- kcTyClDecls syn_decls alg_decls
176 ; let { -- Calculate rec-flag
177 ; calc_rec = calcRecFlags boot_details rec_alg_tyclss
178 ; tc_decl = addLocM (tcTyClDecl calc_rec) }
180 -- Type-check the type synonyms, and extend the envt
181 ; syn_tycons <- tcSynDecls kc_syn_decls
182 ; tcExtendGlobalEnv syn_tycons $ do
184 -- Type-check the data types and classes
185 { alg_tyclss <- mappM tc_decl kc_alg_decls
186 ; return (syn_tycons, concat alg_tyclss)
188 -- Finished with knot-tying now
189 -- Extend the environment with the finished things
190 ; tcExtendGlobalEnv (syn_tycons ++ alg_tyclss) $ do
192 -- Perform the validity check
193 { traceTc (text "ready for validity check")
194 ; mappM_ (addLocM checkValidTyCl) decls
195 ; traceTc (text "done")
197 -- Add the implicit things;
198 -- we want them in the environment because
199 -- they may be mentioned in interface files
200 -- NB: All associated types and their implicit things will be added a
201 -- second time here. This doesn't matter as the definitions are
203 ; let { implicit_things = concatMap implicitTyThings alg_tyclss }
204 ; traceTc ((text "Adding" <+> ppr alg_tyclss)
205 $$ (text "and" <+> ppr implicit_things))
206 ; tcExtendGlobalEnv implicit_things getGblEnv
209 -- Pull associated types out of class declarations, to tie them into the
211 -- NB: We put them in the same place in the list as `tcTyClDecl' will
212 -- eventually put the matching `TyThing's. That's crucial; otherwise,
213 -- the two argument lists of `mkGlobalThings' don't match up.
214 addATs decl@(L _ (ClassDecl {tcdATs = ats})) = decl : ats
217 mkGlobalThings :: [LTyClDecl Name] -- The decls
218 -> [TyThing] -- Knot-tied, in 1-1 correspondence with the decls
220 -- Driven by the Decls, and treating the TyThings lazily
221 -- make a TypeEnv for the new things
222 mkGlobalThings decls things
223 = map mk_thing (decls `zipLazy` things)
225 mk_thing (L _ (ClassDecl {tcdLName = L _ name}), ~(AClass cl))
227 mk_thing (L _ decl, ~(ATyCon tc))
228 = (tcdName decl, ATyCon tc)
232 %************************************************************************
234 \subsection{Type checking family instances}
236 %************************************************************************
238 Family instances are somewhat of a hybrid. They are processed together with
239 class instance heads, but can contain data constructors and hence they share a
240 lot of kinding and type checking code with ordinary algebraic data types (and
244 tcFamInstDecl :: LTyClDecl Name -> TcM (Maybe TyThing) -- Nothing if error
245 tcFamInstDecl (L loc decl)
246 = -- Prime error recovery, set source location
247 recoverM (returnM Nothing) $
250 do { -- type families require -XTypeFamilies and can't be in an
252 ; type_families <- doptM Opt_TypeFamilies
253 ; is_boot <- tcIsHsBoot -- Are we compiling an hs-boot file?
254 ; checkTc type_families $ badFamInstDecl (tcdLName decl)
255 ; checkTc (not is_boot) $ badBootFamInstDeclErr
257 -- perform kind and type checking
258 ; tcFamInstDecl1 decl
261 tcFamInstDecl1 :: TyClDecl Name -> TcM (Maybe TyThing) -- Nothing if error
264 tcFamInstDecl1 (decl@TySynonym {tcdLName = L loc tc_name})
265 = kcIdxTyPats decl $ \k_tvs k_typats resKind family ->
266 do { -- check that the family declaration is for a synonym
267 unless (isSynTyCon family) $
268 addErr (wrongKindOfFamily family)
270 ; -- (1) kind check the right-hand side of the type equation
271 ; k_rhs <- kcCheckHsType (tcdSynRhs decl) resKind
273 -- we need the exact same number of type parameters as the family
275 ; let famArity = tyConArity family
276 ; checkTc (length k_typats == famArity) $
277 wrongNumberOfParmsErr famArity
279 -- (2) type check type equation
280 ; tcTyVarBndrs k_tvs $ \t_tvs -> do { -- turn kinded into proper tyvars
281 ; t_typats <- mappM tcHsKindedType k_typats
282 ; t_rhs <- tcHsKindedType k_rhs
285 -- - check the well-formedness of the instance
286 ; checkValidTypeInst t_typats t_rhs
288 -- (4) construct representation tycon
289 ; rep_tc_name <- newFamInstTyConName tc_name loc
290 ; tycon <- buildSynTyCon rep_tc_name t_tvs (SynonymTyCon t_rhs)
291 (Just (family, t_typats))
293 ; return $ Just (ATyCon tycon)
296 -- "newtype instance" and "data instance"
297 tcFamInstDecl1 (decl@TyData {tcdND = new_or_data, tcdLName = L loc tc_name,
299 = kcIdxTyPats decl $ \k_tvs k_typats resKind family ->
300 do { -- check that the family declaration is for the right kind
301 unless (isAlgTyCon family) $
302 addErr (wrongKindOfFamily family)
304 ; -- (1) kind check the data declaration as usual
305 ; k_decl <- kcDataDecl decl k_tvs
306 ; let k_ctxt = tcdCtxt k_decl
307 k_cons = tcdCons k_decl
309 -- result kind must be '*' (otherwise, we have too few patterns)
310 ; checkTc (isLiftedTypeKind resKind) $ tooFewParmsErr (tyConArity family)
312 -- (2) type check indexed data type declaration
313 ; tcTyVarBndrs k_tvs $ \t_tvs -> do { -- turn kinded into proper tyvars
314 ; unbox_strict <- doptM Opt_UnboxStrictFields
316 -- kind check the type indexes and the context
317 ; t_typats <- mappM tcHsKindedType k_typats
318 ; stupid_theta <- tcHsKindedContext k_ctxt
321 -- - left-hand side contains no type family applications
322 -- (vanilla synonyms are fine, though, and we checked for
324 ; mappM_ checkTyFamFreeness t_typats
326 -- - we don't use GADT syntax for indexed types
327 ; checkTc h98_syntax (badGadtIdxTyDecl tc_name)
329 -- - a newtype has exactly one constructor
330 ; checkTc (new_or_data == DataType || isSingleton k_cons) $
331 newtypeConError tc_name (length k_cons)
333 -- (4) construct representation tycon
334 ; rep_tc_name <- newFamInstTyConName tc_name loc
335 ; tycon <- fixM (\ tycon -> do
336 { data_cons <- mappM (addLocM (tcConDecl unbox_strict tycon t_tvs))
340 DataType -> return (mkDataTyConRhs data_cons)
341 NewType -> ASSERT( not (null data_cons) )
342 mkNewTyConRhs rep_tc_name tycon (head data_cons)
343 ; buildAlgTyCon rep_tc_name t_tvs stupid_theta tc_rhs Recursive
344 False h98_syntax (Just (family, t_typats))
345 -- We always assume that indexed types are recursive. Why?
346 -- (1) Due to their open nature, we can never be sure that a
347 -- further instance might not introduce a new recursive
348 -- dependency. (2) They are always valid loop breakers as
349 -- they involve a coercion.
353 ; return $ Just (ATyCon tycon)
356 h98_syntax = case cons of -- All constructors have same shape
357 L _ (ConDecl { con_res = ResTyGADT _ }) : _ -> False
360 -- Kind checking of indexed types
363 -- Kind check type patterns and kind annotate the embedded type variables.
365 -- * Here we check that a type instance matches its kind signature, but we do
366 -- not check whether there is a pattern for each type index; the latter
367 -- check is only required for type synonym instances.
369 kcIdxTyPats :: TyClDecl Name
370 -> ([LHsTyVarBndr Name] -> [LHsType Name] -> Kind -> TyCon -> TcM a)
371 -- ^^kinded tvs ^^kinded ty pats ^^res kind
373 kcIdxTyPats decl thing_inside
374 = kcHsTyVars (tcdTyVars decl) $ \tvs ->
375 do { family <- tcLookupLocatedTyCon (tcdLName decl)
376 ; let { (kinds, resKind) = splitKindFunTys (tyConKind family)
377 ; hs_typats = fromJust $ tcdTyPats decl }
379 -- we may not have more parameters than the kind indicates
380 ; checkTc (length kinds >= length hs_typats) $
381 tooManyParmsErr (tcdLName decl)
383 -- type functions can have a higher-kinded result
384 ; let resultKind = mkArrowKinds (drop (length hs_typats) kinds) resKind
385 ; typats <- TcRnMonad.zipWithM kcCheckHsType hs_typats kinds
386 ; thing_inside tvs typats resultKind family
392 %************************************************************************
396 %************************************************************************
398 We need to kind check all types in the mutually recursive group
399 before we know the kind of the type variables. For example:
402 op :: D b => a -> b -> b
405 bop :: (Monad c) => ...
407 Here, the kind of the locally-polymorphic type variable "b"
408 depends on *all the uses of class D*. For example, the use of
409 Monad c in bop's type signature means that D must have kind Type->Type.
411 However type synonyms work differently. They can have kinds which don't
412 just involve (->) and *:
413 type R = Int# -- Kind #
414 type S a = Array# a -- Kind * -> #
415 type T a b = (# a,b #) -- Kind * -> * -> (# a,b #)
416 So we must infer their kinds from their right-hand sides *first* and then
417 use them, whereas for the mutually recursive data types D we bring into
418 scope kind bindings D -> k, where k is a kind variable, and do inference.
422 This treatment of type synonyms only applies to Haskell 98-style synonyms.
423 General type functions can be recursive, and hence, appear in `alg_decls'.
425 The kind of a type family is solely determinded by its kind signature;
426 hence, only kind signatures participate in the construction of the initial
427 kind environment (as constructed by `getInitialKind'). In fact, we ignore
428 instances of families altogether in the following. However, we need to
429 include the kinds of associated families into the construction of the
430 initial kind environment. (This is handled by `allDecls').
433 kcTyClDecls syn_decls alg_decls
434 = do { -- First extend the kind env with each data type, class, and
435 -- indexed type, mapping them to a type variable
436 let initialKindDecls = concat [allDecls decl | L _ decl <- alg_decls]
437 ; alg_kinds <- mappM getInitialKind initialKindDecls
438 ; tcExtendKindEnv alg_kinds $ do
440 -- Now kind-check the type synonyms, in dependency order
441 -- We do these differently to data type and classes,
442 -- because a type synonym can be an unboxed type
444 -- and a kind variable can't unify with UnboxedTypeKind
445 -- So we infer their kinds in dependency order
446 { (kc_syn_decls, syn_kinds) <- kcSynDecls (calcSynCycles syn_decls)
447 ; tcExtendKindEnv syn_kinds $ do
449 -- Now kind-check the data type, class, and kind signatures,
450 -- returning kind-annotated decls; we don't kind-check
451 -- instances of indexed types yet, but leave this to
453 { kc_alg_decls <- mappM (wrapLocM kcTyClDecl)
454 (filter (not . isFamInstDecl . unLoc) alg_decls)
456 ; return (kc_syn_decls, kc_alg_decls) }}}
458 -- get all declarations relevant for determining the initial kind
460 allDecls (decl@ClassDecl {tcdATs = ats}) = decl : [ at
463 allDecls decl | isFamInstDecl decl = []
466 ------------------------------------------------------------------------
467 getInitialKind :: TyClDecl Name -> TcM (Name, TcKind)
468 -- Only for data type, class, and indexed type declarations
469 -- Get as much info as possible from the data, class, or indexed type decl,
470 -- so as to maximise usefulness of error messages
472 = do { arg_kinds <- mapM (mk_arg_kind . unLoc) (tyClDeclTyVars decl)
473 ; res_kind <- mk_res_kind decl
474 ; return (tcdName decl, mkArrowKinds arg_kinds res_kind) }
476 mk_arg_kind (UserTyVar _) = newKindVar
477 mk_arg_kind (KindedTyVar _ kind) = return kind
479 mk_res_kind (TyFamily { tcdKind = Just kind }) = return kind
480 mk_res_kind (TyData { tcdKindSig = Just kind }) = return kind
481 -- On GADT-style declarations we allow a kind signature
482 -- data T :: *->* where { ... }
483 mk_res_kind other = return liftedTypeKind
487 kcSynDecls :: [SCC (LTyClDecl Name)]
488 -> TcM ([LTyClDecl Name], -- Kind-annotated decls
489 [(Name,TcKind)]) -- Kind bindings
492 kcSynDecls (group : groups)
493 = do { (decl, nk) <- kcSynDecl group
494 ; (decls, nks) <- tcExtendKindEnv [nk] (kcSynDecls groups)
495 ; return (decl:decls, nk:nks) }
498 kcSynDecl :: SCC (LTyClDecl Name)
499 -> TcM (LTyClDecl Name, -- Kind-annotated decls
500 (Name,TcKind)) -- Kind bindings
501 kcSynDecl (AcyclicSCC ldecl@(L loc decl))
502 = tcAddDeclCtxt decl $
503 kcHsTyVars (tcdTyVars decl) (\ k_tvs ->
504 do { traceTc (text "kcd1" <+> ppr (unLoc (tcdLName decl)) <+> brackets (ppr (tcdTyVars decl))
505 <+> brackets (ppr k_tvs))
506 ; (k_rhs, rhs_kind) <- kcHsType (tcdSynRhs decl)
507 ; traceTc (text "kcd2" <+> ppr (unLoc (tcdLName decl)))
508 ; let tc_kind = foldr (mkArrowKind . kindedTyVarKind) rhs_kind k_tvs
509 ; return (L loc (decl { tcdTyVars = k_tvs, tcdSynRhs = k_rhs }),
510 (unLoc (tcdLName decl), tc_kind)) })
512 kcSynDecl (CyclicSCC decls)
513 = do { recSynErr decls; failM } -- Fail here to avoid error cascade
514 -- of out-of-scope tycons
516 kindedTyVarKind (L _ (KindedTyVar _ k)) = k
518 ------------------------------------------------------------------------
519 kcTyClDecl :: TyClDecl Name -> TcM (TyClDecl Name)
520 -- Not used for type synonyms (see kcSynDecl)
522 kcTyClDecl decl@(TyData {})
523 = ASSERT( not . isFamInstDecl $ decl ) -- must not be a family instance
524 kcTyClDeclBody decl $
527 kcTyClDecl decl@(TyFamily {})
528 = kcFamilyDecl [] decl -- the empty list signals a toplevel decl
530 kcTyClDecl decl@(ClassDecl {tcdCtxt = ctxt, tcdSigs = sigs, tcdATs = ats})
531 = kcTyClDeclBody decl $ \ tvs' ->
532 do { is_boot <- tcIsHsBoot
533 ; ctxt' <- kcHsContext ctxt
534 ; ats' <- mappM (wrapLocM (kcFamilyDecl tvs')) ats
535 ; sigs' <- mappM (wrapLocM kc_sig) sigs
536 ; return (decl {tcdTyVars = tvs', tcdCtxt = ctxt', tcdSigs = sigs',
539 kc_sig (TypeSig nm op_ty) = do { op_ty' <- kcHsLiftedSigType op_ty
540 ; return (TypeSig nm op_ty') }
541 kc_sig other_sig = return other_sig
543 kcTyClDecl decl@(ForeignType {})
546 kcTyClDeclBody :: TyClDecl Name
547 -> ([LHsTyVarBndr Name] -> TcM a)
549 -- getInitialKind has made a suitably-shaped kind for the type or class
550 -- Unpack it, and attribute those kinds to the type variables
551 -- Extend the env with bindings for the tyvars, taken from
552 -- the kind of the tycon/class. Give it to the thing inside, and
553 -- check the result kind matches
554 kcTyClDeclBody decl thing_inside
555 = tcAddDeclCtxt decl $
556 do { tc_ty_thing <- tcLookupLocated (tcdLName decl)
557 ; let tc_kind = case tc_ty_thing of { AThing k -> k }
558 (kinds, _) = splitKindFunTys tc_kind
559 hs_tvs = tcdTyVars decl
560 kinded_tvs = ASSERT( length kinds >= length hs_tvs )
561 [ L loc (KindedTyVar (hsTyVarName tv) k)
562 | (L loc tv, k) <- zip hs_tvs kinds]
563 ; tcExtendKindEnvTvs kinded_tvs (thing_inside kinded_tvs) }
565 -- Kind check a data declaration, assuming that we already extended the
566 -- kind environment with the type variables of the left-hand side (these
567 -- kinded type variables are also passed as the second parameter).
569 kcDataDecl :: TyClDecl Name -> [LHsTyVarBndr Name] -> TcM (TyClDecl Name)
570 kcDataDecl decl@(TyData {tcdND = new_or_data, tcdCtxt = ctxt, tcdCons = cons})
572 = do { ctxt' <- kcHsContext ctxt
573 ; cons' <- mappM (wrapLocM kc_con_decl) cons
574 ; return (decl {tcdTyVars = tvs, tcdCtxt = ctxt', tcdCons = cons'}) }
576 -- doc comments are typechecked to Nothing here
577 kc_con_decl (ConDecl name expl ex_tvs ex_ctxt details res _) = do
578 kcHsTyVars ex_tvs $ \ex_tvs' -> do
579 ex_ctxt' <- kcHsContext ex_ctxt
580 details' <- kc_con_details details
582 ResTyH98 -> return ResTyH98
583 ResTyGADT ty -> do { ty' <- kcHsSigType ty; return (ResTyGADT ty') }
584 return (ConDecl name expl ex_tvs' ex_ctxt' details' res' Nothing)
586 kc_con_details (PrefixCon btys)
587 = do { btys' <- mappM kc_larg_ty btys
588 ; return (PrefixCon btys') }
589 kc_con_details (InfixCon bty1 bty2)
590 = do { bty1' <- kc_larg_ty bty1
591 ; bty2' <- kc_larg_ty bty2
592 ; return (InfixCon bty1' bty2') }
593 kc_con_details (RecCon fields)
594 = do { fields' <- mappM kc_field fields
595 ; return (RecCon fields') }
597 kc_field (ConDeclField fld bty d) = do { bty' <- kc_larg_ty bty
598 ; return (ConDeclField fld bty' d) }
600 kc_larg_ty bty = case new_or_data of
601 DataType -> kcHsSigType bty
602 NewType -> kcHsLiftedSigType bty
603 -- Can't allow an unlifted type for newtypes, because we're effectively
604 -- going to remove the constructor while coercing it to a lifted type.
605 -- And newtypes can't be bang'd
607 -- Kind check a family declaration or type family default declaration.
609 kcFamilyDecl :: [LHsTyVarBndr Name] -- tyvars of enclosing class decl if any
610 -> TyClDecl Name -> TcM (TyClDecl Name)
611 kcFamilyDecl classTvs decl@(TyFamily {tcdKind = kind})
612 = kcTyClDeclBody decl $ \tvs' ->
613 do { mapM_ unifyClassParmKinds tvs'
614 ; return (decl {tcdTyVars = tvs',
615 tcdKind = kind `mplus` Just liftedTypeKind})
616 -- default result kind is '*'
619 unifyClassParmKinds (L _ (KindedTyVar n k))
620 | Just classParmKind <- lookup n classTyKinds = unifyKind k classParmKind
621 | otherwise = return ()
622 classTyKinds = [(n, k) | L _ (KindedTyVar n k) <- classTvs]
623 kcFamilyDecl _ decl@(TySynonym {}) -- type family defaults
624 = panic "TcTyClsDecls.kcFamilyDecl: not implemented yet"
628 %************************************************************************
630 \subsection{Type checking}
632 %************************************************************************
635 tcSynDecls :: [LTyClDecl Name] -> TcM [TyThing]
636 tcSynDecls [] = return []
637 tcSynDecls (decl : decls)
638 = do { syn_tc <- addLocM tcSynDecl decl
639 ; syn_tcs <- tcExtendGlobalEnv [syn_tc] (tcSynDecls decls)
640 ; return (syn_tc : syn_tcs) }
644 (TySynonym {tcdLName = L _ tc_name, tcdTyVars = tvs, tcdSynRhs = rhs_ty})
645 = tcTyVarBndrs tvs $ \ tvs' -> do
646 { traceTc (text "tcd1" <+> ppr tc_name)
647 ; rhs_ty' <- tcHsKindedType rhs_ty
648 ; tycon <- buildSynTyCon tc_name tvs' (SynonymTyCon rhs_ty') Nothing
649 ; return (ATyCon tycon)
653 tcTyClDecl :: (Name -> RecFlag) -> TyClDecl Name -> TcM [TyThing]
655 tcTyClDecl calc_isrec decl
656 = tcAddDeclCtxt decl (tcTyClDecl1 calc_isrec decl)
658 -- "type family" declarations
659 tcTyClDecl1 _calc_isrec
660 (TyFamily {tcdFlavour = TypeFamily,
661 tcdLName = L _ tc_name, tcdTyVars = tvs, tcdKind = Just kind})
662 -- NB: kind at latest
665 = tcTyVarBndrs tvs $ \ tvs' -> do
666 { traceTc (text "type family: " <+> ppr tc_name)
667 ; idx_tys <- doptM Opt_TypeFamilies
669 -- Check that we don't use families without -XTypeFamilies
670 ; checkTc idx_tys $ badFamInstDecl tc_name
672 ; tycon <- buildSynTyCon tc_name tvs' (OpenSynTyCon kind Nothing) Nothing
673 ; return [ATyCon tycon]
676 -- "data family" declaration
677 tcTyClDecl1 _calc_isrec
678 (TyFamily {tcdFlavour = DataFamily,
679 tcdLName = L _ tc_name, tcdTyVars = tvs, tcdKind = mb_kind})
680 = tcTyVarBndrs tvs $ \ tvs' -> do
681 { traceTc (text "data family: " <+> ppr tc_name)
682 ; extra_tvs <- tcDataKindSig mb_kind
683 ; let final_tvs = tvs' ++ extra_tvs -- we may not need these
685 ; idx_tys <- doptM Opt_TypeFamilies
687 -- Check that we don't use families without -XTypeFamilies
688 ; checkTc idx_tys $ badFamInstDecl tc_name
690 ; tycon <- buildAlgTyCon tc_name final_tvs []
691 mkOpenDataTyConRhs Recursive False True Nothing
692 ; return [ATyCon tycon]
695 -- "newtype" and "data"
696 -- NB: not used for newtype/data instances (whether associated or not)
697 tcTyClDecl1 calc_isrec
698 (TyData {tcdND = new_or_data, tcdCtxt = ctxt, tcdTyVars = tvs,
699 tcdLName = L _ tc_name, tcdKindSig = mb_ksig, tcdCons = cons})
700 = tcTyVarBndrs tvs $ \ tvs' -> do
701 { extra_tvs <- tcDataKindSig mb_ksig
702 ; let final_tvs = tvs' ++ extra_tvs
703 ; stupid_theta <- tcHsKindedContext ctxt
704 ; want_generic <- doptM Opt_Generics
705 ; unbox_strict <- doptM Opt_UnboxStrictFields
706 ; empty_data_decls <- doptM Opt_EmptyDataDecls
707 ; kind_signatures <- doptM Opt_KindSignatures
708 ; gadt_ok <- doptM Opt_GADTs
709 ; is_boot <- tcIsHsBoot -- Are we compiling an hs-boot file?
711 -- Check that we don't use GADT syntax in H98 world
712 ; checkTc (gadt_ok || h98_syntax) (badGadtDecl tc_name)
714 -- Check that we don't use kind signatures without Glasgow extensions
715 ; checkTc (kind_signatures || isNothing mb_ksig) (badSigTyDecl tc_name)
717 -- Check that the stupid theta is empty for a GADT-style declaration
718 ; checkTc (null stupid_theta || h98_syntax) (badStupidTheta tc_name)
720 -- Check that there's at least one condecl,
721 -- or else we're reading an hs-boot file, or -XEmptyDataDecls
722 ; checkTc (not (null cons) || empty_data_decls || is_boot)
723 (emptyConDeclsErr tc_name)
725 -- Check that a newtype has exactly one constructor
726 ; checkTc (new_or_data == DataType || isSingleton cons)
727 (newtypeConError tc_name (length cons))
729 ; tycon <- fixM (\ tycon -> do
730 { data_cons <- mappM (addLocM (tcConDecl unbox_strict tycon final_tvs))
733 if null cons && is_boot -- In a hs-boot file, empty cons means
734 then return AbstractTyCon -- "don't know"; hence Abstract
735 else case new_or_data of
736 DataType -> return (mkDataTyConRhs data_cons)
738 ASSERT( not (null data_cons) )
739 mkNewTyConRhs tc_name tycon (head data_cons)
740 ; buildAlgTyCon tc_name final_tvs stupid_theta tc_rhs is_rec
741 (want_generic && canDoGenerics data_cons) h98_syntax Nothing
743 ; return [ATyCon tycon]
746 is_rec = calc_isrec tc_name
747 h98_syntax = case cons of -- All constructors have same shape
748 L _ (ConDecl { con_res = ResTyGADT _ }) : _ -> False
751 tcTyClDecl1 calc_isrec
752 (ClassDecl {tcdLName = L _ class_name, tcdTyVars = tvs,
753 tcdCtxt = ctxt, tcdMeths = meths,
754 tcdFDs = fundeps, tcdSigs = sigs, tcdATs = ats} )
755 = tcTyVarBndrs tvs $ \ tvs' -> do
756 { ctxt' <- tcHsKindedContext ctxt
757 ; fds' <- mappM (addLocM tc_fundep) fundeps
758 ; atss <- mappM (addLocM (tcTyClDecl1 (const Recursive))) ats
759 -- NB: 'ats' only contains "type family" and "data family"
760 -- declarations as well as type family defaults
761 ; let ats' = zipWith setTyThingPoss atss (map (tcdTyVars . unLoc) ats)
762 ; sig_stuff <- tcClassSigs class_name sigs meths
763 ; clas <- fixM (\ clas ->
764 let -- This little knot is just so we can get
765 -- hold of the name of the class TyCon, which we
766 -- need to look up its recursiveness
767 tycon_name = tyConName (classTyCon clas)
768 tc_isrec = calc_isrec tycon_name
770 buildClass class_name tvs' ctxt' fds' ats'
772 ; return (AClass clas : ats')
773 -- NB: Order is important due to the call to `mkGlobalThings' when
774 -- tying the the type and class declaration type checking knot.
777 tc_fundep (tvs1, tvs2) = do { tvs1' <- mappM tcLookupTyVar tvs1 ;
778 ; tvs2' <- mappM tcLookupTyVar tvs2 ;
779 ; return (tvs1', tvs2') }
781 -- For each AT argument compute the position of the corresponding class
782 -- parameter in the class head. This will later serve as a permutation
783 -- vector when checking the validity of instance declarations.
784 setTyThingPoss [ATyCon tycon] atTyVars =
785 let classTyVars = hsLTyVarNames tvs
787 . map (`elemIndex` classTyVars)
790 -- There will be no Nothing, as we already passed renaming
792 ATyCon (setTyConArgPoss tycon poss)
793 setTyThingPoss _ _ = panic "TcTyClsDecls.setTyThingPoss"
795 tcTyClDecl1 calc_isrec
796 (ForeignType {tcdLName = L _ tc_name, tcdExtName = tc_ext_name})
797 = returnM [ATyCon (mkForeignTyCon tc_name tc_ext_name liftedTypeKind 0)]
799 -----------------------------------
800 tcConDecl :: Bool -- True <=> -funbox-strict_fields
805 tcConDecl unbox_strict tycon tc_tvs -- Data types
806 (ConDecl name _ tvs ctxt details res_ty _)
807 = tcTyVarBndrs tvs $ \ tvs' -> do
808 { ctxt' <- tcHsKindedContext ctxt
809 ; (univ_tvs, ex_tvs, eq_preds, data_tc) <- tcResultType tycon tc_tvs tvs' res_ty
811 -- Tiresome: tidy the tyvar binders, since tc_tvs and tvs' may have the same OccNames
812 tc_datacon is_infix field_lbls btys
813 = do { let bangs = map getBangStrictness btys
814 ; arg_tys <- mappM tcHsBangType btys
815 ; buildDataCon (unLoc name) is_infix
816 (argStrictness unbox_strict bangs arg_tys)
817 (map unLoc field_lbls)
818 univ_tvs ex_tvs eq_preds ctxt' arg_tys
820 -- NB: we put data_tc, the type constructor gotten from the
821 -- constructor type signature into the data constructor;
822 -- that way checkValidDataCon can complain if it's wrong.
825 PrefixCon btys -> tc_datacon False [] btys
826 InfixCon bty1 bty2 -> tc_datacon True [] [bty1,bty2]
827 RecCon fields -> tc_datacon False field_names btys
829 field_names = map cd_fld_name fields
830 btys = map cd_fld_type fields
833 tcResultType :: TyCon
834 -> [TyVar] -- data T a b c = ...
835 -> [TyVar] -- where MkT :: forall a b c. ...
837 -> TcM ([TyVar], -- Universal
838 [TyVar], -- Existential (distinct OccNames from univs)
839 [(TyVar,Type)], -- Equality predicates
840 TyCon) -- TyCon given in the ResTy
841 -- We don't check that the TyCon given in the ResTy is
842 -- the same as the parent tycon, becuase we are in the middle
843 -- of a recursive knot; so it's postponed until checkValidDataCon
845 tcResultType decl_tycon tc_tvs dc_tvs ResTyH98
846 = return (tc_tvs, dc_tvs, [], decl_tycon)
847 -- In H98 syntax the dc_tvs are the existential ones
848 -- data T a b c = forall d e. MkT ...
849 -- The {a,b,c} are tc_tvs, and {d,e} are dc_tvs
851 tcResultType _ tc_tvs dc_tvs (ResTyGADT res_ty)
852 -- E.g. data T a b c where
853 -- MkT :: forall x y z. T (x,y) z z
855 -- ([a,z,c], [x,y], [a:=:(x,y), c:=:z], T)
857 = do { (dc_tycon, res_tys) <- tcLHsConResTy res_ty
859 ; let univ_tvs = choose_univs [] tidy_tc_tvs res_tys
860 -- Each univ_tv is either a dc_tv or a tc_tv
861 ex_tvs = dc_tvs `minusList` univ_tvs
862 eq_spec = [ (tv, ty) | (tv,ty) <- univ_tvs `zip` res_tys,
864 ; return (univ_tvs, ex_tvs, eq_spec, dc_tycon) }
866 -- choose_univs uses the res_ty itself if it's a type variable
867 -- and hasn't already been used; otherwise it uses one of the tc_tvs
868 choose_univs used tc_tvs []
869 = ASSERT( null tc_tvs ) []
870 choose_univs used (tc_tv:tc_tvs) (res_ty:res_tys)
871 | Just tv <- tcGetTyVar_maybe res_ty, not (tv `elem` used)
872 = tv : choose_univs (tv:used) tc_tvs res_tys
874 = tc_tv : choose_univs used tc_tvs res_tys
876 -- NB: tc_tvs and dc_tvs are distinct, but
877 -- we want them to be *visibly* distinct, both for
878 -- interface files and general confusion. So rename
879 -- the tc_tvs, since they are not used yet (no
880 -- consequential renaming needed)
881 init_occ_env = initTidyOccEnv (map getOccName dc_tvs)
882 (_, tidy_tc_tvs) = mapAccumL tidy_one init_occ_env tc_tvs
883 tidy_one env tv = (env', setTyVarName tv (tidyNameOcc name occ'))
886 (env', occ') = tidyOccName env (getOccName name)
889 argStrictness :: Bool -- True <=> -funbox-strict_fields
891 -> [TcType] -> [StrictnessMark]
892 argStrictness unbox_strict bangs arg_tys
893 = ASSERT( length bangs == length arg_tys )
894 zipWith (chooseBoxingStrategy unbox_strict) arg_tys bangs
896 -- We attempt to unbox/unpack a strict field when either:
897 -- (i) The field is marked '!!', or
898 -- (ii) The field is marked '!', and the -funbox-strict-fields flag is on.
900 -- We have turned off unboxing of newtypes because coercions make unboxing
901 -- and reboxing more complicated
902 chooseBoxingStrategy :: Bool -> TcType -> HsBang -> StrictnessMark
903 chooseBoxingStrategy unbox_strict_fields arg_ty bang
905 HsNoBang -> NotMarkedStrict
906 HsStrict | unbox_strict_fields
907 && can_unbox arg_ty -> MarkedUnboxed
908 HsUnbox | can_unbox arg_ty -> MarkedUnboxed
909 other -> MarkedStrict
911 -- we can unbox if the type is a chain of newtypes with a product tycon
913 can_unbox arg_ty = case splitTyConApp_maybe arg_ty of
915 Just (arg_tycon, tycon_args) ->
916 not (isRecursiveTyCon arg_tycon) && -- Note [Recusive unboxing]
917 isProductTyCon arg_tycon &&
918 (if isNewTyCon arg_tycon then
919 can_unbox (newTyConInstRhs arg_tycon tycon_args)
923 Note [Recursive unboxing]
924 ~~~~~~~~~~~~~~~~~~~~~~~~~
925 Be careful not to try to unbox this!
927 But it's the *argument* type that matters. This is fine:
929 because Int is non-recursive.
931 %************************************************************************
933 \subsection{Dependency analysis}
935 %************************************************************************
937 Validity checking is done once the mutually-recursive knot has been
938 tied, so we can look at things freely.
941 checkCycleErrs :: [LTyClDecl Name] -> TcM ()
942 checkCycleErrs tyclss
946 = do { mappM_ recClsErr cls_cycles
947 ; failM } -- Give up now, because later checkValidTyCl
948 -- will loop if the synonym is recursive
950 cls_cycles = calcClassCycles tyclss
952 checkValidTyCl :: TyClDecl Name -> TcM ()
953 -- We do the validity check over declarations, rather than TyThings
954 -- only so that we can add a nice context with tcAddDeclCtxt
956 = tcAddDeclCtxt decl $
957 do { thing <- tcLookupLocatedGlobal (tcdLName decl)
958 ; traceTc (text "Validity of" <+> ppr thing)
960 ATyCon tc -> checkValidTyCon tc
961 AClass cl -> checkValidClass cl
962 ; traceTc (text "Done validity of" <+> ppr thing)
965 -------------------------
966 -- For data types declared with record syntax, we require
967 -- that each constructor that has a field 'f'
968 -- (a) has the same result type
969 -- (b) has the same type for 'f'
970 -- module alpha conversion of the quantified type variables
971 -- of the constructor.
973 checkValidTyCon :: TyCon -> TcM ()
976 = case synTyConRhs tc of
977 OpenSynTyCon _ _ -> return ()
978 SynonymTyCon ty -> checkValidType syn_ctxt ty
980 = -- Check the context on the data decl
981 checkValidTheta (DataTyCtxt name) (tyConStupidTheta tc) `thenM_`
983 -- Check arg types of data constructors
984 mappM_ (checkValidDataCon tc) data_cons `thenM_`
986 -- Check that fields with the same name share a type
987 mappM_ check_fields groups
990 syn_ctxt = TySynCtxt name
992 data_cons = tyConDataCons tc
994 groups = equivClasses cmp_fld (concatMap get_fields data_cons)
995 cmp_fld (f1,_) (f2,_) = f1 `compare` f2
996 get_fields con = dataConFieldLabels con `zip` repeat con
997 -- dataConFieldLabels may return the empty list, which is fine
999 -- See Note [GADT record selectors] in MkId.lhs
1000 -- We must check (a) that the named field has the same
1001 -- type in each constructor
1002 -- (b) that those constructors have the same result type
1004 -- However, the constructors may have differently named type variable
1005 -- and (worse) we don't know how the correspond to each other. E.g.
1006 -- C1 :: forall a b. { f :: a, g :: b } -> T a b
1007 -- C2 :: forall d c. { f :: c, g :: c } -> T c d
1009 -- So what we do is to ust Unify.tcMatchTys to compare the first candidate's
1010 -- result type against other candidates' types BOTH WAYS ROUND.
1011 -- If they magically agrees, take the substitution and
1012 -- apply them to the latter ones, and see if they match perfectly.
1013 check_fields fields@((label, con1) : other_fields)
1014 -- These fields all have the same name, but are from
1015 -- different constructors in the data type
1016 = recoverM (return ()) $ mapM_ checkOne other_fields
1017 -- Check that all the fields in the group have the same type
1018 -- NB: this check assumes that all the constructors of a given
1019 -- data type use the same type variables
1021 (tvs1, _, _, res1) = dataConSig con1
1023 fty1 = dataConFieldType con1 label
1025 checkOne (_, con2) -- Do it bothways to ensure they are structurally identical
1026 = do { checkFieldCompat label con1 con2 ts1 res1 res2 fty1 fty2
1027 ; checkFieldCompat label con2 con1 ts2 res2 res1 fty2 fty1 }
1029 (tvs2, _, _, res2) = dataConSig con2
1031 fty2 = dataConFieldType con2 label
1033 checkFieldCompat fld con1 con2 tvs1 res1 res2 fty1 fty2
1034 = do { checkTc (isJust mb_subst1) (resultTypeMisMatch fld con1 con2)
1035 ; checkTc (isJust mb_subst2) (fieldTypeMisMatch fld con1 con2) }
1037 mb_subst1 = tcMatchTy tvs1 res1 res2
1038 mb_subst2 = tcMatchTyX tvs1 (expectJust "checkFieldCompat" mb_subst1) fty1 fty2
1040 -------------------------------
1041 checkValidDataCon :: TyCon -> DataCon -> TcM ()
1042 checkValidDataCon tc con
1043 = setSrcSpan (srcLocSpan (getSrcLoc con)) $
1044 addErrCtxt (dataConCtxt con) $
1045 do { checkTc (dataConTyCon con == tc) (badDataConTyCon con)
1046 ; checkValidType ctxt (dataConUserType con)
1047 ; ifM (isNewTyCon tc) (checkNewDataCon con)
1050 ctxt = ConArgCtxt (dataConName con)
1052 -------------------------------
1053 checkNewDataCon :: DataCon -> TcM ()
1054 -- Checks for the data constructor of a newtype
1056 = do { checkTc (isSingleton arg_tys) (newtypeFieldErr con (length arg_tys))
1058 ; checkTc (null eq_spec) (newtypePredError con)
1059 -- Return type is (T a b c)
1060 ; checkTc (null ex_tvs && null eq_theta && null dict_theta) (newtypeExError con)
1062 ; checkTc (not (any isMarkedStrict (dataConStrictMarks con)))
1063 (newtypeStrictError con)
1067 (_univ_tvs, ex_tvs, eq_spec, eq_theta, dict_theta, arg_tys, _res_ty) = dataConFullSig con
1069 -------------------------------
1070 checkValidClass :: Class -> TcM ()
1072 = do { constrained_class_methods <- doptM Opt_ConstrainedClassMethods
1073 ; multi_param_type_classes <- doptM Opt_MultiParamTypeClasses
1074 ; fundep_classes <- doptM Opt_FunctionalDependencies
1076 -- Check that the class is unary, unless GlaExs
1077 ; checkTc (notNull tyvars) (nullaryClassErr cls)
1078 ; checkTc (multi_param_type_classes || unary) (classArityErr cls)
1079 ; checkTc (fundep_classes || null fundeps) (classFunDepsErr cls)
1081 -- Check the super-classes
1082 ; checkValidTheta (ClassSCCtxt (className cls)) theta
1084 -- Check the class operations
1085 ; mappM_ (check_op constrained_class_methods) op_stuff
1087 -- Check that if the class has generic methods, then the
1088 -- class has only one parameter. We can't do generic
1089 -- multi-parameter type classes!
1090 ; checkTc (unary || no_generics) (genericMultiParamErr cls)
1093 (tyvars, fundeps, theta, _, _, op_stuff) = classExtraBigSig cls
1094 unary = isSingleton tyvars
1095 no_generics = null [() | (_, GenDefMeth) <- op_stuff]
1097 check_op constrained_class_methods (sel_id, dm)
1098 = addErrCtxt (classOpCtxt sel_id tau) $ do
1099 { checkValidTheta SigmaCtxt (tail theta)
1100 -- The 'tail' removes the initial (C a) from the
1101 -- class itself, leaving just the method type
1103 ; traceTc (text "class op type" <+> ppr op_ty <+> ppr tau)
1104 ; checkValidType (FunSigCtxt op_name) tau
1106 -- Check that the type mentions at least one of
1107 -- the class type variables...or at least one reachable
1108 -- from one of the class variables. Example: tc223
1109 -- class Error e => Game b mv e | b -> mv e where
1110 -- newBoard :: MonadState b m => m ()
1111 -- Here, MonadState has a fundep m->b, so newBoard is fine
1112 ; let grown_tyvars = grow theta (mkVarSet tyvars)
1113 ; checkTc (tyVarsOfType tau `intersectsVarSet` grown_tyvars)
1114 (noClassTyVarErr cls sel_id)
1116 -- Check that for a generic method, the type of
1117 -- the method is sufficiently simple
1118 ; checkTc (dm /= GenDefMeth || validGenericMethodType tau)
1119 (badGenericMethodType op_name op_ty)
1122 op_name = idName sel_id
1123 op_ty = idType sel_id
1124 (_,theta1,tau1) = tcSplitSigmaTy op_ty
1125 (_,theta2,tau2) = tcSplitSigmaTy tau1
1126 (theta,tau) | constrained_class_methods = (theta1 ++ theta2, tau2)
1127 | otherwise = (theta1, mkPhiTy (tail theta1) tau1)
1128 -- Ugh! The function might have a type like
1129 -- op :: forall a. C a => forall b. (Eq b, Eq a) => tau2
1130 -- With -XConstrainedClassMethods, we want to allow this, even though the inner
1131 -- forall has an (Eq a) constraint. Whereas in general, each constraint
1132 -- in the context of a for-all must mention at least one quantified
1133 -- type variable. What a mess!
1136 ---------------------------------------------------------------------
1137 resultTypeMisMatch field_name con1 con2
1138 = vcat [sep [ptext SLIT("Constructors") <+> ppr con1 <+> ptext SLIT("and") <+> ppr con2,
1139 ptext SLIT("have a common field") <+> quotes (ppr field_name) <> comma],
1140 nest 2 $ ptext SLIT("but have different result types")]
1141 fieldTypeMisMatch field_name con1 con2
1142 = sep [ptext SLIT("Constructors") <+> ppr con1 <+> ptext SLIT("and") <+> ppr con2,
1143 ptext SLIT("give different types for field"), quotes (ppr field_name)]
1145 dataConCtxt con = ptext SLIT("In the definition of data constructor") <+> quotes (ppr con)
1147 classOpCtxt sel_id tau = sep [ptext SLIT("When checking the class method:"),
1148 nest 2 (ppr sel_id <+> dcolon <+> ppr tau)]
1151 = ptext SLIT("No parameters for class") <+> quotes (ppr cls)
1154 = vcat [ptext SLIT("Too many parameters for class") <+> quotes (ppr cls),
1155 parens (ptext SLIT("Use -XMultiParamTypeClasses to allow multi-parameter classes"))]
1158 = vcat [ptext SLIT("Fundeps in class") <+> quotes (ppr cls),
1159 parens (ptext SLIT("Use -XFunctionalDependencies to allow fundeps"))]
1161 noClassTyVarErr clas op
1162 = sep [ptext SLIT("The class method") <+> quotes (ppr op),
1163 ptext SLIT("mentions none of the type variables of the class") <+>
1164 ppr clas <+> hsep (map ppr (classTyVars clas))]
1166 genericMultiParamErr clas
1167 = ptext SLIT("The multi-parameter class") <+> quotes (ppr clas) <+>
1168 ptext SLIT("cannot have generic methods")
1170 badGenericMethodType op op_ty
1171 = hang (ptext SLIT("Generic method type is too complex"))
1172 4 (vcat [ppr op <+> dcolon <+> ppr op_ty,
1173 ptext SLIT("You can only use type variables, arrows, lists, and tuples")])
1176 = setSrcSpan (getLoc (head sorted_decls)) $
1177 addErr (sep [ptext SLIT("Cycle in type synonym declarations:"),
1178 nest 2 (vcat (map ppr_decl sorted_decls))])
1180 sorted_decls = sortLocated syn_decls
1181 ppr_decl (L loc decl) = ppr loc <> colon <+> ppr decl
1184 = setSrcSpan (getLoc (head sorted_decls)) $
1185 addErr (sep [ptext SLIT("Cycle in class declarations (via superclasses):"),
1186 nest 2 (vcat (map ppr_decl sorted_decls))])
1188 sorted_decls = sortLocated cls_decls
1189 ppr_decl (L loc decl) = ppr loc <> colon <+> ppr (decl { tcdSigs = [] })
1191 sortLocated :: [Located a] -> [Located a]
1192 sortLocated things = sortLe le things
1194 le (L l1 _) (L l2 _) = l1 <= l2
1196 badDataConTyCon data_con
1197 = hang (ptext SLIT("Data constructor") <+> quotes (ppr data_con) <+>
1198 ptext SLIT("returns type") <+> quotes (ppr (dataConTyCon data_con)))
1199 2 (ptext SLIT("instead of its parent type"))
1202 = vcat [ ptext SLIT("Illegal generalised algebraic data declaration for") <+> quotes (ppr tc_name)
1203 , nest 2 (parens $ ptext SLIT("Use -XGADTs to allow GADTs")) ]
1205 badStupidTheta tc_name
1206 = ptext SLIT("A data type declared in GADT style cannot have a context:") <+> quotes (ppr tc_name)
1208 newtypeConError tycon n
1209 = sep [ptext SLIT("A newtype must have exactly one constructor,"),
1210 nest 2 $ ptext SLIT("but") <+> quotes (ppr tycon) <+> ptext SLIT("has") <+> speakN n ]
1213 = sep [ptext SLIT("A newtype constructor cannot have an existential context,"),
1214 nest 2 $ ptext SLIT("but") <+> quotes (ppr con) <+> ptext SLIT("does")]
1216 newtypeStrictError con
1217 = sep [ptext SLIT("A newtype constructor cannot have a strictness annotation,"),
1218 nest 2 $ ptext SLIT("but") <+> quotes (ppr con) <+> ptext SLIT("does")]
1220 newtypePredError con
1221 = sep [ptext SLIT("A newtype constructor must have a return type of form T a1 ... an"),
1222 nest 2 $ ptext SLIT("but") <+> quotes (ppr con) <+> ptext SLIT("does not")]
1224 newtypeFieldErr con_name n_flds
1225 = sep [ptext SLIT("The constructor of a newtype must have exactly one field"),
1226 nest 2 $ ptext SLIT("but") <+> quotes (ppr con_name) <+> ptext SLIT("has") <+> speakN n_flds]
1228 badSigTyDecl tc_name
1229 = vcat [ ptext SLIT("Illegal kind signature") <+>
1230 quotes (ppr tc_name)
1231 , nest 2 (parens $ ptext SLIT("Use -XKindSignatures to allow kind signatures")) ]
1233 badFamInstDecl tc_name
1234 = vcat [ ptext SLIT("Illegal family instance for") <+>
1235 quotes (ppr tc_name)
1236 , nest 2 (parens $ ptext SLIT("Use -XTypeFamilies to allow indexed type families")) ]
1238 badGadtIdxTyDecl tc_name
1239 = vcat [ ptext SLIT("Illegal generalised algebraic data declaration for") <+>
1240 quotes (ppr tc_name)
1241 , nest 2 (parens $ ptext SLIT("Family instances can not yet use GADT declarations")) ]
1243 tooManyParmsErr tc_name
1244 = ptext SLIT("Family instance has too many parameters:") <+>
1245 quotes (ppr tc_name)
1247 tooFewParmsErr arity
1248 = ptext SLIT("Family instance has too few parameters; expected") <+>
1251 wrongNumberOfParmsErr exp_arity
1252 = ptext SLIT("Number of parameters must match family declaration; expected")
1255 badBootFamInstDeclErr =
1256 ptext SLIT("Illegal family instance in hs-boot file")
1258 wrongKindOfFamily family =
1259 ptext SLIT("Wrong category of family instance; declaration was for a") <+>
1262 kindOfFamily | isSynTyCon family = ptext SLIT("type synonym")
1263 | isAlgTyCon family = ptext SLIT("data type")
1264 | otherwise = pprPanic "wrongKindOfFamily" (ppr family)
1266 emptyConDeclsErr tycon
1267 = sep [quotes (ppr tycon) <+> ptext SLIT("has no constructors"),
1268 nest 2 $ ptext SLIT("(-XEmptyDataDecls permits this)")]