b02eb2b9bb4f273dbebd88761a0cf48ab826ca53
[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  (  mkHsLet )
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  ( tcBindsAndThen )
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   = tcBindsAndThen glue binds   $
115     setSrcSpan body_loc         $
116     tc_cmd env body res_ty
117   where
118     glue binds expr = HsLet [binds] (L body_loc expr)
119
120 tc_cmd env in_cmd@(HsCase scrut matches) (stk, res_ty)
121   = addErrCtxt (cmdCtxt in_cmd)         $
122     addErrCtxt (caseScrutCtxt scrut)    (
123       tcInferRho scrut 
124     )                                                           `thenM` \ (scrut', scrut_ty) ->
125     tcMatchesCase match_ctxt scrut_ty matches (Check res_ty)    `thenM` \ matches' ->
126     returnM (HsCase scrut' matches')
127   where
128     match_ctxt = MC { mc_what = CaseAlt,
129                       mc_body = mc_body }
130     mc_body body (Check res_ty') = tcCmd env body (stk, res_ty')
131
132 tc_cmd env (HsIf pred b1 b2) res_ty
133   = do  { pred' <- tcCheckRho pred boolTy
134         ; b1'   <- tcCmd env b1 res_ty
135         ; b2'   <- tcCmd env b2 res_ty
136         ; return (HsIf pred' b1' b2')
137     }
138
139 -------------------------------------------
140 --              Arrow application
141 --          (f -< a)   or   (f -<< a)
142
143 tc_cmd env cmd@(HsArrApp fun arg _ ho_app lr) (cmd_stk, res_ty)
144   = addErrCtxt (cmdCtxt cmd)    $
145     do  { arg_ty <- newTyFlexiVarTy openTypeKind
146         ; let fun_ty = mkCmdArrTy env (foldl mkPairTy arg_ty cmd_stk) res_ty
147
148         ; fun' <- select_arrow_scope (tcCheckRho fun fun_ty)
149
150         ; arg' <- tcCheckRho arg arg_ty
151
152         ; return (HsArrApp fun' arg' fun_ty ho_app lr) }
153   where
154         -- Before type-checking f, use the environment of the enclosing
155         -- proc for the (-<) case.  
156         -- Local bindings, inside the enclosing proc, are not in scope 
157         -- inside f.  In the higher-order case (-<<), they are.
158     select_arrow_scope tc = case ho_app of
159         HsHigherOrderApp -> tc
160         HsFirstOrderApp  -> escapeArrowScope tc
161
162 -------------------------------------------
163 --              Command application
164
165 tc_cmd env cmd@(HsApp fun arg) (cmd_stk, res_ty)
166   = addErrCtxt (cmdCtxt cmd)    $
167 -- gaw 2004 FIX?
168     do  { arg_ty <- newTyFlexiVarTy openTypeKind
169
170         ; fun' <- tcCmd env fun (arg_ty:cmd_stk, res_ty)
171
172         ; arg' <- tcCheckRho arg arg_ty
173
174         ; return (HsApp fun' arg') }
175
176 -------------------------------------------
177 --              Lambda
178
179 -- gaw 2004
180 tc_cmd env cmd@(HsLam (MatchGroup [L mtch_loc (match@(Match pats maybe_rhs_sig grhss))] _))
181        (cmd_stk, res_ty)
182   = addErrCtxt (matchCtxt match_ctxt match)     $
183
184     do  {       -- Check the cmd stack is big enough
185         ; checkTc (lengthAtLeast cmd_stk n_pats)
186                   (kappaUnderflow cmd)
187
188                 -- Check the patterns, and the GRHSs inside
189         ; (pats', grhss') <- setSrcSpan mtch_loc                                        $
190                              tcMatchPats pats (map Check cmd_stk) (Check res_ty)        $
191                              tc_grhss grhss
192
193         ; let match' = L mtch_loc (Match pats' Nothing grhss')
194         ; return (HsLam (MatchGroup [match'] res_ty))
195         }
196
197   where
198     n_pats     = length pats
199     stk'       = drop n_pats cmd_stk
200     match_ctxt = LambdaExpr     -- Maybe KappaExpr?
201     pg_ctxt    = PatGuard match_ctxt
202
203     tc_grhss (GRHSs grhss binds)
204         = tcBindsAndThen glueBindsOnGRHSs binds $
205           do { grhss' <- mappM (wrapLocM tc_grhs) grhss
206              ; return (GRHSs grhss' []) }
207
208     tc_grhs (GRHS guards body)
209         = do { (guards', rhs') <- tcStmts pg_ctxt
210                                           (tcGuardStmt res_ty)
211                                           guards
212                                           (tcCmd env body (stk', res_ty))
213              ; return (GRHS guards' rhs') }
214
215 -------------------------------------------
216 --              Do notation
217
218 tc_cmd env cmd@(HsDo do_or_lc stmts body ty) (cmd_stk, res_ty)
219   = do  { checkTc (null cmd_stk) (nonEmptyCmdStkErr cmd)
220         ; (stmts', body') <- tcStmts do_or_lc tc_stmt stmts $
221                              tcCmd env body ([], res_ty)
222         ; return (HsDo do_or_lc stmts' body' res_ty) }
223   where
224     tc_stmt = tcMDoStmt res_ty tc_rhs
225     tc_rhs rhs = do { ty <- newTyFlexiVarTy liftedTypeKind
226                     ; rhs' <- tcCmd env rhs ([], ty)
227                     ; return (rhs', ty) }
228
229
230 -----------------------------------------------------------------
231 --      Arrow ``forms''       (| e c1 .. cn |)
232 --
233 --      G      |-b  c : [s1 .. sm] s
234 --      pop(G) |-   e : forall w. b ((w,s1) .. sm) s
235 --                              -> a ((w,t1) .. tn) t
236 --      e \not\in (s, s1..sm, t, t1..tn)
237 --      ----------------------------------------------
238 --      G |-a  (| e c |)  :  [t1 .. tn] t
239
240 tc_cmd env cmd@(HsArrForm expr fixity cmd_args) (cmd_stk, res_ty)       
241   = addErrCtxt (cmdCtxt cmd)    $
242     do  { cmds_w_tys <- zipWithM new_cmd_ty cmd_args [1..]
243         ; span       <- getSrcSpanM
244         ; [w_tv]     <- tcSkolTyVars (ArrowSkol span) [alphaTyVar]
245         ; let w_ty = mkTyVarTy w_tv     -- Just a convenient starting point
246
247                 --  a ((w,t1) .. tn) t
248         ; let e_res_ty = mkCmdArrTy env (foldl mkPairTy w_ty cmd_stk) res_ty
249
250                 --   b ((w,s1) .. sm) s
251                 --   -> a ((w,t1) .. tn) t
252         ; let e_ty = mkFunTys [mkAppTys b [tup,s] | (_,_,b,tup,s) <- cmds_w_tys] 
253                               e_res_ty
254
255                 -- Check expr
256         ; (expr', lie) <- escapeArrowScope (getLIE (tcCheckRho expr e_ty))
257         ; inst_binds <- tcSimplifyCheck sig_msg [w_tv] [] lie
258
259                 -- Check that the polymorphic variable hasn't been unified with anything
260                 -- and is not free in res_ty or the cmd_stk  (i.e.  t, t1..tn)
261         ; checkSigTyVarsWrt (tyVarsOfTypes (res_ty:cmd_stk)) [w_tv] 
262
263                 -- OK, now we are in a position to unscramble 
264                 -- the s1..sm and check each cmd
265         ; cmds' <- mapM (tc_cmd w_tv) cmds_w_tys
266
267         ; returnM (HsArrForm (mkHsTyLam [w_tv] (mkHsLet inst_binds expr')) fixity cmds')
268         }
269   where
270         -- Make the types       
271         --      b, ((e,s1) .. sm), s
272     new_cmd_ty :: LHsCmdTop Name -> Int
273                -> TcM (LHsCmdTop Name, Int, TcType, TcType, TcType)
274     new_cmd_ty cmd i
275 -- gaw 2004 FIX?
276           = do  { b_ty   <- newTyFlexiVarTy arrowTyConKind
277                 ; tup_ty <- newTyFlexiVarTy liftedTypeKind
278                         -- We actually make a type variable for the tuple
279                         -- because we don't know how deeply nested it is yet    
280                 ; s_ty   <- newTyFlexiVarTy liftedTypeKind
281                 ; return (cmd, i, b_ty, tup_ty, s_ty)
282                 }
283
284     tc_cmd w_tv (cmd, i, b, tup_ty, s)
285       = do { tup_ty' <- zonkTcType tup_ty
286            ; let (corner_ty, arg_tys) = unscramble tup_ty'
287
288                 -- Check that it has the right shape:
289                 --      ((w,s1) .. sn)
290                 -- where the si do not mention w
291            ; checkTc (corner_ty `tcEqType` mkTyVarTy w_tv && 
292                       not (w_tv `elemVarSet` tyVarsOfTypes arg_tys))
293                      (badFormFun i tup_ty')
294
295            ; tcCmdTop (env { cmd_arr = b }) cmd (arg_tys, s) }
296
297     unscramble :: TcType -> (TcType, [TcType])
298     -- unscramble ((w,s1) .. sn)        =  (w, [s1..sn])
299     unscramble ty
300        = case tcSplitTyConApp_maybe ty of
301             Just (tc, [t,s]) | tc == pairTyCon 
302                ->  let 
303                       (w,ss) = unscramble t  
304                    in (w, s:ss)
305                                     
306             other -> (ty, [])
307
308     sig_msg  = ptext SLIT("expected type of a command form")
309
310 -----------------------------------------------------------------
311 --              Base case for illegal commands
312 -- This is where expressions that aren't commands get rejected
313
314 tc_cmd env cmd _
315   = failWithTc (vcat [ptext SLIT("The expression"), nest 2 (ppr cmd), 
316                       ptext SLIT("was found where an arrow command was expected")])
317 \end{code}
318
319
320 %************************************************************************
321 %*                                                                      *
322                 Helpers
323 %*                                                                      *
324 %************************************************************************
325
326
327 \begin{code}
328 mkPairTy t1 t2 = mkTyConApp pairTyCon [t1,t2]
329
330 arrowTyConKind :: Kind          --  *->*->*
331 arrowTyConKind = mkArrowKinds [liftedTypeKind, liftedTypeKind] liftedTypeKind
332 \end{code}
333
334
335 %************************************************************************
336 %*                                                                      *
337                 Errors
338 %*                                                                      *
339 %************************************************************************
340
341 \begin{code}
342 cmdCtxt cmd = ptext SLIT("In the command:") <+> ppr cmd
343
344 caseScrutCtxt cmd
345   = hang (ptext SLIT("In the scrutinee of a case command:")) 4 (ppr cmd)
346
347 nonEmptyCmdStkErr cmd
348   = hang (ptext SLIT("Non-empty command stack at command:"))
349          4 (ppr cmd)
350
351 kappaUnderflow cmd
352   = hang (ptext SLIT("Command stack underflow at command:"))
353          4 (ppr cmd)
354
355 badFormFun i tup_ty'
356  = hang (ptext SLIT("The type of the") <+> speakNth i <+> ptext SLIT("argument of a command form has the wrong shape"))
357         4 (ptext SLIT("Argument type:") <+> ppr tup_ty')
358 \end{code}