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,
19 #include "HsVersions.h"
21 import {-# SOURCE #-} RnSource ( rnHsSigType )
24 import HsBinds ( sigsForMe )
28 import RnExpr ( rnMatch, rnGRHSs, rnPat, checkPrecMatch )
29 import RnEnv ( bindLocatedLocalsRn, lookupBndrRn, lookupOccRn, lookupGlobalOccRn,
30 isUnboundName, warnUnusedLocalBinds,
31 FreeVars, emptyFVs, plusFV, plusFVs, unitFV,
34 import CmdLineOpts ( opt_WarnMissingSigs )
35 import Digraph ( stronglyConnComp, SCC(..) )
36 import Name ( OccName, Name, nameOccName )
38 import RdrName ( RdrName, rdrNameOcc )
39 import BasicTypes ( RecFlag(..), TopLevelFlag(..) )
40 import Util ( thenCmp, removeDups )
41 import List ( partition )
42 import ListSetOps ( minusList )
43 import Bag ( bagToList )
44 import FiniteMap ( emptyFM, addListToFM, lookupFM )
45 import Maybe ( isJust )
49 -- ToDo: Put the annotations into the monad, so that they arrive in the proper
50 -- place and can be used when complaining.
52 The code tree received by the function @rnBinds@ contains definitions
53 in where-clauses which are all apparently mutually recursive, but which may
54 not really depend upon each other. For example, in the top level program
59 the definitions of @a@ and @y@ do not depend on each other at all.
60 Unfortunately, the typechecker cannot always check such definitions.
61 \footnote{Mycroft, A. 1984. Polymorphic type schemes and recursive
62 definitions. In Proceedings of the International Symposium on Programming,
63 Toulouse, pp. 217-39. LNCS 167. Springer Verlag.}
64 However, the typechecker usually can check definitions in which only the
65 strongly connected components have been collected into recursive bindings.
66 This is precisely what the function @rnBinds@ does.
68 ToDo: deal with case where a single monobinds binds the same variable
71 The vertag tag is a unique @Int@; the tags only need to be unique
72 within one @MonoBinds@, so that unique-Int plumbing is done explicitly
73 (heavy monad machinery not needed).
77 type Cycle = [VertexTag]
78 type Edge = (VertexTag, VertexTag)
81 %************************************************************************
83 %* naming conventions *
85 %************************************************************************
87 \subsection[name-conventions]{Name conventions}
89 The basic algorithm involves walking over the tree and returning a tuple
90 containing the new tree plus its free variables. Some functions, such
91 as those walking polymorphic bindings (HsBinds) and qualifier lists in
92 list comprehensions (@Quals@), return the variables bound in local
93 environments. These are then used to calculate the free variables of the
94 expression evaluated in these environments.
96 Conventions for variable names are as follows:
99 new code is given a prime to distinguish it from the old.
102 a set of variables defined in @Exp@ is written @dvExp@
105 a set of variables free in @Exp@ is written @fvExp@
108 %************************************************************************
110 %* analysing polymorphic bindings (HsBinds, Bind, MonoBinds) *
112 %************************************************************************
114 \subsubsection[dep-HsBinds]{Polymorphic bindings}
116 Non-recursive expressions are reconstructed without any changes at top
117 level, although their component expressions may have to be altered.
118 However, non-recursive expressions are currently not expected as
119 \Haskell{} programs, and this code should not be executed.
121 Monomorphic bindings contain information that is returned in a tuple
122 (a @FlatMonoBindsInfo@) containing:
126 a unique @Int@ that serves as the ``vertex tag'' for this binding.
129 the name of a function or the names in a pattern. These are a set
130 referred to as @dvLhs@, the defined variables of the left hand side.
133 the free variables of the body. These are referred to as @fvBody@.
136 the definition's actual code. This is referred to as just @code@.
139 The function @nonRecDvFv@ returns two sets of variables. The first is
140 the set of variables defined in the set of monomorphic bindings, while the
141 second is the set of free variables in those bindings.
143 The set of variables defined in a non-recursive binding is just the
144 union of all of them, as @union@ removes duplicates. However, the
145 free variables in each successive set of cumulative bindings is the
146 union of those in the previous set plus those of the newest binding after
147 the defined variables of the previous set have been removed.
149 @rnMethodBinds@ deals only with the declarations in class and
150 instance declarations. It expects only to see @FunMonoBind@s, and
151 it expects the global environment to contain bindings for the binders
152 (which are all class operations).
154 %************************************************************************
156 %* Top-level bindings
158 %************************************************************************
160 @rnTopBinds@ assumes that the environment already
161 contains bindings for the binders of this particular binding.
164 rnTopBinds :: RdrNameHsBinds -> RnMS s (RenamedHsBinds, FreeVars)
166 rnTopBinds EmptyBinds = returnRn (EmptyBinds, emptyFVs)
167 rnTopBinds (MonoBind bind sigs _) = rnTopMonoBinds bind sigs
168 -- The parser doesn't produce other forms
171 rnTopMonoBinds EmptyMonoBinds sigs
172 = returnRn (EmptyBinds, emptyFVs)
174 rnTopMonoBinds mbinds sigs
175 = mapRn lookupBndrRn binder_rdr_names `thenRn` \ binder_names ->
177 binder_set = mkNameSet binder_names
179 binder_occ_fm = addListToFM emptyFM (map (\ x -> (nameOccName x,x)) binder_names)
181 -- the names appearing in the sigs have to be bound by
182 -- this group's binders.
183 lookup_occ_rn_sig rdr_name =
184 case lookupFM binder_occ_fm (rdrNameOcc rdr_name) of
185 Nothing -> failUnboundNameErrRn rdr_name
188 renameSigs opt_WarnMissingSigs binder_set lookup_occ_rn_sig sigs
189 `thenRn` \ (siglist, sig_fvs) ->
190 rn_mono_binds siglist mbinds `thenRn` \ (final_binds, bind_fvs) ->
191 returnRn (final_binds, bind_fvs `plusFV` sig_fvs)
193 binder_rdr_names = map fst (bagToList (collectMonoBinders mbinds))
196 %************************************************************************
200 %************************************************************************
203 - collects up the binders for this declaration group,
204 - checks that they form a set
205 - extends the environment to bind them to new local names
206 - calls @rnMonoBinds@ to do the real work
209 rnBinds :: RdrNameHsBinds
210 -> (RenamedHsBinds -> RnMS s (result, FreeVars))
211 -> RnMS s (result, FreeVars)
213 rnBinds EmptyBinds thing_inside = thing_inside EmptyBinds
214 rnBinds (MonoBind bind sigs _) thing_inside = rnMonoBinds bind sigs thing_inside
215 -- the parser doesn't produce other forms
218 rnMonoBinds :: RdrNameMonoBinds
220 -> (RenamedHsBinds -> RnMS s (result, FreeVars))
221 -> RnMS s (result, FreeVars)
223 rnMonoBinds EmptyMonoBinds sigs thing_inside = thing_inside EmptyBinds
225 rnMonoBinds mbinds sigs thing_inside -- Non-empty monobinds
226 = -- Extract all the binders in this group,
227 -- and extend current scope, inventing new names for the new binders
228 -- This also checks that the names form a set
229 bindLocatedLocalsRn (text "a binding group") mbinders_w_srclocs $ \ new_mbinders ->
231 binder_set = mkNameSet new_mbinders
233 -- Weed out the fixity declarations that do not
234 -- apply to any of the binders in this group.
235 (sigs_for_me, fixes_not_for_me) = partition forLocalBind sigs
237 forLocalBind (FixSig sig@(FixitySig name _ _ )) =
238 isJust (lookupFM binder_occ_fm (rdrNameOcc name))
239 forLocalBind _ = True
241 binder_occ_fm = addListToFM emptyFM (map (\ x -> (nameOccName x,x)) new_mbinders)
243 -- the names appearing in the sigs have to be bound by
244 -- this group's binders.
245 lookup_occ_rn_sig rdr_name =
246 case lookupFM binder_occ_fm (rdrNameOcc rdr_name) of
247 Nothing -> failUnboundNameErrRn rdr_name
251 -- Report the fixity declarations in this group that
252 -- don't refer to any of the group's binders.
254 mapRn_ (unknownSigErr) fixes_not_for_me `thenRn_`
255 renameSigs False binder_set lookup_occ_rn_sig sigs_for_me
256 `thenRn` \ (siglist, sig_fvs) ->
258 fixity_sigs = [(name,sig) | FixSig sig@(FixitySig name _ _) <- siglist ]
260 -- Install the fixity declarations that do apply here and go.
261 extendFixityEnv fixity_sigs (
262 rn_mono_binds siglist mbinds ) `thenRn` \ (binds, bind_fvs) ->
264 -- Now do the "thing inside", and deal with the free-variable calculations
265 thing_inside binds `thenRn` \ (result,result_fvs) ->
267 all_fvs = result_fvs `plusFV` bind_fvs `plusFV` sig_fvs
268 unused_binders = nameSetToList (binder_set `minusNameSet` all_fvs)
270 warnUnusedLocalBinds unused_binders `thenRn_`
271 returnRn (result, delListFromNameSet all_fvs new_mbinders)
273 mbinders_w_srclocs = bagToList (collectMonoBinders mbinds)
277 %************************************************************************
279 %* MonoBinds -- the main work is done here
281 %************************************************************************
283 @rn_mono_binds@ is used by *both* top-level and nested bindings. It
284 assumes that all variables bound in this group are already in scope.
285 This is done *either* by pass 3 (for the top-level bindings), *or* by
286 @rnMonoBinds@ (for the nested ones).
289 rn_mono_binds :: [RenamedSig] -- Signatures attached to this group
291 -> RnMS s (RenamedHsBinds, --
292 FreeVars) -- Free variables
294 rn_mono_binds siglist mbinds
296 -- Rename the bindings, returning a MonoBindsInfo
297 -- which is a list of indivisible vertices so far as
298 -- the strongly-connected-components (SCC) analysis is concerned
299 flattenMonoBinds siglist mbinds `thenRn` \ mbinds_info ->
301 -- Do the SCC analysis
303 edges = mkEdges (mbinds_info `zip` [(0::Int)..])
304 scc_result = stronglyConnComp edges
305 final_binds = foldr1 ThenBinds (map reconstructCycle scc_result)
307 -- Deal with bound and free-var calculation
308 rhs_fvs = plusFVs [fvs | (_,fvs,_,_) <- mbinds_info]
310 returnRn (final_binds, rhs_fvs)
313 @flattenMonoBinds@ is ever-so-slightly magical in that it sticks
314 unique ``vertex tags'' on its output; minor plumbing required.
316 Sigh - need to pass along the signatures for the group of bindings,
320 flattenMonoBinds :: [RenamedSig] -- Signatures
322 -> RnMS s [FlatMonoBindsInfo]
324 flattenMonoBinds sigs EmptyMonoBinds = returnRn []
326 flattenMonoBinds sigs (AndMonoBinds bs1 bs2)
327 = flattenMonoBinds sigs bs1 `thenRn` \ flat1 ->
328 flattenMonoBinds sigs bs2 `thenRn` \ flat2 ->
329 returnRn (flat1 ++ flat2)
331 flattenMonoBinds sigs (PatMonoBind pat grhss locn)
332 = pushSrcLocRn locn $
333 rnPat pat `thenRn` \ (pat', pat_fvs) ->
335 -- Find which things are bound in this group
337 names_bound_here = mkNameSet (collectPatBinders pat')
338 sigs_for_me = sigsForMe (`elemNameSet` names_bound_here) sigs
339 sigs_fvs = foldr sig_fv emptyFVs sigs_for_me
341 rnGRHSs grhss `thenRn` \ (grhss', fvs) ->
344 fvs `plusFV` sigs_fvs `plusFV` pat_fvs,
345 PatMonoBind pat' grhss' locn,
349 flattenMonoBinds sigs (FunMonoBind name inf matches locn)
350 = pushSrcLocRn locn $
351 lookupBndrRn name `thenRn` \ new_name ->
353 sigs_for_me = sigsForMe (new_name ==) sigs
354 sigs_fvs = foldr sig_fv emptyFVs sigs_for_me
356 mapAndUnzipRn rnMatch matches `thenRn` \ (new_matches, fv_lists) ->
357 mapRn_ (checkPrecMatch inf new_name) new_matches `thenRn_`
359 [(unitNameSet new_name,
360 plusFVs fv_lists `plusFV` sigs_fvs,
361 FunMonoBind new_name inf new_matches locn,
367 @rnMethodBinds@ is used for the method bindings of a class and an instance
368 declaration. like @rnMonoBinds@ but without dependency analysis.
371 rnMethodBinds :: RdrNameMonoBinds -> RnMS s (RenamedMonoBinds, FreeVars)
373 rnMethodBinds EmptyMonoBinds = returnRn (EmptyMonoBinds, emptyFVs)
375 rnMethodBinds (AndMonoBinds mb1 mb2)
376 = rnMethodBinds mb1 `thenRn` \ (mb1', fvs1) ->
377 rnMethodBinds mb2 `thenRn` \ (mb2', fvs2) ->
378 returnRn (mb1' `AndMonoBinds` mb2', fvs1 `plusFV` fvs2)
380 rnMethodBinds (FunMonoBind name inf matches locn)
381 = pushSrcLocRn locn $
383 lookupGlobalOccRn name `thenRn` \ sel_name ->
384 -- We use the selector name as the binder
386 mapAndUnzipRn rnMatch matches `thenRn` \ (new_matches, fvs_s) ->
387 mapRn_ (checkPrecMatch inf sel_name) new_matches `thenRn_`
388 returnRn (FunMonoBind sel_name inf new_matches locn, plusFVs fvs_s)
390 rnMethodBinds (PatMonoBind (VarPatIn name) grhss locn)
391 = pushSrcLocRn locn $
392 lookupGlobalOccRn name `thenRn` \ sel_name ->
393 rnGRHSs grhss `thenRn` \ (grhss', fvs) ->
394 returnRn (PatMonoBind (VarPatIn sel_name) grhss' locn, fvs)
396 -- Can't handle method pattern-bindings which bind multiple methods.
397 rnMethodBinds mbind@(PatMonoBind other_pat _ locn)
398 = pushSrcLocRn locn $
399 failWithRn (EmptyMonoBinds, emptyFVs) (methodBindErr mbind)
403 -- If a SPECIALIZE pragma is of the "... = blah" form,
404 -- then we'd better make sure "blah" is taken into
405 -- acct in the dependency analysis (or we get an
406 -- unexpected out-of-scope error)! WDP 95/07
408 -- This is only necessary for the dependency analysis. The free vars
409 -- of the types in the signatures is gotten from renameSigs
411 sig_fv (SpecSig _ _ (Just blah) _) acc = acc `plusFV` unitFV blah
415 %************************************************************************
417 \subsection[reconstruct-deps]{Reconstructing dependencies}
419 %************************************************************************
421 This @MonoBinds@- and @ClassDecls@-specific code is segregated here,
422 as the two cases are similar.
425 reconstructCycle :: SCC FlatMonoBindsInfo
428 reconstructCycle (AcyclicSCC (_, _, binds, sigs))
429 = MonoBind binds sigs NonRecursive
431 reconstructCycle (CyclicSCC cycle)
432 = MonoBind this_gp_binds this_gp_sigs Recursive
434 this_gp_binds = foldr1 AndMonoBinds [binds | (_, _, binds, _) <- cycle]
435 this_gp_sigs = foldr1 (++) [sigs | (_, _, _, sigs) <- cycle]
438 %************************************************************************
440 %* Manipulating FlatMonoBindInfo *
442 %************************************************************************
444 During analysis a @MonoBinds@ is flattened to a @FlatMonoBindsInfo@.
445 The @RenamedMonoBinds@ is always an empty bind, a pattern binding or
446 a function binding, and has itself been dependency-analysed and
450 type FlatMonoBindsInfo
451 = (NameSet, -- Set of names defined in this vertex
452 NameSet, -- Set of names used in this vertex
454 [RenamedSig]) -- Signatures, if any, for this vertex
456 mkEdges :: [(FlatMonoBindsInfo, VertexTag)] -> [(FlatMonoBindsInfo, VertexTag, [VertexTag])]
459 = [ (info, tag, dest_vertices (nameSetToList names_used))
460 | (info@(names_defined, names_used, mbind, sigs), tag) <- flat_info
463 -- An edge (v,v') indicates that v depends on v'
464 dest_vertices src_mentions = [ target_vertex
465 | ((names_defined, _, _, _), target_vertex) <- flat_info,
466 mentioned_name <- src_mentions,
467 mentioned_name `elemNameSet` names_defined
472 %************************************************************************
474 \subsubsection[dep-Sigs]{Signatures (and user-pragmas for values)}
476 %************************************************************************
478 @renameSigs@ checks for: (a)~more than one sig for one thing;
479 (b)~signatures given for things not bound here; (c)~with suitably
480 flaggery, that all top-level things have type signatures.
482 At the moment we don't gather free-var info from the types in
483 signatures. We'd only need this if we wanted to report unused tyvars.
486 renameSigs :: Bool -- True => warn if (required) type signatures are missing.
487 -> NameSet -- Set of names bound in this group
488 -> (RdrName -> RnMS s Name)
490 -> RnMS s ([RenamedSig], FreeVars) -- List of Sig constructors
492 renameSigs sigs_required binders lookup_occ_nm sigs
493 = -- Rename the signatures
494 mapAndUnzipRn (renameSig lookup_occ_nm) sigs `thenRn` \ (sigs', fvs_s) ->
496 -- Check for (a) duplicate signatures
497 -- (b) signatures for things not in this group
498 -- (c) optionally, bindings with no signature
500 (goodies, dups) = removeDups cmp_sig (sigsForMe (not . isUnboundName) sigs')
501 not_this_group = sigsForMe (not . (`elemNameSet` binders)) goodies
502 type_sig_vars = [n | Sig n _ _ <- goodies]
503 un_sigd_binders | sigs_required = nameSetToList binders `minusList` type_sig_vars
506 mapRn_ dupSigDeclErr dups `thenRn_`
507 mapRn_ unknownSigErr not_this_group `thenRn_`
508 mapRn_ (addWarnRn.missingSigWarn) un_sigd_binders `thenRn_`
509 returnRn (sigs', plusFVs fvs_s)
511 -- we need bindings of *some* sort for every name
513 -- We use lookupOccRn in the signatures, which is a little bit unsatisfactory
514 -- because this won't work for:
515 -- instance Foo T where
518 -- We'll just rename the INLINE prag to refer to whatever other 'op'
519 -- is in scope. (I'm assuming that Baz.op isn't in scope unqualified.)
520 -- Doesn't seem worth much trouble to sort this.
522 renameSig lookup_occ_nm (Sig v ty src_loc)
523 = pushSrcLocRn src_loc $
524 lookup_occ_nm v `thenRn` \ new_v ->
525 rnHsSigType (quotes (ppr v)) ty `thenRn` \ (new_ty,fvs) ->
526 returnRn (Sig new_v new_ty src_loc, fvs)
528 renameSig _ (SpecInstSig ty src_loc)
529 = pushSrcLocRn src_loc $
530 rnHsSigType (text "A SPECIALISE instance pragma") ty `thenRn` \ (new_ty, fvs) ->
531 returnRn (SpecInstSig new_ty src_loc, fvs)
533 renameSig lookup_occ_nm (SpecSig v ty using src_loc)
534 = pushSrcLocRn src_loc $
535 lookup_occ_nm v `thenRn` \ new_v ->
536 rnHsSigType (quotes (ppr v)) ty `thenRn` \ (new_ty,fvs1) ->
537 rn_using using `thenRn` \ (new_using,fvs2) ->
538 returnRn (SpecSig new_v new_ty new_using src_loc, fvs1 `plusFV` fvs2)
540 rn_using Nothing = returnRn (Nothing, emptyFVs)
541 rn_using (Just x) = lookupOccRn x `thenRn` \ new_x ->
542 returnRn (Just new_x, unitFV new_x)
544 renameSig lookup_occ_nm (InlineSig v src_loc)
545 = pushSrcLocRn src_loc $
546 lookup_occ_nm v `thenRn` \ new_v ->
547 returnRn (InlineSig new_v src_loc, emptyFVs)
549 renameSig lookup_occ_nm (FixSig (FixitySig v fix src_loc))
550 = pushSrcLocRn src_loc $
551 lookup_occ_nm v `thenRn` \ new_v ->
552 returnRn (FixSig (FixitySig new_v fix src_loc), emptyFVs)
554 renameSig lookup_occ_nm (NoInlineSig v src_loc)
555 = pushSrcLocRn src_loc $
556 lookup_occ_nm v `thenRn` \ new_v ->
557 returnRn (NoInlineSig new_v src_loc, emptyFVs)
560 Checking for distinct signatures; oh, so boring
563 cmp_sig :: RenamedSig -> RenamedSig -> Ordering
564 cmp_sig (Sig n1 _ _) (Sig n2 _ _) = n1 `compare` n2
565 cmp_sig (InlineSig n1 _) (InlineSig n2 _) = n1 `compare` n2
566 cmp_sig (NoInlineSig n1 _) (NoInlineSig n2 _) = n1 `compare` n2
567 cmp_sig (SpecInstSig ty1 _) (SpecInstSig ty2 _) = cmpHsType compare ty1 ty2
568 cmp_sig (SpecSig n1 ty1 _ _) (SpecSig n2 ty2 _ _)
569 = -- may have many specialisations for one value;
570 -- but not ones that are exactly the same...
571 thenCmp (n1 `compare` n2) (cmpHsType compare ty1 ty2)
573 cmp_sig other_1 other_2 -- Tags *must* be different
574 | (sig_tag other_1) _LT_ (sig_tag other_2) = LT
577 sig_tag (Sig n1 _ _) = (ILIT(1) :: FAST_INT)
578 sig_tag (SpecSig n1 _ _ _) = ILIT(2)
579 sig_tag (InlineSig n1 _) = ILIT(3)
580 sig_tag (NoInlineSig n1 _) = ILIT(4)
581 sig_tag (SpecInstSig _ _) = ILIT(5)
582 sig_tag (FixSig _) = ILIT(6)
583 sig_tag _ = panic# "tag(RnBinds)"
586 %************************************************************************
588 \subsection{Error messages}
590 %************************************************************************
593 dupSigDeclErr (sig:sigs)
595 addErrRn (sep [ptext SLIT("Duplicate"),
596 ptext what_it_is <> colon,
599 (what_it_is, loc) = sig_doc sig
603 addErrRn (sep [ptext SLIT("Misplaced"),
604 ptext what_it_is <> colon,
607 (what_it_is, loc) = sig_doc sig
609 sig_doc (Sig _ _ loc) = (SLIT("type signature"),loc)
610 sig_doc (ClassOpSig _ _ _ loc) = (SLIT("class-method type signature"), loc)
611 sig_doc (SpecSig _ _ _ loc) = (SLIT("SPECIALISE pragma"),loc)
612 sig_doc (InlineSig _ loc) = (SLIT("INLINE pragma"),loc)
613 sig_doc (NoInlineSig _ loc) = (SLIT("NOINLINE pragma"),loc)
614 sig_doc (SpecInstSig _ loc) = (SLIT("SPECIALISE instance pragma"),loc)
615 sig_doc (FixSig (FixitySig _ _ loc)) = (SLIT("fixity declaration"), loc)
618 = sep [ptext SLIT("definition but no type signature for"), quotes (ppr var)]
621 = hang (ptext SLIT("Can't handle multiple methods defined by one pattern binding"))