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