• Stars
    star
    230
  • Rank 174,053 (Top 4 %)
  • Language
    Haskell
  • License
    BSD 3-Clause "New...
  • Created about 8 years ago
  • Updated 12 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Haskell/Java interop via inline Java code in Haskell modules.

inline-java: Call any JVM function from Haskell

Build

The Haskell standard includes a native foreign function interface (FFI). Using it can be a bit involved and only C support is implemented in GHC. inline-java lets you call any JVM function directly, from Haskell, without the need to write your own foreign import declarations using the FFI. In the style of inline-c for C and inline-r for calling R, inline-java lets you name any function to call inline in your code. It is implemented on top of the jni and jvm packages using a GHC Core plugin to orchestrate compilation and loading of the inlined Java snippets.

Example

Graphical Hello World using Java Swing:

{-# LANGUAGE DataKinds #-}
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE OverloadedStrings #-}
module Main where

import Data.Text (Text)
import Language.Java
import Language.Java.Inline

main :: IO ()
main = withJVM [] $ do
    message <- reflect ("Hello World!" :: Text)
    [java| {
      javax.swing.JOptionPane.showMessageDialog(null, $message);
      } |]

Building it

Requirements:

  • the Bazel build tool, and
  • the Nix package manager.

To build:

$ nix-shell --pure --run "bazel build //..."

To test:

$ nix-shell --pure --run "bazel test //..."

Using the safe interface

There is an experimental interface which catches common memory management mistakes at compile time via the LinearTypes language extension.

For examples of how to use the safe interface you can check the tests, the directory server example and the wizzardo-http benchmark.

Further reading

Check the tutorial on how to use inline-java. If you want to know more about how it is implemented, look at our post on the plugin implementation.

There is also a post which gives an overview of the safe interface.

Debugging

The generated java output can be dumped to stderr by passing to GHC

-fplugin-opt=Language.Java.Inline.Plugin:dump-java

If -ddump-to-file is in effect, the java code is dumped to <module>.dump-java instead.

Troubleshooting

Build-time error package or class Blah does not exist

inline-java is going to invoke the javac compiler, and any classes used in java quotations need to be reachable via the CLASSPATH environment variable. For instance,

CLASSPATH=/path/to/my.jar:/some/other/path ghc --make program.hs

Run-time error ThreadNotAttached

Haskell threads need to be attached to the JVM before making JNI calls. Foreign.JNI.withJVM attaches the calling thread, and other threads can be attached with Foreign.JNI.runInAttachedThread. When the JVM calls into Haskell, the thread is already attached.

Run-time error ThreadNotBound

JNI calls need to be done from bound threads. The thread invoking the main function of a program is bound. Threads created with forkOS are bound. In other threads, Control.Concurrent.runInBoundThread can be used to run a computation in a bound thread.

Run-time error java.lang.NoClassDefFoundError

Classes might not be found at runtime if they are not in a folder or jar listed in the parameter -Djava.class.path=<classpath> passed to withJVM.

withJVM ["-Djava.class.path=/path/to/my.jar:/some/other/path"] $ do
  ...

Additionally, classes might not be found if a thread other than the one calling main is trying to use them. One solution is to have the thread calling main load all the classes in advance. Then the classes will be available in the JVM for other threads that need them. Calling Language.Java.Inline.loadJavaWrappers will have the effect of loading all classes needed for java quotations, which will suffice in many cases.

Another option is to set the context class loader of other threads, so they earn the ability to load classes on their own. This might work when the thread was attached to the JVM via the JNI, and the context class loader is just null.

loader <- [java| Thread.currentThread().getContextClassLoader() |]
            `Language.Java.withLocalRef` Foreign.JNI.newGlobalRef
...
forkOS $ runInAttachedThread $ do
  [java| { Thread.currentThread().setContextClassLoader($loader); } |]
  ...

Run-time error JVMException

Any java exception that goes from Java to Haskell will be wrapped as a value of type JVMException with a reference to the Java object representing the exception. The message and the stack trace of the exception can be retrieved from the exception object with more JNI calls, e.g.

\(JVMException e) -> [java| { $e.printStackTrace(); } |]

or with JNI.Foreign.showException.

License

Copyright (c) 2015-2016 EURL Tweag.

All rights reserved.

inline-java is free software, and may be redistributed under the terms specified in the LICENSE file.

Sponsors

Β Β Β Β Β Β Β Β  Tweag I/O Β Β Β Β Β Β Β Β Β Β Β Β  LeapYear

inline-java is maintained by Tweag I/O.

Have questions? Need help? Tweet at @tweagio.

More Repositories

1

nickel

Better configuration for less
Rust
2,275
star
2

asterius

DEPRECATED in favor of ghc wasm backend, see https://www.tweag.io/blog/2022-11-22-wasm-backend-merged-in-ghc
Haskell
1,978
star
3

ormolu

A formatter for Haskell source code
Haskell
958
star
4

jupyenv

Declarative and reproducible Jupyter environments - powered by Nix
Nix
660
star
5

HaskellR

The full power of R in Haskell.
Haskell
583
star
6

topiary

Rust
486
star
7

sparkle

Haskell on Apache Spark.
Haskell
447
star
8

monad-bayes

A library for probabilistic programming in Haskell.
Jupyter Notebook
407
star
9

awesome-learning-haskell

A collection of resources which were useful to Tweagers for learning Haskell and its various aspects
399
star
10

funflow

Functional workflows
Haskell
361
star
11

linear-base

Standard library for linear types in Haskell.
Haskell
335
star
12

rules_nixpkgs

Rules for importing Nixpkgs packages into Bazel.
Starlark
285
star
13

rules_haskell

Haskell rules for Bazel.
Starlark
265
star
14

capability

Extensional capabilities and deriving combinators
Haskell
214
star
15

FawltyDeps

Python dependency checker
Python
192
star
16

clodl

Turn dynamically linked ELF binaries and libraries into self-contained closures.
Starlark
170
star
17

inline-js

Call JavaScript from Haskell, and vice versa!
Haskell
128
star
18

opam-nix

Turn opam-based OCaml projects into Nix derivations
Nix
111
star
19

nixtract

A CLI tool to extract the graph of derivations from a Nix flake.
Rust
81
star
20

nix-hour

Questions for the weekly Nix Hour
Nix
77
star
21

linear-types

Drafts, notes and resources for adding linear typing to GHC.
TeX
75
star
22

python-monorepo-example

Example of a python monorepo using pip, the poetry backend, and Pants
Python
75
star
23

terraform-provider-nixos

Terraform provider for NixOS and NixOps
Go
70
star
24

tf-ncl

Terraform Configurations with Nickel
Rust
65
star
25

distributed-closure

Serializable closures for distributed programming.
Haskell
63
star
26

terraform-provider-secret

Terraform secret provider
Shell
62
star
27

guides

Designing, programming and deploying, in style.
58
star
28

servant-template

A modern template for a Servant
Haskell
51
star
29

nix_bazel_codelab

Nix+Bazel Codelab
Starlark
49
star
30

kernmantle

Braiding extensible effects together in a pipeline/workflow of tasks
Haskell
47
star
31

pirouette

Language-generic workbench for building static analysis
Haskell
47
star
32

python-nix

Python-Nix FFI library using the new C API
Python
45
star
33

skyscope

A tool for visualising and exploring Bazel Skyframe graphs.
Haskell
45
star
34

rules_sh

Shell rules for Bazel
Starlark
42
star
35

nix-ux

Nix UX improvements
Nix
36
star
36

genealogos

Genealogos, a Nix sbom generator
Rust
36
star
37

blog-resources

Extra resources for Tweag's blog posts.
Jupyter Notebook
35
star
38

cooked-validators

Haskell
35
star
39

lagoon

Data centralization tool
Haskell
35
star
40

webauthn

A library for parsing and validating webauthn/fido2 credentials
Haskell
34
star
41

haskell-training

Material for Haskell training
Haskell
31
star
42

hyperion

A lab for future Criterion features.
Haskell
29
star
43

ghc-wasm-miso-examples

Haskell
24
star
44

rust-alpine-mimalloc

Shell
23
star
45

network-transport-zeromq

ZeroMQ transport for distributed-process (aka Cloud Haskell)
Haskell
22
star
46

nix-remote-rust

Rust
21
star
47

haskell-stack-nix-example

Examples of valid and invalid Stack + Nix integration
Nix
20
star
48

timestats

A library to profile time in a Haskell program
Haskell
17
star
49

ssh-participation

An ssh server that creates new users on-the-fly, great for letting users participate in a demo
Nix
16
star
50

nix_gazelle_extension

Gazelle language extension for nix files
Go
15
star
51

epcb

Nix RFC draft on evaluation purity and caching builtins
15
star
52

nixpkgs-graph-explorer

Explore the nixpkgs dependency graph
Python
14
star
53

nixpkgs-graph

Generate a graph from nixpkgs
Python
14
star
54

haskell-binaryen

Haskell bindings to binaryen.
WebAssembly
14
star
55

gazelle_cabal

A gazelle extension to produce Haskell rules from cabal files
Haskell
13
star
56

smtlib-backends

A Haskell library providing low-level functions for SMTLIB-based interaction with SMT solvers.
Haskell
13
star
57

chainsail

Replica Exchange sampling as-a-service
Python
11
star
58

rust-wasm-threads

Examples of Web Workers using rust and WASM
Rust
11
star
59

random-quality

Framework for testing quality of random number generators
Nix
10
star
60

rules_haskell_examples

Examples of using Bazel's Haskell rules.
9
star
61

funflow2

Compose and run computational workflows
Haskell
9
star
62

rust-wasm-nix

Nix
9
star
63

store-graph

simple haskell code that builds a graph from the nix store
Shell
9
star
64

purescript-unlift

MonadBase, MonadUnliftEffect, MonadUnliftAff, and MonadUnlift
Nix
9
star
65

stackage-head

Stackage builds based on GHC HEAD
Haskell
9
star
66

nix-installer-generator

Nix installer generator
Nix
8
star
67

functionless

CLI tool for packaging Haskell executables for AWS Lambda
Java
8
star
68

formik-apollo

A little bit of for using Formik with Apollo
TypeScript
8
star
69

ch-nixops-example

Example deployment of Cloud Haskell app using NixOps.
Haskell
8
star
70

nix-store-gcs-proxy

A HTTP nix store that proxies requests to Google Storage
Nix
8
star
71

ghc-wasm32-wasi

DEPRECATED, new home https://gitlab.haskell.org/ghc/ghc-wasm-meta
Nix
7
star
72

python-nix-flake-template

Bootstrap a reproducible yet flexible Python development environment using Nix
Nix
7
star
73

ghc-wasm-bindists

Stable links for various GHC WASM bindists
Haskell
7
star
74

terraform-gcp-cdn-bucket

A Google Storage Bucket + CDN configuration
HCL
7
star
75

servant-oauth2

A modern servant wrapper around the wai-middleware-auth OAuth2 provider implementations.
Haskell
7
star
76

chainsail-resources

Examples, documentation and other additional resources related to Chainsail
Python
6
star
77

hello-plutarch

Template project for smart-contracts in Plutarch
Nix
6
star
78

summer-of-nix-modules

Incremental module system buildup for Summer of Nix
Nix
6
star
79

tendermint-bazel

Building Go with Bazel
Go
6
star
80

linear-constraints

TeX
6
star
81

ghc-asterius

DEPRECATED, new home https://gitlab.haskell.org/ghc/ghc
Haskell
6
star
82

remote-execution-nix

nix to bazel-re proxy
Rust
6
star
83

work-daigest

Create a digest of your work week using a LLM
Python
6
star
84

tf-ncl-examples

Examples of Terraform configuration with Nickel
NCL
5
star
85

nickel-lang.org

The website of the Nickel language
JavaScript
5
star
86

nix-marp

Run Marp tools via Nix
Nix
5
star
87

nickel-kubernetes

Typecheck, template and modularize your Kubernetes definitions with Nickel
Rust
5
star
88

pyfunflow

Declarative composable typed workflows in Python
Python
5
star
89

duckling

a Haskell library that parses text into structured data
Haskell
4
star
90

graft

Haskell
4
star
91

nix-unit-testing

A showcase of different unit testing frameworks for Nix.
Python
4
star
92

rules_purescript

Python
4
star
93

toronto_reproducibility_workshop

Slides and toy project for the talk at the Toronto Workshop on Reproducibility
Python
4
star
94

nixos-specialisation-dual-boot

Nix
4
star
95

organist-example

Python
4
star
96

gh-migration-scripts

Repository to house scripts to help with GH migration projects
JavaScript
4
star
97

gazelle_haskell_modules

A gazelle extension to generate haskell_module rules
Haskell
4
star
98

inputs

Utilities for building forms with React
TypeScript
3
star
99

pthread

Bindings for the pthread library
Haskell
3
star
100

cooked-smart-contracts

Smart contracts for the Cardano blockchain written with Cooked-validators
Haskell
3
star