[project @ 1997-07-05 03:02:04 by sof]
[ghc-hetmet.git] / ghc / compiler / deSugar / DsExpr.lhs
index 0afd0bc..1478d68 100644 (file)
@@ -9,11 +9,15 @@
 module DsExpr ( dsExpr ) where
 
 IMP_Ubiq()
+#if defined(__GLASGOW_HASKELL__) && __GLASGOW_HASKELL__ <= 201
 IMPORT_DELOOPER(DsLoop)                -- partly to get dsBinds, partly to chk dsExpr
+#else
+import {-# SOURCE #-} DsBinds (dsBinds )
+#endif
 
 import HsSyn           ( failureFreePat,
                          HsExpr(..), OutPat(..), HsLit(..), ArithSeqInfo(..),
-                         Stmt(..), Match(..), Qualifier, HsBinds, HsType,
+                         Stmt(..), DoOrListComp(..), Match(..), HsBinds, HsType, Fixity,
                          GRHSsAndBinds
                        )
 import TcHsSyn         ( SYN_IE(TypecheckedHsExpr), SYN_IE(TypecheckedHsBinds),
@@ -26,7 +30,7 @@ import DsMonad
 import DsCCall         ( dsCCall )
 import DsHsSyn         ( outPatType )
 import DsListComp      ( dsListComp )
-import DsUtils         ( mkAppDs, mkConDs, mkPrimDs, dsExprToAtom,
+import DsUtils         ( mkAppDs, mkConDs, mkPrimDs, dsExprToAtom, mkTupleExpr,
                          mkErrorAppDs, showForErr, EquationInfo,
                          MatchResult, SYN_IE(DsCoreArg)
                        )
@@ -38,25 +42,25 @@ import CostCentre   ( mkUserCC )
 import FieldLabel      ( fieldLabelType, FieldLabel )
 import Id              ( idType, nullIdEnv, addOneToIdEnv,
                          dataConArgTys, dataConFieldLabels,
-                         recordSelectorFieldLabel
+                         recordSelectorFieldLabel, SYN_IE(Id)
                        )
 import Literal         ( mkMachInt, Literal(..) )
 import Name            ( Name{--O only-} )
-import PprStyle                ( PprStyle(..) )
+import Outputable      ( PprStyle(..), Outputable(..) )
 import PprType         ( GenType )
 import PrelVals                ( rEC_CON_ERROR_ID, rEC_UPD_ERROR_ID, voidId )
-import Pretty          ( ppShow, ppBesides, ppPStr, ppStr )
-import TyCon           ( isDataTyCon, isNewTyCon )
-import Type            ( splitSigmaTy, splitFunTy, typePrimRep,
-                         getAppDataTyConExpandingDicts, getAppTyCon, applyTy,
-                         maybeBoxedPrimType
+import Pretty          ( Doc, hcat, ptext, text )
+import Type            ( splitSigmaTy, splitFunTy, typePrimRep, 
+                         getAppDataTyConExpandingDicts, maybeAppTyCon, getAppTyCon, applyTy,
+                         maybeBoxedPrimType, splitAppTy, SYN_IE(Type)
                        )
 import TysPrim         ( voidTy )
-import TysWiredIn      ( mkTupleTy, tupleCon, nilDataCon, consDataCon,
+import TysWiredIn      ( mkTupleTy, tupleCon, nilDataCon, consDataCon, listTyCon,
                          charDataCon, charTy
                        )
 import TyVar           ( nullTyVarEnv, addOneToTyVarEnv, GenTyVar{-instance Eq-} )
 import Usage           ( SYN_IE(UVar) )
+import Maybes          ( maybeToBool )
 import Util            ( zipEqual, pprError, panic, assertPanic )
 
 mk_nil_con ty = mkCon nilDataCon [] [ty] []  -- micro utility...
@@ -75,7 +79,7 @@ around; if we get hits, we use the value accordingly.
 \begin{code}
 dsExpr :: TypecheckedHsExpr -> DsM CoreExpr
 
-dsExpr e@(HsVar var) = dsApp e []
+dsExpr e@(HsVar var) = dsId var
 \end{code}
 
 %************************************************************************
@@ -149,7 +153,7 @@ dsExpr (HsLitOut (HsLitLit s) ty)
            -> (boxing_data_con, typePrimRep prim_ty)
          Nothing
            -> pprError "ERROR: ``literal-literal'' not a single-constructor type: "
-                       (ppBesides [ppPStr s, ppStr "; type: ", ppr PprDebug ty])
+                       (hcat [ptext s, text "; type: ", ppr PprDebug ty])
 
 dsExpr (HsLitOut (HsInt i) ty)
   = returnDs (Lit (NoRepInteger i ty))
@@ -188,8 +192,8 @@ dsExpr expr@(HsLam a_Match)
   = matchWrapper LambdaMatch [a_Match] "lambda"        `thenDs` \ (binders, matching_code) ->
     returnDs ( mkValLam binders matching_code )
 
-dsExpr expr@(HsApp e1 e2)    = dsApp expr []
-dsExpr expr@(OpApp e1 op e2) = dsApp expr []
+dsExpr expr@(HsApp e1 e2)      = dsApp expr []
+dsExpr expr@(OpApp e1 op _ e2) = dsApp expr []
 \end{code}
 
 Operator sections.  At first it looks as if we can convert
@@ -261,18 +265,32 @@ dsExpr expr@(HsCase discrim matches src_loc)
     matchWrapper CaseMatch matches "case"      `thenDs` \ ([discrim_var], matching_code) ->
     returnDs ( mkCoLetAny (NonRec discrim_var core_discrim) matching_code )
 
-dsExpr (ListComp expr quals)
-  = dsExpr expr `thenDs` \ core_expr ->
-    dsListComp core_expr quals
-
 dsExpr (HsLet binds expr)
-  = dsBinds False binds        `thenDs` \ core_binds ->
-    dsExpr expr                `thenDs` \ core_expr ->
+  = dsBinds False binds     `thenDs` \ core_binds ->
+    dsExpr expr                    `thenDs` \ core_expr ->
     returnDs ( mkCoLetsAny core_binds core_expr )
 
-dsExpr (HsDoOut stmts then_id zero_id src_loc)
+dsExpr (HsDoOut do_or_lc stmts return_id then_id zero_id result_ty src_loc)
+  | maybeToBool maybe_list_comp
+  =    -- Special case for list comprehensions
+    putSrcLocDs src_loc $
+    dsListComp stmts elt_ty
+
+  | otherwise
   = putSrcLocDs src_loc $
-    dsDo then_id zero_id stmts
+    dsDo do_or_lc stmts return_id then_id zero_id result_ty
+  where
+    maybe_list_comp 
+       = case (do_or_lc, maybeAppTyCon result_ty) of
+           (ListComp, Just (tycon, [elt_ty]))
+                 | tycon == listTyCon
+                -> Just elt_ty
+           other -> Nothing
+       -- We need the ListComp form to use deListComp (rather than the "do" form)
+       -- because the "return" in a do block is a call to "PrelBase.return", and
+       -- not a ReturnStmt.  Only the ListComp form has ReturnStmts
+
+    Just elt_ty = maybe_list_comp
 
 dsExpr (HsIf guard_expr then_expr else_expr src_loc)
   = putSrcLocDs src_loc $
@@ -397,20 +415,20 @@ might do some argument-evaluation first; and may have to throw away some
 dictionaries.
 
 \begin{code}
-dsExpr (RecordUpdOut record_expr dicts rbinds)
+dsExpr (RecordUpdOut record_expr record_out_ty dicts rbinds)
   = dsExpr record_expr  `thenDs` \ record_expr' ->
 
        -- Desugar the rbinds, and generate let-bindings if
        -- necessary so that we don't lose sharing
     dsRbinds rbinds            $ \ rbinds' ->
     let
-       record_ty               = coreExprType record_expr'
-       (tycon, inst_tys, cons) = --trace "DsExpr.getAppDataTyConExpandingDicts" $
-                                 getAppDataTyConExpandingDicts record_ty
-       cons_to_upd             = filter has_all_fields cons
+       record_in_ty               = coreExprType record_expr'
+       (tycon, in_inst_tys, cons) = getAppDataTyConExpandingDicts record_in_ty
+       (_,     out_inst_tys, _)   = getAppDataTyConExpandingDicts record_out_ty
+       cons_to_upd                = filter has_all_fields cons
 
        -- initial_args are passed to every constructor
-       initial_args            = map TyArg inst_tys ++ map VarArg dicts
+       initial_args            = map TyArg out_inst_tys ++ map VarArg dicts
                
        mk_val_arg (field, arg_id) 
          = case [arg | (f, arg) <- rbinds',
@@ -420,7 +438,7 @@ dsExpr (RecordUpdOut record_expr dicts rbinds)
              []         -> VarArg arg_id
 
        mk_alt con
-         = newSysLocalsDs (dataConArgTys con inst_tys) `thenDs` \ arg_ids ->
+         = newSysLocalsDs (dataConArgTys con in_inst_tys)      `thenDs` \ arg_ids ->
            let 
                val_args = map mk_val_arg (zipEqual "dsExpr:RecordUpd" (dataConFieldLabels con) arg_ids)
            in
@@ -430,8 +448,8 @@ dsExpr (RecordUpdOut record_expr dicts rbinds)
          | length cons_to_upd == length cons 
          = returnDs NoDefault
          | otherwise                       
-         = newSysLocalDs record_ty                     `thenDs` \ deflt_id ->
-           mkErrorAppDs rEC_UPD_ERROR_ID record_ty ""  `thenDs` \ err ->
+         = newSysLocalDs record_in_ty                          `thenDs` \ deflt_id ->
+           mkErrorAppDs rEC_UPD_ERROR_ID record_out_ty ""      `thenDs` \ err ->
            returnDs (BindDefault deflt_id err)
     in
     mapDs mk_alt cons_to_upd   `thenDs` \ alts ->
@@ -472,27 +490,15 @@ of length 0 or 1.
 \end{verbatim}
 \begin{code}
 dsExpr (SingleDict dict)       -- just a local
-  = lookupEnvWithDefaultDs dict (Var dict)
+  = lookupEnvDs dict   `thenDs` \ dict' ->
+    returnDs (Var dict')
 
-dsExpr (Dictionary dicts methods)
-  = -- hey, these things may have been substituted away...
-    zipWithDs lookupEnvWithDefaultDs
-             dicts_and_methods dicts_and_methods_exprs
-                       `thenDs` \ core_d_and_ms ->
+dsExpr (Dictionary [] [])      -- Empty dictionary represented by void,
+  = returnDs (Var voidId)      -- (not, as would happen if we took the next case, by ())
 
-    (case num_of_d_and_ms of
-      0 -> returnDs (Var voidId)
-
-      1 -> returnDs (head core_d_and_ms) -- just a single Id
-
-      _ ->         -- tuple 'em up
-          mkConDs (tupleCon num_of_d_and_ms)
-                  (map (TyArg . coreExprType) core_d_and_ms ++ map VarArg core_d_and_ms)
-    )
-  where
-    dicts_and_methods      = dicts ++ methods
-    dicts_and_methods_exprs = map Var dicts_and_methods
-    num_of_d_and_ms        = length dicts_and_methods
+dsExpr (Dictionary dicts methods)
+  = mapDs lookupEnvDs (dicts ++ methods)       `thenDs` \ d_and_ms' ->
+    returnDs (mkTupleExpr d_and_ms')
 
 dsExpr (ClassDictLam dicts methods expr)
   = dsExpr expr                `thenDs` \ core_expr ->
@@ -519,7 +525,7 @@ dsExpr (ClassDictLam dicts methods expr)
 
 #ifdef DEBUG
 -- HsSyn constructs that just shouldn't be here:
-dsExpr (HsDo _ _)          = panic "dsExpr:HsDo"
+dsExpr (HsDo _ _ _)        = panic "dsExpr:HsDo"
 dsExpr (ExplicitList _)            = panic "dsExpr:ExplicitList"
 dsExpr (ExprWithTySig _ _)  = panic "dsExpr:ExprWithTySig"
 dsExpr (ArithSeqIn _)      = panic "dsExpr:ArithSeqIn"
@@ -549,29 +555,27 @@ dsApp (HsApp e1 e2) args
   = dsExpr e2                  `thenDs` \ core_e2 ->
     dsApp  e1 (VarArg core_e2 : args)
 
-dsApp (OpApp e1 op e2) args
+dsApp (OpApp e1 op _ e2) args
   = dsExpr e1                  `thenDs` \ core_e1 ->
     dsExpr e2                  `thenDs` \ core_e2 ->
     dsApp  op (VarArg core_e1 : VarArg core_e2 : args)
 
 dsApp (DictApp expr dicts) args
-  =    -- now, those dicts may have been substituted away...
-    zipWithDs lookupEnvWithDefaultDs dicts (map Var dicts)
-                               `thenDs` \ core_dicts ->
-    dsApp expr (map VarArg core_dicts ++ args)
+  = mapDs lookupEnvDs dicts    `thenDs` \ core_dicts ->
+    dsApp expr (map (VarArg . Var) core_dicts ++ args)
 
 dsApp (TyApp expr tys) args
   = dsApp expr (map TyArg tys ++ args)
 
 -- we might should look out for SectionLs, etc., here, but we don't
 
-dsApp (HsVar v) args
-  = lookupEnvDs v      `thenDs` \ maybe_expr ->
-    mkAppDs (case maybe_expr of { Nothing -> Var v; Just expr -> expr }) args
-
 dsApp anything_else args
   = dsExpr anything_else       `thenDs` \ core_expr ->
     mkAppDs core_expr args
+
+dsId v
+  = lookupEnvDs v      `thenDs` \ v' ->
+    returnDs (Var v')
 \end{code}
 
 \begin{code}
@@ -611,47 +615,73 @@ dsRbinds ((sel_id, rhs, pun_flag) : rbinds) continue_with
 
 Basically does the translation given in the Haskell~1.3 report:
 \begin{code}
-dsDo   :: Id           -- id for: (>>=) m
-       -> Id           -- id for: zero m
+dsDo   :: DoOrListComp
        -> [TypecheckedStmt]
+       -> Id           -- id for: return m
+       -> Id           -- id for: (>>=) m
+       -> Id           -- id for: zero m
+       -> Type         -- Element type; the whole expression has type (m t)
        -> 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)]
+dsDo do_or_lc stmts return_id then_id zero_id result_ty
+  = dsId return_id     `thenDs` \ return_ds -> 
+    dsId then_id       `thenDs` \ then_ds -> 
+    dsId zero_id       `thenDs` \ zero_ds -> 
+    let
+       (_, b_ty) = splitAppTy result_ty        -- result_ty must be of the form (m b)
+       
+       go [ReturnStmt expr] 
+         = dsExpr expr                 `thenDs` \ expr2 ->
+           mkAppDs return_ds [TyArg b_ty, VarArg expr2]
+    
+       go (GuardStmt expr locn : stmts)
+         = do_expr expr locn                   `thenDs` \ expr2 ->
+           go stmts                            `thenDs` \ rest ->
+           mkAppDs zero_ds [TyArg b_ty]        `thenDs` \ zero_expr ->
+           returnDs (mkCoreIfThenElse expr2 rest zero_expr)
+    
+       go (ExprStmt expr locn : stmts)
+         = do_expr expr locn           `thenDs` \ expr2 ->
+           let
+               (_, a_ty) = splitAppTy (coreExprType expr2)     -- Must be of form (m a)
+           in
+           if null stmts then
+               returnDs expr2
+           else
+               go stmts                `thenDs` \ rest  ->
+               newSysLocalDs a_ty              `thenDs` \ ignored_result_id ->
+               mkAppDs then_ds [TyArg a_ty, TyArg b_ty, VarArg expr2, 
+                                  VarArg (mkValLam [ignored_result_id] rest)]
+    
+       go (LetStmt binds : stmts )
+         = dsBinds False binds   `thenDs` \ binds2 ->
+           go stmts              `thenDs` \ rest   ->
+           returnDs (mkCoLetsAny binds2 rest)
+    
+       go (BindStmt pat expr locn : stmts)
+         = putSrcLocDs locn $
+           dsExpr expr            `thenDs` \ expr2 ->
+           let
+               (_, a_ty)  = splitAppTy (coreExprType expr2)    -- Must be of form (m a)
+               zero_expr  = TyApp (HsVar zero_id) [b_ty]
+               main_match = PatMatch pat (SimpleMatch (
+                            HsDoOut do_or_lc stmts return_id then_id zero_id result_ty locn))
+               the_matches
+                 = if failureFreePat pat
+                   then [main_match]
+                   else [main_match, PatMatch (WildPat a_ty) (SimpleMatch zero_expr)]
+           in
+           matchWrapper DoBindMatch the_matches match_msg
+                               `thenDs` \ (binders, matching_code) ->
+           mkAppDs then_ds [TyArg a_ty, TyArg b_ty,
+                            VarArg expr2, VarArg (mkValLam binders matching_code)]
+    in
+    go stmts
+
   where
-    ds_rest = dsDo then_id zero_id stmts
     do_expr expr locn = putSrcLocDs locn (dsExpr expr)
 
-#ifdef DEBUG
-dsDo then_expr zero_expr [] = panic "dsDo:[]"
-#endif
+    match_msg = case do_or_lc of
+                       DoStmt   -> "`do' statement"
+                       ListComp -> "comprehension"
 \end{code}