2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1996
4 \section[TcSimplify]{TcSimplify}
7 #include "HsVersions.h"
10 tcSimplify, tcSimplifyAndCheck, tcSimplifyWithExtraGlobals,
11 tcSimplifyTop, tcSimplifyThetas, tcSimplifyCheckThetas, tcSimplifyRank2,
17 import HsSyn ( MonoBinds(..), HsExpr(..), InPat, OutPat, HsLit,
18 Match, HsBinds, Qualifier, PolyType, ArithSeqInfo,
19 GRHSsAndBinds, Stmt, Fake )
20 import TcHsSyn ( TcIdOcc(..), TcIdBndr(..), TcExpr(..), TcMonoBinds(..) )
22 import TcMonad hiding ( rnMtoTcM )
23 import Inst ( lookupInst, lookupSimpleInst,
24 tyVarsOfInst, isTyVarDict, isDict,
25 matchesInst, instToId, instBindingRequired,
26 instCanBeGeneralised, newDictsAtLoc,
28 Inst(..), LIE(..), zonkLIE, emptyLIE,
29 plusLIE, unitLIE, consLIE, InstOrigin(..),
31 import TcEnv ( tcGetGlobalTyVars )
32 import TcType ( TcType(..), TcTyVar(..), TcTyVarSet(..), TcMaybe, tcInstType )
33 import Unify ( unifyTauTy )
35 import Bag ( Bag, unitBag, listToBag, foldBag, filterBag, emptyBag, bagToList,
36 snocBag, consBag, unionBags, isEmptyBag )
37 import Class ( GenClass, Class(..), ClassInstEnv(..),
38 isNumericClass, isStandardClass, isCcallishClass,
39 isSuperClassOf, classSuperDictSelId, classInstEnv
42 import Maybes ( expectJust, firstJust, catMaybes, seqMaybe, maybeToBool, Maybe(..) )
43 import Outputable ( Outputable(..){-instance * []-} )
44 import PprStyle--ToDo:rm
45 import PprType ( GenType, GenTyVar, GenClass{-instance Outputable;ToDo:rm-} )
47 import SrcLoc ( mkUnknownSrcLoc )
49 import Type ( GenType, Type(..), TauType(..), mkTyVarTy, getTyVar, eqSimpleTy,
51 import TysWiredIn ( intTy )
52 import TyVar ( GenTyVar, GenTyVarSet(..),
53 elementOfTyVarSet, emptyTyVarSet, unionTyVarSets,
54 isEmptyTyVarSet, tyVarSetToList )
55 import Unique ( Unique )
59 %************************************************************************
61 \subsection[tcSimplify-main]{Main entry function}
63 %************************************************************************
65 * May modify the substitution to bind ambiguous type variables.
69 (1) If an inst constrains only ``global'' type variables, (or none),
70 return it as a ``global'' inst.
74 (2) Simplify it repeatedly (checking for (1) of course) until it is a dict
75 constraining only a type variable.
77 (3) If it constrains a ``local'' type variable, return it as a ``local'' inst.
78 Otherwise it must be ambiguous, so try to resolve the ambiguity.
82 tcSimpl :: Bool -- True <=> simplify const insts
83 -> TcTyVarSet s -- ``Global'' type variables
84 -> TcTyVarSet s -- ``Local'' type variables
85 -- ASSERT: both these tyvar sets are already zonked
86 -> LIE s -- Given; these constrain only local tyvars
88 -> TcM s (LIE s, -- Free
89 [(TcIdOcc s,TcExpr s)], -- Bindings
90 LIE s) -- Remaining wanteds; no dups
92 tcSimpl squash_consts global_tvs local_tvs givens wanteds
93 = -- ASSSERT: global_tvs and local_tvs are already zonked
94 -- Make sure the insts fixed points of the substitution
95 zonkLIE givens `thenNF_Tc` \ givens ->
96 zonkLIE wanteds `thenNF_Tc` \ wanteds ->
98 -- Deal with duplicates and type constructors
100 squash_consts (\tv -> tv `elementOfTyVarSet` global_tvs)
101 givens wanteds `thenTc` \ (globals, tycon_binds, locals_and_ambigs) ->
103 -- Now disambiguate if necessary
105 ambigs = filterBag is_ambiguous locals_and_ambigs
107 if not (isEmptyBag ambigs) then
108 -- Some ambiguous dictionaries. We now disambiguate them,
109 -- which binds the offending type variables to suitable types in the
110 -- substitution, and then we retry the whole process. This
111 -- time there won't be any ambiguous ones.
112 -- There's no need to back-substitute on global and local tvs,
113 -- because the ambiguous type variables can't be in either.
115 -- Why do we retry the whole process? Because binding a type variable
116 -- to a particular type might enable a short-cut simplification which
117 -- elimTyCons will have missed the first time.
119 disambiguateDicts ambigs `thenTc_`
120 tcSimpl squash_consts global_tvs local_tvs givens wanteds
123 -- No ambiguous dictionaries. Just bash on with the results
126 -- Check for non-generalisable insts
128 locals = locals_and_ambigs -- ambigs is empty
129 cant_generalise = filterBag (not . instCanBeGeneralised) locals
131 checkTc (isEmptyBag cant_generalise)
132 (genCantGenErr cant_generalise) `thenTc_`
135 -- Deal with superclass relationships
136 elimSCs givens locals `thenNF_Tc` \ (sc_binds, locals2) ->
139 returnTc (globals, bagToList (sc_binds `unionBags` tycon_binds), locals2)
141 is_ambiguous (Dict _ _ ty _ _)
142 = not (getTyVar "is_ambiguous" ty `elementOfTyVarSet` local_tvs)
145 The main wrapper is @tcSimplify@. It just calls @tcSimpl@, but with
146 the ``don't-squash-consts'' flag set depending on top-level ness. For
147 top level defns we *do* squash constants, so that they stay local to a
148 single defn. This makes things which are inlined more likely to be
149 exportable, because their constants are "inside". Later passes will
150 float them out if poss, after inlinings are sorted out.
154 :: TcTyVarSet s -- ``Local'' type variables
156 -> TcM s (LIE s, -- Free
157 [(TcIdOcc s,TcExpr s)], -- Bindings
158 LIE s) -- Remaining wanteds; no dups
160 tcSimplify local_tvs wanteds
161 = tcGetGlobalTyVars `thenNF_Tc` \ global_tvs ->
162 tcSimpl False global_tvs local_tvs emptyBag wanteds
165 @tcSimplifyWithExtraGlobals@ is just like @tcSimplify@ except that you get
166 to specify some extra global type variables that the simplifer will treat
167 as free in the environment.
170 tcSimplifyWithExtraGlobals
171 :: TcTyVarSet s -- Extra ``Global'' type variables
172 -> TcTyVarSet s -- ``Local'' type variables
174 -> TcM s (LIE s, -- Free
175 [(TcIdOcc s,TcExpr s)], -- Bindings
176 LIE s) -- Remaining wanteds; no dups
178 tcSimplifyWithExtraGlobals extra_global_tvs local_tvs wanteds
179 = tcGetGlobalTyVars `thenNF_Tc` \ global_tvs ->
181 (global_tvs `unionTyVarSets` extra_global_tvs)
182 local_tvs emptyBag wanteds
185 @tcSimplifyAndCheck@ is similar to the above, except that it checks
186 that there is an empty wanted-set at the end. It may still return
187 some of constant insts, which have to be resolved finally at the end.
191 :: TcTyVarSet s -- ``Local'' type variables; ASSERT is fixpoint
194 -> TcM s (LIE s, -- Free
195 [(TcIdOcc s,TcExpr s)]) -- Bindings
197 tcSimplifyAndCheck local_tvs givens wanteds
198 = tcGetGlobalTyVars `thenNF_Tc` \ global_tvs ->
199 tcSimpl False global_tvs local_tvs
200 givens wanteds `thenTc` \ (free_insts, binds, wanteds') ->
201 checkTc (isEmptyBag wanteds')
202 (reduceErr wanteds') `thenTc_`
203 returnTc (free_insts, binds)
206 @tcSimplifyRank2@ checks that the argument of a rank-2 polymorphic function
210 tcSimplifyRank2 :: TcTyVarSet s -- ``Local'' type variables; ASSERT is fixpoint
212 -> TcM s (LIE s, -- Free
213 [(TcIdOcc s,TcExpr s)]) -- Bindings
216 tcSimplifyRank2 local_tvs givens
217 = zonkLIE givens `thenNF_Tc` \ givens' ->
219 (\tv -> not (tv `elementOfTyVarSet` local_tvs))
220 -- This predicate claims that all
221 -- any non-local tyvars are global,
222 -- thereby postponing dealing with
223 -- ambiguity until the enclosing Gen
224 emptyLIE givens' `thenTc` \ (free, dict_binds, wanteds) ->
226 checkTc (isEmptyBag wanteds) (reduceErr wanteds) `thenTc_`
228 returnTc (free, bagToList dict_binds)
231 @tcSimplifyTop@ deals with constant @Insts@, using the standard simplification
232 mechansim with the extra flag to say ``beat out constant insts''.
235 tcSimplifyTop :: LIE s -> TcM s [(TcIdOcc s, TcExpr s)]
237 = tcSimpl True emptyTyVarSet emptyTyVarSet emptyBag dicts `thenTc` \ (_, binds, _) ->
241 %************************************************************************
243 \subsection[elimTyCons]{@elimTyCons@}
245 %************************************************************************
248 elimTyCons :: Bool -- True <=> Simplify const insts
249 -> (TcTyVar s -> Bool) -- Free tyvar predicate
252 -> TcM s (LIE s, -- Free
253 Bag (TcIdOcc s, TcExpr s), -- Bindings
254 LIE s -- Remaining wanteds; no dups;
255 -- dicts only (no Methods)
259 The bindings returned may mention any or all of ``givens'', so the
260 order in which the generated binds are put together is {\em tricky}.
261 Case~4 of @try@ is the general case to see.
263 When we do @eTC givens (wanted:wanteds)@ [some details omitted], we...
265 (1) first look up @wanted@; this gives us one binding to heave in:
268 (2) step (1) also gave us some @simpler_wanteds@; we simplify
269 these and get some (simpler-wanted-)bindings {\em that must be
270 in scope} for the @wanted=rhs@ binding above!
272 (3) we simplify the remaining @wanteds@ (recursive call), giving
273 us yet more bindings.
275 The final arrangement of the {\em non-recursive} bindings is
277 let <simpler-wanted-binds> in
279 let <yet-more-bindings> ...
282 elimTyCons squash_consts is_free_tv givens wanteds
283 = eTC givens (bagToList wanteds) `thenTc` \ (_, free, binds, irreds) ->
284 returnTc (free,binds,irreds)
286 -- eTC :: LIE s -> [Inst s]
287 -- -> TcM s (LIE s, LIE s, Bag (TcIdOcc s, TcExpr s), LIE s)
289 eTC givens [] = returnTc (givens, emptyBag, emptyBag, emptyBag)
291 eTC givens (wanted:wanteds)
292 -- Case 0: same as an existing inst
293 | maybeToBool maybe_equiv
294 = eTC givens wanteds `thenTc` \ (givens1, frees, binds, irreds) ->
296 -- Create a new binding iff it's needed
297 this = expectJust "eTC" maybe_equiv
298 new_binds | instBindingRequired wanted = (instToId wanted, HsVar (instToId this))
302 returnTc (givens1, frees, new_binds, irreds)
304 -- Case 1: constrains no type variables at all
305 -- In this case we have a quick go to see if it has an
306 -- instance which requires no inputs (ie a constant); if so we use
307 -- it; if not, we give up on the instance and just heave it out the
308 -- top in the free result
309 | isEmptyTyVarSet tvs_of_wanted
310 = simplify_it squash_consts {- If squash_consts is false,
311 simplify only if trival -}
312 givens wanted wanteds
314 -- Case 2: constrains free vars only, so fling it out the top in free_ids
315 | all is_free_tv (tyVarSetToList tvs_of_wanted)
316 = eTC (wanted `consBag` givens) wanteds `thenTc` \ (givens1, frees, binds, irreds) ->
317 returnTc (givens1, wanted `consBag` frees, binds, irreds)
319 -- Case 3: is a dict constraining only a tyvar,
320 -- so return it as part of the "wanteds" result
322 = eTC (wanted `consBag` givens) wanteds `thenTc` \ (givens1, frees, binds, irreds) ->
323 returnTc (givens1, frees, binds, wanted `consBag` irreds)
325 -- Case 4: is not a simple dict, so look up in instance environment
327 = simplify_it True {- Simplify even if not trivial -}
328 givens wanted wanteds
330 tvs_of_wanted = tyVarsOfInst wanted
332 -- Look for something in "givens" that matches "wanted"
333 Just the_equiv = maybe_equiv
334 maybe_equiv = foldBag seqMaybe try Nothing givens
335 try given | wanted `matchesInst` given = Just given
336 | otherwise = Nothing
339 simplify_it simplify_always givens wanted wanteds
340 -- Recover immediately on no-such-instance errors
341 = recoverTc (returnTc (wanted `consBag` givens, emptyLIE, emptyBag, emptyLIE))
342 (simplify_one simplify_always givens wanted)
343 `thenTc` \ (givens1, frees1, binds1, irreds1) ->
344 eTC givens1 wanteds `thenTc` \ (givens2, frees2, binds2, irreds2) ->
345 returnTc (givens2, frees1 `plusLIE` frees2,
346 binds1 `unionBags` binds2,
347 irreds1 `plusLIE` irreds2)
350 simplify_one simplify_always givens wanted
351 | not (instBindingRequired wanted)
352 = -- No binding required for this chap, so squash right away
353 lookupInst wanted `thenTc` \ (simpler_wanteds, _) ->
354 eTC givens simpler_wanteds `thenTc` \ (givens1, frees1, binds1, irreds1) ->
355 returnTc (wanted `consBag` givens1, frees1, binds1, irreds1)
358 = -- An binding is required for this inst
359 lookupInst wanted `thenTc` \ (simpler_wanteds, bind@(_,rhs)) ->
361 if (not_var rhs && not simplify_always) then
362 -- Ho ho! It isn't trivial to simplify "wanted",
363 -- because the rhs isn't a simple variable. Unless the flag
364 -- simplify_always is set, just give up now and
365 -- just fling it out the top.
366 returnTc (wanted `consLIE` givens, unitLIE wanted, emptyBag, emptyLIE)
368 -- Aha! Either it's easy, or simplify_always is True
369 -- so we must do it right here.
370 eTC givens simpler_wanteds `thenTc` \ (givens1, frees1, binds1, irreds1) ->
371 returnTc (wanted `consLIE` givens1, frees1,
372 binds1 `snocBag` bind,
375 not_var :: TcExpr s -> Bool
376 not_var (HsVar _) = False
381 %************************************************************************
383 \subsection[elimSCs]{@elimSCs@}
385 %************************************************************************
388 elimSCs :: LIE s -- Given; no dups
389 -> LIE s -- Wanted; no dups; all dictionaries, all
390 -- constraining just a type variable
391 -> NF_TcM s (Bag (TcIdOcc s,TcExpr s), -- Bindings
392 LIE s) -- Minimal wanted set
394 elimSCs givens wanteds
395 = -- Sort the wanteds so that subclasses occur before superclasses
397 (filterBag isDict givens) -- Filter out non-dictionaries
400 elimSCs_help :: LIE s -- Given; no dups
401 -> [Inst s] -- Wanted; no dups;
402 -> NF_TcM s (Bag (TcIdOcc s, TcExpr s), -- Bindings
403 LIE s) -- Minimal wanted set
405 elimSCs_help given [] = returnNF_Tc (emptyBag, emptyLIE)
407 elimSCs_help givens (wanted:wanteds)
408 = trySC givens wanted `thenNF_Tc` \ (givens1, binds1, irreds1) ->
409 elimSCs_help givens1 wanteds `thenNF_Tc` \ (binds2, irreds2) ->
410 returnNF_Tc (binds1 `unionBags` binds2, irreds1 `plusLIE` irreds2)
413 trySC :: LIE s -- Givens
415 -> NF_TcM s (LIE s, -- New givens,
416 Bag (TcIdOcc s,TcExpr s), -- Bindings
417 LIE s) -- Irreducible wanted set
419 trySC givens wanted@(Dict _ wanted_class wanted_ty wanted_orig loc)
420 | not (maybeToBool maybe_best_subclass_chain)
421 = -- No superclass relationship
422 returnNF_Tc (givens, emptyBag, unitLIE wanted)
425 = -- There's a subclass relationship with a "given"
426 -- Build intermediate dictionaries
428 theta = [ (clas, wanted_ty) | clas <- reverse classes ]
429 -- The reverse is because the list comes back in the "wrong" order I think
431 newDictsAtLoc wanted_orig loc theta `thenNF_Tc` \ (intermediates, _) ->
433 -- Create bindings for the wanted dictionary and the intermediates.
434 -- Later binds may depend on earlier ones, so each new binding is pushed
435 -- on the front of the accumulating parameter list of bindings
437 mk_bind (dict,clas) dict_sub@(Dict _ dict_sub_class ty _ _)
438 = ((dict_sub, dict_sub_class),
439 (instToId dict, DictApp (TyApp (HsVar (RealId (classSuperDictSelId dict_sub_class
442 [instToId dict_sub]))
443 (_, new_binds) = mapAccumR mk_bind (wanted,wanted_class) (given : intermediates)
445 returnNF_Tc (wanted `consLIE` givens `plusLIE` listToBag intermediates,
450 maybe_best_subclass_chain = foldBag choose_best find_subclass_chain Nothing givens
451 Just (given, classes, _) = maybe_best_subclass_chain
453 choose_best c1@(Just (_,_,n1)) c2@(Just (_,_,n2)) | n1 <= n2 = c1
455 choose_best Nothing c2 = c2
456 choose_best c1 Nothing = c1
458 find_subclass_chain given@(Dict _ given_class given_ty _ _)
459 | wanted_ty `eqSimpleTy` given_ty
460 = case (wanted_class `isSuperClassOf` given_class) of
462 Just classes -> Just (given,
468 | otherwise = Nothing
471 sortSC :: LIE s -- Expected to be all dicts (no MethodIds), all of
472 -- which constrain type variables
473 -> [Inst s] -- Sorted with subclasses before superclasses
475 sortSC dicts = sortLt lt (bagToList dicts)
477 (Dict _ c1 ty1 _ _) `lt` (Dict _ c2 ty2 _ _)
478 = if ty1 `eqSimpleTy` ty2 then
479 maybeToBool (c2 `isSuperClassOf` c1)
481 -- Order is immaterial, I think...
486 %************************************************************************
488 \subsection[simple]{@Simple@ versions}
490 %************************************************************************
492 Much simpler versions when there are no bindings to make!
494 @tcSimplifyThetas@ simplifies class-type constraints formed by
495 @deriving@ declarations and when specialising instances. We are
496 only interested in the simplified bunch of class/type constraints.
499 tcSimplifyThetas :: (Class -> ClassInstEnv) -- How to find the ClassInstEnv
500 -> [(Class, TauType)] -- Given
501 -> [(Class, TauType)] -- Wanted
502 -> TcM s [(Class, TauType)]
505 tcSimplifyThetas inst_mapper given wanted
506 = elimTyConsSimple inst_mapper wanted `thenTc` \ wanted1 ->
507 returnTc (elimSCsSimple given wanted1)
510 @tcSimplifyCheckThetas@ just checks class-type constraints, essentially;
511 used with \tr{default} declarations. We are only interested in
512 whether it worked or not.
515 tcSimplifyCheckThetas :: [(Class, TauType)] -- Simplify this to nothing at all
518 tcSimplifyCheckThetas theta
519 = elimTyConsSimple classInstEnv theta `thenTc` \ theta1 ->
520 ASSERT( null theta1 )
526 elimTyConsSimple :: (Class -> ClassInstEnv)
528 -> TcM s [(Class,Type)]
529 elimTyConsSimple inst_mapper theta
532 elim [] = returnTc []
533 elim ((clas,ty):rest) = elim_one clas ty `thenTc` \ r1 ->
534 elim rest `thenTc` \ r2 ->
538 = case getTyVar_maybe ty of
540 Just tv -> returnTc [(clas,ty)]
542 otherwise -> recoverTc (returnTc []) $
543 lookupSimpleInst (inst_mapper clas) clas ty `thenTc` \ theta ->
546 elimSCsSimple :: [(Class,Type)] -- Given
547 -> [(Class,Type)] -- Wanted
548 -> [(Class,Type)] -- Subset of wanted; no dups, no subclass relnships
550 elimSCsSimple givens [] = []
551 elimSCsSimple givens (c_t@(clas,ty) : rest)
552 | any (`subsumes` c_t) givens ||
553 any (`subsumes` c_t) rest -- (clas,ty) is old hat
554 = elimSCsSimple givens rest
555 | otherwise -- (clas,ty) is new
556 = c_t : elimSCsSimple (c_t : givens) rest
558 rest' = elimSCsSimple rest
559 (c1,t1) `subsumes` (c2,t2) = t1 `eqSimpleTy` t2 &&
560 (c1 == c2 || maybeToBool (c2 `isSuperClassOf` c1))
561 -- We deal with duplicates here ^^^^^^^^
562 -- It's a simple place to do it, although it's done in elimTyCons in the
563 -- full-blown version of the simpifier.
566 %************************************************************************
568 \subsection[binds-for-local-funs]{@bindInstsOfLocalFuns@}
570 %************************************************************************
572 When doing a binding group, we may have @Insts@ of local functions.
573 For example, we might have...
575 let f x = x + 1 -- orig local function (overloaded)
576 f.1 = f Int -- two instances of f
581 The point is: we must drop the bindings for @f.1@ and @f.2@ here,
582 where @f@ is in scope; those @Insts@ must certainly not be passed
583 upwards towards the top-level. If the @Insts@ were binding-ified up
584 there, they would have unresolvable references to @f@.
586 We pass in an @init_lie@ of @Insts@ and a list of locally-bound @Ids@.
587 For each method @Inst@ in the @init_lie@ that mentions one of the
588 @Ids@, we create a binding. We return the remaining @Insts@ (in an
589 @LIE@), as well as the @HsBinds@ generated.
592 bindInstsOfLocalFuns :: LIE s -> [TcIdBndr s] -> TcM s (LIE s, TcMonoBinds s)
594 bindInstsOfLocalFuns init_lie local_ids
595 = foldrTc bind_inst (emptyBag, EmptyMonoBinds) (bagToList init_lie)
597 bind_inst inst@(Method uniq (TcId id) tys rho orig loc) (insts, binds)
598 | id `is_elem` local_ids
599 = lookupInst inst `thenTc` \ (dict_insts, (id,rhs)) ->
600 returnTc (listToBag dict_insts `plusLIE` insts,
601 VarMonoBind id rhs `AndMonoBinds` binds)
603 bind_inst some_other_inst (insts, binds)
604 -- Either not a method, or a method instance for an id not in local_ids
605 = returnTc (some_other_inst `consBag` insts, binds)
607 is_elem = isIn "bindInstsOfLocalFuns"
611 %************************************************************************
613 \section[Disambig]{Disambiguation of overloading}
615 %************************************************************************
618 If a dictionary constrains a type variable which is
621 not mentioned in the environment
623 and not mentioned in the type of the expression
625 then it is ambiguous. No further information will arise to instantiate
626 the type variable; nor will it be generalised and turned into an extra
627 parameter to a function.
629 It is an error for this to occur, except that Haskell provided for
630 certain rules to be applied in the special case of numeric types.
635 at least one of its classes is a numeric class, and
637 all of its classes are numeric or standard
639 then the type variable can be defaulted to the first type in the
640 default-type list which is an instance of all the offending classes.
642 So here is the function which does the work. It takes the ambiguous
643 dictionaries and either resolves them (producing bindings) or
644 complains. It works by splitting the dictionary list by type
645 variable, and using @disambigOne@ to do the real business.
647 IMPORTANT: @disambiguate@ assumes that its argument dictionaries
648 constrain only a simple type variable.
651 type SimpleDictInfo s = (Inst s, Class, TcTyVar s)
653 disambiguateDicts :: LIE s -> TcM s ()
655 disambiguateDicts insts
656 = mapTc disambigOne inst_infos `thenTc` \ binds_lists ->
659 inst_infos = equivClasses cmp_tyvars (map mk_inst_info (bagToList insts))
660 (_,_,tv1) `cmp_tyvars` (_,_,tv2) = tv1 `cmp` tv2
662 mk_inst_info dict@(Dict _ clas ty _ _)
663 = (dict, clas, getTyVar "disambiguateDicts" ty)
666 @disambigOne@ assumes that its arguments dictionaries constrain all
667 the same type variable.
669 ADR Comment 20/6/94: I've changed the @CReturnable@ case to default to
670 @()@ instead of @Int@. I reckon this is the Right Thing to do since
671 the most common use of defaulting is code like:
673 _ccall_ foo `seqPrimIO` bar
675 Since we're not using the result of @foo@, the result if (presumably)
679 disambigOne :: [SimpleDictInfo s] -> TcM s ()
681 disambigOne dict_infos
682 | not (isStandardNumericDefaultable classes)
683 = failTc (ambigErr dicts) -- no default
685 | otherwise -- isStandardNumericDefaultable dict_infos
686 = -- THE DICTS OBEY THE DEFAULTABLE CONSTRAINT
687 -- SO, TRY DEFAULT TYPES IN ORDER
689 -- Failure here is caused by there being no type in the
690 -- default list which can satisfy all the ambiguous classes.
691 -- For example, if Real a is reqd, but the only type in the
692 -- default list is Int.
693 tcGetDefaultTys `thenNF_Tc` \ default_tys ->
695 try_default [] -- No defaults work, so fail
696 = failTc (defaultErr dicts default_tys)
698 try_default (default_ty : default_tys)
699 = tryTc (try_default default_tys) $ -- If default_ty fails, we try
700 -- default_tys instead
701 tcSimplifyCheckThetas thetas `thenTc` \ _ ->
704 thetas = classes `zip` repeat default_ty
706 -- See if any default works, and if so bind the type variable to it
707 try_default default_tys `thenTc` \ chosen_default_ty ->
708 tcInstType [] chosen_default_ty `thenNF_Tc` \ chosen_default_tc_ty -> -- Tiresome!
709 unifyTauTy (mkTyVarTy tyvar) chosen_default_tc_ty
712 (_,_,tyvar) = head dict_infos -- Should be non-empty
713 dicts = [dict | (dict,_,_) <- dict_infos]
714 classes = [clas | (_,clas,_) <- dict_infos]
718 @isStandardNumericDefaultable@ sees whether the dicts have the
719 property required for defaulting; namely at least one is numeric, and
720 all are standard; or all are CcallIsh.
723 isStandardNumericDefaultable :: [Class] -> Bool
725 isStandardNumericDefaultable classes
726 = --pprTrace "isStdNumeric:\n" (ppAboves [ppCat (map (ppr PprDebug) classes), ppCat (map (ppr PprDebug . isNumericClass) classes), ppCat (map (ppr PprDebug . isStandardClass) classes), ppCat (map (ppr PprDebug . isCcallishClass) classes)]) $
727 (any isNumericClass classes && all isStandardClass classes)
728 || (all isCcallishClass classes)
735 ToDo: for these error messages, should we note the location as coming
736 from the insts, or just whatever seems to be around in the monad just
740 genCantGenErr insts sty -- Can't generalise these Insts
741 = ppHang (ppStr "Cannot generalise these overloadings (in a _ccall_):")
742 4 (ppAboves (map (ppr sty) (bagToList insts)))
747 = ppAboves (map (pprInst sty "Ambiguous overloading") insts)
750 @reduceErr@ complains if we can't express required dictionaries in
751 terms of the signature.
755 = ppAboves (map (pprInst sty "Context required by inferred type, but missing on a type signature")
760 defaultErr dicts defaulting_tys sty
761 = ppHang (ppStr "Ambiguously-overloaded types could not be resolved:")
763 ppHang (ppStr "Conflicting:")
764 4 (ppInterleave ppSemi (map (pprInst sty ""{-???-}) dicts)),
765 ppHang (ppStr "Defaulting types :")
766 4 (ppr sty defaulting_tys),
767 ppStr "([Int, Double] is the default list of defaulting types.)" ])