Massive patch for the first months work adding System FC to GHC #9
[ghc-hetmet.git] / 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(..), LPat, HsConDetails(..) )
14 import DsBinds          ( dsLHsBinds )
15 import DataCon          ( DataCon, dataConInstOrigArgTys, 
16                           dataConFieldLabels, dataConSourceArity )
17 import TcType           ( tcTyConAppArgs )
18 import Type             ( mkTyVarTys )
19 import CoreSyn
20 import DsMonad
21 import DsUtils
22
23 import Id               ( Id, idName )
24 import Type             ( Type )
25 import SrcLoc           ( unLoc, Located(..) )
26 import Outputable
27 \end{code}
28
29 We are confronted with the first column of patterns in a set of
30 equations, all beginning with constructors from one ``family'' (e.g.,
31 @[]@ and @:@ make up the @List@ ``family'').  We want to generate the
32 alternatives for a @Case@ expression.  There are several choices:
33 \begin{enumerate}
34 \item
35 Generate an alternative for every constructor in the family, whether
36 they are used in this set of equations or not; this is what the Wadler
37 chapter does.
38 \begin{description}
39 \item[Advantages:]
40 (a)~Simple.  (b)~It may also be that large sparsely-used constructor
41 families are mainly handled by the code for literals.
42 \item[Disadvantages:]
43 (a)~Not practical for large sparsely-used constructor families, e.g.,
44 the ASCII character set.  (b)~Have to look up a list of what
45 constructors make up the whole family.
46 \end{description}
47
48 \item
49 Generate an alternative for each constructor used, then add a default
50 alternative in case some constructors in the family weren't used.
51 \begin{description}
52 \item[Advantages:]
53 (a)~Alternatives aren't generated for unused constructors.  (b)~The
54 STG is quite happy with defaults.  (c)~No lookup in an environment needed.
55 \item[Disadvantages:]
56 (a)~A spurious default alternative may be generated.
57 \end{description}
58
59 \item
60 ``Do it right:'' generate an alternative for each constructor used,
61 and add a default alternative if all constructors in the family
62 weren't used.
63 \begin{description}
64 \item[Advantages:]
65 (a)~You will get cases with only one alternative (and no default),
66 which should be amenable to optimisation.  Tuples are a common example.
67 \item[Disadvantages:]
68 (b)~Have to look up constructor families in TDE (as above).
69 \end{description}
70 \end{enumerate}
71
72 We are implementing the ``do-it-right'' option for now.  The arguments
73 to @matchConFamily@ are the same as to @match@; the extra @Int@
74 returned is the number of constructors in the family.
75
76 The function @matchConFamily@ is concerned with this
77 have-we-used-all-the-constructors? question; the local function
78 @match_cons_used@ does all the real work.
79 \begin{code}
80 matchConFamily :: [Id]
81                -> Type
82                -> [[EquationInfo]]
83                -> DsM MatchResult
84 -- Each group of eqns is for a single constructor
85 matchConFamily (var:vars) ty groups
86   = do  { alts <- mapM (matchOneCon vars ty) groups
87         ; return (mkCoAlgCaseMatchResult var ty alts) }
88
89 matchOneCon vars ty (eqn1 : eqns)       -- All eqns for a single constructor
90   = do  { (wraps, eqns') <- mapAndUnzipM shift (eqn1:eqns)
91         ; arg_vars <- selectMatchVars (take (dataConSourceArity con) 
92                                             (eqn_pats (head eqns')))
93                 -- Use the new arugment patterns as a source of 
94                 -- suggestions for the new variables
95         ; match_result <- match (arg_vars ++ vars) ty eqns'
96         ; return (con, tvs1 ++ dicts1 ++ arg_vars, 
97                   adjustMatchResult (foldr1 (.) wraps) match_result) }
98   where
99     ConPatOut { pat_con = L _ con, pat_ty = pat_ty1,
100                 pat_tvs = tvs1, pat_dicts = dicts1 } = firstPat eqn1
101         
102     arg_tys  = dataConInstOrigArgTys con inst_tys
103     inst_tys = tcTyConAppArgs pat_ty1 ++ mkTyVarTys tvs1
104         -- Newtypes opaque, hence tcTyConAppArgs
105
106     shift eqn@(EqnInfo { eqn_pats = ConPatOut{ pat_tvs = tvs, pat_dicts = ds, 
107                                                pat_binds = bind, pat_args = args
108                                               } : pats })
109         = do { prs <- dsLHsBinds bind
110              ; return (wrapBinds (tvs `zip` tvs1) 
111                        . wrapBinds (ds  `zip` dicts1)
112                        . mkDsLet (Rec prs),
113                        eqn { eqn_pats = conArgPats con arg_tys args ++ pats }) }
114
115 conArgPats :: DataCon 
116            -> [Type]    -- Instantiated argument types 
117            -> HsConDetails Id (LPat Id)
118            -> [Pat Id]
119 conArgPats data_con arg_tys (PrefixCon ps)   = map unLoc ps
120 conArgPats data_con arg_tys (InfixCon p1 p2) = [unLoc p1, unLoc p2]
121 conArgPats data_con arg_tys (RecCon rpats)
122   | null rpats
123   =     -- Special case for C {}, which can be used for 
124         -- a constructor that isn't declared to have
125         -- fields at all
126     map WildPat arg_tys
127
128   | otherwise
129   = zipWith mk_pat (dataConFieldLabels data_con) arg_tys
130   where
131         -- mk_pat picks a WildPat of the appropriate type for absent fields,
132         -- and the specified pattern for present fields
133     mk_pat lbl arg_ty
134         = case [ pat | (sel_id,pat) <- rpats, idName (unLoc sel_id) == lbl] of
135             (pat:pats) -> ASSERT( null pats ) unLoc pat
136             []         -> WildPat arg_ty
137 \end{code}
138
139 Note [Existentials in shift_con_pat]
140 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
141 Consider
142         data T = forall a. Ord a => T a (a->Int)
143
144         f (T x f) True  = ...expr1...
145         f (T y g) False = ...expr2..
146
147 When we put in the tyvars etc we get
148
149         f (T a (d::Ord a) (x::a) (f::a->Int)) True =  ...expr1...
150         f (T b (e::Ord b) (y::a) (g::a->Int)) True =  ...expr2...
151
152 After desugaring etc we'll get a single case:
153
154         f = \t::T b::Bool -> 
155             case t of
156                T a (d::Ord a) (x::a) (f::a->Int)) ->
157             case b of
158                 True  -> ...expr1...
159                 False -> ...expr2...
160
161 *** We have to substitute [a/b, d/e] in expr2! **
162 Hence
163                 False -> ....((/\b\(e:Ord b).expr2) a d)....
164
165 Originally I tried to use 
166         (\b -> let e = d in expr2) a 
167 to do this substitution.  While this is "correct" in a way, it fails
168 Lint, because e::Ord b but d::Ord a.  
169