49586bc972496411c00863e4d35e79f784b47255
[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 {-# LANGUAGE TypeFamilies #-}
11
12 module MatchCon ( matchConFamily, matchPatSyn ) where
13
14 #include "HsVersions.h"
15
16 import GhcPrelude
17
18 import {-# SOURCE #-} Match ( match )
19
20 import HsSyn
21 import DsBinds
22 import ConLike
23 import TcType
24 import DsMonad
25 import DsUtils
26 import MkCore ( mkCoreLets )
27 import Util
28 import Id
29 import NameEnv
30 import FieldLabel ( flSelector )
31 import SrcLoc
32 import Outputable
33 import Control.Monad(liftM)
34 import Data.List (groupBy)
35
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 -}
88
89 matchConFamily :: [Id]
90 -> Type
91 -> [[EquationInfo]]
92 -> DsM MatchResult
93 -- Each group of eqns is for a single constructor
94 matchConFamily (var:vars) ty groups
95 = do alts <- mapM (fmap toRealAlt . matchOneConLike vars ty) groups
96 return (mkCoAlgCaseMatchResult var ty alts)
97 where
98 toRealAlt alt = case alt_pat alt of
99 RealDataCon dcon -> alt{ alt_pat = dcon }
100 _ -> panic "matchConFamily: not RealDataCon"
101 matchConFamily [] _ _ = panic "matchConFamily []"
102
103 matchPatSyn :: [Id]
104 -> Type
105 -> [EquationInfo]
106 -> DsM MatchResult
107 matchPatSyn (var:vars) ty eqns
108 = do alt <- fmap toSynAlt $ matchOneConLike vars ty eqns
109 return (mkCoSynCaseMatchResult var ty alt)
110 where
111 toSynAlt alt = case alt_pat alt of
112 PatSynCon psyn -> alt{ alt_pat = psyn }
113 _ -> panic "matchPatSyn: not PatSynCon"
114 matchPatSyn _ _ _ = panic "matchPatSyn []"
115
116 type ConArgPats = HsConDetails (LPat GhcTc) (HsRecFields GhcTc (LPat GhcTc))
117
118 matchOneConLike :: [Id]
119 -> Type
120 -> [EquationInfo]
121 -> DsM (CaseAlt ConLike)
122 matchOneConLike vars ty (eqn1 : eqns) -- All eqns for a single constructor
123 = do { let inst_tys = ASSERT( tvs1 `equalLength` ex_tvs )
124 arg_tys ++ mkTyVarTys tvs1
125
126 val_arg_tys = conLikeInstOrigArgTys con1 inst_tys
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]
131 -> [(ConArgPats, EquationInfo)] -> DsM MatchResult
132 -- All members of the group have compatible ConArgPats
133 match_group arg_vars arg_eqn_prs
134 = ASSERT( notNull arg_eqn_prs )
135 do { (wraps, eqns') <- liftM unzip (mapM 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 ds_bind <- dsTcEvBinds bind
144 return ( wrapBinds (tvs `zip` tvs1)
145 . wrapBinds (ds `zip` dicts1)
146 . mkCoreLets ds_bind
147 , eqn { eqn_pats = conArgPats val_arg_tys args ++ pats }
148 )
149 shift (_, (EqnInfo { eqn_pats = ps })) = pprPanic "matchOneCon/shift" (ppr ps)
150
151 ; arg_vars <- selectConMatchVars val_arg_tys args1
152 -- Use the first equation as a source of
153 -- suggestions for the new variables
154
155 -- Divide into sub-groups; see Note [Record patterns]
156 ; let groups :: [[(ConArgPats, EquationInfo)]]
157 groups = groupBy compatible_pats [ (pat_args (firstPat eqn), eqn)
158 | eqn <- eqn1:eqns ]
159
160 ; match_results <- mapM (match_group arg_vars) groups
161
162 ; return $ MkCaseAlt{ alt_pat = con1,
163 alt_bndrs = tvs1 ++ dicts1 ++ arg_vars,
164 alt_wrapper = wrapper1,
165 alt_result = foldr1 combineMatchResults match_results } }
166 where
167 ConPatOut { pat_con = L _ con1, pat_arg_tys = arg_tys, pat_wrap = wrapper1,
168 pat_tvs = tvs1, pat_dicts = dicts1, pat_args = args1 }
169 = firstPat eqn1
170 fields1 = map flSelector (conLikeFieldLabels con1)
171
172 ex_tvs = conLikeExTyVars con1
173
174 -- Choose the right arg_vars in the right order for this group
175 -- Note [Record patterns]
176 select_arg_vars :: [Id] -> [(ConArgPats, EquationInfo)] -> [Id]
177 select_arg_vars arg_vars ((arg_pats, _) : _)
178 | RecCon flds <- arg_pats
179 , let rpats = rec_flds flds
180 , not (null rpats) -- Treated specially; cf conArgPats
181 = ASSERT2( fields1 `equalLength` arg_vars,
182 ppr con1 $$ ppr fields1 $$ ppr arg_vars )
183 map lookup_fld rpats
184 | otherwise
185 = arg_vars
186 where
187 fld_var_env = mkNameEnv $ zipEqual "get_arg_vars" fields1 arg_vars
188 lookup_fld (L _ rpat) = lookupNameEnv_NF fld_var_env
189 (idName (unLoc (hsRecFieldId rpat)))
190 select_arg_vars _ [] = panic "matchOneCon/select_arg_vars []"
191 matchOneConLike _ _ [] = panic "matchOneCon []"
192
193 -----------------
194 compatible_pats :: (ConArgPats,a) -> (ConArgPats,a) -> Bool
195 -- Two constructors have compatible argument patterns if the number
196 -- and order of sub-matches is the same in both cases
197 compatible_pats (RecCon flds1, _) (RecCon flds2, _) = same_fields flds1 flds2
198 compatible_pats (RecCon flds1, _) _ = null (rec_flds flds1)
199 compatible_pats _ (RecCon flds2, _) = null (rec_flds flds2)
200 compatible_pats _ _ = True -- Prefix or infix con
201
202 same_fields :: HsRecFields GhcTc (LPat GhcTc) -> HsRecFields GhcTc (LPat GhcTc)
203 -> Bool
204 same_fields flds1 flds2
205 = all2 (\(L _ f1) (L _ f2)
206 -> unLoc (hsRecFieldId f1) == unLoc (hsRecFieldId f2))
207 (rec_flds flds1) (rec_flds flds2)
208
209
210 -----------------
211 selectConMatchVars :: [Type] -> ConArgPats -> DsM [Id]
212 selectConMatchVars arg_tys (RecCon {}) = newSysLocalsDsNoLP arg_tys
213 selectConMatchVars _ (PrefixCon ps) = selectMatchVars (map unLoc ps)
214 selectConMatchVars _ (InfixCon p1 p2) = selectMatchVars [unLoc p1, unLoc p2]
215
216 conArgPats :: [Type] -- Instantiated argument types
217 -- Used only to fill in the types of WildPats, which
218 -- are probably never looked at anyway
219 -> ConArgPats
220 -> [Pat GhcTc]
221 conArgPats _arg_tys (PrefixCon ps) = map unLoc ps
222 conArgPats _arg_tys (InfixCon p1 p2) = [unLoc p1, unLoc p2]
223 conArgPats arg_tys (RecCon (HsRecFields { rec_flds = rpats }))
224 | null rpats = map WildPat arg_tys
225 -- Important special case for C {}, which can be used for a
226 -- datacon that isn't declared to have fields at all
227 | otherwise = map (unLoc . hsRecFieldArg . unLoc) rpats
228
229 {-
230 Note [Record patterns]
231 ~~~~~~~~~~~~~~~~~~~~~~
232 Consider
233 data T = T { x,y,z :: Bool }
234
235 f (T { y=True, x=False }) = ...
236
237 We must match the patterns IN THE ORDER GIVEN, thus for the first
238 one we match y=True before x=False. See Trac #246; or imagine
239 matching against (T { y=False, x=undefined }): should fail without
240 touching the undefined.
241
242 Now consider:
243
244 f (T { y=True, x=False }) = ...
245 f (T { x=True, y= False}) = ...
246
247 In the first we must test y first; in the second we must test x
248 first. So we must divide even the equations for a single constructor
249 T into sub-goups, based on whether they match the same field in the
250 same order. That's what the (groupBy compatible_pats) grouping.
251
252 All non-record patterns are "compatible" in this sense, because the
253 positional patterns (T a b) and (a `T` b) all match the arguments
254 in order. Also T {} is special because it's equivalent to (T _ _).
255 Hence the (null rpats) checks here and there.
256
257
258 Note [Existentials in shift_con_pat]
259 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
260 Consider
261 data T = forall a. Ord a => T a (a->Int)
262
263 f (T x f) True = ...expr1...
264 f (T y g) False = ...expr2..
265
266 When we put in the tyvars etc we get
267
268 f (T a (d::Ord a) (x::a) (f::a->Int)) True = ...expr1...
269 f (T b (e::Ord b) (y::a) (g::a->Int)) True = ...expr2...
270
271 After desugaring etc we'll get a single case:
272
273 f = \t::T b::Bool ->
274 case t of
275 T a (d::Ord a) (x::a) (f::a->Int)) ->
276 case b of
277 True -> ...expr1...
278 False -> ...expr2...
279
280 *** We have to substitute [a/b, d/e] in expr2! **
281 Hence
282 False -> ....((/\b\(e:Ord b).expr2) a d)....
283
284 Originally I tried to use
285 (\b -> let e = d in expr2) a
286 to do this substitution. While this is "correct" in a way, it fails
287 Lint, because e::Ord b but d::Ord a.
288
289 -}