Define custom command for a cabal repl session

Imagine you want to demo or test your cabal package in a REPL environment. Instead of loading the modules you need manually each time you do cabal repl, you want everything to load automatically.

For that, you place a “.ghci” in your cabal package folder (where its .cabal file is). And write “import YourModule” in it, but you get an error:

$ cabal repl your-package
...
<no location info>: error: [GHC-35235]
    Could not find module ‘YourModule’.
    It is not a module in the current program, or in any known package.

You find the “–repl-options” option:

--repl-options=FLAG

    To avoid ghci-specific flags from triggering unneeded global rebuilds, these flags are stripped from the internal configuration. As a result, --ghc-options will no longer (reliably) work to pass flags to ghci (or other REPLs). Instead, you should use the --repl-options flag to specify these options to the invoked REPL.

No matter how you try, it doesn’t work out.

So, the solution I had settled on in the end was to use :def command of GHCi, as an example:

:set -package base -package yul-dsl
:module +Prelude
:set -XNoOverloadedStrings

-- to be used in :setup
:{
__import_modules = unlines
  [ ":module + YolSuite.ReplUtils"
  , ":module + YulDSL.Core ERC20"
  ]
:}

-- define a :setup command for demo purpose:
:def setup (const . pure $ __import_modules)

Now in the cabal repl environment, I can simply do before demo or testing:

:setup

Let me know if you have better ways of doing it!

1 Like

I was thinking that maybe you could make a custom Prelude that loads those modules automatically, but custom preludes also seem to break cabal repl according to my limited testing.

Edit: thanks to this stackoverflow post:

I figured out that you can make the custom prelude work if you put it into a different sublibrary. That also fixes the .ghci module loading problem. So you can do something like this:

-- .ghci
import YourModule
-- your-package.cabal
[...]

library demo
  build-depends: your-package
$ cabal repl demo

You can even give your script a different name if you put this in your .cabal file:

library demo
  build-depends: your-package
  ghc-options:   -ghci-script demo-script
2 Likes

also an interesting alternative solution!