Massive patch for the first months work adding System FC to GHC #14
[ghc-hetmet.git] / compiler / hsSyn / HsPat.lhs
1 %
2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
3 %
4 \section[PatSyntax]{Abstract Haskell syntax---patterns}
5
6 \begin{code}
7 module HsPat (
8         Pat(..), InPat, OutPat, LPat, 
9         
10         HsConDetails(..), hsConArgs,
11
12         mkPrefixConPat, mkCharLitPat, mkNilPat, mkCoPat,
13
14         isBangHsBind,   
15         patsAreAllCons, isConPat, isSigPat, isWildPat,
16         patsAreAllLits, isLitPat, isIrrefutableHsPat
17     ) where
18
19 #include "HsVersions.h"
20
21
22 import {-# SOURCE #-} HsExpr            ( SyntaxExpr )
23
24 -- friends:
25 import HsBinds          ( DictBinds, HsBind(..), ExprCoFn, isIdCoercion, emptyLHsBinds, pprLHsBinds )
26 import HsLit            ( HsLit(HsCharPrim), HsOverLit )
27 import HsTypes          ( LHsType, PostTcType )
28 import BasicTypes       ( Boxity, tupleParens )
29 -- others:
30 import PprCore          ( {- instance OutputableBndr TyVar -} )
31 import TysWiredIn       ( nilDataCon, charDataCon, charTy )
32 import Var              ( TyVar )
33 import DataCon          ( DataCon, dataConTyCon )
34 import TyCon            ( isProductTyCon )
35 import Outputable       
36 import Type             ( Type )
37 import SrcLoc           ( Located(..), unLoc, noLoc )
38 \end{code}
39
40
41 \begin{code}
42 type InPat id  = LPat id        -- No 'Out' constructors
43 type OutPat id = LPat id        -- No 'In' constructors
44
45 type LPat id = Located (Pat id)
46
47 data Pat id
48   =     ------------ Simple patterns ---------------
49     WildPat     PostTcType              -- Wild card
50   | VarPat      id                      -- Variable
51   | VarPatOut   id (DictBinds id)       -- Used only for overloaded Ids; the 
52                                         -- bindings give its overloaded instances
53   | LazyPat     (LPat id)               -- Lazy pattern
54   | AsPat       (Located id) (LPat id)  -- As pattern
55   | ParPat      (LPat id)               -- Parenthesised pattern
56   | BangPat     (LPat id)               -- Bang patterng
57
58         ------------ Lists, tuples, arrays ---------------
59   | ListPat     [LPat id]               -- Syntactic list
60                 PostTcType              -- The type of the elements
61                     
62   | TuplePat    [LPat id]               -- Tuple
63                 Boxity                  -- UnitPat is TuplePat []
64                 PostTcType
65         -- You might think that the PostTcType was redundant, but it's essential
66         --      data T a where
67         --        T1 :: Int -> T Int
68         --      f :: (T a, a) -> Int
69         --      f (T1 x, z) = z
70         -- When desugaring, we must generate
71         --      f = /\a. \v::a.  case v of (t::T a, w::a) ->
72         --                       case t of (T1 (x::Int)) -> 
73         -- Note the (w::a), NOT (w::Int), because we have not yet
74         -- refined 'a' to Int.  So we must know that the second component
75         -- of the tuple is of type 'a' not Int.  See selectMatchVar
76
77   | PArrPat     [LPat id]               -- Syntactic parallel array
78                 PostTcType              -- The type of the elements
79
80         ------------ Constructor patterns ---------------
81   | ConPatIn    (Located id)
82                 (HsConDetails id (LPat id))
83
84   | ConPatOut {
85         pat_con   :: Located DataCon,
86         pat_tvs   :: [TyVar],           -- Existentially bound type variables
87                                         --   including any bound coercion variables
88         pat_dicts :: [id],              -- Ditto dictionaries
89         pat_binds :: DictBinds id,      -- Bindings involving those dictionaries
90         pat_args  :: HsConDetails id (LPat id),
91         pat_ty    :: Type               -- The type of the pattern
92     }
93
94         ------------ Literal and n+k patterns ---------------
95   | LitPat          HsLit               -- Used for *non-overloaded* literal patterns:
96                                         -- Int#, Char#, Int, Char, String, etc.
97
98   | NPat            (HsOverLit id)              -- ALWAYS positive
99                     (Maybe (SyntaxExpr id))     -- Just (Name of 'negate') for negative
100                                                 -- patterns, Nothing otherwise
101                     (SyntaxExpr id)             -- Equality checker, of type t->t->Bool
102                     PostTcType                  -- Type of the pattern
103
104   | NPlusKPat       (Located id)        -- n+k pattern
105                     (HsOverLit id)      -- It'll always be an HsIntegral
106                     (SyntaxExpr id)     -- (>=) function, of type t->t->Bool
107                     (SyntaxExpr id)     -- Name of '-' (see RnEnv.lookupSyntaxName)
108
109         ------------ Generics ---------------
110   | TypePat         (LHsType id)        -- Type pattern for generic definitions
111                                         -- e.g  f{| a+b |} = ...
112                                         -- These show up only in class declarations,
113                                         -- and should be a top-level pattern
114
115         ------------ Pattern type signatures ---------------
116   | SigPatIn        (LPat id)           -- Pattern with a type signature
117                     (LHsType id)
118
119   | SigPatOut       (LPat id)           -- Pattern with a type signature
120                     Type
121
122         ------------ Dictionary patterns (translation only) ---------------
123   | DictPat         -- Used when destructing Dictionaries with an explicit case
124                     [id]                        -- superclass dicts
125                     [id]                        -- methods
126
127         ------------ Pattern coercions (translation only) ---------------
128   | CoPat       ExprCoFn                -- If co::t1 -> t2, p::t2, 
129                                         -- then (CoPat co p) :: t1
130                 (Pat id)                -- No nested location reqd
131                 Type    
132 \end{code}
133
134 HsConDetails is use both for patterns and for data type declarations
135
136 \begin{code}
137 data HsConDetails id arg
138   = PrefixCon [arg]                     -- C p1 p2 p3
139   | RecCon    [(Located id, arg)]       -- C { x = p1, y = p2 }
140   | InfixCon  arg arg                   -- p1 `C` p2
141
142 hsConArgs :: HsConDetails id arg -> [arg]
143 hsConArgs (PrefixCon ps)   = ps
144 hsConArgs (RecCon fs)      = map snd fs
145 hsConArgs (InfixCon p1 p2) = [p1,p2]
146 \end{code}
147
148
149 %************************************************************************
150 %*                                                                      *
151 %*              Printing patterns
152 %*                                                                      *
153 %************************************************************************
154
155 \begin{code}
156 instance (OutputableBndr name) => Outputable (Pat name) where
157     ppr = pprPat
158
159 pprPatBndr :: OutputableBndr name => name -> SDoc
160 pprPatBndr var                  -- Print with type info if -dppr-debug is on
161   = getPprStyle $ \ sty ->
162     if debugStyle sty then
163         parens (pprBndr LambdaBind var)         -- Could pass the site to pprPat
164                                                 -- but is it worth it?
165     else
166         ppr var
167
168 pprPat :: (OutputableBndr name) => Pat name -> SDoc
169 pprPat (VarPat var)       = pprPatBndr var
170 pprPat (VarPatOut var bs) = parens (pprPatBndr var <+> braces (ppr bs))
171 pprPat (WildPat _)        = char '_'
172 pprPat (LazyPat pat)      = char '~' <> ppr pat
173 pprPat (BangPat pat)      = char '!' <> ppr pat
174 pprPat (AsPat name pat)   = parens (hcat [ppr name, char '@', ppr pat])
175 pprPat (ParPat pat)       = parens (ppr pat)
176 pprPat (ListPat pats _)     = brackets (interpp'SP pats)
177 pprPat (PArrPat pats _)     = pabrackets (interpp'SP pats)
178 pprPat (TuplePat pats bx _) = tupleParens bx (interpp'SP pats)
179
180 pprPat (ConPatIn con details) = pprUserCon con details
181 pprPat (ConPatOut { pat_con = con, pat_tvs = tvs, pat_dicts = dicts, 
182                     pat_binds = binds, pat_args = details })
183   = getPprStyle $ \ sty ->      -- Tiresome; in TcBinds.tcRhs we print out a 
184     if debugStyle sty then      -- typechecked Pat in an error message, 
185                                 -- and we want to make sure it prints nicely
186         ppr con <+> sep [ hsep (map pprPatBndr tvs) <+> hsep (map pprPatBndr dicts),
187                           pprLHsBinds binds, pprConArgs details]
188     else pprUserCon con details
189
190 pprPat (LitPat s)             = ppr s
191 pprPat (NPat l Nothing  _ _)  = ppr l
192 pprPat (NPat l (Just _) _ _)  = char '-' <> ppr l
193 pprPat (NPlusKPat n k _ _)    = hcat [ppr n, char '+', ppr k]
194 pprPat (TypePat ty)           = ptext SLIT("{|") <> ppr ty <> ptext SLIT("|}")
195 pprPat (CoPat co pat _)       = parens (ppr co) <+> ptext SLIT("`cast`") <+> ppr pat
196 pprPat (SigPatIn pat ty)      = ppr pat <+> dcolon <+> ppr ty
197 pprPat (SigPatOut pat ty)     = ppr pat <+> dcolon <+> ppr ty
198 pprPat (DictPat ds ms)        = parens (sep [ptext SLIT("{-dict-}"),
199                                              brackets (interpp'SP ds),
200                                              brackets (interpp'SP ms)])
201
202 pprUserCon c (InfixCon p1 p2) = ppr p1 <+> ppr c <+> ppr p2
203 pprUserCon c details          = ppr c <+> pprConArgs details
204
205 pprConArgs (PrefixCon pats) = interppSP pats
206 pprConArgs (InfixCon p1 p2) = interppSP [p1,p2]
207 pprConArgs (RecCon rpats)   = braces (hsep (punctuate comma (map (pp_rpat) rpats)))
208                             where
209                               pp_rpat (v, p) = hsep [ppr v, char '=', ppr p]
210
211
212 -- add parallel array brackets around a document
213 --
214 pabrackets   :: SDoc -> SDoc
215 pabrackets p  = ptext SLIT("[:") <> p <> ptext SLIT(":]")
216 \end{code}
217
218
219 %************************************************************************
220 %*                                                                      *
221 %*              Building patterns
222 %*                                                                      *
223 %************************************************************************
224
225 \begin{code}
226 mkPrefixConPat :: DataCon -> [OutPat id] -> Type -> OutPat id
227 -- Make a vanilla Prefix constructor pattern
228 mkPrefixConPat dc pats ty 
229   = noLoc $ ConPatOut { pat_con = noLoc dc, pat_tvs = [], pat_dicts = [],
230                         pat_binds = emptyLHsBinds, pat_args = PrefixCon pats, 
231                         pat_ty = ty }
232
233 mkNilPat :: Type -> OutPat id
234 mkNilPat ty = mkPrefixConPat nilDataCon [] ty
235
236 mkCharLitPat :: Char -> OutPat id
237 mkCharLitPat c = mkPrefixConPat charDataCon [noLoc $ LitPat (HsCharPrim c)] charTy
238
239 mkCoPat :: ExprCoFn -> OutPat id -> Type -> OutPat id
240 mkCoPat co lpat@(L loc pat) ty
241   | isIdCoercion co = lpat
242   | otherwise = L loc (CoPat co pat ty)
243 \end{code}
244
245
246 %************************************************************************
247 %*                                                                      *
248 %* Predicates for checking things about pattern-lists in EquationInfo   *
249 %*                                                                      *
250 %************************************************************************
251
252 \subsection[Pat-list-predicates]{Look for interesting things in patterns}
253
254 Unlike in the Wadler chapter, where patterns are either ``variables''
255 or ``constructors,'' here we distinguish between:
256 \begin{description}
257 \item[unfailable:]
258 Patterns that cannot fail to match: variables, wildcards, and lazy
259 patterns.
260
261 These are the irrefutable patterns; the two other categories
262 are refutable patterns.
263
264 \item[constructor:]
265 A non-literal constructor pattern (see next category).
266
267 \item[literal patterns:]
268 At least the numeric ones may be overloaded.
269 \end{description}
270
271 A pattern is in {\em exactly one} of the above three categories; `as'
272 patterns are treated specially, of course.
273
274 The 1.3 report defines what ``irrefutable'' and ``failure-free'' patterns are.
275 \begin{code}
276 isWildPat (WildPat _) = True
277 isWildPat other       = False
278
279 patsAreAllCons :: [Pat id] -> Bool
280 patsAreAllCons pat_list = all isConPat pat_list
281
282 isConPat (AsPat _ pat)   = isConPat (unLoc pat)
283 isConPat (ConPatIn {})   = True
284 isConPat (ConPatOut {})  = True
285 isConPat (ListPat {})    = True
286 isConPat (PArrPat {})    = True
287 isConPat (TuplePat {})   = True
288 isConPat (DictPat ds ms) = (length ds + length ms) > 1
289 isConPat other           = False
290
291 isSigPat (SigPatIn _ _)  = True
292 isSigPat (SigPatOut _ _) = True
293 isSigPat other           = False
294
295 patsAreAllLits :: [Pat id] -> Bool
296 patsAreAllLits pat_list = all isLitPat pat_list
297
298 isLitPat (AsPat _ pat)          = isLitPat (unLoc pat)
299 isLitPat (LitPat _)             = True
300 isLitPat (NPat _ _ _ _)         = True
301 isLitPat (NPlusKPat _ _ _ _)    = True
302 isLitPat other                  = False
303
304 isBangHsBind :: HsBind id -> Bool
305 -- In this module because HsPat is above HsBinds in the import graph
306 isBangHsBind (PatBind { pat_lhs = L _ (BangPat p) }) = True
307 isBangHsBind bind                                    = False
308
309 isIrrefutableHsPat :: LPat id -> Bool
310 -- This function returns False if it's in doubt; specifically
311 -- on a ConPatIn it doesn't know the size of the constructor family
312 -- But if it returns True, the pattern is definitely irrefutable
313 isIrrefutableHsPat pat
314   = go pat
315   where
316     go (L _ pat)         = go1 pat
317
318     go1 (WildPat _)         = True
319     go1 (VarPat _)          = True
320     go1 (VarPatOut _ _)     = True
321     go1 (LazyPat pat)       = True
322     go1 (BangPat pat)       = go pat
323     go1 (CoPat _ pat _)     = go1 pat
324     go1 (ParPat pat)        = go pat
325     go1 (AsPat _ pat)       = go pat
326     go1 (SigPatIn pat _)    = go pat
327     go1 (SigPatOut pat _)   = go pat
328     go1 (TuplePat pats _ _) = all go pats
329     go1 (ListPat pats _)    = False
330     go1 (PArrPat pats _)    = False     -- ?
331
332     go1 (ConPatIn _ _) = False  -- Conservative
333     go1 (ConPatOut{ pat_con = L _ con, pat_args = details }) 
334         =  isProductTyCon (dataConTyCon con)
335         && all go (hsConArgs details)
336
337     go1 (LitPat _)         = False
338     go1 (NPat _ _ _ _)     = False
339     go1 (NPlusKPat _ _ _ _) = False
340
341     go1 (TypePat _)   = panic "isIrrefutableHsPat: type pattern"
342     go1 (DictPat _ _) = panic "isIrrefutableHsPat: type pattern"
343 \end{code}
344