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