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, later bindings
56 -- in the list may depend on earlier
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)
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
69 -- Reason 2: instance decls can only have FunBinds, which is convenient
70 -- If you change this, you'll need tochange e.g. rnMethodBinds
72 -- But note that the form f :: a->a = ...
73 -- parses as a pattern binding, just like
74 -- (f :: a -> a) = ...
78 fun_infix :: Bool, -- True => infix declaration
80 fun_matches :: MatchGroup id, -- The payload
82 fun_co_fn :: HsWrapper, -- Coercion from the type of the MatchGroup to the type of
84 -- f :: Int -> forall a. a -> a
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'.
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
98 fun_tick :: Maybe (Int,[id]) -- This is the (optional) module-local tick number.
101 | PatBind { -- The pattern is never a simple variable;
102 -- That case is done by FunBind
105 pat_rhs_ty :: PostTcType, -- Type of the GRHSs
106 bind_fvs :: NameSet -- Same as for FunBind
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
114 | AbsBinds { -- Binds abstraction; TRANSLATION
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
122 -- Consider (AbsBinds tvs ds [(ftvs, poly_f, mono_f) binds]
124 -- Creates bindings for (polymorphic, overloaded) poly_f
125 -- in terms of monomorphic, non-overloaded mono_f
128 -- 1. 'binds' binds mono_f
129 -- 2. ftvs is a subset of tvs
130 -- 3. ftvs includes all tyvars free in ds
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.)
136 placeHolderNames :: NameSet
137 -- Used for the NameSet in FunBind and PatBind prior to the renamer
138 placeHolderNames = panic "placeHolderNames"
141 instance OutputableBndr id => Outputable (HsLocalBinds id) where
142 ppr (HsValBinds bs) = ppr bs
143 ppr (HsIPBinds bs) = ppr bs
144 ppr EmptyLocalBinds = empty
146 instance OutputableBndr id => Outputable (HsValBinds id) where
147 ppr (ValBindsIn binds sigs)
148 = pprValBindsForUser binds sigs
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)
155 pprValBindsForUser (unionManyBags (map snd sccs)) sigs
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")
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))
171 decls :: [(SrcSpan, SDoc)]
172 decls = [(loc, ppr sig) | L loc sig <- sigs] ++
173 [(loc, ppr bind) | L loc bind <- bagToList binds]
175 sort_by_loc decls = sortLe (\(l1,_) (l2,_) -> l1 <= l2) decls
177 pprLHsBinds :: OutputableBndr id => LHsBinds id -> SDoc
179 | isEmptyLHsBinds binds = empty
180 | otherwise = lbrace <+> pprDeeperList vcat (map ppr (bagToList binds)) <+> rbrace
183 emptyLocalBinds :: HsLocalBinds a
184 emptyLocalBinds = EmptyLocalBinds
186 isEmptyLocalBinds :: HsLocalBinds a -> Bool
187 isEmptyLocalBinds (HsValBinds ds) = isEmptyValBinds ds
188 isEmptyLocalBinds (HsIPBinds ds) = isEmptyIPBinds ds
189 isEmptyLocalBinds EmptyLocalBinds = True
191 isEmptyValBinds :: HsValBinds a -> Bool
192 isEmptyValBinds (ValBindsIn ds sigs) = isEmptyLHsBinds ds && null sigs
193 isEmptyValBinds (ValBindsOut ds sigs) = null ds && null sigs
195 emptyValBindsIn, emptyValBindsOut :: HsValBinds a
196 emptyValBindsIn = ValBindsIn emptyBag []
197 emptyValBindsOut = ValBindsOut [] []
199 emptyLHsBinds :: LHsBinds id
200 emptyLHsBinds = emptyBag
202 isEmptyLHsBinds :: LHsBinds id -> Bool
203 isEmptyLHsBinds = isEmptyBag
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)
222 f1p = /\ tvs -> \ [d1,d2] -> letrec DBINDS and BIND
225 gp = ...same again, with gm instead of fm
227 This is a pretty bad translation, because it duplicates all the bindings.
228 So the desugarer tries to do a better job:
230 fp = /\ [a,b] -> \ [d1,d2] -> case tp [a,b] [d1,d2] of
234 tp = /\ [a,b] -> \ [d1,d2] -> letrec DBINDS and BIND
238 instance OutputableBndr id => Outputable (HsBind id) where
239 ppr mbind = ppr_monobind mbind
241 ppr_monobind :: OutputableBndr id => HsBind id -> SDoc
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,
250 Just t -> text "-- tick id = " <> ppr t
251 ) $$ pprFunBind (unLoc fun) matches
252 -- ToDo: print infix if appropriate
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)))]
261 nest 2 ( vcat [pprBndr LetBind x | (_,x,_,_) <- exports]
262 -- Print type signatures
263 $$ pprLHsBinds val_binds )
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))]
270 %************************************************************************
272 Implicit parameter bindings
274 %************************************************************************
280 (DictBinds id) -- Only in typechecker output; binds
281 -- uses of the implicit parameters
283 isEmptyIPBinds :: HsIPBinds id -> Bool
284 isEmptyIPBinds (IPBinds is ds) = null is && isEmptyBag ds
286 type LIPBind id = Located (IPBind id)
288 -- | Implicit parameter bindings.
294 instance (OutputableBndr id) => Outputable (HsIPBinds id) where
295 ppr (IPBinds bs ds) = pprDeeperList vcat (map ppr bs)
298 instance (OutputableBndr id) => Outputable (IPBind id) where
299 ppr (IPBind id rhs) = pprBndr LetBind id <+> equals <+> pprExpr (unLoc rhs)
303 %************************************************************************
305 \subsection{Coercion functions}
307 %************************************************************************
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
314 = WpHole -- The identity coercion
316 | WpCompose HsWrapper HsWrapper -- (\a1..an. []) `WpCompose` (\x1..xn. [])
317 -- = (\a1..an \x1..xn. [])
319 | WpCo Coercion -- A cast: [] `cast` co
320 -- Guaranteedn not the identity coercion
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
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)
332 instance Outputable HsWrapper where
333 ppr co_fn = pprHsWrapper (ptext SLIT("<>")) co_fn
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]
345 (<.>) :: HsWrapper -> HsWrapper -> HsWrapper
348 c1 <.> c2 = c1 `WpCompose` c2
350 mkWpTyApps :: [Type] -> HsWrapper
351 mkWpTyApps tys = mk_co_fn WpTyApp (reverse tys)
353 mkWpApps :: [Id] -> HsWrapper
354 mkWpApps ids = mk_co_fn WpApp (reverse ids)
356 mkWpTyLams :: [TyVar] -> HsWrapper
357 mkWpTyLams ids = mk_co_fn WpTyLam ids
359 mkWpLams :: [Id] -> HsWrapper
360 mkWpLams ids = mk_co_fn WpLam ids
362 mk_co_fn :: (a -> HsWrapper) -> [a] -> HsWrapper
363 mk_co_fn f as = foldr (WpCompose . f) WpHole as
365 idHsWrapper :: HsWrapper
368 isIdHsWrapper :: HsWrapper -> Bool
369 isIdHsWrapper WpHole = True
370 isIdHsWrapper other = False
374 %************************************************************************
376 \subsection{@Sig@: type signatures and value-modifying user pragmas}
378 %************************************************************************
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.,
386 type LSig name = Located (Sig name)
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
394 -- An ordinary fixity declaration
396 | FixSig (FixitySig name) -- Fixity declaration
400 | InlineSig (Located name) -- Function name
403 -- A specialisation pragma
404 -- {-# SPECIALISE f :: Int -> Int #-}
405 | SpecSig (Located name) -- Specialise a function or datatype ...
406 (LHsType name) -- ... to these types
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
415 type LFixitySig name = Located (FixitySig name)
416 data FixitySig name = FixitySig (Located name) Fixity
418 -- A Prag conveys pragmas from the type checker to the desugarer
419 type LPrag = Located Prag
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
432 isInlinePrag (InlinePrag _) = True
433 isInlinePrag prag = False
435 isSpecPrag (SpecPrag {}) = True
436 isSpecPrag prag = False
440 okBindSig :: NameSet -> LSig Name -> Bool
441 okBindSig ns sig = sigForThisGroup ns sig
443 okHsBootSig :: LSig Name -> Bool
444 okHsBootSig (L _ (TypeSig _ _)) = True
445 okHsBootSig (L _ (FixSig _)) = True
446 okHsBootSig sig = False
448 okClsDclSig :: LSig Name -> Bool
449 okClsDclSig (L _ (SpecInstSig _)) = False
450 okClsDclSig sig = True -- All others OK
452 okInstDclSig :: NameSet -> LSig Name -> Bool
453 okInstDclSig ns lsig@(L _ sig) = ok ns sig
455 ok ns (TypeSig _ _) = False
456 ok ns (FixSig _) = False
457 ok ns (SpecInstSig _) = True
458 ok ns sig = sigForThisGroup ns lsig
460 sigForThisGroup :: NameSet -> LSig Name -> Bool
461 sigForThisGroup ns sig
462 = case sigName sig of
464 Just n -> n `elemNameSet` ns
466 sigName :: LSig name -> Maybe name
467 sigName (L _ sig) = sigNameNoLoc sig
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
476 isFixityLSig :: LSig name -> Bool
477 isFixityLSig (L _ (FixSig {})) = True
478 isFixityLSig _ = False
480 isVanillaLSig :: LSig name -> Bool
481 isVanillaLSig (L _(TypeSig {})) = True
482 isVanillaLSig sig = False
484 isSpecLSig :: LSig name -> Bool
485 isSpecLSig (L _(SpecSig {})) = True
486 isSpecLSig sig = False
488 isSpecInstLSig (L _ (SpecInstSig {})) = True
489 isSpecInstLSig sig = False
491 isPragLSig :: LSig name -> Bool
492 -- Identifies pragmas
493 isPragLSig (L _ (SpecSig {})) = True
494 isPragLSig (L _ (InlineSig {})) = True
495 isPragLSig other = False
497 isInlineLSig :: LSig name -> Bool
498 -- Identifies inline pragmas
499 isInlineLSig (L _ (InlineSig {})) = True
500 isInlineLSig other = False
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")
509 Signature equality is used when checking for duplicate signatures
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
523 instance (OutputableBndr name) => Outputable (Sig name) where
524 ppr sig = ppr_sig sig
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)
533 instance Outputable name => Outputable (FixitySig name) where
534 ppr (FixitySig name fixity) = sep [ppr fixity, ppr name]
536 pragBrackets :: SDoc -> SDoc
537 pragBrackets doc = ptext SLIT("{-#") <+> doc <+> ptext SLIT("#-}")
539 pprVarSig :: (Outputable id, Outputable ty) => id -> ty -> SDoc
540 pprVarSig var ty = sep [ppr var <+> dcolon, nest 2 (ppr ty)]
542 pprSpec :: (Outputable id, Outputable ty) => id -> ty -> InlineSpec -> SDoc
543 pprSpec var ty inl = sep [ptext SLIT("SPECIALIZE") <+> ppr inl <+> pprVarSig var ty]
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