[project @ 2003-10-09 11:58:39 by simonpj]
[ghc-hetmet.git] / ghc / compiler / deSugar / MatchCon.lhs
1
2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
3 %
4 \section[MatchCon]{Pattern-matching constructors}
5
6 \begin{code}
7 module MatchCon ( matchConFamily ) where
8
9 #include "HsVersions.h"
10
11 import {-# SOURCE #-} Match     ( match )
12
13 import HsSyn            ( Pat(..), HsConDetails(..) )
14
15 import DsMonad
16 import DsUtils
17
18 import Id               ( Id )
19 import Subst            ( mkSubst, mkInScopeSet, bindSubst, substExpr )
20 import CoreFVs          ( exprFreeVars )
21 import VarEnv           ( emptySubstEnv )
22 import ListSetOps       ( equivClassesByUniq )
23 import Unique           ( Uniquable(..) )
24 \end{code}
25
26 We are confronted with the first column of patterns in a set of
27 equations, all beginning with constructors from one ``family'' (e.g.,
28 @[]@ and @:@ make up the @List@ ``family'').  We want to generate the
29 alternatives for a @Case@ expression.  There are several choices:
30 \begin{enumerate}
31 \item
32 Generate an alternative for every constructor in the family, whether
33 they are used in this set of equations or not; this is what the Wadler
34 chapter does.
35 \begin{description}
36 \item[Advantages:]
37 (a)~Simple.  (b)~It may also be that large sparsely-used constructor
38 families are mainly handled by the code for literals.
39 \item[Disadvantages:]
40 (a)~Not practical for large sparsely-used constructor families, e.g.,
41 the ASCII character set.  (b)~Have to look up a list of what
42 constructors make up the whole family.
43 \end{description}
44
45 \item
46 Generate an alternative for each constructor used, then add a default
47 alternative in case some constructors in the family weren't used.
48 \begin{description}
49 \item[Advantages:]
50 (a)~Alternatives aren't generated for unused constructors.  (b)~The
51 STG is quite happy with defaults.  (c)~No lookup in an environment needed.
52 \item[Disadvantages:]
53 (a)~A spurious default alternative may be generated.
54 \end{description}
55
56 \item
57 ``Do it right:'' generate an alternative for each constructor used,
58 and add a default alternative if all constructors in the family
59 weren't used.
60 \begin{description}
61 \item[Advantages:]
62 (a)~You will get cases with only one alternative (and no default),
63 which should be amenable to optimisation.  Tuples are a common example.
64 \item[Disadvantages:]
65 (b)~Have to look up constructor families in TDE (as above).
66 \end{description}
67 \end{enumerate}
68
69 We are implementing the ``do-it-right'' option for now.  The arguments
70 to @matchConFamily@ are the same as to @match@; the extra @Int@
71 returned is the number of constructors in the family.
72
73 The function @matchConFamily@ is concerned with this
74 have-we-used-all-the-constructors? question; the local function
75 @match_cons_used@ does all the real work.
76 \begin{code}
77 matchConFamily :: [Id]
78                -> [EquationInfo]
79                -> DsM MatchResult
80
81 matchConFamily (var:vars) eqns_info
82   = let
83         -- Sort into equivalence classes by the unique on the constructor
84         -- All the EqnInfos should start with a ConPat
85         eqn_groups = equivClassesByUniq get_uniq eqns_info
86         get_uniq (EqnInfo _ _ (ConPatOut data_con _ _ _ _ : _) _) = getUnique data_con
87     in
88         -- Now make a case alternative out of each group
89     mappM (match_con vars) eqn_groups   `thenDs` \ alts ->
90
91     returnDs (mkCoAlgCaseMatchResult var alts)
92 \end{code}
93
94 And here is the local function that does all the work.  It is
95 more-or-less the @matchCon@/@matchClause@ functions on page~94 in
96 Wadler's chapter in SLPJ.
97
98 \begin{code}
99 match_con vars (eqn1@(EqnInfo _ _ (ConPatOut data_con (PrefixCon arg_pats) _ ex_tvs ex_dicts : _) _)
100                 : other_eqns)
101   = -- Make new vars for the con arguments; avoid new locals where possible
102     mappM selectMatchVar arg_pats       `thenDs` \ arg_vars ->
103
104     -- Now do the business to make the alt for _this_ ConPat ...
105     match (arg_vars ++ vars) 
106           (map shift_con_pat (eqn1:other_eqns)) `thenDs` \ match_result ->
107
108     --          [See "notes on do_subst" below this function]
109     -- Make the ex_tvs and ex_dicts line up with those
110     -- in the first pattern.  Remember, they are all guaranteed to be variables
111     let
112         match_result' | null ex_tvs     = match_result
113                       | null other_eqns = match_result
114                       | otherwise       = adjustMatchResult do_subst match_result
115     in
116         
117     returnDs (data_con, ex_tvs ++ ex_dicts ++ arg_vars, match_result')
118   where
119     shift_con_pat :: EquationInfo -> EquationInfo
120     shift_con_pat (EqnInfo n ctx (ConPatOut _ (PrefixCon arg_pats) _ _ _ : pats) match_result)
121       = EqnInfo n ctx (arg_pats ++ pats) match_result
122
123     other_pats = [p | EqnInfo _ _ (p:_) _ <- other_eqns]
124
125     var_prs = concat [ (ex_tvs'   `zip` ex_tvs) ++ 
126                        (ex_dicts' `zip` ex_dicts) 
127                      | ConPatOut _ _ _ ex_tvs' ex_dicts' <- other_pats ]
128
129     do_subst e = substExpr subst e
130                where
131                  subst    = foldl (\ s (v', v) -> bindSubst s v' v) in_scope var_prs
132                  in_scope = mkSubst (mkInScopeSet (exprFreeVars e)) emptySubstEnv
133                         -- We put all the free variables of e into the in-scope 
134                         -- set of the substitution, not because it is necessary,
135                         -- but to suppress the warning in Subst.lookupInScope
136                         -- Tiresome, but doing the substitution at all is rare.
137 \end{code}
138
139 Note on @shift_con_pats@ just above: does what the list comprehension in
140 @matchClause@ (SLPJ, p.~94) does, except things are trickier in real
141 life.  Works for @ConPats@, and we want it to fail catastrophically
142 for anything else (which a list comprehension wouldn't).
143 Cf.~@shift_lit_pats@ in @MatchLits@.
144
145
146 Notes on do_subst stuff
147 ~~~~~~~~~~~~~~~~~~~~~~~
148 Consider
149         data T = forall a. Ord a => T a (a->Int)
150
151         f (T x f) True  = ...expr1...
152         f (T y g) False = ...expr2..
153
154 When we put in the tyvars etc we get
155
156         f (T a (d::Ord a) (x::a) (f::a->Int)) True =  ...expr1...
157         f (T b (e::Ord a) (y::a) (g::a->Int)) True =  ...expr2...
158
159 After desugaring etc we'll get a single case:
160
161         f = \t::T b::Bool -> 
162             case t of
163                T a (d::Ord a) (x::a) (f::a->Int)) ->
164             case b of
165                 True  -> ...expr1...
166                 False -> ...expr2...
167
168 *** We have to substitute [a/b, d/e] in expr2! **
169 That is what do_subst is doing.
170
171 Originally I tried to use 
172         (\b -> let e = d in expr2) a 
173 to do this substitution.  While this is "correct" in a way, it fails
174 Lint, because e::Ord b but d::Ord a.  
175
176 So now I simply do the substitution properly using substExpr.
177