a733638c9ef4f17f846fe5f4a9a9c48933f22353
[ghc-hetmet.git] / ghc / compiler / typecheck / TcBinds.lhs
1 %
2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1996
3 %
4 \section[TcBinds]{TcBinds}
5
6 \begin{code}
7 #include "HsVersions.h"
8
9 module TcBinds ( tcBindsAndThen, tcPragmaSigs ) where
10
11 IMP_Ubiq()
12
13 import HsSyn            ( HsBinds(..), Bind(..), Sig(..), MonoBinds(..), 
14                           HsExpr, Match, PolyType, InPat, OutPat(..),
15                           GRHSsAndBinds, ArithSeqInfo, HsLit, Fake,
16                           collectBinders )
17 import RnHsSyn          ( SYN_IE(RenamedHsBinds), SYN_IE(RenamedBind), RenamedSig(..), 
18                           SYN_IE(RenamedMonoBinds), RnName(..) 
19                         )
20 import TcHsSyn          ( SYN_IE(TcHsBinds), SYN_IE(TcBind), SYN_IE(TcMonoBinds),
21                           TcIdOcc(..), SYN_IE(TcIdBndr) )
22
23 import TcMonad          hiding ( rnMtoTcM )     
24 import GenSpecEtc       ( checkSigTyVars, genBinds, TcSigInfo(..) )
25 import Inst             ( Inst, SYN_IE(LIE), emptyLIE, plusLIE, InstOrigin(..) )
26 import TcEnv            ( tcExtendLocalValEnv, tcLookupLocalValueOK, newMonoIds )
27 IMPORT_DELOOPER(TcLoop)         ( tcGRHSsAndBinds )
28 import TcMatches        ( tcMatchesFun )
29 import TcMonoType       ( tcPolyType )
30 import TcPat            ( tcPat )
31 import TcSimplify       ( bindInstsOfLocalFuns )
32 import TcType           ( newTcTyVar, tcInstSigType )
33 import Unify            ( unifyTauTy )
34
35 import Kind             ( mkBoxedTypeKind, mkTypeKind )
36 import Id               ( GenId, idType, mkUserId )
37 import IdInfo           ( noIdInfo )
38 import Maybes           ( assocMaybe, catMaybes )
39 import Name             ( pprNonSym, Name )
40 import PragmaInfo       ( PragmaInfo(..) )
41 import Pretty
42 import Type             ( mkTyVarTy, mkTyVarTys, isTyVarTy,
43                           mkSigmaTy, splitSigmaTy,
44                           splitRhoTy, mkForAllTy, splitForAllTy )
45 import Util             ( isIn, zipEqual, panic )
46 \end{code}
47
48 %************************************************************************
49 %*                                                                      *
50 \subsection{Type-checking bindings}
51 %*                                                                      *
52 %************************************************************************
53
54 @tcBindsAndThen@ typechecks a @HsBinds@.  The "and then" part is because
55 it needs to know something about the {\em usage} of the things bound,
56 so that it can create specialisations of them.  So @tcBindsAndThen@
57 takes a function which, given an extended environment, E, typechecks
58 the scope of the bindings returning a typechecked thing and (most
59 important) an LIE.  It is this LIE which is then used as the basis for
60 specialising the things bound.
61
62 @tcBindsAndThen@ also takes a "combiner" which glues together the
63 bindings and the "thing" to make a new "thing".
64
65 The real work is done by @tcBindAndThen@.
66
67 Recursive and non-recursive binds are handled in essentially the same
68 way: because of uniques there are no scoping issues left.  The only
69 difference is that non-recursive bindings can bind primitive values.
70
71 Even for non-recursive binding groups we add typings for each binder
72 to the LVE for the following reason.  When each individual binding is
73 checked the type of its LHS is unified with that of its RHS; and
74 type-checking the LHS of course requires that the binder is in scope.
75
76 At the top-level the LIE is sure to contain nothing but constant
77 dictionaries, which we resolve at the module level.
78
79 \begin{code}
80 tcBindsAndThen
81         :: (TcHsBinds s -> thing -> thing)              -- Combinator
82         -> RenamedHsBinds
83         -> TcM s (thing, LIE s, thing_ty)
84         -> TcM s (thing, LIE s, thing_ty)
85
86 tcBindsAndThen combiner EmptyBinds do_next
87   = do_next     `thenTc` \ (thing, lie, thing_ty) ->
88     returnTc (combiner EmptyBinds thing, lie, thing_ty)
89
90 tcBindsAndThen combiner (SingleBind bind) do_next
91   = tcBindAndThen combiner bind [] do_next
92
93 tcBindsAndThen combiner (BindWith bind sigs) do_next
94   = tcBindAndThen combiner bind sigs do_next
95
96 tcBindsAndThen combiner (ThenBinds binds1 binds2) do_next
97   = tcBindsAndThen combiner binds1 (tcBindsAndThen combiner binds2 do_next)
98 \end{code}
99
100 An aside.  The original version of @tcBindsAndThen@ which lacks a
101 combiner function, appears below.  Though it is perfectly well
102 behaved, it cannot be typed by Haskell, because the recursive call is
103 at a different type to the definition itself.  There aren't too many
104 examples of this, which is why I thought it worth preserving! [SLPJ]
105
106 \begin{pseudocode}
107 tcBindsAndThen
108         :: RenamedHsBinds
109         -> TcM s (thing, LIE s, thing_ty))
110         -> TcM s ((TcHsBinds s, thing), LIE s, thing_ty)
111
112 tcBindsAndThen EmptyBinds do_next
113   = do_next             `thenTc` \ (thing, lie, thing_ty) ->
114     returnTc ((EmptyBinds, thing), lie, thing_ty)
115
116 tcBindsAndThen (SingleBind bind) do_next
117   = tcBindAndThen bind [] do_next
118
119 tcBindsAndThen (BindWith bind sigs) do_next
120   = tcBindAndThen bind sigs do_next
121
122 tcBindsAndThen (ThenBinds binds1 binds2) do_next
123   = tcBindsAndThen binds1 (tcBindsAndThen binds2 do_next)
124         `thenTc` \ ((binds1', (binds2', thing')), lie1, thing_ty) ->
125
126     returnTc ((binds1' `ThenBinds` binds2', thing'), lie1, thing_ty)
127 \end{pseudocode}
128
129 %************************************************************************
130 %*                                                                      *
131 \subsection{Bind}
132 %*                                                                      *
133 %************************************************************************
134
135 \begin{code}
136 tcBindAndThen
137         :: (TcHsBinds s -> thing -> thing)                -- Combinator
138         -> RenamedBind                                    -- The Bind to typecheck
139         -> [RenamedSig]                                   -- ...and its signatures
140         -> TcM s (thing, LIE s, thing_ty)                 -- Thing to type check in
141                                                           -- augmented envt
142         -> TcM s (thing, LIE s, thing_ty)                 -- Results, incl the
143
144 tcBindAndThen combiner bind sigs do_next
145   = fixTc (\ ~(prag_info_fn, _) ->
146         -- This is the usual prag_info fix; the PragmaInfo field of an Id
147         -- is not inspected till ages later in the compiler, so there
148         -- should be no black-hole problems here.
149     
150     tcBindAndSigs binder_names bind 
151                   sigs prag_info_fn     `thenTc` \ (poly_binds, poly_lie, poly_ids) ->
152
153         -- Extend the environment to bind the new polymorphic Ids
154     tcExtendLocalValEnv binder_names poly_ids $
155
156         -- Build bindings and IdInfos corresponding to user pragmas
157     tcPragmaSigs sigs                   `thenTc` \ (prag_info_fn, prag_binds, prag_lie) ->
158
159         -- Now do whatever happens next, in the augmented envt
160     do_next                             `thenTc` \ (thing, thing_lie, thing_ty) ->
161
162         -- Create specialisations of functions bound here
163     bindInstsOfLocalFuns (prag_lie `plusLIE` thing_lie)
164                           poly_ids      `thenTc` \ (lie2, inst_mbinds) ->
165
166         -- All done
167     let
168         final_lie   = lie2 `plusLIE` poly_lie
169         final_binds = poly_binds `ThenBinds`
170                       SingleBind (NonRecBind inst_mbinds) `ThenBinds`
171                       prag_binds
172     in
173     returnTc (prag_info_fn, (combiner final_binds thing, final_lie, thing_ty))
174     )                                   `thenTc` \ (_, result) ->
175     returnTc result
176   where
177     binder_names = collectBinders bind
178
179
180 tcBindAndSigs binder_rn_names bind sigs prag_info_fn
181   = let
182         binder_names = map de_rn binder_rn_names
183         de_rn (RnName n) = n
184     in
185     recoverTc (
186         -- If typechecking the binds fails, then return with each
187         -- binder given type (forall a.a), to minimise subsequent
188         -- error messages
189         newTcTyVar mkBoxedTypeKind              `thenNF_Tc` \ alpha_tv ->
190         let
191           forall_a_a = mkForAllTy alpha_tv (mkTyVarTy alpha_tv)
192           poly_ids   = [ mkUserId name forall_a_a (prag_info_fn name)
193                        | name <- binder_names]
194         in
195         returnTc (EmptyBinds, emptyLIE, poly_ids)
196     ) $
197
198         -- Create a new identifier for each binder, with each being given
199         -- a type-variable type.
200     newMonoIds binder_rn_names kind (\ mono_ids ->
201             tcTySigs sigs               `thenTc` \ sig_info ->
202             tc_bind bind                `thenTc` \ (bind', lie) ->
203             returnTc (mono_ids, bind', lie, sig_info)
204     )
205             `thenTc` \ (mono_ids, bind', lie, sig_info) ->
206
207             -- Notice that genBinds gets the old (non-extended) environment
208     genBinds binder_names mono_ids bind' lie sig_info prag_info_fn
209   where
210     kind = case bind of
211                 NonRecBind _ -> mkTypeKind      -- Recursive, so no unboxed types
212                 RecBind _    -> mkBoxedTypeKind -- Non-recursive, so we permit unboxed types
213 \end{code}
214
215
216 ===========
217 \begin{code}
218 {-
219
220 data SigInfo
221   = SigInfo     RnName
222                 (TcIdBndr s)            -- Polymorpic version
223                 (TcIdBndr s)            -- Monomorphic verstion
224                 [TcType s] [TcIdOcc s]  -- Instance information for the monomorphic version
225
226
227
228         -- Deal with type signatures
229     tcTySigs sigs               `thenTc` \ sig_infos ->
230     let
231         sig_binders   = [binder      | SigInfo binder _ _ _ _  <- sig_infos]
232         poly_sigs     = [(name,poly) | SigInfo name poly _ _ _ <- sig_infos]
233         mono_sigs     = [(name,mono) | SigInfo name _ mono _ _ <- sig_infos]
234         nosig_binders = binders `minusList` sig_binders
235     in
236
237
238         -- Typecheck the binding group
239     tcExtendLocalEnv poly_sigs          (
240     newMonoIds nosig_binders kind       (\ nosig_local_ids ->
241             tcMonoBinds mono_sigs mono_binds    `thenTc` \ binds_w_lies ->
242             returnTc (nosig_local_ids, binds_w_lies)
243     ))                                  `thenTc` \ (nosig_local_ids, binds_w_lies) ->
244
245
246         -- Decide what to generalise over
247     getImplicitStuffToGen sig_ids binds_w_lies  
248                         `thenTc` \ (tyvars_not_to_gen, tyvars_to_gen, lie_to_gen) ->
249
250
251         *** CHECK FOR UNBOXED TYVARS HERE! ***
252
253
254
255         -- Make poly_ids for all the binders that don't have type signatures
256     let
257         tys_to_gen   = mkTyVarTys tyvars_to_gen
258         dicts_to_gen = map instToId (bagToList lie_to_gen)
259         dict_tys     = map tcIdType dicts_to_gen
260
261         mk_poly binder local_id = mkUserId (getName binder) ty noPragmaInfo
262                        where
263                           ty = mkForAllTys tyvars_to_gen $
264                                mkFunTys dict_tys $
265                                tcIdType local_id
266
267         more_sig_infos = [ SigInfo binder (mk_poly binder local_id) 
268                                    local_id tys_to_gen dicts_to_gen lie_to_gen
269                          | (binder, local_id) <- zipEqual "???" nosig_binders nosig_local_ids
270                          ]
271
272         all_sig_infos = sig_infos ++ more_sig_infos     -- Contains a "signature" for each binder
273     in
274
275
276         -- Now generalise the bindings
277     let
278         -- local_binds is a bunch of bindings of the form
279         --      f_mono = f_poly tyvars dicts
280         -- one for each binder, f, that lacks a type signature.
281         -- This bunch of bindings is put at the top of the RHS of every
282         -- binding in the group, so as to bind all the f_monos.
283                 
284         local_binds = [ (local_id, mkHsDictApp (mkHsTyApp (HsVar local_id) tys_to_gen) dicts_to_gen)
285                       | local_id <- nosig_local_ids
286                       ]
287
288         find_sig lid = head [ (pid, tvs, ds, lie) 
289                           | SigInfo _ pid lid' tvs ds lie, 
290                             lid==lid'
291                           ]
292
293       gen_bind (bind, lie)
294         = tcSimplifyWithExtraGlobals tyvars_not_to_gen tyvars_to_gen avail lie
295                                     `thenTc` \ (lie_free, dict_binds) ->
296           returnTc (AbsBind tyvars_to_gen_here
297                             dicts
298                             (zipEqual "gen_bind" local_ids poly_ids)
299                             (dict_binds ++ local_binds)
300                             bind,
301                     lie_free)
302         where
303           local_ids  = bindersOf bind
304           local_sigs = [sig | sig@(SigInfo _ _ local_id _ _) <- all_sig_infos,
305                               local_id `elem` local_ids
306                        ]
307
308           (tyvars_to_gen_here, dicts, avail) 
309                 = case (local_ids, sigs) of
310
311                     ([local_id], [SigInfo _ _ _ tyvars_to_gen dicts lie])
312                           -> (tyvars_to_gen, dicts, lie)
313
314                     other -> (tyvars_to_gen, dicts, avail)
315 \end{code}
316
317 @getImplicitStuffToGen@ decides what type variables
318 and LIE to generalise over.
319
320 For a "restricted group" -- see the monomorphism restriction
321 for a definition -- we bind no dictionaries, and
322 remove from tyvars_to_gen any constrained type variables
323
324 *Don't* simplify dicts at this point, because we aren't going
325 to generalise over these dicts.  By the time we do simplify them
326 we may well know more.  For example (this actually came up)
327         f :: Array Int Int
328         f x = array ... xs where xs = [1,2,3,4,5]
329 We don't want to generate lots of (fromInt Int 1), (fromInt Int 2)
330 stuff.  If we simplify only at the f-binding (not the xs-binding)
331 we'll know that the literals are all Ints, and we can just produce
332 Int literals!
333
334 Find all the type variables involved in overloading, the "constrained_tyvars"
335 These are the ones we *aren't* going to generalise.
336 We must be careful about doing this:
337  (a) If we fail to generalise a tyvar which is not actually
338         constrained, then it will never, ever get bound, and lands
339         up printed out in interface files!  Notorious example:
340                 instance Eq a => Eq (Foo a b) where ..
341         Here, b is not constrained, even though it looks as if it is.
342         Another, more common, example is when there's a Method inst in
343         the LIE, whose type might very well involve non-overloaded
344         type variables.
345  (b) On the other hand, we mustn't generalise tyvars which are constrained,
346         because we are going to pass on out the unmodified LIE, with those
347         tyvars in it.  They won't be in scope if we've generalised them.
348
349 So we are careful, and do a complete simplification just to find the
350 constrained tyvars. We don't use any of the results, except to
351 find which tyvars are constrained.
352
353 \begin{code}
354 getImplicitStuffToGen is_restricted sig_ids binds_w_lies
355   | isUnRestrictedGroup tysig_vars bind
356   = tcSimplify tyvars_to_gen lie        `thenTc` \ (_, _, dicts_to_gen) ->
357     returnNF_Tc (emptyTyVarSet, tyvars_to_gen, dicts_to_gen)
358
359   | otherwise
360   = tcSimplify tyvars_to_gen lie            `thenTc` \ (_, _, constrained_dicts) ->
361      let
362           -- ASSERT: dicts_sig is already zonked!
363           constrained_tyvars    = foldBag unionTyVarSets tyVarsOfInst emptyTyVarSet constrained_dicts
364           reduced_tyvars_to_gen = tyvars_to_gen `minusTyVarSet` constrained_tyvars
365      in
366      returnTc (constrained_tyvars, reduced_tyvars_to_gen, emptyLIE)
367
368   where
369     sig_vars   = [sig_var | (TySigInfo sig_var _ _ _ _) <- ty_sigs]
370
371     (tyvars_to_gen, lie) = foldBag (\(tv1,lie2) (tv2,lie2) -> (tv1 `unionTyVarSets` tv2,
372                                                                lie1 `plusLIE` lie2))
373                                     get
374                                     (emptyTyVarSet, emptyLIE)
375                                     binds_w_lies
376     get (bind, lie)
377       = case bindersOf bind of
378           [local_id] | local_id `in` sig_ids ->         -- A simple binding with
379                                                         -- a type signature
380                         (emptyTyVarSet, emptyLIE)
381
382           local_ids ->                                  -- Complex binding or no type sig
383                         (foldr (unionTyVarSets . tcIdType) emptyTyVarSet local_ids, 
384                          lie)
385 -}
386 \end{code}
387                            
388
389
390 \begin{code}
391 tc_bind :: RenamedBind -> TcM s (TcBind s, LIE s)
392
393 tc_bind (NonRecBind mono_binds)
394   = tcMonoBinds mono_binds      `thenTc` \ (mono_binds2, lie) ->
395     returnTc  (NonRecBind mono_binds2, lie)
396
397 tc_bind (RecBind mono_binds)
398   = tcMonoBinds mono_binds      `thenTc` \ (mono_binds2, lie) ->
399     returnTc  (RecBind mono_binds2, lie)
400 \end{code}
401
402 \begin{code}
403 tcMonoBinds :: RenamedMonoBinds -> TcM s (TcMonoBinds s, LIE s)
404
405 tcMonoBinds EmptyMonoBinds = returnTc (EmptyMonoBinds, emptyLIE)
406
407 tcMonoBinds (AndMonoBinds mb1 mb2)
408   = tcMonoBinds mb1             `thenTc` \ (mb1a, lie1) ->
409     tcMonoBinds mb2             `thenTc` \ (mb2a, lie2) ->
410     returnTc (AndMonoBinds mb1a mb2a, lie1 `plusLIE` lie2)
411
412 tcMonoBinds bind@(PatMonoBind pat grhss_and_binds locn)
413   = tcAddSrcLoc locn             $
414
415         -- LEFT HAND SIDE
416     tcPat pat                           `thenTc` \ (pat2, lie_pat, pat_ty) ->
417
418         -- BINDINGS AND GRHSS
419     tcGRHSsAndBinds grhss_and_binds     `thenTc` \ (grhss_and_binds2, lie, grhss_ty) ->
420
421         -- Unify the two sides
422     tcAddErrCtxt (patMonoBindsCtxt bind) $
423         unifyTauTy pat_ty grhss_ty                      `thenTc_`
424
425         -- RETURN
426     returnTc (PatMonoBind pat2 grhss_and_binds2 locn,
427               plusLIE lie_pat lie)
428
429 tcMonoBinds (FunMonoBind name inf matches locn)
430   = tcAddSrcLoc locn                            $
431     tcLookupLocalValueOK "tcMonoBinds" name     `thenNF_Tc` \ id ->
432     tcMatchesFun name (idType id) matches       `thenTc` \ (matches', lie) ->
433     returnTc (FunMonoBind (TcId id) inf matches' locn, lie)
434 \end{code}
435
436 %************************************************************************
437 %*                                                                      *
438 \subsection{Signatures}
439 %*                                                                      *
440 %************************************************************************
441
442 @tcSigs@ checks the signatures for validity, and returns a list of
443 {\em freshly-instantiated} signatures.  That is, the types are already
444 split up, and have fresh type variables installed.  All non-type-signature
445 "RenamedSigs" are ignored.
446
447 \begin{code}
448 tcTySigs :: [RenamedSig] -> TcM s [TcSigInfo s]
449
450 tcTySigs (Sig v ty _ src_loc : other_sigs)
451  = tcAddSrcLoc src_loc (
452         tcPolyType ty                   `thenTc` \ sigma_ty ->
453         tcInstSigType sigma_ty          `thenNF_Tc` \ sigma_ty' ->
454         let
455             (tyvars', theta', tau') = splitSigmaTy sigma_ty'
456         in
457
458         tcLookupLocalValueOK "tcSig1" v `thenNF_Tc` \ val ->
459         unifyTauTy (idType val) tau'    `thenTc_`
460
461         returnTc (TySigInfo val tyvars' theta' tau' src_loc)
462    )            `thenTc` \ sig_info1 ->
463
464    tcTySigs other_sigs  `thenTc` \ sig_infos ->
465    returnTc (sig_info1 : sig_infos)
466
467 tcTySigs (other : sigs) = tcTySigs sigs
468 tcTySigs []             = returnTc []
469 \end{code}
470
471
472 %************************************************************************
473 %*                                                                      *
474 \subsection{SPECIALIZE pragmas}
475 %*                                                                      *
476 %************************************************************************
477
478
479 @tcPragmaSigs@ munches up the "signatures" that arise through *user*
480 pragmas.  It is convenient for them to appear in the @[RenamedSig]@
481 part of a binding because then the same machinery can be used for
482 moving them into place as is done for type signatures.
483
484 \begin{code}
485 tcPragmaSigs :: [RenamedSig]                    -- The pragma signatures
486              -> TcM s (Name -> PragmaInfo,      -- Maps name to the appropriate PragmaInfo
487                        TcHsBinds s,
488                        LIE s)
489
490 tcPragmaSigs sigs = returnTc ( \name -> NoPragmaInfo, EmptyBinds, emptyLIE )
491
492 {- 
493 tcPragmaSigs sigs
494   = mapAndUnzip3Tc tcPragmaSig sigs     `thenTc` \ (names_w_id_infos, binds, lies) ->
495     let
496         name_to_info name = foldr ($) noIdInfo
497                                   [info_fn | (n,info_fn) <- names_w_id_infos, n==name]
498     in
499     returnTc (name_to_info,
500               foldr ThenBinds EmptyBinds binds,
501               foldr plusLIE emptyLIE lies)
502 \end{code}
503
504 Here are the easy cases for tcPragmaSigs
505
506 \begin{code}
507 tcPragmaSig (DeforestSig name loc)
508   = returnTc ((name, addInfo DoDeforest),EmptyBinds,emptyLIE)
509 tcPragmaSig (InlineSig name loc)
510   = returnTc ((name, addInfo_UF (iWantToBeINLINEd UnfoldAlways)), EmptyBinds, emptyLIE)
511 tcPragmaSig (MagicUnfoldingSig name string loc)
512   = returnTc ((name, addInfo_UF (mkMagicUnfolding string)), EmptyBinds, emptyLIE)
513 \end{code}
514
515 The interesting case is for SPECIALISE pragmas.  There are two forms.
516 Here's the first form:
517 \begin{verbatim}
518         f :: Ord a => [a] -> b -> b
519         {-# SPECIALIZE f :: [Int] -> b -> b #-}
520 \end{verbatim}
521
522 For this we generate:
523 \begin{verbatim}
524         f* = /\ b -> let d1 = ...
525                      in f Int b d1
526 \end{verbatim}
527
528 where f* is a SpecPragmaId.  The **sole** purpose of SpecPragmaIds is to
529 retain a right-hand-side that the simplifier will otherwise discard as
530 dead code... the simplifier has a flag that tells it not to discard
531 SpecPragmaId bindings.
532
533 In this case the f* retains a call-instance of the overloaded
534 function, f, (including appropriate dictionaries) so that the
535 specialiser will subsequently discover that there's a call of @f@ at
536 Int, and will create a specialisation for @f@.  After that, the
537 binding for @f*@ can be discarded.
538
539 The second form is this:
540 \begin{verbatim}
541         f :: Ord a => [a] -> b -> b
542         {-# SPECIALIZE f :: [Int] -> b -> b = g #-}
543 \end{verbatim}
544
545 Here @g@ is specified as a function that implements the specialised
546 version of @f@.  Suppose that g has type (a->b->b); that is, g's type
547 is more general than that required.  For this we generate
548 \begin{verbatim}
549         f@Int = /\b -> g Int b
550         f* = f@Int
551 \end{verbatim}
552
553 Here @f@@Int@ is a SpecId, the specialised version of @f@.  It inherits
554 f's export status etc.  @f*@ is a SpecPragmaId, as before, which just serves
555 to prevent @f@@Int@ from being discarded prematurely.  After specialisation,
556 if @f@@Int@ is going to be used at all it will be used explicitly, so the simplifier can
557 discard the f* binding.
558
559 Actually, there is really only point in giving a SPECIALISE pragma on exported things,
560 and the simplifer won't discard SpecIds for exporte things anyway, so maybe this is
561 a bit of overkill.
562
563 \begin{code}
564 tcPragmaSig (SpecSig name poly_ty maybe_spec_name src_loc)
565   = tcAddSrcLoc src_loc                         $
566     tcAddErrCtxt (valSpecSigCtxt name spec_ty)  $
567
568         -- Get and instantiate its alleged specialised type
569     tcPolyType poly_ty                          `thenTc` \ sig_sigma ->
570     tcInstSigType  sig_sigma                    `thenNF_Tc` \ sig_ty ->
571     let
572         (sig_tyvars, sig_theta, sig_tau) = splitSigmaTy sig_ty
573         origin = ValSpecOrigin name
574     in
575
576         -- Check that the SPECIALIZE pragma had an empty context
577     checkTc (null sig_theta)
578             (panic "SPECIALIZE non-empty context (ToDo: msg)") `thenTc_`
579
580         -- Get and instantiate the type of the id mentioned
581     tcLookupLocalValueOK "tcPragmaSig" name     `thenNF_Tc` \ main_id ->
582     tcInstSigType [] (idType main_id)           `thenNF_Tc` \ main_ty ->
583     let
584         (main_tyvars, main_rho) = splitForAllTy main_ty
585         (main_theta,main_tau)   = splitRhoTy main_rho
586         main_arg_tys            = mkTyVarTys main_tyvars
587     in
588
589         -- Check that the specialised type is indeed an instance of
590         -- the type of the main function.
591     unifyTauTy sig_tau main_tau         `thenTc_`
592     checkSigTyVars sig_tyvars sig_tau   `thenTc_`
593
594         -- Check that the type variables of the polymorphic function are
595         -- either left polymorphic, or instantiate to ground type.
596         -- Also check that the overloaded type variables are instantiated to
597         -- ground type; or equivalently that all dictionaries have ground type
598     mapTc zonkTcType main_arg_tys       `thenNF_Tc` \ main_arg_tys' ->
599     zonkTcThetaType main_theta          `thenNF_Tc` \ main_theta' ->
600     tcAddErrCtxt (specGroundnessCtxt main_arg_tys')
601               (checkTc (all isGroundOrTyVarTy main_arg_tys'))           `thenTc_`
602     tcAddErrCtxt (specContextGroundnessCtxt main_theta')
603               (checkTc (and [isGroundTy ty | (_,ty) <- theta']))        `thenTc_`
604
605         -- Build the SpecPragmaId; it is the thing that makes sure we
606         -- don't prematurely dead-code-eliminate the binding we are really interested in.
607     newSpecPragmaId name sig_ty         `thenNF_Tc` \ spec_pragma_id ->
608
609         -- Build a suitable binding; depending on whether we were given
610         -- a value (Maybe Name) to be used as the specialisation.
611     case using of
612       Nothing ->                -- No implementation function specified
613
614                 -- Make a Method inst for the occurrence of the overloaded function
615         newMethodWithGivenTy (OccurrenceOf name)
616                   (TcId main_id) main_arg_tys main_rho  `thenNF_Tc` \ (lie, meth_id) ->
617
618         let
619             pseudo_bind = VarMonoBind spec_pragma_id pseudo_rhs
620             pseudo_rhs  = mkHsTyLam sig_tyvars (HsVar (TcId meth_id))
621         in
622         returnTc (pseudo_bind, lie, \ info -> info)
623
624       Just spec_name ->         -- Use spec_name as the specialisation value ...
625
626                 -- Type check a simple occurrence of the specialised Id
627         tcId spec_name          `thenTc` \ (spec_body, spec_lie, spec_tau) ->
628
629                 -- Check that it has the correct type, and doesn't constrain the
630                 -- signature variables at all
631         unifyTauTy sig_tau spec_tau             `thenTc_`
632         checkSigTyVars sig_tyvars sig_tau       `thenTc_`
633
634             -- Make a local SpecId to bind to applied spec_id
635         newSpecId main_id main_arg_tys sig_ty   `thenNF_Tc` \ local_spec_id ->
636
637         let
638             spec_rhs   = mkHsTyLam sig_tyvars spec_body
639             spec_binds = VarMonoBind local_spec_id spec_rhs
640                            `AndMonoBinds`
641                          VarMonoBind spec_pragma_id (HsVar (TcId local_spec_id))
642             spec_info  = SpecInfo spec_tys (length main_theta) local_spec_id
643         in
644         returnTc ((name, addInfo spec_info), spec_binds, spec_lie)
645 -}
646 \end{code}
647
648
649 %************************************************************************
650 %*                                                                      *
651 \subsection[TcBinds-monomorphism]{The monomorphism restriction}
652 %*                                                                      *
653 %************************************************************************
654
655 Not exported:
656
657 \begin{code}
658 isUnRestrictedGroup :: [TcIdBndr s]             -- Signatures given for these
659                     -> TcBind s
660                     -> Bool
661
662 isUnRestrictedGroup sigs EmptyBind              = True
663 isUnRestrictedGroup sigs (NonRecBind monobinds) = isUnResMono sigs monobinds
664 isUnRestrictedGroup sigs (RecBind monobinds)    = isUnResMono sigs monobinds
665
666 is_elem v vs = isIn "isUnResMono" v vs
667
668 isUnResMono sigs (PatMonoBind (VarPat (TcId v)) _ _)    = v `is_elem` sigs
669 isUnResMono sigs (PatMonoBind other      _ _)           = False
670 isUnResMono sigs (VarMonoBind (TcId v) _)               = v `is_elem` sigs
671 isUnResMono sigs (FunMonoBind _ _ _ _)                  = True
672 isUnResMono sigs (AndMonoBinds mb1 mb2)                 = isUnResMono sigs mb1 &&
673                                                           isUnResMono sigs mb2
674 isUnResMono sigs EmptyMonoBinds                         = True
675 \end{code}
676
677
678 %************************************************************************
679 %*                                                                      *
680 \subsection[TcBinds-errors]{Error contexts and messages}
681 %*                                                                      *
682 %************************************************************************
683
684
685 \begin{code}
686 patMonoBindsCtxt bind sty
687   = ppHang (ppPStr SLIT("In a pattern binding:")) 4 (ppr sty bind)
688
689 --------------------------------------------
690 specContextGroundnessCtxt -- err_ctxt dicts sty
691   = panic "specContextGroundnessCtxt"
692 {-
693   = ppHang (
694         ppSep [ppBesides [ppStr "In the SPECIALIZE pragma for `", ppr sty name, ppStr "'"],
695                ppBesides [ppStr " specialised to the type `", ppr sty spec_ty,  ppStr "'"],
696                pp_spec_id sty,
697                ppStr "... not all overloaded type variables were instantiated",
698                ppStr "to ground types:"])
699       4 (ppAboves [ppCat [ppr sty c, ppr sty t]
700                   | (c,t) <- map getDictClassAndType dicts])
701   where
702     (name, spec_ty, locn, pp_spec_id)
703       = case err_ctxt of
704           ValSpecSigCtxt    n ty loc      -> (n, ty, loc, \ x -> ppNil)
705           ValSpecSpecIdCtxt n ty spec loc ->
706             (n, ty, loc,
707              \ sty -> ppBesides [ppStr "... type of explicit id `", ppr sty spec, ppStr "'"])
708 -}
709
710 -----------------------------------------------
711 specGroundnessCtxt
712   = panic "specGroundnessCtxt"
713
714
715 valSpecSigCtxt v ty sty
716   = ppHang (ppPStr SLIT("In a SPECIALIZE pragma for a value:"))
717          4 (ppSep [ppBeside (pprNonSym sty v) (ppPStr SLIT(" ::")),
718                   ppr sty ty])
719 \end{code}
720