[project @ 2005-07-06 10:43:36 by simonmar]
[ghc-hetmet.git] / ghc / compiler / typecheck / TcSimplify.lhs
index 2e04d90..c23e798 100644 (file)
@@ -21,7 +21,6 @@ module TcSimplify (
 #include "HsVersions.h"
 
 import {-# SOURCE #-} TcUnify( unifyTauTy )
-import TcEnv           -- temp
 import HsSyn           ( HsBind(..), HsExpr(..), LHsExpr, emptyLHsBinds )
 import TcHsSyn         ( TcId, TcDictBinds, mkHsApp, mkHsTyApp, mkHsDictApp )
 
@@ -29,7 +28,7 @@ import TcRnMonad
 import Inst            ( lookupInst, LookupInstResult(..),
                          tyVarsOfInst, fdPredsOfInsts, newDicts, 
                          isDict, isClassDict, isLinearInst, linearInstType,
-                         isStdClassTyVarDict, isMethodFor, isMethod,
+                         isMethodFor, isMethod,
                          instToId, tyVarsOfInsts,  cloneDict,
                          ipNamesOfInsts, ipNamesOfInst, dictPred,
                          instBindingRequired, fdPredsOfInst,
@@ -37,26 +36,28 @@ import Inst         ( lookupInst, LookupInstResult(..),
                          getDictClassTys, isTyVarDict, instLoc,
                          zonkInst, tidyInsts, tidyMoreInsts,
                          Inst, pprInsts, pprDictsInFull, pprInstInFull, tcGetInstEnvs,
-                         isInheritableInst, pprDFuns, pprDictsTheta
+                         isInheritableInst, pprDictsTheta
                        )
-import TcEnv           ( tcGetGlobalTyVars, tcLookupId, findGlobals, pprBinders )
-import InstEnv         ( lookupInstEnv, classInstances )
+import TcEnv           ( tcGetGlobalTyVars, tcLookupId, findGlobals, pprBinders,
+                         lclEnvElts, tcMetaTy )
+import InstEnv         ( lookupInstEnv, classInstances, pprInstances )
 import TcMType         ( zonkTcTyVarsAndFV, tcInstTyVars, checkAmbiguity )
 import TcType          ( TcTyVar, TcTyVarSet, ThetaType, TcPredType, 
                           mkClassPred, isOverloadedTy, mkTyConApp, isSkolemTyVar,
                          mkTyVarTy, tcGetTyVar, isTyVarClassPred, mkTyVarTys,
                          tyVarsOfPred, tcEqType, pprPred, mkPredTy )
+import TcIface         ( checkWiredInTyCon )
 import Id              ( idType, mkUserLocal )
 import Var             ( TyVar )
 import Name            ( Name, getOccName, getSrcLoc )
 import NameSet         ( NameSet, mkNameSet, elemNameSet )
 import Class           ( classBigSig, classKey )
 import FunDeps         ( oclose, grow, improve, pprEquationDoc )
-import PrelInfo                ( isNumericClass ) 
+import PrelInfo                ( isNumericClass, isStandardClass ) 
 import PrelNames       ( splitName, fstName, sndName, integerTyConName,
                          showClassKey, eqClassKey, ordClassKey )
 import Type            ( zipTopTvSubst, substTheta, substTy )
-import TysWiredIn      ( pairTyCon, doubleTy )
+import TysWiredIn      ( pairTyCon, doubleTy, doubleTyCon )
 import ErrUtils                ( Message )
 import BasicTypes      ( TopLevelFlag, isNotTopLevel )
 import VarSet
@@ -1313,9 +1314,8 @@ The main control over context reduction is here
 data WhatToDo
  = ReduceMe WantSCs    -- Try to reduce this
                        -- If there's no instance, behave exactly like
-                       -- DontReduce: add the inst to
-                       -- the irreductible ones, but don't
-                       -- produce an error message of any kind.
+                       -- DontReduce: add the inst to the irreductible ones, 
+                       -- but don't produce an error message of any kind.
                        -- It might be quite legitimate such as (Eq a)!
 
  | KeepDictWithoutSCs  -- Return as irreducible; don't add its superclasses
@@ -1331,6 +1331,8 @@ reduceMe inst = ReduceMe AddSCs
 
 data WantSCs = NoSCs | AddSCs  -- Tells whether we should add the superclasses
                                -- of a predicate when adding it to the avails
+       -- The reason for this flag is entirely the super-class loop problem
+       -- Note [SUPER-CLASS LOOP 1]
 \end{code}
 
 
@@ -1857,7 +1859,7 @@ addAvailAndSCs want_scs avails inst avail
 
     findAllDeps :: IdSet -> Avail -> IdSet
     -- Find all the Insts that this one depends on
-    -- See Note [SUPERCLASS-LOOP]
+    -- See Note [SUPERCLASS-LOOP 2]
     -- Watch out, though.  Since the avails may contain loops 
     -- (see Note [RECURSIVE DICTIONARIES]), so we need to track the ones we've seen so far
     findAllDeps so_far (Rhs _ kids) = foldl find_all so_far kids
@@ -2020,21 +2022,32 @@ tc_simplify_top doc is_interactive want_scs wanteds
        ; (frees, binds, irreds) <- simpleReduceLoop doc try_me wanteds
 
        ; let
-               -- All the non-std ones are definite errors
-           (stds, non_stds) = partition isStdClassTyVarDict irreds
-    
-                   -- Group by type variable
-           std_groups = equivClasses cmp_by_tyvar stds
-    
-                   -- Pick the ones which its worth trying to disambiguate
-                   -- namely, the onese whose type variable isn't bound
-                   -- up with one of the non-standard classes
-           (std_oks, std_bads) = partition worth_a_try std_groups
-           worth_a_try group@(d:_) = not (non_std_tyvars `intersectsVarSet` tyVarsOfInst d)
-           non_std_tyvars              = unionVarSets (map tyVarsOfInst non_stds)
+               -- All the non-tv ones are definite errors
+           (tv_dicts, non_tvs) = partition isTyVarDict irreds
+           bad_tyvars = unionVarSets (map tyVarsOfInst non_tvs)
+
+               -- Group by type variable
+           tv_groups = equivClasses cmp_by_tyvar tv_dicts
+
+               -- Pick the ones which its worth trying to disambiguate
+               -- namely, the ones whose type variable isn't bound
+               -- up with one of the non-tyvar classes
+           (default_gps, non_default_gps) = partition defaultable_group tv_groups
+           defaultable_group ds@(d:_) 
+               =  not (bad_tyvars `intersectsVarSet` tyVarsOfInst d)
+               && defaultable_classes (map get_clas ds)
+           defaultable_classes clss 
+               | is_interactive = any isInteractiveClass clss
+               | otherwise      = all isStandardClass clss && any isNumericClass clss
+
+           isInteractiveClass cls = isNumericClass cls
+                                 || (classKey cls `elem` [showClassKey, eqClassKey, ordClassKey])
+                       -- In interactive mode, we default Show a to Show ()
+                       -- to avoid graututious errors on "show []"
+
     
                    -- Collect together all the bad guys
-           bad_guys       = non_stds ++ concat std_bads
+           bad_guys           = non_tvs ++ concat non_default_gps
            (non_ips, bad_ips) = partition isClassDict bad_guys
            (ambigs, no_insts) = partition isTyVarDict non_ips
            -- If the dict has no type constructors involved, it must be ambiguous,
@@ -2068,7 +2081,7 @@ tc_simplify_top doc is_interactive want_scs wanteds
                  addTopAmbigErrs ambigs
 
                  -- Disambiguate the ones that look feasible
-               ; mappM (disambigGroup is_interactive) std_oks }
+               ; mappM (disambigGroup is_interactive) default_gps }
 
        ; return (binds `unionBags` unionManyBags binds_ambig) }
 
@@ -2119,7 +2132,6 @@ disambigGroup :: Bool     -- True <=> simplifying at top-level interactive loop
              -> TcM TcDictBinds
 
 disambigGroup is_interactive dicts
-  |   any std_default_class classes    -- Guaranteed all standard classes
   =    -- THE DICTS OBEY THE DEFAULTABLE CONSTRAINT
        -- SO, TRY DEFAULT TYPES IN ORDER
 
@@ -2145,21 +2157,10 @@ disambigGroup is_interactive dicts
     case mb_ty of
        Left  _                 -> bomb_out
        Right chosen_default_ty -> choose_default chosen_default_ty
-
-  | otherwise                          -- No defaults
-  = bomb_out
-
   where
     tyvar   = get_tv (head dicts)      -- Should be non-empty
     classes = map get_clas dicts
 
-    std_default_class cls
-      =  isNumericClass cls
-      || (is_interactive && 
-         classKey cls `elem` [showClassKey, eqClassKey, ordClassKey])
-               -- In interactive mode, we default Show a to Show ()
-               -- to avoid graututious errors on "show []"
-
     choose_default default_ty  -- Commit to tyvar = default_ty
       =        -- Bind the type variable 
        unifyTauTy default_ty (mkTyVarTy tyvar) `thenM_`
@@ -2180,6 +2181,7 @@ get_default_tys
                Nothing  ->     -- No use-supplied default;
                                -- use [Integer, Double]
                            do { integer_ty <- tcMetaTy integerTyConName
+                              ; checkWiredInTyCon doubleTyCon
                               ; return [integer_ty, doubleTy] } }
 \end{code}
 
@@ -2381,7 +2383,6 @@ addNoInstanceErrs mb_what givens []
 addNoInstanceErrs mb_what givens dicts
   =    -- Some of the dicts are here because there is no instances
        -- and some because there are too many instances (overlap)
-    getDOpts           `thenM` \ dflags ->
     tcGetInstEnvs      `thenM` \ inst_envs ->
     let
        (tidy_env1, tidy_givens) = tidyInsts givens
@@ -2394,7 +2395,7 @@ addNoInstanceErrs mb_what givens dicts
        check_overlap (overlap_doc, no_inst_dicts) dict 
          | not (isClassDict dict) = (overlap_doc, dict : no_inst_dicts)
          | otherwise
-         = case lookupInstEnv dflags inst_envs clas tys of
+         = case lookupInstEnv inst_envs clas tys of
                -- The case of exactly one match and no unifiers means
                -- a successful lookup.  That can't happen here, becuase
                -- dicts only end up here if they didn't match in Inst.lookupInst
@@ -2424,7 +2425,7 @@ addNoInstanceErrs mb_what givens dicts
       = vcat [ addInstLoc [dict] ((ptext SLIT("Overlapping instances for") 
                                        <+> pprPred (dictPred dict))),
                sep [ptext SLIT("Matching instances") <> colon,
-                    nest 2 (vcat [pprDFuns dfuns, pprDFuns unifiers])],
+                    nest 2 (vcat [pprInstances ispecs, pprInstances unifiers])],
                ASSERT( not (null matches) )
                if not (isSingleton matches)
                then    -- Two or more matches
@@ -2435,7 +2436,7 @@ addNoInstanceErrs mb_what givens dicts
                                 quotes (pprWithCommas ppr (varSetElems (tyVarsOfInst dict))),
                              ptext SLIT("Use -fallow-incoherent-instances to use the first choice above")])]
       where
-       dfuns = [df | (_, (_,_,df)) <- matches]
+       ispecs = [ispec | (_, ispec) <- matches]
 
     mk_probable_fix tidy_env dicts     
       = returnM (tidy_env, sep [ptext SLIT("Probable fix:"), nest 2 (vcat fixes)])