[project @ 1998-12-02 13:17:09 by simonm]
[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            ( OutPat(..) )
14
15 import DsMonad
16 import DsUtils
17
18 import Id               ( Id )
19 import CoreSyn
20 import Type             ( mkTyVarTys )
21 import Unique           ( Uniquable(..), Unique )
22 import UniqFM           -- Until equivClassesUniq moves to Util
23 import Outputable
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 _ _ (ConPat data_con _ _ _ _ : _) _) = getUnique data_con
87     in
88         -- Now make a case alternative out of each group
89     mapDs (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 all_eqns@(EqnInfo n ctx (ConPat data_con _ ex_tvs ex_dicts arg_pats : pats1) match_result1 : other_eqns)
100   = -- Make new vars for the con arguments; avoid new locals where possible
101     mapDs selectMatchVar arg_pats                          `thenDs` \ arg_vars ->
102
103     -- Now do the business to make the alt for _this_ ConPat ...
104     match (ex_dicts ++ arg_vars ++ vars)
105           (map shift_con_pat all_eqns)  `thenDs` \ match_result ->
106
107         -- Substitute over the result
108     let
109         match_result' | null ex_tvs = match_result
110                       | otherwise   = adjustMatchResult subst_it match_result
111     in  
112     returnDs (data_con, ex_tvs ++ ex_dicts ++ arg_vars, match_result')
113   where
114     shift_con_pat :: EquationInfo -> EquationInfo
115     shift_con_pat (EqnInfo n ctx (ConPat _ _ ex_tvs' ex_dicts' arg_pats: pats) match_result)
116       = EqnInfo n ctx (new_pats  ++ pats) match_result
117       where
118         new_pats  = map VarPat ex_dicts' ++ arg_pats 
119
120         -- We 'substitute' by going: (/\ tvs' -> e) tvs
121     subst_it e = foldr subst_one e other_eqns
122     subst_one (EqnInfo _ _ (ConPat _ _ ex_tvs' _ _ : _) _) e = mkTyApps (mkLams ex_tvs' e) ex_tys
123     ex_tys = mkTyVarTys ex_tvs
124
125
126 -- Belongs in Util.lhs
127 equivClassesByUniq :: (a -> Unique) -> [a] -> [[a]]
128         -- NB: it's *very* important that if we have the input list [a,b,c],
129         -- where a,b,c all have the same unique, then we get back the list
130         --      [a,b,c]
131         -- not
132         --      [c,b,a]
133         -- Hence the use of foldr, plus the reversed-args tack_on below
134 equivClassesByUniq get_uniq xs
135   = eltsUFM (foldr add emptyUFM xs)
136   where
137     add a ufm = addToUFM_C tack_on ufm (get_uniq a) [a]
138     tack_on old new = new++old
139 \end{code}
140
141 Note on @shift_con_pats@ just above: does what the list comprehension in
142 @matchClause@ (SLPJ, p.~94) does, except things are trickier in real
143 life.  Works for @ConPats@, and we want it to fail catastrophically
144 for anything else (which a list comprehension wouldn't).
145 Cf.~@shift_lit_pats@ in @MatchLits@.