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