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