[project @ 2001-03-08 12:07:38 by simonpj]
[ghc-hetmet.git] / ghc / compiler / deSugar / DsForeign.lhs
index 3614d8d..7e1f46d 100644 (file)
@@ -12,44 +12,37 @@ module DsForeign ( dsForeigns ) where
 
 import CoreSyn
 
-import DsCCall         ( dsCCall, mkCCall, boxResult, unboxArg )
+import DsCCall         ( dsCCall, mkCCall, boxResult, unboxArg, resultWrapper )
 import DsMonad
-import DsUtils
 
 import HsSyn           ( ExtName(..), ForeignDecl(..), isDynamicExtName, ForKind(..) )
 import HsDecls         ( extNameStatic )
 import CallConv
 import TcHsSyn         ( TypecheckedForeignDecl )
 import CoreUtils       ( exprType, mkInlineMe )
-import DataCon         ( DataCon, dataConWrapId )
-import Id              ( Id, idType, idName, mkWildId, mkVanillaId, mkSysLocal,
+import Id              ( Id, idType, idName, mkVanillaGlobal, mkSysLocal,
                          setInlinePragma )
-import IdInfo          ( neverInlinePrag )
-import MkId            ( mkWorkerId )
+import IdInfo          ( neverInlinePrag, vanillaIdInfo )
 import Literal         ( Literal(..) )
 import Module          ( Module, moduleUserString )
 import Name            ( mkGlobalName, nameModule, nameOccName, getOccString, 
                          mkForeignExportOcc, isLocalName,
-                         NamedThing(..), Provenance(..), ExportFlag(..)
+                         NamedThing(..),
                        )
-import Type            ( unUsgTy, repType,
-                         splitTyConApp_maybe, splitFunTys, splitForAllTys,
+import Type            ( repType, splitTyConApp_maybe,
+                         tyConAppTyCon, splitFunTys, splitForAllTys,
                          Type, mkFunTys, mkForAllTys, mkTyConApp,
-                         mkTyVarTy, mkFunTy, splitAppTy, applyTy, funResultTy
+                         mkFunTy, splitAppTy, applyTy, funResultTy
                        )
-import PprType         ( {- instance Outputable Type -} )
-import PrimOp          ( PrimOp(..), CCall(..), CCallTarget(..), dynamicTarget )
-import Var             ( TyVar )
-import TysPrim         ( realWorldStatePrimTy, addrPrimTy )
-import TysWiredIn      ( unitTy, addrTy, stablePtrTyCon,
-                         addrDataCon
+import PrimOp          ( CCall(..), CCallTarget(..), dynamicTarget )
+import TysWiredIn      ( unitTy, addrTy, stablePtrTyCon )
+import TysPrim         ( addrPrimTy )
+import PrelNames       ( hasKey, ioTyConKey, deRefStablePtrName, newStablePtrName,
+                         bindIOName, returnIOName
                        )
-import Unique          ( Uniquable(..), hasKey,
-                         ioTyConKey, deRefStablePtrIdKey, returnIOIdKey, 
-                         bindIOIdKey, makeStablePtrIdKey
-               )
-import Maybes          ( maybeToBool )
 import Outputable
+
+import Maybe           ( fromJust )
 \end{code}
 
 Desugaring of @foreign@ declarations is naturally split up into
@@ -66,31 +59,35 @@ is the same as
 so we reuse the desugaring code in @DsCCall@ to deal with these.
 
 \begin{code}
+type Binding = (Id, CoreExpr)  -- No rec/nonrec structure;
+                               -- the occurrence analyser will sort it all out
+
 dsForeigns :: Module
            -> [TypecheckedForeignDecl] 
-          -> DsM ( [CoreBind]        -- desugared foreign imports
-                  , [CoreBind]        -- helper functions for foreign exports
+          -> DsM ( [Id]                -- Foreign-exported binders; 
+                                       -- we have to generate code to register these
+                 , [Binding]
                  , SDoc              -- Header file prototypes for
                                       -- "foreign exported" functions.
                  , SDoc              -- C stubs to use when calling
                                       -- "foreign exported" functions.
                  )
-dsForeigns mod_name fos = foldlDs combine ([],[],empty,empty) fos
+dsForeigns mod_name fos = foldlDs combine ([], [], empty, empty) fos
  where
-  combine (acc_fi, acc_fe, acc_h, acc_c) fo@(ForeignDecl i imp_exp _ ext_nm cconv _) 
+  combine (acc_feb, acc_f, acc_h, acc_c) fo@(ForeignDecl i imp_exp _ ext_nm cconv _) 
     | isForeignImport =   -- foreign import (dynamic)?
         dsFImport i (idType i) uns ext_nm cconv  `thenDs` \ bs -> 
-       returnDs (bs ++ acc_fi, acc_fe, acc_h, acc_c)
+       returnDs (acc_feb, bs ++ acc_f, acc_h, acc_c)
     | isForeignLabel = 
-        dsFLabel i ext_nm `thenDs` \ b -> 
-       returnDs (b:acc_fi, acc_fe, acc_h, acc_c)
+        dsFLabel i (idType i) ext_nm `thenDs` \ b -> 
+       returnDs (acc_feb, b:acc_f, acc_h, acc_c)
     | isDynamicExtName ext_nm =
-        dsFExportDynamic i (idType i) mod_name ext_nm cconv  `thenDs` \ (fi,fe,h,c) -> 
-       returnDs (fi:acc_fi, fe:acc_fe, h $$ acc_h, c $$ acc_c)
+        dsFExportDynamic i (idType i) mod_name ext_nm cconv  `thenDs` \ (feb,bs,h,c) -> 
+       returnDs (feb:acc_feb, bs ++ acc_f, h $$ acc_h, c $$ acc_c)
 
     | otherwise               =  -- foreign export
-        dsFExport i (idType i) mod_name ext_nm cconv False   `thenDs` \ (fe,h,c) ->
-       returnDs (acc_fi, fe:acc_fe, h $$ acc_h, c $$ acc_c)
+        dsFExport i (idType i) mod_name ext_nm cconv False   `thenDs` \ (feb,fe,h,c) ->
+       returnDs (feb:acc_feb, fe:acc_f, h $$ acc_h, c $$ acc_c)
    where
     isForeignImport = 
        case imp_exp of
@@ -131,7 +128,7 @@ dsFImport :: Id
          -> Bool               -- True <=> might cause Haskell GC
          -> ExtName
          -> CallConv
-         -> DsM [CoreBind]
+         -> DsM [Binding]
 dsFImport fn_id ty may_not_gc ext_name cconv 
   = let
        (tvs, fun_ty)        = splitForAllTys ty
@@ -161,18 +158,19 @@ dsFImport fn_id ty may_not_gc ext_name cconv
        wrapper_body = foldr ($) (res_wrapper work_app) arg_wrappers
         wrap_rhs     = mkInlineMe (mkLams (tvs ++ args) wrapper_body)
     in
-    returnDs [NonRec fn_id wrap_rhs, NonRec work_id work_rhs]
+    returnDs [(work_id, work_rhs), (fn_id, wrap_rhs)]
 \end{code}
 
 Foreign labels 
 
 \begin{code}
-dsFLabel :: Id -> ExtName -> DsM CoreBind
-dsFLabel nm ext_name = returnDs (NonRec nm fo_rhs)
+dsFLabel :: Id -> Type -> ExtName -> DsM Binding
+dsFLabel nm ty ext_name = 
+   ASSERT(fromJust res_ty == addrPrimTy) -- typechecker ensures this
+   returnDs (nm, fo_rhs (mkLit (MachLabel enm)))
   where
-   fo_rhs = mkConApp addrDataCon [mkLit (MachLitLit addr addrPrimTy)]
+   (res_ty, fo_rhs) = resultWrapper ty
    enm    = extNameStatic ext_name
-   addr   = SLIT("(&") _APPEND_ enm _APPEND_ SLIT(")")
 \end{code}
 
 The function that does most of the work for `@foreign export@' declarations.
@@ -194,7 +192,8 @@ dsFExport :: Id
          -> CallConv
          -> Bool               -- True => invoke IO action that's hanging off 
                                -- the first argument's stable pointer
-         -> DsM ( CoreBind
+         -> DsM ( Id           -- The foreign-exported Id
+                , Binding
                 , SDoc
                 , SDoc
                 )
@@ -210,7 +209,7 @@ dsFExport fn_id ty mod_name ext_name cconv isDyn
                 returnDs (\body -> body, orig_res_ty, res_ty)
 
        other ->        -- The function returns t, so wrap the call in returnIO
-                dsLookupGlobalValue returnIOIdKey      `thenDs` \ retIOId ->
+                dsLookupGlobalValue returnIOName       `thenDs` \ retIOId ->
                 returnDs (\body -> mkApps (Var retIOId) [Type orig_res_ty, body],
                           funResultTy (applyTy (idType retIOId) orig_res_ty), 
                                -- We don't have ioTyCon conveniently to hand
@@ -225,8 +224,8 @@ dsFExport fn_id ty mod_name ext_name cconv isDyn
      (if isDyn then 
         newSysLocalDs stbl_ptr_ty                      `thenDs` \ stbl_ptr ->
        newSysLocalDs stbl_ptr_to_ty                    `thenDs` \ stbl_value ->
-       dsLookupGlobalValue deRefStablePtrIdKey         `thenDs` \ deRefStablePtrId ->
-        dsLookupGlobalValue bindIOIdKey                        `thenDs` \ bindIOId ->
+       dsLookupGlobalValue deRefStablePtrName          `thenDs` \ deRefStablePtrId ->
+        dsLookupGlobalValue bindIOName                 `thenDs` \ bindIOId ->
        let
         the_deref_app = mkApps (Var deRefStablePtrId)
                                [ Type stbl_ptr_to_ty, Var stbl_ptr ]
@@ -260,7 +259,7 @@ dsFExport fn_id ty mod_name ext_name cconv isDyn
        helper_ty =  mkForAllTys tvs $
                     mkFunTys wrapper_arg_tys io_res_ty
 
-       f_helper_glob = mkVanillaId helper_name helper_ty
+       f_helper_glob = mkVanillaGlobal helper_name helper_ty vanillaIdInfo
                      where
                        name                = idName fn_id
                        mod     
@@ -268,8 +267,7 @@ dsFExport fn_id ty mod_name ext_name cconv isDyn
                         | otherwise        = nameModule name
 
                        occ                 = mkForeignExportOcc (nameOccName name)
-                       prov                = LocalDef src_loc Exported
-                       helper_name         = mkGlobalName uniq mod occ prov
+                       helper_name         = mkGlobalName uniq mod occ src_loc
 
        the_app = getFun_wrapper (return_io_wrapper (mkVarApps (Var i) (tvs ++ fe_args)))
        the_body = mkLams (tvs ++ wrapper_args) the_app
@@ -279,7 +277,7 @@ dsFExport fn_id ty mod_name ext_name cconv isDyn
                                      c_nm f_helper_glob
                                       wrapper_arg_tys res_ty cconv isDyn
      in
-     returnDs (NonRec f_helper_glob the_body, h_stub, c_stub)
+     returnDs (f_helper_glob, (f_helper_glob, the_body), h_stub, c_stub)
 
   where
    (tvs,sans_foralls)                  = splitForAllTys ty
@@ -307,7 +305,7 @@ foreign export dynamic f :: (Addr -> Int -> IO Int) -> IO Addr
 
 f :: (Addr -> Int -> IO Int) -> IO Addr
 f cback =
-   bindIO (makeStablePtr cback)
+   bindIO (newStablePtr cback)
           (\StablePtr sp# -> IO (\s1# ->
               case _ccall_ createAdjustor cconv sp# ``f_helper'' s1# of
                  (# s2#, a# #) -> (# s2#, A# a# #)))
@@ -323,7 +321,7 @@ dsFExportDynamic :: Id
                 -> Module
                 -> ExtName
                 -> CallConv
-                -> DsM (CoreBind, CoreBind, SDoc, SDoc)
+                -> DsM (Id, [Binding], SDoc, SDoc)
 dsFExportDynamic i ty mod_name ext_name cconv =
      newSysLocalDs ty                                   `thenDs` \ fe_id ->
      let 
@@ -332,13 +330,13 @@ dsFExportDynamic i ty mod_name ext_name cconv =
        fe_ext_name = ExtName (_PK_ fe_nm) Nothing
      in
      dsFExport  i export_ty mod_name fe_ext_name cconv True
-     `thenDs` \ (fe@(NonRec fe_helper fe_expr), h_code, c_code) ->
+       `thenDs` \ (feb, fe, h_code, c_code) ->
      newSysLocalDs arg_ty                      `thenDs` \ cback ->
-     dsLookupGlobalValue makeStablePtrIdKey    `thenDs` \ makeStablePtrId ->
+     dsLookupGlobalValue newStablePtrName      `thenDs` \ newStablePtrId ->
      let
-       mk_stbl_ptr_app    = mkApps (Var makeStablePtrId) [ Type arg_ty, Var cback ]
+       mk_stbl_ptr_app    = mkApps (Var newStablePtrId) [ Type arg_ty, Var cback ]
      in
-     dsLookupGlobalValue bindIOIdKey                   `thenDs` \ bindIOId ->
+     dsLookupGlobalValue bindIOName                    `thenDs` \ bindIOId ->
      newSysLocalDs (mkTyConApp stablePtrTyCon [arg_ty]) `thenDs` \ stbl_value ->
      let
       stbl_app cont ret_ty 
@@ -358,25 +356,26 @@ dsFExportDynamic i ty mod_name ext_name cconv =
        -}
       adj_args      = [ mkIntLitInt (callConvToInt cconv)
                      , Var stbl_value
-                     , mkLit (MachLitLit (_PK_ fe_nm) addrPrimTy)
+                     , mkLit (MachLabel (_PK_ fe_nm))
                      ]
         -- name of external entry point providing these services.
        -- (probably in the RTS.) 
       adjustor     = SLIT("createAdjustor")
      in
-     dsCCall adjustor adj_args False False ioAddrTy `thenDs` \ ccall_adj ->
+     dsCCall adjustor adj_args False False io_res_ty `thenDs` \ ccall_adj ->
      let ccall_adj_ty = exprType ccall_adj
          ccall_io_adj = mkLams [stbl_value]                 $
-                       Note (Coerce io_res_ty (unUsgTy ccall_adj_ty))
+                       Note (Coerce io_res_ty ccall_adj_ty)
                             ccall_adj
      in
      let io_app = mkLams tvs    $
                  mkLams [cback] $
-                 stbl_app ccall_io_adj addrTy
+                 stbl_app ccall_io_adj res_ty
+        fed = (i `setInlinePragma` neverInlinePrag, io_app)
+               -- Never inline the f.e.d. function, because the litlit
+               -- might not be in scope in other modules.
      in
-       -- Never inline the f.e.d. function, because the litlit might not be in scope
-       -- in other modules.
-     returnDs (NonRec (i `setInlinePragma` neverInlinePrag) io_app, fe, h_code, c_code)
+     returnDs (feb, [fed, fe], h_code, c_code)
 
  where
   (tvs,sans_foralls)              = splitForAllTys ty
@@ -485,7 +484,7 @@ unpackHObj :: Type -> SDoc
 unpackHObj t = text "rts_get" <> text (showFFIType t)
 
 showStgType :: Type -> SDoc
-showStgType t = text "Stg" <> text (showFFIType t)
+showStgType t = text "Hs" <> text (showFFIType t)
 
 showFFIType :: Type -> String
 showFFIType t = getOccString (getName tc)