2 % (c) The University of Glasgow 2006
3 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
5 \section[HsBinds]{Abstract syntax: top-level bindings and signatures}
7 Datatype for: @BindGroup@, @Bind@, @Sig@, @Bind@.
12 #include "HsVersions.h"
14 import {-# SOURCE #-} HsExpr ( HsExpr, pprExpr, LHsExpr,
15 MatchGroup, pprFunBind,
17 import {-# SOURCE #-} HsPat ( LPat )
33 %************************************************************************
35 \subsection{Bindings: @BindGroup@}
37 %************************************************************************
39 Global bindings (where clauses)
42 data HsLocalBinds id -- Bindings in a 'let' expression
43 -- or a 'where' clause
44 = HsValBinds (HsValBinds id)
45 | HsIPBinds (HsIPBinds id)
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
54 | ValBindsOut -- After renaming
55 [(RecFlag, LHsBinds id)] -- Dependency analysed
58 type LHsBinds id = Bag (LHsBind id)
59 type DictBinds id = LHsBinds id -- Used for dictionary or method bindings
60 type LHsBind id = Located (HsBind id)
63 = FunBind { -- FunBind is used for both functions f x = e
64 -- and variables f = \x -> e
65 -- Reason 1: Special case for type inference: see TcBinds.tcMonoBinds
67 -- Reason 2: instance decls can only have FunBinds, which is convenient
68 -- If you change this, you'll need tochange e.g. rnMethodBinds
70 -- But note that the form f :: a->a = ...
71 -- parses as a pattern binding, just like
72 -- (f :: a -> a) = ...
76 fun_infix :: Bool, -- True => infix declaration
78 fun_matches :: MatchGroup id, -- The payload
80 fun_co_fn :: HsWrapper, -- Coercion from the type of the MatchGroup to the type of
82 -- f :: Int -> forall a. a -> a
84 -- Then the MatchGroup will have type (Int -> a' -> a')
85 -- (with a free type variable a'). The coercion will take
86 -- a CoreExpr of this type and convert it to a CoreExpr of
87 -- type Int -> forall a'. a' -> a'
88 -- Notice that the coercion captures the free a'.
90 bind_fvs :: NameSet, -- After the renamer, this contains a superset of the
91 -- Names of the other binders in this binding group that
92 -- are free in the RHS of the defn
93 -- Before renaming, and after typechecking,
94 -- the field is unused; it's just an error thunk
96 fun_tick :: Maybe Int -- This is the (optional) module-local tick number.
99 | PatBind { -- The pattern is never a simple variable;
100 -- That case is done by FunBind
103 pat_rhs_ty :: PostTcType, -- Type of the GRHSs
104 bind_fvs :: NameSet -- Same as for FunBind
107 | VarBind { -- Dictionary binding and suchlike
108 var_id :: id, -- All VarBinds are introduced by the type checker
109 var_rhs :: LHsExpr id -- Located only for consistency
112 | AbsBinds { -- Binds abstraction; TRANSLATION
114 abs_dicts :: [DictId],
115 abs_exports :: [([TyVar], id, id, [Prag])], -- (tvs, poly_id, mono_id, prags)
116 abs_binds :: LHsBinds id -- The dictionary bindings and typechecked user bindings
117 -- mixed up together; you can tell the dict bindings because
118 -- they are all VarBinds
120 -- Consider (AbsBinds tvs ds [(ftvs, poly_f, mono_f) binds]
122 -- Creates bindings for (polymorphic, overloaded) poly_f
123 -- in terms of monomorphic, non-overloaded mono_f
126 -- 1. 'binds' binds mono_f
127 -- 2. ftvs is a subset of tvs
128 -- 3. ftvs includes all tyvars free in ds
130 -- See section 9 of static semantics paper for more details.
131 -- (You can get a PhD for explaining the True Meaning
132 -- of this last construct.)
134 placeHolderNames :: NameSet
135 -- Used for the NameSet in FunBind and PatBind prior to the renamer
136 placeHolderNames = panic "placeHolderNames"
139 instance OutputableBndr id => Outputable (HsLocalBinds id) where
140 ppr (HsValBinds bs) = ppr bs
141 ppr (HsIPBinds bs) = ppr bs
142 ppr EmptyLocalBinds = empty
144 instance OutputableBndr id => Outputable (HsValBinds id) where
145 ppr (ValBindsIn binds sigs)
146 = pprValBindsForUser binds sigs
148 ppr (ValBindsOut sccs sigs)
149 = getPprStyle $ \ sty ->
150 if debugStyle sty then -- Print with sccs showing
151 vcat (map ppr sigs) $$ vcat (map ppr_scc sccs)
153 pprValBindsForUser (unionManyBags (map snd sccs)) sigs
155 ppr_scc (rec_flag, binds) = pp_rec rec_flag <+> pprLHsBinds binds
156 pp_rec Recursive = ptext SLIT("rec")
157 pp_rec NonRecursive = ptext SLIT("nonrec")
159 -- *not* pprLHsBinds because we don't want braces; 'let' and
160 -- 'where' include a list of HsBindGroups and we don't want
161 -- several groups of bindings each with braces around.
162 -- Sort by location before printing
163 pprValBindsForUser :: (OutputableBndr id1, OutputableBndr id2)
164 => LHsBinds id1 -> [LSig id2] -> SDoc
165 pprValBindsForUser binds sigs
166 = vcat (map snd (sort_by_loc decls))
169 decls :: [(SrcSpan, SDoc)]
170 decls = [(loc, ppr sig) | L loc sig <- sigs] ++
171 [(loc, ppr bind) | L loc bind <- bagToList binds]
173 sort_by_loc decls = sortLe (\(l1,_) (l2,_) -> l1 <= l2) decls
175 pprLHsBinds :: OutputableBndr id => LHsBinds id -> SDoc
177 | isEmptyLHsBinds binds = empty
178 | otherwise = lbrace <+> vcat (map ppr (bagToList binds)) <+> rbrace
181 emptyLocalBinds :: HsLocalBinds a
182 emptyLocalBinds = EmptyLocalBinds
184 isEmptyLocalBinds :: HsLocalBinds a -> Bool
185 isEmptyLocalBinds (HsValBinds ds) = isEmptyValBinds ds
186 isEmptyLocalBinds (HsIPBinds ds) = isEmptyIPBinds ds
187 isEmptyLocalBinds EmptyLocalBinds = True
189 isEmptyValBinds :: HsValBinds a -> Bool
190 isEmptyValBinds (ValBindsIn ds sigs) = isEmptyLHsBinds ds && null sigs
191 isEmptyValBinds (ValBindsOut ds sigs) = null ds && null sigs
193 emptyValBindsIn, emptyValBindsOut :: HsValBinds a
194 emptyValBindsIn = ValBindsIn emptyBag []
195 emptyValBindsOut = ValBindsOut [] []
197 emptyLHsBinds :: LHsBinds id
198 emptyLHsBinds = emptyBag
200 isEmptyLHsBinds :: LHsBinds id -> Bool
201 isEmptyLHsBinds = isEmptyBag
204 plusHsValBinds :: HsValBinds a -> HsValBinds a -> HsValBinds a
205 plusHsValBinds (ValBindsIn ds1 sigs1) (ValBindsIn ds2 sigs2)
206 = ValBindsIn (ds1 `unionBags` ds2) (sigs1 ++ sigs2)
207 plusHsValBinds (ValBindsOut ds1 sigs1) (ValBindsOut ds2 sigs2)
208 = ValBindsOut (ds1 ++ ds2) (sigs1 ++ sigs2)
220 f1p = /\ tvs -> \ [d1,d2] -> letrec DBINDS and BIND
223 gp = ...same again, with gm instead of fm
225 This is a pretty bad translation, because it duplicates all the bindings.
226 So the desugarer tries to do a better job:
228 fp = /\ [a,b] -> \ [d1,d2] -> case tp [a,b] [d1,d2] of
232 tp = /\ [a,b] -> \ [d1,d2] -> letrec DBINDS and BIND
236 instance OutputableBndr id => Outputable (HsBind id) where
237 ppr mbind = ppr_monobind mbind
239 ppr_monobind :: OutputableBndr id => HsBind id -> SDoc
241 ppr_monobind (PatBind { pat_lhs = pat, pat_rhs = grhss }) = pprPatBind pat grhss
242 ppr_monobind (VarBind { var_id = var, var_rhs = rhs }) = ppr var <+> equals <+> pprExpr (unLoc rhs)
243 ppr_monobind (FunBind { fun_id = fun,
244 fun_matches = matches,
248 Just t -> text "-- tick id = " <> ppr t
249 ) $$ pprFunBind (unLoc fun) matches
250 -- ToDo: print infix if appropriate
252 ppr_monobind (AbsBinds { abs_tvs = tyvars, abs_dicts = dictvars,
253 abs_exports = exports, abs_binds = val_binds })
254 = sep [ptext SLIT("AbsBinds"),
255 brackets (interpp'SP tyvars),
256 brackets (interpp'SP dictvars),
257 brackets (sep (punctuate comma (map ppr_exp exports)))]
259 nest 2 ( vcat [pprBndr LetBind x | (_,x,_,_) <- exports]
260 -- Print type signatures
261 $$ pprLHsBinds val_binds )
263 ppr_exp (tvs, gbl, lcl, prags)
264 = vcat [ppr gbl <+> ptext SLIT("<=") <+> ppr tvs <+> ppr lcl,
265 nest 2 (vcat (map (pprPrag gbl) prags))]
268 %************************************************************************
270 Implicit parameter bindings
272 %************************************************************************
278 (DictBinds id) -- Only in typechecker output; binds
279 -- uses of the implicit parameters
281 isEmptyIPBinds :: HsIPBinds id -> Bool
282 isEmptyIPBinds (IPBinds is ds) = null is && isEmptyBag ds
284 type LIPBind id = Located (IPBind id)
286 -- | Implicit parameter bindings.
292 instance (OutputableBndr id) => Outputable (HsIPBinds id) where
293 ppr (IPBinds bs ds) = vcat (map ppr bs)
296 instance (OutputableBndr id) => Outputable (IPBind id) where
297 ppr (IPBind id rhs) = pprBndr LetBind id <+> equals <+> pprExpr (unLoc rhs)
301 %************************************************************************
303 \subsection{Coercion functions}
305 %************************************************************************
308 -- A HsWrapper is an expression with a hole in it
309 -- We need coercions to have concrete form so that we can zonk them
312 = WpHole -- The identity coercion
314 | WpCompose HsWrapper HsWrapper -- (\a1..an. []) `WpCompose` (\x1..xn. [])
315 -- = (\a1..an \x1..xn. [])
317 | WpCo Coercion -- A cast: [] `cast` co
318 -- Guaranteedn not the identity coercion
320 | WpApp Var -- [] x; the xi are dicts or coercions
321 | WpTyApp Type -- [] t
322 | WpLam Id -- \x. []; the xi are dicts or coercions
323 | WpTyLam TyVar -- \a. []
325 -- Non-empty bindings, so that the identity coercion
326 -- is always exactly WpHole
327 | WpLet (LHsBinds Id) -- let binds in []
328 -- (would be nicer to be core bindings)
330 instance Outputable HsWrapper where
331 ppr co_fn = pprHsWrapper (ptext SLIT("<>")) co_fn
333 pprHsWrapper :: SDoc -> HsWrapper -> SDoc
334 pprHsWrapper it WpHole = it
335 pprHsWrapper it (WpCompose f1 f2) = pprHsWrapper (pprHsWrapper it f2) f1
336 pprHsWrapper it (WpCo co) = it <+> ptext SLIT("`cast`") <+> pprParendType co
337 pprHsWrapper it (WpApp id) = it <+> ppr id
338 pprHsWrapper it (WpTyApp ty) = it <+> ptext SLIT("@") <+> pprParendType ty
339 pprHsWrapper it (WpLam id) = ptext SLIT("\\") <> pprBndr LambdaBind id <> dot <+> it
340 pprHsWrapper it (WpTyLam tv) = ptext SLIT("/\\") <> pprBndr LambdaBind tv <> dot <+> it
341 pprHsWrapper it (WpLet binds) = sep [ptext SLIT("let") <+> braces (ppr binds), it]
343 (<.>) :: HsWrapper -> HsWrapper -> HsWrapper
346 c1 <.> c2 = c1 `WpCompose` c2
348 mkWpTyApps :: [Type] -> HsWrapper
349 mkWpTyApps tys = mk_co_fn WpTyApp (reverse tys)
351 mkWpApps :: [Id] -> HsWrapper
352 mkWpApps ids = mk_co_fn WpApp (reverse ids)
354 mkWpTyLams :: [TyVar] -> HsWrapper
355 mkWpTyLams ids = mk_co_fn WpTyLam ids
357 mkWpLams :: [Id] -> HsWrapper
358 mkWpLams ids = mk_co_fn WpLam ids
360 mk_co_fn :: (a -> HsWrapper) -> [a] -> HsWrapper
361 mk_co_fn f as = foldr (WpCompose . f) WpHole as
363 idHsWrapper :: HsWrapper
366 isIdHsWrapper :: HsWrapper -> Bool
367 isIdHsWrapper WpHole = True
368 isIdHsWrapper other = False
372 %************************************************************************
374 \subsection{@Sig@: type signatures and value-modifying user pragmas}
376 %************************************************************************
378 It is convenient to lump ``value-modifying'' user-pragmas (e.g.,
379 ``specialise this function to these four types...'') in with type
380 signatures. Then all the machinery to move them into place, etc.,
384 type LSig name = Located (Sig name)
387 = TypeSig (Located name) -- A bog-std type signature
390 | SpecSig (Located name) -- Specialise a function or datatype ...
391 (LHsType name) -- ... to these types
394 | InlineSig (Located name) -- Function name
397 | SpecInstSig (LHsType name) -- (Class tys); should be a specialisation of the
398 -- current instance decl
400 | FixSig (FixitySig name) -- Fixity declaration
402 type LFixitySig name = Located (FixitySig name)
403 data FixitySig name = FixitySig (Located name) Fixity
405 -- A Prag conveys pragmas from the type checker to the desugarer
411 (HsExpr Id) -- An expression, of the given specialised type, which
412 PostTcType -- specialises the polymorphic function
413 [Id] -- Dicts mentioned free in the expression
414 InlineSpec -- Inlining spec for the specialised function
416 isInlinePrag (InlinePrag _) = True
417 isInlinePrag prag = False
419 isSpecPrag (SpecPrag _ _ _ _) = True
420 isSpecPrag prag = False
424 okBindSig :: NameSet -> LSig Name -> Bool
425 okBindSig ns sig = sigForThisGroup ns sig
427 okHsBootSig :: LSig Name -> Bool
428 okHsBootSig (L _ (TypeSig _ _)) = True
429 okHsBootSig (L _ (FixSig _)) = True
430 okHsBootSig sig = False
432 okClsDclSig :: LSig Name -> Bool
433 okClsDclSig (L _ (SpecInstSig _)) = False
434 okClsDclSig sig = True -- All others OK
436 okInstDclSig :: NameSet -> LSig Name -> Bool
437 okInstDclSig ns lsig@(L _ sig) = ok ns sig
439 ok ns (TypeSig _ _) = False
440 ok ns (FixSig _) = False
441 ok ns (SpecInstSig _) = True
442 ok ns sig = sigForThisGroup ns lsig
444 sigForThisGroup :: NameSet -> LSig Name -> Bool
445 sigForThisGroup ns sig
446 = case sigName sig of
448 Just n -> n `elemNameSet` ns
450 sigName :: LSig name -> Maybe name
451 sigName (L _ sig) = sigNameNoLoc sig
453 sigNameNoLoc :: Sig name -> Maybe name
454 sigNameNoLoc (TypeSig n _) = Just (unLoc n)
455 sigNameNoLoc (SpecSig n _ _) = Just (unLoc n)
456 sigNameNoLoc (InlineSig n _) = Just (unLoc n)
457 sigNameNoLoc (FixSig (FixitySig n _)) = Just (unLoc n)
458 sigNameNoLoc other = Nothing
460 isFixityLSig :: LSig name -> Bool
461 isFixityLSig (L _ (FixSig {})) = True
462 isFixityLSig _ = False
464 isVanillaLSig :: LSig name -> Bool
465 isVanillaLSig (L _(TypeSig {})) = True
466 isVanillaLSig sig = False
468 isSpecLSig :: LSig name -> Bool
469 isSpecLSig (L _(SpecSig {})) = True
470 isSpecLSig sig = False
472 isSpecInstLSig (L _ (SpecInstSig {})) = True
473 isSpecInstLSig sig = False
475 isPragLSig :: LSig name -> Bool
476 -- Identifies pragmas
477 isPragLSig (L _ (SpecSig {})) = True
478 isPragLSig (L _ (InlineSig {})) = True
479 isPragLSig other = False
481 isInlineLSig :: LSig name -> Bool
482 -- Identifies inline pragmas
483 isInlineLSig (L _ (InlineSig {})) = True
484 isInlineLSig other = False
486 hsSigDoc (TypeSig {}) = ptext SLIT("type signature")
487 hsSigDoc (SpecSig {}) = ptext SLIT("SPECIALISE pragma")
488 hsSigDoc (InlineSig _ spec) = ppr spec <+> ptext SLIT("pragma")
489 hsSigDoc (SpecInstSig {}) = ptext SLIT("SPECIALISE instance pragma")
490 hsSigDoc (FixSig {}) = ptext SLIT("fixity declaration")
493 Signature equality is used when checking for duplicate signatures
496 eqHsSig :: LSig Name -> LSig Name -> Bool
497 eqHsSig (L _ (FixSig (FixitySig n1 _))) (L _ (FixSig (FixitySig n2 _))) = unLoc n1 == unLoc n2
498 eqHsSig (L _ (TypeSig n1 _)) (L _ (TypeSig n2 _)) = unLoc n1 == unLoc n2
499 eqHsSig (L _ (InlineSig n1 s1)) (L _ (InlineSig n2 s2)) = s1 == s2 && unLoc n1 == unLoc n2
500 -- For specialisations, we don't have equality over
501 -- HsType, so it's not convenient to spot duplicate
502 -- specialisations here. Check for this later, when we're in Type land
503 eqHsSig _other1 _other2 = False
507 instance (OutputableBndr name) => Outputable (Sig name) where
508 ppr sig = ppr_sig sig
510 ppr_sig :: OutputableBndr name => Sig name -> SDoc
511 ppr_sig (TypeSig var ty) = pprVarSig (unLoc var) ty
512 ppr_sig (FixSig fix_sig) = ppr fix_sig
513 ppr_sig (SpecSig var ty inl) = pragBrackets (pprSpec var ty inl)
514 ppr_sig (InlineSig var inl) = pragBrackets (ppr inl <+> ppr var)
515 ppr_sig (SpecInstSig ty) = pragBrackets (ptext SLIT("SPECIALIZE instance") <+> ppr ty)
517 instance Outputable name => Outputable (FixitySig name) where
518 ppr (FixitySig name fixity) = sep [ppr fixity, ppr name]
520 pragBrackets :: SDoc -> SDoc
521 pragBrackets doc = ptext SLIT("{-#") <+> doc <+> ptext SLIT("#-}")
523 pprVarSig :: (Outputable id, Outputable ty) => id -> ty -> SDoc
524 pprVarSig var ty = sep [ppr var <+> dcolon, nest 2 (ppr ty)]
526 pprSpec :: (Outputable id, Outputable ty) => id -> ty -> InlineSpec -> SDoc
527 pprSpec var ty inl = sep [ptext SLIT("SPECIALIZE") <+> ppr inl <+> pprVarSig var ty]
529 pprPrag :: Outputable id => id -> Prag -> SDoc
530 pprPrag var (InlinePrag inl) = ppr inl <+> ppr var
531 pprPrag var (SpecPrag expr ty _ inl) = pprSpec var ty inl