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