Add {-# OPTIONS_GHC -w #-} and some blurb to all compiler modules
[ghc-hetmet.git] / compiler / deSugar / MatchCon.lhs
1 %
2 % (c) The University of Glasgow 2006
3 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4 %
5
6 Pattern-matching constructors
7
8 \begin{code}
9 {-# OPTIONS_GHC -w #-}
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/WorkingConventions#Warnings
14 -- for details
15
16 module MatchCon ( matchConFamily ) where
17
18 #include "HsVersions.h"
19
20 import {-# SOURCE #-} Match     ( match )
21
22 import HsSyn
23 import DsBinds
24 import DataCon
25 import TcType
26 import Type
27 import CoreSyn
28 import DsMonad
29 import DsUtils
30 import Util     ( takeList )
31 import Id
32 import SrcLoc
33 import Outputable
34 \end{code}
35
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:
40 \begin{enumerate}
41 \item
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
44 chapter does.
45 \begin{description}
46 \item[Advantages:]
47 (a)~Simple.  (b)~It may also be that large sparsely-used constructor
48 families are mainly handled by the code for literals.
49 \item[Disadvantages:]
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.
53 \end{description}
54
55 \item
56 Generate an alternative for each constructor used, then add a default
57 alternative in case some constructors in the family weren't used.
58 \begin{description}
59 \item[Advantages:]
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.
62 \item[Disadvantages:]
63 (a)~A spurious default alternative may be generated.
64 \end{description}
65
66 \item
67 ``Do it right:'' generate an alternative for each constructor used,
68 and add a default alternative if all constructors in the family
69 weren't used.
70 \begin{description}
71 \item[Advantages:]
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.
74 \item[Disadvantages:]
75 (b)~Have to look up constructor families in TDE (as above).
76 \end{description}
77 \end{enumerate}
78
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.
82
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.
86 \begin{code}
87 matchConFamily :: [Id]
88                -> Type
89                -> [[EquationInfo]]
90                -> DsM MatchResult
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) }
95
96 matchOneCon vars ty (eqn1 : eqns)       -- All eqns for a single constructor
97   = do  { (wraps, eqns') <- mapAndUnzipM shift (eqn1:eqns)
98         ; arg_vars <- selectMatchVars (take (dataConSourceArity con1) 
99                                             (eqn_pats (head eqns')))
100                 -- Use the new arugment patterns as a source of 
101                 -- suggestions for the new variables
102         ; match_result <- match (arg_vars ++ vars) ty eqns'
103         ; return (con1, tvs1 ++ dicts1 ++ arg_vars, 
104                   adjustMatchResult (foldr1 (.) wraps) match_result) }
105   where
106     ConPatOut { pat_con = L _ con1, pat_ty = pat_ty1,
107                 pat_tvs = tvs1, pat_dicts = dicts1 } = firstPat eqn1
108         
109     arg_tys  = dataConInstOrigArgTys con1 inst_tys
110     inst_tys = tcTyConAppArgs pat_ty1 ++ 
111                mkTyVarTys (takeList (dataConExTyVars con1) tvs1)
112         -- Newtypes opaque, hence tcTyConAppArgs
113         -- dataConInstOrigArgTys takes the univ and existential tyvars
114         -- and returns the types of the *value* args, which is what we want
115
116     shift eqn@(EqnInfo { eqn_pats = ConPatOut{ pat_tvs = tvs, pat_dicts = ds, 
117                                                pat_binds = bind, pat_args = args
118                                               } : pats })
119         = do { prs <- dsLHsBinds bind
120              ; return (wrapBinds (tvs `zip` tvs1) 
121                        . wrapBinds (ds  `zip` dicts1)
122                        . mkDsLet (Rec prs),
123                        eqn { eqn_pats = conArgPats con1 arg_tys args ++ pats }) }
124
125 conArgPats :: DataCon 
126            -> [Type]    -- Instantiated argument types 
127                         -- Used only to fill in the types of WildPats, which
128                         -- are probably never looked at anyway
129            -> HsConDetails (LPat Id) (HsRecFields Id (LPat Id))
130            -> [Pat Id]
131 conArgPats data_con arg_tys (PrefixCon ps)   = map unLoc ps
132 conArgPats data_con arg_tys (InfixCon p1 p2) = [unLoc p1, unLoc p2]
133 conArgPats data_con arg_tys (RecCon (HsRecFields rpats _))
134   | null rpats
135   =     -- Special case for C {}, which can be used for 
136         -- a constructor that isn't declared to have
137         -- fields at all
138     map WildPat arg_tys
139
140   | otherwise
141   = zipWith mk_pat (dataConFieldLabels data_con) arg_tys
142   where
143         -- mk_pat picks a WildPat of the appropriate type for absent fields,
144         -- and the specified pattern for present fields
145     mk_pat lbl arg_ty
146         = case [ pat | HsRecField sel_id pat _ <- rpats, idName (unLoc sel_id) == lbl ] of
147             (pat:pats) -> ASSERT( null pats ) unLoc pat
148             []         -> WildPat arg_ty
149 \end{code}
150
151 Note [Existentials in shift_con_pat]
152 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
153 Consider
154         data T = forall a. Ord a => T a (a->Int)
155
156         f (T x f) True  = ...expr1...
157         f (T y g) False = ...expr2..
158
159 When we put in the tyvars etc we get
160
161         f (T a (d::Ord a) (x::a) (f::a->Int)) True =  ...expr1...
162         f (T b (e::Ord b) (y::a) (g::a->Int)) True =  ...expr2...
163
164 After desugaring etc we'll get a single case:
165
166         f = \t::T b::Bool -> 
167             case t of
168                T a (d::Ord a) (x::a) (f::a->Int)) ->
169             case b of
170                 True  -> ...expr1...
171                 False -> ...expr2...
172
173 *** We have to substitute [a/b, d/e] in expr2! **
174 Hence
175                 False -> ....((/\b\(e:Ord b).expr2) a d)....
176
177 Originally I tried to use 
178         (\b -> let e = d in expr2) a 
179 to do this substitution.  While this is "correct" in a way, it fails
180 Lint, because e::Ord b but d::Ord a.  
181