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