2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1995
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, Qual, PolyType, ArithSeqInfo,
19 GRHSsAndBinds, Stmt, Fake )
20 import TcHsSyn ( TcIdOcc(..), TcIdBndr(..), TcExpr(..), TcMonoBinds(..) )
22 import TcMonad hiding ( rnMtoTcM )
23 import Inst ( lookupInst, tyVarsOfInst, isTyVarDict, isDict, matchesInst,
24 instToId, instBindingRequired, instCanBeGeneralised, newDictsAtLoc,
25 Inst(..), LIE(..), zonkLIE, emptyLIE, plusLIE, unitLIE, consLIE,
26 InstOrigin(..), OverloadedLit )
27 import TcEnv ( tcGetGlobalTyVars )
28 import TcType ( TcType(..), TcTyVar(..), TcTyVarSet(..), TcMaybe, tcInstType )
29 import Unify ( unifyTauTy )
31 import Bag ( Bag, unitBag, listToBag, foldBag, filterBag, emptyBag, bagToList,
32 snocBag, consBag, unionBags, isEmptyBag )
33 import Class ( isNumericClass, isStandardClass, isCcallishClass,
34 isSuperClassOf, classSuperDictSelId
37 import Maybes ( expectJust, firstJust, catMaybes, seqMaybe, maybeToBool, Maybe(..) )
38 import Outputable ( Outputable(..){-instance * []-} )
39 import PprStyle--ToDo:rm
40 import PprType ( GenType, GenTyVar, GenClass{-instance Outputable;ToDo:rm-} )
42 import SrcLoc ( mkUnknownSrcLoc )
44 import Type ( GenType, Type(..), TauType(..), mkTyVarTy, getTyVar, eqSimpleTy )
45 import TysWiredIn ( intTy )
46 import TyVar ( GenTyVar, GenTyVarSet(..),
47 elementOfTyVarSet, emptyTyVarSet, unionTyVarSets,
48 isEmptyTyVarSet, tyVarSetToList )
49 import Unique ( Unique )
53 %************************************************************************
55 \subsection[tcSimplify-main]{Main entry function}
57 %************************************************************************
59 * May modify the substitution to bind ambiguous type variables.
63 (1) If an inst constrains only ``global'' type variables, (or none),
64 return it as a ``global'' inst.
68 (2) Simplify it repeatedly (checking for (1) of course) until it is a dict
69 constraining only a type variable.
71 (3) If it constrains a ``local'' type variable, return it as a ``local'' inst.
72 Otherwise it must be ambiguous, so try to resolve the ambiguity.
76 tcSimpl :: Bool -- True <=> simplify const insts
77 -> TcTyVarSet s -- ``Global'' type variables
78 -> TcTyVarSet s -- ``Local'' type variables
79 -- ASSERT: both these tyvar sets are already zonked
80 -> LIE s -- Given; these constrain only local tyvars
82 -> TcM s (LIE s, -- Free
83 [(TcIdOcc s,TcExpr s)], -- Bindings
84 LIE s) -- Remaining wanteds; no dups
86 tcSimpl squash_consts global_tvs local_tvs givens wanteds
87 = -- ASSSERT: global_tvs and local_tvs are already zonked
88 -- Make sure the insts fixed points of the substitution
89 zonkLIE givens `thenNF_Tc` \ givens ->
90 zonkLIE wanteds `thenNF_Tc` \ wanteds ->
92 -- Deal with duplicates and type constructors
94 squash_consts (\tv -> tv `elementOfTyVarSet` global_tvs)
95 givens wanteds `thenTc` \ (globals, tycon_binds, locals_and_ambigs) ->
97 -- Now disambiguate if necessary
99 ambigs = filterBag is_ambiguous locals_and_ambigs
101 if not (isEmptyBag ambigs) then
102 -- Some ambiguous dictionaries. We now disambiguate them,
103 -- which binds the offending type variables to suitable types in the
104 -- substitution, and then we retry the whole process. This
105 -- time there won't be any ambiguous ones.
106 -- There's no need to back-substitute on global and local tvs,
107 -- because the ambiguous type variables can't be in either.
109 -- Why do we retry the whole process? Because binding a type variable
110 -- to a particular type might enable a short-cut simplification which
111 -- elimTyCons will have missed the first time.
113 disambiguateDicts ambigs `thenTc_`
114 tcSimpl squash_consts global_tvs local_tvs givens wanteds
117 -- No ambiguous dictionaries. Just bash on with the results
120 -- Check for non-generalisable insts
122 locals = locals_and_ambigs -- ambigs is empty
123 cant_generalise = filterBag (not . instCanBeGeneralised) locals
125 checkTc (isEmptyBag cant_generalise)
126 (genCantGenErr cant_generalise) `thenTc_`
129 -- Deal with superclass relationships
130 elimSCs givens locals `thenNF_Tc` \ (sc_binds, locals2) ->
133 returnTc (globals, bagToList (sc_binds `unionBags` tycon_binds), locals2)
135 is_ambiguous (Dict _ _ ty _ _)
136 = not (getTyVar "is_ambiguous" ty `elementOfTyVarSet` local_tvs)
139 The main wrapper is @tcSimplify@. It just calls @tcSimpl@, but with
140 the ``don't-squash-consts'' flag set depending on top-level ness. For
141 top level defns we *do* squash constants, so that they stay local to a
142 single defn. This makes things which are inlined more likely to be
143 exportable, because their constants are "inside". Later passes will
144 float them out if poss, after inlinings are sorted out.
148 :: TcTyVarSet s -- ``Local'' type variables
150 -> TcM s (LIE s, -- Free
151 [(TcIdOcc s,TcExpr s)], -- Bindings
152 LIE s) -- Remaining wanteds; no dups
154 tcSimplify local_tvs wanteds
155 = tcGetGlobalTyVars `thenNF_Tc` \ global_tvs ->
156 tcSimpl False global_tvs local_tvs emptyBag wanteds
159 @tcSimplifyWithExtraGlobals@ is just like @tcSimplify@ except that you get
160 to specify some extra global type variables that the simplifer will treat
161 as free in the environment.
164 tcSimplifyWithExtraGlobals
165 :: TcTyVarSet s -- Extra ``Global'' type variables
166 -> TcTyVarSet s -- ``Local'' type variables
168 -> TcM s (LIE s, -- Free
169 [(TcIdOcc s,TcExpr s)], -- Bindings
170 LIE s) -- Remaining wanteds; no dups
172 tcSimplifyWithExtraGlobals extra_global_tvs local_tvs wanteds
173 = tcGetGlobalTyVars `thenNF_Tc` \ global_tvs ->
175 (global_tvs `unionTyVarSets` extra_global_tvs)
176 local_tvs emptyBag wanteds
179 @tcSimplifyAndCheck@ is similar to the above, except that it checks
180 that there is an empty wanted-set at the end. It may still return
181 some of constant insts, which have to be resolved finally at the end.
185 :: TcTyVarSet s -- ``Local'' type variables; ASSERT is fixpoint
188 -> TcM s (LIE s, -- Free
189 [(TcIdOcc s,TcExpr s)]) -- Bindings
191 tcSimplifyAndCheck local_tvs givens wanteds
192 = tcGetGlobalTyVars `thenNF_Tc` \ global_tvs ->
193 tcSimpl False global_tvs local_tvs
194 givens wanteds `thenTc` \ (free_insts, binds, wanteds') ->
195 checkTc (isEmptyBag wanteds')
196 (reduceErr wanteds') `thenTc_`
197 returnTc (free_insts, binds)
200 @tcSimplifyRank2@ checks that the argument of a rank-2 polymorphic function
204 tcSimplifyRank2 :: TcTyVarSet s -- ``Local'' type variables; ASSERT is fixpoint
206 -> TcM s (LIE s, -- Free
207 [(TcIdOcc s,TcExpr s)]) -- Bindings
210 tcSimplifyRank2 local_tvs givens
211 = zonkLIE givens `thenNF_Tc` \ givens' ->
213 (\tv -> not (tv `elementOfTyVarSet` local_tvs))
214 -- This predicate claims that all
215 -- any non-local tyvars are global,
216 -- thereby postponing dealing with
217 -- ambiguity until the enclosing Gen
218 emptyLIE givens' `thenTc` \ (free, dict_binds, wanteds) ->
220 checkTc (isEmptyBag wanteds) (reduceErr wanteds) `thenTc_`
222 returnTc (free, bagToList dict_binds)
225 @tcSimplifyTop@ deals with constant @Insts@, using the standard simplification
226 mechansim with the extra flag to say ``beat out constant insts''.
229 tcSimplifyTop :: LIE s -> TcM s [(TcIdOcc s, TcExpr s)]
231 = tcGetGlobalTyVars `thenNF_Tc` \ global_tvs ->
232 tcSimpl True emptyTyVarSet emptyTyVarSet emptyBag dicts `thenTc` \ (_, binds, _) ->
236 @tcSimplifyThetas@ simplifies class-type constraints formed by
237 @deriving@ declarations and when specialising instances. We are
238 only interested in the simplified bunch of class/type constraints.
241 tcSimplifyThetas :: (Class -> TauType -> InstOrigin s) -- Creates an origin for the dummy dicts
242 -> [(Class, TauType)] -- Simplify this
243 -> TcM s [(Class, TauType)] -- Result
245 tcSimplifyThetas = panic "tcSimplifyThetas"
248 tcSimplifyThetas mk_inst_origin theta
250 dicts = listToBag (map mk_dummy_dict theta)
252 -- Do the business (this is just the heart of "tcSimpl")
253 elimTyCons True (\tv -> False) emptyLIE dicts `thenTc` \ (_, _, dicts2) ->
255 -- Deal with superclass relationships
256 elimSCs [] dicts2 `thenNF_Tc` \ (_, dicts3) ->
258 returnTc (map unmk_dummy_dict (bagToList dicts3))
260 mk_dummy_dict (clas, ty) = Dict uniq clas ty (mk_inst_origin clas ty) mkUnknownSrcLoc
261 uniq = panic "tcSimplifyThetas:uniq"
263 unmk_dummy_dict (Dict _ clas ty _ _) = (clas, ty)
267 @tcSimplifyCheckThetas@ just checks class-type constraints, essentially;
268 used with \tr{default} declarations. We are only interested in
269 whether it worked or not.
272 tcSimplifyCheckThetas :: InstOrigin s -- context; for error msg
273 -> [(Class, TauType)] -- Simplify this
276 tcSimplifyCheckThetas x y = _trace "tcSimplifyCheckThetas: does nothing" $
280 tcSimplifyCheckThetas origin theta
282 dicts = map mk_dummy_dict theta
284 -- Do the business (this is just the heart of "tcSimpl")
285 elimTyCons True (\tv -> False) emptyLIE dicts `thenTc` \ _ ->
289 mk_dummy_dict (clas, ty)
290 = Dict uniq clas ty origin mkUnknownSrcLoc
292 uniq = panic "tcSimplifyCheckThetas:uniq"
297 %************************************************************************
299 \subsection[elimTyCons]{@elimTyCons@}
301 %************************************************************************
304 elimTyCons :: Bool -- True <=> Simplify const insts
305 -> (TcTyVar s -> Bool) -- Free tyvar predicate
308 -> TcM s (LIE s, -- Free
309 Bag (TcIdOcc s, TcExpr s), -- Bindings
310 LIE s -- Remaining wanteds; no dups;
311 -- dicts only (no Methods)
315 The bindings returned may mention any or all of ``givens'', so the
316 order in which the generated binds are put together is {\em tricky}.
317 Case~4 of @try@ is the general case to see.
319 When we do @eTC givens (wanted:wanteds)@ [some details omitted], we...
321 (1) first look up @wanted@; this gives us one binding to heave in:
324 (2) step (1) also gave us some @simpler_wanteds@; we simplify
325 these and get some (simpler-wanted-)bindings {\em that must be
326 in scope} for the @wanted=rhs@ binding above!
328 (3) we simplify the remaining @wanteds@ (recursive call), giving
329 us yet more bindings.
331 The final arrangement of the {\em non-recursive} bindings is
333 let <simpler-wanted-binds> in
335 let <yet-more-bindings> ...
338 elimTyCons squash_consts is_free_tv givens wanteds
339 = eTC givens (bagToList wanteds) `thenTc` \ (_, free, binds, irreds) ->
340 returnTc (free,binds,irreds)
342 -- eTC :: LIE s -> [Inst s]
343 -- -> TcM s (LIE s, LIE s, Bag (TcIdOcc s, TcExpr s), LIE s)
345 eTC givens [] = returnTc (givens, emptyBag, emptyBag, emptyBag)
347 eTC givens (wanted:wanteds)
348 -- Case 0: same as an existing inst
349 | maybeToBool maybe_equiv
350 = eTC givens wanteds `thenTc` \ (givens1, frees, binds, irreds) ->
352 -- Create a new binding iff it's needed
353 this = expectJust "eTC" maybe_equiv
354 new_binds | instBindingRequired wanted = (instToId wanted, HsVar (instToId this))
358 returnTc (givens1, frees, new_binds, irreds)
360 -- Case 1: constrains no type variables at all
361 -- In this case we have a quick go to see if it has an
362 -- instance which requires no inputs (ie a constant); if so we use
363 -- it; if not, we give up on the instance and just heave it out the
364 -- top in the free result
365 | isEmptyTyVarSet tvs_of_wanted
366 = simplify_it squash_consts {- If squash_consts is false,
367 simplify only if trival -}
368 givens wanted wanteds
370 -- Case 2: constrains free vars only, so fling it out the top in free_ids
371 | all is_free_tv (tyVarSetToList tvs_of_wanted)
372 = eTC (wanted `consBag` givens) wanteds `thenTc` \ (givens1, frees, binds, irreds) ->
373 returnTc (givens1, wanted `consBag` frees, binds, irreds)
375 -- Case 3: is a dict constraining only a tyvar,
376 -- so return it as part of the "wanteds" result
378 = eTC (wanted `consBag` givens) wanteds `thenTc` \ (givens1, frees, binds, irreds) ->
379 returnTc (givens1, frees, binds, wanted `consBag` irreds)
381 -- Case 4: is not a simple dict, so look up in instance environment
383 = simplify_it True {- Simplify even if not trivial -}
384 givens wanted wanteds
386 tvs_of_wanted = tyVarsOfInst wanted
388 -- Look for something in "givens" that matches "wanted"
389 Just the_equiv = maybe_equiv
390 maybe_equiv = foldBag seqMaybe try Nothing givens
391 try given | wanted `matchesInst` given = Just given
392 | otherwise = Nothing
395 simplify_it simplify_always givens wanted wanteds
396 -- Recover immediately on no-such-instance errors
397 = recoverTc (returnTc (wanted `consBag` givens, emptyLIE, emptyBag, emptyLIE))
398 (simplify_one simplify_always givens wanted)
399 `thenTc` \ (givens1, frees1, binds1, irreds1) ->
400 eTC givens1 wanteds `thenTc` \ (givens2, frees2, binds2, irreds2) ->
401 returnTc (givens2, frees1 `plusLIE` frees2,
402 binds1 `unionBags` binds2,
403 irreds1 `plusLIE` irreds2)
406 simplify_one simplify_always givens wanted
407 | not (instBindingRequired wanted)
408 = -- No binding required for this chap, so squash right away
409 lookupInst wanted `thenTc` \ (simpler_wanteds, _) ->
410 eTC givens simpler_wanteds `thenTc` \ (givens1, frees1, binds1, irreds1) ->
411 returnTc (wanted `consBag` givens1, frees1, binds1, irreds1)
414 = -- An binding is required for this inst
415 lookupInst wanted `thenTc` \ (simpler_wanteds, bind@(_,rhs)) ->
417 if (not_var rhs && not simplify_always) then
418 -- Ho ho! It isn't trivial to simplify "wanted",
419 -- because the rhs isn't a simple variable. Unless the flag
420 -- simplify_always is set, just give up now and
421 -- just fling it out the top.
422 returnTc (wanted `consLIE` givens, unitLIE wanted, emptyBag, emptyLIE)
424 -- Aha! Either it's easy, or simplify_always is True
425 -- so we must do it right here.
426 eTC givens simpler_wanteds `thenTc` \ (givens1, frees1, binds1, irreds1) ->
427 returnTc (wanted `consLIE` givens1, frees1,
428 binds1 `snocBag` bind,
431 not_var :: TcExpr s -> Bool
432 not_var (HsVar _) = False
437 %************************************************************************
439 \subsection[elimSCs]{@elimSCs@}
441 %************************************************************************
444 elimSCs :: LIE s -- Given; no dups
445 -> LIE s -- Wanted; no dups; all dictionaries, all
446 -- constraining just a type variable
447 -> NF_TcM s (Bag (TcIdOcc s,TcExpr s), -- Bindings
448 LIE s) -- Minimal wanted set
450 elimSCs givens wanteds
451 = -- Sort the wanteds so that subclasses occur before superclasses
453 (filterBag isDict givens) -- Filter out non-dictionaries
456 elimSCs_help :: LIE s -- Given; no dups
457 -> [Inst s] -- Wanted; no dups;
458 -> NF_TcM s (Bag (TcIdOcc s, TcExpr s), -- Bindings
459 LIE s) -- Minimal wanted set
461 elimSCs_help given [] = returnNF_Tc (emptyBag, emptyLIE)
463 elimSCs_help givens (wanted:wanteds)
464 = trySC givens wanted `thenNF_Tc` \ (givens1, binds1, irreds1) ->
465 elimSCs_help givens1 wanteds `thenNF_Tc` \ (binds2, irreds2) ->
466 returnNF_Tc (binds1 `unionBags` binds2, irreds1 `plusLIE` irreds2)
469 trySC :: LIE s -- Givens
471 -> NF_TcM s (LIE s, -- New givens,
472 Bag (TcIdOcc s,TcExpr s), -- Bindings
473 LIE s) -- Irreducible wanted set
475 trySC givens wanted@(Dict _ wanted_class wanted_ty wanted_orig loc)
476 | not (maybeToBool maybe_best_subclass_chain)
477 = -- No superclass relationship
478 returnNF_Tc (givens, emptyBag, unitLIE wanted)
481 = -- There's a subclass relationship with a "given"
482 -- Build intermediate dictionaries
484 theta = [ (clas, wanted_ty) | clas <- reverse classes ]
485 -- The reverse is because the list comes back in the "wrong" order I think
487 newDictsAtLoc wanted_orig loc theta `thenNF_Tc` \ (intermediates, _) ->
489 -- Create bindings for the wanted dictionary and the intermediates.
490 -- Later binds may depend on earlier ones, so each new binding is pushed
491 -- on the front of the accumulating parameter list of bindings
493 mk_bind (dict,clas) dict_sub@(Dict _ dict_sub_class ty _ _)
494 = ((dict_sub, dict_sub_class),
495 (instToId dict, DictApp (TyApp (HsVar (RealId (classSuperDictSelId dict_sub_class
498 [instToId dict_sub]))
499 (_, new_binds) = mapAccumR mk_bind (wanted,wanted_class) (given : intermediates)
501 returnNF_Tc (wanted `consLIE` givens `plusLIE` listToBag intermediates,
506 maybe_best_subclass_chain = foldBag choose_best find_subclass_chain Nothing givens
507 Just (given, classes, _) = maybe_best_subclass_chain
509 choose_best c1@(Just (_,_,n1)) c2@(Just (_,_,n2)) | n1 <= n2 = c1
511 choose_best Nothing c2 = c2
512 choose_best c1 Nothing = c1
514 find_subclass_chain given@(Dict _ given_class given_ty _ _)
515 | wanted_ty `eqSimpleTy` given_ty
516 = case (wanted_class `isSuperClassOf` given_class) of
518 Just classes -> Just (given,
524 | otherwise = Nothing
527 sortSC :: LIE s -- Expected to be all dicts (no MethodIds), all of
528 -- which constrain type variables
529 -> [Inst s] -- Sorted with subclasses before superclasses
531 sortSC dicts = sortLt lt (bagToList dicts)
533 (Dict _ c1 ty1 _ _) `lt` (Dict _ c2 ty2 _ _)
534 = if ty1 `eqSimpleTy` ty2 then
535 maybeToBool (c2 `isSuperClassOf` c1)
537 -- order is immaterial, I think...
542 %************************************************************************
544 \subsection[binds-for-local-funs]{@bindInstsOfLocalFuns@}
546 %************************************************************************
548 When doing a binding group, we may have @Insts@ of local functions.
549 For example, we might have...
551 let f x = x + 1 -- orig local function (overloaded)
552 f.1 = f Int -- two instances of f
557 The point is: we must drop the bindings for @f.1@ and @f.2@ here,
558 where @f@ is in scope; those @Insts@ must certainly not be passed
559 upwards towards the top-level. If the @Insts@ were binding-ified up
560 there, they would have unresolvable references to @f@.
562 We pass in an @init_lie@ of @Insts@ and a list of locally-bound @Ids@.
563 For each method @Inst@ in the @init_lie@ that mentions one of the
564 @Ids@, we create a binding. We return the remaining @Insts@ (in an
565 @LIE@), as well as the @HsBinds@ generated.
568 bindInstsOfLocalFuns :: LIE s -> [TcIdBndr s] -> TcM s (LIE s, TcMonoBinds s)
570 bindInstsOfLocalFuns init_lie local_ids
571 = foldrTc bind_inst (emptyBag, EmptyMonoBinds) (bagToList init_lie)
573 bind_inst inst@(Method uniq (TcId id) tys rho orig loc) (insts, binds)
574 | id `is_elem` local_ids
575 = lookupInst inst `thenTc` \ (dict_insts, (id,rhs)) ->
576 returnTc (listToBag dict_insts `plusLIE` insts,
577 VarMonoBind id rhs `AndMonoBinds` binds)
579 bind_inst some_other_inst (insts, binds)
580 -- Either not a method, or a method instance for an id not in local_ids
581 = returnTc (some_other_inst `consBag` insts, binds)
583 is_elem = isIn "bindInstsOfLocalFuns"
587 %************************************************************************
589 \section[Disambig]{Disambiguation of overloading}
591 %************************************************************************
594 If a dictionary constrains a type variable which is
597 not mentioned in the environment
599 and not mentioned in the type of the expression
601 then it is ambiguous. No further information will arise to instantiate
602 the type variable; nor will it be generalised and turned into an extra
603 parameter to a function.
605 It is an error for this to occur, except that Haskell provided for
606 certain rules to be applied in the special case of numeric types.
611 at least one of its classes is a numeric class, and
613 all of its classes are numeric or standard
615 then the type variable can be defaulted to the first type in the
616 default-type list which is an instance of all the offending classes.
618 So here is the function which does the work. It takes the ambiguous
619 dictionaries and either resolves them (producing bindings) or
620 complains. It works by splitting the dictionary list by type
621 variable, and using @disambigOne@ to do the real business.
623 IMPORTANT: @disambiguate@ assumes that its argument dictionaries
624 constrain only a simple type variable.
627 type SimpleDictInfo s = (Inst s, Class, TcTyVar s)
629 disambiguateDicts :: LIE s -> TcM s ()
631 disambiguateDicts insts
632 = mapTc disambigOne inst_infos `thenTc` \ binds_lists ->
635 inst_infos = equivClasses cmp_tyvars (map mk_inst_info (bagToList insts))
636 (_,_,tv1) `cmp_tyvars` (_,_,tv2) = tv1 `cmp` tv2
638 mk_inst_info dict@(Dict _ clas ty _ _)
639 = (dict, clas, getTyVar "disambiguateDicts" ty)
642 @disambigOne@ assumes that its arguments dictionaries constrain all
643 the same type variable.
645 ADR Comment 20/6/94: I've changed the @CReturnable@ case to default to
646 @()@ instead of @Int@. I reckon this is the Right Thing to do since
647 the most common use of defaulting is code like:
649 _ccall_ foo `seqPrimIO` bar
651 Since we're not using the result of @foo@, the result if (presumably)
653 WDP Comment: no such thing as voidTy; so not quite in yet (94/07).
657 disambigOne :: [SimpleDictInfo s] -> TcM s ()
659 disambigOne dict_infos
660 | not (isStandardNumericDefaultable classes)
661 = failTc (ambigErr dicts) -- no default
663 | otherwise -- isStandardNumericDefaultable dict_infos
664 = -- THE DICTS OBEY THE DEFAULTABLE CONSTRAINT
665 -- SO, TRY DEFAULT TYPES IN ORDER
667 -- Failure here is caused by there being no type in the
668 -- default list which can satisfy all the ambiguous classes.
669 -- For example, if Real a is reqd, but the only type in the
670 -- default list is Int.
671 tcGetDefaultTys `thenNF_Tc` \ default_tys ->
673 try_default [] -- No defaults work, so fail
674 = failTc (defaultErr dicts default_tys)
676 try_default (default_ty : default_tys)
677 = tryTc (try_default default_tys) $ -- If default_ty fails, we try
678 -- default_tys instead
679 tcSimplifyCheckThetas DefaultDeclOrigin thetas `thenTc` \ _ ->
682 thetas = classes `zip` repeat default_ty
684 -- See if any default works, and if so bind the type variable to it
685 try_default default_tys `thenTc` \ chosen_default_ty ->
686 tcInstType [] chosen_default_ty `thenNF_Tc` \ chosen_default_tc_ty -> -- Tiresome!
687 unifyTauTy (mkTyVarTy tyvar) chosen_default_tc_ty
690 (_,_,tyvar) = head dict_infos -- Should be non-empty
691 dicts = [dict | (dict,_,_) <- dict_infos]
692 classes = [clas | (_,clas,_) <- dict_infos]
696 @isStandardNumericDefaultable@ sees whether the dicts have the
697 property required for defaulting; namely at least one is numeric, and
698 all are standard; or all are CcallIsh.
701 isStandardNumericDefaultable :: [Class] -> Bool
703 isStandardNumericDefaultable classes
704 = --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)]) $
705 (any isNumericClass classes && all isStandardClass classes)
706 || (all isCcallishClass classes)
713 ToDo: for these error messages, should we note the location as coming
714 from the insts, or just whatever seems to be around in the monad just
718 genCantGenErr insts sty -- Can't generalise these Insts
719 = ppHang (ppStr "Cannot generalise these overloadings (in a _ccall_):")
720 4 (ppAboves (map (ppr sty) (bagToList insts)))
725 = ppHang (ppStr "Ambiguous overloading")
726 4 (ppAboves (map (ppr sty) insts))
729 @reduceErr@ complains if we can't express required dictionaries in
730 terms of the signature.
734 = ppHang (ppStr "Type signature lacks context required by inferred type")
735 4 (ppHang (ppStr "Context reqd: ")
736 4 (ppAboves (map (ppr sty) (bagToList insts)))
741 defaultErr dicts defaulting_tys sty
742 = ppHang (ppStr "Ambiguously-overloaded types could not be resolved:")
744 ppHang (ppStr "Conflicting:")
745 4 (ppInterleave ppSemi (map (ppr sty) dicts)),
746 ppHang (ppStr "Defaulting types :")
747 4 (ppr sty defaulting_tys),
748 ppStr "([Int, Double] is the default list of defaulting types.)" ])