Skip to content

Fix hls-class-plugin on ghc-9.2 #2733

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 19 commits into from
Mar 6, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/workflows/test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -164,7 +164,7 @@ jobs:
name: Test hls-floskell-plugin
run: cabal test hls-floskell-plugin --test-options="$TEST_OPTS" || cabal test hls-floskell-plugin --test-options="$TEST_OPTS" || LSP_TEST_LOG_COLOR=0 LSP_TEST_LOG_MESSAGES=true LSP_TEST_LOG_STDERR=true cabal test hls-floskell-plugin --test-options="$TEST_OPTS"

- if: matrix.test && matrix.ghc != '9.2.1'
- if: matrix.test
name: Test hls-class-plugin
run: cabal test hls-class-plugin --test-options="$TEST_OPTS" || cabal test hls-class-plugin --test-options="$TEST_OPTS" || LSP_TEST_LOG_COLOR=0 LSP_TEST_LOG_MESSAGES=true LSP_TEST_LOG_STDERR=true cabal test hls-class-plugin --test-options="$TEST_OPTS"

Expand Down
1 change: 0 additions & 1 deletion cabal-ghc921.project
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,6 @@ constraints:
haskell-language-server
+ignore-plugins-ghc-bounds
-brittany
-class
-haddockComments
-hlint
-retrie
Expand Down
104 changes: 74 additions & 30 deletions plugins/hls-class-plugin/src/Ide/Plugin/Class.hs
Original file line number Diff line number Diff line change
Expand Up @@ -21,10 +21,11 @@ import Data.List
import qualified Data.Map.Strict as Map
import Data.Maybe
import qualified Data.Text as T
import qualified Data.Set as Set
import Development.IDE hiding (pluginHandlers)
import Development.IDE.Core.PositionMapping (fromCurrentRange,
toCurrentRange)
import Development.IDE.GHC.Compat
import Development.IDE.GHC.Compat as Compat hiding (locA)
import Development.IDE.GHC.Compat.Util
import Development.IDE.Spans.AtPoint
import qualified GHC.Generics as Generics
Expand All @@ -38,6 +39,11 @@ import Language.LSP.Server
import Language.LSP.Types
import qualified Language.LSP.Types.Lens as J

#if MIN_VERSION_ghc(9,2,0)
import GHC.Hs (AnnsModule(AnnsModule))
import GHC.Parser.Annotation
#endif

descriptor :: PluginId -> PluginDescriptor IdeState
descriptor plId = (defaultPluginDescriptor plId)
{ pluginCommands = commands
Expand All @@ -63,25 +69,78 @@ addMethodPlaceholders state AddMinimalMethodsParams{..} = do
medit <- liftIO $ runMaybeT $ do
docPath <- MaybeT . pure . uriToNormalizedFilePath $ toNormalizedUri uri
pm <- MaybeT . runAction "classplugin" state $ use GetParsedModule docPath
let
ps = pm_parsed_source pm
anns = relativiseApiAnns ps (pm_annotations pm)
old = T.pack $ exactPrint ps anns

(hsc_dflags . hscEnv -> df) <- MaybeT . runAction "classplugin" state $ use GhcSessionDeps docPath
List (unzip -> (mAnns, mDecls)) <- MaybeT . pure $ traverse (makeMethodDecl df) methodGroup
let
(ps', (anns', _), _) = runTransform (mergeAnns (mergeAnnList mAnns) anns) (addMethodDecls ps mDecls)
new = T.pack $ exactPrint ps' anns'

(old, new) <- makeEditText pm df
pure (workspaceEdit caps old new)

forM_ medit $ \edit ->
sendRequest SWorkspaceApplyEdit (ApplyWorkspaceEditParams Nothing edit) (\_ -> pure ())
pure (Right Null)
where

indent = 2

workspaceEdit caps old new
= diffText caps (uri, old) new IncludeDeletions

toMethodName n
| Just (h, _) <- T.uncons n
, not (isAlpha h || h == '_')
= "(" <> n <> ")"
| otherwise
= n

#if MIN_VERSION_ghc(9,2,0)
makeEditText pm df = do
List mDecls <- MaybeT . pure $ traverse (makeMethodDecl df) methodGroup
let ps = makeDeltaAst $ pm_parsed_source pm
old = T.pack $ exactPrint ps
(ps', _, _) = runTransform (addMethodDecls ps mDecls)
new = T.pack $ exactPrint ps'
pure (old, new)

makeMethodDecl df mName =
either (const Nothing) Just . parseDecl df (T.unpack mName) . T.unpack
$ toMethodName mName <> " = _"

addMethodDecls ps mDecls = do
allDecls <- hsDecls ps
let (before, ((L l inst): after)) = break (containRange range . getLoc) allDecls
replaceDecls ps (before ++ (L l (addWhere inst)): (map newLine mDecls ++ after))
where
-- Add `where` keyword for `instance X where` if `where` is missing.
--
-- The `where` in ghc-9.2 is now stored in the instance declaration
-- directly. More precisely, giving an `HsDecl GhcPs`, we have:
-- InstD --> ClsInstD --> ClsInstDecl --> XCClsInstDecl --> (EpAnn [AddEpAnn], AnnSortKey),
-- here `AnnEpAnn` keeps the track of Anns.
--
-- See the link for the original definition:
-- https://hackage.haskell.org/package/ghc-9.2.1/docs/Language-Haskell-Syntax-Extension.html#t:XCClsInstDecl
addWhere (InstD xInstD (ClsInstD ext decl@ClsInstDecl{..})) =
let ((EpAnn entry anns comments), key) = cid_ext
in InstD xInstD (ClsInstD ext decl {
cid_ext = (EpAnn
entry
(AddEpAnn AnnWhere (EpaDelta (SameLine 1) []) : anns)
comments
, key)
})
addWhere decl = decl
Comment on lines +119 to +128
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

can you add a brief comment explaining what this code does? It's kinda hard to read and therefore maintain

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Explained the effect of the function and the trace of the parameter.


newLine (L l e) =
let dp = deltaPos 1 (indent + 1) -- Not sure why there need one more space
in L (noAnnSrcSpanDP (locA l) dp <> l) e

#else
makeEditText pm df = do
List (unzip -> (mAnns, mDecls)) <- MaybeT . pure $ traverse (makeMethodDecl df) methodGroup
let ps = pm_parsed_source pm
anns = relativiseApiAnns ps (pm_annotations pm)
old = T.pack $ exactPrint ps anns
(ps', (anns', _), _) = runTransform (mergeAnns (mergeAnnList mAnns) anns) (addMethodDecls ps mDecls)
new = T.pack $ exactPrint ps' anns'
pure (old, new)

makeMethodDecl df mName =
case parseDecl df (T.unpack mName) . T.unpack $ toMethodName mName <> " = _" of
Right (ann, d) -> Just (setPrecedingLines d 1 indent ann, d)
Expand Down Expand Up @@ -112,16 +171,7 @@ addMethodPlaceholders state AddMinimalMethodsParams{..} = do

findInstDecl :: ParsedSource -> Transform (LHsDecl GhcPs)
findInstDecl ps = head . filter (containRange range . getLoc) <$> hsDecls ps

workspaceEdit caps old new
= diffText caps (uri, old) new IncludeDeletions

toMethodName n
| Just (h, _) <- T.uncons n
, not (isAlpha h || h == '_')
= "(" <> n <> ")"
| otherwise
= n
#endif

-- |
-- This implementation is ad-hoc in a sense that the diagnostic detection mechanism is
Expand Down Expand Up @@ -169,15 +219,9 @@ codeAction state plId (CodeActionParams _ _ docId _ context) = liftIO $ fmap (fr
pure
$ head . head
$ pointCommand hf (fromJust (fromCurrentRange pmap range) ^. J.start & J.character -~ 1)
#if !MIN_VERSION_ghc(9,0,0)
( (Map.keys . Map.filter isClassNodeIdentifier . nodeIdentifiers . nodeInfo)
( (Map.keys . Map.filter isClassNodeIdentifier . Compat.getNodeIds)
<=< nodeChildren
)
#else
( (Map.keys . Map.filter isClassNodeIdentifier . sourcedNodeIdents . sourcedNodeInfo)
<=< nodeChildren
)
#endif

findClassFromIdentifier docPath (Right name) = do
(hscEnv -> hscenv, _) <- MaybeT . runAction "classplugin" state $ useWithStale GhcSessionDeps docPath
Expand All @@ -197,7 +241,7 @@ containRange :: Range -> SrcSpan -> Bool
containRange range x = isInsideSrcSpan (range ^. J.start) x || isInsideSrcSpan (range ^. J.end) x

isClassNodeIdentifier :: IdentifierDetails a -> Bool
isClassNodeIdentifier = isNothing . identType
isClassNodeIdentifier ident = (isNothing . identType) ident && Use `Set.member` (identInfo ident)

isClassMethodWarning :: T.Text -> Bool
isClassMethodWarning = T.isPrefixOf "• No explicit implementation for"
Expand Down
3 changes: 3 additions & 0 deletions plugins/hls-class-plugin/test/Main.hs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
{-# LANGUAGE TypeOperators #-}

{-# OPTIONS_GHC -Wall #-}
{-# OPTIONS_GHC -Wno-incomplete-uni-patterns #-}
module Main
( main
) where
Expand Down Expand Up @@ -45,6 +46,8 @@ tests = testGroup
executeCodeAction mmAction
, goldenWithClass "Creates a placeholder for a method starting with '_'" "T4" "" $ \(_fAction:_) -> do
executeCodeAction _fAction
, goldenWithClass "Creates a placeholder for '==' with extra lines" "T5" "" $ \(eqAction:_) -> do
executeCodeAction eqAction
]

_CACodeAction :: Prism' (Command |? CodeAction) CodeAction
Expand Down
8 changes: 8 additions & 0 deletions plugins/hls-class-plugin/test/testdata/T5.expected.hs
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
module T1 where

data X = X

instance Eq X where
(==) = _

x = ()
7 changes: 7 additions & 0 deletions plugins/hls-class-plugin/test/testdata/T5.hs
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
module T1 where

data X = X

instance Eq X where

x = ()
3 changes: 1 addition & 2 deletions stack-9.2.1.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ packages:
- ./hls-test-utils
- ./shake-bench
- ./plugins/hls-call-hierarchy-plugin
# - ./plugins/hls-class-plugin
- ./plugins/hls-class-plugin
# - ./plugins/hls-haddock-comments-plugin
# - ./plugins/hls-eval-plugin
- ./plugins/hls-explicit-imports-plugin
Expand Down Expand Up @@ -116,7 +116,6 @@ flags:
ignore-plugins-ghc-bounds: true
alternateNumberFormat: false
brittany: false
class: false
eval: false
haddockComments: false
hlint: false
Expand Down