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
97 | PatBind { -- The pattern is never a simple variable;
98 -- That case is done by FunBind
101 pat_rhs_ty :: PostTcType, -- Type of the GRHSs
102 bind_fvs :: NameSet -- Same as for FunBind
105 | VarBind { -- Dictionary binding and suchlike
106 var_id :: id, -- All VarBinds are introduced by the type checker
107 var_rhs :: LHsExpr id -- Located only for consistency
110 | AbsBinds { -- Binds abstraction; TRANSLATION
112 abs_dicts :: [DictId],
113 abs_exports :: [([TyVar], id, id, [Prag])], -- (tvs, poly_id, mono_id, prags)
114 abs_binds :: LHsBinds id -- The dictionary bindings and typechecked user bindings
115 -- mixed up together; you can tell the dict bindings because
116 -- they are all VarBinds
118 -- Consider (AbsBinds tvs ds [(ftvs, poly_f, mono_f) binds]
120 -- Creates bindings for (polymorphic, overloaded) poly_f
121 -- in terms of monomorphic, non-overloaded mono_f
124 -- 1. 'binds' binds mono_f
125 -- 2. ftvs is a subset of tvs
126 -- 3. ftvs includes all tyvars free in ds
128 -- See section 9 of static semantics paper for more details.
129 -- (You can get a PhD for explaining the True Meaning
130 -- of this last construct.)
132 placeHolderNames :: NameSet
133 -- Used for the NameSet in FunBind and PatBind prior to the renamer
134 placeHolderNames = panic "placeHolderNames"
137 instance OutputableBndr id => Outputable (HsLocalBinds id) where
138 ppr (HsValBinds bs) = ppr bs
139 ppr (HsIPBinds bs) = ppr bs
140 ppr EmptyLocalBinds = empty
142 instance OutputableBndr id => Outputable (HsValBinds id) where
143 ppr (ValBindsIn binds sigs)
144 = pprValBindsForUser binds sigs
146 ppr (ValBindsOut sccs sigs)
147 = getPprStyle $ \ sty ->
148 if debugStyle sty then -- Print with sccs showing
149 vcat (map ppr sigs) $$ vcat (map ppr_scc sccs)
151 pprValBindsForUser (unionManyBags (map snd sccs)) sigs
153 ppr_scc (rec_flag, binds) = pp_rec rec_flag <+> pprLHsBinds binds
154 pp_rec Recursive = ptext SLIT("rec")
155 pp_rec NonRecursive = ptext SLIT("nonrec")
157 -- *not* pprLHsBinds because we don't want braces; 'let' and
158 -- 'where' include a list of HsBindGroups and we don't want
159 -- several groups of bindings each with braces around.
160 -- Sort by location before printing
161 pprValBindsForUser :: (OutputableBndr id1, OutputableBndr id2)
162 => LHsBinds id1 -> [LSig id2] -> SDoc
163 pprValBindsForUser binds sigs
164 = vcat (map snd (sort_by_loc decls))
167 decls :: [(SrcSpan, SDoc)]
168 decls = [(loc, ppr sig) | L loc sig <- sigs] ++
169 [(loc, ppr bind) | L loc bind <- bagToList binds]
171 sort_by_loc decls = sortLe (\(l1,_) (l2,_) -> l1 <= l2) decls
173 pprLHsBinds :: OutputableBndr id => LHsBinds id -> SDoc
175 | isEmptyLHsBinds binds = empty
176 | otherwise = lbrace <+> vcat (map ppr (bagToList binds)) <+> rbrace
179 emptyLocalBinds :: HsLocalBinds a
180 emptyLocalBinds = EmptyLocalBinds
182 isEmptyLocalBinds :: HsLocalBinds a -> Bool
183 isEmptyLocalBinds (HsValBinds ds) = isEmptyValBinds ds
184 isEmptyLocalBinds (HsIPBinds ds) = isEmptyIPBinds ds
185 isEmptyLocalBinds EmptyLocalBinds = True
187 isEmptyValBinds :: HsValBinds a -> Bool
188 isEmptyValBinds (ValBindsIn ds sigs) = isEmptyLHsBinds ds && null sigs
189 isEmptyValBinds (ValBindsOut ds sigs) = null ds && null sigs
191 emptyValBindsIn, emptyValBindsOut :: HsValBinds a
192 emptyValBindsIn = ValBindsIn emptyBag []
193 emptyValBindsOut = ValBindsOut [] []
195 emptyLHsBinds :: LHsBinds id
196 emptyLHsBinds = emptyBag
198 isEmptyLHsBinds :: LHsBinds id -> Bool
199 isEmptyLHsBinds = isEmptyBag
202 plusHsValBinds :: HsValBinds a -> HsValBinds a -> HsValBinds a
203 plusHsValBinds (ValBindsIn ds1 sigs1) (ValBindsIn ds2 sigs2)
204 = ValBindsIn (ds1 `unionBags` ds2) (sigs1 ++ sigs2)
205 plusHsValBinds (ValBindsOut ds1 sigs1) (ValBindsOut ds2 sigs2)
206 = ValBindsOut (ds1 ++ ds2) (sigs1 ++ sigs2)
218 f1p = /\ tvs -> \ [d1,d2] -> letrec DBINDS and BIND
221 gp = ...same again, with gm instead of fm
223 This is a pretty bad translation, because it duplicates all the bindings.
224 So the desugarer tries to do a better job:
226 fp = /\ [a,b] -> \ [d1,d2] -> case tp [a,b] [d1,d2] of
230 tp = /\ [a,b] -> \ [d1,d2] -> letrec DBINDS and BIND
234 instance OutputableBndr id => Outputable (HsBind id) where
235 ppr mbind = ppr_monobind mbind
237 ppr_monobind :: OutputableBndr id => HsBind id -> SDoc
239 ppr_monobind (PatBind { pat_lhs = pat, pat_rhs = grhss }) = pprPatBind pat grhss
240 ppr_monobind (VarBind { var_id = var, var_rhs = rhs }) = ppr var <+> equals <+> pprExpr (unLoc rhs)
241 ppr_monobind (FunBind { fun_id = fun, fun_matches = matches }) = pprFunBind (unLoc fun) matches
242 -- ToDo: print infix if appropriate
244 ppr_monobind (AbsBinds { abs_tvs = tyvars, abs_dicts = dictvars,
245 abs_exports = exports, abs_binds = val_binds })
246 = sep [ptext SLIT("AbsBinds"),
247 brackets (interpp'SP tyvars),
248 brackets (interpp'SP dictvars),
249 brackets (sep (punctuate comma (map ppr_exp exports)))]
251 nest 2 ( vcat [pprBndr LetBind x | (_,x,_,_) <- exports]
252 -- Print type signatures
253 $$ pprLHsBinds val_binds )
255 ppr_exp (tvs, gbl, lcl, prags)
256 = vcat [ppr gbl <+> ptext SLIT("<=") <+> ppr tvs <+> ppr lcl,
257 nest 2 (vcat (map (pprPrag gbl) prags))]
260 %************************************************************************
262 Implicit parameter bindings
264 %************************************************************************
270 (DictBinds id) -- Only in typechecker output; binds
271 -- uses of the implicit parameters
273 isEmptyIPBinds :: HsIPBinds id -> Bool
274 isEmptyIPBinds (IPBinds is ds) = null is && isEmptyBag ds
276 type LIPBind id = Located (IPBind id)
278 -- | Implicit parameter bindings.
284 instance (OutputableBndr id) => Outputable (HsIPBinds id) where
285 ppr (IPBinds bs ds) = vcat (map ppr bs)
288 instance (OutputableBndr id) => Outputable (IPBind id) where
289 ppr (IPBind id rhs) = pprBndr LetBind id <+> equals <+> pprExpr (unLoc rhs)
293 %************************************************************************
295 \subsection{Coercion functions}
297 %************************************************************************
300 -- A HsWrapper is an expression with a hole in it
301 -- We need coercions to have concrete form so that we can zonk them
304 = WpHole -- The identity coercion
306 | WpCompose HsWrapper HsWrapper -- (\a1..an. []) `WpCompose` (\x1..xn. [])
307 -- = (\a1..an \x1..xn. [])
309 | WpCo Coercion -- A cast: [] `cast` co
310 -- Guaranteedn not the identity coercion
312 | WpApp Var -- [] x; the xi are dicts or coercions
313 | WpTyApp Type -- [] t
314 | WpLam Id -- \x. []; the xi are dicts or coercions
315 | WpTyLam TyVar -- \a. []
317 -- Non-empty bindings, so that the identity coercion
318 -- is always exactly WpHole
319 | WpLet (LHsBinds Id) -- let binds in []
320 -- (would be nicer to be core bindings)
322 instance Outputable HsWrapper where
323 ppr co_fn = pprHsWrapper (ptext SLIT("<>")) co_fn
325 pprHsWrapper :: SDoc -> HsWrapper -> SDoc
326 pprHsWrapper it WpHole = it
327 pprHsWrapper it (WpCompose f1 f2) = pprHsWrapper (pprHsWrapper it f2) f1
328 pprHsWrapper it (WpCo co) = it <+> ptext SLIT("`cast`") <+> pprParendType co
329 pprHsWrapper it (WpApp id) = it <+> ppr id
330 pprHsWrapper it (WpTyApp ty) = it <+> ptext SLIT("@") <+> pprParendType ty
331 pprHsWrapper it (WpLam id) = ptext SLIT("\\") <> pprBndr LambdaBind id <> dot <+> it
332 pprHsWrapper it (WpTyLam tv) = ptext SLIT("/\\") <> pprBndr LambdaBind tv <> dot <+> it
333 pprHsWrapper it (WpLet binds) = sep [ptext SLIT("let") <+> braces (ppr binds), it]
335 (<.>) :: HsWrapper -> HsWrapper -> HsWrapper
338 c1 <.> c2 = c1 `WpCompose` c2
340 mkWpTyApps :: [Type] -> HsWrapper
341 mkWpTyApps tys = mk_co_fn WpTyApp (reverse tys)
343 mkWpApps :: [Id] -> HsWrapper
344 mkWpApps ids = mk_co_fn WpApp (reverse ids)
346 mkWpTyLams :: [TyVar] -> HsWrapper
347 mkWpTyLams ids = mk_co_fn WpTyLam ids
349 mkWpLams :: [Id] -> HsWrapper
350 mkWpLams ids = mk_co_fn WpLam ids
352 mk_co_fn :: (a -> HsWrapper) -> [a] -> HsWrapper
353 mk_co_fn f as = foldr (WpCompose . f) WpHole as
355 idHsWrapper :: HsWrapper
358 isIdHsWrapper :: HsWrapper -> Bool
359 isIdHsWrapper WpHole = True
360 isIdHsWrapper other = False
364 %************************************************************************
366 \subsection{@Sig@: type signatures and value-modifying user pragmas}
368 %************************************************************************
370 It is convenient to lump ``value-modifying'' user-pragmas (e.g.,
371 ``specialise this function to these four types...'') in with type
372 signatures. Then all the machinery to move them into place, etc.,
376 type LSig name = Located (Sig name)
379 = TypeSig (Located name) -- A bog-std type signature
382 | SpecSig (Located name) -- Specialise a function or datatype ...
383 (LHsType name) -- ... to these types
386 | InlineSig (Located name) -- Function name
389 | SpecInstSig (LHsType name) -- (Class tys); should be a specialisation of the
390 -- current instance decl
392 | FixSig (FixitySig name) -- Fixity declaration
394 type LFixitySig name = Located (FixitySig name)
395 data FixitySig name = FixitySig (Located name) Fixity
397 -- A Prag conveys pragmas from the type checker to the desugarer
403 (HsExpr Id) -- An expression, of the given specialised type, which
404 PostTcType -- specialises the polymorphic function
405 [Id] -- Dicts mentioned free in the expression
406 InlineSpec -- Inlining spec for the specialised function
408 isInlinePrag (InlinePrag _) = True
409 isInlinePrag prag = False
411 isSpecPrag (SpecPrag _ _ _ _) = True
412 isSpecPrag prag = False
416 okBindSig :: NameSet -> LSig Name -> Bool
417 okBindSig ns sig = sigForThisGroup ns sig
419 okHsBootSig :: LSig Name -> Bool
420 okHsBootSig (L _ (TypeSig _ _)) = True
421 okHsBootSig (L _ (FixSig _)) = True
422 okHsBootSig sig = False
424 okClsDclSig :: LSig Name -> Bool
425 okClsDclSig (L _ (SpecInstSig _)) = False
426 okClsDclSig sig = True -- All others OK
428 okInstDclSig :: NameSet -> LSig Name -> Bool
429 okInstDclSig ns lsig@(L _ sig) = ok ns sig
431 ok ns (TypeSig _ _) = False
432 ok ns (FixSig _) = False
433 ok ns (SpecInstSig _) = True
434 ok ns sig = sigForThisGroup ns lsig
436 sigForThisGroup :: NameSet -> LSig Name -> Bool
437 sigForThisGroup ns sig
438 = case sigName sig of
440 Just n -> n `elemNameSet` ns
442 sigName :: LSig name -> Maybe name
443 sigName (L _ sig) = sigNameNoLoc sig
445 sigNameNoLoc :: Sig name -> Maybe name
446 sigNameNoLoc (TypeSig n _) = Just (unLoc n)
447 sigNameNoLoc (SpecSig n _ _) = Just (unLoc n)
448 sigNameNoLoc (InlineSig n _) = Just (unLoc n)
449 sigNameNoLoc (FixSig (FixitySig n _)) = Just (unLoc n)
450 sigNameNoLoc other = Nothing
452 isFixityLSig :: LSig name -> Bool
453 isFixityLSig (L _ (FixSig {})) = True
454 isFixityLSig _ = False
456 isVanillaLSig :: LSig name -> Bool
457 isVanillaLSig (L _(TypeSig {})) = True
458 isVanillaLSig sig = False
460 isSpecLSig :: LSig name -> Bool
461 isSpecLSig (L _(SpecSig {})) = True
462 isSpecLSig sig = False
464 isSpecInstLSig (L _ (SpecInstSig {})) = True
465 isSpecInstLSig sig = False
467 isPragLSig :: LSig name -> Bool
468 -- Identifies pragmas
469 isPragLSig (L _ (SpecSig {})) = True
470 isPragLSig (L _ (InlineSig {})) = True
471 isPragLSig other = False
473 isInlineLSig :: LSig name -> Bool
474 -- Identifies inline pragmas
475 isInlineLSig (L _ (InlineSig {})) = True
476 isInlineLSig other = False
478 hsSigDoc (TypeSig {}) = ptext SLIT("type signature")
479 hsSigDoc (SpecSig {}) = ptext SLIT("SPECIALISE pragma")
480 hsSigDoc (InlineSig _ spec) = ppr spec <+> ptext SLIT("pragma")
481 hsSigDoc (SpecInstSig {}) = ptext SLIT("SPECIALISE instance pragma")
482 hsSigDoc (FixSig {}) = ptext SLIT("fixity declaration")
485 Signature equality is used when checking for duplicate signatures
488 eqHsSig :: LSig Name -> LSig Name -> Bool
489 eqHsSig (L _ (FixSig (FixitySig n1 _))) (L _ (FixSig (FixitySig n2 _))) = unLoc n1 == unLoc n2
490 eqHsSig (L _ (TypeSig n1 _)) (L _ (TypeSig n2 _)) = unLoc n1 == unLoc n2
491 eqHsSig (L _ (InlineSig n1 s1)) (L _ (InlineSig n2 s2)) = s1 == s2 && unLoc n1 == unLoc n2
492 -- For specialisations, we don't have equality over
493 -- HsType, so it's not convenient to spot duplicate
494 -- specialisations here. Check for this later, when we're in Type land
495 eqHsSig _other1 _other2 = False
499 instance (OutputableBndr name) => Outputable (Sig name) where
500 ppr sig = ppr_sig sig
502 ppr_sig :: OutputableBndr name => Sig name -> SDoc
503 ppr_sig (TypeSig var ty) = pprVarSig (unLoc var) ty
504 ppr_sig (FixSig fix_sig) = ppr fix_sig
505 ppr_sig (SpecSig var ty inl) = pragBrackets (pprSpec var ty inl)
506 ppr_sig (InlineSig var inl) = pragBrackets (ppr inl <+> ppr var)
507 ppr_sig (SpecInstSig ty) = pragBrackets (ptext SLIT("SPECIALIZE instance") <+> ppr ty)
509 instance Outputable name => Outputable (FixitySig name) where
510 ppr (FixitySig name fixity) = sep [ppr fixity, ppr name]
512 pragBrackets :: SDoc -> SDoc
513 pragBrackets doc = ptext SLIT("{-#") <+> doc <+> ptext SLIT("#-}")
515 pprVarSig :: (Outputable id, Outputable ty) => id -> ty -> SDoc
516 pprVarSig var ty = sep [ppr var <+> dcolon, nest 2 (ppr ty)]
518 pprSpec :: (Outputable id, Outputable ty) => id -> ty -> InlineSpec -> SDoc
519 pprSpec var ty inl = sep [ptext SLIT("SPECIALIZE") <+> ppr inl <+> pprVarSig var ty]
521 pprPrag :: Outputable id => id -> Prag -> SDoc
522 pprPrag var (InlinePrag inl) = ppr inl <+> ppr var
523 pprPrag var (SpecPrag expr ty _ inl) = pprSpec var ty inl