Skip to content

support add-argument action #3149

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 20 commits into from
Nov 6, 2022
Merged
Show file tree
Hide file tree
Changes from 14 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
1 change: 1 addition & 0 deletions CODEOWNERS
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
/plugins/hls-qualify-imported-names-plugin @eddiemundo
/plugins/hls-refine-imports-plugin
/plugins/hls-rename-plugin @OliverMadine
/plugins/hls-refactor-plugin @santiweight
/plugins/hls-retrie-plugin @pepeiborra
/plugins/hls-code-range-plugin @kokobd
/plugins/hls-splice-plugin @konn
Expand Down
8 changes: 8 additions & 0 deletions docs/features.md
Original file line number Diff line number Diff line change
Expand Up @@ -271,6 +271,14 @@ Known Limitations:

![Link to Docs](../plugins/hls-change-type-signature-plugin/README.md)

### Add argument to function

Provided by: `hls-refactor-plugin`

Code action kind: `quickfix`

Add an undefined variable as an argument to the top-level binding.

### Convert to GADT syntax

Provided by: `hls-gadt-plugin`
Expand Down
5 changes: 5 additions & 0 deletions ghcide/src/Development/IDE/GHC/Error.hs
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ module Development.IDE.GHC.Error
, zeroSpan
, realSpan
, isInsideSrcSpan
, spanContainsRange
, noSpan

-- * utilities working with severities
Expand All @@ -43,6 +44,7 @@ import Development.IDE.GHC.Orphans ()
import Development.IDE.Types.Diagnostics as D
import Development.IDE.Types.Location
import GHC
import Language.LSP.Types (isSubrangeOf)


diagFromText :: T.Text -> D.DiagnosticSeverity -> SrcSpan -> T.Text -> FileDiagnostic
Expand Down Expand Up @@ -119,6 +121,9 @@ p `isInsideSrcSpan` r = case srcSpanToRange r of
Just (Range sp ep) -> sp <= p && p <= ep
_ -> False

spanContainsRange :: SrcSpan -> Range -> Bool
spanContainsRange srcSpan range = maybe False (range `isSubrangeOf`) $ srcSpanToRange srcSpan
Copy link
Collaborator

Choose a reason for hiding this comment

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

I think this is clearer as a simple case

Suggested change
spanContainsRange srcSpan range = maybe False (range `isSubrangeOf`) $ srcSpanToRange srcSpan
spanContainsRange srcSpan range = case srcSpanToRange srcSpan of
Just r -> range `isSubrangeOf` r
-- Nice place to explain why this is the right policy
Nothing -> False

And having written it that way, I'm not sure whether we have got the right policy there. Do we want to return False in the "can't turn a src span into a range" case? Should we be returning a Maybe Bool and preserving that information?

Copy link
Collaborator

Choose a reason for hiding this comment

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

At the very least the Haddock should tell you that the returned bool includes this information!

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

I returned a Nothing and added a comment; I think it's clearer now...


-- | Convert a GHC severity to a DAML compiler Severity. Severities below
-- "Warning" level are dropped (returning Nothing).
toDSeverity :: GHC.Severity -> Maybe D.DiagnosticSeverity
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import qualified Data.Map.Strict as Map
import Data.Maybe (mapMaybe)
import Data.Text (Text)
import qualified Data.Text as Text
import Development.IDE (spanContainsRange)
import Development.IDE.Core.RuleTypes (GetFileContents (GetFileContents),
GetHieAst (GetHieAst),
HieAstResult (HAR, refMap),
Expand Down Expand Up @@ -87,16 +88,12 @@ descriptor pluginId = (defaultPluginDescriptor pluginId) {
]
}

isRangeWithinSrcSpan :: Range -> SrcSpan -> Bool
isRangeWithinSrcSpan (Range start end) srcSpan =
isInsideSrcSpan start srcSpan && isInsideSrcSpan end srcSpan

findLImportDeclAt :: Range -> ParsedModule -> Maybe (LImportDecl GhcPs)
findLImportDeclAt range parsedModule
| ParsedModule {..} <- parsedModule
, L _ hsModule <- pm_parsed_source
, locatedImportDecls <- hsmodImports hsModule =
find (\ (L (locA -> srcSpan) _) -> isRangeWithinSrcSpan range srcSpan) locatedImportDecls
find (\ (L (locA -> srcSpan) _) -> srcSpan `spanContainsRange` range) locatedImportDecls

makeCodeActions :: Uri -> [TextEdit] -> [a |? CodeAction]
makeCodeActions uri textEdits = [InR CodeAction {..} | not (null textEdits)]
Expand Down Expand Up @@ -132,7 +129,7 @@ data ImportedBy = ImportedBy {
}

isRangeWithinImportedBy :: Range -> ImportedBy -> Bool
isRangeWithinImportedBy range (ImportedBy _ srcSpan) = isRangeWithinSrcSpan range srcSpan
isRangeWithinImportedBy range (ImportedBy _ srcSpan) = spanContainsRange srcSpan range

globalRdrEnvToNameToImportedByMap :: GlobalRdrEnv -> NameEnv [ImportedBy]
globalRdrEnvToNameToImportedByMap =
Expand Down
2 changes: 2 additions & 0 deletions plugins/hls-refactor-plugin/hls-refactor-plugin.cabal
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,8 @@ test-suite tests
, extra
, text-rope
, containers
-- ghc is included to enable the MIN_VERSION_ghc macro
, ghc
, ghcide
, ghcide-test-utils
, shake
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,10 @@ module Development.IDE.GHC.ExactPrint
transform,
transformM,
ExactPrint(..),
#if MIN_VERSION_ghc(9,2,1)
modifySmallestDeclWithM,
modifyMgMatchesT,
#endif
#if !MIN_VERSION_ghc(9,2,0)
Anns,
Annotate,
Expand Down Expand Up @@ -114,10 +118,10 @@ instance Pretty Log where

instance Show (Annotated ParsedSource) where
show _ = "<Annotated ParsedSource>"

instance NFData (Annotated ParsedSource) where
rnf = rwhnf

data GetAnnotatedParsedSource = GetAnnotatedParsedSource
deriving (Eq, Show, Typeable, GHC.Generic)

Expand Down Expand Up @@ -430,6 +434,39 @@ graftDecls dst decs0 = Graft $ \dflags a -> do
| otherwise = DL.singleton (L src e) <> go rest
modifyDeclsT (pure . DL.toList . go) a

#if MIN_VERSION_ghc(9,2,1)
-- | Replace the smallest declaration whose SrcSpan satisfies the given condition with a new
-- list of declarations.
--
-- For example, if you would like to move a where-clause-defined variable to the same
-- level as its parent HsDecl, you could use this function.
modifySmallestDeclWithM ::
forall a.
(HasDecls a) =>
(SrcSpan -> Bool) ->
(LHsDecl GhcPs -> TransformT (Either String) [LHsDecl GhcPs]) ->
a ->
TransformT (Either String) a
modifySmallestDeclWithM validSpan f a = do
let modifyMatchingDecl [] = pure DL.empty
modifyMatchingDecl (e@(L src _) : rest)
| validSpan $ locA src = do
decs' <- f e
pure $ DL.fromList decs' <> DL.fromList rest
| otherwise = (DL.singleton e <>) <$> modifyMatchingDecl rest
modifyDeclsT (fmap DL.toList . modifyMatchingDecl) a

-- | Modify the each LMatch in a MatchGroup
modifyMgMatchesT ::
Monad m =>
MatchGroup GhcPs (LHsExpr GhcPs) ->
(LMatch GhcPs (LHsExpr GhcPs) -> TransformT m (LMatch GhcPs (LHsExpr GhcPs))) ->
TransformT m (MatchGroup GhcPs (LHsExpr GhcPs))
modifyMgMatchesT (MG xMg (L locMatches matches) originMg) f = do
matches' <- mapM f matches
pure $ MG xMg (L locMatches matches') originMg
#endif

graftSmallestDeclsWithM ::
forall a.
(HasDecls a) =>
Expand Down
123 changes: 97 additions & 26 deletions plugins/hls-refactor-plugin/src/Development/IDE/Plugin/CodeAction.hs
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ import Data.Ord (comparing)
import qualified Data.Set as S
import qualified Data.Text as T
import qualified Data.Text.Utf16.Rope as Rope
import Data.Tuple.Extra (first)
import Development.IDE.Core.Rules
import Development.IDE.Core.RuleTypes
import Development.IDE.Core.Service
Expand All @@ -63,7 +64,8 @@ import Development.IDE.Types.Logger hiding
import Development.IDE.Types.Options
import GHC.Exts (fromList)
import qualified GHC.LanguageExtensions as Lang
import Ide.PluginUtils (subRange)
import Ide.PluginUtils (makeDiffTextEdit,
subRange)
import Ide.Types
import qualified Language.LSP.Server as LSP
import Language.LSP.Types (ApplyWorkspaceEditParams (..),
Expand All @@ -89,6 +91,11 @@ import Language.LSP.VFS (VirtualFile,
import qualified Text.Fuzzy.Parallel as TFP
import Text.Regex.TDFA (mrAfter,
(=~), (=~~))
#if MIN_VERSION_ghc(9,2,1)
import GHC.Types.SrcLoc (generatedSrcSpan)
import Language.Haskell.GHC.ExactPrint (noAnnSrcSpanDP1,
runTransformT)
#endif
#if MIN_VERSION_ghc(9,2,0)
import GHC (AddEpAnn (AddEpAnn),
Anchor (anchor_op),
Expand Down Expand Up @@ -168,6 +175,9 @@ bindingsPluginDescriptor recorder plId = mkExactprintPluginDescriptor recorder $
, wrap suggestImplicitParameter
#endif
, wrap suggestNewDefinition
#if MIN_VERSION_ghc(9,2,1)
, wrap suggestAddArgument
#endif
, wrap suggestDeleteUnusedBinding
]
plId
Expand Down Expand Up @@ -243,7 +253,7 @@ extendImportHandler' ideState ExtendImport {..}
Nothing -> newThing
Just p -> p <> "(" <> newThing <> ")"
t <- liftMaybe $ snd <$> newImportToEdit n ps (fromMaybe "" contents)
return (nfp, WorkspaceEdit {_changes=Just (fromList [(doc,List [t])]), _documentChanges=Nothing, _changeAnnotations=Nothing})
return (nfp, WorkspaceEdit {_changes=Just (GHC.Exts.fromList [(doc,List [t])]), _documentChanges=Nothing, _changeAnnotations=Nothing})
| otherwise =
mzero

Expand Down Expand Up @@ -385,7 +395,7 @@ suggestHideShadow ps fileContents mTcM mHar Diagnostic {_message, _range}
Just matched <- allMatchRegexUnifySpaces _message "imported from ‘([^’]+)’ at ([^ ]*)",
mods <- [(modName, s) | [_, modName, s] <- matched],
result <- nubOrdBy (compare `on` fst) $ mods >>= uncurry (suggests identifier),
hideAll <- ("Hide " <> identifier <> " from all occurence imports", concat $ snd <$> result) =
hideAll <- ("Hide " <> identifier <> " from all occurence imports", concatMap snd result) =
result <> [hideAll]
| otherwise = []
where
Expand Down Expand Up @@ -881,34 +891,95 @@ suggestReplaceIdentifier contents Diagnostic{_range=_range,..}
= [ ("Replace with ‘" <> name <> "’", [mkRenameEdit contents _range name]) | name <- renameSuggestions ]
| otherwise = []

matchVariableNotInScope :: T.Text -> Maybe (T.Text, Maybe T.Text)
Copy link
Collaborator

Choose a reason for hiding this comment

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

Perhaps an annoying suggestion, but these matching functions are all nice pure functions that could benefit from some direct tests checking that they do definitely match all the cases you care about.

Copy link
Collaborator

Choose a reason for hiding this comment

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

Also, this module is also quite large, perhaps the add-action stuff could go in a separate module also?

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

I actually already did this in a followup MR. Would you be okay with following up with this change (to avoid unnecessary conflicts)?

matchVariableNotInScope message
-- * Variable not in scope:
-- suggestAcion :: Maybe T.Text -> Range -> Range
-- * Variable not in scope:
-- suggestAcion
| Just (name, typ) <- matchVariableNotInScopeTyped message = Just (name, Just typ)
| Just name <- matchVariableNotInScopeUntyped message = Just (name, Nothing)
| otherwise = Nothing
where
matchVariableNotInScopeTyped message
| Just [name, typ] <- matchRegexUnifySpaces message "Variable not in scope: ([^ ]+) :: ([^*•]+)" =
Just (name, typ)
| otherwise = Nothing
matchVariableNotInScopeUntyped message
| Just [name] <- matchRegexUnifySpaces message "Variable not in scope: ([^ ]+)" =
Just name
| otherwise = Nothing

matchFoundHole :: T.Text -> Maybe (T.Text, T.Text)
matchFoundHole message
| Just [name, typ] <- matchRegexUnifySpaces message "Found hole: _([^ ]+) :: ([^*•]+) Or perhaps" =
Just (name, typ)
| otherwise = Nothing

matchFoundHoleIncludeUnderscore :: T.Text -> Maybe (T.Text, T.Text)
matchFoundHoleIncludeUnderscore message = first ("_" <>) <$> matchFoundHole message

suggestNewDefinition :: IdeOptions -> ParsedModule -> Maybe T.Text -> Diagnostic -> [(T.Text, [TextEdit])]
suggestNewDefinition ideOptions parsedModule contents Diagnostic{_message, _range}
-- * Variable not in scope:
-- suggestAcion :: Maybe T.Text -> Range -> Range
| Just [name, typ] <- matchRegexUnifySpaces message "Variable not in scope: ([^ ]+) :: ([^*•]+)"
= newDefinitionAction ideOptions parsedModule _range name typ
| Just [name, typ] <- matchRegexUnifySpaces message "Found hole: _([^ ]+) :: ([^*•]+) Or perhaps"
, [(label, newDefinitionEdits)] <- newDefinitionAction ideOptions parsedModule _range name typ
= [(label, mkRenameEdit contents _range name : newDefinitionEdits)]
| otherwise = []
where
message = unifySpaces _message
suggestNewDefinition ideOptions parsedModule contents Diagnostic {_message, _range}
| Just (name, typ) <- matchVariableNotInScope message =
newDefinitionAction ideOptions parsedModule _range name typ
| Just (name, typ) <- matchFoundHole message,
Copy link
Collaborator

Choose a reason for hiding this comment

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

I think you have a Plan. Something like:

  • Look for errors of a particular kind
  • Based on the kind of error, make certain kinds of suggestion

But the Plan is not written down anywhere, and as a reader it's hard to figure out what it is. Maybe worth writing it down somewhere and referring to it?

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

Revised

[(label, newDefinitionEdits)] <- newDefinitionAction ideOptions parsedModule _range name (Just typ) =
[(label, mkRenameEdit contents _range name : newDefinitionEdits)]
| otherwise = []
where
message = unifySpaces _message

newDefinitionAction :: IdeOptions -> ParsedModule -> Range -> T.Text -> T.Text -> [(T.Text, [TextEdit])]
newDefinitionAction IdeOptions{..} parsedModule Range{_start} name typ
| Range _ lastLineP : _ <-
newDefinitionAction :: IdeOptions -> ParsedModule -> Range -> T.Text -> Maybe T.Text -> [(T.Text, [TextEdit])]
newDefinitionAction IdeOptions {..} parsedModule Range {_start} name typ
| Range _ lastLineP : _ <-
[ realSrcSpanToRange sp
| (L (locA -> l@(RealSrcSpan sp _)) _) <- hsmodDecls
, _start `isInsideSrcSpan` l]
, nextLineP <- Position{ _line = _line lastLineP + 1, _character = 0}
= [ ("Define " <> sig
, [TextEdit (Range nextLineP nextLineP) (T.unlines ["", sig, name <> " = _"])]
)]
| otherwise = []
| (L (locA -> l@(RealSrcSpan sp _)) _) <- hsmodDecls,
_start `isInsideSrcSpan` l
],
nextLineP <- Position {_line = _line lastLineP + 1, _character = 0} =
[ ( "Define " <> sig,
[TextEdit (Range nextLineP nextLineP) (T.unlines ["", sig, name <> " = _"])]
)
]
| otherwise = []
where
colon = if optNewColonConvention then " : " else " :: "
sig = name <> colon <> T.dropWhileEnd isSpace typ
ParsedModule{pm_parsed_source = L _ HsModule{hsmodDecls}} = parsedModule
sig = name <> colon <> T.dropWhileEnd isSpace (fromMaybe "_" typ)
ParsedModule {pm_parsed_source = L _ HsModule {hsmodDecls}} = parsedModule

#if MIN_VERSION_ghc(9,2,1)
suggestAddArgument :: ParsedModule -> Diagnostic -> Either ResponseError [(T.Text, [TextEdit])]
suggestAddArgument parsedModule Diagnostic {_message, _range}
| Just (name, typ) <- matchVariableNotInScope message = addArgumentAction parsedModule _range name typ
| Just (name, typ) <- matchFoundHoleIncludeUnderscore message = addArgumentAction parsedModule _range name (Just typ)
| otherwise = pure []
where
message = unifySpaces _message

-- TODO use typ to modify type signature
addArgumentAction :: ParsedModule -> Range -> T.Text -> Maybe T.Text -> Either ResponseError [(T.Text, [TextEdit])]
addArgumentAction (ParsedModule _ parsedSource _ _) range name _typ =
do
let addArgToMatch (L locMatch (Match xMatch ctxMatch pats rhs)) = do
let unqualName = mkRdrUnqual $ mkVarOcc $ T.unpack name
let newPat = L (noAnnSrcSpanDP1 generatedSrcSpan) $ VarPat NoExtField (noLocA unqualName)
pure $ L locMatch (Match xMatch ctxMatch (pats <> [newPat]) rhs)
insertArg = \case
(L locDecl (ValD xVal (FunBind xFunBind idFunBind mg coreFunBind))) -> do
mg' <- modifyMgMatchesT mg addArgToMatch
let decl' = L locDecl (ValD xVal (FunBind xFunBind idFunBind mg' coreFunBind))
pure [decl']
decl -> pure [decl]
case runTransformT $ modifySmallestDeclWithM (`spanContainsRange` range) insertArg (makeDeltaAst parsedSource) of
Left err -> Left $ responseError ("Error when inserting argument: " <> T.pack err)
Right (newSource, _, _) ->
let diff = makeDiffTextEdit (T.pack $ exactPrint parsedSource) (T.pack $ exactPrint newSource)
in pure [("Add argument ‘" <> name <> "’ to function", fromLspList diff)]
#endif

fromLspList :: List a -> [a]
fromLspList (List a) = a

suggestFillTypeWildcard :: Diagnostic -> [(T.Text, TextEdit)]
suggestFillTypeWildcard Diagnostic{_range=_range,..}
Expand Down
Loading