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