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