2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4 \section[RnSource]{Main pass of renamer}
9 rnTyClDecls, checkModDeprec,
13 #include "HsVersions.h"
15 import {-# SOURCE #-} RnExpr( rnLExpr )
18 import RdrName ( RdrName, isRdrDataCon, elemLocalRdrEnv,
19 globalRdrEnvElts, GlobalRdrElt(..), isLocalGRE )
20 import RdrHsSyn ( extractGenericPatTyVars, extractHsRhoRdrTyVars )
22 import RnTypes ( rnLHsType, rnLHsTypes, rnHsSigType, rnHsTypeFVs, rnContext )
23 import RnBinds ( rnTopBinds, rnMethodBinds, renameSigs, mkSigTvFn )
24 import RnEnv ( lookupLocalDataTcNames,
25 lookupLocatedTopBndrRn, lookupLocatedOccRn,
26 lookupOccRn, newLocalsRn,
27 bindLocatedLocalsFV, bindPatSigTyVarsFV,
28 bindTyVarsRn, extendTyVarEnvFVRn,
29 bindLocalNames, checkDupNames, mapFvRn
33 import HscTypes ( FixityEnv, FixItem(..),
34 Deprecations, Deprecs(..), DeprecTxt, plusDeprecs )
35 import Class ( FunDep )
36 import Name ( Name, nameOccName )
39 import OccName ( occEnvElts )
41 import SrcLoc ( Located(..), unLoc, noLoc )
42 import DynFlags ( DynFlag(..) )
43 import Maybes ( seqMaybe )
44 import Maybe ( isNothing, isJust )
45 import Monad ( liftM, when )
46 import BasicTypes ( Boxity(..) )
49 @rnSourceDecl@ `renames' declarations.
50 It simultaneously performs dependency analysis and precedence parsing.
51 It also does the following error checks:
54 Checks that tyvars are used properly. This includes checking
55 for undefined tyvars, and tyvars in contexts that are ambiguous.
56 (Some of this checking has now been moved to module @TcMonoType@,
57 since we don't have functional dependency information at this point.)
59 Checks that all variable occurences are defined.
61 Checks the @(..)@ etc constraints in the export list.
66 rnSrcDecls :: HsGroup RdrName -> RnM (TcGblEnv, HsGroup Name)
68 rnSrcDecls (HsGroup { hs_valds = val_decls,
69 hs_tyclds = tycl_decls,
70 hs_instds = inst_decls,
71 hs_derivds = deriv_decls,
73 hs_depds = deprec_decls,
74 hs_fords = foreign_decls,
75 hs_defds = default_decls,
76 hs_ruleds = rule_decls })
78 = do { -- Deal with deprecations (returns only the extra deprecations)
79 deprecs <- rnSrcDeprecDecls deprec_decls ;
80 updGblEnv (\gbl -> gbl { tcg_deprecs = tcg_deprecs gbl `plusDeprecs` deprecs })
83 -- Deal with top-level fixity decls
84 -- (returns the total new fixity env)
85 rn_fix_decls <- rnSrcFixityDecls fix_decls ;
86 fix_env <- rnSrcFixityDeclsEnv rn_fix_decls ;
87 updGblEnv (\gbl -> gbl { tcg_fix_env = fix_env })
90 -- Rename other declarations
91 traceRn (text "Start rnmono") ;
92 (rn_val_decls, bind_dus) <- rnTopBinds val_decls ;
93 traceRn (text "finish rnmono" <+> ppr rn_val_decls) ;
95 -- You might think that we could build proper def/use information
96 -- for type and class declarations, but they can be involved
97 -- in mutual recursion across modules, and we only do the SCC
98 -- analysis for them in the type checker.
99 -- So we content ourselves with gathering uses only; that
100 -- means we'll only report a declaration as unused if it isn't
101 -- mentioned at all. Ah well.
102 (rn_tycl_decls, src_fvs1)
103 <- mapFvRn (wrapLocFstM rnTyClDecl) tycl_decls ;
104 (rn_inst_decls, src_fvs2)
105 <- mapFvRn (wrapLocFstM rnSrcInstDecl) inst_decls ;
106 (rn_deriv_decls, src_fvs_deriv)
107 <- mapFvRn (wrapLocFstM rnSrcDerivDecl) deriv_decls ;
108 (rn_rule_decls, src_fvs3)
109 <- mapFvRn (wrapLocFstM rnHsRuleDecl) rule_decls ;
110 (rn_foreign_decls, src_fvs4)
111 <- mapFvRn (wrapLocFstM rnHsForeignDecl) foreign_decls ;
112 (rn_default_decls, src_fvs5)
113 <- mapFvRn (wrapLocFstM rnDefaultDecl) default_decls ;
116 rn_group = HsGroup { hs_valds = rn_val_decls,
117 hs_tyclds = rn_tycl_decls,
118 hs_instds = rn_inst_decls,
119 hs_derivds = rn_deriv_decls,
120 hs_fixds = rn_fix_decls,
122 hs_fords = rn_foreign_decls,
123 hs_defds = rn_default_decls,
124 hs_ruleds = rn_rule_decls } ;
126 other_fvs = plusFVs [src_fvs1, src_fvs2, src_fvs_deriv, src_fvs3,
127 src_fvs4, src_fvs5] ;
128 src_dus = bind_dus `plusDU` usesOnly other_fvs
129 -- Note: src_dus will contain *uses* for locally-defined types
130 -- and classes, but no *defs* for them. (Because rnTyClDecl
131 -- returns only the uses.) This is a little
132 -- surprising but it doesn't actually matter at all.
135 traceRn (text "finish rnSrc" <+> ppr rn_group) ;
136 traceRn (text "finish Dus" <+> ppr src_dus ) ;
137 tcg_env <- getGblEnv ;
138 return (tcg_env `addTcgDUs` src_dus, rn_group)
141 rnTyClDecls :: [LTyClDecl RdrName] -> RnM [LTyClDecl Name]
142 rnTyClDecls tycl_decls = do
143 (decls', fvs) <- mapFvRn (wrapLocFstM rnTyClDecl) tycl_decls
146 addTcgDUs :: TcGblEnv -> DefUses -> TcGblEnv
147 addTcgDUs tcg_env dus = tcg_env { tcg_dus = tcg_dus tcg_env `plusDU` dus }
151 %*********************************************************
153 Source-code fixity declarations
155 %*********************************************************
158 rnSrcFixityDecls :: [LFixitySig RdrName] -> RnM [LFixitySig Name]
159 rnSrcFixityDecls fix_decls
160 = do fix_decls <- mapM rnFixityDecl fix_decls
161 return (concat fix_decls)
163 rnFixityDecl :: LFixitySig RdrName -> RnM [LFixitySig Name]
164 rnFixityDecl (L loc (FixitySig (L nameLoc rdr_name) fixity))
165 = setSrcSpan nameLoc $
166 -- GHC extension: look up both the tycon and data con
167 -- for con-like things
168 -- If neither are in scope, report an error; otherwise
169 -- add both to the fixity env
170 do names <- lookupLocalDataTcNames rdr_name
171 return [ L loc (FixitySig (L nameLoc name) fixity)
174 rnSrcFixityDeclsEnv :: [LFixitySig Name] -> RnM FixityEnv
175 rnSrcFixityDeclsEnv fix_decls
176 = getGblEnv `thenM` \ gbl_env ->
177 foldlM rnFixityDeclEnv (tcg_fix_env gbl_env)
178 fix_decls `thenM` \ fix_env ->
179 traceRn (text "fixity env" <+> pprFixEnv fix_env) `thenM_`
182 rnFixityDeclEnv :: FixityEnv -> LFixitySig Name -> RnM FixityEnv
183 rnFixityDeclEnv fix_env (L loc (FixitySig (L nameLoc name) fixity))
184 = case lookupNameEnv fix_env name of
185 Just (FixItem _ _ loc')
186 -> do addLocErr (L nameLoc name) (dupFixityDecl loc')
189 -> return (extendNameEnv fix_env name fix_item)
190 where fix_item = FixItem (nameOccName name) fixity nameLoc
192 pprFixEnv :: FixityEnv -> SDoc
194 = pprWithCommas (\ (FixItem n f _) -> ppr f <+> ppr n)
197 dupFixityDecl loc rdr_name
198 = vcat [ptext SLIT("Multiple fixity declarations for") <+> quotes (ppr rdr_name),
199 ptext SLIT("also at ") <+> ppr loc
204 %*********************************************************
206 Source-code deprecations declarations
208 %*********************************************************
210 For deprecations, all we do is check that the names are in scope.
211 It's only imported deprecations, dealt with in RnIfaces, that we
212 gather them together.
215 rnSrcDeprecDecls :: [LDeprecDecl RdrName] -> RnM Deprecations
219 rnSrcDeprecDecls decls
220 = mappM (addLocM rn_deprec) decls `thenM` \ pairs_s ->
221 returnM (DeprecSome (mkNameEnv (concat pairs_s)))
223 rn_deprec (Deprecation rdr_name txt)
224 = lookupLocalDataTcNames rdr_name `thenM` \ names ->
225 returnM [(name, (nameOccName name, txt)) | name <- names]
227 checkModDeprec :: Maybe DeprecTxt -> Deprecations
228 -- Check for a module deprecation; done once at top level
229 checkModDeprec Nothing = NoDeprecs
230 checkModDeprec (Just txt) = DeprecAll txt
233 %*********************************************************
235 \subsection{Source code declarations}
237 %*********************************************************
240 rnDefaultDecl (DefaultDecl tys)
241 = mapFvRn (rnHsTypeFVs doc_str) tys `thenM` \ (tys', fvs) ->
242 returnM (DefaultDecl tys', fvs)
244 doc_str = text "In a `default' declaration"
247 %*********************************************************
249 \subsection{Foreign declarations}
251 %*********************************************************
254 rnHsForeignDecl (ForeignImport name ty spec)
255 = lookupLocatedTopBndrRn name `thenM` \ name' ->
256 rnHsTypeFVs (fo_decl_msg name) ty `thenM` \ (ty', fvs) ->
257 returnM (ForeignImport name' ty' spec, fvs)
259 rnHsForeignDecl (ForeignExport name ty spec)
260 = lookupLocatedOccRn name `thenM` \ name' ->
261 rnHsTypeFVs (fo_decl_msg name) ty `thenM` \ (ty', fvs) ->
262 returnM (ForeignExport name' ty' spec, fvs )
263 -- NB: a foreign export is an *occurrence site* for name, so
264 -- we add it to the free-variable list. It might, for example,
265 -- be imported from another module
267 fo_decl_msg name = ptext SLIT("In the foreign declaration for") <+> ppr name
271 %*********************************************************
273 \subsection{Instance declarations}
275 %*********************************************************
278 rnSrcInstDecl (InstDecl inst_ty mbinds uprags ats)
279 -- Used for both source and interface file decls
280 = rnHsSigType (text "an instance decl") inst_ty `thenM` \ inst_ty' ->
282 -- Rename the associated types
283 -- The typechecker (not the renamer) checks that all
284 -- the declarations are for the right class
286 at_doc = text "In the associated types of an instance declaration"
287 at_names = map (head . tyClDeclNames . unLoc) ats
289 checkDupNames at_doc at_names `thenM_`
290 rnATInsts ats `thenM` \ (ats', at_fvs) ->
292 -- Rename the bindings
293 -- The typechecker (not the renamer) checks that all
294 -- the bindings are for the right class
296 meth_doc = text "In the bindings in an instance declaration"
297 meth_names = collectHsBindLocatedBinders mbinds
298 (inst_tyvars, _, cls,_) = splitHsInstDeclTy (unLoc inst_ty')
300 checkDupNames meth_doc meth_names `thenM_`
301 extendTyVarEnvForMethodBinds inst_tyvars (
302 -- (Slightly strangely) the forall-d tyvars scope over
303 -- the method bindings too
304 rnMethodBinds cls (\n->[]) -- No scoped tyvars
306 ) `thenM` \ (mbinds', meth_fvs) ->
307 -- Rename the prags and signatures.
308 -- Note that the type variables are not in scope here,
309 -- so that instance Eq a => Eq (T a) where
310 -- {-# SPECIALISE instance Eq a => Eq (T [a]) #-}
313 -- But the (unqualified) method names are in scope
315 binders = collectHsBindBinders mbinds'
316 ok_sig = okInstDclSig (mkNameSet binders)
318 bindLocalNames binders (renameSigs ok_sig uprags) `thenM` \ uprags' ->
320 returnM (InstDecl inst_ty' mbinds' uprags' ats',
321 meth_fvs `plusFV` at_fvs
322 `plusFV` hsSigsFVs uprags'
323 `plusFV` extractHsTyNames inst_ty')
324 -- We return the renamed associated data type declarations so
325 -- that they can be entered into the list of type declarations
326 -- for the binding group, but we also keep a copy in the instance.
327 -- The latter is needed for well-formedness checks in the type
328 -- checker (eg, to ensure that all ATs of the instance actually
329 -- receive a declaration).
330 -- NB: Even the copies in the instance declaration carry copies of
331 -- the instance context after renaming. This is a bit
332 -- strange, but should not matter (and it would be more work
333 -- to remove the context).
336 Renaming of the associated types in instances.
338 * We raise an error if we encounter a kind signature in an instance.
341 rnATInsts :: [LTyClDecl RdrName] -> RnM ([LTyClDecl Name], FreeVars)
343 mapFvRn (wrapLocFstM rnATInst) atDecls
345 rnATInst tydecl@TyFunction {} =
349 rnATInst tydecl@TySynonym {} = rnTyClDecl tydecl
350 rnATInst tydecl@TyData {} =
352 checkM (not . isKindSigDecl $ tydecl) $ addErr noKindSig
355 panic "RnSource.rnATInsts: not a type declaration"
357 noKindSig = text "Instances cannot have kind signatures"
360 For the method bindings in class and instance decls, we extend the
361 type variable environment iff -fglasgow-exts
364 extendTyVarEnvForMethodBinds tyvars thing_inside
365 = doptM Opt_GlasgowExts `thenM` \ opt_GlasgowExts ->
366 if opt_GlasgowExts then
367 extendTyVarEnvFVRn (map hsLTyVarName tyvars) thing_inside
372 %*********************************************************
374 \subsection{Stand-alone deriving declarations}
376 %*********************************************************
379 rnSrcDerivDecl :: DerivDecl RdrName -> RnM (DerivDecl Name, FreeVars)
380 rnSrcDerivDecl (DerivDecl ty n)
381 = do ty' <- rnLHsType (text "a deriving decl") ty
382 n' <- lookupLocatedOccRn n
383 let fvs = extractHsTyNames ty' `addOneFV` unLoc n'
384 return (DerivDecl ty' n', fvs)
387 %*********************************************************
391 %*********************************************************
394 rnHsRuleDecl (HsRule rule_name act vars lhs fv_lhs rhs fv_rhs)
395 = bindPatSigTyVarsFV (collectRuleBndrSigTys vars) $
397 bindLocatedLocalsFV doc (map get_var vars) $ \ ids ->
398 mapFvRn rn_var (vars `zip` ids) `thenM` \ (vars', fv_vars) ->
400 rnLExpr lhs `thenM` \ (lhs', fv_lhs') ->
401 rnLExpr rhs `thenM` \ (rhs', fv_rhs') ->
403 checkValidRule rule_name ids lhs' fv_lhs' `thenM_`
405 returnM (HsRule rule_name act vars' lhs' fv_lhs' rhs' fv_rhs',
406 fv_vars `plusFV` fv_lhs' `plusFV` fv_rhs')
408 doc = text "In the transformation rule" <+> ftext rule_name
410 get_var (RuleBndr v) = v
411 get_var (RuleBndrSig v _) = v
413 rn_var (RuleBndr (L loc v), id)
414 = returnM (RuleBndr (L loc id), emptyFVs)
415 rn_var (RuleBndrSig (L loc v) t, id)
416 = rnHsTypeFVs doc t `thenM` \ (t', fvs) ->
417 returnM (RuleBndrSig (L loc id) t', fvs)
420 = sep [ptext SLIT("Rule") <+> doubleQuotes (ftext name) <> colon,
421 ptext SLIT("Forall'd variable") <+> quotes (ppr var) <+>
422 ptext SLIT("does not appear on left hand side")]
425 Note [Rule LHS validity checking]
426 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
427 Check the shape of a transformation rule LHS. Currently we only allow
428 LHSs of the form @(f e1 .. en)@, where @f@ is not one of the
429 @forall@'d variables.
431 We used restrict the form of the 'ei' to prevent you writing rules
432 with LHSs with a complicated desugaring (and hence unlikely to match);
433 (e.g. a case expression is not allowed: too elaborate.)
435 But there are legitimate non-trivial args ei, like sections and
436 lambdas. So it seems simmpler not to check at all, and that is why
437 check_e is commented out.
440 checkValidRule rule_name ids lhs' fv_lhs'
441 = do { -- Check for the form of the LHS
442 case (validRuleLhs ids lhs') of
444 Just bad -> failWithTc (badRuleLhsErr rule_name lhs' bad)
446 -- Check that LHS vars are all bound
447 ; let bad_vars = [var | var <- ids, not (var `elemNameSet` fv_lhs')]
448 ; mappM (addErr . badRuleVar rule_name) bad_vars }
450 validRuleLhs :: [Name] -> LHsExpr Name -> Maybe (HsExpr Name)
452 -- Just e => Not ok, and e is the offending expression
453 validRuleLhs foralls lhs
456 checkl (L loc e) = check e
458 check (OpApp e1 op _ e2) = checkl op `seqMaybe` checkl_e e1 `seqMaybe` checkl_e e2
459 check (HsApp e1 e2) = checkl e1 `seqMaybe` checkl_e e2
460 check (HsVar v) | v `notElem` foralls = Nothing
461 check other = Just other -- Failure
464 checkl_e (L loc e) = Nothing -- Was (check_e e); see Note [Rule LHS validity checking]
466 {- Commented out; see Note [Rule LHS validity checking] above
467 check_e (HsVar v) = Nothing
468 check_e (HsPar e) = checkl_e e
469 check_e (HsLit e) = Nothing
470 check_e (HsOverLit e) = Nothing
472 check_e (OpApp e1 op _ e2) = checkl_e e1 `seqMaybe` checkl_e op `seqMaybe` checkl_e e2
473 check_e (HsApp e1 e2) = checkl_e e1 `seqMaybe` checkl_e e2
474 check_e (NegApp e _) = checkl_e e
475 check_e (ExplicitList _ es) = checkl_es es
476 check_e (ExplicitTuple es _) = checkl_es es
477 check_e other = Just other -- Fails
479 checkl_es es = foldr (seqMaybe . checkl_e) Nothing es
482 badRuleLhsErr name lhs bad_e
483 = sep [ptext SLIT("Rule") <+> ftext name <> colon,
484 nest 4 (vcat [ptext SLIT("Illegal expression:") <+> ppr bad_e,
485 ptext SLIT("in left-hand side:") <+> ppr lhs])]
487 ptext SLIT("LHS must be of form (f e1 .. en) where f is not forall'd")
491 %*********************************************************
493 \subsection{Type, class and iface sig declarations}
495 %*********************************************************
497 @rnTyDecl@ uses the `global name function' to create a new type
498 declaration in which local names have been replaced by their original
499 names, reporting any unknown names.
501 Renaming type variables is a pain. Because they now contain uniques,
502 it is necessary to pass in an association list which maps a parsed
503 tyvar to its @Name@ representation.
504 In some cases (type signatures of values),
505 it is even necessary to go over the type first
506 in order to get the set of tyvars used by it, make an assoc list,
507 and then go over it again to rename the tyvars!
508 However, we can also do some scoping checks at the same time.
511 rnTyClDecl (ForeignType {tcdLName = name, tcdFoType = fo_type, tcdExtName = ext_name})
512 = lookupLocatedTopBndrRn name `thenM` \ name' ->
513 returnM (ForeignType {tcdLName = name', tcdFoType = fo_type, tcdExtName = ext_name},
516 rnTyClDecl (tydecl@TyData {tcdND = new_or_data, tcdCtxt = context,
517 tcdLName = tycon, tcdTyVars = tyvars,
518 tcdTyPats = typatsMaybe, tcdCons = condecls,
519 tcdKindSig = sig, tcdDerivs = derivs})
520 | isKindSigDecl tydecl -- kind signature of indexed type
521 = rnTySig tydecl bindTyVarsRn
522 | is_vanilla -- Normal Haskell data type decl
523 = ASSERT( isNothing sig ) -- In normal H98 form, kind signature on the
524 -- data type is syntactically illegal
525 bindTyVarsRn data_doc tyvars $ \ tyvars' ->
526 do { tycon' <- if isIdxTyDecl tydecl
527 then lookupLocatedOccRn tycon -- may be imported family
528 else lookupLocatedTopBndrRn tycon
529 ; context' <- rnContext data_doc context
530 ; typats' <- rnTyPats data_doc typatsMaybe
531 ; (derivs', deriv_fvs) <- rn_derivs derivs
532 ; checkDupNames data_doc con_names
533 ; condecls' <- rnConDecls (unLoc tycon') condecls
534 ; returnM (TyData {tcdND = new_or_data, tcdCtxt = context',
535 tcdLName = tycon', tcdTyVars = tyvars',
536 tcdTyPats = typats', tcdKindSig = Nothing,
537 tcdCons = condecls', tcdDerivs = derivs'},
538 delFVs (map hsLTyVarName tyvars') $
539 extractHsCtxtTyNames context' `plusFV`
540 plusFVs (map conDeclFVs condecls') `plusFV`
542 (if isIdxTyDecl tydecl
543 then unitFV (unLoc tycon') -- type instance => use
548 = ASSERT( none typatsMaybe ) -- GADTs cannot have type patterns for now
549 do { tycon' <- if isIdxTyDecl tydecl
550 then lookupLocatedOccRn tycon -- may be imported family
551 else lookupLocatedTopBndrRn tycon
552 ; checkTc (null (unLoc context)) (badGadtStupidTheta tycon)
553 ; tyvars' <- bindTyVarsRn data_doc tyvars
554 (\ tyvars' -> return tyvars')
555 -- For GADTs, the type variables in the declaration
556 -- do not scope over the constructor signatures
557 -- data T a where { T1 :: forall b. b-> b }
558 ; (derivs', deriv_fvs) <- rn_derivs derivs
559 ; checkDupNames data_doc con_names
560 ; condecls' <- rnConDecls (unLoc tycon') condecls
561 ; returnM (TyData {tcdND = new_or_data, tcdCtxt = noLoc [],
562 tcdLName = tycon', tcdTyVars = tyvars',
563 tcdTyPats = Nothing, tcdKindSig = sig,
564 tcdCons = condecls', tcdDerivs = derivs'},
565 plusFVs (map conDeclFVs condecls') `plusFV`
567 (if isIdxTyDecl tydecl
568 then unitFV (unLoc tycon') -- type instance => use
572 is_vanilla = case condecls of -- Yuk
574 L _ (ConDecl { con_res = ResTyH98 }) : _ -> True
578 none (Just []) = True
581 data_doc = text "In the data type declaration for" <+> quotes (ppr tycon)
582 con_names = map con_names_helper condecls
584 con_names_helper (L _ c) = con_name c
586 rn_derivs Nothing = returnM (Nothing, emptyFVs)
587 rn_derivs (Just ds) = rnLHsTypes data_doc ds `thenM` \ ds' ->
588 returnM (Just ds', extractHsTyNames_s ds')
590 rnTyClDecl (tydecl@TyFunction {}) =
591 rnTySig tydecl bindTyVarsRn
593 rnTyClDecl tydecl@(TySynonym {tcdLName = name, tcdTyVars = tyvars,
594 tcdTyPats = typatsMaybe, tcdSynRhs = ty})
595 = bindTyVarsRn syn_doc tyvars $ \ tyvars' ->
596 do { name' <- if isIdxTyDecl tydecl
597 then lookupLocatedOccRn name -- may be imported family
598 else lookupLocatedTopBndrRn name
599 ; typats' <- rnTyPats syn_doc typatsMaybe
600 ; (ty', fvs) <- rnHsTypeFVs syn_doc ty
601 ; returnM (TySynonym {tcdLName = name', tcdTyVars = tyvars',
602 tcdTyPats = typats', tcdSynRhs = ty'},
603 delFVs (map hsLTyVarName tyvars') $
605 (if isIdxTyDecl tydecl
606 then unitFV (unLoc name') -- type instance => use
610 syn_doc = text "In the declaration for type synonym" <+> quotes (ppr name)
612 rnTyClDecl (ClassDecl {tcdCtxt = context, tcdLName = cname,
613 tcdTyVars = tyvars, tcdFDs = fds, tcdSigs = sigs,
614 tcdMeths = mbinds, tcdATs = ats})
615 = lookupLocatedTopBndrRn cname `thenM` \ cname' ->
617 -- Tyvars scope over superclass context and method signatures
618 bindTyVarsRn cls_doc tyvars ( \ tyvars' ->
619 rnContext cls_doc context `thenM` \ context' ->
620 rnFds cls_doc fds `thenM` \ fds' ->
621 rnATs ats `thenM` \ (ats', ats_fvs) ->
622 renameSigs okClsDclSig sigs `thenM` \ sigs' ->
623 returnM (tyvars', context', fds', (ats', ats_fvs), sigs')
624 ) `thenM` \ (tyvars', context', fds', (ats', ats_fvs), sigs') ->
626 -- Check for duplicates among the associated types
628 at_rdr_names_w_locs = [tcdLName ty | L _ ty <- ats]
630 checkDupNames at_doc at_rdr_names_w_locs `thenM_`
632 -- Check the signatures
633 -- First process the class op sigs (op_sigs), then the fixity sigs (non_op_sigs).
635 sig_rdr_names_w_locs = [op | L _ (TypeSig op _) <- sigs]
637 checkDupNames sig_doc sig_rdr_names_w_locs `thenM_`
638 -- Typechecker is responsible for checking that we only
639 -- give default-method bindings for things in this class.
640 -- The renamer *could* check this for class decls, but can't
641 -- for instance decls.
643 -- The newLocals call is tiresome: given a generic class decl
646 -- op {| x+y |} (Inl a) = ...
647 -- op {| x+y |} (Inr b) = ...
648 -- op {| a*b |} (a*b) = ...
649 -- we want to name both "x" tyvars with the same unique, so that they are
650 -- easy to group together in the typechecker.
651 extendTyVarEnvForMethodBinds tyvars' (
652 getLocalRdrEnv `thenM` \ name_env ->
654 meth_rdr_names_w_locs = collectHsBindLocatedBinders mbinds
655 gen_rdr_tyvars_w_locs =
656 [ tv | tv <- extractGenericPatTyVars mbinds,
657 not (unLoc tv `elemLocalRdrEnv` name_env) ]
659 checkDupNames meth_doc meth_rdr_names_w_locs `thenM_`
660 newLocalsRn gen_rdr_tyvars_w_locs `thenM` \ gen_tyvars ->
661 rnMethodBinds (unLoc cname') (mkSigTvFn sigs') gen_tyvars mbinds
662 ) `thenM` \ (mbinds', meth_fvs) ->
664 returnM (ClassDecl { tcdCtxt = context', tcdLName = cname',
665 tcdTyVars = tyvars', tcdFDs = fds', tcdSigs = sigs',
666 tcdMeths = mbinds', tcdATs = ats'},
667 delFVs (map hsLTyVarName tyvars') $
668 extractHsCtxtTyNames context' `plusFV`
669 plusFVs (map extractFunDepNames (map unLoc fds')) `plusFV`
670 hsSigsFVs sigs' `plusFV`
674 meth_doc = text "In the default-methods for class" <+> ppr cname
675 cls_doc = text "In the declaration for class" <+> ppr cname
676 sig_doc = text "In the signatures for class" <+> ppr cname
677 at_doc = text "In the associated types for class" <+> ppr cname
679 badGadtStupidTheta tycon
680 = vcat [ptext SLIT("No context is allowed on a GADT-style data declaration"),
681 ptext SLIT("(You can put a context on each contructor, though.)")]
684 %*********************************************************
686 \subsection{Support code for type/data declarations}
688 %*********************************************************
691 -- Although, we are processing type patterns here, all type variables will
692 -- already be in scope (they are the same as in the 'tcdTyVars' field of the
693 -- type declaration to which these patterns belong)
695 rnTyPats :: SDoc -> Maybe [LHsType RdrName] -> RnM (Maybe [LHsType Name])
696 rnTyPats _ Nothing = return Nothing
697 rnTyPats doc (Just typats) = liftM Just $ rnLHsTypes doc typats
699 rnConDecls :: Name -> [LConDecl RdrName] -> RnM [LConDecl Name]
700 rnConDecls tycon condecls
701 = mappM (wrapLocM rnConDecl) condecls
703 rnConDecl :: ConDecl RdrName -> RnM (ConDecl Name)
704 rnConDecl (ConDecl name expl tvs cxt details res_ty)
705 = do { addLocM checkConName name
707 ; new_name <- lookupLocatedTopBndrRn name
708 ; name_env <- getLocalRdrEnv
710 -- For H98 syntax, the tvs are the existential ones
711 -- For GADT syntax, the tvs are all the quantified tyvars
712 -- Hence the 'filter' in the ResTyH98 case only
713 ; let not_in_scope = not . (`elemLocalRdrEnv` name_env) . unLoc
714 arg_tys = hsConArgs details
715 implicit_tvs = case res_ty of
716 ResTyH98 -> filter not_in_scope $
718 ResTyGADT ty -> get_rdr_tvs (ty : arg_tys)
721 Implicit -> userHsTyVarBndrs implicit_tvs
723 ; bindTyVarsRn doc tvs' $ \new_tyvars -> do
724 { new_context <- rnContext doc cxt
725 ; new_details <- rnConDetails doc details
726 ; (new_details', new_res_ty) <- rnConResult doc new_details res_ty
727 ; return (ConDecl new_name expl new_tyvars new_context new_details' new_res_ty) }}
729 doc = text "In the definition of data constructor" <+> quotes (ppr name)
730 get_rdr_tvs tys = extractHsRhoRdrTyVars cxt (noLoc (HsTupleTy Boxed tys))
732 rnConResult _ details ResTyH98 = return (details, ResTyH98)
734 rnConResult doc details (ResTyGADT ty) = do
735 ty' <- rnHsSigType doc ty
736 let (arg_tys, res_ty) = splitHsFunType ty'
737 -- We can split it up, now the renamer has dealt with fixities
739 PrefixCon _xs -> ASSERT( null _xs ) return (PrefixCon arg_tys, ResTyGADT res_ty)
740 RecCon fields -> return (details, ResTyGADT ty')
741 InfixCon {} -> panic "rnConResult"
743 rnConDetails doc (PrefixCon tys)
744 = mappM (rnLHsType doc) tys `thenM` \ new_tys ->
745 returnM (PrefixCon new_tys)
747 rnConDetails doc (InfixCon ty1 ty2)
748 = rnLHsType doc ty1 `thenM` \ new_ty1 ->
749 rnLHsType doc ty2 `thenM` \ new_ty2 ->
750 returnM (InfixCon new_ty1 new_ty2)
752 rnConDetails doc (RecCon fields)
753 = checkDupNames doc field_names `thenM_`
754 mappM (rnField doc) fields `thenM` \ new_fields ->
755 returnM (RecCon new_fields)
757 field_names = [fld | (fld, _) <- fields]
759 rnField doc (name, ty)
760 = lookupLocatedTopBndrRn name `thenM` \ new_name ->
761 rnLHsType doc ty `thenM` \ new_ty ->
762 returnM (new_name, new_ty)
764 -- Rename kind signatures (signatures of indexed data types/newtypes and
765 -- signatures of type functions)
767 -- * This function is parametrised by the routine handling the index
768 -- variables. On the toplevel, these are defining occurences, whereas they
769 -- are usage occurences for associated types.
771 rnTySig :: TyClDecl RdrName
772 -> (SDoc -> [LHsTyVarBndr RdrName] ->
773 ([LHsTyVarBndr Name] -> RnM (TyClDecl Name, FreeVars)) ->
774 RnM (TyClDecl Name, FreeVars))
775 -> RnM (TyClDecl Name, FreeVars)
777 rnTySig (tydecl@TyData {tcdCtxt = context, tcdLName = tycon,
778 tcdTyVars = tyvars, tcdTyPats = mb_typats,
779 tcdCons = condecls, tcdKindSig = sig,
782 ASSERT( null condecls ) -- won't have constructors
783 ASSERT( isNothing mb_typats ) -- won't have type patterns
784 ASSERT( isNothing derivs ) -- won't have deriving
785 ASSERT( isJust sig ) -- will have kind signature
786 do { checkM (not . null $ tyvars) $ addErr needOneIdx -- #indexes >= 1
787 ; bindIdxVars (ksig_doc tycon) tyvars $ \tyvars' -> do {
788 ; tycon' <- lookupLocatedTopBndrRn tycon
789 ; context' <- rnContext (ksig_doc tycon) context
790 ; returnM (TyData {tcdND = tcdND tydecl, tcdCtxt = context',
791 tcdLName = tycon', tcdTyVars = tyvars',
792 tcdTyPats = Nothing, tcdKindSig = sig,
793 tcdCons = [], tcdDerivs = Nothing},
794 delFVs (map hsLTyVarName tyvars') $
795 extractHsCtxtTyNames context')
799 rnTySig (tydecl@TyFunction {tcdLName = tycon, tcdTyVars = tyvars,
802 do { checkM (not . null $ tyvars) $ addErr needOneIdx -- #indexes >= 1
803 ; bindIdxVars (ksig_doc tycon) tyvars $ \tyvars' -> do {
804 ; tycon' <- lookupLocatedTopBndrRn tycon
805 ; returnM (TyFunction {tcdLName = tycon', tcdTyVars = tyvars',
806 tcdIso = tcdIso tydecl, tcdKind = sig},
810 ksig_doc tycon = text "In the kind signature for" <+> quotes (ppr tycon)
811 needOneIdx = text "Kind signature requires at least one type index"
813 -- Rename associated type declarations (in classes)
815 -- * This can be kind signatures and (default) type function equations.
817 rnATs :: [LTyClDecl RdrName] -> RnM ([LTyClDecl Name], FreeVars)
818 rnATs ats = mapFvRn (wrapLocFstM rn_at) ats
820 rn_at (tydecl@TyData {}) = rnTySig tydecl lookupIdxVars
821 rn_at (tydecl@TyFunction {}) = rnTySig tydecl lookupIdxVars
822 rn_at (tydecl@TySynonym {}) =
824 checkM (isNothing (tcdTyPats tydecl)) $ addErr noPatterns
826 rn_at _ = panic "RnSource.rnATs: invalid TyClDecl"
828 lookupIdxVars _ tyvars cont =
829 do { checkForDups tyvars;
830 ; tyvars' <- mappM lookupIdxVar tyvars
833 -- Type index variables must be class parameters, which are the only
834 -- type variables in scope at this point.
835 lookupIdxVar (L l tyvar) =
837 name' <- lookupOccRn (hsTyVarName tyvar)
838 return $ L l (replaceTyVarName tyvar name')
840 -- Type variable may only occur once.
842 checkForDups [] = return ()
843 checkForDups (L loc tv:ltvs) =
844 do { setSrcSpan loc $
845 when (hsTyVarName tv `ltvElem` ltvs) $
846 addErr (repeatedTyVar tv)
850 rdrName `ltvElem` [] = False
851 rdrName `ltvElem` (L _ tv:ltvs)
852 | rdrName == hsTyVarName tv = True
853 | otherwise = rdrName `ltvElem` ltvs
855 noPatterns = text "Default definition for an associated synonym cannot have"
856 <+> text "type pattern"
858 repeatedTyVar tv = ptext SLIT("Illegal repeated type variable") <+>
861 -- This data decl will parse OK
863 -- treating "a" as the constructor.
864 -- It is really hard to make the parser spot this malformation.
865 -- So the renamer has to check that the constructor is legal
867 -- We can get an operator as the constructor, even in the prefix form:
868 -- data T = :% Int Int
869 -- from interface files, which always print in prefix form
871 checkConName name = checkErr (isRdrDataCon name) (badDataCon name)
874 = hsep [ptext SLIT("Illegal data constructor name"), quotes (ppr name)]
878 %*********************************************************
880 \subsection{Support code to rename types}
882 %*********************************************************
885 rnFds :: SDoc -> [Located (FunDep RdrName)] -> RnM [Located (FunDep Name)]
888 = mappM (wrapLocM rn_fds) fds
891 = rnHsTyVars doc tys1 `thenM` \ tys1' ->
892 rnHsTyVars doc tys2 `thenM` \ tys2' ->
893 returnM (tys1', tys2')
895 rnHsTyVars doc tvs = mappM (rnHsTyvar doc) tvs
896 rnHsTyvar doc tyvar = lookupOccRn tyvar
900 %*********************************************************
904 %*********************************************************
910 h = ...$(thing "f")...
912 The splice can expand into literally anything, so when we do dependency
913 analysis we must assume that it might mention 'f'. So we simply treat
914 all locally-defined names as mentioned by any splice. This is terribly
915 brutal, but I don't see what else to do. For example, it'll mean
916 that every locally-defined thing will appear to be used, so no unused-binding
917 warnings. But if we miss the dependency, then we might typecheck 'h' before 'f',
918 and that will crash the type checker because 'f' isn't in scope.
920 Currently, I'm not treating a splice as also mentioning every import,
921 which is a bit inconsistent -- but there are a lot of them. We might
922 thereby get some bogus unused-import warnings, but we won't crash the
923 type checker. Not very satisfactory really.
926 rnSplice :: HsSplice RdrName -> RnM (HsSplice Name, FreeVars)
927 rnSplice (HsSplice n expr)
928 = do { checkTH expr "splice"
930 ; [n'] <- newLocalsRn [L loc n]
931 ; (expr', fvs) <- rnLExpr expr
933 -- Ugh! See Note [Splices] above
934 ; lcl_rdr <- getLocalRdrEnv
935 ; gbl_rdr <- getGlobalRdrEnv
936 ; let gbl_names = mkNameSet [gre_name gre | gre <- globalRdrEnvElts gbl_rdr,
938 lcl_names = mkNameSet (occEnvElts lcl_rdr)
940 ; return (HsSplice n' expr', fvs `plusFV` lcl_names `plusFV` gbl_names) }
943 checkTH e what = returnM () -- OK
945 checkTH e what -- Raise an error in a stage-1 compiler
946 = addErr (vcat [ptext SLIT("Template Haskell") <+> text what <+>
947 ptext SLIT("illegal in a stage-1 compiler"),