[project @ 2005-03-18 13:37:27 by simonmar]
[ghc-hetmet.git] / ghc / compiler / hsSyn / HsTypes.lhs
1 ]%
2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
3 %
4 \section[HsTypes]{Abstract syntax: user-defined types}
5
6 \begin{code}
7 module HsTypes (
8         HsType(..), LHsType, 
9         HsTyVarBndr(..), LHsTyVarBndr,
10         HsExplicitForAll(..),
11         HsContext, LHsContext,
12         HsPred(..), LHsPred,
13
14         LBangType, BangType, HsBang(..), 
15         getBangType, getBangStrictness, 
16         
17         mkExplicitHsForAllTy, mkImplicitHsForAllTy, 
18         hsTyVarName, hsTyVarNames, replaceTyVarName,
19         hsLTyVarName, hsLTyVarNames, hsLTyVarLocName, hsLTyVarLocNames,
20         splitHsInstDeclTy,
21         
22         -- Type place holder
23         PostTcType, placeHolderType,
24
25         -- Name place holder
26         SyntaxName, placeHolderName,
27
28         -- Printing
29         pprParendHsType, pprHsForAll, pprHsContext, ppr_hs_context, pprHsTyVarBndr
30     ) where
31
32 #include "HsVersions.h"
33
34 import {-# SOURCE #-} HsExpr ( HsSplice, pprSplice )
35
36 import Type             ( Type )
37 import Kind             ( {- instance Outputable Kind -}, Kind,
38                           pprParendKind, pprKind, isLiftedTypeKind )
39 import Name             ( Name, mkInternalName )
40 import OccName          ( mkVarOcc )
41 import BasicTypes       ( IPName, Boxity, tupleParens )
42 import PrelNames        ( unboundKey )
43 import SrcLoc           ( noSrcLoc, Located(..), unLoc, noSrcSpan )
44 import StaticFlags      ( opt_PprStyle_Debug )
45 import Outputable
46 \end{code}
47
48
49 %************************************************************************
50 %*                                                                      *
51 \subsection{Annotating the syntax}
52 %*                                                                      *
53 %************************************************************************
54
55 \begin{code}
56 type PostTcType = Type          -- Used for slots in the abstract syntax
57                                 -- where we want to keep slot for a type
58                                 -- to be added by the type checker...but
59                                 -- before typechecking it's just bogus
60
61 placeHolderType :: PostTcType   -- Used before typechecking
62 placeHolderType  = panic "Evaluated the place holder for a PostTcType"
63
64
65 type SyntaxName = Name          -- These names are filled in by the renamer
66                                 -- Before then they are a placeHolderName (so that
67                                 --      we can still print the HsSyn)
68                                 -- They correspond to "rebindable syntax";
69                                 -- See RnEnv.lookupSyntaxName
70
71 placeHolderName :: SyntaxName
72 placeHolderName = mkInternalName unboundKey 
73                         (mkVarOcc FSLIT("syntaxPlaceHolder")) 
74                         noSrcLoc
75 \end{code}
76
77 %************************************************************************
78 %*                                                                      *
79 \subsection{Bang annotations}
80 %*                                                                      *
81 %************************************************************************
82
83 \begin{code}
84 type LBangType name = Located (BangType name)
85 type BangType name  = HsType name       -- Bangs are in the HsType data type
86
87 data HsBang = HsNoBang  -- Only used as a return value for getBangStrictness,
88                         -- never appears on a HsBangTy
89             | HsStrict  -- ! 
90             | HsUnbox   -- {-# UNPACK #-} ! (GHC extension, meaning "unbox")
91
92 instance Outputable HsBang where
93     ppr (HsNoBang) = empty
94     ppr (HsStrict) = char '!'
95     ppr (HsUnbox)  = ptext SLIT("!!")
96
97 getBangType :: LHsType a -> LHsType a
98 getBangType (L _ (HsBangTy _ ty)) = ty
99 getBangType ty                    = ty
100
101 getBangStrictness :: LHsType a -> HsBang
102 getBangStrictness (L _ (HsBangTy s _)) = s
103 getBangStrictness _                    = HsNoBang
104 \end{code}
105
106
107 %************************************************************************
108 %*                                                                      *
109 \subsection{Data types}
110 %*                                                                      *
111 %************************************************************************
112
113 This is the syntax for types as seen in type signatures.
114
115 \begin{code}
116 type LHsContext name = Located (HsContext name)
117
118 type HsContext name = [LHsPred name]
119
120 type LHsPred name = Located (HsPred name)
121
122 data HsPred name = HsClassP name [LHsType name]
123                  | HsIParam (IPName name) (LHsType name)
124
125 type LHsType name = Located (HsType name)
126
127 data HsType name
128   = HsForAllTy  HsExplicitForAll        -- Renamer leaves this flag unchanged, to record the way
129                                         -- the user wrote it originally, so that the printer can
130                                         -- print it as the user wrote it
131                 [LHsTyVarBndr name]     -- With ImplicitForAll, this is the empty list
132                                         -- until the renamer fills in the variables
133                 (LHsContext name)
134                 (LHsType name)
135
136   | HsTyVar             name            -- Type variable or type constructor
137
138   | HsBangTy    HsBang (LHsType name)   -- Bang-style type annotations 
139
140   | HsAppTy             (LHsType name)
141                         (LHsType name)
142
143   | HsFunTy             (LHsType name)   -- function type
144                         (LHsType name)
145
146   | HsListTy            (LHsType name)  -- Element type
147
148   | HsPArrTy            (LHsType name)  -- Elem. type of parallel array: [:t:]
149
150   | HsTupleTy           Boxity
151                         [LHsType name]  -- Element types (length gives arity)
152
153   | HsOpTy              (LHsType name) (Located name) (LHsType name)
154
155   | HsParTy             (LHsType name)   
156         -- Parenthesis preserved for the precedence re-arrangement in RnTypes
157         -- It's important that a * (b + c) doesn't get rearranged to (a*b) + c!
158         -- 
159         -- However, NB that toHsType doesn't add HsParTys (in an effort to keep
160         -- interface files smaller), so when printing a HsType we may need to
161         -- add parens.  
162
163   | HsNumTy             Integer         -- Generics only
164
165   | HsPredTy            (HsPred name)   -- Only used in the type of an instance
166                                         -- declaration, eg.  Eq [a] -> Eq a
167                                         --                             ^^^^
168                                         --                            HsPredTy
169                                         -- Note no need for location info on the
170                                         -- enclosed HsPred; the one on the type will do
171
172   | HsKindSig           (LHsType name)  -- (ty :: kind)
173                         Kind            -- A type with a kind signature
174
175   | HsSpliceTy          (HsSplice name)
176
177 data HsExplicitForAll = Explicit | Implicit
178
179 -----------------------
180 -- Combine adjacent for-alls. 
181 -- The following awkward situation can happen otherwise:
182 --      f :: forall a. ((Num a) => Int)
183 -- might generate HsForAll (Just [a]) [] (HsForAll Nothing [Num a] t)
184 -- Then a isn't discovered as ambiguous, and we abstract the AbsBinds wrt []
185 -- but the export list abstracts f wrt [a].  Disaster.
186 --
187 -- A valid type must have one for-all at the top of the type, or of the fn arg types
188
189 mkImplicitHsForAllTy     ctxt ty = mkHsForAllTy Implicit [] ctxt ty
190 mkExplicitHsForAllTy tvs ctxt ty = mkHsForAllTy Explicit tvs ctxt ty
191
192 mkHsForAllTy :: HsExplicitForAll -> [LHsTyVarBndr name] -> LHsContext name -> LHsType name -> HsType name
193 -- Smart constructor for HsForAllTy
194 mkHsForAllTy exp tvs (L _ []) ty = mk_forall_ty exp tvs ty
195 mkHsForAllTy exp tvs ctxt ty = HsForAllTy exp tvs ctxt ty
196
197 -- mk_forall_ty makes a pure for-all type (no context)
198 mk_forall_ty Explicit [] ty                           = unLoc ty        -- Explicit for-all with no tyvars
199 mk_forall_ty exp  tvs  (L _ (HsParTy ty))                     = mk_forall_ty exp tvs ty
200 mk_forall_ty exp1 tvs1 (L _ (HsForAllTy exp2 tvs2 ctxt ty)) = mkHsForAllTy (exp1 `plus` exp2) (tvs1 ++ tvs2) ctxt ty
201 mk_forall_ty exp  tvs  ty                             = HsForAllTy exp tvs (L noSrcSpan []) ty
202
203 Implicit `plus` Implicit = Implicit
204 exp1     `plus` exp2     = Explicit
205
206 type LHsTyVarBndr name = Located (HsTyVarBndr name)
207
208 data HsTyVarBndr name
209   = UserTyVar name
210   | KindedTyVar name Kind
211         -- *** NOTA BENE *** A "monotype" in a pragma can have
212         -- for-alls in it, (mostly to do with dictionaries).  These
213         -- must be explicitly Kinded.
214
215 hsTyVarName :: HsTyVarBndr name -> name
216 hsTyVarName (UserTyVar n)     = n
217 hsTyVarName (KindedTyVar n _) = n
218
219 hsLTyVarName :: LHsTyVarBndr name -> name
220 hsLTyVarName = hsTyVarName . unLoc
221
222 hsTyVarNames :: [HsTyVarBndr name] -> [name]
223 hsTyVarNames tvs = map hsTyVarName tvs
224
225 hsLTyVarNames :: [LHsTyVarBndr name] -> [name]
226 hsLTyVarNames = map hsLTyVarName
227
228 hsLTyVarLocName :: LHsTyVarBndr name -> Located name
229 hsLTyVarLocName = fmap hsTyVarName
230
231 hsLTyVarLocNames :: [LHsTyVarBndr name] -> [Located name]
232 hsLTyVarLocNames = map hsLTyVarLocName
233
234 replaceTyVarName :: HsTyVarBndr name1 -> name2 -> HsTyVarBndr name2
235 replaceTyVarName (UserTyVar n)     n' = UserTyVar n'
236 replaceTyVarName (KindedTyVar n k) n' = KindedTyVar n' k
237 \end{code}
238
239
240 \begin{code}
241 splitHsInstDeclTy 
242     :: OutputableBndr name
243     => HsType name 
244     -> ([LHsTyVarBndr name], HsContext name, name, [LHsType name])
245         -- Split up an instance decl type, returning the pieces
246
247 splitHsInstDeclTy inst_ty
248   = case inst_ty of
249         HsParTy (L _ ty)              -> splitHsInstDeclTy ty
250         HsForAllTy _ tvs cxt (L _ ty) -> split_tau tvs (unLoc cxt) ty
251         other                         -> split_tau []  []          other
252     -- The type vars should have been computed by now, even if they were implicit
253   where
254     split_tau tvs cxt (HsPredTy (HsClassP cls tys)) = (tvs, cxt, cls, tys)
255     split_tau tvs cxt (HsParTy (L _ ty))            = split_tau tvs cxt ty
256 \end{code}
257
258
259 %************************************************************************
260 %*                                                                      *
261 \subsection{Pretty printing}
262 %*                                                                      *
263 %************************************************************************
264
265 NB: these types get printed into interface files, so 
266     don't change the printing format lightly
267
268 \begin{code}
269 instance (OutputableBndr name) => Outputable (HsType name) where
270     ppr ty = pprHsType ty
271
272 instance (Outputable name) => Outputable (HsTyVarBndr name) where
273     ppr (UserTyVar name)        = ppr name
274     ppr (KindedTyVar name kind) = pprHsTyVarBndr name kind
275
276 instance OutputableBndr name => Outputable (HsPred name) where
277     ppr (HsClassP clas tys) = ppr clas <+> hsep (map (pprParendHsType.unLoc) tys)
278     ppr (HsIParam n ty)    = hsep [ppr n, dcolon, ppr ty]
279
280 pprHsTyVarBndr :: Outputable name => name -> Kind -> SDoc
281 pprHsTyVarBndr name kind | isLiftedTypeKind kind = ppr name
282                          | otherwise             = hsep [ppr name, dcolon, pprParendKind kind]
283
284 pprHsForAll exp tvs cxt 
285   | show_forall = forall_part <+> pprHsContext (unLoc cxt)
286   | otherwise   = pprHsContext (unLoc cxt)
287   where
288     show_forall =  opt_PprStyle_Debug
289                 || (not (null tvs) && is_explicit)
290     is_explicit = case exp of {Explicit -> True; Implicit -> False}
291     forall_part = ptext SLIT("forall") <+> interppSP tvs <> dot
292
293 pprHsContext :: (OutputableBndr name) => HsContext name -> SDoc
294 pprHsContext []  = empty
295 pprHsContext cxt = ppr_hs_context cxt <+> ptext SLIT("=>")
296
297 ppr_hs_context []  = empty
298 ppr_hs_context cxt = parens (interpp'SP cxt)
299 \end{code}
300
301 \begin{code}
302 pREC_TOP = (0 :: Int)  -- type   in ParseIface.y
303 pREC_FUN = (1 :: Int)  -- btype  in ParseIface.y
304                         -- Used for LH arg of (->)
305 pREC_OP  = (2 :: Int)   -- Used for arg of any infix operator
306                         -- (we don't keep their fixities around)
307 pREC_CON = (3 :: Int)   -- Used for arg of type applicn: 
308                         -- always parenthesise unless atomic
309
310 maybeParen :: Int       -- Precedence of context
311            -> Int       -- Precedence of top-level operator
312            -> SDoc -> SDoc      -- Wrap in parens if (ctxt >= op)
313 maybeParen ctxt_prec op_prec p | ctxt_prec >= op_prec = parens p
314                                | otherwise            = p
315         
316 -- printing works more-or-less as for Types
317
318 pprHsType, pprParendHsType :: (OutputableBndr name) => HsType name -> SDoc
319
320 pprHsType ty       = getPprStyle $ \sty -> ppr_mono_ty pREC_TOP (prepare sty ty)
321 pprParendHsType ty = ppr_mono_ty pREC_CON ty
322
323 -- Before printing a type
324 -- (a) Remove outermost HsParTy parens
325 -- (b) Drop top-level for-all type variables in user style
326 --     since they are implicit in Haskell
327 prepare sty (HsParTy ty)          = prepare sty (unLoc ty)
328 prepare sty ty                    = ty
329
330 ppr_mono_lty ctxt_prec ty = ppr_mono_ty ctxt_prec (unLoc ty)
331
332 ppr_mono_ty ctxt_prec (HsForAllTy exp tvs ctxt ty)
333   = maybeParen ctxt_prec pREC_FUN $
334     sep [pprHsForAll exp tvs ctxt, ppr_mono_lty pREC_TOP ty]
335
336 -- gaw 2004
337 ppr_mono_ty ctxt_prec (HsBangTy b ty)     = ppr b <> ppr ty
338 ppr_mono_ty ctxt_prec (HsTyVar name)      = ppr name
339 ppr_mono_ty ctxt_prec (HsFunTy ty1 ty2)   = ppr_fun_ty ctxt_prec ty1 ty2
340 ppr_mono_ty ctxt_prec (HsTupleTy con tys) = tupleParens con (interpp'SP tys)
341 ppr_mono_ty ctxt_prec (HsKindSig ty kind) = parens (ppr_mono_lty pREC_TOP ty <+> dcolon <+> pprKind kind)
342 ppr_mono_ty ctxt_prec (HsListTy ty)       = brackets (ppr_mono_lty pREC_TOP ty)
343 ppr_mono_ty ctxt_prec (HsPArrTy ty)       = pabrackets (ppr_mono_lty pREC_TOP ty)
344 ppr_mono_ty ctxt_prec (HsPredTy pred)     = braces (ppr pred)
345 ppr_mono_ty ctxt_prec (HsNumTy n)         = integer n  -- generics only
346 ppr_mono_ty ctxt_prec (HsSpliceTy s)      = pprSplice s
347
348 ppr_mono_ty ctxt_prec (HsAppTy fun_ty arg_ty)
349   = maybeParen ctxt_prec pREC_CON $
350     hsep [ppr_mono_lty pREC_FUN fun_ty, ppr_mono_lty pREC_CON arg_ty]
351
352 ppr_mono_ty ctxt_prec (HsOpTy ty1 op ty2)  
353   = maybeParen ctxt_prec pREC_OP $
354     ppr_mono_lty pREC_OP ty1 <+> ppr op <+> ppr_mono_lty pREC_OP ty2
355
356 ppr_mono_ty ctxt_prec (HsParTy ty)
357   = parens (ppr_mono_lty pREC_TOP ty)
358   -- Put the parens in where the user did
359   -- But we still use the precedence stuff to add parens because
360   --    toHsType doesn't put in any HsParTys, so we may still need them
361
362 --------------------------
363 ppr_fun_ty ctxt_prec ty1 ty2
364   = let p1 = ppr_mono_lty pREC_FUN ty1
365         p2 = ppr_mono_lty pREC_TOP ty2
366     in
367     maybeParen ctxt_prec pREC_FUN $
368     sep [p1, ptext SLIT("->") <+> p2]
369
370 --------------------------
371 pabrackets p = ptext SLIT("[:") <> p <> ptext SLIT(":]")
372 \end{code}
373
374