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