Separate conversion from parsing

This commit is contained in:
Ali Abrar 2023-07-24 13:49:06 -04:00
parent fc327d7e3f
commit f91206517e
2 changed files with 14 additions and 16 deletions

View File

@ -93,8 +93,8 @@ exposure = do
hiding <- isJust <$> optional (rword "hiding")
(if hiding then Hidden else Exposed) <$> exports
module' :: Maybe Qualified -> Parser Module
module' cfgQualified = do
module' :: Parser Module
module' = do
void $ rword "import"
_qualified' <- isJust <$> optional (rword "qualified")
_name <- moduleName
@ -102,19 +102,15 @@ module' cfgQualified = do
_alias <- optional alias
_exports <- optional exposure
space
let _qualified = case cfgQualified of
Nothing -> if _qualified'
then Just Qualified_Pre
else if _qualified'' then Just Qualified_Post else Nothing
Just q -> if (_qualified' || _qualified'') then Just q else Nothing
let _qualified = if _qualified' then Just Qualified_Pre else if _qualified'' then Just Qualified_Post else Nothing
pure Module {..}
sortExports :: Module -> Module
sortExports m = m { _exports = fmap sort <$> _exports m }
lineType :: Maybe Qualified -> String -> LineType
lineType mq x =
case parse (module' mq) "" x of
lineType :: String -> LineType
lineType x =
case parse module' "" x of
Left _ -> CodeLine x
Right m -> ModuleLine m
@ -135,8 +131,10 @@ sortImports :: Maybe Qualified -> String -> String
sortImports mq
= unlines
. fmap (\case CodeLine x -> x
ModuleLine x -> view x)
ModuleLine x -> view $ convert x)
. concatMap sortIfModules
. groupLines
. map (lineType mq)
. map lineType
. lines
where
convert x = x { _qualified = mq <|> _qualified x}

View File

@ -9,11 +9,11 @@ main = defaultMain $ testGroup "Tests" [unitTests]
unitTests :: TestTree
unitTests = testGroup "Unit tests"
[ testCase "" $
lineType Nothing "not a module" @?= CodeLine "not a module"
lineType "not a module" @?= CodeLine "not a module"
, testCase "bare" $
lineType Nothing "import ModuleName" @?= ModuleLine (Module Nothing "ModuleName" Nothing Nothing)
lineType "import ModuleName" @?= ModuleLine (Module Nothing "ModuleName" Nothing Nothing)
, testCase "pre-qualified" $
lineType Nothing "import qualified ModuleName" @?= ModuleLine (Module (Just Qualified_Pre) "ModuleName" Nothing Nothing)
lineType "import qualified ModuleName" @?= ModuleLine (Module (Just Qualified_Pre) "ModuleName" Nothing Nothing)
, testCase "post-qualified" $
lineType Nothing "import ModuleName qualified as Mod" @?= ModuleLine (Module (Just Qualified_Post) "ModuleName" (Just "Mod") Nothing)
lineType "import ModuleName qualified as Mod" @?= ModuleLine (Module (Just Qualified_Post) "ModuleName" (Just "Mod") Nothing)
]