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