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