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