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