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