-
Notifications
You must be signed in to change notification settings - Fork 234
/
Copy pathLanguageServer.cs
1216 lines (1043 loc) · 47.4 KB
/
LanguageServer.cs
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
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
using Microsoft.PowerShell.EditorServices.Extensions;
using Microsoft.PowerShell.EditorServices.Protocol.LanguageServer;
using Microsoft.PowerShell.EditorServices.Protocol.MessageProtocol;
using Microsoft.PowerShell.EditorServices.Protocol.MessageProtocol.Channel;
using Microsoft.PowerShell.EditorServices.Session;
using Microsoft.PowerShell.EditorServices.Utility;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Management.Automation;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using DebugAdapterMessages = Microsoft.PowerShell.EditorServices.Protocol.DebugAdapter;
namespace Microsoft.PowerShell.EditorServices.Protocol.Server
{
public class LanguageServer : LanguageServerBase
{
private static CancellationTokenSource existingRequestCancellation;
private bool profilesLoaded;
private EditorSession editorSession;
private OutputDebouncer outputDebouncer;
private LanguageServerEditorOperations editorOperations;
private LanguageServerSettings currentSettings = new LanguageServerSettings();
/// <param name="hostDetails">
/// Provides details about the host application.
/// </param>
public LanguageServer(HostDetails hostDetails, ProfilePaths profilePaths)
: this(hostDetails, profilePaths, new StdioServerChannel())
{
}
/// <param name="hostDetails">
/// Provides details about the host application.
/// </param>
public LanguageServer(HostDetails hostDetails, ProfilePaths profilePaths, ChannelBase serverChannel)
: base(serverChannel)
{
this.editorSession = new EditorSession();
this.editorSession.StartSession(hostDetails, profilePaths);
this.editorSession.ConsoleService.OutputWritten += this.powerShellContext_OutputWritten;
// Attach to ExtensionService events
this.editorSession.ExtensionService.CommandAdded += ExtensionService_ExtensionAdded;
this.editorSession.ExtensionService.CommandUpdated += ExtensionService_ExtensionUpdated;
this.editorSession.ExtensionService.CommandRemoved += ExtensionService_ExtensionRemoved;
// Create the IEditorOperations implementation
this.editorOperations =
new LanguageServerEditorOperations(
this.editorSession,
this);
// Always send console prompts through the UI in the language service
// TODO: This will change later once we have a general REPL available
// in VS Code.
this.editorSession.ConsoleService.PushPromptHandlerContext(
new ProtocolPromptHandlerContext(
this,
this.editorSession.ConsoleService));
// Set up the output debouncer to throttle output event writes
this.outputDebouncer = new OutputDebouncer(this);
}
protected override void Initialize()
{
// Register all supported message types
this.SetRequestHandler(InitializeRequest.Type, this.HandleInitializeRequest);
this.SetEventHandler(DidOpenTextDocumentNotification.Type, this.HandleDidOpenTextDocumentNotification);
this.SetEventHandler(DidCloseTextDocumentNotification.Type, this.HandleDidCloseTextDocumentNotification);
this.SetEventHandler(DidChangeTextDocumentNotification.Type, this.HandleDidChangeTextDocumentNotification);
this.SetEventHandler(DidChangeConfigurationNotification<LanguageServerSettingsWrapper>.Type, this.HandleDidChangeConfigurationNotification);
this.SetRequestHandler(DefinitionRequest.Type, this.HandleDefinitionRequest);
this.SetRequestHandler(ReferencesRequest.Type, this.HandleReferencesRequest);
this.SetRequestHandler(CompletionRequest.Type, this.HandleCompletionRequest);
this.SetRequestHandler(CompletionResolveRequest.Type, this.HandleCompletionResolveRequest);
this.SetRequestHandler(SignatureHelpRequest.Type, this.HandleSignatureHelpRequest);
this.SetRequestHandler(DocumentHighlightRequest.Type, this.HandleDocumentHighlightRequest);
this.SetRequestHandler(HoverRequest.Type, this.HandleHoverRequest);
this.SetRequestHandler(DocumentSymbolRequest.Type, this.HandleDocumentSymbolRequest);
this.SetRequestHandler(WorkspaceSymbolRequest.Type, this.HandleWorkspaceSymbolRequest);
this.SetRequestHandler(ShowOnlineHelpRequest.Type, this.HandleShowOnlineHelpRequest);
this.SetRequestHandler(ExpandAliasRequest.Type, this.HandleExpandAliasRequest);
this.SetRequestHandler(FindModuleRequest.Type, this.HandleFindModuleRequest);
this.SetRequestHandler(InstallModuleRequest.Type, this.HandleInstallModuleRequest);
this.SetRequestHandler(InvokeExtensionCommandRequest.Type, this.HandleInvokeExtensionCommandRequest);
this.SetRequestHandler(DebugAdapterMessages.EvaluateRequest.Type, this.HandleEvaluateRequest);
// Initialize the extension service
// TODO: This should be made awaited once Initialize is async!
this.editorSession.ExtensionService.Initialize(
this.editorOperations).Wait();
}
protected override async Task Shutdown()
{
// Make sure remaining output is flushed before exiting
await this.outputDebouncer.Flush();
Logger.Write(LogLevel.Normal, "Language service is shutting down...");
if (this.editorSession != null)
{
this.editorSession.Dispose();
this.editorSession = null;
}
}
#region Built-in Message Handlers
protected async Task HandleInitializeRequest(
InitializeRequest initializeParams,
RequestContext<InitializeResult> requestContext)
{
// Grab the workspace path from the parameters
editorSession.Workspace.WorkspacePath = initializeParams.RootPath;
await requestContext.SendResult(
new InitializeResult
{
Capabilities = new ServerCapabilities
{
TextDocumentSync = TextDocumentSyncKind.Incremental,
DefinitionProvider = true,
ReferencesProvider = true,
DocumentHighlightProvider = true,
DocumentSymbolProvider = true,
WorkspaceSymbolProvider = true,
HoverProvider = true,
CompletionProvider = new CompletionOptions
{
ResolveProvider = true,
TriggerCharacters = new string[] { ".", "-", ":", "\\" }
},
SignatureHelpProvider = new SignatureHelpOptions
{
TriggerCharacters = new string[] { " " } // TODO: Other characters here?
}
}
});
}
protected async Task HandleShowOnlineHelpRequest(
string helpParams,
RequestContext<object> requestContext)
{
if (helpParams == null) { helpParams = "get-help"; }
var psCommand = new PSCommand();
psCommand.AddCommand("Get-Help");
psCommand.AddArgument(helpParams);
psCommand.AddParameter("Online");
await editorSession.PowerShellContext.ExecuteCommand<object>(psCommand);
await requestContext.SendResult(null);
}
private async Task HandleInstallModuleRequest(
string moduleName,
RequestContext<object> requestContext
)
{
var script = string.Format("Install-Module -Name {0} -Scope CurrentUser", moduleName);
var executeTask =
editorSession.PowerShellContext.ExecuteScriptString(
script,
true,
true).ConfigureAwait(false);
await requestContext.SendResult(null);
}
private Task HandleInvokeExtensionCommandRequest(
InvokeExtensionCommandRequest commandDetails,
RequestContext<string> requestContext)
{
// We don't await the result of the execution here because we want
// to be able to receive further messages while the editor command
// is executing. This important in cases where the pipeline thread
// gets blocked by something in the script like a prompt to the user.
EditorContext editorContext =
this.editorOperations.ConvertClientEditorContext(
commandDetails.Context);
Task commandTask =
this.editorSession.ExtensionService.InvokeCommand(
commandDetails.Name,
editorContext);
commandTask.ContinueWith(t =>
{
return requestContext.SendResult(null);
});
return Task.FromResult(true);
}
private async Task HandleExpandAliasRequest(
string content,
RequestContext<string> requestContext)
{
var script = @"
function __Expand-Alias {
param($targetScript)
[ref]$errors=$null
$tokens = [System.Management.Automation.PsParser]::Tokenize($targetScript, $errors).Where({$_.type -eq 'command'}) |
Sort Start -Descending
foreach ($token in $tokens) {
$definition=(Get-Command ('`'+$token.Content) -CommandType Alias -ErrorAction SilentlyContinue).Definition
if($definition) {
$lhs=$targetScript.Substring(0, $token.Start)
$rhs=$targetScript.Substring($token.Start + $token.Length)
$targetScript=$lhs + $definition + $rhs
}
}
$targetScript
}";
var psCommand = new PSCommand();
psCommand.AddScript(script);
await this.editorSession.PowerShellContext.ExecuteCommand<PSObject>(psCommand);
psCommand = new PSCommand();
psCommand.AddCommand("__Expand-Alias").AddArgument(content);
var result = await this.editorSession.PowerShellContext.ExecuteCommand<string>(psCommand);
await requestContext.SendResult(result.First().ToString());
}
private async Task HandleFindModuleRequest(
object param,
RequestContext<object> requestContext)
{
var psCommand = new PSCommand();
psCommand.AddScript("Find-Module | Select Name, Description");
var modules = await editorSession.PowerShellContext.ExecuteCommand<PSObject>(psCommand);
var moduleList = new List<PSModuleMessage>();
if (modules != null)
{
foreach (dynamic m in modules)
{
moduleList.Add(new PSModuleMessage { Name = m.Name, Description = m.Description });
}
}
await requestContext.SendResult(moduleList);
}
protected Task HandleDidOpenTextDocumentNotification(
DidOpenTextDocumentNotification openParams,
EventContext eventContext)
{
ScriptFile openedFile =
editorSession.Workspace.GetFileBuffer(
openParams.Uri,
openParams.Text);
// TODO: Get all recently edited files in the workspace
this.RunScriptDiagnostics(
new ScriptFile[] { openedFile },
editorSession,
eventContext);
Logger.Write(LogLevel.Verbose, "Finished opening document.");
return Task.FromResult(true);
}
protected Task HandleDidCloseTextDocumentNotification(
TextDocumentIdentifier closeParams,
EventContext eventContext)
{
// Find and close the file in the current session
var fileToClose = editorSession.Workspace.GetFile(closeParams.Uri);
if (fileToClose != null)
{
editorSession.Workspace.CloseFile(fileToClose);
}
Logger.Write(LogLevel.Verbose, "Finished closing document.");
return Task.FromResult(true);
}
protected Task HandleDidChangeTextDocumentNotification(
DidChangeTextDocumentParams textChangeParams,
EventContext eventContext)
{
List<ScriptFile> changedFiles = new List<ScriptFile>();
// A text change notification can batch multiple change requests
foreach (var textChange in textChangeParams.ContentChanges)
{
ScriptFile changedFile = editorSession.Workspace.GetFile(textChangeParams.Uri);
changedFile.ApplyChange(
GetFileChangeDetails(
textChange.Range.Value,
textChange.Text));
changedFiles.Add(changedFile);
}
// TODO: Get all recently edited files in the workspace
this.RunScriptDiagnostics(
changedFiles.ToArray(),
editorSession,
eventContext);
return Task.FromResult(true);
}
protected async Task HandleDidChangeConfigurationNotification(
DidChangeConfigurationParams<LanguageServerSettingsWrapper> configChangeParams,
EventContext eventContext)
{
bool oldLoadProfiles = this.currentSettings.EnableProfileLoading;
bool oldScriptAnalysisEnabled =
this.currentSettings.ScriptAnalysis.Enable.HasValue;
string oldScriptAnalysisSettingsPath =
this.currentSettings.ScriptAnalysis.SettingsPath;
this.currentSettings.Update(
configChangeParams.Settings.Powershell,
this.editorSession.Workspace.WorkspacePath);
if (!this.profilesLoaded &&
this.currentSettings.EnableProfileLoading &&
oldLoadProfiles != this.currentSettings.EnableProfileLoading)
{
await this.editorSession.PowerShellContext.LoadHostProfiles();
this.profilesLoaded = true;
}
// If there is a new settings file path, restart the analyzer with the new settigs.
bool settingsPathChanged = false;
string newSettingsPath = this.currentSettings.ScriptAnalysis.SettingsPath;
if (!string.Equals(oldScriptAnalysisSettingsPath, newSettingsPath, StringComparison.OrdinalIgnoreCase))
{
this.editorSession.AnalysisService.SettingsPath = newSettingsPath;
settingsPathChanged = true;
}
// If script analysis settings have changed we need to clear & possibly update the current diagnostic records.
if ((oldScriptAnalysisEnabled != this.currentSettings.ScriptAnalysis.Enable) || settingsPathChanged)
{
// If the user just turned off script analysis or changed the settings path, send a diagnostics
// event to clear the analysis markers that they already have.
if (!this.currentSettings.ScriptAnalysis.Enable.Value || settingsPathChanged)
{
ScriptFileMarker[] emptyAnalysisDiagnostics = new ScriptFileMarker[0];
foreach (var scriptFile in editorSession.Workspace.GetOpenedFiles())
{
await PublishScriptDiagnostics(
scriptFile,
emptyAnalysisDiagnostics,
eventContext);
}
}
// If script analysis is enabled and the settings file changed get new diagnostic records.
if (this.currentSettings.ScriptAnalysis.Enable.Value && settingsPathChanged)
{
await this.RunScriptDiagnostics(
this.editorSession.Workspace.GetOpenedFiles(),
this.editorSession,
eventContext);
}
}
}
protected async Task HandleDefinitionRequest(
TextDocumentPosition textDocumentPosition,
RequestContext<Location[]> requestContext)
{
ScriptFile scriptFile =
editorSession.Workspace.GetFile(
textDocumentPosition.Uri);
SymbolReference foundSymbol =
editorSession.LanguageService.FindSymbolAtLocation(
scriptFile,
textDocumentPosition.Position.Line + 1,
textDocumentPosition.Position.Character + 1);
List<Location> definitionLocations = new List<Location>();
GetDefinitionResult definition = null;
if (foundSymbol != null)
{
definition =
await editorSession.LanguageService.GetDefinitionOfSymbol(
scriptFile,
foundSymbol,
editorSession.Workspace);
if (definition != null)
{
definitionLocations.Add(
new Location
{
Uri = new Uri("file://" + definition.FoundDefinition.FilePath).AbsoluteUri,
Range = GetRangeFromScriptRegion(definition.FoundDefinition.ScriptRegion)
});
}
}
await requestContext.SendResult(definitionLocations.ToArray());
}
protected async Task HandleReferencesRequest(
ReferencesParams referencesParams,
RequestContext<Location[]> requestContext)
{
ScriptFile scriptFile =
editorSession.Workspace.GetFile(
referencesParams.Uri);
SymbolReference foundSymbol =
editorSession.LanguageService.FindSymbolAtLocation(
scriptFile,
referencesParams.Position.Line + 1,
referencesParams.Position.Character + 1);
FindReferencesResult referencesResult =
await editorSession.LanguageService.FindReferencesOfSymbol(
foundSymbol,
editorSession.Workspace.ExpandScriptReferences(scriptFile));
Location[] referenceLocations = null;
if (referencesResult != null)
{
referenceLocations =
referencesResult
.FoundReferences
.Select(r =>
{
return new Location
{
Uri = new Uri("file://" + r.FilePath).AbsoluteUri,
Range = GetRangeFromScriptRegion(r.ScriptRegion)
};
})
.ToArray();
}
else
{
referenceLocations = new Location[0];
}
await requestContext.SendResult(referenceLocations);
}
protected async Task HandleCompletionRequest(
TextDocumentPosition textDocumentPosition,
RequestContext<CompletionItem[]> requestContext)
{
int cursorLine = textDocumentPosition.Position.Line + 1;
int cursorColumn = textDocumentPosition.Position.Character + 1;
ScriptFile scriptFile =
editorSession.Workspace.GetFile(
textDocumentPosition.Uri);
CompletionResults completionResults =
await editorSession.LanguageService.GetCompletionsInFile(
scriptFile,
cursorLine,
cursorColumn);
CompletionItem[] completionItems = null;
if (completionResults != null)
{
int sortIndex = 1;
completionItems =
completionResults
.Completions
.Select(
c => CreateCompletionItem(
c,
completionResults.ReplacedRange,
sortIndex++))
.ToArray();
}
else
{
completionItems = new CompletionItem[0];
}
await requestContext.SendResult(completionItems);
}
protected async Task HandleCompletionResolveRequest(
CompletionItem completionItem,
RequestContext<CompletionItem> requestContext)
{
if (completionItem.Kind == CompletionItemKind.Function)
{
// Get the documentation for the function
CommandInfo commandInfo =
await CommandHelpers.GetCommandInfo(
completionItem.Label,
this.editorSession.PowerShellContext);
completionItem.Documentation =
await CommandHelpers.GetCommandSynopsis(
commandInfo,
this.editorSession.PowerShellContext);
}
// Send back the updated CompletionItem
await requestContext.SendResult(completionItem);
}
protected async Task HandleSignatureHelpRequest(
TextDocumentPosition textDocumentPosition,
RequestContext<SignatureHelp> requestContext)
{
ScriptFile scriptFile =
editorSession.Workspace.GetFile(
textDocumentPosition.Uri);
ParameterSetSignatures parameterSets =
await editorSession.LanguageService.FindParameterSetsInFile(
scriptFile,
textDocumentPosition.Position.Line + 1,
textDocumentPosition.Position.Character + 1);
SignatureInformation[] signatures = null;
int? activeParameter = null;
int? activeSignature = 0;
if (parameterSets != null)
{
signatures =
parameterSets
.Signatures
.Select(s =>
{
return new SignatureInformation
{
Label = parameterSets.CommandName + " " + s.SignatureText,
Documentation = null,
Parameters =
s.Parameters
.Select(CreateParameterInfo)
.ToArray()
};
})
.ToArray();
}
else
{
signatures = new SignatureInformation[0];
}
await requestContext.SendResult(
new SignatureHelp
{
Signatures = signatures,
ActiveParameter = activeParameter,
ActiveSignature = activeSignature
});
}
protected async Task HandleDocumentHighlightRequest(
TextDocumentPosition textDocumentPosition,
RequestContext<DocumentHighlight[]> requestContext)
{
ScriptFile scriptFile =
editorSession.Workspace.GetFile(
textDocumentPosition.Uri);
FindOccurrencesResult occurrencesResult =
editorSession.LanguageService.FindOccurrencesInFile(
scriptFile,
textDocumentPosition.Position.Line + 1,
textDocumentPosition.Position.Character + 1);
DocumentHighlight[] documentHighlights = null;
if (occurrencesResult != null)
{
documentHighlights =
occurrencesResult
.FoundOccurrences
.Select(o =>
{
return new DocumentHighlight
{
Kind = DocumentHighlightKind.Write, // TODO: Which symbol types are writable?
Range = GetRangeFromScriptRegion(o.ScriptRegion)
};
})
.ToArray();
}
else
{
documentHighlights = new DocumentHighlight[0];
}
await requestContext.SendResult(documentHighlights);
}
protected async Task HandleHoverRequest(
TextDocumentPosition textDocumentPosition,
RequestContext<Hover> requestContext)
{
ScriptFile scriptFile =
editorSession.Workspace.GetFile(
textDocumentPosition.Uri);
SymbolDetails symbolDetails =
await editorSession
.LanguageService
.FindSymbolDetailsAtLocation(
scriptFile,
textDocumentPosition.Position.Line + 1,
textDocumentPosition.Position.Character + 1);
List<MarkedString> symbolInfo = new List<MarkedString>();
Range? symbolRange = null;
if (symbolDetails != null)
{
symbolInfo.Add(
new MarkedString
{
Language = "PowerShell",
Value = symbolDetails.DisplayString
});
if (!string.IsNullOrEmpty(symbolDetails.Documentation))
{
symbolInfo.Add(
new MarkedString
{
Language = "markdown",
Value = symbolDetails.Documentation
});
}
symbolRange = GetRangeFromScriptRegion(symbolDetails.SymbolReference.ScriptRegion);
}
await requestContext.SendResult(
new Hover
{
Contents = symbolInfo.ToArray(),
Range = symbolRange
});
}
protected async Task HandleDocumentSymbolRequest(
TextDocumentIdentifier textDocumentIdentifier,
RequestContext<SymbolInformation[]> requestContext)
{
ScriptFile scriptFile =
editorSession.Workspace.GetFile(
textDocumentIdentifier.Uri);
FindOccurrencesResult foundSymbols =
editorSession.LanguageService.FindSymbolsInFile(
scriptFile);
SymbolInformation[] symbols = null;
string containerName = Path.GetFileNameWithoutExtension(scriptFile.FilePath);
if (foundSymbols != null)
{
symbols =
foundSymbols
.FoundOccurrences
.Select(r =>
{
return new SymbolInformation
{
ContainerName = containerName,
Kind = GetSymbolKind(r.SymbolType),
Location = new Location
{
Uri = new Uri("file://" + r.FilePath).AbsolutePath,
Range = GetRangeFromScriptRegion(r.ScriptRegion)
},
Name = GetDecoratedSymbolName(r)
};
})
.ToArray();
}
else
{
symbols = new SymbolInformation[0];
}
await requestContext.SendResult(symbols);
}
private SymbolKind GetSymbolKind(SymbolType symbolType)
{
switch (symbolType)
{
case SymbolType.Configuration:
case SymbolType.Function:
case SymbolType.Workflow:
return SymbolKind.Function;
default:
return SymbolKind.Variable;
}
}
private string GetDecoratedSymbolName(SymbolReference symbolReference)
{
string name = symbolReference.SymbolName;
if (symbolReference.SymbolType == SymbolType.Configuration ||
symbolReference.SymbolType == SymbolType.Function ||
symbolReference.SymbolType == SymbolType.Workflow)
{
name += " { }";
}
return name;
}
protected async Task HandleWorkspaceSymbolRequest(
WorkspaceSymbolParams workspaceSymbolParams,
RequestContext<SymbolInformation[]> requestContext)
{
var symbols = new List<SymbolInformation>();
foreach (ScriptFile scriptFile in editorSession.Workspace.GetOpenedFiles())
{
FindOccurrencesResult foundSymbols =
editorSession.LanguageService.FindSymbolsInFile(
scriptFile);
// TODO: Need to compute a relative path that is based on common path for all workspace files
string containerName = Path.GetFileNameWithoutExtension(scriptFile.FilePath);
if (foundSymbols != null)
{
var matchedSymbols =
foundSymbols
.FoundOccurrences
.Where(r => IsQueryMatch(workspaceSymbolParams.Query, r.SymbolName))
.Select(r =>
{
return new SymbolInformation
{
ContainerName = containerName,
Kind = r.SymbolType == SymbolType.Variable ? SymbolKind.Variable : SymbolKind.Function,
Location = new Location
{
Uri = new Uri("file://" + r.FilePath).AbsoluteUri,
Range = GetRangeFromScriptRegion(r.ScriptRegion)
},
Name = GetDecoratedSymbolName(r)
};
});
symbols.AddRange(matchedSymbols);
}
}
await requestContext.SendResult(symbols.ToArray());
}
private bool IsQueryMatch(string query, string symbolName)
{
return symbolName.IndexOf(query, StringComparison.OrdinalIgnoreCase) >= 0;
}
protected Task HandleEvaluateRequest(
DebugAdapterMessages.EvaluateRequestArguments evaluateParams,
RequestContext<DebugAdapterMessages.EvaluateResponseBody> requestContext)
{
// We don't await the result of the execution here because we want
// to be able to receive further messages while the current script
// is executing. This important in cases where the pipeline thread
// gets blocked by something in the script like a prompt to the user.
var executeTask =
this.editorSession.PowerShellContext.ExecuteScriptString(
evaluateParams.Expression,
true,
true);
// Return the execution result after the task completes so that the
// caller knows when command execution completed.
executeTask.ContinueWith(
(task) =>
{
// Return an empty result since the result value is irrelevant
// for this request in the LanguageServer
return
requestContext.SendResult(
new DebugAdapterMessages.EvaluateResponseBody
{
Result = "",
VariablesReference = 0
});
});
return Task.FromResult(true);
}
#endregion
#region Event Handlers
private async void powerShellContext_OutputWritten(object sender, OutputWrittenEventArgs e)
{
// Queue the output for writing
await this.outputDebouncer.Invoke(e);
}
private async void ExtensionService_ExtensionAdded(object sender, EditorCommand e)
{
await this.SendEvent(
ExtensionCommandAddedNotification.Type,
new ExtensionCommandAddedNotification
{
Name = e.Name,
DisplayName = e.DisplayName
});
}
private async void ExtensionService_ExtensionUpdated(object sender, EditorCommand e)
{
await this.SendEvent(
ExtensionCommandUpdatedNotification.Type,
new ExtensionCommandUpdatedNotification
{
Name = e.Name,
});
}
private async void ExtensionService_ExtensionRemoved(object sender, EditorCommand e)
{
await this.SendEvent(
ExtensionCommandRemovedNotification.Type,
new ExtensionCommandRemovedNotification
{
Name = e.Name,
});
}
#endregion
#region Helper Methods
private static Range GetRangeFromScriptRegion(ScriptRegion scriptRegion)
{
return new Range
{
Start = new Position
{
Line = scriptRegion.StartLineNumber - 1,
Character = scriptRegion.StartColumnNumber - 1
},
End = new Position
{
Line = scriptRegion.EndLineNumber - 1,
Character = scriptRegion.EndColumnNumber - 1
}
};
}
private static FileChange GetFileChangeDetails(Range changeRange, string insertString)
{
// The protocol's positions are zero-based so add 1 to all offsets
return new FileChange
{
InsertString = insertString,
Line = changeRange.Start.Line + 1,
Offset = changeRange.Start.Character + 1,
EndLine = changeRange.End.Line + 1,
EndOffset = changeRange.End.Character + 1
};
}
private Task RunScriptDiagnostics(
ScriptFile[] filesToAnalyze,
EditorSession editorSession,
EventContext eventContext)
{
if (!this.currentSettings.ScriptAnalysis.Enable.Value)
{
// If the user has disabled script analysis, skip it entirely
return Task.FromResult(true);
}
// If there's an existing task, attempt to cancel it
try
{
if (existingRequestCancellation != null)
{
// Try to cancel the request
existingRequestCancellation.Cancel();
// If cancellation didn't throw an exception,
// clean up the existing token
existingRequestCancellation.Dispose();
existingRequestCancellation = null;
}
}
catch (Exception e)
{
// TODO: Catch a more specific exception!
Logger.Write(
LogLevel.Error,
string.Format(
"Exception while canceling analysis task:\n\n{0}",
e.ToString()));
TaskCompletionSource<bool> cancelTask = new TaskCompletionSource<bool>();
cancelTask.SetCanceled();
return cancelTask.Task;
}
// Create a fresh cancellation token and then start the task.
// We create this on a different TaskScheduler so that we
// don't block the main message loop thread.
// TODO: Is there a better way to do this?
existingRequestCancellation = new CancellationTokenSource();
Task.Factory.StartNew(
() =>
DelayThenInvokeDiagnostics(
750,
filesToAnalyze,
editorSession,
eventContext,
existingRequestCancellation.Token),
CancellationToken.None,
TaskCreationOptions.None,
TaskScheduler.Default);
return Task.FromResult(true);
}
private static async Task DelayThenInvokeDiagnostics(
int delayMilliseconds,
ScriptFile[] filesToAnalyze,
EditorSession editorSession,
EventContext eventContext,
CancellationToken cancellationToken)
{
// First of all, wait for the desired delay period before
// analyzing the provided list of files
try
{
await Task.Delay(delayMilliseconds, cancellationToken);
}
catch (TaskCanceledException)
{
// If the task is cancelled, exit directly
return;
}
// If we've made it past the delay period then we don't care
// about the cancellation token anymore. This could happen
// when the user stops typing for long enough that the delay
// period ends but then starts typing while analysis is going
// on. It makes sense to send back the results from the first
// delay period while the second one is ticking away.