Super-monster patch implementing the new typechecker -- at last
[ghc-hetmet.git] / compiler / deSugar / MatchCon.lhs
1 %
2 % (c) The University of Glasgow 2006
3 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4 %
5
6 Pattern-matching constructors
7
8 \begin{code}
9 {-# OPTIONS -fno-warn-incomplete-patterns #-}
10 -- The above warning supression flag is a temporary kludge.
11 -- While working on this module you are encouraged to remove it and fix
12 -- any warnings in the module. See
13 --     http://hackage.haskell.org/trac/ghc/wiki/Commentary/CodingStyle#Warnings
14 -- for details
15
16 module MatchCon ( matchConFamily ) where
17
18 #include "HsVersions.h"
19
20 import {-# SOURCE #-} Match     ( match )
21
22 import HsSyn
23 import DsBinds
24 import DataCon
25 import TcType
26 import DsMonad
27 import DsUtils
28 import Util     ( all2, takeList, zipEqual )
29 import ListSetOps ( runs )
30 import Id
31 import Var      ( Var )
32 import NameEnv
33 import SrcLoc
34 import Outputable
35 \end{code}
36
37 We are confronted with the first column of patterns in a set of
38 equations, all beginning with constructors from one ``family'' (e.g.,
39 @[]@ and @:@ make up the @List@ ``family'').  We want to generate the
40 alternatives for a @Case@ expression.  There are several choices:
41 \begin{enumerate}
42 \item
43 Generate an alternative for every constructor in the family, whether
44 they are used in this set of equations or not; this is what the Wadler
45 chapter does.
46 \begin{description}
47 \item[Advantages:]
48 (a)~Simple.  (b)~It may also be that large sparsely-used constructor
49 families are mainly handled by the code for literals.
50 \item[Disadvantages:]
51 (a)~Not practical for large sparsely-used constructor families, e.g.,
52 the ASCII character set.  (b)~Have to look up a list of what
53 constructors make up the whole family.
54 \end{description}
55
56 \item
57 Generate an alternative for each constructor used, then add a default
58 alternative in case some constructors in the family weren't used.
59 \begin{description}
60 \item[Advantages:]
61 (a)~Alternatives aren't generated for unused constructors.  (b)~The
62 STG is quite happy with defaults.  (c)~No lookup in an environment needed.
63 \item[Disadvantages:]
64 (a)~A spurious default alternative may be generated.
65 \end{description}
66
67 \item
68 ``Do it right:'' generate an alternative for each constructor used,
69 and add a default alternative if all constructors in the family
70 weren't used.
71 \begin{description}
72 \item[Advantages:]
73 (a)~You will get cases with only one alternative (and no default),
74 which should be amenable to optimisation.  Tuples are a common example.
75 \item[Disadvantages:]
76 (b)~Have to look up constructor families in TDE (as above).
77 \end{description}
78 \end{enumerate}
79
80 We are implementing the ``do-it-right'' option for now.  The arguments
81 to @matchConFamily@ are the same as to @match@; the extra @Int@
82 returned is the number of constructors in the family.
83
84 The function @matchConFamily@ is concerned with this
85 have-we-used-all-the-constructors? question; the local function
86 @match_cons_used@ does all the real work.
87 \begin{code}
88 matchConFamily :: [Id]
89                -> Type
90                -> [[EquationInfo]]
91                -> DsM MatchResult
92 -- Each group of eqns is for a single constructor
93 matchConFamily (var:vars) ty groups
94   = do  { alts <- mapM (matchOneCon vars ty) groups
95         ; return (mkCoAlgCaseMatchResult var ty alts) }
96
97 type ConArgPats = HsConDetails (LPat Id) (HsRecFields Id (LPat Id))
98
99 matchOneCon :: [Id]
100             -> Type
101             -> [EquationInfo]
102             -> DsM (DataCon, [Var], MatchResult)
103 matchOneCon vars ty (eqn1 : eqns)       -- All eqns for a single constructor
104   = do  { arg_vars <- selectConMatchVars arg_tys args1
105                 -- Use the first equation as a source of 
106                 -- suggestions for the new variables
107
108         -- Divide into sub-groups; see Note [Record patterns]
109         ; let groups :: [[(ConArgPats, EquationInfo)]]
110               groups = runs compatible_pats [ (pat_args (firstPat eqn), eqn) 
111                                             | eqn <- eqn1:eqns ]
112
113         ; match_results <- mapM (match_group arg_vars) groups
114
115         ; return (con1, tvs1 ++ dicts1 ++ arg_vars, 
116                   foldr1 combineMatchResults match_results) }
117   where
118     ConPatOut { pat_con = L _ con1, pat_ty = pat_ty1,
119                 pat_tvs = tvs1, pat_dicts = dicts1, pat_args = args1 }
120               = firstPat eqn1
121     fields1 = dataConFieldLabels con1
122         
123     arg_tys  = dataConInstOrigArgTys con1 inst_tys
124     inst_tys = tcTyConAppArgs pat_ty1 ++ 
125                mkTyVarTys (takeList (dataConExTyVars con1) tvs1)
126         -- Newtypes opaque, hence tcTyConAppArgs
127         -- dataConInstOrigArgTys takes the univ and existential tyvars
128         -- and returns the types of the *value* args, which is what we want
129
130     match_group :: [Id] -> [(ConArgPats, EquationInfo)] -> DsM MatchResult
131     -- All members of the group have compatible ConArgPats
132     match_group arg_vars arg_eqn_prs
133       = do { (wraps, eqns') <- mapAndUnzipM shift arg_eqn_prs
134            ; let group_arg_vars = select_arg_vars arg_vars arg_eqn_prs
135            ; match_result <- match (group_arg_vars ++ vars) ty eqns'
136            ; return (adjustMatchResult (foldr1 (.) wraps) match_result) }
137
138     shift (_, eqn@(EqnInfo { eqn_pats = ConPatOut{ pat_tvs = tvs, pat_dicts = ds, 
139                                                    pat_binds = bind, pat_args = args
140                                         } : pats }))
141       = do { ds_ev_binds <- dsTcEvBinds bind
142            ; return (wrapBinds (tvs `zip` tvs1) 
143                     . wrapBinds (ds  `zip` dicts1)
144                     . wrapDsEvBinds ds_ev_binds,
145                     eqn { eqn_pats = conArgPats arg_tys args ++ pats }) }
146
147     -- Choose the right arg_vars in the right order for this group
148     -- Note [Record patterns]
149     select_arg_vars arg_vars ((arg_pats, _) : _)
150       | RecCon flds <- arg_pats
151       , let rpats = rec_flds flds  
152       , not (null rpats)     -- Treated specially; cf conArgPats
153       = ASSERT2( length fields1 == length arg_vars, 
154                  ppr con1 $$ ppr fields1 $$ ppr arg_vars )
155         map lookup_fld rpats
156       | otherwise
157       = arg_vars
158       where
159         fld_var_env = mkNameEnv $ zipEqual "get_arg_vars" fields1 arg_vars
160         lookup_fld rpat = lookupNameEnv_NF fld_var_env 
161                                            (idName (unLoc (hsRecFieldId rpat)))
162
163 -----------------
164 compatible_pats :: (ConArgPats,a) -> (ConArgPats,a) -> Bool
165 -- Two constructors have compatible argument patterns if the number
166 -- and order of sub-matches is the same in both cases
167 compatible_pats (RecCon flds1, _) (RecCon flds2, _) = same_fields flds1 flds2
168 compatible_pats (RecCon flds1, _) _                 = null (rec_flds flds1)
169 compatible_pats _                 (RecCon flds2, _) = null (rec_flds flds2)
170 compatible_pats _                 _                 = True -- Prefix or infix con
171
172 same_fields :: HsRecFields Id (LPat Id) -> HsRecFields Id (LPat Id) -> Bool
173 same_fields flds1 flds2 
174   = all2 (\f1 f2 -> unLoc (hsRecFieldId f1) == unLoc (hsRecFieldId f2))
175          (rec_flds flds1) (rec_flds flds2)
176
177
178 -----------------
179 selectConMatchVars :: [Type] -> ConArgPats -> DsM [Id]
180 selectConMatchVars arg_tys (RecCon {})      = newSysLocalsDs arg_tys
181 selectConMatchVars _       (PrefixCon ps)   = selectMatchVars (map unLoc ps)
182 selectConMatchVars _       (InfixCon p1 p2) = selectMatchVars [unLoc p1, unLoc p2]
183
184 conArgPats :: [Type]    -- Instantiated argument types 
185                         -- Used only to fill in the types of WildPats, which
186                         -- are probably never looked at anyway
187            -> ConArgPats
188            -> [Pat Id]
189 conArgPats _arg_tys (PrefixCon ps)   = map unLoc ps
190 conArgPats _arg_tys (InfixCon p1 p2) = [unLoc p1, unLoc p2]
191 conArgPats  arg_tys (RecCon (HsRecFields { rec_flds = rpats }))
192   | null rpats = map WildPat arg_tys
193         -- Important special case for C {}, which can be used for a 
194         -- datacon that isn't declared to have fields at all
195   | otherwise  = map (unLoc . hsRecFieldArg) rpats
196 \end{code}
197
198 Note [Record patterns]
199 ~~~~~~~~~~~~~~~~~~~~~~
200 Consider 
201          data T = T { x,y,z :: Bool }
202
203          f (T { y=True, x=False }) = ...
204
205 We must match the patterns IN THE ORDER GIVEN, thus for the first
206 one we match y=True before x=False.  See Trac #246; or imagine 
207 matching against (T { y=False, x=undefined }): should fail without
208 touching the undefined. 
209
210 Now consider:
211
212          f (T { y=True, x=False }) = ...
213          f (T { x=True, y= False}) = ...
214
215 In the first we must test y first; in the second we must test x 
216 first.  So we must divide even the equations for a single constructor
217 T into sub-goups, based on whether they match the same field in the
218 same order.  That's what the (runs compatible_pats) grouping.
219
220 All non-record patterns are "compatible" in this sense, because the
221 positional patterns (T a b) and (a `T` b) all match the arguments
222 in order.  Also T {} is special because it's equivalent to (T _ _).
223 Hence the (null rpats) checks here and there.
224
225
226 Note [Existentials in shift_con_pat]
227 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
228 Consider
229         data T = forall a. Ord a => T a (a->Int)
230
231         f (T x f) True  = ...expr1...
232         f (T y g) False = ...expr2..
233
234 When we put in the tyvars etc we get
235
236         f (T a (d::Ord a) (x::a) (f::a->Int)) True =  ...expr1...
237         f (T b (e::Ord b) (y::a) (g::a->Int)) True =  ...expr2...
238
239 After desugaring etc we'll get a single case:
240
241         f = \t::T b::Bool -> 
242             case t of
243                T a (d::Ord a) (x::a) (f::a->Int)) ->
244             case b of
245                 True  -> ...expr1...
246                 False -> ...expr2...
247
248 *** We have to substitute [a/b, d/e] in expr2! **
249 Hence
250                 False -> ....((/\b\(e:Ord b).expr2) a d)....
251
252 Originally I tried to use 
253         (\b -> let e = d in expr2) a 
254 to do this substitution.  While this is "correct" in a way, it fails
255 Lint, because e::Ord b but d::Ord a.  
256