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