Another major improvement of "improvement"
[ghc.git] / compiler / typecheck / TcArrows.hs
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
8 {-# LANGUAGE RankNTypes #-}
9
10 module TcArrows ( tcProc ) where
11
12 import {-# SOURCE #-} TcExpr( tcMonoExpr, tcInferRho, tcSyntaxOp, tcCheckId, tcPolyExpr )
13
14 import HsSyn
15 import TcMatches
16 import TcHsSyn( hsLPatType )
17 import TcType
18 import TcMType
19 import TcBinds
20 import TcPat
21 import TcUnify
22 import TcRnMonad
23 import TcEnv
24 import TcEvidence
25 import Id( mkLocalId )
26 import Inst
27 import Name
28 import Coercion ( Role(..) )
29 import TysWiredIn
30 import VarSet
31 import TysPrim
32 import BasicTypes( Arity )
33 import SrcLoc
34 import Outputable
35 import FastString
36 import Util
37
38 import Control.Monad
39
40 {-
41 Note [Arrow overivew]
42 ~~~~~~~~~~~~~~~~~~~~~
43 Here's a summary of arrows and how they typecheck. First, here's
44 a cut-down syntax:
45
46 expr ::= ....
47 | proc pat cmd
48
49 cmd ::= cmd exp -- Arrow application
50 | \pat -> cmd -- Arrow abstraction
51 | (| exp cmd1 ... cmdn |) -- Arrow form, n>=0
52 | ... -- If, case in the usual way
53
54 cmd_type ::= carg_type --> type
55
56 carg_type ::= ()
57 | (type, carg_type)
58
59 Note that
60 * The 'exp' in an arrow form can mention only
61 "arrow-local" variables
62
63 * An "arrow-local" variable is bound by an enclosing
64 cmd binding form (eg arrow abstraction)
65
66 * A cmd_type is here written with a funny arrow "-->",
67 The bit on the left is a carg_type (command argument type)
68 which itself is a nested tuple, finishing with ()
69
70 * The arrow-tail operator (e1 -< e2) means
71 (| e1 <<< arr snd |) e2
72
73
74 ************************************************************************
75 * *
76 Proc
77 * *
78 ************************************************************************
79 -}
80
81 tcProc :: InPat Name -> LHsCmdTop Name -- proc pat -> expr
82 -> TcRhoType -- Expected type of whole proc expression
83 -> TcM (OutPat TcId, LHsCmdTop TcId, TcCoercion)
84
85 tcProc pat cmd exp_ty
86 = newArrowScope $
87 do { (co, (exp_ty1, res_ty)) <- matchExpectedAppTy exp_ty
88 ; (co1, (arr_ty, arg_ty)) <- matchExpectedAppTy exp_ty1
89 ; let cmd_env = CmdEnv { cmd_arr = arr_ty }
90 ; (pat', cmd') <- tcPat ProcExpr pat arg_ty $
91 tcCmdTop cmd_env cmd (unitTy, res_ty)
92 ; let res_co = mkTcTransCo co (mkTcAppCo co1 (mkTcNomReflCo res_ty))
93 ; return (pat', cmd', res_co) }
94
95 {-
96 ************************************************************************
97 * *
98 Commands
99 * *
100 ************************************************************************
101 -}
102
103 -- See Note [Arrow overview]
104 type CmdType = (CmdArgType, TcTauType) -- cmd_type
105 type CmdArgType = TcTauType -- carg_type, a nested tuple
106
107 data CmdEnv
108 = CmdEnv {
109 cmd_arr :: TcType -- arrow type constructor, of kind *->*->*
110 }
111
112 mkCmdArrTy :: CmdEnv -> TcTauType -> TcTauType -> TcTauType
113 mkCmdArrTy env t1 t2 = mkAppTys (cmd_arr env) [t1, t2]
114
115 ---------------------------------------
116 tcCmdTop :: CmdEnv
117 -> LHsCmdTop Name
118 -> CmdType
119 -> TcM (LHsCmdTop TcId)
120
121 tcCmdTop env (L loc (HsCmdTop cmd _ _ names)) cmd_ty@(cmd_stk, res_ty)
122 = setSrcSpan loc $
123 do { cmd' <- tcCmd env cmd cmd_ty
124 ; names' <- mapM (tcSyntaxName ProcOrigin (cmd_arr env)) names
125 ; return (L loc $ HsCmdTop cmd' cmd_stk res_ty names') }
126 ----------------------------------------
127 tcCmd :: CmdEnv -> LHsCmd Name -> CmdType -> TcM (LHsCmd TcId)
128 -- The main recursive function
129 tcCmd env (L loc cmd) res_ty
130 = setSrcSpan loc $ do
131 { cmd' <- tc_cmd env cmd res_ty
132 ; return (L loc cmd') }
133
134 tc_cmd :: CmdEnv -> HsCmd Name -> CmdType -> TcM (HsCmd TcId)
135 tc_cmd env (HsCmdPar cmd) res_ty
136 = do { cmd' <- tcCmd env cmd res_ty
137 ; return (HsCmdPar cmd') }
138
139 tc_cmd env (HsCmdLet binds (L body_loc body)) res_ty
140 = do { (binds', body') <- tcLocalBinds binds $
141 setSrcSpan body_loc $
142 tc_cmd env body res_ty
143 ; return (HsCmdLet binds' (L body_loc body')) }
144
145 tc_cmd env in_cmd@(HsCmdCase scrut matches) (stk, res_ty)
146 = addErrCtxt (cmdCtxt in_cmd) $ do
147 (scrut', scrut_ty) <- tcInferRho scrut
148 matches' <- tcMatchesCase match_ctxt scrut_ty matches res_ty
149 return (HsCmdCase scrut' matches')
150 where
151 match_ctxt = MC { mc_what = CaseAlt,
152 mc_body = mc_body }
153 mc_body body res_ty' = tcCmd env body (stk, res_ty')
154
155 tc_cmd env (HsCmdIf Nothing pred b1 b2) res_ty -- Ordinary 'if'
156 = do { pred' <- tcMonoExpr pred boolTy
157 ; b1' <- tcCmd env b1 res_ty
158 ; b2' <- tcCmd env b2 res_ty
159 ; return (HsCmdIf Nothing pred' b1' b2')
160 }
161
162 tc_cmd env (HsCmdIf (Just fun) pred b1 b2) res_ty -- Rebindable syntax for if
163 = do { pred_ty <- newFlexiTyVarTy openTypeKind
164 -- For arrows, need ifThenElse :: forall r. T -> r -> r -> r
165 -- because we're going to apply it to the environment, not
166 -- the return value.
167 ; (_, [r_tv]) <- tcInstSkolTyVars [alphaTyVar]
168 ; let r_ty = mkTyVarTy r_tv
169 ; let if_ty = mkFunTys [pred_ty, r_ty, r_ty] r_ty
170 ; checkTc (not (r_tv `elemVarSet` tyVarsOfType pred_ty))
171 (ptext (sLit "Predicate type of `ifThenElse' depends on result type"))
172 ; fun' <- tcSyntaxOp IfOrigin fun if_ty
173 ; pred' <- tcMonoExpr pred pred_ty
174 ; b1' <- tcCmd env b1 res_ty
175 ; b2' <- tcCmd env b2 res_ty
176 ; return (HsCmdIf (Just fun') pred' b1' b2')
177 }
178
179 -------------------------------------------
180 -- Arrow application
181 -- (f -< a) or (f -<< a)
182 --
183 -- D |- fun :: a t1 t2
184 -- D,G |- arg :: t1
185 -- ------------------------
186 -- D;G |-a fun -< arg :: stk --> t2
187 --
188 -- D,G |- fun :: a t1 t2
189 -- D,G |- arg :: t1
190 -- ------------------------
191 -- D;G |-a fun -<< arg :: stk --> t2
192 --
193 -- (plus -<< requires ArrowApply)
194
195 tc_cmd env cmd@(HsCmdArrApp fun arg _ ho_app lr) (_, res_ty)
196 = addErrCtxt (cmdCtxt cmd) $
197 do { arg_ty <- newFlexiTyVarTy openTypeKind
198 ; let fun_ty = mkCmdArrTy env arg_ty res_ty
199 ; fun' <- select_arrow_scope (tcMonoExpr fun fun_ty)
200
201 ; arg' <- tcMonoExpr arg arg_ty
202
203 ; return (HsCmdArrApp fun' arg' fun_ty ho_app lr) }
204 where
205 -- Before type-checking f, use the environment of the enclosing
206 -- proc for the (-<) case.
207 -- Local bindings, inside the enclosing proc, are not in scope
208 -- inside f. In the higher-order case (-<<), they are.
209 -- See Note [Escaping the arrow scope] in TcRnTypes
210 select_arrow_scope tc = case ho_app of
211 HsHigherOrderApp -> tc
212 HsFirstOrderApp -> escapeArrowScope tc
213
214 -------------------------------------------
215 -- Command application
216 --
217 -- D,G |- exp : t
218 -- D;G |-a cmd : (t,stk) --> res
219 -- -----------------------------
220 -- D;G |-a cmd exp : stk --> res
221
222 tc_cmd env cmd@(HsCmdApp fun arg) (cmd_stk, res_ty)
223 = addErrCtxt (cmdCtxt cmd) $
224 do { arg_ty <- newFlexiTyVarTy openTypeKind
225 ; fun' <- tcCmd env fun (mkPairTy arg_ty cmd_stk, res_ty)
226 ; arg' <- tcMonoExpr arg arg_ty
227 ; return (HsCmdApp fun' arg') }
228
229 -------------------------------------------
230 -- Lambda
231 --
232 -- D;G,x:t |-a cmd : stk --> res
233 -- ------------------------------
234 -- D;G |-a (\x.cmd) : (t,stk) --> res
235
236 tc_cmd env
237 (HsCmdLam (MG { mg_alts = [L mtch_loc
238 (match@(Match _ pats _maybe_rhs_sig grhss))],
239 mg_origin = origin }))
240 (cmd_stk, res_ty)
241 = addErrCtxt (pprMatchInCtxt match_ctxt match) $
242 do { (co, arg_tys, cmd_stk') <- matchExpectedCmdArgs n_pats cmd_stk
243
244 -- Check the patterns, and the GRHSs inside
245 ; (pats', grhss') <- setSrcSpan mtch_loc $
246 tcPats LambdaExpr pats arg_tys $
247 tc_grhss grhss cmd_stk' res_ty
248
249 ; let match' = L mtch_loc (Match Nothing pats' Nothing grhss')
250 arg_tys = map hsLPatType pats'
251 cmd' = HsCmdLam (MG { mg_alts = [match'], mg_arg_tys = arg_tys
252 , mg_res_ty = res_ty, mg_origin = origin })
253 ; return (mkHsCmdCast co cmd') }
254 where
255 n_pats = length pats
256 match_ctxt = (LambdaExpr :: HsMatchContext Name) -- Maybe KappaExpr?
257 pg_ctxt = PatGuard match_ctxt
258
259 tc_grhss (GRHSs grhss binds) stk_ty res_ty
260 = do { (binds', grhss') <- tcLocalBinds binds $
261 mapM (wrapLocM (tc_grhs stk_ty res_ty)) grhss
262 ; return (GRHSs grhss' binds') }
263
264 tc_grhs stk_ty res_ty (GRHS guards body)
265 = do { (guards', rhs') <- tcStmtsAndThen pg_ctxt tcGuardStmt guards res_ty $
266 \ res_ty -> tcCmd env body (stk_ty, res_ty)
267 ; return (GRHS guards' rhs') }
268
269 -------------------------------------------
270 -- Do notation
271
272 tc_cmd env (HsCmdDo stmts _) (cmd_stk, res_ty)
273 = do { co <- unifyType unitTy cmd_stk -- Expecting empty argument stack
274 ; stmts' <- tcStmts ArrowExpr (tcArrDoStmt env) stmts res_ty
275 ; return (mkHsCmdCast co (HsCmdDo stmts' res_ty)) }
276
277
278 -----------------------------------------------------------------
279 -- Arrow ``forms'' (| e c1 .. cn |)
280 --
281 -- D; G |-a1 c1 : stk1 --> r1
282 -- ...
283 -- D; G |-an cn : stkn --> rn
284 -- D |- e :: forall e. a1 (e, stk1) t1
285 -- ...
286 -- -> an (e, stkn) tn
287 -- -> a (e, stk) t
288 -- e \not\in (stk, stk1, ..., stkm, t, t1, ..., tn)
289 -- ----------------------------------------------
290 -- D; G |-a (| e c1 ... cn |) : stk --> t
291
292 tc_cmd env cmd@(HsCmdArrForm expr fixity cmd_args) (cmd_stk, res_ty)
293 = addErrCtxt (cmdCtxt cmd) $
294 do { (cmd_args', cmd_tys) <- mapAndUnzipM tc_cmd_arg cmd_args
295 ; let e_ty = mkForAllTy alphaTyVar $ -- We use alphaTyVar for 'w'
296 mkFunTys cmd_tys $
297 mkCmdArrTy env (mkPairTy alphaTy cmd_stk) res_ty
298 ; expr' <- tcPolyExpr expr e_ty
299 ; return (HsCmdArrForm expr' fixity cmd_args') }
300
301 where
302 tc_cmd_arg :: LHsCmdTop Name -> TcM (LHsCmdTop TcId, TcType)
303 tc_cmd_arg cmd
304 = do { arr_ty <- newFlexiTyVarTy arrowTyConKind
305 ; stk_ty <- newFlexiTyVarTy liftedTypeKind
306 ; res_ty <- newFlexiTyVarTy liftedTypeKind
307 ; let env' = env { cmd_arr = arr_ty }
308 ; cmd' <- tcCmdTop env' cmd (stk_ty, res_ty)
309 ; return (cmd', mkCmdArrTy env' (mkPairTy alphaTy stk_ty) res_ty) }
310
311 -----------------------------------------------------------------
312 -- Base case for illegal commands
313 -- This is where expressions that aren't commands get rejected
314
315 tc_cmd _ cmd _
316 = failWithTc (vcat [ptext (sLit "The expression"), nest 2 (ppr cmd),
317 ptext (sLit "was found where an arrow command was expected")])
318
319
320 matchExpectedCmdArgs :: Arity -> TcType -> TcM (TcCoercion, [TcType], TcType)
321 matchExpectedCmdArgs 0 ty
322 = return (mkTcNomReflCo ty, [], ty)
323 matchExpectedCmdArgs n ty
324 = do { (co1, [ty1, ty2]) <- matchExpectedTyConApp pairTyCon ty
325 ; (co2, tys, res_ty) <- matchExpectedCmdArgs (n-1) ty2
326 ; return (mkTcTyConAppCo Nominal pairTyCon [co1, co2], ty1:tys, res_ty) }
327
328 {-
329 ************************************************************************
330 * *
331 Stmts
332 * *
333 ************************************************************************
334 -}
335
336 --------------------------------
337 -- Mdo-notation
338 -- The distinctive features here are
339 -- (a) RecStmts, and
340 -- (b) no rebindable syntax
341
342 tcArrDoStmt :: CmdEnv -> TcCmdStmtChecker
343 tcArrDoStmt env _ (LastStmt rhs _) res_ty thing_inside
344 = do { rhs' <- tcCmd env rhs (unitTy, res_ty)
345 ; thing <- thing_inside (panic "tcArrDoStmt")
346 ; return (LastStmt rhs' noSyntaxExpr, thing) }
347
348 tcArrDoStmt env _ (BodyStmt rhs _ _ _) res_ty thing_inside
349 = do { (rhs', elt_ty) <- tc_arr_rhs env rhs
350 ; thing <- thing_inside res_ty
351 ; return (BodyStmt rhs' noSyntaxExpr noSyntaxExpr elt_ty, thing) }
352
353 tcArrDoStmt env ctxt (BindStmt pat rhs _ _) res_ty thing_inside
354 = do { (rhs', pat_ty) <- tc_arr_rhs env rhs
355 ; (pat', thing) <- tcPat (StmtCtxt ctxt) pat pat_ty $
356 thing_inside res_ty
357 ; return (BindStmt pat' rhs' noSyntaxExpr noSyntaxExpr, thing) }
358
359 tcArrDoStmt env ctxt (RecStmt { recS_stmts = stmts, recS_later_ids = later_names
360 , recS_rec_ids = rec_names }) res_ty thing_inside
361 = do { let tup_names = rec_names ++ filterOut (`elem` rec_names) later_names
362 ; tup_elt_tys <- newFlexiTyVarTys (length tup_names) liftedTypeKind
363 ; let tup_ids = zipWith mkLocalId tup_names tup_elt_tys
364 ; tcExtendIdEnv tup_ids $ do
365 { (stmts', tup_rets)
366 <- tcStmtsAndThen ctxt (tcArrDoStmt env) stmts res_ty $ \ _res_ty' ->
367 -- ToDo: res_ty not really right
368 zipWithM tcCheckId tup_names tup_elt_tys
369
370 ; thing <- thing_inside res_ty
371 -- NB: The rec_ids for the recursive things
372 -- already scope over this part. This binding may shadow
373 -- some of them with polymorphic things with the same Name
374 -- (see note [RecStmt] in HsExpr)
375
376 ; let rec_ids = takeList rec_names tup_ids
377 ; later_ids <- tcLookupLocalIds later_names
378
379 ; let rec_rets = takeList rec_names tup_rets
380 ; let ret_table = zip tup_ids tup_rets
381 ; let later_rets = [r | i <- later_ids, (j, r) <- ret_table, i == j]
382
383 ; return (emptyRecStmtId { recS_stmts = stmts'
384 , recS_later_ids = later_ids
385 , recS_later_rets = later_rets
386 , recS_rec_ids = rec_ids
387 , recS_rec_rets = rec_rets
388 , recS_ret_ty = res_ty }, thing)
389 }}
390
391 tcArrDoStmt _ _ stmt _ _
392 = pprPanic "tcArrDoStmt: unexpected Stmt" (ppr stmt)
393
394 tc_arr_rhs :: CmdEnv -> LHsCmd Name -> TcM (LHsCmd TcId, TcType)
395 tc_arr_rhs env rhs = do { ty <- newFlexiTyVarTy liftedTypeKind
396 ; rhs' <- tcCmd env rhs (unitTy, ty)
397 ; return (rhs', ty) }
398
399 {-
400 ************************************************************************
401 * *
402 Helpers
403 * *
404 ************************************************************************
405 -}
406
407 mkPairTy :: Type -> Type -> Type
408 mkPairTy t1 t2 = mkTyConApp pairTyCon [t1,t2]
409
410 arrowTyConKind :: Kind -- *->*->*
411 arrowTyConKind = mkArrowKinds [liftedTypeKind, liftedTypeKind] liftedTypeKind
412
413 {-
414 ************************************************************************
415 * *
416 Errors
417 * *
418 ************************************************************************
419 -}
420
421 cmdCtxt :: HsCmd Name -> SDoc
422 cmdCtxt cmd = ptext (sLit "In the command:") <+> ppr cmd