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