Global renamings in HsSyn
[ghc-hetmet.git] / compiler / hsSyn / HsBinds.lhs
1 %
2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
3 %
4 \section[HsBinds]{Abstract syntax: top-level bindings and signatures}
5
6 Datatype for: @BindGroup@, @Bind@, @Sig@, @Bind@.
7
8 \begin{code}
9 module HsBinds where
10
11 #include "HsVersions.h"
12
13 import {-# SOURCE #-} HsExpr ( HsExpr, pprExpr, LHsExpr,
14                                MatchGroup, pprFunBind,
15                                GRHSs, pprPatBind )
16 import {-# SOURCE #-} HsPat  ( LPat )
17
18 import HsTypes          ( LHsType, PostTcType )
19 import PprCore          ( {- instances -} )
20 import Coercion         ( Coercion )
21 import Type             ( Type, pprParendType )
22 import Name             ( Name )
23 import NameSet          ( NameSet, elemNameSet )
24 import BasicTypes       ( IPName, RecFlag(..), InlineSpec(..), Fixity )
25 import Outputable       
26 import SrcLoc           ( Located(..), SrcSpan, unLoc )
27 import Util             ( sortLe )
28 import Var              ( TyVar, DictId, Id, Var )
29 import Bag              ( Bag, emptyBag, isEmptyBag, bagToList, unionBags, unionManyBags )
30 \end{code}
31
32 %************************************************************************
33 %*                                                                      *
34 \subsection{Bindings: @BindGroup@}
35 %*                                                                      *
36 %************************************************************************
37
38 Global bindings (where clauses)
39
40 \begin{code}
41 data HsLocalBinds id    -- Bindings in a 'let' expression
42                         -- or a 'where' clause
43   = HsValBinds (HsValBinds id)
44   | HsIPBinds  (HsIPBinds id)
45
46   | EmptyLocalBinds
47
48 data HsValBinds id      -- Value bindings (not implicit parameters)
49   = ValBindsIn                          -- Before typechecking
50         (LHsBinds id) [LSig id]         -- Not dependency analysed
51                                         -- Recursive by default
52
53   | ValBindsOut                         -- After renaming
54         [(RecFlag, LHsBinds id)]        -- Dependency analysed
55         [LSig Name]
56
57 type LHsBinds id  = Bag (LHsBind id)
58 type DictBinds id = LHsBinds id         -- Used for dictionary or method bindings
59 type LHsBind  id  = Located (HsBind id)
60
61 data HsBind id
62   = FunBind {   -- FunBind is used for both functions   f x = e
63                 -- and variables                        f = \x -> e
64 -- Reason 1: Special case for type inference: see TcBinds.tcMonoBinds
65 --
66 -- Reason 2: instance decls can only have FunBinds, which is convenient
67 --           If you change this, you'll need tochange e.g. rnMethodBinds
68
69 -- But note that the form       f :: a->a = ...
70 -- parses as a pattern binding, just like
71 --                      (f :: a -> a) = ... 
72
73         fun_id :: Located id,
74
75         fun_infix :: Bool,      -- True => infix declaration
76
77         fun_matches :: MatchGroup id,   -- The payload
78
79         fun_co_fn :: HsWrapper, -- Coercion from the type of the MatchGroup to the type of
80                                 -- the Id.  Example:
81                                 --      f :: Int -> forall a. a -> a
82                                 --      f x y = y
83                                 -- Then the MatchGroup will have type (Int -> a' -> a')
84                                 -- (with a free type variable a').  The coercion will take
85                                 -- a CoreExpr of this type and convert it to a CoreExpr of
86                                 -- type         Int -> forall a'. a' -> a'
87                                 -- Notice that the coercion captures the free a'.
88
89         bind_fvs :: NameSet     -- After the renamer, this contains a superset of the 
90                                 -- Names of the other binders in this binding group that 
91                                 -- are free in the RHS of the defn
92                                 -- Before renaming, and after typechecking, 
93                                 -- the field is unused; it's just an error thunk
94     }
95
96   | PatBind {   -- The pattern is never a simple variable;
97                 -- That case is done by FunBind
98         pat_lhs    :: LPat id,
99         pat_rhs    :: GRHSs id,
100         pat_rhs_ty :: PostTcType,       -- Type of the GRHSs
101         bind_fvs   :: NameSet           -- Same as for FunBind
102     }
103
104   | VarBind {   -- Dictionary binding and suchlike 
105         var_id :: id,           -- All VarBinds are introduced by the type checker
106         var_rhs :: LHsExpr id   -- Located only for consistency
107     }
108
109   | AbsBinds {                                  -- Binds abstraction; TRANSLATION
110         abs_tvs     :: [TyVar],  
111         abs_dicts   :: [DictId],
112         abs_exports :: [([TyVar], id, id, [Prag])],     -- (tvs, poly_id, mono_id, prags)
113         abs_binds   :: LHsBinds id              -- The dictionary bindings and typechecked user bindings
114                                                 -- mixed up together; you can tell the dict bindings because
115                                                 -- they are all VarBinds
116     }
117         -- Consider (AbsBinds tvs ds [(ftvs, poly_f, mono_f) binds]
118         -- 
119         -- Creates bindings for (polymorphic, overloaded) poly_f
120         -- in terms of monomorphic, non-overloaded mono_f
121         --
122         -- Invariants: 
123         --      1. 'binds' binds mono_f
124         --      2. ftvs is a subset of tvs
125         --      3. ftvs includes all tyvars free in ds
126         --
127         -- See section 9 of static semantics paper for more details.
128         -- (You can get a PhD for explaining the True Meaning
129         --  of this last construct.)
130
131 placeHolderNames :: NameSet
132 -- Used for the NameSet in FunBind and PatBind prior to the renamer
133 placeHolderNames = panic "placeHolderNames"
134
135 ------------
136 instance OutputableBndr id => Outputable (HsLocalBinds id) where
137   ppr (HsValBinds bs) = ppr bs
138   ppr (HsIPBinds bs)  = ppr bs
139   ppr EmptyLocalBinds = empty
140
141 instance OutputableBndr id => Outputable (HsValBinds id) where
142   ppr (ValBindsIn binds sigs)
143    = pprValBindsForUser binds sigs
144
145   ppr (ValBindsOut sccs sigs) 
146     = getPprStyle $ \ sty ->
147       if debugStyle sty then    -- Print with sccs showing
148         vcat (map ppr sigs) $$ vcat (map ppr_scc sccs)
149      else
150         pprValBindsForUser (unionManyBags (map snd sccs)) sigs
151    where
152      ppr_scc (rec_flag, binds) = pp_rec rec_flag <+> pprLHsBinds binds
153      pp_rec Recursive    = ptext SLIT("rec")
154      pp_rec NonRecursive = ptext SLIT("nonrec")
155
156 --  *not* pprLHsBinds because we don't want braces; 'let' and
157 -- 'where' include a list of HsBindGroups and we don't want
158 -- several groups of bindings each with braces around.
159 -- Sort by location before printing
160 pprValBindsForUser :: (OutputableBndr id1, OutputableBndr id2)
161                    => LHsBinds id1 -> [LSig id2] -> SDoc
162 pprValBindsForUser binds sigs
163   = vcat (map snd (sort_by_loc decls))
164   where
165
166     decls :: [(SrcSpan, SDoc)]
167     decls = [(loc, ppr sig)  | L loc sig <- sigs] ++
168             [(loc, ppr bind) | L loc bind <- bagToList binds]
169
170     sort_by_loc decls = sortLe (\(l1,_) (l2,_) -> l1 <= l2) decls
171
172 pprLHsBinds :: OutputableBndr id => LHsBinds id -> SDoc
173 pprLHsBinds binds 
174   | isEmptyLHsBinds binds = empty
175   | otherwise = lbrace <+> vcat (map ppr (bagToList binds)) <+> rbrace
176
177 ------------
178 emptyLocalBinds :: HsLocalBinds a
179 emptyLocalBinds = EmptyLocalBinds
180
181 isEmptyLocalBinds :: HsLocalBinds a -> Bool
182 isEmptyLocalBinds (HsValBinds ds) = isEmptyValBinds ds
183 isEmptyLocalBinds (HsIPBinds ds)  = isEmptyIPBinds ds
184 isEmptyLocalBinds EmptyLocalBinds = True
185
186 isEmptyValBinds :: HsValBinds a -> Bool
187 isEmptyValBinds (ValBindsIn ds sigs)  = isEmptyLHsBinds ds && null sigs
188 isEmptyValBinds (ValBindsOut ds sigs) = null ds && null sigs
189
190 emptyValBindsIn, emptyValBindsOut :: HsValBinds a
191 emptyValBindsIn  = ValBindsIn emptyBag []
192 emptyValBindsOut = ValBindsOut []      []
193
194 emptyLHsBinds :: LHsBinds id
195 emptyLHsBinds = emptyBag
196
197 isEmptyLHsBinds :: LHsBinds id -> Bool
198 isEmptyLHsBinds = isEmptyBag
199
200 ------------
201 plusHsValBinds :: HsValBinds a -> HsValBinds a -> HsValBinds a
202 plusHsValBinds (ValBindsIn ds1 sigs1) (ValBindsIn ds2 sigs2)
203   = ValBindsIn (ds1 `unionBags` ds2) (sigs1 ++ sigs2)
204 plusHsValBinds (ValBindsOut ds1 sigs1) (ValBindsOut ds2 sigs2)
205   = ValBindsOut (ds1 ++ ds2) (sigs1 ++ sigs2)
206 \end{code}
207
208 What AbsBinds means
209 ~~~~~~~~~~~~~~~~~~~
210          AbsBinds tvs
211                   [d1,d2]
212                   [(tvs1, f1p, f1m), 
213                    (tvs2, f2p, f2m)]
214                   BIND
215 means
216
217         f1p = /\ tvs -> \ [d1,d2] -> letrec DBINDS and BIND 
218                                       in fm
219
220         gp = ...same again, with gm instead of fm
221
222 This is a pretty bad translation, because it duplicates all the bindings.
223 So the desugarer tries to do a better job:
224
225         fp = /\ [a,b] -> \ [d1,d2] -> case tp [a,b] [d1,d2] of
226                                         (fm,gm) -> fm
227         ..ditto for gp..
228
229         tp = /\ [a,b] -> \ [d1,d2] -> letrec DBINDS and BIND 
230                                        in (fm,gm)
231
232 \begin{code}
233 instance OutputableBndr id => Outputable (HsBind id) where
234     ppr mbind = ppr_monobind mbind
235
236 ppr_monobind :: OutputableBndr id => HsBind id -> SDoc
237
238 ppr_monobind (PatBind { pat_lhs = pat, pat_rhs = grhss })      = pprPatBind pat grhss
239 ppr_monobind (VarBind { var_id = var, var_rhs = rhs })         = ppr var <+> equals <+> pprExpr (unLoc rhs)
240 ppr_monobind (FunBind { fun_id = fun, fun_matches = matches }) = pprFunBind (unLoc fun) matches
241       -- ToDo: print infix if appropriate
242
243 ppr_monobind (AbsBinds { abs_tvs = tyvars, abs_dicts = dictvars, 
244                          abs_exports = exports, abs_binds = val_binds })
245      = sep [ptext SLIT("AbsBinds"),
246             brackets (interpp'SP tyvars),
247             brackets (interpp'SP dictvars),
248             brackets (sep (punctuate comma (map ppr_exp exports)))]
249        $$
250        nest 2 ( vcat [pprBndr LetBind x | (_,x,_,_) <- exports]
251                         -- Print type signatures
252                 $$ pprLHsBinds val_binds )
253   where
254     ppr_exp (tvs, gbl, lcl, prags)
255         = vcat [ppr gbl <+> ptext SLIT("<=") <+> ppr tvs <+> ppr lcl,
256                 nest 2 (vcat (map (pprPrag gbl) prags))]
257 \end{code}
258
259 %************************************************************************
260 %*                                                                      *
261                 Implicit parameter bindings
262 %*                                                                      *
263 %************************************************************************
264
265 \begin{code}
266 data HsIPBinds id
267   = IPBinds 
268         [LIPBind id] 
269         (DictBinds id)  -- Only in typechecker output; binds 
270                         -- uses of the implicit parameters
271
272 isEmptyIPBinds :: HsIPBinds id -> Bool
273 isEmptyIPBinds (IPBinds is ds) = null is && isEmptyBag ds
274
275 type LIPBind id = Located (IPBind id)
276
277 -- | Implicit parameter bindings.
278 data IPBind id
279   = IPBind
280         (IPName id)
281         (LHsExpr id)
282
283 instance (OutputableBndr id) => Outputable (HsIPBinds id) where
284   ppr (IPBinds bs ds) = vcat (map ppr bs) 
285                         $$ pprLHsBinds ds
286
287 instance (OutputableBndr id) => Outputable (IPBind id) where
288   ppr (IPBind id rhs) = pprBndr LetBind id <+> equals <+> pprExpr (unLoc rhs)
289 \end{code}
290
291
292 %************************************************************************
293 %*                                                                      *
294 \subsection{Coercion functions}
295 %*                                                                      *
296 %************************************************************************
297
298 \begin{code}
299 -- A HsWrapper is an expression with a hole in it
300 -- We need coercions to have concrete form so that we can zonk them
301
302 data HsWrapper
303   = WpHole                      -- The identity coercion
304
305   | WpCompose HsWrapper HsWrapper       -- (\a1..an. []) `WpCompose` (\x1..xn. [])
306                                 --      = (\a1..an \x1..xn. [])
307
308   | WpCo Coercion               -- A cast:  [] `cast` co
309                                 -- Guaranteedn not the identity coercion
310
311   | WpApp Var                   -- [] x; the xi are dicts or coercions
312   | WpTyApp Type                -- [] t
313   | WpLam Id                    -- \x. []; the xi are dicts or coercions
314   | WpTyLam TyVar               -- \a. []
315
316         -- Non-empty bindings, so that the identity coercion
317         -- is always exactly WpHole
318   | WpLet (LHsBinds Id)         -- let binds in []
319                                 -- (would be nicer to be core bindings)
320
321 instance Outputable HsWrapper where 
322   ppr co_fn = pprHsWrapper (ptext SLIT("<>")) co_fn
323
324 pprHsWrapper :: SDoc -> HsWrapper -> SDoc
325 pprHsWrapper it WpHole = it
326 pprHsWrapper it (WpCompose f1 f2) = pprHsWrapper (pprHsWrapper it f2) f1
327 pprHsWrapper it (WpCo co)     = it <+> ptext SLIT("`cast`") <+> pprParendType co
328 pprHsWrapper it (WpApp id)    = it <+> ppr id
329 pprHsWrapper it (WpTyApp ty)  = it <+> ptext SLIT("@") <+> pprParendType ty
330 pprHsWrapper it (WpLam id)    = ptext SLIT("\\") <> pprBndr LambdaBind id <> dot <+> it
331 pprHsWrapper it (WpTyLam tv)  = ptext SLIT("/\\") <> pprBndr LambdaBind tv <> dot <+> it
332 pprHsWrapper it (WpLet binds) = sep [ptext SLIT("let") <+> braces (ppr binds), it]
333
334 (<.>) :: HsWrapper -> HsWrapper -> HsWrapper
335 WpHole <.> c = c
336 c <.> WpHole = c
337 c1 <.> c2    = c1 `WpCompose` c2
338
339 mkWpTyApps :: [Type] -> HsWrapper
340 mkWpTyApps tys = mk_co_fn WpTyApp (reverse tys)
341
342 mkWpApps :: [Id] -> HsWrapper
343 mkWpApps ids = mk_co_fn WpApp (reverse ids)
344
345 mkWpTyLams :: [TyVar] -> HsWrapper
346 mkWpTyLams ids = mk_co_fn WpTyLam ids
347
348 mkWpLams :: [Id] -> HsWrapper
349 mkWpLams ids = mk_co_fn WpLam ids
350
351 mk_co_fn :: (a -> HsWrapper) -> [a] -> HsWrapper
352 mk_co_fn f as = foldr (WpCompose . f) WpHole as
353
354 idHsWrapper :: HsWrapper
355 idHsWrapper = WpHole
356
357 isIdHsWrapper :: HsWrapper -> Bool
358 isIdHsWrapper WpHole = True
359 isIdHsWrapper other  = False
360 \end{code}
361
362
363 %************************************************************************
364 %*                                                                      *
365 \subsection{@Sig@: type signatures and value-modifying user pragmas}
366 %*                                                                      *
367 %************************************************************************
368
369 It is convenient to lump ``value-modifying'' user-pragmas (e.g.,
370 ``specialise this function to these four types...'') in with type
371 signatures.  Then all the machinery to move them into place, etc.,
372 serves for both.
373
374 \begin{code}
375 type LSig name = Located (Sig name)
376
377 data Sig name
378   = TypeSig     (Located name)  -- A bog-std type signature
379                 (LHsType name)
380
381   | SpecSig     (Located name)  -- Specialise a function or datatype ...
382                 (LHsType name)  -- ... to these types
383                 InlineSpec
384
385   | InlineSig   (Located name)  -- Function name
386                 InlineSpec
387
388   | SpecInstSig (LHsType name)  -- (Class tys); should be a specialisation of the 
389                                 -- current instance decl
390
391   | FixSig      (FixitySig name)        -- Fixity declaration
392
393 type LFixitySig name = Located (FixitySig name)
394 data FixitySig name = FixitySig (Located name) Fixity 
395
396 -- A Prag conveys pragmas from the type checker to the desugarer
397 data Prag 
398   = InlinePrag 
399         InlineSpec
400
401   | SpecPrag   
402         (HsExpr Id)     -- An expression, of the given specialised type, which
403         PostTcType      -- specialises the polymorphic function
404         [Id]            -- Dicts mentioned free in the expression
405         InlineSpec      -- Inlining spec for the specialised function
406
407 isInlinePrag (InlinePrag _) = True
408 isInlinePrag prag           = False
409
410 isSpecPrag (SpecPrag _ _ _ _) = True
411 isSpecPrag prag               = False
412 \end{code}
413
414 \begin{code}
415 okBindSig :: NameSet -> LSig Name -> Bool
416 okBindSig ns sig = sigForThisGroup ns sig
417
418 okHsBootSig :: LSig Name -> Bool
419 okHsBootSig (L _ (TypeSig  _ _)) = True
420 okHsBootSig (L _ (FixSig _))     = True
421 okHsBootSig sig                  = False
422
423 okClsDclSig :: LSig Name -> Bool
424 okClsDclSig (L _ (SpecInstSig _)) = False
425 okClsDclSig sig                   = True        -- All others OK
426
427 okInstDclSig :: NameSet -> LSig Name -> Bool
428 okInstDclSig ns lsig@(L _ sig) = ok ns sig
429   where
430     ok ns (TypeSig _ _)   = False
431     ok ns (FixSig _)      = False
432     ok ns (SpecInstSig _) = True
433     ok ns sig             = sigForThisGroup ns lsig
434
435 sigForThisGroup :: NameSet -> LSig Name -> Bool
436 sigForThisGroup ns sig
437   = case sigName sig of
438         Nothing -> False
439         Just n  -> n `elemNameSet` ns
440
441 sigName :: LSig name -> Maybe name
442 sigName (L _ sig) = f sig
443  where
444     f (TypeSig   n _)          = Just (unLoc n)
445     f (SpecSig   n _ _)        = Just (unLoc n)
446     f (InlineSig n _)          = Just (unLoc n)
447     f (FixSig (FixitySig n _)) = Just (unLoc n)
448     f other                     = Nothing
449
450 isFixityLSig :: LSig name -> Bool
451 isFixityLSig (L _ (FixSig {})) = True
452 isFixityLSig _                 = False
453
454 isVanillaLSig :: LSig name -> Bool
455 isVanillaLSig (L _(TypeSig {})) = True
456 isVanillaLSig sig               = False
457
458 isSpecLSig :: LSig name -> Bool
459 isSpecLSig (L _(SpecSig {})) = True
460 isSpecLSig sig               = False
461
462 isSpecInstLSig (L _ (SpecInstSig {})) = True
463 isSpecInstLSig sig                    = False
464
465 isPragLSig :: LSig name -> Bool
466         -- Identifies pragmas 
467 isPragLSig (L _ (SpecSig {}))   = True
468 isPragLSig (L _ (InlineSig {})) = True
469 isPragLSig other                = False
470
471 isInlineLSig :: LSig name -> Bool
472         -- Identifies inline pragmas 
473 isInlineLSig (L _ (InlineSig {})) = True
474 isInlineLSig other                = False
475
476 hsSigDoc (TypeSig {})           = ptext SLIT("type signature")
477 hsSigDoc (SpecSig {})           = ptext SLIT("SPECIALISE pragma")
478 hsSigDoc (InlineSig _ spec)     = ppr spec <+> ptext SLIT("pragma")
479 hsSigDoc (SpecInstSig {})       = ptext SLIT("SPECIALISE instance pragma")
480 hsSigDoc (FixSig {})            = ptext SLIT("fixity declaration")
481 \end{code}
482
483 Signature equality is used when checking for duplicate signatures
484
485 \begin{code}
486 eqHsSig :: LSig Name -> LSig Name -> Bool
487 eqHsSig (L _ (FixSig (FixitySig n1 _))) (L _ (FixSig (FixitySig n2 _))) = unLoc n1 == unLoc n2
488 eqHsSig (L _ (TypeSig n1 _))            (L _ (TypeSig n2 _))            = unLoc n1 == unLoc n2
489 eqHsSig (L _ (InlineSig n1 s1)) (L _ (InlineSig n2 s2))                 = s1 == s2 && unLoc n1 == unLoc n2
490         -- For specialisations, we don't have equality over
491         -- HsType, so it's not convenient to spot duplicate 
492         -- specialisations here.  Check for this later, when we're in Type land
493 eqHsSig _other1 _other2 = False
494 \end{code}
495
496 \begin{code}
497 instance (OutputableBndr name) => Outputable (Sig name) where
498     ppr sig = ppr_sig sig
499
500 ppr_sig :: OutputableBndr name => Sig name -> SDoc
501 ppr_sig (TypeSig var ty)          = pprVarSig (unLoc var) ty
502 ppr_sig (FixSig fix_sig)          = ppr fix_sig
503 ppr_sig (SpecSig var ty inl)      = pragBrackets (pprSpec var ty inl)
504 ppr_sig (InlineSig var inl)       = pragBrackets (ppr inl <+> ppr var)
505 ppr_sig (SpecInstSig ty)          = pragBrackets (ptext SLIT("SPECIALIZE instance") <+> ppr ty)
506
507 instance Outputable name => Outputable (FixitySig name) where
508   ppr (FixitySig name fixity) = sep [ppr fixity, ppr name]
509
510 pragBrackets :: SDoc -> SDoc
511 pragBrackets doc = ptext SLIT("{-#") <+> doc <+> ptext SLIT("#-}") 
512
513 pprVarSig :: (Outputable id, Outputable ty) => id -> ty -> SDoc
514 pprVarSig var ty = sep [ppr var <+> dcolon, nest 2 (ppr ty)]
515
516 pprSpec :: (Outputable id, Outputable ty) => id -> ty -> InlineSpec -> SDoc
517 pprSpec var ty inl = sep [ptext SLIT("SPECIALIZE") <+> ppr inl <+> pprVarSig var ty]
518
519 pprPrag :: Outputable id => id -> Prag -> SDoc
520 pprPrag var (InlinePrag inl)         = ppr inl <+> ppr var
521 pprPrag var (SpecPrag expr ty _ inl) = pprSpec var ty inl
522 \end{code}