[project @ 2001-06-11 12:24:51 by simonpj]
[ghc-hetmet.git] / ghc / compiler / hsSyn / HsBinds.lhs
1 %
2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
3 %
4 \section[HsBinds]{Abstract syntax: top-level bindings and signatures}
5
6 Datatype for: @HsBinds@, @Bind@, @Sig@, @MonoBinds@.
7
8 \begin{code}
9 module HsBinds where
10
11 #include "HsVersions.h"
12
13 import {-# SOURCE #-} HsExpr ( HsExpr, pprExpr,
14                                Match,  pprFunBind,
15                                GRHSs,  pprPatBind )
16
17 -- friends:
18 import HsTypes          ( HsType )
19 import CoreSyn          ( CoreExpr )
20 import PprCore          ( {- instance Outputable (Expr a) -} )
21
22 --others:
23 import Name             ( Name )
24 import PrelNames        ( isUnboundName )
25 import NameSet          ( NameSet, elemNameSet, nameSetToList )
26 import BasicTypes       ( RecFlag(..), Fixity )
27 import Outputable       
28 import SrcLoc           ( SrcLoc )
29 import Var              ( TyVar )
30 import Class            ( DefMeth (..) )
31 \end{code}
32
33 %************************************************************************
34 %*                                                                      *
35 \subsection{Bindings: @HsBinds@}
36 %*                                                                      *
37 %************************************************************************
38
39 The following syntax may produce new syntax which is not part of the input,
40 and which is instead a translation of the input to the typechecker.
41 Syntax translations are marked TRANSLATION in comments. New empty
42 productions are useful in development but may not appear in the final
43 grammar.
44
45 Collections of bindings, created by dependency analysis and translation:
46
47 \begin{code}
48 data HsBinds id pat             -- binders and bindees
49   = EmptyBinds
50
51   | ThenBinds   (HsBinds id pat)
52                 (HsBinds id pat)
53
54   | MonoBind    (MonoBinds id pat)
55                 [Sig id]                -- Empty on typechecker output
56                 RecFlag
57 \end{code}
58
59 \begin{code}
60 nullBinds :: HsBinds id pat -> Bool
61
62 nullBinds EmptyBinds            = True
63 nullBinds (ThenBinds b1 b2)     = nullBinds b1 && nullBinds b2
64 nullBinds (MonoBind b _ _)      = nullMonoBinds b
65
66 mkMonoBind :: MonoBinds id pat -> [Sig id] -> RecFlag -> HsBinds id pat
67 mkMonoBind EmptyMonoBinds _ _ = EmptyBinds
68 mkMonoBind mbinds sigs is_rec = MonoBind mbinds sigs is_rec
69 \end{code}
70
71 \begin{code}
72 instance (Outputable pat, Outputable id) =>
73                 Outputable (HsBinds id pat) where
74     ppr binds = ppr_binds binds
75
76 ppr_binds EmptyBinds = empty
77 ppr_binds (ThenBinds binds1 binds2)
78     = ppr_binds binds1 $$ ppr_binds binds2
79 ppr_binds (MonoBind bind sigs is_rec)
80      = vcat [ppr_isrec,
81              vcat (map ppr sigs),
82              ppr bind
83        ]
84      where
85        ppr_isrec = getPprStyle $ \ sty -> 
86                    if userStyle sty then empty else
87                    case is_rec of
88                         Recursive    -> ptext SLIT("{- rec -}")
89                         NonRecursive -> ptext SLIT("{- nonrec -}")
90 \end{code}
91
92 %************************************************************************
93 %*                                                                      *
94 \subsection{Bindings: @MonoBinds@}
95 %*                                                                      *
96 %************************************************************************
97
98 Global bindings (where clauses)
99
100 \begin{code}
101 data MonoBinds id pat
102   = EmptyMonoBinds
103
104   | AndMonoBinds    (MonoBinds id pat)
105                     (MonoBinds id pat)
106
107   | FunMonoBind     id          -- Used for both functions      f x = e
108                                 -- and variables                f = \x -> e
109                                 -- Reason: the Match stuff lets us have an optional
110                                 --         result type sig      f :: a->a = ...mentions a...
111                     Bool                -- True => infix declaration
112                     [Match id pat]
113                     SrcLoc
114
115   | PatMonoBind     pat         -- The pattern is never a simple variable;
116                                 -- That case is done by FunMonoBind
117                     (GRHSs id pat)
118                     SrcLoc
119
120   | VarMonoBind     id                  -- TRANSLATION
121                     (HsExpr id pat)
122
123   | CoreMonoBind    id                  -- TRANSLATION
124                     CoreExpr            -- No zonking; this is a final CoreExpr with Ids and Types!
125
126   | AbsBinds                            -- Binds abstraction; TRANSLATION
127                 [TyVar]                 -- Type variables
128                 [id]                    -- Dicts
129                 [([TyVar], id, id)]     -- (type variables, polymorphic, momonmorphic) triples
130                 NameSet                 -- Set of *polymorphic* variables that have an INLINE pragma
131                 (MonoBinds id pat)      -- The "business end"
132
133         -- Creates bindings for *new* (polymorphic, overloaded) locals
134         -- in terms of *old* (monomorphic, non-overloaded) ones.
135         --
136         -- See section 9 of static semantics paper for more details.
137         -- (You can get a PhD for explaining the True Meaning
138         --  of this last construct.)
139 \end{code}
140
141 What AbsBinds means
142 ~~~~~~~~~~~~~~~~~~~
143          AbsBinds tvs
144                   [d1,d2]
145                   [(tvs1, f1p, f1m), 
146                    (tvs2, f2p, f2m)]
147                   BIND
148 means
149
150         f1p = /\ tvs -> \ [d1,d2] -> letrec DBINDS and BIND 
151                                       in fm
152
153         gp = ...same again, with gm instead of fm
154
155 This is a pretty bad translation, because it duplicates all the bindings.
156 So the desugarer tries to do a better job:
157
158         fp = /\ [a,b] -> \ [d1,d2] -> case tp [a,b] [d1,d2] of
159                                         (fm,gm) -> fm
160         ..ditto for gp..
161
162         p = /\ [a,b] -> \ [d1,d2] -> letrec DBINDS and BIND 
163                                       in (fm,gm)
164
165 \begin{code}
166 -- We keep the invariant that a MonoBinds is only empty 
167 -- if it is exactly EmptyMonoBinds
168
169 nullMonoBinds :: MonoBinds id pat -> Bool
170 nullMonoBinds EmptyMonoBinds         = True
171 nullMonoBinds other_monobind         = False
172
173 andMonoBinds :: MonoBinds id pat -> MonoBinds id pat -> MonoBinds id pat
174 andMonoBinds EmptyMonoBinds mb = mb
175 andMonoBinds mb EmptyMonoBinds = mb
176 andMonoBinds mb1 mb2 = AndMonoBinds mb1 mb2
177
178 andMonoBindList :: [MonoBinds id pat] -> MonoBinds id pat
179 andMonoBindList binds
180   = loop1 binds
181   where
182     loop1 [] = EmptyMonoBinds
183     loop1 (EmptyMonoBinds : binds) = loop1 binds
184     loop1 (b:bs) = loop2 b bs
185
186         -- acc is non-empty
187     loop2 acc [] = acc
188     loop2 acc (EmptyMonoBinds : bs) = loop2 acc bs
189     loop2 acc (b:bs) = loop2 (acc `AndMonoBinds` b) bs
190 \end{code}
191
192
193 \begin{code}
194 instance (Outputable id, Outputable pat) =>
195                 Outputable (MonoBinds id pat) where
196     ppr mbind = ppr_monobind mbind
197
198
199 ppr_monobind :: (Outputable id, Outputable pat) => MonoBinds id pat -> SDoc
200 ppr_monobind EmptyMonoBinds = empty
201 ppr_monobind (AndMonoBinds binds1 binds2)
202       = ppr_monobind binds1 $$ ppr_monobind binds2
203
204 ppr_monobind (PatMonoBind pat grhss locn)       = pprPatBind pat grhss
205 ppr_monobind (FunMonoBind fun inf matches locn) = pprFunBind fun matches
206       -- ToDo: print infix if appropriate
207
208 ppr_monobind (VarMonoBind name expr)
209       = sep [ppr name <+> equals, nest 4 (pprExpr expr)]
210
211 ppr_monobind (CoreMonoBind name expr)
212       = sep [ppr name <+> equals, nest 4 (ppr expr)]
213
214 ppr_monobind (AbsBinds tyvars dictvars exports inlines val_binds)
215      = sep [ptext SLIT("AbsBinds"),
216             brackets (interpp'SP tyvars),
217             brackets (interpp'SP dictvars),
218             brackets (sep (punctuate comma (map ppr exports))),
219             brackets (interpp'SP (nameSetToList inlines))]
220        $$
221        nest 4 (ppr val_binds)
222 \end{code}
223
224 %************************************************************************
225 %*                                                                      *
226 \subsection{@Sig@: type signatures and value-modifying user pragmas}
227 %*                                                                      *
228 %************************************************************************
229
230 It is convenient to lump ``value-modifying'' user-pragmas (e.g.,
231 ``specialise this function to these four types...'') in with type
232 signatures.  Then all the machinery to move them into place, etc.,
233 serves for both.
234
235 \begin{code}
236 data Sig name
237   = Sig         name            -- a bog-std type signature
238                 (HsType name)
239                 SrcLoc
240
241   | ClassOpSig  name            -- Selector name
242                 (DefMeth name)  -- Default-method info
243                                 -- See "THE NAMING STORY" in HsDecls
244                 (HsType name)
245                 SrcLoc
246
247   | SpecSig     name            -- specialise a function or datatype ...
248                 (HsType name)   -- ... to these types
249                 SrcLoc
250
251   | InlineSig   name            -- INLINE f
252                 (Maybe Int)     -- phase
253                 SrcLoc
254
255   | NoInlineSig name            -- NOINLINE f
256                 (Maybe Int)     -- phase
257                 SrcLoc
258
259   | SpecInstSig (HsType name)   -- (Class tys); should be a specialisation of the 
260                                 -- current instance decl
261                 SrcLoc
262
263   | FixSig      (FixitySig name)        -- Fixity declaration
264
265
266 data FixitySig name = FixitySig name Fixity SrcLoc 
267
268 instance Eq name => Eq (FixitySig name) where
269    (FixitySig n1 f1 _) == (FixitySig n2 f2 _) = n1==n2 && f1==f2
270 \end{code}
271
272 \begin{code}
273 okBindSig :: NameSet -> Sig Name -> Bool
274 okBindSig ns (ClassOpSig _ _ _ _)                               = False
275 okBindSig ns sig = sigForThisGroup ns sig
276
277 okClsDclSig :: NameSet -> Sig Name -> Bool
278 okClsDclSig ns (Sig _ _ _)                                        = False
279 okClsDclSig ns sig = sigForThisGroup ns sig
280
281 okInstDclSig :: NameSet -> Sig Name -> Bool
282 okInstDclSig ns (Sig _ _ _)                                        = False
283 okInstDclSig ns (FixSig _)                                         = False
284 okInstDclSig ns (SpecInstSig _ _)                                  = True
285 okInstDclSig ns sig = sigForThisGroup ns sig
286
287 sigForThisGroup ns sig 
288   = case sigName sig of
289         Nothing                  -> False
290         Just n | isUnboundName n -> True        -- Don't complain about an unbound name again
291                | otherwise       -> n `elemNameSet` ns
292
293 sigName :: Sig name -> Maybe name
294 sigName (Sig         n _ _)             = Just n
295 sigName (ClassOpSig  n _ _ _)           = Just n
296 sigName (SpecSig     n _ _)             = Just n
297 sigName (InlineSig   n _   _)           = Just n
298 sigName (NoInlineSig n _   _)           = Just n
299 sigName (FixSig (FixitySig n _ _))      = Just n
300 sigName other                           = Nothing
301
302 isFixitySig :: Sig name -> Bool
303 isFixitySig (FixSig _) = True
304 isFixitySig _          = False
305
306 isClassOpSig :: Sig name -> Bool
307 isClassOpSig (ClassOpSig _ _ _ _) = True
308 isClassOpSig _                    = False
309
310 isPragSig :: Sig name -> Bool
311         -- Identifies pragmas 
312 isPragSig (SpecSig _ _ _)     = True
313 isPragSig (InlineSig   _ _ _) = True
314 isPragSig (NoInlineSig _ _ _) = True
315 isPragSig (SpecInstSig _ _)   = True
316 isPragSig other               = False
317 \end{code}
318
319 \begin{code}
320 hsSigDoc (Sig        _ _ loc)         = (SLIT("type signature"),loc)
321 hsSigDoc (ClassOpSig _ _ _ loc)       = (SLIT("class-method type signature"), loc)
322 hsSigDoc (SpecSig    _ _ loc)         = (SLIT("SPECIALISE pragma"),loc)
323 hsSigDoc (InlineSig  _ _    loc)      = (SLIT("INLINE pragma"),loc)
324 hsSigDoc (NoInlineSig  _ _  loc)      = (SLIT("NOINLINE pragma"),loc)
325 hsSigDoc (SpecInstSig _ loc)          = (SLIT("SPECIALISE instance pragma"),loc)
326 hsSigDoc (FixSig (FixitySig _ _ loc)) = (SLIT("fixity declaration"), loc)
327 \end{code}
328
329 \begin{code}
330 instance (Outputable name) => Outputable (Sig name) where
331     ppr sig = ppr_sig sig
332
333 ppr_sig :: Outputable name => Sig name -> SDoc
334 ppr_sig (Sig var ty _)
335       = sep [ppr var <+> dcolon, nest 4 (ppr ty)]
336
337 ppr_sig (ClassOpSig var dm ty _)
338       = sep [ppr var <+> pp_dm <+> dcolon, nest 4 (ppr ty)]
339       where
340         pp_dm = case dm of 
341                   DefMeth _  -> equals  -- Default method indicator
342                   GenDefMeth -> semi    -- Generic method indicator
343                   NoDefMeth  -> empty   -- No Method at all
344
345 ppr_sig (SpecSig var ty _)
346       = sep [ hsep [text "{-# SPECIALIZE", ppr var, dcolon],
347               nest 4 (ppr ty <+> text "#-}")
348         ]
349
350 ppr_sig (InlineSig var phase _)
351       = hsep [text "{-# INLINE", ppr_phase phase, ppr var, text "#-}"]
352
353 ppr_sig (NoInlineSig var phase _)
354       = hsep [text "{-# NOINLINE", ppr_phase phase, ppr var, text "#-}"]
355
356 ppr_sig (SpecInstSig ty _)
357       = hsep [text "{-# SPECIALIZE instance", ppr ty, text "#-}"]
358
359 ppr_sig (FixSig fix_sig) = ppr fix_sig
360
361
362 instance Outputable name => Outputable (FixitySig name) where
363   ppr (FixitySig name fixity loc) = sep [ppr fixity, ppr name]
364
365 ppr_phase :: Maybe Int -> SDoc
366 ppr_phase Nothing  = empty
367 ppr_phase (Just n) = int n
368 \end{code}
369
370 Checking for distinct signatures; oh, so boring
371
372
373 \begin{code}
374 eqHsSig :: Sig Name -> Sig Name -> Bool
375 eqHsSig (Sig n1 _ _)         (Sig n2 _ _)         = n1 == n2
376 eqHsSig (InlineSig n1 _ _)   (InlineSig n2 _ _)   = n1 == n2
377 eqHsSig (NoInlineSig n1 _ _) (NoInlineSig n2 _ _) = n1 == n2
378
379 eqHsSig (SpecInstSig ty1 _)  (SpecInstSig ty2 _)  = ty1 == ty2
380 eqHsSig (SpecSig n1 ty1 _)   (SpecSig n2 ty2 _)   =
381     -- may have many specialisations for one value;
382     -- but not ones that are exactly the same...
383     (n1 == n2) && (ty1 == ty2)
384
385 eqHsSig _other1 _other2 = False
386 \end{code}