2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4 \section[RnBinds]{Renaming and dependency analysis of bindings}
6 This module does renaming and dependency analysis on value bindings in
7 the abstract syntax. It does {\em not} do cycle-checks on class or
8 type-synonym declarations; those cannot be done at this stage because
9 they may be affected by renaming (which isn't fully worked out yet).
13 rnTopBinds, rnTopMonoBinds,
14 rnMethodBinds, renameSigs, renameSigsFVs,
19 #include "HsVersions.h"
21 import {-# SOURCE #-} RnSource ( rnHsSigType, rnHsType )
24 import HsBinds ( eqHsSig, sigName, hsSigDoc )
28 import RnExpr ( rnMatch, rnGRHSs, rnPat, checkPrecMatch )
29 import RnEnv ( bindLocatedLocalsRn, lookupBndrRn,
30 lookupGlobalOccRn, lookupSigOccRn,
31 warnUnusedLocalBinds, mapFvRn, extendTyVarEnvFVRn,
33 import CmdLineOpts ( DynFlag(..) )
34 import Digraph ( stronglyConnComp, SCC(..) )
35 import Name ( OccName, Name, nameOccName, nameSrcLoc )
37 import RdrName ( RdrName, rdrNameOcc )
38 import BasicTypes ( RecFlag(..) )
39 import List ( partition )
41 import PrelNames ( isUnboundName )
44 -- ToDo: Put the annotations into the monad, so that they arrive in the proper
45 -- place and can be used when complaining.
47 The code tree received by the function @rnBinds@ contains definitions
48 in where-clauses which are all apparently mutually recursive, but which may
49 not really depend upon each other. For example, in the top level program
54 the definitions of @a@ and @y@ do not depend on each other at all.
55 Unfortunately, the typechecker cannot always check such definitions.
56 \footnote{Mycroft, A. 1984. Polymorphic type schemes and recursive
57 definitions. In Proceedings of the International Symposium on Programming,
58 Toulouse, pp. 217-39. LNCS 167. Springer Verlag.}
59 However, the typechecker usually can check definitions in which only the
60 strongly connected components have been collected into recursive bindings.
61 This is precisely what the function @rnBinds@ does.
63 ToDo: deal with case where a single monobinds binds the same variable
66 The vertag tag is a unique @Int@; the tags only need to be unique
67 within one @MonoBinds@, so that unique-Int plumbing is done explicitly
68 (heavy monad machinery not needed).
74 %************************************************************************
76 %* naming conventions *
78 %************************************************************************
80 \subsection[name-conventions]{Name conventions}
82 The basic algorithm involves walking over the tree and returning a tuple
83 containing the new tree plus its free variables. Some functions, such
84 as those walking polymorphic bindings (HsBinds) and qualifier lists in
85 list comprehensions (@Quals@), return the variables bound in local
86 environments. These are then used to calculate the free variables of the
87 expression evaluated in these environments.
89 Conventions for variable names are as follows:
92 new code is given a prime to distinguish it from the old.
95 a set of variables defined in @Exp@ is written @dvExp@
98 a set of variables free in @Exp@ is written @fvExp@
101 %************************************************************************
103 %* analysing polymorphic bindings (HsBinds, Bind, MonoBinds) *
105 %************************************************************************
107 \subsubsection[dep-HsBinds]{Polymorphic bindings}
109 Non-recursive expressions are reconstructed without any changes at top
110 level, although their component expressions may have to be altered.
111 However, non-recursive expressions are currently not expected as
112 \Haskell{} programs, and this code should not be executed.
114 Monomorphic bindings contain information that is returned in a tuple
115 (a @FlatMonoBindsInfo@) containing:
119 a unique @Int@ that serves as the ``vertex tag'' for this binding.
122 the name of a function or the names in a pattern. These are a set
123 referred to as @dvLhs@, the defined variables of the left hand side.
126 the free variables of the body. These are referred to as @fvBody@.
129 the definition's actual code. This is referred to as just @code@.
132 The function @nonRecDvFv@ returns two sets of variables. The first is
133 the set of variables defined in the set of monomorphic bindings, while the
134 second is the set of free variables in those bindings.
136 The set of variables defined in a non-recursive binding is just the
137 union of all of them, as @union@ removes duplicates. However, the
138 free variables in each successive set of cumulative bindings is the
139 union of those in the previous set plus those of the newest binding after
140 the defined variables of the previous set have been removed.
142 @rnMethodBinds@ deals only with the declarations in class and
143 instance declarations. It expects only to see @FunMonoBind@s, and
144 it expects the global environment to contain bindings for the binders
145 (which are all class operations).
147 %************************************************************************
149 \subsubsection{ Top-level bindings}
151 %************************************************************************
153 @rnTopBinds@ assumes that the environment already
154 contains bindings for the binders of this particular binding.
157 rnTopBinds :: RdrNameHsBinds -> RnMS (RenamedHsBinds, FreeVars)
159 rnTopBinds EmptyBinds = returnRn (EmptyBinds, emptyFVs)
160 rnTopBinds (MonoBind bind sigs _) = rnTopMonoBinds bind sigs
161 -- The parser doesn't produce other forms
164 rnTopMonoBinds mbinds sigs
165 = mapRn lookupBndrRn binder_rdr_names `thenRn` \ binder_names ->
167 bndr_name_set = mkNameSet binder_names
169 renameSigsFVs (okBindSig bndr_name_set) sigs `thenRn` \ (siglist, sig_fvs) ->
170 doptRn Opt_WarnMissingSigs `thenRn` \ warnMissing ->
172 type_sig_vars = [n | Sig n _ _ <- siglist]
173 un_sigd_binders | warnMissing = nameSetToList (delListFromNameSet
174 bndr_name_set type_sig_vars)
177 mapRn_ missingSigWarn un_sigd_binders `thenRn_`
179 rn_mono_binds siglist mbinds `thenRn` \ (final_binds, bind_fvs) ->
180 returnRn (final_binds, bind_fvs `plusFV` sig_fvs)
182 binder_rdr_names = collectMonoBinders mbinds
185 %************************************************************************
189 %************************************************************************
191 \subsubsection{Nested binds}
195 \item collects up the binders for this declaration group,
196 \item checks that they form a set
197 \item extends the environment to bind them to new local names
198 \item calls @rnMonoBinds@ to do the real work
202 rnBinds :: RdrNameHsBinds
203 -> (RenamedHsBinds -> RnMS (result, FreeVars))
204 -> RnMS (result, FreeVars)
206 rnBinds EmptyBinds thing_inside = thing_inside EmptyBinds
207 rnBinds (MonoBind bind sigs _) thing_inside = rnMonoBinds bind sigs thing_inside
208 -- the parser doesn't produce other forms
211 rnMonoBinds :: RdrNameMonoBinds
213 -> (RenamedHsBinds -> RnMS (result, FreeVars))
214 -> RnMS (result, FreeVars)
216 rnMonoBinds mbinds sigs thing_inside -- Non-empty monobinds
217 = -- Extract all the binders in this group,
218 -- and extend current scope, inventing new names for the new binders
219 -- This also checks that the names form a set
220 bindLocatedLocalsRn (text "a binding group")
221 mbinders_w_srclocs $ \ new_mbinders ->
223 binder_set = mkNameSet new_mbinders
225 -- Rename the signatures
226 renameSigsFVs (okBindSig binder_set) sigs `thenRn` \ (siglist, sig_fvs) ->
228 -- Report the fixity declarations in this group that
229 -- don't refer to any of the group's binders.
230 -- Then install the fixity declarations that do apply here
231 -- Notice that they scope over thing_inside too
233 fixity_sigs = [(name,sig) | FixSig sig@(FixitySig name _ _) <- siglist ]
235 extendFixityEnv fixity_sigs $
237 rn_mono_binds siglist mbinds `thenRn` \ (binds, bind_fvs) ->
239 -- Now do the "thing inside", and deal with the free-variable calculations
240 thing_inside binds `thenRn` \ (result,result_fvs) ->
242 all_fvs = result_fvs `plusFV` bind_fvs `plusFV` sig_fvs
243 unused_binders = nameSetToList (binder_set `minusNameSet` all_fvs)
245 warnUnusedLocalBinds unused_binders `thenRn_`
246 returnRn (result, delListFromNameSet all_fvs new_mbinders)
248 mbinders_w_srclocs = collectLocatedMonoBinders mbinds
252 %************************************************************************
254 \subsubsection{ MonoBinds -- the main work is done here}
256 %************************************************************************
258 @rn_mono_binds@ is used by {\em both} top-level and nested bindings.
259 It assumes that all variables bound in this group are already in scope.
260 This is done {\em either} by pass 3 (for the top-level bindings),
261 {\em or} by @rnMonoBinds@ (for the nested ones).
264 rn_mono_binds :: [RenamedSig] -- Signatures attached to this group
266 -> RnMS (RenamedHsBinds, --
267 FreeVars) -- Free variables
269 rn_mono_binds siglist mbinds
271 -- Rename the bindings, returning a MonoBindsInfo
272 -- which is a list of indivisible vertices so far as
273 -- the strongly-connected-components (SCC) analysis is concerned
274 flattenMonoBinds siglist mbinds `thenRn` \ mbinds_info ->
276 -- Do the SCC analysis
278 edges = mkEdges (mbinds_info `zip` [(0::Int)..])
279 scc_result = stronglyConnComp edges
280 final_binds = foldr (ThenBinds . reconstructCycle) EmptyBinds scc_result
282 -- Deal with bound and free-var calculation
283 rhs_fvs = plusFVs [fvs | (_,fvs,_,_) <- mbinds_info]
285 returnRn (final_binds, rhs_fvs)
288 @flattenMonoBinds@ is ever-so-slightly magical in that it sticks
289 unique ``vertex tags'' on its output; minor plumbing required.
291 Sigh --- need to pass along the signatures for the group of bindings,
292 in case any of them \fbox{\ ???\ }
295 flattenMonoBinds :: [RenamedSig] -- Signatures
297 -> RnMS [FlatMonoBindsInfo]
299 flattenMonoBinds sigs EmptyMonoBinds = returnRn []
301 flattenMonoBinds sigs (AndMonoBinds bs1 bs2)
302 = flattenMonoBinds sigs bs1 `thenRn` \ flat1 ->
303 flattenMonoBinds sigs bs2 `thenRn` \ flat2 ->
304 returnRn (flat1 ++ flat2)
306 flattenMonoBinds sigs (PatMonoBind pat grhss locn)
307 = pushSrcLocRn locn $
308 rnPat pat `thenRn` \ (pat', pat_fvs) ->
310 -- Find which things are bound in this group
312 names_bound_here = mkNameSet (collectPatBinders pat')
314 sigsForMe names_bound_here sigs `thenRn` \ sigs_for_me ->
315 rnGRHSs grhss `thenRn` \ (grhss', fvs) ->
318 fvs `plusFV` pat_fvs,
319 PatMonoBind pat' grhss' locn,
323 flattenMonoBinds sigs (FunMonoBind name inf matches locn)
324 = pushSrcLocRn locn $
325 lookupBndrRn name `thenRn` \ new_name ->
327 names_bound_here = unitNameSet new_name
329 sigsForMe names_bound_here sigs `thenRn` \ sigs_for_me ->
330 mapFvRn rnMatch matches `thenRn` \ (new_matches, fvs) ->
331 mapRn_ (checkPrecMatch inf new_name) new_matches `thenRn_`
333 [(unitNameSet new_name,
335 FunMonoBind new_name inf new_matches locn,
340 sigsForMe names_bound_here sigs
341 = foldlRn check [] (filter (sigForThisGroup names_bound_here) sigs)
343 check sigs sig = case filter (eqHsSig sig) sigs of
344 [] -> returnRn (sig:sigs)
345 other -> dupSigDeclErr sig `thenRn_`
350 @rnMethodBinds@ is used for the method bindings of a class and an instance
351 declaration. Like @rnMonoBinds@ but without dependency analysis.
353 NOTA BENE: we record each {\em binder} of a method-bind group as a free variable.
354 That's crucial when dealing with an instance decl:
356 instance Foo (T a) where
359 This might be the {\em sole} occurrence of @op@ for an imported class @Foo@,
360 and unless @op@ occurs we won't treat the type signature of @op@ in the class
361 decl for @Foo@ as a source of instance-decl gates. But we should! Indeed,
362 in many ways the @op@ in an instance decl is just like an occurrence, not
366 rnMethodBinds :: [Name] -- Names for generic type variables
368 -> RnMS (RenamedMonoBinds, FreeVars)
370 rnMethodBinds gen_tyvars EmptyMonoBinds = returnRn (EmptyMonoBinds, emptyFVs)
372 rnMethodBinds gen_tyvars (AndMonoBinds mb1 mb2)
373 = rnMethodBinds gen_tyvars mb1 `thenRn` \ (mb1', fvs1) ->
374 rnMethodBinds gen_tyvars mb2 `thenRn` \ (mb2', fvs2) ->
375 returnRn (mb1' `AndMonoBinds` mb2', fvs1 `plusFV` fvs2)
377 rnMethodBinds gen_tyvars (FunMonoBind name inf matches locn)
378 = pushSrcLocRn locn $
380 lookupGlobalOccRn name `thenRn` \ sel_name ->
381 -- We use the selector name as the binder
383 mapFvRn rn_match matches `thenRn` \ (new_matches, fvs) ->
384 mapRn_ (checkPrecMatch inf sel_name) new_matches `thenRn_`
385 returnRn (FunMonoBind sel_name inf new_matches locn, fvs `addOneFV` sel_name)
387 -- Gruesome; bring into scope the correct members of the generic type variables
388 -- See comments in RnSource.rnDecl(ClassDecl)
389 rn_match match@(Match _ (TypePatIn ty : _) _ _)
390 = extendTyVarEnvFVRn gen_tvs (rnMatch match)
392 tvs = map rdrNameOcc (extractHsTyRdrNames ty)
393 gen_tvs = [tv | tv <- gen_tyvars, nameOccName tv `elem` tvs]
395 rn_match match = rnMatch match
398 -- Can't handle method pattern-bindings which bind multiple methods.
399 rnMethodBinds gen_tyvars mbind@(PatMonoBind other_pat _ locn)
400 = pushSrcLocRn locn $
401 failWithRn (EmptyMonoBinds, emptyFVs) (methodBindErr mbind)
405 %************************************************************************
407 \subsection[reconstruct-deps]{Reconstructing dependencies}
409 %************************************************************************
411 This @MonoBinds@- and @ClassDecls@-specific code is segregated here,
412 as the two cases are similar.
415 reconstructCycle :: SCC FlatMonoBindsInfo
418 reconstructCycle (AcyclicSCC (_, _, binds, sigs))
419 = MonoBind binds sigs NonRecursive
421 reconstructCycle (CyclicSCC cycle)
422 = MonoBind this_gp_binds this_gp_sigs Recursive
424 this_gp_binds = foldr1 AndMonoBinds [binds | (_, _, binds, _) <- cycle]
425 this_gp_sigs = foldr1 (++) [sigs | (_, _, _, sigs) <- cycle]
428 %************************************************************************
430 \subsubsection{ Manipulating FlatMonoBindInfo}
432 %************************************************************************
434 During analysis a @MonoBinds@ is flattened to a @FlatMonoBindsInfo@.
435 The @RenamedMonoBinds@ is always an empty bind, a pattern binding or
436 a function binding, and has itself been dependency-analysed and
440 type FlatMonoBindsInfo
441 = (NameSet, -- Set of names defined in this vertex
442 NameSet, -- Set of names used in this vertex
444 [RenamedSig]) -- Signatures, if any, for this vertex
446 mkEdges :: [(FlatMonoBindsInfo, VertexTag)] -> [(FlatMonoBindsInfo, VertexTag, [VertexTag])]
449 = [ (info, tag, dest_vertices (nameSetToList names_used))
450 | (info@(names_defined, names_used, mbind, sigs), tag) <- flat_info
453 -- An edge (v,v') indicates that v depends on v'
454 dest_vertices src_mentions = [ target_vertex
455 | ((names_defined, _, _, _), target_vertex) <- flat_info,
456 mentioned_name <- src_mentions,
457 mentioned_name `elemNameSet` names_defined
462 %************************************************************************
464 \subsubsection[dep-Sigs]{Signatures (and user-pragmas for values)}
466 %************************************************************************
468 @renameSigs@ checks for:
470 \item more than one sig for one thing;
471 \item signatures given for things not bound here;
472 \item with suitably flaggery, that all top-level things have type signatures.
475 At the moment we don't gather free-var info from the types in
476 signatures. We'd only need this if we wanted to report unused tyvars.
479 renameSigsFVs ok_sig sigs
480 = renameSigs ok_sig sigs `thenRn` \ sigs' ->
481 returnRn (sigs', hsSigsFVs sigs')
483 renameSigs :: (RenamedSig -> Bool) -- OK-sig predicate
487 renameSigs ok_sig [] = returnRn []
489 renameSigs ok_sig sigs
490 = -- Rename the signatures
491 mapRn renameSig sigs `thenRn` \ sigs' ->
493 -- Check for (a) duplicate signatures
494 -- (b) signatures for things not in this group
496 in_scope = filter is_in_scope sigs'
497 is_in_scope sig = case sigName sig of
498 Just n -> not (isUnboundName n)
500 (goods, bads) = partition ok_sig in_scope
502 mapRn_ unknownSigErr bads `thenRn_`
505 -- We use lookupSigOccRn in the signatures, which is a little bit unsatisfactory
506 -- because this won't work for:
507 -- instance Foo T where
510 -- We'll just rename the INLINE prag to refer to whatever other 'op'
511 -- is in scope. (I'm assuming that Baz.op isn't in scope unqualified.)
512 -- Doesn't seem worth much trouble to sort this.
514 renameSig :: Sig RdrName -> RnMS (Sig Name)
515 -- ClassOpSig is renamed elsewhere.
516 renameSig (Sig v ty src_loc)
517 = pushSrcLocRn src_loc $
518 lookupSigOccRn v `thenRn` \ new_v ->
519 rnHsSigType (quotes (ppr v)) ty `thenRn` \ new_ty ->
520 returnRn (Sig new_v new_ty src_loc)
522 renameSig (SpecInstSig ty src_loc)
523 = pushSrcLocRn src_loc $
524 rnHsType (text "A SPECIALISE instance pragma") ty `thenRn` \ new_ty ->
525 returnRn (SpecInstSig new_ty src_loc)
527 renameSig (SpecSig v ty src_loc)
528 = pushSrcLocRn src_loc $
529 lookupSigOccRn v `thenRn` \ new_v ->
530 rnHsSigType (quotes (ppr v)) ty `thenRn` \ new_ty ->
531 returnRn (SpecSig new_v new_ty src_loc)
533 renameSig (FixSig (FixitySig v fix src_loc))
534 = pushSrcLocRn src_loc $
535 lookupSigOccRn v `thenRn` \ new_v ->
536 returnRn (FixSig (FixitySig new_v fix src_loc))
538 renameSig (InlineSig v p src_loc)
539 = pushSrcLocRn src_loc $
540 lookupSigOccRn v `thenRn` \ new_v ->
541 returnRn (InlineSig new_v p src_loc)
543 renameSig (NoInlineSig v p src_loc)
544 = pushSrcLocRn src_loc $
545 lookupSigOccRn v `thenRn` \ new_v ->
546 returnRn (NoInlineSig new_v p src_loc)
550 renameIE :: (RdrName -> RnMS Name) -> IE RdrName -> RnMS (IE Name, FreeVars)
551 renameIE lookup_occ_nm (IEVar v)
552 = lookup_occ_nm v `thenRn` \ new_v ->
553 returnRn (IEVar new_v, unitFV new_v)
555 renameIE lookup_occ_nm (IEThingAbs v)
556 = lookup_occ_nm v `thenRn` \ new_v ->
557 returnRn (IEThingAbs new_v, unitFV new_v)
559 renameIE lookup_occ_nm (IEThingAll v)
560 = lookup_occ_nm v `thenRn` \ new_v ->
561 returnRn (IEThingAll new_v, unitFV new_v)
563 renameIE lookup_occ_nm (IEThingWith v vs)
564 = lookup_occ_nm v `thenRn` \ new_v ->
565 mapRn lookup_occ_nm vs `thenRn` \ new_vs ->
566 returnRn (IEThingWith new_v new_vs, plusFVs [ unitFV x | x <- new_v:new_vs ])
568 renameIE lookup_occ_nm (IEModuleContents m)
569 = returnRn (IEModuleContents m, emptyFVs)
573 %************************************************************************
575 \subsection{Error messages}
577 %************************************************************************
582 addErrRn (sep [ptext SLIT("Duplicate") <+> ptext what_it_is <> colon,
585 (what_it_is, loc) = hsSigDoc sig
589 addErrRn (sep [ptext SLIT("Misplaced") <+> ptext what_it_is <> colon,
592 (what_it_is, loc) = hsSigDoc sig
595 = pushSrcLocRn (nameSrcLoc var) $
596 addWarnRn (sep [ptext SLIT("Definition but no type signature for"), quotes (ppr var)])
599 = hang (ptext SLIT("Can't handle multiple methods defined by one pattern binding"))