[project @ 2000-09-07 16:24:14 by simonpj]
[ghc-hetmet.git] / ghc / compiler / deSugar / DsForeign.lhs
index 7817c52..6c7ad10 100644 (file)
@@ -12,40 +12,41 @@ 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 )
-import MkId            ( mkWorkerId )
+import Id              ( Id, idType, idName, mkVanillaId, mkSysLocal,
+                         setInlinePragma )
+import IdInfo          ( neverInlinePrag )
 import Literal         ( Literal(..) )
 import Module          ( Module, moduleUserString )
 import Name            ( mkGlobalName, nameModule, nameOccName, getOccString, 
                          mkForeignExportOcc, isLocalName,
                          NamedThing(..), Provenance(..), ExportFlag(..)
                        )
-import PrelInfo                ( deRefStablePtr_NAME, returnIO_NAME, bindIO_NAME, makeStablePtr_NAME )
-import Type            ( unUsgTy,
+import Type            ( unUsgTy, repType,
                          splitTyConApp_maybe, splitFunTys, splitForAllTys,
                          Type, mkFunTys, mkForAllTys, mkTyConApp,
                          mkTyVarTy, mkFunTy, splitAppTy, applyTy, funResultTy
                        )
-import PprType         ( {- instance Outputable Type -} )
-import PrimOp          ( PrimOp(..), CCall(..), CCallTarget(..) )
-import Var             ( TyVar )
-import TysPrim         ( realWorldStatePrimTy, addrPrimTy )
+import PrimOp          ( PrimOp(..), CCall(..), 
+                         CCallTarget(..), dynamicTarget )
 import TysWiredIn      ( unitTy, addrTy, stablePtrTyCon,
-                         unboxedTupleCon, addrDataCon
+                         addrDataCon
                        )
-import Unique
-import Maybes          ( maybeToBool )
+import TysPrim         ( addrPrimTy )
+import Unique          ( Uniquable(..), hasKey,
+                         ioTyConKey, deRefStablePtrIdKey, returnIOIdKey, 
+                         bindIOIdKey, makeStablePtrIdKey
+               )
 import Outputable
+
+import Maybe           ( fromJust )
 \end{code}
 
 Desugaring of @foreign@ declarations is naturally split up into
@@ -78,7 +79,7 @@ dsForeigns mod_name fos = foldlDs combine ([],[],empty,empty) fos
         dsFImport i (idType i) uns ext_nm cconv  `thenDs` \ bs -> 
        returnDs (bs ++ acc_fi, acc_fe, acc_h, acc_c)
     | isForeignLabel = 
-        dsFLabel i ext_nm `thenDs` \ b -> 
+        dsFLabel i (idType i) ext_nm `thenDs` \ b -> 
        returnDs (b:acc_fi, acc_fe, acc_h, acc_c)
     | isDynamicExtName ext_nm =
         dsFExportDynamic i (idType i) mod_name ext_nm cconv  `thenDs` \ (fi,fe,h,c) -> 
@@ -137,37 +138,38 @@ dsFImport fn_id ty may_not_gc ext_name cconv
     mapAndUnzipDs unboxArg (map Var args)      `thenDs` \ (val_args, arg_wrappers) ->
     boxResult io_res_ty                                `thenDs` \ (ccall_result_ty, res_wrapper) ->
 
-    (case ext_name of
-       Dynamic       -> getUniqueDs `thenDs` \ u -> 
-                       returnDs (DynamicTarget u)
-       ExtName fs _  -> returnDs (StaticTarget fs))    `thenDs` \ lbl ->
-
     getUniqueDs                                                `thenDs` \ ccall_uniq ->
     getUniqueDs                                                `thenDs` \ work_uniq ->
     let
+       lbl = case ext_name of
+               Dynamic      -> dynamicTarget
+               ExtName fs _ -> StaticTarget fs
+
        -- Build the worker
        work_arg_ids  = [v | Var v <- val_args]         -- All guaranteed to be vars
        worker_ty     = mkForAllTys tvs (mkFunTys (map idType work_arg_ids) ccall_result_ty)
        the_ccall     = CCall lbl False (not may_not_gc) cconv
        the_ccall_app = mkCCall ccall_uniq the_ccall val_args ccall_result_ty
        work_rhs      = mkLams tvs (mkLams work_arg_ids the_ccall_app)
-       work_id       = mkWorkerId work_uniq fn_id worker_ty
+       work_id       = mkSysLocal SLIT("$wccall") work_uniq worker_ty
 
        -- Build the wrapper
        work_app     = mkApps (mkVarApps (Var work_id) tvs) val_args
        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 [NonRec work_id work_rhs, NonRec 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 CoreBind
+dsFLabel nm ty ext_name = 
+   ASSERT(fromJust res_ty == addrPrimTy) -- typechecker ensures this
+   returnDs (NonRec nm (fo_rhs (mkLit (MachLabel enm))))
   where
-   fo_rhs = mkConApp addrDataCon [mkLit (MachLitLit enm addrPrimTy)]
+   (res_ty, fo_rhs) = resultWrapper ty
    enm    = extNameStatic ext_name
 \end{code}
 
@@ -201,12 +203,12 @@ dsFExport fn_id ty mod_name ext_name cconv isDyn
        -- If it's plain t, return      (\x.returnIO x, IO t, t)
      (case splitTyConApp_maybe orig_res_ty of
        Just (ioTyCon, [res_ty])
-             -> ASSERT( getUnique ioTyCon == ioTyConKey )
+             -> ASSERT( ioTyCon `hasKey` ioTyConKey )
                        -- The function already returns IO t
                 returnDs (\body -> body, orig_res_ty, res_ty)
 
        other ->        -- The function returns t, so wrap the call in returnIO
-                dsLookupGlobalValue returnIO_NAME      `thenDs` \ retIOId ->
+                dsLookupGlobalValue returnIOIdKey      `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
@@ -221,13 +223,12 @@ 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 deRefStablePtr_NAME         `thenDs` \ deRefStablePtrId ->
+       dsLookupGlobalValue deRefStablePtrIdKey         `thenDs` \ deRefStablePtrId ->
+        dsLookupGlobalValue bindIOIdKey                        `thenDs` \ bindIOId ->
        let
         the_deref_app = mkApps (Var deRefStablePtrId)
                                [ Type stbl_ptr_to_ty, Var stbl_ptr ]
-        in
-        dsLookupGlobalValue bindIO_NAME                         `thenDs` \ bindIOId ->
-       let
+
         stbl_app cont = mkApps (Var bindIOId)
                                [ Type stbl_ptr_to_ty
                                , Type res_ty
@@ -297,24 +298,17 @@ of some fixed type behind an externally callable interface (i.e.,
 as a C function pointer). Useful for callbacks and stuff.
 
 \begin{verbatim}
-foreign export stdcall f :: (Addr -> Int -> IO Int) -> IO Addr
+foreign export dynamic f :: (Addr -> Int -> IO Int) -> IO Addr
 
--- Haskell-visible constructor, which is generated from the
--- above:
+-- Haskell-visible constructor, which is generated from the above:
+-- SUP: No check for NULL from createAdjustor anymore???
 
 f :: (Addr -> Int -> IO Int) -> IO Addr
-f cback = IO ( \ s1# ->
-  case makeStablePtr# cback s1# of { StateAndStablePtr# s2# sp# ->
-  case _ccall_ "mkAdjustor" sp# ``f_helper'' s2# of
-    StateAndAddr# s3# a# ->
-    case addr2Int# a# of
-      0# -> IOfail s# err
-      _  -> 
-        let
-         a :: Addr
-         a = A# a#
-        in
-         IOok s3# a)
+f cback =
+   bindIO (makeStablePtr cback)
+          (\StablePtr sp# -> IO (\s1# ->
+              case _ccall_ createAdjustor cconv sp# ``f_helper'' s1# of
+                 (# s2#, a# #) -> (# s2#, A# a# #)))
 
 foreign export "f_helper" f_helper :: StablePtr (Addr -> Int -> IO Int) -> Addr -> Int -> IO Int
 -- `special' foreign export that invokes the closure pointed to by the
@@ -336,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` \ (fe@(NonRec fe_helper fe_expr), h_code, c_code) ->
      newSysLocalDs arg_ty                      `thenDs` \ cback ->
-     dsLookupGlobalValue makeStablePtr_NAME    `thenDs` \ makeStablePtrId ->
+     dsLookupGlobalValue makeStablePtrIdKey    `thenDs` \ makeStablePtrId ->
      let
        mk_stbl_ptr_app    = mkApps (Var makeStablePtrId) [ Type arg_ty, Var cback ]
      in
-     dsLookupGlobalValue bindIO_NAME                   `thenDs` \ bindIOId ->
+     dsLookupGlobalValue bindIOIdKey                   `thenDs` \ bindIOId ->
      newSysLocalDs (mkTyConApp stablePtrTyCon [arg_ty]) `thenDs` \ stbl_value ->
      let
       stbl_app cont ret_ty 
@@ -362,13 +356,13 @@ 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))
@@ -376,9 +370,11 @@ dsFExportDynamic i ty mod_name ext_name cconv =
      in
      let io_app = mkLams tvs    $
                  mkLams [cback] $
-                 stbl_app ccall_io_adj addrTy
+                 stbl_app ccall_io_adj res_ty
      in
-     returnDs (NonRec i io_app, fe, h_code, c_code)
+       -- 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)
 
  where
   (tvs,sans_foralls)              = splitForAllTys ty
@@ -492,7 +488,7 @@ showStgType t = text "Stg" <> text (showFFIType t)
 showFFIType :: Type -> String
 showFFIType t = getOccString (getName tc)
  where
-  tc = case splitTyConApp_maybe t of
+  tc = case splitTyConApp_maybe (repType t) of
            Just (tc,_) -> tc
            Nothing     -> pprPanic "showFFIType" (ppr t)
 \end{code}