[project @ 2000-02-16 12:56:22 by panne]
[ghc-hetmet.git] / ghc / compiler / hsSyn / HsDecls.lhs
1 %
2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
3 %
4 \section[HsDecls]{Abstract syntax: global declarations}
5
6 Definitions for: @TyDecl@ and @ConDecl@, @ClassDecl@,
7 @InstDecl@, @DefaultDecl@ and @ForeignDecl@.
8
9 \begin{code}
10 module HsDecls (
11         HsDecl(..), TyClDecl(..), InstDecl(..), RuleDecl(..), RuleBndr(..),
12         DefaultDecl(..), ForeignDecl(..), ForKind(..),
13         ExtName(..), isDynamic,
14         ConDecl(..), ConDetails(..), BangType(..),
15         IfaceSig(..),  SpecDataSig(..), 
16         hsDeclName, tyClDeclName, isClassDecl, isSynDecl, isDataDecl, countTyClDecls
17     ) where
18
19 #include "HsVersions.h"
20
21 -- friends:
22 import HsBinds          ( HsBinds, MonoBinds, Sig, FixitySig(..), nullMonoBinds )
23 import HsExpr           ( HsExpr )
24 import HsPragmas        ( DataPragmas, ClassPragmas )
25 import HsTypes
26 import HsCore           ( UfExpr, UfBinder, IfaceSig(..), UfRuleBody )
27 import BasicTypes       ( Fixity, NewOrData(..) )
28 import CallConv         ( CallConv, pprCallConv )
29 import Var              ( TyVar )
30
31 -- others:
32 import PprType
33 import {-# SOURCE #-} FunDeps ( pprFundeps )
34 import Outputable       
35 import SrcLoc           ( SrcLoc )
36 import Util
37 \end{code}
38
39
40 %************************************************************************
41 %*                                                                      *
42 \subsection[HsDecl]{Declarations}
43 %*                                                                      *
44 %************************************************************************
45
46 \begin{code}
47 data HsDecl name pat
48   = TyClD       (TyClDecl name pat)
49   | InstD       (InstDecl  name pat)
50   | DefD        (DefaultDecl name)
51   | ValD        (HsBinds name pat)
52   | ForD        (ForeignDecl name)
53   | SigD        (IfaceSig name)
54   | FixD        (FixitySig name)
55   | RuleD       (RuleDecl name pat)
56
57 -- NB: all top-level fixity decls are contained EITHER
58 -- EITHER FixDs
59 -- OR     in the ClassDecls in TyClDs
60 --
61 -- The former covers
62 --      a) data constructors
63 --      b) class methods (but they can be also done in the
64 --              signatures of class decls)
65 --      c) imported functions (that have an IfacSig)
66 --      d) top level decls
67 --
68 -- The latter is for class methods only
69 \end{code}
70
71 \begin{code}
72 #ifdef DEBUG
73 hsDeclName :: (Outputable name, Outputable pat)
74            => HsDecl name pat -> name
75 #endif
76 hsDeclName (TyClD decl)                          = tyClDeclName decl
77 hsDeclName (SigD  (IfaceSig name _ _ _))         = name
78 hsDeclName (InstD (InstDecl _ _ _ name _))       = name
79 hsDeclName (ForD  (ForeignDecl name _ _ _ _ _))  = name
80 hsDeclName (FixD  (FixitySig name _ _))          = name
81 -- Others don't make sense
82 #ifdef DEBUG
83 hsDeclName x                                  = pprPanic "HsDecls.hsDeclName" (ppr x)
84 #endif
85
86 tyClDeclName :: TyClDecl name pat -> name
87 tyClDeclName (TyData _ _ name _ _ _ _ _)        = name
88 tyClDeclName (TySynonym name _ _ _)             = name
89 tyClDeclName (ClassDecl _ name _ _ _ _ _ _ _ _ _) = name
90 \end{code}
91
92 \begin{code}
93 instance (Outputable name, Outputable pat)
94         => Outputable (HsDecl name pat) where
95
96     ppr (TyClD dcl)  = ppr dcl
97     ppr (SigD sig)   = ppr sig
98     ppr (ValD binds) = ppr binds
99     ppr (DefD def)   = ppr def
100     ppr (InstD inst) = ppr inst
101     ppr (ForD fd)    = ppr fd
102     ppr (FixD fd)    = ppr fd
103     ppr (RuleD rd)   = ppr rd
104 \end{code}
105
106
107 %************************************************************************
108 %*                                                                      *
109 \subsection[TyDecl]{@data@, @newtype@ or @type@ (synonym) type declaration}
110 %*                                                                      *
111 %************************************************************************
112
113 \begin{code}
114 data TyClDecl name pat
115   = TyData      NewOrData
116                 (HsContext name) -- context
117                 name             -- type constructor
118                 [HsTyVar name]   -- type variables
119                 [ConDecl name]   -- data constructors (empty if abstract)
120                 (Maybe [name])   -- derivings; Nothing => not specified
121                                  -- (i.e., derive default); Just [] => derive
122                                  -- *nothing*; Just <list> => as you would
123                                  -- expect...
124                 (DataPragmas name)
125                 SrcLoc
126
127   | TySynonym   name            -- type constructor
128                 [HsTyVar name]  -- type variables
129                 (HsType name)   -- synonym expansion
130                 SrcLoc
131
132   | ClassDecl   (HsContext name)        -- context...
133                 name                    -- name of the class
134                 [HsTyVar name]          -- the class type variables
135                 [([name], [name])]      -- functional dependencies
136                 [Sig name]              -- methods' signatures
137                 (MonoBinds name pat)    -- default methods
138                 (ClassPragmas name)
139                 name name [name]        -- The names of the tycon, datacon, and superclass selectors
140                                         -- for this class.  These are filled in as the ClassDecl is made.
141                 SrcLoc
142 \end{code}
143
144 \begin{code}
145 countTyClDecls :: [TyClDecl name pat] -> (Int, Int, Int, Int)
146         -- class, data, newtype, synonym decls
147 countTyClDecls decls 
148  = (length [() | ClassDecl _ _ _ _ _ _ _ _ _ _ _ <- decls],
149     length [() | TyData DataType _ _ _ _ _ _ _ <- decls],
150     length [() | TyData NewType  _ _ _ _ _ _ _ <- decls],
151     length [() | TySynonym _ _ _ _             <- decls])
152
153 isDataDecl, isSynDecl, isClassDecl :: TyClDecl name pat -> Bool
154
155 isSynDecl (TySynonym _ _ _ _) = True
156 isSynDecl other               = False
157
158 isDataDecl (TyData _ _ _ _ _ _ _ _) = True
159 isDataDecl other                    = False
160
161 isClassDecl (ClassDecl _ _ _ _ _ _ _ _ _ _ _) = True
162 isClassDecl other                           = False
163 \end{code}
164
165 \begin{code}
166 instance (Outputable name, Outputable pat)
167               => Outputable (TyClDecl name pat) where
168
169     ppr (TySynonym tycon tyvars mono_ty src_loc)
170       = hang (pp_decl_head SLIT("type") empty tycon tyvars)
171              4 (ppr mono_ty)
172
173     ppr (TyData new_or_data context tycon tyvars condecls derivings pragmas src_loc)
174       = pp_tydecl
175                   (pp_decl_head keyword (pprHsContext context) tycon tyvars)
176                   (pp_condecls condecls)
177                   derivings
178       where
179         keyword = case new_or_data of
180                         NewType  -> SLIT("newtype")
181                         DataType -> SLIT("data")
182
183     ppr (ClassDecl context clas tyvars fds sigs methods pragmas _ _ _ src_loc)
184       | null sigs       -- No "where" part
185       = top_matter
186
187       | otherwise       -- Laid out
188       = sep [hsep [top_matter, ptext SLIT("where {")],
189                nest 4 (vcat [sep (map ppr_sig sigs),
190                                    ppr methods,
191                                    char '}'])]
192       where
193         top_matter = hsep [ptext SLIT("class"), pprHsContext context,
194                             ppr clas, hsep (map (ppr) tyvars), pprFundeps fds]
195         ppr_sig sig = ppr sig <> semi
196
197
198 pp_decl_head str pp_context tycon tyvars
199   = hsep [ptext str, pp_context, ppr tycon,
200            interppSP tyvars, ptext SLIT("=")]
201
202 pp_condecls []     = empty              -- Curious!
203 pp_condecls (c:cs) = sep (ppr c : map (\ c -> ptext SLIT("|") <+> ppr c) cs)
204
205 pp_tydecl pp_head pp_decl_rhs derivings
206   = hang pp_head 4 (sep [
207         pp_decl_rhs,
208         case derivings of
209           Nothing          -> empty
210           Just ds          -> hsep [ptext SLIT("deriving"), parens (interpp'SP ds)]
211     ])
212 \end{code}
213
214 A type for recording what types a datatype should be specialised to.
215 It's called a ``Sig'' because it's sort of like a ``type signature''
216 for an datatype declaration.
217
218 \begin{code}
219 data SpecDataSig name
220   = SpecDataSig name            -- tycon to specialise
221                 (HsType name)
222                 SrcLoc
223
224 instance (Outputable name)
225               => Outputable (SpecDataSig name) where
226
227     ppr (SpecDataSig tycon ty _)
228       = hsep [text "{-# SPECIALIZE data", ppr ty, text "#-}"]
229 \end{code}
230
231 %************************************************************************
232 %*                                                                      *
233 \subsection[ConDecl]{A data-constructor declaration}
234 %*                                                                      *
235 %************************************************************************
236
237 \begin{code}
238 data ConDecl name
239   = ConDecl     name                    -- Constructor name
240
241                 [HsTyVar name]          -- Existentially quantified type variables
242                 (HsContext name)        -- ...and context
243                                         -- If both are empty then there are no existentials
244
245                 (ConDetails name)
246                 SrcLoc
247
248 data ConDetails name
249   = VanillaCon                  -- prefix-style con decl
250                 [BangType name]
251
252   | InfixCon                    -- infix-style con decl
253                 (BangType name)
254                 (BangType name)
255
256   | RecCon                      -- record-style con decl
257                 [([name], BangType name)]       -- list of "fields"
258
259   | NewCon                      -- newtype con decl, possibly with a labelled field.
260                 (HsType name)
261                 (Maybe name)    -- Just x => labelled field 'x'
262
263 data BangType name
264   = Banged   (HsType name)      -- HsType: to allow Haskell extensions
265   | Unbanged (HsType name)      -- (MonoType only needed for straight Haskell)
266   | Unpacked (HsType name)      -- Field is strict and to be unpacked if poss.
267 \end{code}
268
269 \begin{code}
270 instance (Outputable name) => Outputable (ConDecl name) where
271     ppr (ConDecl con tvs cxt con_details  loc)
272       = sep [pprForAll tvs, pprHsContext cxt, ppr_con_details con con_details]
273
274 ppr_con_details con (InfixCon ty1 ty2)
275   = hsep [ppr_bang ty1, ppr con, ppr_bang ty2]
276
277 ppr_con_details con (VanillaCon tys)
278   = ppr con <+> hsep (map (ppr_bang) tys)
279
280 ppr_con_details con (NewCon ty Nothing)
281   = ppr con <+> pprParendHsType ty
282
283 ppr_con_details con (NewCon ty (Just x))
284   = ppr con <+> braces pp_field 
285    where
286     pp_field = ppr x <+> dcolon <+> pprParendHsType ty
287  
288 ppr_con_details con (RecCon fields)
289   = ppr con <+> braces (hsep (punctuate comma (map ppr_field fields)))
290   where
291     ppr_field (ns, ty) = hsep (map (ppr) ns) <+> 
292                          dcolon <+>
293                          ppr_bang ty
294
295 ppr_bang (Banged   ty) = ptext SLIT("!") <> pprParendHsType ty
296 ppr_bang (Unbanged ty) = pprParendHsType ty
297 ppr_bang (Unpacked ty) = ptext SLIT("! !") <> pprParendHsType ty
298 \end{code}
299
300
301 %************************************************************************
302 %*                                                                      *
303 \subsection[InstDecl]{An instance declaration
304 %*                                                                      *
305 %************************************************************************
306
307 \begin{code}
308 data InstDecl name pat
309   = InstDecl    (HsType name)   -- Context => Class Instance-type
310                                 -- Using a polytype means that the renamer conveniently
311                                 -- figures out the quantified type variables for us.
312
313                 (MonoBinds name pat)
314
315                 [Sig name]              -- User-supplied pragmatic info
316
317                 name                    -- Name for the dictionary function
318
319                 SrcLoc
320 \end{code}
321
322 \begin{code}
323 instance (Outputable name, Outputable pat)
324               => Outputable (InstDecl name pat) where
325
326     ppr (InstDecl inst_ty binds uprags dfun_name src_loc)
327       = getPprStyle $ \ sty ->
328         if ifaceStyle sty || (nullMonoBinds binds && null uprags) then
329            hsep [ptext SLIT("instance"), ppr inst_ty]
330         else
331            vcat [hsep [ptext SLIT("instance"), ppr inst_ty, ptext SLIT("where")],
332                  nest 4 (ppr uprags),
333                  nest 4 (ppr binds) ]
334 \end{code}
335
336
337 %************************************************************************
338 %*                                                                      *
339 \subsection[DefaultDecl]{A @default@ declaration}
340 %*                                                                      *
341 %************************************************************************
342
343 There can only be one default declaration per module, but it is hard
344 for the parser to check that; we pass them all through in the abstract
345 syntax, and that restriction must be checked in the front end.
346
347 \begin{code}
348 data DefaultDecl name
349   = DefaultDecl [HsType name]
350                 SrcLoc
351
352 instance (Outputable name)
353               => Outputable (DefaultDecl name) where
354
355     ppr (DefaultDecl tys src_loc)
356       = ptext SLIT("default") <+> parens (interpp'SP tys)
357 \end{code}
358
359 %************************************************************************
360 %*                                                                      *
361 \subsection{Foreign function interface declaration}
362 %*                                                                      *
363 %************************************************************************
364
365 \begin{code}
366 data ForeignDecl name = 
367    ForeignDecl 
368         name 
369         ForKind   
370         (HsType name)
371         ExtName
372         CallConv
373         SrcLoc
374
375 instance (Outputable name)
376               => Outputable (ForeignDecl name) where
377
378     ppr (ForeignDecl nm imp_exp ty ext_name cconv src_loc)
379       = ptext SLIT("foreign") <+> ppr_imp_exp <+> pprCallConv cconv <+> 
380         ppr ext_name <+> ppr_unsafe <+> ppr nm <+> dcolon <+> ppr ty
381         where
382          (ppr_imp_exp, ppr_unsafe) =
383            case imp_exp of
384              FoLabel     -> (ptext SLIT("label"), empty)
385              FoExport    -> (ptext SLIT("export"), empty)
386              FoImport us 
387                 | us        -> (ptext SLIT("import"), ptext SLIT("unsafe"))
388                 | otherwise -> (ptext SLIT("import"), empty)
389
390 data ForKind
391  = FoLabel
392  | FoExport
393  | FoImport Bool -- True  => unsafe call.
394
395 data ExtName
396  = Dynamic 
397  | ExtName FAST_STRING (Maybe FAST_STRING)
398
399 isDynamic :: ExtName -> Bool
400 isDynamic Dynamic = True
401 isDynamic _       = False
402
403
404 instance Outputable ExtName where
405   ppr Dynamic      = ptext SLIT("dynamic")
406   ppr (ExtName nm mb_mod) = 
407      case mb_mod of { Nothing -> empty; Just m -> doubleQuotes (ptext m) } <+> 
408      doubleQuotes (ptext nm)
409
410 \end{code}
411
412 %************************************************************************
413 %*                                                                      *
414 \subsection{Transformation rules}
415 %*                                                                      *
416 %************************************************************************
417
418 \begin{code}
419 data RuleDecl name pat
420   = RuleDecl
421         FAST_STRING             -- Rule name
422         [name]                  -- Forall'd tyvars, filled in by the renamer with
423                                 -- tyvars mentioned in sigs; then filled out by typechecker
424         [RuleBndr name]         -- Forall'd term vars
425         (HsExpr name pat)       -- LHS
426         (HsExpr name pat)       -- RHS
427         SrcLoc          
428
429   | IfaceRuleDecl               -- One that's come in from an interface file
430         name
431         (UfRuleBody name)
432         SrcLoc          
433
434 data RuleBndr name
435   = RuleBndr name
436   | RuleBndrSig name (HsType name)
437
438 instance (Outputable name, Outputable pat)
439               => Outputable (RuleDecl name pat) where
440   ppr (RuleDecl name tvs ns lhs rhs loc)
441         = sep [text "{-# RULES" <+> doubleQuotes (ptext name),
442                pp_forall, ppr lhs, equals <+> ppr rhs,
443                text "#-}" ]
444         where
445           pp_forall | null tvs && null ns = empty
446                     | otherwise           = text "forall" <+> 
447                                             fsep (map ppr tvs ++ map ppr ns)
448                                             <> dot
449   ppr (IfaceRuleDecl var body loc) = text "An imported rule..."
450
451 instance Outputable name => Outputable (RuleBndr name) where
452    ppr (RuleBndr name) = ppr name
453    ppr (RuleBndrSig name ty) = ppr name <> dcolon <> ppr ty
454 \end{code}