Print infix function definitions correctly in HsSyn
[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, fun_infix = inf,
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) inf matches
252
253 ppr_monobind (AbsBinds { abs_tvs = tyvars, abs_dicts = dictvars, 
254                          abs_exports = exports, abs_binds = val_binds })
255      = sep [ptext SLIT("AbsBinds"),
256             brackets (interpp'SP tyvars),
257             brackets (interpp'SP dictvars),
258             brackets (sep (punctuate comma (map ppr_exp exports)))]
259        $$
260        nest 2 ( vcat [pprBndr LetBind x | (_,x,_,_) <- exports]
261                         -- Print type signatures
262                 $$ pprLHsBinds val_binds )
263   where
264     ppr_exp (tvs, gbl, lcl, prags)
265         = vcat [ppr gbl <+> ptext SLIT("<=") <+> ppr tvs <+> ppr lcl,
266                 nest 2 (vcat (map (pprPrag gbl) prags))]
267 \end{code}
268
269 %************************************************************************
270 %*                                                                      *
271                 Implicit parameter bindings
272 %*                                                                      *
273 %************************************************************************
274
275 \begin{code}
276 data HsIPBinds id
277   = IPBinds 
278         [LIPBind id] 
279         (DictBinds id)  -- Only in typechecker output; binds 
280                         -- uses of the implicit parameters
281
282 isEmptyIPBinds :: HsIPBinds id -> Bool
283 isEmptyIPBinds (IPBinds is ds) = null is && isEmptyBag ds
284
285 type LIPBind id = Located (IPBind id)
286
287 -- | Implicit parameter bindings.
288 data IPBind id
289   = IPBind
290         (IPName id)
291         (LHsExpr id)
292
293 instance (OutputableBndr id) => Outputable (HsIPBinds id) where
294   ppr (IPBinds bs ds) = pprDeeperList vcat (map ppr bs) 
295                         $$ pprLHsBinds ds
296
297 instance (OutputableBndr id) => Outputable (IPBind id) where
298   ppr (IPBind id rhs) = pprBndr LetBind id <+> equals <+> pprExpr (unLoc rhs)
299 \end{code}
300
301
302 %************************************************************************
303 %*                                                                      *
304 \subsection{Coercion functions}
305 %*                                                                      *
306 %************************************************************************
307
308 \begin{code}
309 -- A HsWrapper is an expression with a hole in it
310 -- We need coercions to have concrete form so that we can zonk them
311
312 data HsWrapper
313   = WpHole                      -- The identity coercion
314
315   | WpCompose HsWrapper HsWrapper       -- (\a1..an. []) `WpCompose` (\x1..xn. [])
316                                 --      = (\a1..an \x1..xn. [])
317
318   | WpCo Coercion               -- A cast:  [] `cast` co
319                                 -- Guaranteedn not the identity coercion
320
321   | WpApp Var                   -- [] d         the 'd' is a type-class dictionary
322   | WpTyApp Type                -- [] t         the 't' is a type or corecion
323   | WpLam Id                    -- \d. []       the 'd' is a type-class dictionary
324   | WpTyLam TyVar               -- \a. []       the 'a' is a type or coercion variable
325
326         -- Non-empty bindings, so that the identity coercion
327         -- is always exactly WpHole
328   | WpLet (LHsBinds Id)         -- let binds in []
329                                 -- (would be nicer to be core bindings)
330
331 instance Outputable HsWrapper where 
332   ppr co_fn = pprHsWrapper (ptext SLIT("<>")) co_fn
333
334 pprHsWrapper :: SDoc -> HsWrapper -> SDoc
335 pprHsWrapper it WpHole = it
336 pprHsWrapper it (WpCompose f1 f2) = pprHsWrapper (pprHsWrapper it f2) f1
337 pprHsWrapper it (WpCo co)     = it <+> ptext SLIT("`cast`") <+> pprParendType co
338 pprHsWrapper it (WpApp id)    = it <+> ppr id
339 pprHsWrapper it (WpTyApp ty)  = it <+> ptext SLIT("@") <+> pprParendType ty
340 pprHsWrapper it (WpLam id)    = ptext SLIT("\\") <> pprBndr LambdaBind id <> dot <+> it
341 pprHsWrapper it (WpTyLam tv)  = ptext SLIT("/\\") <> pprBndr LambdaBind tv <> dot <+> it
342 pprHsWrapper it (WpLet binds) = sep [ptext SLIT("let") <+> braces (ppr binds), it]
343
344 (<.>) :: HsWrapper -> HsWrapper -> HsWrapper
345 WpHole <.> c = c
346 c <.> WpHole = c
347 c1 <.> c2    = c1 `WpCompose` c2
348
349 mkWpTyApps :: [Type] -> HsWrapper
350 mkWpTyApps tys = mk_co_fn WpTyApp (reverse tys)
351
352 mkWpApps :: [Id] -> HsWrapper
353 mkWpApps ids = mk_co_fn WpApp (reverse ids)
354
355 mkWpTyLams :: [TyVar] -> HsWrapper
356 mkWpTyLams ids = mk_co_fn WpTyLam ids
357
358 mkWpLams :: [Id] -> HsWrapper
359 mkWpLams ids = mk_co_fn WpLam ids
360
361 mk_co_fn :: (a -> HsWrapper) -> [a] -> HsWrapper
362 mk_co_fn f as = foldr (WpCompose . f) WpHole as
363
364 idHsWrapper :: HsWrapper
365 idHsWrapper = WpHole
366
367 isIdHsWrapper :: HsWrapper -> Bool
368 isIdHsWrapper WpHole = True
369 isIdHsWrapper other  = False
370 \end{code}
371
372
373 %************************************************************************
374 %*                                                                      *
375 \subsection{@Sig@: type signatures and value-modifying user pragmas}
376 %*                                                                      *
377 %************************************************************************
378
379 It is convenient to lump ``value-modifying'' user-pragmas (e.g.,
380 ``specialise this function to these four types...'') in with type
381 signatures.  Then all the machinery to move them into place, etc.,
382 serves for both.
383
384 \begin{code}
385 type LSig name = Located (Sig name)
386
387 data Sig name   -- Signatures and pragmas
388   =     -- An ordinary type signature
389         -- f :: Num a => a -> a
390     TypeSig     (Located name)  -- A bog-std type signature
391                 (LHsType name)
392
393         -- An ordinary fixity declaration
394         --      infixl *** 8
395   | FixSig      (FixitySig name)        -- Fixity declaration
396
397         -- An inline pragma
398         -- {#- INLINE f #-}
399   | InlineSig   (Located name)  -- Function name
400                 InlineSpec
401
402         -- A specialisation pragma
403         -- {-# SPECIALISE f :: Int -> Int #-}
404   | SpecSig     (Located name)  -- Specialise a function or datatype ...
405                 (LHsType name)  -- ... to these types
406                 InlineSpec
407
408         -- A specialisation pragma for instance declarations only
409         -- {-# SPECIALISE instance Eq [Int] #-}
410   | SpecInstSig (LHsType name)  -- (Class tys); should be a specialisation of the 
411                                 -- current instance decl
412
413
414 type LFixitySig name = Located (FixitySig name)
415 data FixitySig name = FixitySig (Located name) Fixity 
416
417 -- A Prag conveys pragmas from the type checker to the desugarer
418 type LPrag = Located Prag
419 data Prag 
420   = InlinePrag 
421         InlineSpec
422
423   | SpecPrag   
424         (HsExpr Id)     -- An expression, of the given specialised type, which
425         PostTcType      -- specialises the polymorphic function
426         [Id]            -- Dicts mentioned free in the expression
427                         --   Apr07: I think this is pretty useless
428                         --          see Note [Const rule dicts] in DsBinds
429         InlineSpec      -- Inlining spec for the specialised function
430
431 isInlinePrag (InlinePrag _) = True
432 isInlinePrag prag           = False
433
434 isSpecPrag (SpecPrag {}) = True
435 isSpecPrag prag          = False
436 \end{code}
437
438 \begin{code}
439 okBindSig :: NameSet -> LSig Name -> Bool
440 okBindSig ns sig = sigForThisGroup ns sig
441
442 okHsBootSig :: LSig Name -> Bool
443 okHsBootSig (L _ (TypeSig  _ _)) = True
444 okHsBootSig (L _ (FixSig _))     = True
445 okHsBootSig sig                  = False
446
447 okClsDclSig :: LSig Name -> Bool
448 okClsDclSig (L _ (SpecInstSig _)) = False
449 okClsDclSig sig                   = True        -- All others OK
450
451 okInstDclSig :: NameSet -> LSig Name -> Bool
452 okInstDclSig ns lsig@(L _ sig) = ok ns sig
453   where
454     ok ns (TypeSig _ _)   = False
455     ok ns (FixSig _)      = False
456     ok ns (SpecInstSig _) = True
457     ok ns sig             = sigForThisGroup ns lsig
458
459 sigForThisGroup :: NameSet -> LSig Name -> Bool
460 sigForThisGroup ns sig
461   = case sigName sig of
462         Nothing -> False
463         Just n  -> n `elemNameSet` ns
464
465 sigName :: LSig name -> Maybe name
466 sigName (L _ sig) = sigNameNoLoc sig
467
468 sigNameNoLoc :: Sig name -> Maybe name    
469 sigNameNoLoc (TypeSig   n _)          = Just (unLoc n)
470 sigNameNoLoc (SpecSig   n _ _)        = Just (unLoc n)
471 sigNameNoLoc (InlineSig n _)          = Just (unLoc n)
472 sigNameNoLoc (FixSig (FixitySig n _)) = Just (unLoc n)
473 sigNameNoLoc other                              = Nothing
474
475 isFixityLSig :: LSig name -> Bool
476 isFixityLSig (L _ (FixSig {})) = True
477 isFixityLSig _                 = False
478
479 isVanillaLSig :: LSig name -> Bool
480 isVanillaLSig (L _(TypeSig {})) = True
481 isVanillaLSig sig               = False
482
483 isSpecLSig :: LSig name -> Bool
484 isSpecLSig (L _(SpecSig {})) = True
485 isSpecLSig sig               = False
486
487 isSpecInstLSig (L _ (SpecInstSig {})) = True
488 isSpecInstLSig sig                    = False
489
490 isPragLSig :: LSig name -> Bool
491         -- Identifies pragmas 
492 isPragLSig (L _ (SpecSig {}))   = True
493 isPragLSig (L _ (InlineSig {})) = True
494 isPragLSig other                = False
495
496 isInlineLSig :: LSig name -> Bool
497         -- Identifies inline pragmas 
498 isInlineLSig (L _ (InlineSig {})) = True
499 isInlineLSig other                = False
500
501 hsSigDoc (TypeSig {})           = ptext SLIT("type signature")
502 hsSigDoc (SpecSig {})           = ptext SLIT("SPECIALISE pragma")
503 hsSigDoc (InlineSig _ spec)     = ppr spec <+> ptext SLIT("pragma")
504 hsSigDoc (SpecInstSig {})       = ptext SLIT("SPECIALISE instance pragma")
505 hsSigDoc (FixSig {})            = ptext SLIT("fixity declaration")
506 \end{code}
507
508 Signature equality is used when checking for duplicate signatures
509
510 \begin{code}
511 eqHsSig :: LSig Name -> LSig Name -> Bool
512 eqHsSig (L _ (FixSig (FixitySig n1 _))) (L _ (FixSig (FixitySig n2 _))) = unLoc n1 == unLoc n2
513 eqHsSig (L _ (TypeSig n1 _))            (L _ (TypeSig n2 _))            = unLoc n1 == unLoc n2
514 eqHsSig (L _ (InlineSig n1 s1)) (L _ (InlineSig n2 s2))                 = s1 == s2 && unLoc n1 == unLoc n2
515         -- For specialisations, we don't have equality over
516         -- HsType, so it's not convenient to spot duplicate 
517         -- specialisations here.  Check for this later, when we're in Type land
518 eqHsSig _other1 _other2 = False
519 \end{code}
520
521 \begin{code}
522 instance (OutputableBndr name) => Outputable (Sig name) where
523     ppr sig = ppr_sig sig
524
525 ppr_sig :: OutputableBndr name => Sig name -> SDoc
526 ppr_sig (TypeSig var ty)          = pprVarSig (unLoc var) ty
527 ppr_sig (FixSig fix_sig)          = ppr fix_sig
528 ppr_sig (SpecSig var ty inl)      = pragBrackets (pprSpec var ty inl)
529 ppr_sig (InlineSig var inl)       = pragBrackets (ppr inl <+> ppr var)
530 ppr_sig (SpecInstSig ty)          = pragBrackets (ptext SLIT("SPECIALIZE instance") <+> ppr ty)
531
532 instance Outputable name => Outputable (FixitySig name) where
533   ppr (FixitySig name fixity) = sep [ppr fixity, ppr name]
534
535 pragBrackets :: SDoc -> SDoc
536 pragBrackets doc = ptext SLIT("{-#") <+> doc <+> ptext SLIT("#-}") 
537
538 pprVarSig :: (Outputable id, Outputable ty) => id -> ty -> SDoc
539 pprVarSig var ty = sep [ppr var <+> dcolon, nest 2 (ppr ty)]
540
541 pprSpec :: (Outputable id, Outputable ty) => id -> ty -> InlineSpec -> SDoc
542 pprSpec var ty inl = sep [ptext SLIT("SPECIALIZE") <+> ppr inl <+> pprVarSig var ty]
543
544 pprPrag :: Outputable id => id -> LPrag -> SDoc
545 pprPrag var (L _ (InlinePrag inl))         = ppr inl <+> ppr var
546 pprPrag var (L _ (SpecPrag expr ty _ inl)) = pprSpec var ty inl
547 \end{code}
548