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