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