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