Can't figure out how to run GHC with a plugin

Setup that I have: Cabal library project that depends on GHC and has a copy of SourcePlugin from GHC docs

The problem is that I can’t figure out how to run GHC with the plugin. Running GHC directly produces following output:

$ ghc -fplugin src/SourcePlugin src/Parser.hs
Loaded package environment from /home/ddrone/.ghc/x86_64-linux-9.6.1/environments/default
attempting to use module ‘main:src/SourcePlugin’ (./src/SourcePlugin.hs) which is not loaded

Replacing ghc with cabal exec ghc does seem to actually run GHC, but I don’t see the output plugin is supposed to write to stdout:

$ cabal exec ghc -fplugin src/SourcePlugin.hs src/Parser.hs 
Loaded package environment from /home/ddrone/Projects/ghc-plugin/dist-newstyle/tmp/environment.-47119/.ghc.environment.x86_64-linux-9.6.1
[1 of 2] Compiling Parser           ( src/Parser.hs, src/Parser.o ) [Source file changed]

Not sure what I should do instead?

In the first one I think the issue is passing a filepath (src/SourcePlugin) as an argument to -fplugin, which just expects a module name (SourcePlugin).

In the second one, cabal flags are not the same as ghc flags, and -fplugin is a ghc flag which I don’t think is recognized by cabal.

You can retry the first item with ghc -fplugin SourcePlugin src/Parser.hs and having SourcePlugin.hs in the root directory, and you can retry the second option with cabal run --ghc-options='-fplugin SourcePlugin' src/Parser.hs or by having a cabal file with ghc-options: -fplugin=SourcePlugin

No, I’m pretty sure the way I was passing value to -fplugin was right, as evidenced by difference between two invocations of GHC:

$ ghc -fplugin SourcePlugin src/Parser.hs
Loaded package environment from /home/ddrone/.ghc/x86_64-linux-9.6.1/environments/default
<command line>: Could not find module ‘SourcePlugin’
Use -v (or `:set -v` in ghci) to see a list of the files searched for.

$ ghc -fplugin src/SourcePlugin src/Parser.hs
Loaded package environment from /home/ddrone/.ghc/x86_64-linux-9.6.1/environments/default
attempting to use module ‘main:src/SourcePlugin’ (./src/SourcePlugin.hs) which is not loaded

I’ve managed to solve the problem - looks like the easiest way to get what I want is to add a new executable to cabal and configure ghc-options there. Here’s the snippet I’ve ended up using (ghc-plugin is the name of library package that has the SourcePlugin module):

executable parser
    build-depends: base, ghc-plugin
    main-is: Parser.hs
    ghc-options: -fplugin SourcePlugin
1 Like

No, fplugin takes a Haskell module as input. And the module also needs to be compiled first: you cant use a plugin in the same library where it’s defined.

Your second example worked because you’re setting the plugin to a module name and you moved it to the executable stanza, which is not the same library stanza the plugin is being compiled in

1 Like