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