2 % (c) The University of Glasgow 2006
3 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
6 Pattern-matching constructors
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
16 module MatchCon ( matchConFamily ) where
18 #include "HsVersions.h"
20 import {-# SOURCE #-} Match ( match )
30 import Util ( all2, takeList, zipEqual )
31 import ListSetOps ( runs )
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:
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
50 (a)~Simple. (b)~It may also be that large sparsely-used constructor
51 families are mainly handled by the code for literals.
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.
59 Generate an alternative for each constructor used, then add a default
60 alternative in case some constructors in the family weren't used.
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.
66 (a)~A spurious default alternative may be generated.
70 ``Do it right:'' generate an alternative for each constructor used,
71 and add a default alternative if all constructors in the family
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.
78 (b)~Have to look up constructor families in TDE (as above).
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.
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.
90 matchConFamily :: [Id]
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) }
99 type ConArgPats = HsConDetails (LPat Id) (HsRecFields Id (LPat Id))
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
110 -- Divide into sub-groups; see Note [Record patterns]
111 ; let groups :: [[(ConArgPats, EquationInfo)]]
112 groups = runs compatible_pats [ (pat_args (firstPat eqn), eqn)
115 ; match_results <- mapM (match_group arg_vars) groups
117 ; return (con1, tvs1 ++ dicts1 ++ arg_vars,
118 foldr1 combineMatchResults match_results) }
120 ConPatOut { pat_con = L _ con1, pat_ty = pat_ty1,
121 pat_tvs = tvs1, pat_dicts = dicts1, pat_args = args1 }
123 fields1 = dataConFieldLabels con1
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
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) }
140 shift (_, eqn@(EqnInfo { eqn_pats = ConPatOut{ pat_tvs = tvs, pat_dicts = ds,
141 pat_binds = bind, pat_args = args
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 }) }
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 )
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)))
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
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)
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]
186 conArgPats :: [Type] -- Instantiated argument types
187 -- Used only to fill in the types of WildPats, which
188 -- are probably never looked at anyway
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
200 Note [Record patterns]
201 ~~~~~~~~~~~~~~~~~~~~~~
203 data T = T { x,y,z :: Bool }
205 f (T { y=True, x=False }) = ...
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.
214 f (T { y=True, x=False }) = ...
215 f (T { x=True, y= False}) = ...
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.
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.
228 Note [Existentials in shift_con_pat]
229 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
231 data T = forall a. Ord a => T a (a->Int)
233 f (T x f) True = ...expr1...
234 f (T y g) False = ...expr2..
236 When we put in the tyvars etc we get
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...
241 After desugaring etc we'll get a single case:
245 T a (d::Ord a) (x::a) (f::a->Int)) ->
250 *** We have to substitute [a/b, d/e] in expr2! **
252 False -> ....((/\b\(e:Ord b).expr2) a d)....
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.