Cannot parse module with only conditional CPP block
wenkokke opened this issue · 1 comments
Describe the bug
The GHC parser (in Haddock mode) and by extension Ormolu cannot parse modules that only contain a conditional CPP block. This is possibly an upstream issue with ghc-lib-parser
, but I'm filing it here because I'm unsure as GHC compiles the file correctly.
To Reproduce
Write the following to Bug.hs
:
{-# LANGUAGE CPP #-}
module Bug where
#ifdef flag
constant :: Int
constant = 1312
#endif
Then run:
ormolu Bug.hs
Ormolu fails with:
Bug.hs:1:1
The GHC parser (in Haddock mode) failed:
{ErrorWithoutFlag
lexical error in pragma at character 'i'}
Expected behavior
Ormolu outputs the file unchanged.
Environment
- macOS Ventura
- ormolu 0.7.0.0
- ghc-lib-parser 9.6.2.20230523
Thanks for the report, this bug was introduced in #994 because we now parse the imports of a module before formatting:
Line 96 in fe98934
The problem here is that
rawInputStringBuffer
is not pre-processed in any way, i.e. it still contains all CPP markers. It seems to be able to cope with some CPP in imports at least, e.g. this is formatted just fine, although only the first import (A
) is taken into consideration:
{-# LANGUAGE CPP #-}
module Bug where
import A
#ifdef flag
import B
#endif
import C
One straightforward approach to fix this would be to remove all CPP lines before running parseImports
; we could both do it such that we remove or keep import B
in this example.