Fix Trac #959: a long-standing bug in instantiating otherwise-unbound type variables
[ghc-hetmet.git] / compiler / deSugar / DsBinds.lhs
index 764e44b..515ac85 100644 (file)
@@ -23,6 +23,7 @@ import {-# SOURCE #-} Match( matchWrapper )
 import DsMonad
 import DsGRHSs
 import DsUtils
+import OccurAnal
 
 import HsSyn           -- lots of things
 import CoreSyn         -- lots of things
@@ -30,18 +31,16 @@ import MkCore
 import CoreUtils
 import CoreFVs
 
-import TcHsSyn ( mkArbitraryType )     -- Mis-placed?
 import TcType
-import OccurAnal
+import TysPrim  ( anyTypeOfKind )
 import CostCentre
 import Module
 import Id
-import Name    ( localiseName )
-import Var     ( TyVar )
+import MkId    ( seqId )
+import Var     ( Var, TyVar, tyVarKind )
 import VarSet
 import Rules
 import VarEnv
-import Type
 import Outputable
 import SrcLoc
 import Maybes
@@ -164,14 +163,16 @@ dsHsBind auto_scc rest (AbsBinds [] [] exports binds)
   where B is the *non-recursive* binding
        fl = fg a b
        gl = gg b
-       h  = h a b 
+       h  = h a b    -- See (b); note shadowing!
   
   Notice (a) g has a different number of type variables to f, so we must
             use the mkArbitraryType thing to fill in the gaps.  
             We use a type-let to do that.
 
         (b) The local variable h isn't in the exports, and rather than
-            clone a fresh copy we simply replace h by (h a b).  
+            clone a fresh copy we simply replace h by (h a b), where
+            the two h's have different types!  Shadowing happens here,
+            which looks confusing but works fine.
 
         (c) The result is *still* quadratic-sized if there are a lot of
             small bindings.  So if there are more than some small
@@ -191,8 +192,9 @@ dsHsBind auto_scc rest (AbsBinds tyvars [] exports binds)
                        -- see if it has any impact; it is on by default
   =    -- Note [Abstracting over tyvars only]
     do { core_prs <- ds_lhs_binds NoSccs binds
-       ; arby_env <- mkArbitraryTypeEnv tyvars exports
-       ; let (lg_binds, core_prs') = mapAndUnzip do_one core_prs
+       ; 
+       ; let arby_env = mkArbitraryTypeEnv tyvars exports
+              (lg_binds, core_prs') = mapAndUnzip do_one core_prs
              bndrs = mkVarSet (map fst core_prs)
 
              add_lets | core_prs `lengthExceeds` 10 = add_some
@@ -261,26 +263,26 @@ dsHsBind auto_scc rest (AbsBinds all_tyvars dicts exports binds)
 
        ; poly_tup_id <- newSysLocalDs (exprType poly_tup_expr)
 
-       ; let dict_args = map Var dicts
-
-             mk_bind ((tyvars, global, local, prags), n)       -- locals !! n == local
-               =       -- Need to make fresh locals to bind in the selector, because
-                       -- some of the tyvars will be bound to 'Any'
-                 do { ty_args <- mapM mk_ty_arg all_tyvars
-                    ; let substitute = substTyWith all_tyvars ty_args
+       ; let mk_bind ((tyvars, global, local, prags), n)  -- locals!!n == local
+               =       -- Need to make fresh locals to bind in the selector,
+                       -- because some of the tyvars will be bound to 'Any'
+                 do { let ty_args = map mk_ty_arg all_tyvars
+                          substitute = substTyWith all_tyvars ty_args
                     ; locals' <- newSysLocalsDs (map substitute local_tys)
                     ; tup_id  <- newSysLocalDs  (substitute tup_ty)
-                    ; mb_specs <- mapM (dsSpec all_tyvars dicts tyvars global local core_bind) 
+                    ; mb_specs <- mapM (dsSpec all_tyvars dicts tyvars global
+                                        local core_bind) 
                                         prags
                     ; let (spec_binds, rules) = unzip (catMaybes mb_specs)
                           global' = addIdSpecialisations global rules
                           rhs = mkLams tyvars $ mkLams dicts $
                                 mkTupleSelector locals' (locals' !! n) tup_id $
-                                mkApps (mkTyApps (Var poly_tup_id) ty_args) dict_args
+                                mkVarApps (mkTyApps (Var poly_tup_id) ty_args)
+                                          dicts
                     ; return ((global', rhs) : spec_binds) }
                where
                  mk_ty_arg all_tyvar
-                       | all_tyvar `elem` tyvars = return (mkTyVarTy all_tyvar)
+                       | all_tyvar `elem` tyvars = mkTyVarTy all_tyvar
                        | otherwise               = dsMkArbitraryType all_tyvar
 
        ; export_binds_s <- mapM mk_bind (exports `zip` [0..])
@@ -333,36 +335,26 @@ dsSpec all_tvs dicts tvs poly_id mono_id mono_bind
     do { let poly_name = idName poly_id
        ; spec_name <- newLocalName poly_name
        ; ds_spec_expr  <- dsExpr spec_expr
-       ; let (bndrs, body) = collectBinders (occurAnalyseExpr ds_spec_expr)
-             -- ds_spec_expr may look like
-             --     /\a. f a Int dOrdInt
-             -- or  /\a.\d:Ord a. let { dl::Ord [a] = dOrdList a d } in f [a] dl
-               -- The occurrence-analysis does two things
-               -- (a) identifies unused binders: Note [Unused spec binders]
-               -- (b) sorts dict bindings into NonRecs 
-               --      so they can be inlined by decomposeRuleLhs
-             mb_lhs = decomposeRuleLhs body
-
-       -- Check for dead binders: Note [Unused spec binders]
-       ; case filter isDeadBinder bndrs of {
-               bs | not (null bs) -> do { warnDs (dead_msg bs); return Nothing }
-                  | otherwise -> 
+       ; case (decomposeRuleLhs ds_spec_expr) of {
+           Nothing -> do { warnDs decomp_msg; return Nothing } ;
 
-         case mb_lhs of
-           Nothing -> do { warnDs decomp_msg; return Nothing }
+           Just (bndrs, _fn, args) ->
 
-           Just (_, args) -> do {
+       -- Check for dead binders: Note [Unused spec binders]
+         case filter isDeadBinder bndrs of {
+               bs | not (null bs) -> do { warnDs (dead_msg bs); return Nothing } 
+                  | otherwise -> do
 
-         f_body <- fix_up (Let mono_bind (Var mono_id))
+       { let     f_body = fix_up (Let mono_bind (Var mono_id))
 
-       ; let     local_poly  = setIdNotExported poly_id
+                 local_poly  = setIdNotExported poly_id
                        -- Very important to make the 'f' non-exported,
                        -- else it won't be inlined!
                  spec_id     = mkLocalId spec_name spec_ty
                  spec_rhs    = Let (NonRec local_poly poly_f_body) ds_spec_expr
                  poly_f_body = mkLams (tvs ++ dicts) f_body
                                
-                 extra_dict_bndrs = [localise d 
+                 extra_dict_bndrs = [localiseId d  -- See Note [Constant rule dicts]
                                     | d <- varSetElems (exprFreeVars ds_spec_expr)
                                     , isDictId d]
                        -- Note [Const rule dicts]
@@ -372,13 +364,13 @@ dsSpec all_tvs dicts tvs poly_id mono_id mono_bind
                                (extra_dict_bndrs ++ bndrs) args
                                (mkVarApps (Var spec_id) bndrs)
        ; return (Just (addInlineInfo inl spec_id spec_rhs, rule))
-       } } }
+       } } } }
   where
        -- Bind to Any any of all_ptvs that aren't 
        -- relevant for this particular function 
-    fix_up body | null void_tvs = return body
-               | otherwise     = do { void_tys <- mapM dsMkArbitraryType void_tvs
-                                    ; return (mkTyApps (mkLams void_tvs body) void_tys) }
+    fix_up body | null void_tvs = body
+               | otherwise     = mkTyApps (mkLams void_tvs body) $
+                                  map dsMkArbitraryType void_tvs
 
     void_tvs = all_tvs \\ tvs
 
@@ -390,31 +382,26 @@ dsSpec all_tvs dicts tvs poly_id mono_id mono_bind
 
     decomp_msg = hang (ptext (sLit "Specialisation too complicated to desugar; ignored"))
                    2 (ppr spec_expr)
+            
 
-    localise d = mkLocalId (localiseName (idName d)) (idType d)
-            -- See Note [Constant rule dicts]
-
-mkArbitraryTypeEnv :: [TyVar] -> [([TyVar], a, b, c)] -> DsM (TyVarEnv Type)
+mkArbitraryTypeEnv :: [TyVar] -> [([TyVar], a, b, c)] -> TyVarEnv Type
 -- If any of the tyvars is missing from any of the lists in 
 -- the second arg, return a binding in the result
 mkArbitraryTypeEnv tyvars exports
   = go emptyVarEnv exports
   where
-    go env [] = return env
+    go env [] = env
     go env ((ltvs, _, _, _) : exports)
-       = do { env' <- foldlM extend env [tv | tv <- tyvars
-                                       , not (tv `elem` ltvs)
-                                       , not (tv `elemVarEnv` env)]
-            ; go env' exports }
+       = go env' exports
+        where
+          env' = foldl extend env [tv | tv <- tyvars
+                                     , not (tv `elem` ltvs)
+                                     , not (tv `elemVarEnv` env)]
 
-    extend env tv = do { ty <- dsMkArbitraryType tv
-                      ; return (extendVarEnv env tv ty) }
+    extend env tv = extendVarEnv env tv (dsMkArbitraryType tv)
 
-
-dsMkArbitraryType :: TcTyVar -> DsM Type
-dsMkArbitraryType tv = mkArbitraryType warn tv
-  where
-    warn span msg = putSrcSpanDs span (warnDs msg)
+dsMkArbitraryType :: TcTyVar -> Type
+dsMkArbitraryType tv = anyTypeOfKind (tyVarKind tv)
 \end{code}
 
 Note [Unused spec binders]
@@ -453,7 +440,7 @@ And from that we want the rule
 
 But be careful!  That dInt might be GHC.Base.$fOrdInt, which is an External
 Name, and you can't bind them in a lambda or forall without getting things
-confused. Hence the use of 'localise' to make it Internal.
+confused. Hence the use of 'localiseId' to make it Internal.
 
 
 %************************************************************************
@@ -463,19 +450,37 @@ confused. Hence the use of 'localise' to make it Internal.
 %************************************************************************
 
 \begin{code}
-decomposeRuleLhs :: CoreExpr -> Maybe (Id, [CoreExpr])
+decomposeRuleLhs :: CoreExpr -> Maybe ([Var], Id, [CoreExpr])
+-- Take apart the LHS of a RULE.  It's suuposed to look like
+--     /\a. f a Int dOrdInt
+-- or  /\a.\d:Ord a. let { dl::Ord [a] = dOrdList a d } in f [a] dl
+-- That is, the RULE binders are lambda-bound
 -- Returns Nothing if the LHS isn't of the expected shape
 decomposeRuleLhs lhs 
-  = go emptyVarEnv (occurAnalyseExpr lhs)      -- Occurrence analysis sorts out the dict
-                                               -- bindings so we know if they are recursive
+  = case (decomp emptyVarEnv body) of
+       Nothing         -> Nothing
+       Just (fn, args) -> Just (bndrs, fn, args)
   where
+    occ_lhs = occurAnalyseExpr lhs
+               -- The occurrence-analysis does two things
+               -- (a) identifies unused binders: Note [Unused spec binders]
+               -- (b) sorts dict bindings into NonRecs 
+               --      so they can be inlined by 'decomp'
+    (bndrs, body) = collectBinders occ_lhs
+
         -- Substitute dicts in the LHS args, so that there 
         -- aren't any lets getting in the way
         -- Note that we substitute the function too; we might have this as
         -- a LHS:       let f71 = M.f Int in f71
-    go env (Let (NonRec dict rhs) body) 
-        = go (extendVarEnv env dict (simpleSubst env rhs)) body
-    go env body 
+    decomp env (Let (NonRec dict rhs) body) 
+        = decomp (extendVarEnv env dict (simpleSubst env rhs)) body
+
+    decomp env (Case scrut bndr ty [(DEFAULT, _, body)])
+        | isDeadBinder bndr    -- Note [Matching seqId]
+        = Just (seqId, [Type (idType bndr), Type ty, 
+                        simpleSubst env scrut, simpleSubst env body])
+
+    decomp env body 
         = case collectArgs (simpleSubst env body) of
             (Var fn, args) -> Just (fn, args)
             _              -> Nothing
@@ -515,17 +520,23 @@ addInlinePrags prags bndr rhs
        (inl:_) -> addInlineInfo inl bndr rhs
 
 addInlineInfo :: InlineSpec -> Id -> CoreExpr -> (Id,CoreExpr)
-addInlineInfo (Inline phase is_inline) bndr rhs
-  = (attach_phase bndr phase, wrap_inline is_inline rhs)
+addInlineInfo (Inline prag is_inline) bndr rhs
+  = (attach_pragma bndr prag, wrap_inline is_inline rhs)
   where
-    attach_phase bndr phase 
-       | isAlwaysActive phase = bndr   -- Default phase
-       | otherwise            = bndr `setInlinePragma` phase
+    attach_pragma bndr prag
+        | isDefaultInlinePragma prag = bndr
+        | otherwise                  = bndr `setInlinePragma` prag
 
     wrap_inline True  body = mkInlineMe body
     wrap_inline False body = body
 \end{code}
 
+Note [Matching seq]
+~~~~~~~~~~~~~~~~~~~
+The desugarer turns (seq e r) into (case e of _ -> r), via a special-case hack
+and this code turns it back into an application of seq!  
+See Note [Rules for seq] in MkId for the details.
+
 
 %************************************************************************
 %*                                                                     *