packages feed

clashilator-0.1.0: template/FFI.hsc.mustache

{-# LANGUAGE RecordWildCards, ForeignFunctionInterface #-}
module Clash.Clashilator.FFI where

import Prelude
import Clash.Prelude

import Data.Word
import Data.Int
import Foreign.Storable
import Foreign.Ptr
import Foreign.Marshal.Alloc

data INPUT = INPUT {
{{#inPorts}}
    {{^first}}, {{/first}}{{hsName}} :: {{hsType}}
{{/inPorts}}
    }
    deriving (Show)

data OUTPUT = OUTPUT{
{{#outPorts}}
    {{^first}}, {{/first}}{{hsName}} :: {{hsType}}
{{/outPorts}}
    }
    deriving (Show)


#include "Interface.h"

data Sim

foreign import ccall unsafe "vinit" simInit :: IO (Ptr Sim)
foreign import ccall unsafe "vshutdown" simShutdown :: Ptr Sim -> IO ()
foreign import ccall unsafe "vstep" simStep :: Ptr Sim -> Ptr INPUT -> Ptr OUTPUT -> IO ()

instance Storable Bit where
    alignment = alignment . bitToBool
    sizeOf = sizeOf . bitToBool
    peek = fmap boolToBit . peek . castPtr
    poke ptr = poke (castPtr ptr) . bitToBool

instance Storable INPUT where
    alignment _ = #alignment INPUT
    sizeOf _ = #size INPUT
    {-# INLINE peek #-}
    peek ptr = const INPUT <$> pure ()
{{#inPorts}}
        <*> (#peek INPUT, {{cName}}) ptr
{{/inPorts}}
    {-# INLINE poke #-}
    poke ptr this = do
{{#inPorts}}
        (#poke INPUT, {{cName}}) ptr ({{hsName}} this)
{{/inPorts}}
        return ()

instance Storable OUTPUT where
    alignment _ = #alignment OUTPUT
    sizeOf _ = #size OUTPUT
    {-# INLINE peek #-}
    peek ptr = const OUTPUT <$> pure ()
{{#outPorts}}
        <*> (#peek OUTPUT, {{cName}}) ptr
{{/outPorts}}
    {-# INLINE poke #-}
    poke ptr this = do
{{#outPorts}}
        (#poke OUTPUT, {{cName}}) ptr ({{hsName}} this)
{{/outPorts}}
        return ()