Skip to content

Commit

Permalink
Merge pull request #486 from well-typed/userland-capi
Browse files Browse the repository at this point in the history
Add userland-capi PoC
  • Loading branch information
edsko authored Mar 7, 2025
2 parents e1d48a0 + 0f2fb54 commit cb41c23
Show file tree
Hide file tree
Showing 9 changed files with 293 additions and 19 deletions.
50 changes: 31 additions & 19 deletions .github/workflows/haskell-ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,9 @@
#
# For more information, see https://github.com/haskell-CI/haskell-ci
#
# version: 0.19.20240708
# version: 0.19.20250216
#
# REGENDATA ("0.19.20240708",["github","cabal.project.ci"])
# REGENDATA ("0.19.20250216",["github","cabal.project.ci"])
#
name: Haskell-CI
on:
Expand All @@ -23,7 +23,7 @@ on:
jobs:
linux:
name: Haskell-CI - Linux - ${{ matrix.compiler }}
runs-on: ubuntu-20.04
runs-on: ubuntu-24.04
timeout-minutes:
60
container:
Expand Down Expand Up @@ -59,17 +59,30 @@ jobs:
allow-failure: false
fail-fast: false
steps:
- name: apt
- name: apt-get install
run: |
apt-get update
apt-get install -y --no-install-recommends gnupg ca-certificates dirmngr curl git software-properties-common libtinfo5
apt-get install -y libclang-dev llvm
- name: Install GHCup
run: |
mkdir -p "$HOME/.ghcup/bin"
curl -sL https://downloads.haskell.org/ghcup/0.1.30.0/x86_64-linux-ghcup-0.1.30.0 > "$HOME/.ghcup/bin/ghcup"
chmod a+x "$HOME/.ghcup/bin/ghcup"
"$HOME/.ghcup/bin/ghcup" install ghc "$HCVER" || (cat "$HOME"/.ghcup/logs/*.* && false)
- name: Install cabal-install
run: |
"$HOME/.ghcup/bin/ghcup" install cabal 3.12.1.0 || (cat "$HOME"/.ghcup/logs/*.* && false)
apt-get update
apt-get install -y libclang-dev llvm
echo "CABAL=$HOME/.ghcup/bin/cabal-3.12.1.0 -vnormal+nowrap" >> "$GITHUB_ENV"
- name: Install GHC (GHCup)
if: matrix.setup-method == 'ghcup'
run: |
"$HOME/.ghcup/bin/ghcup" install ghc "$HCVER" || (cat "$HOME"/.ghcup/logs/*.* && false)
HC=$("$HOME/.ghcup/bin/ghcup" whereis ghc "$HCVER")
HCPKG=$(echo "$HC" | sed 's#ghc$#ghc-pkg#')
HADDOCK=$(echo "$HC" | sed 's#ghc$#haddock#')
echo "HC=$HC" >> "$GITHUB_ENV"
echo "HCPKG=$HCPKG" >> "$GITHUB_ENV"
echo "HADDOCK=$HADDOCK" >> "$GITHUB_ENV"
env:
HCKIND: ${{ matrix.compilerKind }}
HCNAME: ${{ matrix.compiler }}
Expand All @@ -80,21 +93,12 @@ jobs:
echo "LANG=C.UTF-8" >> "$GITHUB_ENV"
echo "CABAL_DIR=$HOME/.cabal" >> "$GITHUB_ENV"
echo "CABAL_CONFIG=$HOME/.cabal/config" >> "$GITHUB_ENV"
HCDIR=/opt/$HCKIND/$HCVER
HC=$("$HOME/.ghcup/bin/ghcup" whereis ghc "$HCVER")
HCPKG=$(echo "$HC" | sed 's#ghc$#ghc-pkg#')
HADDOCK=$(echo "$HC" | sed 's#ghc$#haddock#')
echo "HC=$HC" >> "$GITHUB_ENV"
echo "HCPKG=$HCPKG" >> "$GITHUB_ENV"
echo "HADDOCK=$HADDOCK" >> "$GITHUB_ENV"
echo "CABAL=$HOME/.ghcup/bin/cabal-3.12.1.0 -vnormal+nowrap" >> "$GITHUB_ENV"
HCNUMVER=$(${HC} --numeric-version|perl -ne '/^(\d+)\.(\d+)\.(\d+)(\.(\d+))?$/; print(10000 * $1 + 100 * $2 + ($3 == 0 ? $5 != 1 : $3))')
echo "HCNUMVER=$HCNUMVER" >> "$GITHUB_ENV"
echo "ARG_TESTS=--enable-tests" >> "$GITHUB_ENV"
echo "ARG_BENCH=--enable-benchmarks" >> "$GITHUB_ENV"
echo "HEADHACKAGE=false" >> "$GITHUB_ENV"
echo "ARG_COMPILER=--$HCKIND --with-compiler=$HC" >> "$GITHUB_ENV"
echo "GHCJSARITH=0" >> "$GITHUB_ENV"
env:
HCKIND: ${{ matrix.compilerKind }}
HCNAME: ${{ matrix.compiler }}
Expand Down Expand Up @@ -155,6 +159,7 @@ jobs:
echo "packages: $GITHUB_WORKSPACE/source/hs-bindgen-libclang" >> cabal.project
echo "packages: $GITHUB_WORKSPACE/source/ansi-diff" >> cabal.project
echo "packages: $GITHUB_WORKSPACE/source/c-expr" >> cabal.project
echo "packages: $GITHUB_WORKSPACE/source/clang-ast-dump" >> cabal.project
cat cabal.project
- name: sdist
run: |
Expand All @@ -176,6 +181,8 @@ jobs:
echo "PKGDIR_ansi_diff=${PKGDIR_ansi_diff}" >> "$GITHUB_ENV"
PKGDIR_c_expr="$(find "$GITHUB_WORKSPACE/unpacked" -maxdepth 1 -type d -regex '.*/c-expr-[0-9.]*')"
echo "PKGDIR_c_expr=${PKGDIR_c_expr}" >> "$GITHUB_ENV"
PKGDIR_clang_ast_dump="$(find "$GITHUB_WORKSPACE/unpacked" -maxdepth 1 -type d -regex '.*/clang-ast-dump-[0-9.]*')"
echo "PKGDIR_clang_ast_dump=${PKGDIR_clang_ast_dump}" >> "$GITHUB_ENV"
rm -f cabal.project cabal.project.local
touch cabal.project
touch cabal.project.local
Expand All @@ -184,6 +191,7 @@ jobs:
echo "packages: ${PKGDIR_hs_bindgen_libclang}" >> cabal.project
echo "packages: ${PKGDIR_ansi_diff}" >> cabal.project
echo "packages: ${PKGDIR_c_expr}" >> cabal.project
echo "packages: ${PKGDIR_clang_ast_dump}" >> cabal.project
echo "package hs-bindgen-runtime" >> cabal.project
echo " ghc-options: -Werror=missing-methods" >> cabal.project
echo "package hs-bindgen" >> cabal.project
Expand All @@ -194,6 +202,8 @@ jobs:
echo " ghc-options: -Werror=missing-methods" >> cabal.project
echo "package c-expr" >> cabal.project
echo " ghc-options: -Werror=missing-methods" >> cabal.project
echo "package clang-ast-dump" >> cabal.project
echo " ghc-options: -Werror=missing-methods" >> cabal.project
cat >> cabal.project <<EOF
package hs-bindgen
ghc-options: -Werror
Expand All @@ -207,7 +217,7 @@ jobs:
package ansi-diff
ghc-options: -Werror
EOF
$HCPKG list --simple-output --names-only | perl -ne 'for (split /\s+/) { print "constraints: any.$_ installed\n" unless /^(ansi-diff|hs-bindgen|hs-bindgen-libclang|hs-bindgen-runtime)$/; }' >> cabal.project.local
$HCPKG list --simple-output --names-only | perl -ne 'for (split /\s+/) { print "constraints: any.$_ installed\n" unless /^(ansi-diff|c-expr|clang-ast-dump|hs-bindgen|hs-bindgen-libclang|hs-bindgen-runtime)$/; }' >> cabal.project.local
cat cabal.project
cat cabal.project.local
- name: dump install plan
Expand Down Expand Up @@ -241,9 +251,11 @@ jobs:
${CABAL} -vnormal check
cd ${PKGDIR_hs_bindgen_libclang} || false
${CABAL} -vnormal check
cd ${PKGDIR_ansi_diff} || false
${CABAL} -vnormal check
cd ${PKGDIR_c_expr} || false
${CABAL} -vnormal check
cd ${PKGDIR_ansi_diff} || false
cd ${PKGDIR_clang_ast_dump} || false
${CABAL} -vnormal check
- name: haddock
run: |
Expand All @@ -253,8 +265,8 @@ jobs:
rm -f cabal.project.local
$CABAL v2-build $ARG_COMPILER --disable-tests --disable-benchmarks all
- name: save cache
uses: actions/cache/save@v4
if: always()
uses: actions/cache/save@v4
with:
key: ${{ runner.os }}-${{ matrix.compiler }}-${{ github.sha }}
path: ~/.cabal/store
1 change: 1 addition & 0 deletions cabal.project
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ packages: hs-bindgen-testlib
packages: c-expr
packages: clang-ast-dump
packages: ansi-diff
packages: userland-capi

tests: True
benchmarks: True
Expand Down
1 change: 1 addition & 0 deletions cabal.project.ci
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ packages: hs-bindgen-libclang
packages: ansi-diff
packages: c-expr
packages: clang-ast-dump
packages: userland-capi

package hs-bindgen
ghc-options: -Werror
Expand Down
29 changes: 29 additions & 0 deletions userland-capi/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
Copyright (c) 2024, Well-Typed LLP and Anduril Industries Inc.


Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.

* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials provided
with the distribution.

* Neither the name of the copyright holder nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
64 changes: 64 additions & 0 deletions userland-capi/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
# Userland CAPI

Originally CApiFFI was created to solve a convenience problem with `iconv` foreign imports:
https://gitlab.haskell.org/ghc/ghc/-/issues/2979

An important point made already then, is that when creating trivial wrappers,
we need at least to try to make their names unique enough, so the C names won't clash
with some other wrappers. (FWIW, that can easily become issue with names like `hs_sha256_update`!)

Maybe more as a side-effect `CApiFFI` also enabled "type-checking" of C-imports,
as there is a true C code using them compiled with C-compiler, not just linking (which only checked that symbol exists).

However, `CApiFFI` may be considered partial feature. A C-file for wrappers is created, but as programmers we have very limited tools to affect it.
We *could* make an include file with some trivial import, and that way "splice" some contents into the wrapper C file;
the cost is the need to create an extra source file.

Some time later GHC TH got ability to add arbitrary
code to be compiled and linked together with a module:
[addForeignSource](https://hackage.haskell.org/package/template-haskell-2.22.0.0/docs/Language-Haskell-TH-Syntax.html#v:addForeignSource).

`addForeignSource` allows to do the same things `CApiFFI` does:

With `CApiFFI` we do

```haskell
-- we can use CApiFFI to import printf with some fixed signature
foreign import capi "stdio.h printf" my_printf :: CString -> CInt -> IO ()
```

but we can also do

```haskell
-- or we can create wrapper ourselves, all from Haskell source:
$(do
addForeignSource LangC $ unlines
[ "#include <stdio.h>"
, "void printf_wrapper(const char *fmt, int x) { printf(fmt, x); }"
]

[d|
foreign import ccall "printf_wrapper" my_printf2 :: CString -> CInt -> IO ()
|])
```

Obviously the latter is more verbose, as we do everything ourselves.
But we can imagine a small library allowing to make imports (and their wrappers) in more concise way.

A first step could be

```haskell
$(userlandCApi 'localname $ do
addInclude "<stdio.h>"
w <- freshCName "printf"
addC $ "void " ++ w ++ "(const char *fmt, int x) { printf(fmt, x); }"
addDec $ foreignImport w "my_printf2" [t| CString -> CInt -> IO () |])
```

here we use `'localname` to give generator a module unique identifier (unit id together with module name),
from which it can generate unique(-enough) wrapper names.

We can also imagine further adding some utilties to declare C and Hs types simultaneously.

This approach allows to create more elaborate C wrappers (and why not wrappers on Haskell side).
The cost is that approach is not as integrated. `CType` annotations are not reifiable, so we'd need to teach the library that `CInt` is `int` etc.
26 changes: 26 additions & 0 deletions userland-capi/examples/example01.hs
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
{-# LANGUAGE CApiFFI #-}
{-# LANGUAGE TemplateHaskell #-}
module Main (main) where

import Foreign.C.String (CString, withCString)
import Foreign.C.Types (CInt (..))
import Language.Haskell.TH.Syntax (ForeignSrcLang (LangC), addForeignSource)

-- we can use CApiFFI to import printf with some fixed signature
foreign import capi "stdio.h printf" my_printf :: CString -> CInt -> IO ()

-- or we can create wrapper ourselves, all from Haskell source:
$(do
addForeignSource LangC $ unlines
[ "#include <stdio.h>"
, "void printf_wrapper(const char *fmt, int x) { printf(fmt, x); }"
]

[d|
foreign import ccall "printf_wrapper" my_printf2 :: CString -> CInt -> IO ()
|])

main :: IO ()
main = do
withCString "hello %d\n" $ \str -> my_printf str 42
withCString "hello %d\n" $ \str -> my_printf2 str 42
23 changes: 23 additions & 0 deletions userland-capi/examples/example02.hs
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
{-# LANGUAGE CApiFFI, TemplateHaskell #-}
{-# OPTIONS_GHC -ddump-splices #-}
module Main (main) where

import UserlandCApi
import Foreign.C.Types
import Foreign.C.String

foreign import capi "stdio.h printf" my_printf :: CString -> CInt -> IO ()

localname :: ()
localname = ()

$(userlandCApi 'localname $ do
addInclude "<stdio.h>"
w <- freshCName "printf"
addC $ "void " ++ w ++ "(const char *fmt, int x) { printf(fmt, x); }"
addDec $ foreignImport w "my_printf2" [t| CString -> CInt -> IO () |])

main :: IO ()
main = do
withCString "hello %d\n" $ \str -> my_printf str 42
withCString "hello %d\n" $ \str -> my_printf2 str 42
77 changes: 77 additions & 0 deletions userland-capi/src/UserlandCApi.hs
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
module UserlandCApi where

import Language.Haskell.TH
import Language.Haskell.TH.Syntax
import Data.IORef
import Data.Char
import Control.Monad

data S = S
{ lname :: Name
, includes :: [String]
, csource :: [String]
, decs :: [DecQ]
}

newtype UC a = UC { unUC :: IORef S -> IO a }

instance Functor UC where
fmap = liftM
instance Applicative UC where
pure x = UC (\_ -> return x)
(<*>) = ap
instance Monad UC where
return = pure
m >>= k = UC $ \ref -> do
x <- unUC m ref
unUC (k x) ref

addInclude :: String -> UC ()
addInclude incl = UC $ \ref -> do
s <- readIORef ref
writeIORef ref s { includes = includes s ++ [incl] }

-- TODO: add counter
freshCName :: String -> UC String
freshCName n = UC $ \ref -> do
s <- readIORef ref
return $ case lname s of
Name _ (NameG _ (PkgName p) (ModName m)) -> filter isLetter (p++m)++"_"++n++"_wrapper"
_ -> n ++ "_wrapper"

addC :: String -> UC ()
addC c = UC $ \ref -> do
s <- readIORef ref
writeIORef ref s { csource = csource s ++ [c] }

addDec :: DecQ -> UC ()
addDec d = UC $ \ref -> do
s <- readIORef ref
writeIORef ref s { decs = decs s ++ [d] }

runUC :: Name -> UC () -> IO S
runUC n m = do
ref <- newIORef (S n [] [] [])
unUC m ref
readIORef ref

foreignImport :: String -> String -> TypeQ -> DecQ
foreignImport cname hsname ty = ForeignD . ImportF CCall Safe cname (mkName hsname) <$> ty

userlandCApi
:: Name -- ^ This name is used to create unique identifiers, based on unit-id and current module.
-> UC ()
-> DecsQ
userlandCApi localname uc = do
runIO $ putStrLn "hello at compile time"
s <- runIO (runUC localname uc)
let source' = source s
runIO $ print localname
runIO $ putStrLn source'
addForeignSource LangC source'
sequence (decs s)
where
source s = unlines $
[ "#include " ++ l
| l <- includes s
] ++ csource s
Loading

0 comments on commit cb41c23

Please sign in to comment.