forked from haskell/haskell-language-server
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTypes.hs
532 lines (451 loc) · 22.2 KB
/
Types.hs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE CPP #-}
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE DefaultSignatures #-}
{-# LANGUAGE DeriveAnyClass #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE DerivingStrategies #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE NamedFieldPuns #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE PolyKinds #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE UndecidableInstances #-}
{-# LANGUAGE ViewPatterns #-}
module Ide.Types
where
#ifdef mingw32_HOST_OS
import qualified System.Win32.Process as P (getCurrentProcessId)
#else
import Control.Monad (void)
import qualified System.Posix.Process as P (getProcessID)
import System.Posix.Signals
#endif
import Control.Lens ((^.))
import Data.Aeson hiding (defaultOptions)
import qualified Data.DList as DList
import qualified Data.Default
import Data.Dependent.Map (DMap)
import qualified Data.Dependent.Map as DMap
import Data.GADT.Compare
import Data.List.NonEmpty (NonEmpty (..), toList)
import qualified Data.Map as Map
import Data.Maybe
import Data.Semigroup
import Data.String
import qualified Data.Text as T
import Data.Text.Encoding (encodeUtf8)
import Development.IDE.Graph
import GHC (DynFlags)
import GHC.Generics
import Ide.Plugin.Config
import Ide.Plugin.Properties
import Language.LSP.Server (LspM, getVirtualFile)
import Language.LSP.Types hiding
(SemanticTokenAbsolute (length, line),
SemanticTokenRelative (length),
SemanticTokensEdit (_start))
import Language.LSP.Types.Capabilities (ClientCapabilities (ClientCapabilities),
TextDocumentClientCapabilities (_codeAction, _documentSymbol))
import Language.LSP.Types.Lens as J (HasChildren (children),
HasCommand (command),
HasContents (contents),
HasDeprecated (deprecated),
HasEdit (edit),
HasKind (kind),
HasName (name),
HasOptions (..),
HasRange (range),
HasTextDocument (..),
HasTitle (title),
HasUri (..))
import Language.LSP.VFS
import OpenTelemetry.Eventlog
import Options.Applicative (ParserInfo)
import System.IO.Unsafe
import Text.Regex.TDFA.Text ()
-- ---------------------------------------------------------------------
newtype IdePlugins ideState = IdePlugins
{ ipMap :: [(PluginId, PluginDescriptor ideState)]}
deriving newtype (Monoid, Semigroup)
-- | Hooks for modifying the 'DynFlags' at different times of the compilation
-- process. Plugins can install a 'DynFlagsModifications' via
-- 'pluginModifyDynflags' in their 'PluginDescriptor'.
data DynFlagsModifications =
DynFlagsModifications
{ -- | Invoked immediately at the package level. Changes to the 'DynFlags'
-- made in 'dynFlagsModifyGlobal' are guaranteed to be seen everywhere in
-- the compilation pipeline.
dynFlagsModifyGlobal :: DynFlags -> DynFlags
-- | Invoked just before the parsing step, and reset immediately
-- afterwards. 'dynFlagsModifyParser' allows plugins to enable language
-- extensions only during parsing. for example, to let them enable
-- certain pieces of syntax.
, dynFlagsModifyParser :: DynFlags -> DynFlags
}
instance Semigroup DynFlagsModifications where
DynFlagsModifications g1 p1 <> DynFlagsModifications g2 p2 =
DynFlagsModifications (g2 . g1) (p2 . p1)
instance Monoid DynFlagsModifications where
mempty = DynFlagsModifications id id
-- ---------------------------------------------------------------------
newtype IdeCommand state = IdeCommand (state -> IO ())
instance Show (IdeCommand st) where show _ = "<ide command>"
-- ---------------------------------------------------------------------
data PluginDescriptor ideState =
PluginDescriptor { pluginId :: !PluginId
, pluginRules :: !(Rules ())
, pluginCommands :: ![PluginCommand ideState]
, pluginHandlers :: PluginHandlers ideState
, pluginConfigDescriptor :: ConfigDescriptor
, pluginNotificationHandlers :: PluginNotificationHandlers ideState
, pluginModifyDynflags :: DynFlagsModifications
, pluginCli :: Maybe (ParserInfo (IdeCommand ideState))
}
-- | An existential wrapper of 'Properties'
data CustomConfig = forall r. CustomConfig (Properties r)
-- | Describes the configuration a plugin.
-- A plugin may be configurable in such form:
-- @
-- {
-- "plugin-id": {
-- "globalOn": true,
-- "codeActionsOn": true,
-- "codeLensOn": true,
-- "config": {
-- "property1": "foo"
-- }
-- }
-- }
-- @
-- @globalOn@, @codeActionsOn@, and @codeLensOn@ etc. are called generic configs,
-- which can be inferred from handlers registered by the plugin.
-- @config@ is called custom config, which is defined using 'Properties'.
data ConfigDescriptor = ConfigDescriptor {
-- | Whether or not to generate generic configs.
configEnableGenericConfig :: Bool,
-- | Whether or not to generate @diagnosticsOn@ config.
-- Diagnostics emit in arbitrary shake rules,
-- so we can't know statically if the plugin produces diagnostics
configHasDiagnostics :: Bool,
-- | Custom config.
configCustomConfig :: CustomConfig
}
mkCustomConfig :: Properties r -> CustomConfig
mkCustomConfig = CustomConfig
defaultConfigDescriptor :: ConfigDescriptor
defaultConfigDescriptor = ConfigDescriptor True False (mkCustomConfig emptyProperties)
-- | Methods that can be handled by plugins.
-- 'ExtraParams' captures any extra data the IDE passes to the handlers for this method
-- Only methods for which we know how to combine responses can be instances of 'PluginMethod'
class HasTracing (MessageParams m) => PluginMethod m where
-- | Parse the configuration to check if this plugin is enabled
pluginEnabled :: SMethod m -> PluginId -> Config -> Bool
-- | How to combine responses from different plugins
combineResponses
:: SMethod m
-> Config -- ^ IDE Configuration
-> ClientCapabilities
-> MessageParams m
-> NonEmpty (ResponseResult m) -> ResponseResult m
default combineResponses :: Semigroup (ResponseResult m)
=> SMethod m -> Config -> ClientCapabilities -> MessageParams m -> NonEmpty (ResponseResult m) -> ResponseResult m
combineResponses _method _config _caps _params = sconcat
instance PluginMethod TextDocumentCodeAction where
pluginEnabled _ = pluginEnabledConfig plcCodeActionsOn
combineResponses _method _config (ClientCapabilities _ textDocCaps _ _ _) (CodeActionParams _ _ _ _ context) resps =
fmap compat $ List $ filter wasRequested $ (\(List x) -> x) $ sconcat resps
where
compat :: (Command |? CodeAction) -> (Command |? CodeAction)
compat x@(InL _) = x
compat x@(InR action)
| Just _ <- textDocCaps >>= _codeAction >>= _codeActionLiteralSupport
= x
| otherwise = InL cmd
where
cmd = mkLspCommand "hls" "fallbackCodeAction" (action ^. title) (Just cmdParams)
cmdParams = [toJSON (FallbackCodeActionParams (action ^. edit) (action ^. command))]
wasRequested :: (Command |? CodeAction) -> Bool
wasRequested (InL _) = True
wasRequested (InR ca)
| Nothing <- _only context = True
| Just (List allowed) <- _only context
-- See https://github.com/microsoft/language-server-protocol/issues/970
-- This is somewhat vague, but due to the hierarchical nature of action kinds, we
-- should check whether the requested kind is a *prefix* of the action kind.
-- That means, for example, we will return actions with kinds `quickfix.import` and
-- `quickfix.somethingElse` if the requested kind is `quickfix`.
-- TODO: add helpers in `lsp` for handling code action hierarchies
-- For now we abuse the fact that the JSON representation gives us the hierarchical string.
, Just caKind <- ca ^. kind
, String caKindStr <- toJSON caKind =
any (\k -> k `T.isPrefixOf` caKindStr) [kstr | k <- allowed, let String kstr = toJSON k ]
| otherwise = False
instance PluginMethod TextDocumentCodeLens where
pluginEnabled _ = pluginEnabledConfig plcCodeLensOn
instance PluginMethod TextDocumentRename where
pluginEnabled _ = pluginEnabledConfig plcRenameOn
instance PluginMethod TextDocumentHover where
pluginEnabled _ = pluginEnabledConfig plcHoverOn
combineResponses _ _ _ _ (catMaybes . toList -> hs) = h
where
r = listToMaybe $ mapMaybe (^. range) hs
h = case foldMap (^. contents) hs of
HoverContentsMS (List []) -> Nothing
hh -> Just $ Hover hh r
instance PluginMethod TextDocumentDocumentSymbol where
pluginEnabled _ = pluginEnabledConfig plcSymbolsOn
combineResponses _ _ (ClientCapabilities _ tdc _ _ _) params xs = res
where
uri' = params ^. textDocument . uri
supportsHierarchy = Just True == (tdc >>= _documentSymbol >>= _hierarchicalDocumentSymbolSupport)
dsOrSi = fmap toEither xs
res
| supportsHierarchy = InL $ sconcat $ fmap (either id (fmap siToDs)) dsOrSi
| otherwise = InR $ sconcat $ fmap (either (List . concatMap dsToSi) id) dsOrSi
siToDs (SymbolInformation name kind _tags dep (Location _uri range) cont)
= DocumentSymbol name cont kind Nothing dep range range Nothing
dsToSi = go Nothing
go :: Maybe T.Text -> DocumentSymbol -> [SymbolInformation]
go parent ds =
let children' :: [SymbolInformation]
children' = concatMap (go (Just name')) (fromMaybe mempty (ds ^. children))
loc = Location uri' (ds ^. range)
name' = ds ^. name
si = SymbolInformation name' (ds ^. kind) Nothing (ds ^. deprecated) loc parent
in [si] <> children'
instance PluginMethod TextDocumentCompletion where
pluginEnabled _ = pluginEnabledConfig plcCompletionOn
combineResponses _ conf _ _ (toList -> xs) = snd $ consumeCompletionResponse limit $ combine xs
where
limit = maxCompletions conf
combine :: [List CompletionItem |? CompletionList] -> (List CompletionItem |? CompletionList)
combine cs = go True mempty cs
go !comp acc [] =
InR (CompletionList comp (List $ DList.toList acc))
go comp acc (InL (List ls) : rest) =
go comp (acc <> DList.fromList ls) rest
go comp acc (InR (CompletionList comp' (List ls)) : rest) =
go (comp && comp') (acc <> DList.fromList ls) rest
-- boolean disambiguators
isCompleteResponse, isIncompleteResponse :: Bool
isIncompleteResponse = True
isCompleteResponse = False
consumeCompletionResponse limit it@(InR (CompletionList _ (List xx))) =
case splitAt limit xx of
-- consumed all the items, return the result as is
(_, []) -> (limit - length xx, it)
-- need to crop the response, set the 'isIncomplete' flag
(xx', _) -> (0, InR (CompletionList isIncompleteResponse (List xx')))
consumeCompletionResponse n (InL (List xx)) =
consumeCompletionResponse n (InR (CompletionList isCompleteResponse (List xx)))
instance PluginMethod TextDocumentFormatting where
pluginEnabled _ pid conf = (PluginId $ formattingProvider conf) == pid
combineResponses _ _ _ _ (x :| _) = x
instance PluginMethod TextDocumentRangeFormatting where
pluginEnabled _ pid conf = (PluginId $ formattingProvider conf) == pid
combineResponses _ _ _ _ (x :| _) = x
instance PluginMethod TextDocumentPrepareCallHierarchy where
pluginEnabled _ = pluginEnabledConfig plcCallHierarchyOn
instance PluginMethod CallHierarchyIncomingCalls where
pluginEnabled _ = pluginEnabledConfig plcCallHierarchyOn
instance PluginMethod CallHierarchyOutgoingCalls where
pluginEnabled _ = pluginEnabledConfig plcCallHierarchyOn
instance PluginMethod CustomMethod where
pluginEnabled _ _ _ = True
combineResponses _ _ _ _ (x :| _) = x
-- ---------------------------------------------------------------------
-- | Methods which have a PluginMethod instance
data IdeMethod (m :: Method FromClient Request) = PluginMethod m => IdeMethod (SMethod m)
instance GEq IdeMethod where
geq (IdeMethod a) (IdeMethod b) = geq a b
instance GCompare IdeMethod where
gcompare (IdeMethod a) (IdeMethod b) = gcompare a b
-- | Methods which have a PluginMethod instance
data IdeNotification (m :: Method FromClient Notification) = HasTracing (MessageParams m) => IdeNotification (SMethod m)
instance GEq IdeNotification where
geq (IdeNotification a) (IdeNotification b) = geq a b
instance GCompare IdeNotification where
gcompare (IdeNotification a) (IdeNotification b) = gcompare a b
-- | Combine handlers for the
newtype PluginHandler a (m :: Method FromClient Request)
= PluginHandler (PluginId -> a -> MessageParams m -> LspM Config (NonEmpty (Either ResponseError (ResponseResult m))))
newtype PluginNotificationHandler a (m :: Method FromClient Notification)
= PluginNotificationHandler (PluginId -> a -> MessageParams m -> LspM Config ())
newtype PluginHandlers a = PluginHandlers (DMap IdeMethod (PluginHandler a))
newtype PluginNotificationHandlers a = PluginNotificationHandlers (DMap IdeNotification (PluginNotificationHandler a))
instance Semigroup (PluginHandlers a) where
(PluginHandlers a) <> (PluginHandlers b) = PluginHandlers $ DMap.unionWithKey go a b
where
go _ (PluginHandler f) (PluginHandler g) = PluginHandler $ \pid ide params ->
(<>) <$> f pid ide params <*> g pid ide params
instance Monoid (PluginHandlers a) where
mempty = PluginHandlers mempty
instance Semigroup (PluginNotificationHandlers a) where
(PluginNotificationHandlers a) <> (PluginNotificationHandlers b) = PluginNotificationHandlers $ DMap.unionWithKey go a b
where
go _ (PluginNotificationHandler f) (PluginNotificationHandler g) = PluginNotificationHandler $ \pid ide params ->
f pid ide params >> g pid ide params
instance Monoid (PluginNotificationHandlers a) where
mempty = PluginNotificationHandlers mempty
type PluginMethodHandler a m = a -> PluginId -> MessageParams m -> LspM Config (Either ResponseError (ResponseResult m))
type PluginNotificationMethodHandler a m = a -> PluginId -> MessageParams m -> LspM Config ()
-- | Make a handler for plugins with no extra data
mkPluginHandler
:: PluginMethod m
=> SClientMethod m
-> PluginMethodHandler ideState m
-> PluginHandlers ideState
mkPluginHandler m f = PluginHandlers $ DMap.singleton (IdeMethod m) (PluginHandler f')
where
f' pid ide params = pure <$> f ide pid params
-- | Make a handler for plugins with no extra data
mkPluginNotificationHandler
:: HasTracing (MessageParams m)
=> SClientMethod (m :: Method FromClient Notification)
-> PluginNotificationMethodHandler ideState m
-> PluginNotificationHandlers ideState
mkPluginNotificationHandler m f
= PluginNotificationHandlers $ DMap.singleton (IdeNotification m) (PluginNotificationHandler f')
where
f' pid ide = f ide pid
defaultPluginDescriptor :: PluginId -> PluginDescriptor ideState
defaultPluginDescriptor plId =
PluginDescriptor
plId
mempty
mempty
mempty
defaultConfigDescriptor
mempty
mempty
Nothing
newtype CommandId = CommandId T.Text
deriving (Show, Read, Eq, Ord)
instance IsString CommandId where
fromString = CommandId . T.pack
data PluginCommand ideState = forall a. (FromJSON a) =>
PluginCommand { commandId :: CommandId
, commandDesc :: T.Text
, commandFunc :: CommandFunction ideState a
}
-- ---------------------------------------------------------------------
type CommandFunction ideState a
= ideState
-> a
-> LspM Config (Either ResponseError Value)
-- ---------------------------------------------------------------------
newtype PluginId = PluginId T.Text
deriving (Show, Read, Eq, Ord)
instance IsString PluginId where
fromString = PluginId . T.pack
configForPlugin :: Config -> PluginId -> PluginConfig
configForPlugin config (PluginId plugin)
= Map.findWithDefault Data.Default.def plugin (plugins config)
-- | Checks that a given plugin is both enabled and the specific feature is
-- enabled
pluginEnabledConfig :: (PluginConfig -> Bool) -> PluginId -> Config -> Bool
pluginEnabledConfig f pid config = plcGlobalOn pluginConfig && f pluginConfig
where
pluginConfig = configForPlugin config pid
-- ---------------------------------------------------------------------
-- | Format the given Text as a whole or only a @Range@ of it.
-- Range must be relative to the text to format.
-- To format the whole document, read the Text from the file and use 'FormatText'
-- as the FormattingType.
data FormattingType = FormatText
| FormatRange Range
type FormattingMethod m =
( J.HasOptions (MessageParams m) FormattingOptions
, J.HasTextDocument (MessageParams m) TextDocumentIdentifier
, ResponseResult m ~ List TextEdit
)
type FormattingHandler a
= a
-> FormattingType
-> T.Text
-> NormalizedFilePath
-> FormattingOptions
-> LspM Config (Either ResponseError (List TextEdit))
mkFormattingHandlers :: forall a. FormattingHandler a -> PluginHandlers a
mkFormattingHandlers f = mkPluginHandler STextDocumentFormatting (provider STextDocumentFormatting)
<> mkPluginHandler STextDocumentRangeFormatting (provider STextDocumentRangeFormatting)
where
provider :: forall m. FormattingMethod m => SMethod m -> PluginMethodHandler a m
provider m ide _pid params
| Just nfp <- uriToNormalizedFilePath $ toNormalizedUri uri = do
mf <- getVirtualFile $ toNormalizedUri uri
case mf of
Just vf -> do
let typ = case m of
STextDocumentFormatting -> FormatText
STextDocumentRangeFormatting -> FormatRange (params ^. J.range)
_ -> error "mkFormattingHandlers: impossible"
f ide typ (virtualFileText vf) nfp opts
Nothing -> pure $ Left $ responseError $ T.pack $ "Formatter plugin: could not get file contents for " ++ show uri
| otherwise = pure $ Left $ responseError $ T.pack $ "Formatter plugin: uriToFilePath failed for: " ++ show uri
where
uri = params ^. J.textDocument . J.uri
opts = params ^. J.options
-- ---------------------------------------------------------------------
responseError :: T.Text -> ResponseError
responseError txt = ResponseError InvalidParams txt Nothing
-- ---------------------------------------------------------------------
data FallbackCodeActionParams =
FallbackCodeActionParams
{ fallbackWorkspaceEdit :: Maybe WorkspaceEdit
, fallbackCommand :: Maybe Command
}
deriving (Generic, ToJSON, FromJSON)
-- ---------------------------------------------------------------------
otSetUri :: SpanInFlight -> Uri -> IO ()
otSetUri sp (Uri t) = setTag sp "uri" (encodeUtf8 t)
class HasTracing a where
traceWithSpan :: SpanInFlight -> a -> IO ()
traceWithSpan _ _ = pure ()
instance {-# OVERLAPPABLE #-} (HasTextDocument a doc, HasUri doc Uri) => HasTracing a where
traceWithSpan sp a = otSetUri sp (a ^. J.textDocument . J.uri)
instance HasTracing Value
instance HasTracing ExecuteCommandParams
instance HasTracing DidChangeWatchedFilesParams where
traceWithSpan sp DidChangeWatchedFilesParams{_changes} =
setTag sp "changes" (encodeUtf8 $ fromString $ show _changes)
instance HasTracing DidChangeWorkspaceFoldersParams
instance HasTracing DidChangeConfigurationParams
instance HasTracing InitializeParams
instance HasTracing (Maybe InitializedParams)
instance HasTracing WorkspaceSymbolParams where
traceWithSpan sp (WorkspaceSymbolParams _ _ query) = setTag sp "query" (encodeUtf8 query)
instance HasTracing CallHierarchyIncomingCallsParams
instance HasTracing CallHierarchyOutgoingCallsParams
-- ---------------------------------------------------------------------
{-# NOINLINE pROCESS_ID #-}
pROCESS_ID :: T.Text
pROCESS_ID = unsafePerformIO getPid
mkLspCommand :: PluginId -> CommandId -> T.Text -> Maybe [Value] -> Command
mkLspCommand plid cn title args' = Command title cmdId args
where
cmdId = mkLspCmdId pROCESS_ID plid cn
args = List <$> args'
mkLspCmdId :: T.Text -> PluginId -> CommandId -> T.Text
mkLspCmdId pid (PluginId plid) (CommandId cid)
= pid <> ":" <> plid <> ":" <> cid
-- | Get the operating system process id for the running server
-- instance. This should be the same for the lifetime of the instance,
-- and different from that of any other currently running instance.
getPid :: IO T.Text
getPid = T.pack . show <$> getProcessID
getProcessID :: IO Int
installSigUsr1Handler :: IO () -> IO ()
#ifdef mingw32_HOST_OS
getProcessID = fromIntegral <$> P.getCurrentProcessId
installSigUsr1Handler _ = return ()
#else
getProcessID = fromIntegral <$> P.getProcessID
installSigUsr1Handler h = void $ installHandler sigUSR1 (Catch h) Nothing
#endif