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 )
28 import Util ( all2, takeList, zipEqual )
29 import ListSetOps ( runs )
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:
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
48 (a)~Simple. (b)~It may also be that large sparsely-used constructor
49 families are mainly handled by the code for literals.
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.
57 Generate an alternative for each constructor used, then add a default
58 alternative in case some constructors in the family weren't used.
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.
64 (a)~A spurious default alternative may be generated.
68 ``Do it right:'' generate an alternative for each constructor used,
69 and add a default alternative if all constructors in the family
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.
76 (b)~Have to look up constructor families in TDE (as above).
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.
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.
88 matchConFamily :: [Id]
92 -- Each group of eqns is for a single constructor
93 matchConFamily (var:vars) ty groups
94 = do { alts <- mapM (matchOneCon vars ty) groups
95 ; return (mkCoAlgCaseMatchResult var ty alts) }
97 type ConArgPats = HsConDetails (LPat Id) (HsRecFields Id (LPat Id))
102 -> DsM (DataCon, [Var], MatchResult)
103 matchOneCon vars ty (eqn1 : eqns) -- All eqns for a single constructor
104 = do { arg_vars <- selectConMatchVars arg_tys args1
105 -- Use the first equation as a source of
106 -- suggestions for the new variables
108 -- Divide into sub-groups; see Note [Record patterns]
109 ; let groups :: [[(ConArgPats, EquationInfo)]]
110 groups = runs compatible_pats [ (pat_args (firstPat eqn), eqn)
113 ; match_results <- mapM (match_group arg_vars) groups
115 ; return (con1, tvs1 ++ dicts1 ++ arg_vars,
116 foldr1 combineMatchResults match_results) }
118 ConPatOut { pat_con = L _ con1, pat_ty = pat_ty1,
119 pat_tvs = tvs1, pat_dicts = dicts1, pat_args = args1 }
121 fields1 = dataConFieldLabels con1
123 arg_tys = dataConInstOrigArgTys con1 inst_tys
124 inst_tys = tcTyConAppArgs pat_ty1 ++
125 mkTyVarTys (takeList (dataConExTyVars con1) tvs1)
126 -- Newtypes opaque, hence tcTyConAppArgs
127 -- dataConInstOrigArgTys takes the univ and existential tyvars
128 -- and returns the types of the *value* args, which is what we want
130 match_group :: [Id] -> [(ConArgPats, EquationInfo)] -> DsM MatchResult
131 -- All members of the group have compatible ConArgPats
132 match_group arg_vars arg_eqn_prs
133 = do { (wraps, eqns') <- mapAndUnzipM shift arg_eqn_prs
134 ; let group_arg_vars = select_arg_vars arg_vars arg_eqn_prs
135 ; match_result <- match (group_arg_vars ++ vars) ty eqns'
136 ; return (adjustMatchResult (foldr1 (.) wraps) match_result) }
138 shift (_, eqn@(EqnInfo { eqn_pats = ConPatOut{ pat_tvs = tvs, pat_dicts = ds,
139 pat_binds = bind, pat_args = args
141 = do { ds_ev_binds <- dsTcEvBinds bind
142 ; return (wrapBinds (tvs `zip` tvs1)
143 . wrapBinds (ds `zip` dicts1)
144 . wrapDsEvBinds ds_ev_binds,
145 eqn { eqn_pats = conArgPats arg_tys args ++ pats }) }
147 -- Choose the right arg_vars in the right order for this group
148 -- Note [Record patterns]
149 select_arg_vars arg_vars ((arg_pats, _) : _)
150 | RecCon flds <- arg_pats
151 , let rpats = rec_flds flds
152 , not (null rpats) -- Treated specially; cf conArgPats
153 = ASSERT2( length fields1 == length arg_vars,
154 ppr con1 $$ ppr fields1 $$ ppr arg_vars )
159 fld_var_env = mkNameEnv $ zipEqual "get_arg_vars" fields1 arg_vars
160 lookup_fld rpat = lookupNameEnv_NF fld_var_env
161 (idName (unLoc (hsRecFieldId rpat)))
164 compatible_pats :: (ConArgPats,a) -> (ConArgPats,a) -> Bool
165 -- Two constructors have compatible argument patterns if the number
166 -- and order of sub-matches is the same in both cases
167 compatible_pats (RecCon flds1, _) (RecCon flds2, _) = same_fields flds1 flds2
168 compatible_pats (RecCon flds1, _) _ = null (rec_flds flds1)
169 compatible_pats _ (RecCon flds2, _) = null (rec_flds flds2)
170 compatible_pats _ _ = True -- Prefix or infix con
172 same_fields :: HsRecFields Id (LPat Id) -> HsRecFields Id (LPat Id) -> Bool
173 same_fields flds1 flds2
174 = all2 (\f1 f2 -> unLoc (hsRecFieldId f1) == unLoc (hsRecFieldId f2))
175 (rec_flds flds1) (rec_flds flds2)
179 selectConMatchVars :: [Type] -> ConArgPats -> DsM [Id]
180 selectConMatchVars arg_tys (RecCon {}) = newSysLocalsDs arg_tys
181 selectConMatchVars _ (PrefixCon ps) = selectMatchVars (map unLoc ps)
182 selectConMatchVars _ (InfixCon p1 p2) = selectMatchVars [unLoc p1, unLoc p2]
184 conArgPats :: [Type] -- Instantiated argument types
185 -- Used only to fill in the types of WildPats, which
186 -- are probably never looked at anyway
189 conArgPats _arg_tys (PrefixCon ps) = map unLoc ps
190 conArgPats _arg_tys (InfixCon p1 p2) = [unLoc p1, unLoc p2]
191 conArgPats arg_tys (RecCon (HsRecFields { rec_flds = rpats }))
192 | null rpats = map WildPat arg_tys
193 -- Important special case for C {}, which can be used for a
194 -- datacon that isn't declared to have fields at all
195 | otherwise = map (unLoc . hsRecFieldArg) rpats
198 Note [Record patterns]
199 ~~~~~~~~~~~~~~~~~~~~~~
201 data T = T { x,y,z :: Bool }
203 f (T { y=True, x=False }) = ...
205 We must match the patterns IN THE ORDER GIVEN, thus for the first
206 one we match y=True before x=False. See Trac #246; or imagine
207 matching against (T { y=False, x=undefined }): should fail without
208 touching the undefined.
212 f (T { y=True, x=False }) = ...
213 f (T { x=True, y= False}) = ...
215 In the first we must test y first; in the second we must test x
216 first. So we must divide even the equations for a single constructor
217 T into sub-goups, based on whether they match the same field in the
218 same order. That's what the (runs compatible_pats) grouping.
220 All non-record patterns are "compatible" in this sense, because the
221 positional patterns (T a b) and (a `T` b) all match the arguments
222 in order. Also T {} is special because it's equivalent to (T _ _).
223 Hence the (null rpats) checks here and there.
226 Note [Existentials in shift_con_pat]
227 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
229 data T = forall a. Ord a => T a (a->Int)
231 f (T x f) True = ...expr1...
232 f (T y g) False = ...expr2..
234 When we put in the tyvars etc we get
236 f (T a (d::Ord a) (x::a) (f::a->Int)) True = ...expr1...
237 f (T b (e::Ord b) (y::a) (g::a->Int)) True = ...expr2...
239 After desugaring etc we'll get a single case:
243 T a (d::Ord a) (x::a) (f::a->Int)) ->
248 *** We have to substitute [a/b, d/e] in expr2! **
250 False -> ....((/\b\(e:Ord b).expr2) a d)....
252 Originally I tried to use
253 (\b -> let e = d in expr2) a
254 to do this substitution. While this is "correct" in a way, it fails
255 Lint, because e::Ord b but d::Ord a.