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 )
36 We are confronted with the first column of patterns in a set of
37 equations, all beginning with constructors from one ``family'' (e.g.,
38 @[]@ and @:@ make up the @List@ ``family''). We want to generate the
39 alternatives for a @Case@ expression. There are several choices:
42 Generate an alternative for every constructor in the family, whether
43 they are used in this set of equations or not; this is what the Wadler
47 (a)~Simple. (b)~It may also be that large sparsely-used constructor
48 families are mainly handled by the code for literals.
50 (a)~Not practical for large sparsely-used constructor families, e.g.,
51 the ASCII character set. (b)~Have to look up a list of what
52 constructors make up the whole family.
56 Generate an alternative for each constructor used, then add a default
57 alternative in case some constructors in the family weren't used.
60 (a)~Alternatives aren't generated for unused constructors. (b)~The
61 STG is quite happy with defaults. (c)~No lookup in an environment needed.
63 (a)~A spurious default alternative may be generated.
67 ``Do it right:'' generate an alternative for each constructor used,
68 and add a default alternative if all constructors in the family
72 (a)~You will get cases with only one alternative (and no default),
73 which should be amenable to optimisation. Tuples are a common example.
75 (b)~Have to look up constructor families in TDE (as above).
79 We are implementing the ``do-it-right'' option for now. The arguments
80 to @matchConFamily@ are the same as to @match@; the extra @Int@
81 returned is the number of constructors in the family.
83 The function @matchConFamily@ is concerned with this
84 have-we-used-all-the-constructors? question; the local function
85 @match_cons_used@ does all the real work.
87 matchConFamily :: [Id]
91 -- Each group of eqns is for a single constructor
92 matchConFamily (var:vars) ty groups
93 = do { alts <- mapM (matchOneCon vars ty) groups
94 ; return (mkCoAlgCaseMatchResult var ty alts) }
96 type ConArgPats = HsConDetails (LPat Id) (HsRecFields Id (LPat Id))
101 -> DsM (DataCon, [Var], MatchResult)
102 matchOneCon vars ty (eqn1 : eqns) -- All eqns for a single constructor
103 = do { arg_vars <- selectConMatchVars arg_tys args1
104 -- Use the first equation as a source of
105 -- suggestions for the new variables
107 -- Divide into sub-groups; see Note [Record patterns]
108 ; let groups :: [[(ConArgPats, EquationInfo)]]
109 groups = runs compatible_pats [ (pat_args (firstPat eqn), eqn)
112 ; match_results <- mapM (match_group arg_vars) groups
114 ; return (con1, tvs1 ++ dicts1 ++ arg_vars,
115 foldr1 combineMatchResults match_results) }
117 ConPatOut { pat_con = L _ con1, pat_ty = pat_ty1,
118 pat_tvs = tvs1, pat_dicts = dicts1, pat_args = args1 }
120 fields1 = dataConFieldLabels con1
122 arg_tys = dataConInstOrigArgTys con1 inst_tys
123 inst_tys = tcTyConAppArgs pat_ty1 ++
124 mkTyVarTys (takeList (dataConExTyVars con1) tvs1)
125 -- Newtypes opaque, hence tcTyConAppArgs
126 -- dataConInstOrigArgTys takes the univ and existential tyvars
127 -- and returns the types of the *value* args, which is what we want
129 match_group :: [Id] -> [(ConArgPats, EquationInfo)] -> DsM MatchResult
130 -- All members of the group have compatible ConArgPats
131 match_group arg_vars arg_eqn_prs
132 = do { (wraps, eqns') <- mapAndUnzipM shift arg_eqn_prs
133 ; let group_arg_vars = select_arg_vars arg_vars arg_eqn_prs
134 ; match_result <- match (group_arg_vars ++ vars) ty eqns'
135 ; return (adjustMatchResult (foldr1 (.) wraps) match_result) }
137 shift (_, eqn@(EqnInfo { eqn_pats = ConPatOut{ pat_tvs = tvs, pat_dicts = ds,
138 pat_binds = bind, pat_args = args
140 = do { ds_ev_binds <- dsTcEvBinds bind
141 ; return (wrapBinds (tvs `zip` tvs1)
142 . wrapBinds (ds `zip` dicts1)
143 . wrapDsEvBinds ds_ev_binds,
144 eqn { eqn_pats = conArgPats arg_tys args ++ pats }) }
146 -- Choose the right arg_vars in the right order for this group
147 -- Note [Record patterns]
148 select_arg_vars arg_vars ((arg_pats, _) : _)
149 | RecCon flds <- arg_pats
150 , let rpats = rec_flds flds
151 , not (null rpats) -- Treated specially; cf conArgPats
152 = ASSERT2( length fields1 == length arg_vars,
153 ppr con1 $$ ppr fields1 $$ ppr arg_vars )
158 fld_var_env = mkNameEnv $ zipEqual "get_arg_vars" fields1 arg_vars
159 lookup_fld rpat = lookupNameEnv_NF fld_var_env
160 (idName (unLoc (hsRecFieldId rpat)))
163 compatible_pats :: (ConArgPats,a) -> (ConArgPats,a) -> Bool
164 -- Two constructors have compatible argument patterns if the number
165 -- and order of sub-matches is the same in both cases
166 compatible_pats (RecCon flds1, _) (RecCon flds2, _) = same_fields flds1 flds2
167 compatible_pats (RecCon flds1, _) _ = null (rec_flds flds1)
168 compatible_pats _ (RecCon flds2, _) = null (rec_flds flds2)
169 compatible_pats _ _ = True -- Prefix or infix con
171 same_fields :: HsRecFields Id (LPat Id) -> HsRecFields Id (LPat Id) -> Bool
172 same_fields flds1 flds2
173 = all2 (\f1 f2 -> unLoc (hsRecFieldId f1) == unLoc (hsRecFieldId f2))
174 (rec_flds flds1) (rec_flds flds2)
178 selectConMatchVars :: [Type] -> ConArgPats -> DsM [Id]
179 selectConMatchVars arg_tys (RecCon {}) = newSysLocalsDs arg_tys
180 selectConMatchVars _ (PrefixCon ps) = selectMatchVars (map unLoc ps)
181 selectConMatchVars _ (InfixCon p1 p2) = selectMatchVars [unLoc p1, unLoc p2]
183 conArgPats :: [Type] -- Instantiated argument types
184 -- Used only to fill in the types of WildPats, which
185 -- are probably never looked at anyway
188 conArgPats _arg_tys (PrefixCon ps) = map unLoc ps
189 conArgPats _arg_tys (InfixCon p1 p2) = [unLoc p1, unLoc p2]
190 conArgPats arg_tys (RecCon (HsRecFields { rec_flds = rpats }))
191 | null rpats = map WildPat arg_tys
192 -- Important special case for C {}, which can be used for a
193 -- datacon that isn't declared to have fields at all
194 | otherwise = map (unLoc . hsRecFieldArg) rpats
197 Note [Record patterns]
198 ~~~~~~~~~~~~~~~~~~~~~~
200 data T = T { x,y,z :: Bool }
202 f (T { y=True, x=False }) = ...
204 We must match the patterns IN THE ORDER GIVEN, thus for the first
205 one we match y=True before x=False. See Trac #246; or imagine
206 matching against (T { y=False, x=undefined }): should fail without
207 touching the undefined.
211 f (T { y=True, x=False }) = ...
212 f (T { x=True, y= False}) = ...
214 In the first we must test y first; in the second we must test x
215 first. So we must divide even the equations for a single constructor
216 T into sub-goups, based on whether they match the same field in the
217 same order. That's what the (runs compatible_pats) grouping.
219 All non-record patterns are "compatible" in this sense, because the
220 positional patterns (T a b) and (a `T` b) all match the arguments
221 in order. Also T {} is special because it's equivalent to (T _ _).
222 Hence the (null rpats) checks here and there.
225 Note [Existentials in shift_con_pat]
226 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
228 data T = forall a. Ord a => T a (a->Int)
230 f (T x f) True = ...expr1...
231 f (T y g) False = ...expr2..
233 When we put in the tyvars etc we get
235 f (T a (d::Ord a) (x::a) (f::a->Int)) True = ...expr1...
236 f (T b (e::Ord b) (y::a) (g::a->Int)) True = ...expr2...
238 After desugaring etc we'll get a single case:
242 T a (d::Ord a) (x::a) (f::a->Int)) ->
247 *** We have to substitute [a/b, d/e] in expr2! **
249 False -> ....((/\b\(e:Ord b).expr2) a d)....
251 Originally I tried to use
252 (\b -> let e = d in expr2) a
253 to do this substitution. While this is "correct" in a way, it fails
254 Lint, because e::Ord b but d::Ord a.