[project @ 1996-07-25 20:43:49 by partain]
[ghc-hetmet.git] / ghc / compiler / deSugar / DsExpr.lhs
index 4522b96..cf1cf58 100644 (file)
@@ -8,26 +8,31 @@
 
 module DsExpr ( dsExpr ) where
 
-import Ubiq
-import DsLoop          -- partly to get dsBinds, partly to chk dsExpr
+IMP_Ubiq()
+IMPORT_DELOOPER(DsLoop)                -- partly to get dsBinds, partly to chk dsExpr
 
-import HsSyn           ( HsExpr(..), HsLit(..), ArithSeqInfo(..),
-                         Match, Qual, HsBinds, Stmt, PolyType )
-import TcHsSyn         ( TypecheckedHsExpr(..), TypecheckedHsBinds(..),
-                         TypecheckedRecordBinds(..)
+import HsSyn           ( failureFreePat,
+                         HsExpr(..), OutPat(..), HsLit(..), ArithSeqInfo(..),
+                         Stmt(..), Match(..), Qualifier, HsBinds, PolyType,
+                         GRHSsAndBinds
+                       )
+import TcHsSyn         ( SYN_IE(TypecheckedHsExpr), SYN_IE(TypecheckedHsBinds),
+                         SYN_IE(TypecheckedRecordBinds), SYN_IE(TypecheckedPat),
+                         SYN_IE(TypecheckedStmt)
                        )
 import CoreSyn
 
 import DsMonad
 import DsCCall         ( dsCCall )
+import DsHsSyn         ( outPatType )
 import DsListComp      ( dsListComp )
 import DsUtils         ( mkAppDs, mkConDs, mkPrimDs, dsExprToAtom,
-                         mkErrorAppDs, showForErr
+                         mkErrorAppDs, showForErr, EquationInfo,
+                         MatchResult, SYN_IE(DsCoreArg)
                        )
 import Match           ( matchWrapper )
 
-import CoreUnfold      ( UnfoldingDetails(..), UnfoldingGuidance(..),
-                         FormSummary )
+import CoreUnfold      ( Unfolding )
 import CoreUtils       ( coreExprType, substCoreExpr, argToExpr,
                          mkCoreIfThenElse, unTagBinders )
 import CostCentre      ( mkUserCC )
@@ -38,21 +43,24 @@ import Id           ( mkTupleCon, idType, nullIdEnv, addOneToIdEnv,
                        )
 import Literal         ( mkMachInt, Literal(..) )
 import MagicUFs                ( MagicUnfoldingFun )
+import Name            ( Name{--O only-} )
 import PprStyle                ( PprStyle(..) )
 import PprType         ( GenType )
-import PrelInfo                ( mkTupleTy, unitTy, nilDataCon, consDataCon,
-                         charDataCon, charTy, rEC_CON_ERROR_ID,
-                         rEC_UPD_ERROR_ID
-                       )
+import PrelVals                ( rEC_CON_ERROR_ID, rEC_UPD_ERROR_ID, voidId )
 import Pretty          ( ppShow, ppBesides, ppPStr, ppStr )
-import Type            ( splitSigmaTy, splitFunTy, typePrimRep, getAppDataTyCon )
-import TyVar           ( nullTyVarEnv, addOneToTyVarEnv )
-import Usage           ( UVar(..) )
+import TyCon           ( isDataTyCon, isNewTyCon )
+import Type            ( splitSigmaTy, splitFunTy, typePrimRep,
+                         getAppDataTyConExpandingDicts, getAppTyCon, applyTy,
+                         maybeBoxedPrimType
+                       )
+import TysPrim         ( voidTy )
+import TysWiredIn      ( mkTupleTy, nilDataCon, consDataCon,
+                         charDataCon, charTy
+                       )
+import TyVar           ( nullTyVarEnv, addOneToTyVarEnv, GenTyVar{-instance Eq-} )
+import Usage           ( SYN_IE(UVar) )
 import Util            ( zipEqual, pprError, panic, assertPanic )
 
-maybeBoxedPrimType = panic "DsExpr.maybeBoxedPrimType"
-splitTyArgs = panic "DsExpr.splitTyArgs"
-
 mk_nil_con ty = mkCon nilDataCon [] [ty] []  -- micro utility...
 \end{code}
 
@@ -69,7 +77,7 @@ around; if we get hits, we use the value accordingly.
 \begin{code}
 dsExpr :: TypecheckedHsExpr -> DsM CoreExpr
 
-dsExpr (HsVar var) = dsApp (HsVar var) []
+dsExpr e@(HsVar var) = dsApp e []
 \end{code}
 
 %************************************************************************
@@ -103,7 +111,7 @@ dsExpr (HsLitOut (HsString s) _)
        the_char = mkCon charDataCon [] [] [LitArg (MachChar (_HEAD_ s))]
        the_nil  = mk_nil_con charTy
     in
-    mkConDs consDataCon [charTy] [the_char, the_nil]
+    mkConDs consDataCon [TyArg charTy, VarArg the_char, VarArg the_nil]
 
 -- "_" => build (\ c n -> c 'c' n)     -- LATER
 
@@ -145,11 +153,11 @@ dsExpr (HsLitOut (HsLitLit s) ty)
            -> pprError "ERROR: ``literal-literal'' not a single-constructor type: "
                        (ppBesides [ppPStr s, ppStr "; type: ", ppr PprDebug ty])
 
-dsExpr (HsLitOut (HsInt i) _)
-  = returnDs (Lit (NoRepInteger i))
+dsExpr (HsLitOut (HsInt i) ty)
+  = returnDs (Lit (NoRepInteger i ty))
 
-dsExpr (HsLitOut (HsFrac r) _)
-  = returnDs (Lit (NoRepRational r))
+dsExpr (HsLitOut (HsFrac r) ty)
+  = returnDs (Lit (NoRepRational r ty))
 
 -- others where we know what to do:
 
@@ -211,15 +219,14 @@ will sort it out.
 dsExpr (SectionL expr op)
   = dsExpr op                  `thenDs` \ core_op ->
     dsExpr expr                        `thenDs` \ core_expr ->
-    dsExprToAtom core_expr     $ \ y_atom ->
+    dsExprToAtom (VarArg core_expr)    $ \ y_atom ->
 
     -- for the type of x, we need the type of op's 2nd argument
     let
        x_ty  = case (splitSigmaTy (coreExprType core_op)) of { (_, _, tau_ty) ->
-               case (splitTyArgs tau_ty)                 of {
+               case (splitFunTy tau_ty)                   of {
                  ((_:arg2_ty:_), _) -> arg2_ty;
-                 _ -> panic "dsExpr:SectionL:arg 2 ty"
-               }}
+                 _ -> panic "dsExpr:SectionL:arg 2 ty" }}
     in
     newSysLocalDs x_ty         `thenDs` \ x_id ->
     returnDs (mkValLam [x_id] (core_op `App` y_atom `App` VarArg x_id)) 
@@ -228,15 +235,14 @@ dsExpr (SectionL expr op)
 dsExpr (SectionR op expr)
   = dsExpr op                  `thenDs` \ core_op ->
     dsExpr expr                        `thenDs` \ core_expr ->
-    dsExprToAtom core_expr     $ \ y_atom ->
+    dsExprToAtom (VarArg core_expr)    $ \ y_atom ->
 
     -- for the type of x, we need the type of op's 1st argument
     let
        x_ty  = case (splitSigmaTy (coreExprType core_op)) of { (_, _, tau_ty) ->
-               case (splitTyArgs tau_ty)                 of {
+               case (splitFunTy tau_ty)                   of {
                  ((arg1_ty:_), _) -> arg1_ty;
-                 _ -> panic "dsExpr:SectionR:arg 1 ty"
-               }}
+                 _ -> panic "dsExpr:SectionR:arg 1 ty" }}
     in
     newSysLocalDs x_ty         `thenDs` \ x_id ->
     returnDs (mkValLam [x_id] (core_op `App` VarArg x_id `App` y_atom))
@@ -262,13 +268,13 @@ dsExpr (ListComp expr quals)
     dsListComp core_expr quals
 
 dsExpr (HsLet binds expr)
-  = dsBinds binds      `thenDs` \ core_binds ->
+  = dsBinds False binds        `thenDs` \ core_binds ->
     dsExpr expr                `thenDs` \ core_expr ->
     returnDs ( mkCoLetsAny core_binds core_expr )
 
-dsExpr (HsDoOut stmts m_id mz_id src_loc)
+dsExpr (HsDoOut stmts then_id zero_id src_loc)
   = putSrcLocDs src_loc $
-    panic "dsExpr:HsDoOut"
+    dsDo then_id zero_id stmts
 
 dsExpr (HsIf guard_expr then_expr else_expr src_loc)
   = putSrcLocDs src_loc $
@@ -276,7 +282,6 @@ dsExpr (HsIf guard_expr then_expr else_expr src_loc)
     dsExpr then_expr   `thenDs` \ core_then ->
     dsExpr else_expr   `thenDs` \ core_else ->
     returnDs (mkCoreIfThenElse core_guard core_then core_else)
-
 \end{code}
 
 
@@ -300,41 +305,53 @@ dsExpr (ExplicitListOut ty xs)
       (y:ys) ->
        dsExpr y                            `thenDs` \ core_hd  ->
        dsExpr (ExplicitListOut ty ys)  `thenDs` \ core_tl  ->
-       mkConDs consDataCon [ty] [core_hd, core_tl]
+       mkConDs consDataCon [TyArg ty, VarArg core_hd, VarArg core_tl]
 
 dsExpr (ExplicitTuple expr_list)
   = mapDs dsExpr expr_list       `thenDs` \ core_exprs  ->
     mkConDs (mkTupleCon (length expr_list))
-           (map coreExprType core_exprs)
-           core_exprs
+           (map (TyArg . coreExprType) core_exprs ++ map VarArg core_exprs)
 
+-- Two cases, one for ordinary constructors and one for newtype constructors
 dsExpr (HsCon con tys args)
+  | isDataTyCon tycon                  -- The usual datatype case
   = mapDs dsExpr args  `thenDs` \ args_exprs ->
-    mkConDs con tys args_exprs
+    mkConDs con (map TyArg tys ++ map VarArg args_exprs)
+
+  | otherwise                          -- The newtype case
+  = ASSERT( isNewTyCon tycon )
+    ASSERT( null rest_args )
+    dsExpr first_arg           `thenDs` \ arg_expr ->
+    returnDs (Coerce (CoerceIn con) result_ty arg_expr)
+
+  where
+    (first_arg:rest_args) = args
+    (args_tys, result_ty) = splitFunTy (foldl applyTy (idType con) tys)
+    (tycon,_)            = getAppTyCon result_ty
 
 dsExpr (ArithSeqOut expr (From from))
   = dsExpr expr                  `thenDs` \ expr2 ->
     dsExpr from                  `thenDs` \ from2 ->
-    mkAppDs expr2 [] [from2]
+    mkAppDs expr2 [VarArg from2]
 
 dsExpr (ArithSeqOut expr (FromTo from two))
   = dsExpr expr                  `thenDs` \ expr2 ->
     dsExpr from                  `thenDs` \ from2 ->
     dsExpr two           `thenDs` \ two2 ->
-    mkAppDs expr2 [] [from2, two2]
+    mkAppDs expr2 [VarArg from2, VarArg two2]
 
 dsExpr (ArithSeqOut expr (FromThen from thn))
   = dsExpr expr                  `thenDs` \ expr2 ->
     dsExpr from                  `thenDs` \ from2 ->
     dsExpr thn           `thenDs` \ thn2 ->
-    mkAppDs expr2 [] [from2, thn2]
+    mkAppDs expr2 [VarArg from2, VarArg thn2]
 
 dsExpr (ArithSeqOut expr (FromThenTo from thn two))
   = dsExpr expr                  `thenDs` \ expr2 ->
     dsExpr from                  `thenDs` \ from2 ->
     dsExpr thn           `thenDs` \ thn2 ->
     dsExpr two           `thenDs` \ two2 ->
-    mkAppDs expr2 [] [from2, thn2, two2]
+    mkAppDs expr2 [VarArg from2, VarArg thn2, VarArg two2]
 \end{code}
 
 Record construction and update
@@ -358,26 +375,23 @@ before printing it as
 dsExpr (RecordCon con_expr rbinds)
   = dsExpr con_expr    `thenDs` \ con_expr' ->
     let
-       con_id   = get_con_id con_expr'
+       con_id       = get_con con_expr'
+       (arg_tys, _) = splitFunTy (coreExprType con_expr')
 
-       mk_arg lbl
+       mk_arg (arg_ty, lbl)
          = case [rhs | (sel_id,rhs,_) <- rbinds,
                        lbl == recordSelectorFieldLabel sel_id] of
              (rhs:rhss) -> ASSERT( null rhss )
                            dsExpr rhs
-             []         -> mkErrorAppDs rEC_CON_ERROR_ID (fieldLabelType lbl) (showForErr lbl)
-
-       -- ToDo Bug: fieldLabelType lbl needs to be instantiated with appropriate type args
-       --           problem also arises if ty is extraced by splitting the type of the con_id
+             []         -> mkErrorAppDs rEC_CON_ERROR_ID arg_ty (showForErr lbl)
     in
-    mapDs mk_arg (dataConFieldLabels con_id) `thenDs` \ con_args ->
-    mkAppDs con_expr' [] con_args
+    mapDs mk_arg (zipEqual "dsExpr:RecordCon" arg_tys (dataConFieldLabels con_id)) `thenDs` \ con_args ->
+    mkAppDs con_expr' (map VarArg con_args)
   where
-       -- The "con_expr'" is simply an application of the constructor Id
-       -- to types and (perhaps) dictionaries.  This boring little 
-       -- function gets the constructor out.
-    get_con_id (App fun _) = get_con_id fun
-    get_con_id (Var con)   = con
+       -- "con_expr'" is simply an application of the constructor Id
+       -- to types and (perhaps) dictionaries. This gets the constructor...
+    get_con (Var con)   = con
+    get_con (App fun _) = get_con fun
 \end{code}
 
 Record update is a little harder. Suppose we have the decl:
@@ -410,7 +424,8 @@ dsExpr (RecordUpdOut record_expr dicts rbinds)
     dsRbinds rbinds            $ \ rbinds' ->
     let
        record_ty               = coreExprType record_expr'
-       (tycon, inst_tys, cons) = _trace "getAppDataTyCon.DsExpr" $ getAppDataTyCon record_ty
+       (tycon, inst_tys, cons) = --trace "DsExpr.getAppDataTyConExpandingDicts" $
+                                 getAppDataTyConExpandingDicts record_ty
        cons_to_upd             = filter has_all_fields cons
 
        -- initial_args are passed to every constructor
@@ -426,7 +441,7 @@ dsExpr (RecordUpdOut record_expr dicts rbinds)
        mk_alt con
          = newSysLocalsDs (dataConArgTys con inst_tys) `thenDs` \ arg_ids ->
            let 
-               val_args = map mk_val_arg (dataConFieldLabels con `zipEqual` arg_ids)
+               val_args = map mk_val_arg (zipEqual "dsExpr:RecordUpd" (dataConFieldLabels con) arg_ids)
            in
            returnDs (con, arg_ids, mkGenApp (mkGenApp (Var con) initial_args) val_args)
 
@@ -485,14 +500,13 @@ dsExpr (Dictionary dicts methods)
                        `thenDs` \ core_d_and_ms ->
 
     (case num_of_d_and_ms of
-      0 -> returnDs cocon_unit -- unit
+      0 -> returnDs (Var voidId)
 
       1 -> returnDs (head core_d_and_ms) -- just a single Id
 
       _ ->         -- tuple 'em up
           mkConDs (mkTupleCon num_of_d_and_ms)
-                  (map coreExprType core_d_and_ms)
-                  core_d_and_ms
+                  (map (TyArg . coreExprType) core_d_and_ms ++ map VarArg core_d_and_ms)
     )
   where
     dicts_and_methods      = dicts ++ methods
@@ -502,7 +516,7 @@ dsExpr (Dictionary dicts methods)
 dsExpr (ClassDictLam dicts methods expr)
   = dsExpr expr                `thenDs` \ core_expr ->
     case num_of_d_and_ms of
-       0 -> newSysLocalDs unitTy `thenDs` \ new_x ->
+       0 -> newSysLocalDs voidTy `thenDs` \ new_x ->
             returnDs (mkValLam [new_x] core_expr)
 
        1 -> -- no untupling
@@ -530,7 +544,6 @@ dsExpr (ExprWithTySig _ _)  = panic "dsExpr:ExprWithTySig"
 dsExpr (ArithSeqIn _)      = panic "dsExpr:ArithSeqIn"
 #endif
 
-cocon_unit = mkCon (mkTupleCon 0) [] [] [] -- out here to avoid CAF (sigh)
 out_of_range_msg                          -- ditto
   = " out of range: [" ++ show minInt ++ ", " ++ show maxInt ++ "]\n"
 \end{code}
@@ -547,8 +560,6 @@ We're doing all this so we can saturate constructors (as painlessly as
 possible).
 
 \begin{code}
-type DsCoreArg = GenCoreArg CoreExpr{-NB!-} TyVar UVar
-
 dsApp :: TypecheckedHsExpr     -- expr to desugar
       -> [DsCoreArg]           -- accumulated ty/val args: NB:
       -> DsM CoreExpr  -- final result
@@ -575,37 +586,13 @@ dsApp (TyApp expr tys) args
 
 dsApp (HsVar v) args
   = lookupEnvDs v      `thenDs` \ maybe_expr ->
-    case maybe_expr of
-      Just expr -> apply_to_args expr args
-
-      Nothing -> -- we're only saturating constructors and PrimOps
-       case getIdUnfolding v of
-         GenForm _ _ the_unfolding EssentialUnfolding
-           -> do_unfold nullTyVarEnv nullIdEnv (unTagBinders the_unfolding) args
-
-         _ -> apply_to_args (Var v) args
-
+    mkAppDs (case maybe_expr of { Nothing -> Var v; Just expr -> expr }) args
 
 dsApp anything_else args
   = dsExpr anything_else       `thenDs` \ core_expr ->
-    apply_to_args core_expr args
-
--- a DsM version of mkGenApp:
-apply_to_args :: CoreExpr -> [DsCoreArg] -> DsM CoreExpr
-
-apply_to_args fun args
-  = let
-       (ty_args, val_args) = foldr sep ([],[]) args
-    in
-    mkAppDs fun ty_args val_args
-  where
-    sep a@(LitArg l)   (tys,vals) = (tys,    (Lit l):vals)
-    sep a@(VarArg e)   (tys,vals) = (tys,    e:vals)
-    sep a@(TyArg ty)   (tys,vals) = (ty:tys, vals)
-    sep a@(UsageArg _) _         = panic "DsExpr:apply_to_args:UsageArg"
+    mkAppDs core_expr args
 \end{code}
 
-
 \begin{code}
 dsRbinds :: TypecheckedRecordBinds             -- The field bindings supplied
         -> ([(Id, CoreArg)] -> DsM CoreExpr)   -- A continuation taking the field
@@ -617,26 +604,73 @@ dsRbinds [] continue_with
   = continue_with []
 
 dsRbinds ((sel_id, rhs, pun_flag) : rbinds) continue_with
-  = dsExpr rhs         `thenDs` \ rhs' ->
-    dsExprToAtom rhs'  $ \ rhs_atom ->
-    dsRbinds rbinds    $ \ rbinds' ->
+  = dsExpr rhs          `thenDs` \ rhs' ->
+    dsExprToAtom (VarArg rhs') $ \ rhs_atom ->
+    dsRbinds rbinds            $ \ rbinds' ->
     continue_with ((sel_id, rhs_atom) : rbinds')
 \end{code}     
 
 \begin{code}
-do_unfold ty_env val_env (Lam (TyBinder tyvar) body) (TyArg ty : args)
-  = do_unfold (addOneToTyVarEnv ty_env tyvar ty) val_env body args
-
-do_unfold ty_env val_env (Lam (ValBinder binder) body) (VarArg expr : args)
-  = dsExprToAtom expr  $ \ arg_atom ->
-    do_unfold ty_env
-             (addOneToIdEnv val_env binder (argToExpr arg_atom))
-             body args
+-- do_unfold ty_env val_env (Lam (TyBinder tyvar) body) (TyArg ty : args)
+--   = do_unfold (addOneToTyVarEnv ty_env tyvar ty) val_env body args
+-- 
+-- do_unfold ty_env val_env (Lam (ValBinder binder) body) (arg@(VarArg expr) : args)
+--   = dsExprToAtom arg  $ \ arg_atom ->
+--     do_unfold ty_env
+--      (addOneToIdEnv val_env binder (argToExpr arg_atom))
+--           body args
+--
+-- do_unfold ty_env val_env body args
+--   =         -- Clone the remaining part of the template
+--    uniqSMtoDsM (substCoreExpr val_env ty_env body)  `thenDs` \ body' ->
+--
+--     -- Apply result to remaining arguments
+--    mkAppDs body' args
+\end{code}
 
-do_unfold ty_env val_env body args
-  =    -- Clone the remaining part of the template
-    uniqSMtoDsM (substCoreExpr val_env ty_env body)    `thenDs` \ body' ->
+Basically does the translation given in the Haskell~1.3 report:
+\begin{code}
+dsDo   :: Id           -- id for: (>>=) m
+       -> Id           -- id for: zero m
+       -> [TypecheckedStmt]
+       -> DsM CoreExpr
+
+dsDo then_id zero_id (stmt:stmts)
+  = case stmt of
+      ExprStmt expr locn -> ASSERT( null stmts ) do_expr expr locn
+
+      ExprStmtOut expr locn a b -> 
+       do_expr expr locn               `thenDs` \ expr2 ->
+       ds_rest                         `thenDs` \ rest  ->
+       newSysLocalDs a                 `thenDs` \ ignored_result_id ->
+       dsApp (HsVar then_id) [TyArg a, TyArg b, VarArg expr2, 
+                              VarArg (mkValLam [ignored_result_id] rest)]
+
+      LetStmt binds ->
+        dsBinds False binds    `thenDs` \ binds2 ->
+       ds_rest                 `thenDs` \ rest   ->
+       returnDs (mkCoLetsAny binds2 rest)
+
+      BindStmtOut pat expr locn a b ->
+       do_expr expr locn   `thenDs` \ expr2 ->
+       let
+           zero_expr = TyApp (HsVar zero_id) [b]
+           main_match
+             = PatMatch pat (SimpleMatch (HsDoOut stmts then_id zero_id locn))
+           the_matches
+             = if failureFreePat pat
+               then [main_match]
+               else [main_match, PatMatch (WildPat a) (SimpleMatch zero_expr)]
+       in
+       matchWrapper DoBindMatch the_matches "`do' statement"
+                           `thenDs` \ (binders, matching_code) ->
+       dsApp (HsVar then_id) [TyArg a, TyArg b,
+                              VarArg expr2, VarArg (mkValLam binders matching_code)]
+  where
+    ds_rest = dsDo then_id zero_id stmts
+    do_expr expr locn = putSrcLocDs locn (dsExpr expr)
 
-       -- Apply result to remaining arguments
-    apply_to_args body' args
+#ifdef DEBUG
+dsDo then_expr zero_expr [] = panic "dsDo:[]"
+#endif
 \end{code}