RnBinds.lhs 43.7 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11
%
% (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
%
\section[RnBinds]{Renaming and dependency analysis of bindings}

This module does renaming and dependency analysis on value bindings in
the abstract syntax.  It does {\em not} do cycle-checks on class or
type-synonym declarations; those cannot be done at this stage because
they may be affected by renaming (which isn't fully worked out yet).

\begin{code}
12
{-# LANGUAGE CPP #-}
13
{-# OPTIONS_GHC -fno-warn-tabs #-}
Ian Lynagh's avatar
Ian Lynagh committed
14 15 16
-- The above warning supression flag is a temporary kludge.
-- While working on this module you are encouraged to remove it and
-- detab the module (please do the detabbing in a separate patch). See
17
--     http://ghc.haskell.org/trac/ghc/wiki/Commentary/CodingStyle#TabsvsSpaces
Ian Lynagh's avatar
Ian Lynagh committed
18 19
-- for details

20 21
module RnBinds (
   -- Renaming top-level bindings
22
   rnTopBindsLHS, rnTopBindsRHS, rnValBindsRHS,
23 24 25 26 27 28

   -- Renaming local bindings
   rnLocalBindsAndThen, rnLocalValBindsLHS, rnLocalValBindsRHS,

   -- Other bindings
   rnMethodBinds, renameSigs, mkSigTvFn,
29
   rnMatchGroup, rnGRHSs, rnGRHS,
30
   makeMiniFixityEnv, MiniFixityEnv,
31
   HsSigCtxt(..)
32 33
   ) where

34
import {-# SOURCE #-} RnExpr( rnLExpr, rnStmts )
35 36

import HsSyn
37
import TcRnMonad
38
import TcEvidence     ( emptyTcEvBinds )
Gergő Érdi's avatar
Gergő Érdi committed
39
import RnTypes        ( bindSigTyVarsFV, rnHsSigType, rnLHsType, checkPrecMatch, rnContext )
40
import RnPat
Gergő Érdi's avatar
Gergő Érdi committed
41
import RnNames
42
import RnEnv
43
import DynFlags
44
import Module
45
import Name
46
import NameEnv
47
import NameSet
48
import RdrName          ( RdrName, rdrNameOcc )
Ian Lynagh's avatar
Ian Lynagh committed
49
import SrcLoc
50 51 52
import ListSetOps       ( findDupsEq )
import BasicTypes       ( RecFlag(..) )
import Digraph          ( SCC(..) )
53
import Bag
54
import Outputable
55
import FastString
56 57
import Data.List        ( partition, sort )
import Maybes           ( orElse )
Ian Lynagh's avatar
Ian Lynagh committed
58
import Control.Monad
59
#if __GLASGOW_HASKELL__ < 709
60
import Data.Traversable ( traverse )
61
#endif
62 63 64 65 66 67 68 69 70 71
\end{code}

-- ToDo: Put the annotations into the monad, so that they arrive in the proper
-- place and can be used when complaining.

The code tree received by the function @rnBinds@ contains definitions
in where-clauses which are all apparently mutually recursive, but which may
not really depend upon each other. For example, in the top level program
\begin{verbatim}
f x = y where a = x
72
              y = x
73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91
\end{verbatim}
the definitions of @a@ and @y@ do not depend on each other at all.
Unfortunately, the typechecker cannot always check such definitions.
\footnote{Mycroft, A. 1984. Polymorphic type schemes and recursive
definitions. In Proceedings of the International Symposium on Programming,
Toulouse, pp. 217-39. LNCS 167. Springer Verlag.}
However, the typechecker usually can check definitions in which only the
strongly connected components have been collected into recursive bindings.
This is precisely what the function @rnBinds@ does.

ToDo: deal with case where a single monobinds binds the same variable
twice.

The vertag tag is a unique @Int@; the tags only need to be unique
within one @MonoBinds@, so that unique-Int plumbing is done explicitly
(heavy monad machinery not needed).


%************************************************************************
92 93 94
%*                                                                      *
%* naming conventions                                                   *
%*                                                                      *
95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118
%************************************************************************

\subsection[name-conventions]{Name conventions}

The basic algorithm involves walking over the tree and returning a tuple
containing the new tree plus its free variables. Some functions, such
as those walking polymorphic bindings (HsBinds) and qualifier lists in
list comprehensions (@Quals@), return the variables bound in local
environments. These are then used to calculate the free variables of the
expression evaluated in these environments.

Conventions for variable names are as follows:
\begin{itemize}
\item
new code is given a prime to distinguish it from the old.

\item
a set of variables defined in @Exp@ is written @dvExp@

\item
a set of variables free in @Exp@ is written @fvExp@
\end{itemize}

%************************************************************************
119
%*                                                                      *
120
%* analysing polymorphic bindings (HsBindGroup, HsBind)
121
%*                                                                      *
122 123 124 125 126 127 128 129 130 131
%************************************************************************

\subsubsection[dep-HsBinds]{Polymorphic bindings}

Non-recursive expressions are reconstructed without any changes at top
level, although their component expressions may have to be altered.
However, non-recursive expressions are currently not expected as
\Haskell{} programs, and this code should not be executed.

Monomorphic bindings contain information that is returned in a tuple
132
(a @FlatMonoBinds@) containing:
133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159

\begin{enumerate}
\item
a unique @Int@ that serves as the ``vertex tag'' for this binding.

\item
the name of a function or the names in a pattern. These are a set
referred to as @dvLhs@, the defined variables of the left hand side.

\item
the free variables of the body. These are referred to as @fvBody@.

\item
the definition's actual code. This is referred to as just @code@.
\end{enumerate}

The function @nonRecDvFv@ returns two sets of variables. The first is
the set of variables defined in the set of monomorphic bindings, while the
second is the set of free variables in those bindings.

The set of variables defined in a non-recursive binding is just the
union of all of them, as @union@ removes duplicates. However, the
free variables in each successive set of cumulative bindings is the
union of those in the previous set plus those of the newest binding after
the defined variables of the previous set have been removed.

@rnMethodBinds@ deals only with the declarations in class and
160
instance declarations.  It expects only to see @FunMonoBind@s, and
161 162 163 164
it expects the global environment to contain bindings for the binders
(which are all class operations).

%************************************************************************
165
%*                                                                      *
166
\subsubsection{ Top-level bindings}
167
%*                                                                      *
168 169 170
%************************************************************************

\begin{code}
171 172
-- for top-level bindings, we need to make top-level names,
-- so we have a different entry point than for local bindings
173
rnTopBindsLHS :: MiniFixityEnv
174
              -> HsValBinds RdrName
175
              -> RnM (HsValBindsLR Name RdrName)
176
rnTopBindsLHS fix_env binds
177
  = rnValBindsLHS (topRecNameMaker fix_env) binds
178

179
rnTopBindsRHS :: NameSet -> HsValBindsLR Name RdrName
180
              -> RnM (HsValBinds Name, DefUses)
181
rnTopBindsRHS bound_names binds
182
  = do { is_boot <- tcIsHsBoot
183
       ; if is_boot
184
         then rnTopBindsBoot binds
185
         else rnValBindsRHS (TopSigCtxt bound_names False) binds }
186 187

rnTopBindsBoot :: HsValBindsLR Name RdrName -> RnM (HsValBinds Name, DefUses)
188
-- A hs-boot file has no bindings.
189
-- Return a single HsBindGroup with empty binds and renamed signatures
190
rnTopBindsBoot (ValBindsIn mbinds sigs)
191 192 193
  = do  { checkErr (isEmptyLHsBinds mbinds) (bindsInHsBootFile mbinds)
        ; (sigs', fvs) <- renameSigs HsBootCtxt sigs
        ; return (ValBindsOut [] sigs', usesOnly fvs) }
Ian Lynagh's avatar
Ian Lynagh committed
194
rnTopBindsBoot b = pprPanic "rnTopBindsBoot" (ppr b)
195 196 197 198
\end{code}


%*********************************************************
199 200 201
%*                                                      *
                HsLocalBinds
%*                                                      *
202 203 204
%*********************************************************

\begin{code}
205 206 207 208
rnLocalBindsAndThen :: HsLocalBinds RdrName
                    -> (HsLocalBinds Name -> RnM (result, FreeVars))
                    -> RnM (result, FreeVars)
-- This version (a) assumes that the binding vars are *not* already in scope
209
--               (b) removes the binders from the free vars of the thing inside
210 211 212 213 214
-- The parser doesn't produce ThenBinds
rnLocalBindsAndThen EmptyLocalBinds thing_inside
  = thing_inside EmptyLocalBinds

rnLocalBindsAndThen (HsValBinds val_binds) thing_inside
215
  = rnLocalValBindsAndThen val_binds $ \ val_binds' ->
216
      thing_inside (HsValBinds val_binds')
217

218 219 220 221
rnLocalBindsAndThen (HsIPBinds binds) thing_inside = do
    (binds',fv_binds) <- rnIPBinds binds
    (thing, fvs_thing) <- thing_inside (HsIPBinds binds')
    return (thing, fvs_thing `plusFV` fv_binds)
222

Ian Lynagh's avatar
Ian Lynagh committed
223
rnIPBinds :: HsIPBinds RdrName -> RnM (HsIPBinds Name, FreeVars)
224 225
rnIPBinds (IPBinds ip_binds _no_dict_binds) = do
    (ip_binds', fvs_s) <- mapAndUnzipM (wrapLocFstM rnIPBind) ip_binds
226
    return (IPBinds ip_binds' emptyTcEvBinds, plusFVs fvs_s)
227

Ian Lynagh's avatar
Ian Lynagh committed
228
rnIPBind :: IPBind RdrName -> RnM (IPBind Name, FreeVars)
229
rnIPBind (IPBind ~(Left n) expr) = do
230
    (expr',fvExpr) <- rnLExpr expr
231
    return (IPBind (Left n) expr', fvExpr)
232 233
\end{code}

234

235
%************************************************************************
236 237 238
%*                                                                      *
                ValBinds
%*                                                                      *
239 240 241
%************************************************************************

\begin{code}
242
-- Renaming local binding groups
243
-- Does duplicate/shadow check
244 245 246
rnLocalValBindsLHS :: MiniFixityEnv
                   -> HsValBinds RdrName
                   -> RnM ([Name], HsValBindsLR Name RdrName)
247 248
rnLocalValBindsLHS fix_env binds
  = do { binds' <- rnValBindsLHS (localRecNameMaker fix_env) binds
249 250

         -- Check for duplicates and shadowing
251 252
         -- Must do this *after* renaming the patterns
         -- See Note [Collect binders only after renaming] in HsUtils
253 254

         -- We need to check for dups here because we
255 256 257 258 259 260 261 262 263 264 265 266 267
         -- don't don't bind all of the variables from the ValBinds at once
         -- with bindLocatedLocals any more.
         --
         -- Note that we don't want to do this at the top level, since
         -- sorting out duplicates and shadowing there happens elsewhere.
         -- The behavior is even different. For example,
         --   import A(f)
         --   f = ...
         -- should not produce a shadowing warning (but it will produce
         -- an ambiguity warning if you use f), but
         --   import A(f)
         --   g = let f = ... in f
         -- should.
268
       ; let bound_names = collectHsValBinders binds'
269 270
       ; envs <- getRdrEnvs
       ; checkDupAndShadowedNames envs bound_names
271

272
       ; return (bound_names, binds') }
273 274 275 276

-- renames the left-hand sides
-- generic version used both at the top level and for local binds
-- does some error checking, but not what gets done elsewhere at the top level
277
rnValBindsLHS :: NameMaker
278 279 280
              -> HsValBinds RdrName
              -> RnM (HsValBindsLR Name RdrName)
rnValBindsLHS topP (ValBindsIn mbinds sigs)
281
  = do { mbinds' <- mapBagM (wrapLocM (rnBindLHS topP doc)) mbinds
282 283
       ; return $ ValBindsIn mbinds' sigs }
  where
284
    bndrs = collectHsBindsBinders mbinds
285 286
    doc   = text "In the binding group for:" <+> pprWithCommas ppr bndrs

287
rnValBindsLHS _ b = pprPanic "rnValBindsLHSFromDoc" (ppr b)
288

289 290
-- General version used both from the top-level and for local things
-- Assumes the LHS vars are in scope
291
--
292
-- Does not bind the local fixity declarations
293
rnValBindsRHS :: HsSigCtxt
294 295
              -> HsValBindsLR Name RdrName
              -> RnM (HsValBinds Name, DefUses)
296

297
rnValBindsRHS ctxt (ValBindsIn mbinds sigs)
298
  = do { (sigs', sig_fvs) <- renameSigs ctxt sigs
Gergő Érdi's avatar
Gergő Érdi committed
299
       ; binds_w_dus <- mapBagM (rnLBind (mkSigTvFn sigs')) mbinds
300
       ; case depAnalBinds binds_w_dus of
301 302 303
           (anal_binds, anal_dus) -> return (valbind', valbind'_dus)
              where
                valbind' = ValBindsOut anal_binds sigs'
304
                valbind'_dus = anal_dus `plusDU` usesOnly sig_fvs
305 306 307
                               -- Put the sig uses *after* the bindings
                               -- so that the binders are removed from
                               -- the uses in the sigs
308 309
       }

310
rnValBindsRHS _ b = pprPanic "rnValBindsRHS" (ppr b)
Ian Lynagh's avatar
Ian Lynagh committed
311

312
-- Wrapper for local binds
313
--
314
-- The *client* of this function is responsible for checking for unused binders;
315 316
-- it doesn't (and can't: we don't have the thing inside the binds) happen here
--
317
-- The client is also responsible for bringing the fixities into scope
318 319 320 321
rnLocalValBindsRHS :: NameSet  -- names bound by the LHSes
                   -> HsValBindsLR Name RdrName
                   -> RnM (HsValBinds Name, DefUses)
rnLocalValBindsRHS bound_names binds
322
  = rnValBindsRHS (LocalBindCtxt bound_names) binds
323 324

-- for local binds
325
-- wrapper that does both the left- and right-hand sides
326 327 328
--
-- here there are no local fixity decls passed in;
-- the local fixity decls come from the ValBinds sigs
329 330 331 332
rnLocalValBindsAndThen :: HsValBinds RdrName
                       -> (HsValBinds Name -> RnM (result, FreeVars))
                       -> RnM (result, FreeVars)
rnLocalValBindsAndThen binds@(ValBindsIn _ sigs) thing_inside
333 334 335
 = do   {     -- (A) Create the local fixity environment
          new_fixities <- makeMiniFixityEnv [L loc sig
                                                  | L loc (FixSig sig) <- sigs]
336

337 338
              -- (B) Rename the LHSes
        ; (bound_names, new_lhs) <- rnLocalValBindsLHS new_fixities binds
339

340 341
              --     ...and bring them (and their fixities) into scope
        ; bindLocalNamesFV bound_names              $
342
          addLocalFixities new_fixities bound_names $ do
343

344 345
        {      -- (C) Do the RHS and thing inside
          (binds', dus) <- rnLocalValBindsRHS (mkNameSet bound_names) new_lhs
346
        ; (result, result_fvs) <- thing_inside binds'
347

348 349 350 351 352 353 354 355 356 357 358 359 360
                -- Report unused bindings based on the (accurate)
                -- findUses.  E.g.
                --      let x = x in 3
                -- should report 'x' unused
        ; let real_uses = findUses dus result_fvs
              -- Insert fake uses for variables introduced implicitly by
              -- wildcards (#4404)
              implicit_uses = hsValBindsImplicits binds'
        ; warnUnusedLocalBinds bound_names
                                      (real_uses `unionNameSets` implicit_uses)

        ; let
            -- The variables "used" in the val binds are:
361
            --   (1) the uses of the binds (allUses)
362
            --   (2) the FVs of the thing-inside
363
            all_uses = allUses dus `plusFV` result_fvs
364 365 366 367 368 369 370
                -- Note [Unused binding hack]
                -- ~~~~~~~~~~~~~~~~~~~~~~~~~~
                -- Note that *in contrast* to the above reporting of
                -- unused bindings, (1) above uses duUses to return *all*
                -- the uses, even if the binding is unused.  Otherwise consider:
                --      x = 3
                --      y = let p = x in 'x'    -- NB: p not used
371 372 373
                -- If we don't "see" the dependency of 'y' on 'x', we may put the
                -- bindings in the wrong order, and the type checker will complain
                -- that x isn't in scope
374 375 376
                --
                -- But note that this means we won't report 'x' as unused,
                -- whereas we would if we had { x = 3; p = x; y = 'x' }
377

378 379 380
        ; return (result, all_uses) }}
                -- The bound names are pruned out of all_uses
                -- by the bindLocalNamesFV call above
Ian Lynagh's avatar
Ian Lynagh committed
381

382
rnLocalValBindsAndThen bs _ = pprPanic "rnLocalValBindsAndThen" (ppr bs)
383 384 385 386


-- Process the fixity declarations, making a FastString -> (Located Fixity) map
-- (We keep the location around for reporting duplicate fixity declarations.)
387
--
388 389 390
-- Checks for duplicates, but not that only locally defined things are fixed.
-- Note: for local fixity declarations, duplicates would also be checked in
--       check_sigs below.  But we also use this function at the top level.
391 392 393

makeMiniFixityEnv :: [LFixitySig RdrName] -> RnM MiniFixityEnv

394
makeMiniFixityEnv decls = foldlM add_one emptyFsEnv decls
395 396 397 398 399 400
 where
   add_one env (L loc (FixitySig (L name_loc name) fixity)) = do
     { -- this fixity decl is a duplicate iff
       -- the ReaderName's OccName's FastString is already in the env
       -- (we only need to check the local fix_env because
       --  definitions of non-local will be caught elsewhere)
401 402
       let { fs = occNameFS (rdrNameOcc name)
           ; fix_item = L loc fixity };
403

404 405
       case lookupFsEnv env fs of
         Nothing -> return $ extendFsEnv env fs fix_item
406
         Just (L loc' _) -> do
407
           { setSrcSpan loc $
408
             addErrAt name_loc (dupFixityDecl loc' name)
409 410 411
           ; return env}
     }

Ian Lynagh's avatar
Ian Lynagh committed
412
dupFixityDecl :: SrcSpan -> RdrName -> SDoc
413
dupFixityDecl loc rdr_name
Ian Lynagh's avatar
Ian Lynagh committed
414
  = vcat [ptext (sLit "Multiple fixity declarations for") <+> quotes (ppr rdr_name),
415
          ptext (sLit "also at ") <+> ppr loc]
416

417
---------------------
418

419 420
-- renaming a single bind

421
rnBindLHS :: NameMaker
422
          -> SDoc
Gergő Érdi's avatar
Gergő Érdi committed
423
          -> HsBind RdrName
424 425 426
          -- returns the renamed left-hand side,
          -- and the FreeVars *of the LHS*
          -- (i.e., any free variables of the pattern)
Gergő Érdi's avatar
Gergő Érdi committed
427
          -> RnM (HsBindLR Name RdrName)
428

Gergő Érdi's avatar
Gergő Érdi committed
429 430
rnBindLHS name_maker _ bind@(PatBind { pat_lhs = pat })
  = do
431
      -- we don't actually use the FV processing of rnPatsAndThen here
432
      (pat',pat'_fvs) <- rnBindPat name_maker pat
Gergő Érdi's avatar
Gergő Érdi committed
433
      return (bind { pat_lhs = pat', bind_fvs = pat'_fvs })
434 435 436
                -- We temporarily store the pat's FVs in bind_fvs;
                -- gets updated to the FVs of the whole bind
                -- when doing the RHS below
437

Gergő Érdi's avatar
Gergő Érdi committed
438 439
rnBindLHS name_maker _ bind@(FunBind { fun_id = name@(L nameLoc _) })
  = do { newname <- applyNameMaker name_maker name
440 441
       ; return (bind { fun_id = L nameLoc newname
                      , bind_fvs = placeHolderNamesTc }) }
Gergő Érdi's avatar
Gergő Érdi committed
442

443
rnBindLHS name_maker _ (PatSynBind psb@PSB{ psb_id = rdrname@(L nameLoc _) })
444 445 446
  = do { unless (isTopRecNameMaker name_maker) $
           addErr localPatternSynonymErr
       ; addLocM checkConName rdrname
Gergő Érdi's avatar
Gergő Érdi committed
447
       ; name <- applyNameMaker name_maker rdrname
448
       ; return (PatSynBind psb{ psb_id = L nameLoc name }) }
449 450 451 452 453
  where
    localPatternSynonymErr :: SDoc
    localPatternSynonymErr
      = hang (ptext (sLit "Illegal pattern synonym declaration"))
           2 (ptext (sLit "Pattern synonym declarations are only valid in the top-level scope"))
Gergő Érdi's avatar
Gergő Érdi committed
454 455 456

rnBindLHS _ _ b = pprPanic "rnBindHS" (ppr b)

457
rnLBind :: (Name -> [Name])             -- Signature tyvar function
458 459 460
        -> LHsBindLR Name RdrName
        -> RnM (LHsBind Name, [Name], Uses)
rnLBind sig_fn (L loc bind)
Gergő Érdi's avatar
Gergő Érdi committed
461 462
  = setSrcSpan loc $
    do { (bind', bndrs, dus) <- rnBind sig_fn bind
463
       ; return (L loc bind', bndrs, dus) }
Ian Lynagh's avatar
Ian Lynagh committed
464

465
-- assumes the left-hands-side vars are in scope
466
rnBind :: (Name -> [Name])              -- Signature tyvar function
Gergő Érdi's avatar
Gergő Érdi committed
467 468 469
       -> HsBindLR Name RdrName
       -> RnM (HsBind Name, [Name], Uses)
rnBind _ bind@(PatBind { pat_lhs = pat
470
                       , pat_rhs = grhss
Gergő Érdi's avatar
Gergő Érdi committed
471 472 473
                                   -- pat fvs were stored in bind_fvs
                                   -- after processing the LHS
                       , bind_fvs = pat_fvs })
474
  = do  { mod <- getModule
475
        ; (grhss', rhs_fvs) <- rnGRHSs PatBindRhs rnLExpr grhss
476

477 478
                -- No scoped type variables for pattern bindings
        ; let all_fvs = pat_fvs `plusFV` rhs_fvs
479
              fvs'    = filterNameSet (nameIsLocalOrFrom mod) all_fvs
480 481 482
                -- Keep locally-defined Names
                -- As well as dependency analysis, we need these for the
                -- MonoLocalBinds test in TcBinds.decideGeneralisationPlan
483
              bndrs = collectPatBinders pat
484 485
              bind' = bind { pat_rhs  = grhss',
                             pat_rhs_ty = placeHolderType, bind_fvs = fvs' }
486
              is_wild_pat = case pat of
487 488 489
                              L _ (WildPat {})                 -> True
                              L _ (BangPat (L _ (WildPat {}))) -> True -- #9127
                              _                                -> False
490 491 492 493 494 495

        -- Warn if the pattern binds no variables, except for the
        -- entirely-explicit idiom    _ = rhs
        -- which (a) is not that different from  _v = rhs
        --       (b) is sometimes used to give a type sig for,
        --           or an occurrence of, a variable on the RHS
ian@well-typed.com's avatar
ian@well-typed.com committed
496
        ; whenWOptM Opt_WarnUnusedBinds $
497 498
          when (null bndrs && not is_wild_pat) $
          addWarn $ unusedPatBindWarn bind'
499

500
        ; fvs' `seq` -- See Note [Free-variable space leak]
Gergő Érdi's avatar
Gergő Érdi committed
501
          return (bind', bndrs, all_fvs) }
502

503 504 505
rnBind sig_fn bind@(FunBind { fun_id = name
                            , fun_infix = is_infix
                            , fun_matches = matches })
506
       -- invariant: no free vars here when it's a FunBind
507
  = do  { let plain_name = unLoc name
508

509 510 511 512 513
        ; (matches', rhs_fvs) <- bindSigTyVarsFV (sig_fn plain_name) $
                                -- bindSigTyVars tests for Opt_ScopedTyVars
                                 rnMatchGroup (FunRhs plain_name is_infix)
                                              rnLExpr matches
        ; when is_infix $ checkPrecMatch plain_name matches'
514

515 516
        ; mod <- getModule
        ; let fvs' = filterNameSet (nameIsLocalOrFrom mod) rhs_fvs
517 518 519
                -- Keep locally-defined Names
                -- As well as dependency analysis, we need these for the
                -- MonoLocalBinds test in TcBinds.decideGeneralisationPlan
520

521
        ; fvs' `seq` -- See Note [Free-variable space leak]
Gergő Érdi's avatar
Gergő Érdi committed
522
          return (bind { fun_matches = matches'
523 524
                       , bind_fvs   = fvs' },
                  [plain_name], rhs_fvs)
525
      }
Ian Lynagh's avatar
Ian Lynagh committed
526

527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545
rnBind sig_fn (PatSynBind bind)
  = do  { (bind', name, fvs) <- rnPatSynBind sig_fn bind
        ; return (PatSynBind bind', name, fvs) }

rnBind _ b = pprPanic "rnBind" (ppr b)

{-
Note [Free-variable space leak]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
We have
    fvs' = trim fvs
and we seq fvs' before turning it as part of a record.

The reason is that trim is sometimes something like
    \xs -> intersectNameSet (mkNameSet bound_names) xs
and we don't want to retain the list bound_names. This showed up in
trac ticket #1136.
-}

546
rnPatSynBind :: (Name -> [Name])                -- Signature tyvar function
547 548 549 550 551 552
             -> PatSynBind Name RdrName
             -> RnM (PatSynBind Name Name, [Name], Uses)
rnPatSynBind _sig_fn bind@(PSB { psb_id = L _ name
                               , psb_args = details
                               , psb_def = pat
                               , psb_dir = dir })
Gergő Érdi's avatar
Gergő Érdi committed
553
       -- invariant: no free vars here when it's a FunBind
554
  = do  { pattern_synonym_ok <- xoptM Opt_PatternSynonyms
Gergő Érdi's avatar
Gergő Érdi committed
555 556
        ; unless pattern_synonym_ok (addErr patternSynonymErr)

557
        ; ((pat', details'), fvs1) <- rnPat PatSyn pat $ \pat' -> do
Gergő Érdi's avatar
Gergő Érdi committed
558 559 560 561 562 563 564 565 566 567 568 569 570 571 572
         -- We check the 'RdrName's instead of the 'Name's
         -- so that the binding locations are reported
         -- from the left-hand side
        { (details', fvs) <- case details of
               PrefixPatSyn vars ->
                   do { checkDupRdrNames vars
                      ; names <- mapM lookupVar vars
                      ; return (PrefixPatSyn names, mkFVs (map unLoc names)) }
               InfixPatSyn var1 var2 ->
                   do { checkDupRdrNames [var1, var2]
                      ; name1 <- lookupVar var1
                      ; name2 <- lookupVar var2
                      -- ; checkPrecMatch -- TODO
                      ; return (InfixPatSyn name1 name2, mkFVs (map unLoc [name1, name2])) }
        ; return ((pat', details'), fvs) }
573 574 575 576 577 578
        ; (dir', fvs2) <- case dir of
            Unidirectional -> return (Unidirectional, emptyFVs)
            ImplicitBidirectional -> return (ImplicitBidirectional, emptyFVs)
            ExplicitBidirectional mg ->
                do { (mg', fvs) <- rnMatchGroup PatSyn rnLExpr mg
                   ; return (ExplicitBidirectional mg', fvs) }
Gergő Érdi's avatar
Gergő Érdi committed
579 580

        ; mod <- getModule
581 582
        ; let fvs = fvs1 `plusFV` fvs2
              fvs' = filterNameSet (nameIsLocalOrFrom mod) fvs
583 584 585
                -- Keep locally-defined Names
                -- As well as dependency analysis, we need these for the
                -- MonoLocalBinds test in TcBinds.decideGeneralisationPlan
Gergő Érdi's avatar
Gergő Érdi committed
586

587 588 589 590
        ; let bind' = bind{ psb_args = details'
                          , psb_def = pat'
                          , psb_dir = dir'
                          , psb_fvs = fvs' }
Gergő Érdi's avatar
Gergő Érdi committed
591 592

        ; fvs' `seq` -- See Note [Free-variable space leak]
593
          return (bind', [name], fvs1)
594
          -- See Note [Pattern synonym wrappers don't yield dependencies]
Gergő Érdi's avatar
Gergő Érdi committed
595 596 597 598 599 600 601 602 603
      }
  where
    lookupVar = wrapLocM lookupOccRn

    patternSynonymErr :: SDoc
    patternSynonymErr
      = hang (ptext (sLit "Illegal pattern synonym declaration"))
           2 (ptext (sLit "Use -XPatternSynonyms to enable this extension"))

604
{-
605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630
Note [Pattern synonym wrappers don't yield dependencies]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

When renaming a pattern synonym that has an explicit wrapper,
references in the wrapper definition should not be used when
calculating dependencies. For example, consider the following pattern
synonym definition:

pattern P x <- C1 x where
  P x = f (C1 x)

f (P x) = C2 x

In this case, 'P' needs to be typechecked in two passes:

1. Typecheck the pattern definition of 'P', which fully determines the
type of 'P'. This step doesn't require knowing anything about 'f',
since the wrapper definition is not looked at.

2. Typecheck the wrapper definition, which needs the typechecked
definition of 'f' to be in scope.

This behaviour is implemented in 'tcValBinds', but it crucially
depends on 'P' not being put in a recursive group with 'f' (which
would make it look like a recursive pattern synonym a la 'pattern P =
P' which is unsound and rejected).
631 632 633

-}

634
---------------------
635
depAnalBinds :: Bag (LHsBind Name, [Name], Uses)
636 637
             -> ([(RecFlag, LHsBinds Name)], DefUses)
-- Dependency analysis; this is important so that
638
-- unused-binding reporting is accurate
639 640 641
depAnalBinds binds_w_dus
  = (map get_binds sccs, map get_du sccs)
  where
642 643 644
    sccs = depAnal (\(_, defs, _) -> defs)
                   (\(_, _, uses) -> nameSetToList uses)
                   (bagToList binds_w_dus)
645

646
    get_binds (AcyclicSCC (bind, _, _)) = (NonRecursive, unitBag bind)
Ian Lynagh's avatar
Ian Lynagh committed
647
    get_binds (CyclicSCC  binds_w_dus)  = (Recursive, listToBag [b | (b,_,_) <- binds_w_dus])
648

649 650
    get_du (AcyclicSCC (_, bndrs, uses)) = (Just (mkNameSet bndrs), uses)
    get_du (CyclicSCC  binds_w_dus)      = (Just defs, uses)
651 652 653
        where
          defs = mkNameSet [b | (_,bs,_) <- binds_w_dus, b <- bs]
          uses = unionManyNameSets [u | (_,_,u) <- binds_w_dus]
654 655 656

---------------------
-- Bind the top-level forall'd type variables in the sigs.
657 658 659
-- E.g  f :: a -> a
--      f = rhs
--      The 'a' scopes over the rhs
660 661 662
--
-- NB: there'll usually be just one (for a function binding)
--     but if there are many, one may shadow the rest; too bad!
663 664 665
--      e.g  x :: [a] -> [a]
--           y :: [(a,a)] -> a
--           (x,y) = e
666 667 668 669 670 671 672
--      In e, 'a' will be in scope, and it'll be the one from 'y'!

mkSigTvFn :: [LSig Name] -> (Name -> [Name])
-- Return a lookup function that maps an Id Name to the names
-- of the type variables that should scope over its body..
mkSigTvFn sigs
  = \n -> lookupNameEnv env n `orElse` []
673
  where
674
    env :: NameEnv [Name]
675
    env = mkNameEnv [ (name, hsLKiTyVarNames ltvs)  -- Kind variables and type variables
676 677
                    | L _ (TypeSig names
                                   (L _ (HsForAllTy Explicit ltvs _ _))) <- sigs
678
                    , (L _ name) <- names]
679 680
        -- Note the pattern-match on "Explicit"; we only bind
        -- type variables from signatures with an explicit top-level for-all
681 682 683 684
\end{code}


@rnMethodBinds@ is used for the method bindings of a class and an instance
685
declaration.   Like @rnBinds@ but without dependency analysis.
686 687 688 689

NOTA BENE: we record each {\em binder} of a method-bind group as a free variable.
That's crucial when dealing with an instance decl:
\begin{verbatim}
690 691
        instance Foo (T a) where
           op x = ...
692 693 694 695 696 697 698 699
\end{verbatim}
This might be the {\em sole} occurrence of @op@ for an imported class @Foo@,
and unless @op@ occurs we won't treat the type signature of @op@ in the class
decl for @Foo@ as a source of instance-decl gates.  But we should!  Indeed,
in many ways the @op@ in an instance decl is just like an occurrence, not
a binder.

\begin{code}
700 701 702 703
rnMethodBinds :: Name                   -- Class name
              -> (Name -> [Name])       -- Signature tyvar function
              -> LHsBinds RdrName
              -> RnM (LHsBinds Name, FreeVars)
704

dreixel's avatar
dreixel committed
705
rnMethodBinds cls sig_fn binds
706
  = do { checkDupRdrNames meth_names
707 708 709 710 711 712 713 714 715
             -- Check that the same method is not given twice in the
             -- same instance decl      instance C T where
             --                       f x = ...
             --                       g y = ...
             --                       f x = ...
             -- We must use checkDupRdrNames because the Name of the
             -- method is the Name of the class selector, whose SrcSpan
             -- points to the class declaration; and we use rnMethodBinds
             -- for instance decls too
716 717

       ; foldlM do_one (emptyBag, emptyFVs) (bagToList binds) }
718
  where
719
    meth_names  = collectMethodBinders binds
720
    do_one (binds,fvs) bind
dreixel's avatar
dreixel committed
721
       = do { (bind', fvs_bind) <- rnMethodBind cls sig_fn bind
722
            ; return (binds `unionBags` bind', fvs_bind `plusFV` fvs) }
723

Ian Lynagh's avatar
Ian Lynagh committed
724
rnMethodBind :: Name
725 726 727 728 729 730 731
              -> (Name -> [Name])
              -> LHsBindLR RdrName RdrName
              -> RnM (Bag (LHsBindLR Name Name), FreeVars)
rnMethodBind cls sig_fn
             (L loc bind@(FunBind { fun_id = name, fun_infix = is_infix
                                  , fun_matches = MG { mg_alts = matches
                                                     , mg_origin = origin } }))
732
  = setSrcSpan loc $ do
733
    sel_name <- wrapLocM (lookupInstDeclBndr cls (ptext (sLit "method"))) name
734 735 736
    let plain_name = unLoc sel_name
        -- We use the selector name as the binder

737
    (new_matches, fvs) <- bindSigTyVarsFV (sig_fn plain_name) $
738 739 740
                          mapFvRn (rnMatch (FunRhs plain_name is_infix) rnLExpr)
                                           matches
    let new_group = mkMatchGroupName origin new_matches
741

742
    when is_infix $ checkPrecMatch plain_name new_group
743
    return (unitBag (L loc (bind { fun_id      = sel_name
744 745
                                 , fun_matches = new_group
                                 , bind_fvs    = fvs })),
746 747
             fvs `addOneFV` plain_name)
        -- The 'fvs' field isn't used for method binds
748 749

-- Can't handle method pattern-bindings which bind multiple methods.
dreixel's avatar
dreixel committed
750
rnMethodBind _ _ (L loc bind@(PatBind {})) = do
751
    addErrAt loc (methodBindErr bind)
752
    return (emptyBag, emptyFVs)
Ian Lynagh's avatar
Ian Lynagh committed
753

dreixel's avatar
dreixel committed
754
rnMethodBind _ _ b = pprPanic "rnMethodBind" (ppr b)
755 756 757
\end{code}


758

759
%************************************************************************
760
%*                                                                      *
761
\subsubsection[dep-Sigs]{Signatures (and user-pragmas for values)}
762
%*                                                                      *
763 764 765 766 767 768 769 770 771 772 773 774
%************************************************************************

@renameSigs@ checks for:
\begin{enumerate}
\item more than one sig for one thing;
\item signatures given for things not bound here;
\end{enumerate}
%
At the moment we don't gather free-var info from the types in
signatures.  We'd only need this if we wanted to report unused tyvars.

\begin{code}
775 776 777
renameSigs :: HsSigCtxt
           -> [LSig RdrName]
           -> RnM ([LSig Name], FreeVars)
778
-- Renames the signatures and performs error checks
779 780
renameSigs ctxt sigs
  = do  { mapM_ dupSigDeclErr (findDupSigs sigs)
781

782
        ; checkDupMinimalSigs sigs
783

784
        ; (sigs', sig_fvs) <- mapFvRn (wrapLocFstM (renameSig ctxt)) sigs
785

786 787
        ; let (good_sigs, bad_sigs) = partition (okHsSig ctxt) sigs'
        ; mapM_ misplacedSigErr bad_sigs                 -- Misplaced
788

789
        ; return (good_sigs, sig_fvs) }
790 791

----------------------
792
-- We use lookupSigOccRn in the signatures, which is a little bit unsatisfactory
793
-- because this won't work for:
794 795 796
--      instance Foo T where
--        {-# INLINE op #-}
--        Baz.op = ...
797 798 799 800
-- We'll just rename the INLINE prag to refer to whatever other 'op'
-- is in scope.  (I'm assuming that Baz.op isn't in scope unqualified.)
-- Doesn't seem worth much trouble to sort this.

801
renameSig :: HsSigCtxt -> Sig RdrName -> RnM (Sig Name, FreeVars)
802
-- FixitySig is renamed elsewhere.
803
renameSig _ (IdSig x)
804
  = return (IdSig x, emptyFVs)    -- Actually this never occurs
805 806

renameSig ctxt sig@(TypeSig vs ty)
807 808 809
  = do  { new_vs <- mapM (lookupSigOccRn ctxt sig) vs
        ; (new_ty, fvs) <- rnHsSigType (ppr_sig_bndrs vs) ty
        ; return (TypeSig new_vs new_ty, fvs) }
810

811
renameSig ctxt sig@(GenericSig vs ty)
812
  = do  { defaultSigs_on <- xoptM Opt_DefaultSignatures
813
        ; unless defaultSigs_on (addErr (defaultSigErr sig))
814
        ; new_v <- mapM (lookupSigOccRn ctxt sig) vs
815 816
        ; (new_ty, fvs) <- rnHsSigType (ppr_sig_bndrs vs) ty
        ; return (GenericSig new_v new_ty, fvs) }
817

818
renameSig _ (SpecInstSig ty)
819 820
  = do  { (new_ty, fvs) <- rnLHsType SpecInstSigCtx ty
        ; return (SpecInstSig new_ty,fvs) }
821

822 823 824
-- {-# SPECIALISE #-} pragmas can refer to imported Ids
-- so, in the top-level case (when mb_names is Nothing)
-- we use lookupOccRn.  If there's both an imported and a local 'f'
simonpj's avatar
simonpj committed
825
-- then the SPECIALISE pragma is ambiguous, unlike all other signatures
826
renameSig ctxt sig@(SpecSig v ty inl)
827
  = do  { new_v <- case ctxt of
828 829
                     TopSigCtxt {} -> lookupLocatedOccRn v
                     _             -> lookupSigOccRn ctxt sig v
830 831
        ; (new_ty, fvs) <- rnHsSigType (quotes (ppr v)) ty
        ; return (SpecSig new_v new_ty inl, fvs) }
832

833
renameSig ctxt sig@(InlineSig v s)
834 835
  = do  { new_v <- lookupSigOccRn ctxt sig v
        ; return (InlineSig new_v s, emptyFVs) }
836

837
renameSig ctxt sig@(FixSig (FixitySig v f))
838 839
  = do  { new_v <- lookupSigOccRn ctxt sig v
        ; return (FixSig (FixitySig new_v f), emptyFVs) }
840

841 842 843 844
renameSig ctxt sig@(MinimalSig bf)
  = do new_bf <- traverse (lookupSigOccRn ctxt sig) bf
       return (MinimalSig new_bf, emptyFVs)

Gergő Érdi's avatar
Gergő Érdi committed
845
renameSig ctxt sig@(PatSynSig v args ty prov req)
846
  = do  v' <- lookupSigOccRn ctxt sig v
Gergő Érdi's avatar
Gergő Érdi committed
847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862
        let doc = quotes (ppr v)
            rn_type = rnHsSigType doc
        (ty', fvs1) <- rn_type ty
        (args', fvs2) <- case args of
            PrefixPatSyn tys ->
                do (tys, fvs) <- unzip <$> mapM rn_type tys
                   return (PrefixPatSyn tys, plusFVs fvs)
            InfixPatSyn left right ->
                do (left', fvs1) <- rn_type left
                   (right', fvs2) <- rn_type right
                   return (InfixPatSyn left' right', fvs1 `plusFV` fvs2)
        (prov', fvs3) <- rnContext (TypeSigCtx doc) prov
        (req', fvs4) <- rnContext (TypeSigCtx doc) req
        let fvs = plusFVs [fvs1, fvs2, fvs3, fvs4]
        return (PatSynSig v' args' ty' prov' req', fvs)

863 864
ppr_sig_bndrs :: [Located RdrName] -> SDoc
ppr_sig_bndrs bs = quotes (pprWithCommas ppr bs)
865 866

okHsSig :: HsSigCtxt -> LSig a -> Bool
867
okHsSig ctxt (L _ sig)
868 869 870 871
  = case (sig, ctxt) of
     (GenericSig {}, ClsDeclCtxt {}) -> True
     (GenericSig {}, _)              -> False

872
     (TypeSig {}, _)              -> True
873

Gergő Érdi's avatar
Gergő Érdi committed
874 875 876
     (PatSynSig {}, TopSigCtxt{}) -> True
     (PatSynSig {}, _)            -> False

877 878 879
     (FixSig {}, InstDeclCtxt {}) -> False
     (FixSig {}, _)               -> True

880
     (IdSig {}, TopSigCtxt {})   -> True
881 882
     (IdSig {}, InstDeclCtxt {}) -> True
     (IdSig {}, _)               -> False
883 884 885 886

     (InlineSig {}, HsBootCtxt) -> False
     (InlineSig {}, _)          -> True

887
     (SpecSig {}, TopSigCtxt {})    -> True
888 889 890 891 892 893
     (SpecSig {}, LocalBindCtxt {}) -> True
     (SpecSig {}, InstDeclCtxt {})  -> True
     (SpecSig {}, _)                -> False

     (SpecInstSig {}, InstDeclCtxt {}) -> True
     (SpecInstSig {}, _)               -> False
894

895 896 897
     (MinimalSig {}, ClsDeclCtxt {}) -> True
     (MinimalSig {}, _)              -> False

898 899
-------------------
findDupSigs :: [LSig RdrName] -> [[(Located RdrName, Sig RdrName)]]
900
-- Check for duplicates on RdrName version,
901 902
-- because renamed version has unboundName for
-- not-in-scope binders, which gives bogus dup-sig errors
903
-- NB: in a class decl, a 'generic' sig is not considered
904
--     equal to an ordinary sig, so we allow, say
905 906
--           class C a where
--             op :: a -> a
907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922
--             default op :: Eq a => a -> a
findDupSigs sigs
  = findDupsEq matching_sig (concatMap (expand_sig . unLoc) sigs)
  where
    expand_sig sig@(FixSig (FixitySig n _)) = [(n,sig)]
    expand_sig sig@(InlineSig n _)          = [(n,sig)]
    expand_sig sig@(TypeSig  ns _)   = [(n,sig) | n <- ns]
    expand_sig sig@(GenericSig ns _) = [(n,sig) | n <- ns]
    expand_sig _ = []

    matching_sig (L _ n1,sig1) (L _ n2,sig2) = n1 == n2 && mtch sig1 sig2
    mtch (FixSig {})     (FixSig {})     = True
    mtch (InlineSig {})  (InlineSig {})  = True
    mtch (TypeSig {})    (TypeSig {})    = True
    mtch (GenericSig {}) (GenericSig {}) = True
    mtch _ _ = False
923 924 925 926 927 928 929

-- Warn about multiple MINIMAL signatures
checkDupMinimalSigs :: [LSig RdrName] -> RnM ()
checkDupMinimalSigs sigs
  = case filter isMinimalLSig sigs of
      minSigs@(_:_:_) -> dupMinimalSigErr minSigs
      _ -> return ()
930 931 932
\end{code}


Thomas Schilling's avatar
Thomas Schilling committed
933
%************************************************************************
934
%*                                                                      *
935
\subsection{Match}
936
%*                                                                      *
Thomas Schilling's avatar
Thomas Schilling committed
937
%************************************************************************
938 939

\begin{code}
Simon Peyton Jones's avatar