2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1995
4 \section[TcSimplify]{TcSimplify}
7 #include "HsVersions.h"
10 tcSimplify, tcSimplifyAndCheck,
11 tcSimplifyTop, tcSimplifyThetas, tcSimplifyCheckThetas, tcSimplifyRank2,
15 IMPORT_Trace -- ToDo: rm (debugging)
19 import TcMonad -- typechecking monadic machinery
20 import TcMonadFns ( newDicts, applyTcSubstAndExpectTyVars )
21 import AbsSyn -- the stuff being typechecked
23 import AbsUniType ( isSuperClassOf, getTyVar, eqTyVar, ltTyVar,
24 instantiateThetaTy, isFunType, getUniDataTyCon,
25 getSuperDictSelId, InstTyEnv(..)
26 IF_ATTACK_PRAGMAS(COMMA isTyVarTy COMMA pprUniType)
27 IF_ATTACK_PRAGMAS(COMMA assocMaybe)
29 import UniType ( UniType(..) ) -- ******* CHEATING ************
30 import Disambig ( disambiguateDicts )
31 import Errors ( reduceErr, genCantGenErr, Error(..) )
32 import Id ( mkInstId )
33 import Inst ( extractTyVarsFromInst, isTyVarDict, matchesInst,
34 instBindingRequired, instCanBeGeneralised,
35 Inst(..), -- We import the CONCRETE type, because
36 -- TcSimplify is allowed to see the rep
38 InstOrigin, OverloadedLit, InstTemplate
42 import ListSetOps ( minusList )
43 import Maybes ( catMaybes, maybeToBool, Maybe(..) )
48 %************************************************************************
50 \subsection[tcSimplify-main]{Main entry function}
52 %************************************************************************
54 * May modify the substitution to bind ambiguous type variables.
58 (1) If an inst constrains only ``global'' type variables, (or none),
59 return it as a ``global'' inst.
63 (2) Simplify it repeatedly (checking for (1) of course) until it is a dict
64 constraining only a type variable.
66 (3) If it constrains a ``local'' type variable, return it as a ``local'' inst.
67 Otherwise it must be ambiguous, so try to resolve the ambiguity.
71 tcSimpl :: Bool -- True <=> Don't simplify const insts
72 -> [TyVar] -- ``Global'' type variables
73 -> [TyVar] -- ``Local'' type variables
74 -> [Inst] -- Given; these constrain only local tyvars
76 -> TcM ([Inst], -- Free
77 [(Inst,TypecheckedExpr)],-- Bindings
78 [Inst]) -- Remaining wanteds; no dups
80 tcSimpl dont_squash_consts global_tvs local_tvs givens wanteds
82 -- Make sure the insts and type variables are fixed points of the substitution
83 applyTcSubstAndExpectTyVars global_tvs `thenNF_Tc` \ global_tvs ->
84 applyTcSubstAndExpectTyVars local_tvs `thenNF_Tc` \ local_tvs ->
85 applyTcSubstToInsts givens `thenNF_Tc` \ givens ->
86 applyTcSubstToInsts wanteds `thenNF_Tc` \ wanteds ->
88 is_elem1 = isIn "tcSimpl1"
89 is_elem2 = isIn "tcSimpl2"
91 -- Deal with duplicates and type constructors
93 dont_squash_consts (\tv -> tv `is_elem1` global_tvs)
94 givens wanteds `thenTc` \ (globals, tycon_binds, locals_and_ambigs) ->
96 -- Now disambiguate if necessary
98 (ambigs, unambigs) = partition (is_ambiguous local_tvs) locals_and_ambigs
99 (locals, cant_generalise) = partition instCanBeGeneralised unambigs
101 checkTc (not (null cant_generalise)) (genCantGenErr cant_generalise) `thenTc_`
103 (if (null ambigs) then
105 -- No ambiguous dictionaries. Just bash on with the results
107 returnTc (globals, tycon_binds, locals_and_ambigs)
111 -- Some ambiguous dictionaries. We now disambiguate them,
112 -- which binds the offending type variables to suitable types in the
113 -- substitution, and then we retry the whole process. This
114 -- time there won't be any ambiguous ones.
115 -- There's no need to back-substitute on global and local tvs,
116 -- because the ambiguous type variables can't be in either.
118 -- Why do we retry the whole process? Because binding a type variable
119 -- to a particular type might enable a short-cut simplification which
120 -- elimTyCons will have missed the first time.
122 disambiguateDicts ambigs `thenTc_`
123 applyTcSubstToInsts givens `thenNF_Tc` \ givens ->
124 applyTcSubstToInsts wanteds `thenNF_Tc` \ wanteds ->
126 dont_squash_consts (\tv -> tv `is_elem2` global_tvs)
129 ) {- End of the "if" -} `thenTc` \ (globals, tycon_binds, locals) ->
131 -- Deal with superclass relationships
132 elimSCs givens locals `thenNF_Tc` \ (sc_binds, locals2) ->
135 returnTc (globals, sc_binds ++ tycon_binds, locals2)
137 is_ambiguous local_tvs (Dict _ _ ty _)
138 = getTyVar "is_ambiguous" ty `not_elem` local_tvs
140 not_elem = isn'tIn "is_ambiguous"
143 The main wrapper is @tcSimplify@. It just calls @tcSimpl@, but with
144 the ``don't-squash-consts'' flag set depending on top-level ness. For
145 top level defns we *do* squash constants, so that they stay local to a
146 single defn. This makes things which are inlined more likely to be
147 exportable, because their constants are "inside". Later passes will
148 float them out if poss, after inlinings are sorted out.
152 :: Bool -- True <=> top level
153 -> [TyVar] -- ``Global'' type variables
154 -> [TyVar] -- ``Local'' type variables
156 -> TcM ([Inst], -- Free
157 [(Inst, TypecheckedExpr)],-- Bindings
158 [Inst]) -- Remaining wanteds; no dups
160 tcSimplify top_level global_tvs local_tvs wanteds
161 = tcSimpl (not top_level) global_tvs local_tvs [] wanteds
164 @tcSimplifyAndCheck@ is similar to the above, except that it checks
165 that there is an empty wanted-set at the end.
167 It may still return some of constant insts, which have
168 to be resolved finally at the end.
172 :: Bool -- True <=> top level
173 -> [TyVar] -- ``Global'' type variables
174 -> [TyVar] -- ``Local'' type variables
177 -> UnifyErrContext -- Context info for error
178 -> TcM ([Inst], -- Free
179 [(Inst, TypecheckedExpr)]) -- Bindings
181 tcSimplifyAndCheck top_level global_tvs local_tvs givens wanteds err_ctxt
182 = tcSimpl (not top_level) global_tvs local_tvs givens wanteds
183 `thenTc` \ (free_insts, binds, wanteds') ->
184 checkTc (not (null wanteds')) (reduceErr wanteds' err_ctxt)
186 returnTc (free_insts, binds)
189 @tcSimplifyRank2@ checks that the argument of a rank-2 polymorphic function
193 tcSimplifyRank2 :: [TyVar] -- ``Local'' type variables; guaranteed fixpoint of subst
196 -> TcM ([Inst], -- Free
197 [(Inst, TypecheckedExpr)]) -- Bindings
199 tcSimplifyRank2 local_tvs givens err_ctxt
200 = applyTcSubstToInsts givens `thenNF_Tc` \ givens' ->
202 (\tv -> not (tv `is_elem` local_tvs))
203 -- This predicate claims that all
204 -- any non-local tyvars are global,
205 -- thereby postponing dealing with
206 -- ambiguity until the enclosing Gen
207 [] givens' `thenTc` \ (free, dict_binds, wanteds) ->
209 checkTc (not (null wanteds)) (reduceErr wanteds err_ctxt) `thenTc_`
211 returnTc (free, dict_binds)
213 is_elem = isIn "tcSimplifyRank2"
216 @tcSimplifyTop@ deals with constant @Insts@, using the standard simplification
217 mechansim with the extra flag to say ``beat out constant insts''.
220 tcSimplifyTop :: [Inst] -> TcM [(Inst, TypecheckedExpr)]
222 = tcSimpl False [] [] [] dicts `thenTc` \ (_, binds, _) ->
226 @tcSimplifyThetas@ simplifies class-type constraints formed by
227 @deriving@ declarations and when specialising instances. We are
228 only interested in the simplified bunch of class/type constraints.
231 tcSimplifyThetas :: (Class -> TauType -> InstOrigin) -- Creates an origin for the dummy dicts
232 -> [(Class, TauType)] -- Simplify this
233 -> TcM [(Class, TauType)] -- Result
235 tcSimplifyThetas mk_inst_origin theta
237 dicts = map mk_dummy_dict theta
239 -- Do the business (this is just the heart of "tcSimpl")
240 elimTyCons False (\tv -> False) [] dicts `thenTc` \ (_, _, dicts2) ->
242 -- Deal with superclass relationships
243 elimSCs [] dicts2 `thenNF_Tc` \ (_, dicts3) ->
245 returnTc (map unmk_dummy_dict dicts3)
247 mk_dummy_dict (clas, ty)
248 = Dict uniq clas ty (mk_inst_origin clas ty)
250 uniq = panic "tcSimplifyThetas:uniq"
252 unmk_dummy_dict (Dict _ clas ty _) = (clas, ty)
255 @tcSimplifyCheckThetas@ just checks class-type constraints, essentially;
256 used with \tr{default} declarations. We are only interested in
257 whether it worked or not.
260 tcSimplifyCheckThetas :: InstOrigin -- context; for error msg
261 -> [(Class, TauType)] -- Simplify this
264 tcSimplifyCheckThetas origin theta
266 dicts = map mk_dummy_dict theta
268 -- Do the business (this is just the heart of "tcSimpl")
269 elimTyCons False (\tv -> False) [] dicts `thenTc` \ _ ->
273 mk_dummy_dict (clas, ty)
274 = Dict uniq clas ty origin
276 uniq = panic "tcSimplifyCheckThetas:uniq"
280 %************************************************************************
282 \subsection[elimTyCons]{@elimTyCons@}
284 %************************************************************************
287 elimTyCons :: Bool -- True <=> Don't simplify const insts
288 -> (TyVar -> Bool) -- Free tyvar predicate
291 -> TcM ([Inst], -- Free
292 [(Inst, TypecheckedExpr)], -- Bindings
293 [Inst] -- Remaining wanteds; no dups;
294 -- dicts only (no Methods)
298 The bindings returned may mention any or all of ``givens'', so the
299 order in which the generated binds are put together is {\em tricky}.
300 Case~4 of @try@ is the general case to see.
302 When we do @eTC givens (wanted:wanteds)@ [some details omitted], we...
304 (1) first look up @wanted@; this gives us one binding to heave in:
307 (2) step (1) also gave us some @simpler_wanteds@; we simplify
308 these and get some (simpler-wanted-)bindings {\em that must be
309 in scope} for the @wanted=rhs@ binding above!
311 (3) we simplify the remaining @wanteds@ (recursive call), giving
312 us yet more bindings.
314 The final arrangement of the {\em non-recursive} bindings is
316 let <simpler-wanted-binds> in
318 let <yet-more-bindings> ...
321 elimTyCons dont_squash_consts is_free_tv givens wanteds
324 eTC :: [Inst] -> [Inst]
325 -> TcM ([Inst], [(Inst, TypecheckedExpr)], [Inst])
327 eTC _ [] = returnTc ([], [], [])
329 eTC givens (wanted:wanteds) = try givens wanted wanteds
330 (extractTyVarsFromInst wanted)
331 (find_equiv givens wanted)
332 -- find_equiv looks in "givens" for an inst equivalent to "wanted"
333 -- This is used only in Case 2 below; it's like a guard which also
336 try :: [Inst] -> Inst -> [Inst] -> [TyVar] -> (Maybe Inst)
337 -> TcM ([Inst], [(Inst, TypecheckedExpr)], [Inst])
339 -- Case 0: same as existing dict, so build a simple binding
340 try givens wanted wanteds tvs_of_wanted (Just this)
341 = eTC givens wanteds `thenTc` \ (frees, binds, wanteds') ->
343 -- Create a new binding iff it's needed
344 new_binds | instBindingRequired wanted = (wanted, Var (mkInstId this)):binds
347 returnTc (frees, new_binds, wanteds')
349 -- Case 1: constrains no type variables at all
350 -- In this case we have a quick go to see if it has an
351 -- instance which requires no inputs (ie a constant); if so we use
352 -- it; if not, we give up on the instance and just heave it out the
353 -- top in the free result
354 try givens wanted wanteds tvs_of_wanted _ | null tvs_of_wanted
355 = simplify_it dont_squash_consts {- If dont_squash_consts is true,
356 simplify only if trival -}
357 givens wanted wanteds
359 -- Case 2: constrains free vars only, so fling it out the top in free_ids
360 try givens wanted wanteds tvs_of_wanted _
361 | all is_free_tv tvs_of_wanted
362 = eTC (wanted:givens) wanteds `thenTc` \ (frees, binds, wanteds') ->
363 returnTc (wanted:frees, binds, wanteds')
365 -- Case 3: is a dict constraining only a tyvar,
366 -- so return it as part of the "wanteds" result
367 try givens wanted wanteds tvs_of_wanted _
369 = eTC (wanted:givens) wanteds `thenTc` \ (frees, binds, wanteds') ->
370 returnTc (frees, binds, wanted:wanteds')
372 -- Case 4: is not a simple dict, so look up in instance environment
373 try givens wanted wanteds tvs_of_wanted _
374 = simplify_it False {- Simplify even if not trivial -}
375 givens wanted wanteds
377 simplify_it only_if_trivial givens wanted wanteds
378 = if not (instBindingRequired wanted) then
379 -- No binding required for this chap, so squash right away
380 lookupNoBindInst_Tc wanted `thenTc` \ simpler_wanteds ->
382 eTC givens simpler_wanteds `thenTc` \ (frees1, binds1, wanteds1) ->
384 new_givens = [new_given | (new_given,rhs) <- binds1]
385 -- Typically binds1 is empty
387 eTC givens wanteds `thenTc` \ (frees2, binds2, wanteds2) ->
389 returnTc (frees1 ++ frees2,
391 wanteds1 ++ wanteds2)
393 else -- An binding is required for this inst
394 lookupInst_Tc wanted `thenTc` \ (rhs, simpler_wanteds) ->
396 if (only_if_trivial && not_var rhs) then
397 -- Ho ho! It isn't trivial to simplify "wanted",
398 -- because the rhs isn't a simple variable. The flag
399 -- dont_squash_consts tells us to give up now and
400 -- just fling it out the top.
401 eTC (wanted:givens) wanteds `thenTc` \ (frees, binds, wanteds') ->
402 returnTc (wanted:frees, binds, wanteds')
404 -- Aha! Either it's easy, or dont_squash_consts is
405 -- False, so we must do it right here.
407 eTC givens simpler_wanteds `thenTc` \ (frees1, binds1, wanteds1) ->
409 new_givens = [new_given | (new_given,rhs) <- binds1]
411 eTC (new_givens ++ [wanted] ++ wanteds1 ++ givens) wanteds
412 `thenTc` \ (frees2, binds2, wanteds2) ->
413 returnTc (frees1 ++ frees2,
414 binds1 ++ [(wanted, rhs)] ++ binds2,
415 wanteds1 ++ wanteds2)
417 not_var :: TypecheckedExpr -> Bool
418 not_var (Var _) = False
421 find_equiv :: [Inst] -> Inst -> Maybe Inst
422 -- Look through the argument list for an inst which is
423 -- equivalent to the second arg.
425 find_equiv [] wanted = Nothing
426 find_equiv (given:givens) wanted
427 | wanted `matchesInst` given = Just given
428 | otherwise = find_equiv givens wanted
432 %************************************************************************
434 \subsection[elimSCs]{@elimSCs@}
436 %************************************************************************
439 elimSCs :: [Inst] -- Given; no dups
440 -> [Inst] -- Wanted; no dups; all dictionaries, all
441 -- constraining just a type variable
442 -> NF_TcM ([(Inst,TypecheckedExpr)], -- Bindings
443 [Inst]) -- Minimal wanted set
445 elimSCs givens wanteds
446 = -- Sort the wanteds so that subclasses occur before superclasses
448 [dict | dict@(Dict _ _ _ _) <- givens] -- Filter out non-dictionaries
451 elimSCs_help :: [Inst] -- Given; no dups
452 -> [Inst] -- Wanted; no dups;
453 -> NF_TcM ([(Inst,TypecheckedExpr)],-- Bindings
454 [Inst]) -- Minimal wanted set
456 elimSCs_help given [] = returnNF_Tc ([], [])
458 elimSCs_help givens (wanted@(Dict _ wanted_class wanted_ty wanted_orig):wanteds)
459 = case (trySC givens wanted_class wanted_ty) of
461 Nothing -> -- No superclass relnship found
462 elimSCs_help (wanted:givens) wanteds `thenNF_Tc` \ (binds, wanteds') ->
463 returnNF_Tc (binds, wanted:wanteds')
465 Just (given, classes) -> -- Aha! There's a superclass relnship
467 -- Build intermediate dictionaries
469 theta = [ (clas, wanted_ty) | clas <- classes ]
471 newDicts wanted_orig theta `thenNF_Tc` \ intermediates ->
473 -- Deal with the recursive call
474 elimSCs_help (wanted : (intermediates ++ givens)) wanteds
475 `thenNF_Tc` \ (binds, wanteds') ->
477 -- Create bindings for the wanted dictionary and the intermediates.
478 -- Later binds may depend on earlier ones, so each new binding is pushed
479 -- on the front of the accumulating parameter list of bindings
481 new_binds = mk_binds wanted wanted_class (intermediates ++ [given]) []
483 returnNF_Tc (new_binds ++ binds, wanteds')
485 mk_binds :: Inst -- Define this
486 -> Class -- ...whose class is this
487 -> [Inst] -- In terms of this sub-class chain
488 -> [(Inst, TypecheckedExpr)] -- Push the binding on front of these
489 -> [(Inst, TypecheckedExpr)]
491 mk_binds dict clas [] binds_so_far = binds_so_far
492 mk_binds dict clas (dict_sub@(Dict _ dict_sub_class ty _):dicts_sub) binds_so_far
493 = mk_binds dict_sub dict_sub_class dicts_sub (new_bind:binds_so_far)
495 new_bind = (dict, DictApp (TyApp (Var (getSuperDictSelId dict_sub_class clas))
500 trySC :: [Inst] -- Givens
501 -> Class -> UniType -- Wanted
502 -> Maybe (Inst, [Class]) -- Nothing if no link; Just (given, classes)
503 -- if wanted can be given in terms of given, with
504 -- intermediate classes specified
505 trySC givens wanted_class wanted_ty
506 = case subclass_relns of
508 ((given, classes, _): _) -> Just (given, classes)
510 subclass_relns :: [(Inst, [Class], Int)] -- Subclass of wanted,
511 -- intervening classes,
512 -- and number of intervening classes
513 -- Sorted with shortest link first
514 subclass_relns = sortLt reln_lt (catMaybes (map find_subclass_reln givens))
516 reln_lt :: (Inst, [Class], Int) -> (Inst, [Class], Int) -> Bool
517 (_,_,n1) `reln_lt` (_,_,n2) = n1 < n2
519 find_subclass_reln given@(Dict _ given_class given_ty _)
520 | wanted_ty == given_ty
521 = case (wanted_class `isSuperClassOf` given_class) of
523 Just classes -> Just (given,
529 | otherwise = Nothing
532 sortSC :: [Inst] -- Expected to be all dicts (no MethodIds), all of
533 -- which constrain type variables
534 -> [Inst] -- Sorted with subclasses before superclasses
536 sortSC dicts = sortLt lt dicts
538 (Dict _ c1 ty1 _) `lt` (Dict _ c2 ty2 _)
539 = tv1 `ltTyVar` tv2 ||
540 (tv1 `eqTyVar` tv2 && maybeToBool (c2 `isSuperClassOf` c1))
542 tv1 = getTyVar "sortSC" ty1
543 tv2 = getTyVar "sortSC" ty2
547 %************************************************************************
549 \subsection[binds-for-local-funs]{@bindInstsOfLocalFuns@}
551 %************************************************************************
553 When doing a binding group, we may have @Insts@ of local functions.
554 For example, we might have...
556 let f x = x + 1 -- orig local function (overloaded)
557 f.1 = f Int -- two instances of f
562 The point is: we must drop the bindings for @f.1@ and @f.2@ here,
563 where @f@ is in scope; those @Insts@ must certainly not be passed
564 upwards towards the top-level. If the @Insts@ were binding-ified up
565 there, they would have unresolvable references to @f@.
567 We pass in an @init_lie@ of @Insts@ and a list of locally-bound @Ids@.
568 For each method @Inst@ in the @init_lie@ that mentions one of the
569 @Ids@, we create a binding. We return the remaining @Insts@ (in an
570 @LIE@), as well as the @Binds@ generated.
573 bindInstsOfLocalFuns :: LIE -> [Id] -> NF_TcM (LIE, TypecheckedMonoBinds)
575 bindInstsOfLocalFuns init_lie local_ids
577 insts = unMkLIE init_lie
579 bind_insts insts [] EmptyMonoBinds
581 bind_insts :: [Inst] -- Insts to mangle
582 -> [Inst] -- accum. Insts to return
583 -> TypecheckedMonoBinds -- accum. Binds to return
584 -> NF_TcM (LIE, TypecheckedMonoBinds)
586 bind_insts [] acc_insts acc_binds
587 = returnNF_Tc (mkLIE acc_insts, acc_binds)
589 bind_insts (inst@(Method uniq id tys orig):insts) acc_insts acc_binds
590 | id `is_elem` local_ids
591 = noFailTc (lookupInst_Tc inst) `thenNF_Tc` \ (expr, dict_insts) ->
593 bind = VarMonoBind (mkInstId inst) expr
595 bind_insts insts (dict_insts ++ acc_insts) (bind `AndMonoBinds` acc_binds)
597 bind_insts (some_other_inst:insts) acc_insts acc_binds
598 -- Either not a method, or a method instance for an id not in local_ids
599 = bind_insts insts (some_other_inst:acc_insts) acc_binds
601 is_elem = isIn "bindInstsOfLocalFuns"