38ca1f6341c03f44ddc2692e349c087c4d7b8b08
[ghc-hetmet.git] / ghc / compiler / typecheck / TcArrows.lhs
1 %
2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
3 %
4 \section{Typecheck arrow notation}
5
6 \begin{code}
7 module TcArrows ( tcProc ) where
8
9 #include "HsVersions.h"
10
11 import {-# SOURCE #-}   TcExpr( tcCheckRho, tcInferRho )
12
13 import HsSyn
14 import TcHsSyn  (  mkHsDictLet )
15
16 import TcMatches ( tcMatchPats, matchCtxt, tcStmts, tcMDoStmt, tcGuardStmt,
17                    TcMatchCtxt(..), tcMatchesCase )
18
19 import TcType   ( TcType, TcTauType, TcRhoType, mkFunTys, mkTyConApp,
20                   mkTyVarTy, mkAppTys, tcSplitTyConApp_maybe, tcEqType, 
21                   SkolemInfo(..) )
22 import TcMType  ( newTyFlexiVarTy, newTyFlexiVarTys, tcSkolTyVars, zonkTcType )
23 import TcBinds  ( tcLocalBinds )
24 import TcSimplify ( tcSimplifyCheck )
25 import TcUnify  ( Expected(..), checkSigTyVarsWrt, zapExpectedTo )
26 import TcRnMonad
27 import Inst     ( tcSyntaxName )
28 import Name     ( Name )
29 import TysWiredIn ( boolTy, pairTyCon )
30 import VarSet 
31 import TysPrim  ( alphaTyVar )
32 import Type     ( Kind, mkArrowKinds, liftedTypeKind, openTypeKind, tyVarsOfTypes )
33
34 import SrcLoc   ( Located(..) )
35 import Outputable
36 import Util     ( lengthAtLeast )
37
38 \end{code}
39
40 %************************************************************************
41 %*                                                                      *
42                 Proc    
43 %*                                                                      *
44 %************************************************************************
45
46 \begin{code}
47 tcProc :: InPat Name -> LHsCmdTop Name          -- proc pat -> expr
48        -> Expected TcRhoType                    -- Expected type of whole proc expression
49        -> TcM (OutPat TcId, LHsCmdTop TcId)
50
51 tcProc pat cmd exp_ty
52 -- gaw 2004 FIX?
53  = newArrowScope $ do
54         { arr_ty <- newTyFlexiVarTy arrowTyConKind
55         ; [arg_ty, res_ty] <- newTyFlexiVarTys 2 liftedTypeKind
56         ; zapExpectedTo exp_ty (mkAppTys arr_ty [arg_ty,res_ty])
57
58         ; let cmd_env = CmdEnv { cmd_arr = arr_ty }
59         ; ([pat'], cmd') <- tcMatchPats [pat] [Check arg_ty] (Check res_ty) $
60                             tcCmdTop cmd_env cmd ([], res_ty)
61                 -- The False says don't do GADT type refinement
62                 -- This is a conservative choice, but I'm not sure of the consequences
63                 -- of type refinement in the arrow world!
64
65         ; return (pat', cmd') }
66 \end{code}
67
68
69 %************************************************************************
70 %*                                                                      *
71                 Commands
72 %*                                                                      *
73 %************************************************************************
74
75 \begin{code}
76 type CmdStack = [TcTauType]
77 data CmdEnv
78   = CmdEnv {
79         cmd_arr         :: TcType -- arrow type constructor, of kind *->*->*
80     }
81
82 mkCmdArrTy :: CmdEnv -> TcTauType -> TcTauType -> TcTauType
83 mkCmdArrTy env t1 t2 = mkAppTys (cmd_arr env) [t1, t2]
84
85 ---------------------------------------
86 tcCmdTop :: CmdEnv 
87          -> LHsCmdTop Name
88          -> (CmdStack, TcTauType)       -- Expected result type; always a monotype
89                                         -- We know exactly how many cmd args are expected,
90                                         -- albeit perhaps not their types; so we can pass 
91                                         -- in a CmdStack
92         -> TcM (LHsCmdTop TcId)
93
94 tcCmdTop env (L loc (HsCmdTop cmd _ _ names)) (cmd_stk, res_ty)
95   = setSrcSpan loc $
96     do  { cmd'   <- tcCmd env cmd (cmd_stk, res_ty)
97         ; names' <- mapM (tcSyntaxName ProcOrigin (cmd_arr env)) names
98         ; return (L loc $ HsCmdTop cmd' cmd_stk res_ty names') }
99
100
101 ----------------------------------------
102 tcCmd :: CmdEnv -> LHsExpr Name -> (CmdStack, TcTauType) -> TcM (LHsExpr TcId)
103         -- The main recursive function
104 tcCmd env (L loc expr) res_ty
105   = setSrcSpan loc $ do
106         { expr' <- tc_cmd env expr res_ty
107         ; return (L loc expr') }
108
109 tc_cmd env (HsPar cmd) res_ty
110   = do  { cmd' <- tcCmd env cmd res_ty
111         ; return (HsPar cmd') }
112
113 tc_cmd env (HsLet binds (L body_loc body)) res_ty
114   = do  { (binds', body') <- tcLocalBinds binds         $
115                              setSrcSpan body_loc        $
116                              tc_cmd env body res_ty
117         ; return (HsLet binds' (L body_loc body')) }
118
119 tc_cmd env in_cmd@(HsCase scrut matches) (stk, res_ty)
120   = addErrCtxt (cmdCtxt in_cmd)         $
121     addErrCtxt (caseScrutCtxt scrut)    (
122       tcInferRho scrut 
123     )                                                           `thenM` \ (scrut', scrut_ty) ->
124     tcMatchesCase match_ctxt scrut_ty matches (Check res_ty)    `thenM` \ matches' ->
125     returnM (HsCase scrut' matches')
126   where
127     match_ctxt = MC { mc_what = CaseAlt,
128                       mc_body = mc_body }
129     mc_body body (Check res_ty') = tcCmd env body (stk, res_ty')
130
131 tc_cmd env (HsIf pred b1 b2) res_ty
132   = do  { pred' <- tcCheckRho pred boolTy
133         ; b1'   <- tcCmd env b1 res_ty
134         ; b2'   <- tcCmd env b2 res_ty
135         ; return (HsIf pred' b1' b2')
136     }
137
138 -------------------------------------------
139 --              Arrow application
140 --          (f -< a)   or   (f -<< a)
141
142 tc_cmd env cmd@(HsArrApp fun arg _ ho_app lr) (cmd_stk, res_ty)
143   = addErrCtxt (cmdCtxt cmd)    $
144     do  { arg_ty <- newTyFlexiVarTy openTypeKind
145         ; let fun_ty = mkCmdArrTy env (foldl mkPairTy arg_ty cmd_stk) res_ty
146
147         ; fun' <- select_arrow_scope (tcCheckRho fun fun_ty)
148
149         ; arg' <- tcCheckRho arg arg_ty
150
151         ; return (HsArrApp fun' arg' fun_ty ho_app lr) }
152   where
153         -- Before type-checking f, use the environment of the enclosing
154         -- proc for the (-<) case.  
155         -- Local bindings, inside the enclosing proc, are not in scope 
156         -- inside f.  In the higher-order case (-<<), they are.
157     select_arrow_scope tc = case ho_app of
158         HsHigherOrderApp -> tc
159         HsFirstOrderApp  -> escapeArrowScope tc
160
161 -------------------------------------------
162 --              Command application
163
164 tc_cmd env cmd@(HsApp fun arg) (cmd_stk, res_ty)
165   = addErrCtxt (cmdCtxt cmd)    $
166 -- gaw 2004 FIX?
167     do  { arg_ty <- newTyFlexiVarTy openTypeKind
168
169         ; fun' <- tcCmd env fun (arg_ty:cmd_stk, res_ty)
170
171         ; arg' <- tcCheckRho arg arg_ty
172
173         ; return (HsApp fun' arg') }
174
175 -------------------------------------------
176 --              Lambda
177
178 -- gaw 2004
179 tc_cmd env cmd@(HsLam (MatchGroup [L mtch_loc (match@(Match pats maybe_rhs_sig grhss))] _))
180        (cmd_stk, res_ty)
181   = addErrCtxt (matchCtxt match_ctxt match)     $
182
183     do  {       -- Check the cmd stack is big enough
184         ; checkTc (lengthAtLeast cmd_stk n_pats)
185                   (kappaUnderflow cmd)
186
187                 -- Check the patterns, and the GRHSs inside
188         ; (pats', grhss') <- setSrcSpan mtch_loc                                        $
189                              tcMatchPats pats (map Check cmd_stk) (Check res_ty)        $
190                              tc_grhss grhss
191
192         ; let match' = L mtch_loc (Match pats' Nothing grhss')
193         ; return (HsLam (MatchGroup [match'] res_ty))
194         }
195
196   where
197     n_pats     = length pats
198     stk'       = drop n_pats cmd_stk
199     match_ctxt = LambdaExpr     -- Maybe KappaExpr?
200     pg_ctxt    = PatGuard match_ctxt
201
202     tc_grhss (GRHSs grhss binds)
203         = do { (binds', grhss') <- tcLocalBinds binds $
204                                    mappM (wrapLocM tc_grhs) grhss
205              ; return (GRHSs grhss' binds') }
206
207     tc_grhs (GRHS guards body)
208         = do { (guards', rhs') <- tcStmts pg_ctxt
209                                           (tcGuardStmt res_ty)
210                                           guards
211                                           (tcCmd env body (stk', res_ty))
212              ; return (GRHS guards' rhs') }
213
214 -------------------------------------------
215 --              Do notation
216
217 tc_cmd env cmd@(HsDo do_or_lc stmts body ty) (cmd_stk, res_ty)
218   = do  { checkTc (null cmd_stk) (nonEmptyCmdStkErr cmd)
219         ; (stmts', body') <- tcStmts do_or_lc tc_stmt stmts $
220                              tcCmd env body ([], res_ty)
221         ; return (HsDo do_or_lc stmts' body' res_ty) }
222   where
223     tc_stmt = tcMDoStmt res_ty tc_rhs
224     tc_rhs rhs = do { ty <- newTyFlexiVarTy liftedTypeKind
225                     ; rhs' <- tcCmd env rhs ([], ty)
226                     ; return (rhs', ty) }
227
228
229 -----------------------------------------------------------------
230 --      Arrow ``forms''       (| e c1 .. cn |)
231 --
232 --      G      |-b  c : [s1 .. sm] s
233 --      pop(G) |-   e : forall w. b ((w,s1) .. sm) s
234 --                              -> a ((w,t1) .. tn) t
235 --      e \not\in (s, s1..sm, t, t1..tn)
236 --      ----------------------------------------------
237 --      G |-a  (| e c |)  :  [t1 .. tn] t
238
239 tc_cmd env cmd@(HsArrForm expr fixity cmd_args) (cmd_stk, res_ty)       
240   = addErrCtxt (cmdCtxt cmd)    $
241     do  { cmds_w_tys <- zipWithM new_cmd_ty cmd_args [1..]
242         ; span       <- getSrcSpanM
243         ; [w_tv]     <- tcSkolTyVars (ArrowSkol span) [alphaTyVar]
244         ; let w_ty = mkTyVarTy w_tv     -- Just a convenient starting point
245
246                 --  a ((w,t1) .. tn) t
247         ; let e_res_ty = mkCmdArrTy env (foldl mkPairTy w_ty cmd_stk) res_ty
248
249                 --   b ((w,s1) .. sm) s
250                 --   -> a ((w,t1) .. tn) t
251         ; let e_ty = mkFunTys [mkAppTys b [tup,s] | (_,_,b,tup,s) <- cmds_w_tys] 
252                               e_res_ty
253
254                 -- Check expr
255         ; (expr', lie) <- escapeArrowScope (getLIE (tcCheckRho expr e_ty))
256         ; inst_binds <- tcSimplifyCheck sig_msg [w_tv] [] lie
257
258                 -- Check that the polymorphic variable hasn't been unified with anything
259                 -- and is not free in res_ty or the cmd_stk  (i.e.  t, t1..tn)
260         ; checkSigTyVarsWrt (tyVarsOfTypes (res_ty:cmd_stk)) [w_tv] 
261
262                 -- OK, now we are in a position to unscramble 
263                 -- the s1..sm and check each cmd
264         ; cmds' <- mapM (tc_cmd w_tv) cmds_w_tys
265
266         ; returnM (HsArrForm (mkHsTyLam [w_tv] (mkHsDictLet inst_binds expr')) fixity cmds')
267         }
268   where
269         -- Make the types       
270         --      b, ((e,s1) .. sm), s
271     new_cmd_ty :: LHsCmdTop Name -> Int
272                -> TcM (LHsCmdTop Name, Int, TcType, TcType, TcType)
273     new_cmd_ty cmd i
274 -- gaw 2004 FIX?
275           = do  { b_ty   <- newTyFlexiVarTy arrowTyConKind
276                 ; tup_ty <- newTyFlexiVarTy liftedTypeKind
277                         -- We actually make a type variable for the tuple
278                         -- because we don't know how deeply nested it is yet    
279                 ; s_ty   <- newTyFlexiVarTy liftedTypeKind
280                 ; return (cmd, i, b_ty, tup_ty, s_ty)
281                 }
282
283     tc_cmd w_tv (cmd, i, b, tup_ty, s)
284       = do { tup_ty' <- zonkTcType tup_ty
285            ; let (corner_ty, arg_tys) = unscramble tup_ty'
286
287                 -- Check that it has the right shape:
288                 --      ((w,s1) .. sn)
289                 -- where the si do not mention w
290            ; checkTc (corner_ty `tcEqType` mkTyVarTy w_tv && 
291                       not (w_tv `elemVarSet` tyVarsOfTypes arg_tys))
292                      (badFormFun i tup_ty')
293
294            ; tcCmdTop (env { cmd_arr = b }) cmd (arg_tys, s) }
295
296     unscramble :: TcType -> (TcType, [TcType])
297     -- unscramble ((w,s1) .. sn)        =  (w, [s1..sn])
298     unscramble ty
299        = case tcSplitTyConApp_maybe ty of
300             Just (tc, [t,s]) | tc == pairTyCon 
301                ->  let 
302                       (w,ss) = unscramble t  
303                    in (w, s:ss)
304                                     
305             other -> (ty, [])
306
307     sig_msg  = ptext SLIT("expected type of a command form")
308
309 -----------------------------------------------------------------
310 --              Base case for illegal commands
311 -- This is where expressions that aren't commands get rejected
312
313 tc_cmd env cmd _
314   = failWithTc (vcat [ptext SLIT("The expression"), nest 2 (ppr cmd), 
315                       ptext SLIT("was found where an arrow command was expected")])
316 \end{code}
317
318
319 %************************************************************************
320 %*                                                                      *
321                 Helpers
322 %*                                                                      *
323 %************************************************************************
324
325
326 \begin{code}
327 mkPairTy t1 t2 = mkTyConApp pairTyCon [t1,t2]
328
329 arrowTyConKind :: Kind          --  *->*->*
330 arrowTyConKind = mkArrowKinds [liftedTypeKind, liftedTypeKind] liftedTypeKind
331 \end{code}
332
333
334 %************************************************************************
335 %*                                                                      *
336                 Errors
337 %*                                                                      *
338 %************************************************************************
339
340 \begin{code}
341 cmdCtxt cmd = ptext SLIT("In the command:") <+> ppr cmd
342
343 caseScrutCtxt cmd
344   = hang (ptext SLIT("In the scrutinee of a case command:")) 4 (ppr cmd)
345
346 nonEmptyCmdStkErr cmd
347   = hang (ptext SLIT("Non-empty command stack at command:"))
348          4 (ppr cmd)
349
350 kappaUnderflow cmd
351   = hang (ptext SLIT("Command stack underflow at command:"))
352          4 (ppr cmd)
353
354 badFormFun i tup_ty'
355  = hang (ptext SLIT("The type of the") <+> speakNth i <+> ptext SLIT("argument of a command form has the wrong shape"))
356         4 (ptext SLIT("Argument type:") <+> ppr tup_ty')
357 \end{code}