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@.
10 {-# OPTIONS -fno-warn-incomplete-patterns #-}
11 -- The above warning supression flag is a temporary kludge.
12 -- While working on this module you are encouraged to remove it and fix
13 -- any warnings in the module. See
14 -- http://hackage.haskell.org/trac/ghc/wiki/Commentary/CodingStyle#Warnings
19 import {-# SOURCE #-} HsExpr ( HsExpr, pprExpr, LHsExpr,
20 MatchGroup, pprFunBind,
22 import {-# SOURCE #-} HsPat ( LPat )
39 %************************************************************************
41 \subsection{Bindings: @BindGroup@}
43 %************************************************************************
45 Global bindings (where clauses)
48 -- During renaming, we need bindings where the left-hand sides
49 -- have been renamed but the the right-hand sides have not.
50 -- the ...LR datatypes are parametrized by two id types,
51 -- one for the left and one for the right.
52 -- Other than during renaming, these will be the same.
54 type HsLocalBinds id = HsLocalBindsLR id id
56 data HsLocalBindsLR idL idR -- Bindings in a 'let' expression
57 -- or a 'where' clause
58 = HsValBinds (HsValBindsLR idL idR)
59 | HsIPBinds (HsIPBinds idR)
62 type HsValBinds id = HsValBindsLR id id
64 data HsValBindsLR idL idR -- Value bindings (not implicit parameters)
65 = ValBindsIn -- Before typechecking
66 (LHsBindsLR idL idR) [LSig idR] -- Not dependency analysed
67 -- Recursive by default
69 | ValBindsOut -- After renaming
70 [(RecFlag, LHsBinds idL)] -- Dependency analysed, later bindings
71 -- in the list may depend on earlier
75 type LHsBinds id = Bag (LHsBind id)
76 type DictBinds id = LHsBinds id -- Used for dictionary or method bindings
77 type LHsBind id = Located (HsBind id)
78 type HsBind id = HsBindLR id id
80 type LHsBindLR idL idR = Located (HsBindLR idL idR)
81 type LHsBindsLR idL idR = Bag (LHsBindLR idL idR)
84 = -- | FunBind is used for both functions @f x = e@
85 -- and variables @f = \x -> e@
87 -- Reason 1: Special case for type inference: see 'TcBinds.tcMonoBinds'.
89 -- Reason 2: Instance decls can only have FunBinds, which is convenient.
90 -- If you change this, you'll need to change e.g. rnMethodBinds
92 -- But note that the form @f :: a->a = ...@
93 -- parses as a pattern binding, just like
94 -- @(f :: a -> a) = ... @
97 fun_id :: Located idL,
99 fun_infix :: Bool, -- ^ True => infix declaration
101 fun_matches :: MatchGroup idR, -- ^ The payload
103 fun_co_fn :: HsWrapper, -- ^ Coercion from the type of the MatchGroup to the type of
106 -- f :: Int -> forall a. a -> a
109 -- Then the MatchGroup will have type (Int -> a' -> a')
110 -- (with a free type variable a'). The coercion will take
111 -- a CoreExpr of this type and convert it to a CoreExpr of
112 -- type Int -> forall a'. a' -> a'
113 -- Notice that the coercion captures the free a'.
115 bind_fvs :: NameSet, -- ^ After the renamer, this contains a superset of the
116 -- Names of the other binders in this binding group that
117 -- are free in the RHS of the defn
118 -- Before renaming, and after typechecking,
119 -- the field is unused; it's just an error thunk
121 fun_tick :: Maybe (Int,[idR]) -- ^ This is the (optional) module-local tick number.
124 | PatBind { -- The pattern is never a simple variable;
125 -- That case is done by FunBind
127 pat_rhs :: GRHSs idR,
128 pat_rhs_ty :: PostTcType, -- Type of the GRHSs
129 bind_fvs :: NameSet -- Same as for FunBind
132 | VarBind { -- Dictionary binding and suchlike
133 var_id :: idL, -- All VarBinds are introduced by the type checker
134 var_rhs :: LHsExpr idR -- Located only for consistency
137 | AbsBinds { -- Binds abstraction; TRANSLATION
139 abs_dicts :: [DictId], -- Includes equality constraints
141 -- AbsBinds only gets used when idL = idR after renaming,
142 -- but these need to be idL's for the collect... code in HsUtil to have
144 abs_exports :: [([TyVar], idL, idL, [LPrag])], -- (tvs, poly_id, mono_id, prags)
145 abs_binds :: LHsBinds idL -- The dictionary bindings and typechecked user bindings
146 -- mixed up together; you can tell the dict bindings because
147 -- they are all VarBinds
149 -- Consider (AbsBinds tvs ds [(ftvs, poly_f, mono_f) binds]
151 -- Creates bindings for (polymorphic, overloaded) poly_f
152 -- in terms of monomorphic, non-overloaded mono_f
155 -- 1. 'binds' binds mono_f
156 -- 2. ftvs is a subset of tvs
157 -- 3. ftvs includes all tyvars free in ds
159 -- See section 9 of static semantics paper for more details.
160 -- (You can get a PhD for explaining the True Meaning
161 -- of this last construct.)
163 placeHolderNames :: NameSet
164 -- Used for the NameSet in FunBind and PatBind prior to the renamer
165 placeHolderNames = panic "placeHolderNames"
168 instance (OutputableBndr idL, OutputableBndr idR) => Outputable (HsLocalBindsLR idL idR) where
169 ppr (HsValBinds bs) = ppr bs
170 ppr (HsIPBinds bs) = ppr bs
171 ppr EmptyLocalBinds = empty
173 instance (OutputableBndr idL, OutputableBndr idR) => Outputable (HsValBindsLR idL idR) where
174 ppr (ValBindsIn binds sigs)
175 = pprValBindsForUser binds sigs
177 ppr (ValBindsOut sccs sigs)
178 = getPprStyle $ \ sty ->
179 if debugStyle sty then -- Print with sccs showing
180 vcat (map ppr sigs) $$ vcat (map ppr_scc sccs)
182 pprValBindsForUser (unionManyBags (map snd sccs)) sigs
184 ppr_scc (rec_flag, binds) = pp_rec rec_flag <+> pprLHsBinds binds
185 pp_rec Recursive = ptext (sLit "rec")
186 pp_rec NonRecursive = ptext (sLit "nonrec")
188 -- *not* pprLHsBinds because we don't want braces; 'let' and
189 -- 'where' include a list of HsBindGroups and we don't want
190 -- several groups of bindings each with braces around.
191 -- Sort by location before printing
192 pprValBindsForUser :: (OutputableBndr idL, OutputableBndr idR, OutputableBndr id2)
193 => LHsBindsLR idL idR -> [LSig id2] -> SDoc
194 pprValBindsForUser binds sigs
195 = pprDeeperList vcat (map snd (sort_by_loc decls))
198 decls :: [(SrcSpan, SDoc)]
199 decls = [(loc, ppr sig) | L loc sig <- sigs] ++
200 [(loc, ppr bind) | L loc bind <- bagToList binds]
202 sort_by_loc decls = sortLe (\(l1,_) (l2,_) -> l1 <= l2) decls
204 pprLHsBinds :: (OutputableBndr idL, OutputableBndr idR) => LHsBindsLR idL idR -> SDoc
206 | isEmptyLHsBinds binds = empty
207 | otherwise = lbrace <+> pprDeeperList vcat (map ppr (bagToList binds)) <+> rbrace
210 emptyLocalBinds :: HsLocalBindsLR a b
211 emptyLocalBinds = EmptyLocalBinds
213 isEmptyLocalBinds :: HsLocalBindsLR a b -> Bool
214 isEmptyLocalBinds (HsValBinds ds) = isEmptyValBinds ds
215 isEmptyLocalBinds (HsIPBinds ds) = isEmptyIPBinds ds
216 isEmptyLocalBinds EmptyLocalBinds = True
218 isEmptyValBinds :: HsValBindsLR a b -> Bool
219 isEmptyValBinds (ValBindsIn ds sigs) = isEmptyLHsBinds ds && null sigs
220 isEmptyValBinds (ValBindsOut ds sigs) = null ds && null sigs
222 emptyValBindsIn, emptyValBindsOut :: HsValBindsLR a b
223 emptyValBindsIn = ValBindsIn emptyBag []
224 emptyValBindsOut = ValBindsOut [] []
226 emptyLHsBinds :: LHsBindsLR idL idR
227 emptyLHsBinds = emptyBag
229 isEmptyLHsBinds :: LHsBindsLR idL idR -> Bool
230 isEmptyLHsBinds = isEmptyBag
233 plusHsValBinds :: HsValBinds a -> HsValBinds a -> HsValBinds a
234 plusHsValBinds (ValBindsIn ds1 sigs1) (ValBindsIn ds2 sigs2)
235 = ValBindsIn (ds1 `unionBags` ds2) (sigs1 ++ sigs2)
236 plusHsValBinds (ValBindsOut ds1 sigs1) (ValBindsOut ds2 sigs2)
237 = ValBindsOut (ds1 ++ ds2) (sigs1 ++ sigs2)
249 f1p = /\ tvs -> \ [d1,d2] -> letrec DBINDS and BIND
252 gp = ...same again, with gm instead of fm
254 This is a pretty bad translation, because it duplicates all the bindings.
255 So the desugarer tries to do a better job:
257 fp = /\ [a,b] -> \ [d1,d2] -> case tp [a,b] [d1,d2] of
261 tp = /\ [a,b] -> \ [d1,d2] -> letrec DBINDS and BIND
265 instance (OutputableBndr idL, OutputableBndr idR) => Outputable (HsBindLR idL idR) where
266 ppr mbind = ppr_monobind mbind
268 ppr_monobind :: (OutputableBndr idL, OutputableBndr idR) => HsBindLR idL idR -> SDoc
270 ppr_monobind (PatBind { pat_lhs = pat, pat_rhs = grhss }) = pprPatBind pat grhss
271 ppr_monobind (VarBind { var_id = var, var_rhs = rhs }) = pprBndr CaseBind var <+> equals <+> pprExpr (unLoc rhs)
272 ppr_monobind (FunBind { fun_id = fun, fun_infix = inf,
273 fun_matches = matches,
277 Just t -> text "-- tick id = " <> ppr t
278 ) $$ pprFunBind (unLoc fun) inf matches
280 ppr_monobind (AbsBinds { abs_tvs = tyvars, abs_dicts = dictvars,
281 abs_exports = exports, abs_binds = val_binds })
282 = sep [ptext (sLit "AbsBinds"),
283 brackets (interpp'SP tyvars),
284 brackets (interpp'SP dictvars),
285 brackets (sep (punctuate comma (map ppr_exp exports)))]
287 nest 2 ( vcat [pprBndr LetBind x | (_,x,_,_) <- exports]
288 -- Print type signatures
289 $$ pprLHsBinds val_binds )
291 ppr_exp (tvs, gbl, lcl, prags)
292 = vcat [ppr gbl <+> ptext (sLit "<=") <+> ppr tvs <+> ppr lcl,
293 nest 2 (vcat (map (pprPrag gbl) prags))]
296 %************************************************************************
298 Implicit parameter bindings
300 %************************************************************************
306 (DictBinds id) -- Only in typechecker output; binds
307 -- uses of the implicit parameters
309 isEmptyIPBinds :: HsIPBinds id -> Bool
310 isEmptyIPBinds (IPBinds is ds) = null is && isEmptyBag ds
312 type LIPBind id = Located (IPBind id)
314 -- | Implicit parameter bindings.
320 instance (OutputableBndr id) => Outputable (HsIPBinds id) where
321 ppr (IPBinds bs ds) = pprDeeperList vcat (map ppr bs)
324 instance (OutputableBndr id) => Outputable (IPBind id) where
325 ppr (IPBind id rhs) = pprBndr LetBind id <+> equals <+> pprExpr (unLoc rhs)
329 %************************************************************************
331 \subsection{Coercion functions}
333 %************************************************************************
336 -- A HsWrapper is an expression with a hole in it
337 -- We need coercions to have concrete form so that we can zonk them
340 = WpHole -- The identity coercion
342 | WpCompose HsWrapper HsWrapper -- (\a1..an. []) `WpCompose` (\x1..xn. [])
343 -- = (\a1..an \x1..xn. [])
345 | WpCast Coercion -- A cast: [] `cast` co
346 -- Guaranteed not the identity coercion
348 | WpApp Var -- [] d the 'd' is a type-class dictionary or coercion variable
350 | WpTyApp Type -- [] t the 't' is a type or corecion
351 -- ToDo: it'd be tidier if 't' was always a type (not coercion),
352 -- but that is inconvenient in Inst.instCallDicts
354 | WpLam Var -- \d. [] the 'd' is a type-class dictionary or coercion variable
355 | WpTyLam TyVar -- \a. [] the 'a' is a type variable (not coercion var)
356 | WpInline -- inline_me [] Wrap inline around the thing
358 -- Non-empty bindings, so that the identity coercion
359 -- is always exactly WpHole
360 | WpLet (LHsBinds Id) -- let binds in []
361 -- (would be nicer to be core bindings)
363 instance Outputable HsWrapper where
364 ppr co_fn = pprHsWrapper (ptext (sLit "<>")) co_fn
366 pprHsWrapper :: SDoc -> HsWrapper -> SDoc
367 pprHsWrapper it wrap =
370 help it (WpCompose f1 f2) = help (help it f2) f1
371 help it (WpCast co) = sep [it, nest 2 (ptext (sLit "`cast`") <+> pprParendType co)]
372 help it (WpApp id) = sep [it, nest 2 (ppr id)]
373 help it (WpTyApp ty) = sep [it, ptext (sLit "@") <+> pprParendType ty]
374 help it (WpLam id) = sep [ptext (sLit "\\") <> pprBndr LambdaBind id <> dot, it]
375 help it (WpTyLam tv) = sep [ptext (sLit "/\\") <> pprBndr LambdaBind tv <> dot, it]
376 help it (WpLet binds) = sep [ptext (sLit "let") <+> braces (ppr binds), it]
377 help it WpInline = sep [ptext (sLit "_inline_me_"), it]
379 -- in debug mode, print the wrapper
380 -- otherwise just print what's inside
381 getPprStyle (\ s -> if debugStyle s then (help it wrap) else it)
383 (<.>) :: HsWrapper -> HsWrapper -> HsWrapper
386 c1 <.> c2 = c1 `WpCompose` c2
388 mkWpTyApps :: [Type] -> HsWrapper
389 mkWpTyApps tys = mk_co_fn WpTyApp (reverse tys)
391 mkWpApps :: [Var] -> HsWrapper
392 mkWpApps ids = mk_co_fn WpApp (reverse ids)
394 mkWpTyLams :: [TyVar] -> HsWrapper
395 mkWpTyLams ids = mk_co_fn WpTyLam ids
397 mkWpLams :: [Var] -> HsWrapper
398 mkWpLams ids = mk_co_fn WpLam ids
400 mk_co_fn :: (a -> HsWrapper) -> [a] -> HsWrapper
401 mk_co_fn f as = foldr (WpCompose . f) WpHole as
403 idHsWrapper :: HsWrapper
406 isIdHsWrapper :: HsWrapper -> Bool
407 isIdHsWrapper WpHole = True
408 isIdHsWrapper _ = False
412 %************************************************************************
414 \subsection{@Sig@: type signatures and value-modifying user pragmas}
416 %************************************************************************
418 It is convenient to lump ``value-modifying'' user-pragmas (e.g.,
419 ``specialise this function to these four types...'') in with type
420 signatures. Then all the machinery to move them into place, etc.,
424 type LSig name = Located (Sig name)
426 data Sig name -- Signatures and pragmas
427 = -- An ordinary type signature
428 -- f :: Num a => a -> a
429 TypeSig (Located name) (LHsType name)
431 -- A type signature in generated code, notably the code
432 -- generated for record selectors. We simply record
433 -- the desired Id itself, replete with its name, type
434 -- and IdDetails. Otherwise it's just like a type
435 -- signature: there should be an accompanying binding
438 -- An ordinary fixity declaration
440 | FixSig (FixitySig name)
444 | InlineSig (Located name) -- Function name
447 -- A specialisation pragma
448 -- {-# SPECIALISE f :: Int -> Int #-}
449 | SpecSig (Located name) -- Specialise a function or datatype ...
450 (LHsType name) -- ... to these types
453 -- A specialisation pragma for instance declarations only
454 -- {-# SPECIALISE instance Eq [Int] #-}
455 | SpecInstSig (LHsType name) -- (Class tys); should be a specialisation of the
456 -- current instance decl
459 type LFixitySig name = Located (FixitySig name)
460 data FixitySig name = FixitySig (Located name) Fixity
462 -- A Prag conveys pragmas from the type checker to the desugarer
463 type LPrag = Located Prag
469 (HsExpr Id) -- An expression, of the given specialised type, which
470 PostTcType -- specialises the polymorphic function
471 InlineSpec -- Inlining spec for the specialised function
473 isInlinePrag :: Prag -> Bool
474 isInlinePrag (InlinePrag _) = True
475 isInlinePrag _ = False
477 isSpecPrag :: Prag -> Bool
478 isSpecPrag (SpecPrag {}) = True
483 okBindSig :: Sig a -> Bool
486 okHsBootSig :: Sig a -> Bool
487 okHsBootSig (TypeSig _ _) = True
488 okHsBootSig (FixSig _) = True
489 okHsBootSig _ = False
491 okClsDclSig :: Sig a -> Bool
492 okClsDclSig (SpecInstSig _) = False
493 okClsDclSig _ = True -- All others OK
495 okInstDclSig :: Sig a -> Bool
496 okInstDclSig (TypeSig _ _) = False
497 okInstDclSig (FixSig _) = False
498 okInstDclSig _ = True
500 sigForThisGroup :: NameSet -> LSig Name -> Bool
501 sigForThisGroup ns sig
502 = case sigName sig of
504 Just n -> n `elemNameSet` ns
506 sigName :: LSig name -> Maybe name
507 sigName (L _ sig) = sigNameNoLoc sig
509 sigNameNoLoc :: Sig name -> Maybe name
510 sigNameNoLoc (TypeSig n _) = Just (unLoc n)
511 sigNameNoLoc (SpecSig n _ _) = Just (unLoc n)
512 sigNameNoLoc (InlineSig n _) = Just (unLoc n)
513 sigNameNoLoc (FixSig (FixitySig n _)) = Just (unLoc n)
514 sigNameNoLoc _ = Nothing
516 isFixityLSig :: LSig name -> Bool
517 isFixityLSig (L _ (FixSig {})) = True
518 isFixityLSig _ = False
520 isVanillaLSig :: LSig name -> Bool -- User type signatures
521 -- A badly-named function, but it's part of the GHCi (used
522 -- by Haddock) so I don't want to change it gratuitously.
523 isVanillaLSig (L _(TypeSig {})) = True
524 isVanillaLSig _ = False
526 isTypeLSig :: LSig name -> Bool -- Type signatures
527 isTypeLSig (L _(TypeSig {})) = True
528 isTypeLSig (L _(IdSig {})) = True
531 isSpecLSig :: LSig name -> Bool
532 isSpecLSig (L _(SpecSig {})) = True
535 isSpecInstLSig :: LSig name -> Bool
536 isSpecInstLSig (L _ (SpecInstSig {})) = True
537 isSpecInstLSig _ = False
539 isPragLSig :: LSig name -> Bool
540 -- Identifies pragmas
541 isPragLSig (L _ (SpecSig {})) = True
542 isPragLSig (L _ (InlineSig {})) = True
545 isInlineLSig :: LSig name -> Bool
546 -- Identifies inline pragmas
547 isInlineLSig (L _ (InlineSig {})) = True
548 isInlineLSig _ = False
550 hsSigDoc :: Sig name -> SDoc
551 hsSigDoc (TypeSig {}) = ptext (sLit "type signature")
552 hsSigDoc (IdSig {}) = ptext (sLit "id signature")
553 hsSigDoc (SpecSig {}) = ptext (sLit "SPECIALISE pragma")
554 hsSigDoc (InlineSig {}) = ptext (sLit "INLINE pragma")
555 hsSigDoc (SpecInstSig {}) = ptext (sLit "SPECIALISE instance pragma")
556 hsSigDoc (FixSig {}) = ptext (sLit "fixity declaration")
559 Signature equality is used when checking for duplicate signatures
562 eqHsSig :: Eq a => LSig a -> LSig a -> Bool
563 eqHsSig (L _ (FixSig (FixitySig n1 _))) (L _ (FixSig (FixitySig n2 _))) = unLoc n1 == unLoc n2
564 eqHsSig (L _ (IdSig n1)) (L _ (IdSig n2)) = n1 == n2
565 eqHsSig (L _ (TypeSig n1 _)) (L _ (TypeSig n2 _)) = unLoc n1 == unLoc n2
566 eqHsSig (L _ (InlineSig n1 _)) (L _ (InlineSig n2 _)) = unLoc n1 == unLoc n2
567 -- For specialisations, we don't have equality over
568 -- HsType, so it's not convenient to spot duplicate
569 -- specialisations here. Check for this later, when we're in Type land
570 eqHsSig _other1 _other2 = False
574 instance (OutputableBndr name) => Outputable (Sig name) where
575 ppr sig = ppr_sig sig
577 ppr_sig :: OutputableBndr name => Sig name -> SDoc
578 ppr_sig (TypeSig var ty) = pprVarSig (unLoc var) ty
579 ppr_sig (IdSig id) = pprVarSig id (varType id)
580 ppr_sig (FixSig fix_sig) = ppr fix_sig
581 ppr_sig (SpecSig var ty inl) = pragBrackets (pprSpec var ty inl)
582 ppr_sig (InlineSig var inl) = pragBrackets (ppr inl <+> ppr var)
583 ppr_sig (SpecInstSig ty) = pragBrackets (ptext (sLit "SPECIALIZE instance") <+> ppr ty)
585 instance Outputable name => Outputable (FixitySig name) where
586 ppr (FixitySig name fixity) = sep [ppr fixity, ppr name]
588 pragBrackets :: SDoc -> SDoc
589 pragBrackets doc = ptext (sLit "{-#") <+> doc <+> ptext (sLit "#-}")
591 pprVarSig :: (Outputable id, Outputable ty) => id -> ty -> SDoc
592 pprVarSig var ty = sep [ppr var <+> dcolon, nest 2 (ppr ty)]
594 pprSpec :: (Outputable id, Outputable ty) => id -> ty -> InlineSpec -> SDoc
595 pprSpec var ty inl = sep [ptext (sLit "SPECIALIZE") <+> ppr inl <+> pprVarSig var ty]
597 pprPrag :: Outputable id => id -> LPrag -> SDoc
598 pprPrag var (L _ (InlinePrag inl)) = ppr inl <+> ppr var
599 pprPrag var (L _ (SpecPrag _expr ty inl)) = pprSpec var ty inl