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