forked from dotnet/interactive
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCSharpKernel.cs
More file actions
500 lines (423 loc) · 17.6 KB
/
Copy pathCSharpKernel.cs
File metadata and controls
500 lines (423 loc) · 17.6 KB
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
// Copyright (c) .NET Foundation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Completion;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Scripting;
using Microsoft.CodeAnalysis.QuickInfo;
using Microsoft.CodeAnalysis.Scripting;
using Microsoft.DotNet.Interactive.Commands;
using Microsoft.DotNet.Interactive.CSharp.SignatureHelp;
using Microsoft.DotNet.Interactive.Events;
using Microsoft.DotNet.Interactive.Formatting;
using Microsoft.DotNet.Interactive.Utility;
using Microsoft.DotNet.Interactive.ValueSharing;
using CompletionItem = Microsoft.DotNet.Interactive.Events.CompletionItem;
namespace Microsoft.DotNet.Interactive.CSharp;
public class CSharpKernel :
Kernel,
IKernelCommandHandler<RequestCompletions>,
IKernelCommandHandler<RequestDiagnostics>,
IKernelCommandHandler<RequestHoverText>,
IKernelCommandHandler<RequestSignatureHelp>,
IKernelCommandHandler<RequestValue>,
IKernelCommandHandler<RequestValueInfos>,
IKernelCommandHandler<SendValue>,
IKernelCommandHandler<SubmitCode>
{
internal const string DefaultKernelName = "csharp";
private static readonly MethodInfo _hasReturnValueMethod = typeof(Script)
.GetMethod("HasReturnValue", BindingFlags.Instance | BindingFlags.NonPublic);
protected CSharpParseOptions _csharpParseOptions =
new(LanguageVersion.Latest, kind: SourceCodeKind.Script);
private InteractiveWorkspace _workspace;
private ScriptOptions _scriptOptions;
private string _workingDirectory;
public CSharpKernel() : this(DefaultKernelName)
{
}
public CSharpKernel(string name) : base(name)
{
KernelInfo.LanguageName = "C#";
KernelInfo.LanguageVersion = "14.0";
KernelInfo.DisplayName = $"{KernelInfo.LocalName} - C# Script";
KernelInfo.Description = """
Compile and run C# Script
""";
_workspace = new InteractiveWorkspace();
//For the VSCode-Add-In Directory.GetCurrentDirectory() would here return something like: c:\Users\<username>\AppData\Roaming\Code\User\globalStorage\ms-dotnettools.dotnet-interactive-vscode
//...so we wait for RunAsync to read Directory.GetCurrentDirectory() the first time.
_scriptOptions = ScriptOptions.Default
.WithLanguageVersion(LanguageVersion.Latest)
.AddImports(
"System",
"System.Text",
"System.Collections",
"System.Collections.Generic",
"System.Threading.Tasks",
"System.Linq")
.AddReferences(
typeof(Enumerable).Assembly,
typeof(IEnumerable<>).Assembly,
typeof(Task<>).Assembly,
typeof(Kernel).Assembly,
typeof(CSharpKernel).Assembly,
typeof(PocketView).Assembly);
RegisterForDisposal(() =>
{
_workspace.Dispose();
_workspace = null;
ScriptState = null;
_scriptOptions = null;
});
}
public ScriptState ScriptState { get; private set; }
private bool IsCompleteSubmission(string code)
{
var syntaxTree = SyntaxFactory.ParseSyntaxTree(code, _csharpParseOptions);
return SyntaxFactory.IsCompleteSubmission(syntaxTree);
}
Task IKernelCommandHandler<RequestValueInfos>.HandleAsync(RequestValueInfos command, KernelInvocationContext context)
{
var valueInfos =
ScriptState?.Variables
.GroupBy(v => v.Name)
.Select(g =>
{
var formattedValues = FormattedValue.CreateSingleFromObject(
g.LastOrDefault()?.Value,
command.MimeType);
return new KernelValueInfo(
g.Key,
formattedValues,
g.Last().Type);
})
.ToArray() ??
[];
context.Publish(new ValueInfosProduced(valueInfos, command));
return Task.CompletedTask;
}
Task IKernelCommandHandler<RequestValue>.HandleAsync(RequestValue command, KernelInvocationContext context)
{
if (TryGetValue<object>(command.Name, out var value))
{
context.Publish(new ValueProduced(
value,
command.Name,
new FormattedValue(
command.MimeType,
value.ToDisplayString(command.MimeType)),
command));
}
else
{
context.Fail(command, message: $"Value '{command.Name}' not found in kernel {Name}");
}
return Task.CompletedTask;
}
public bool TryGetValue<T>(
string name,
out T value)
{
object rawValue;
bool ret;
if (ScriptState?.Variables
.LastOrDefault(v => v.Name == name) is { } variable)
{
rawValue = variable.Value;
ret = true;
}
else
{
rawValue = default;
ret = false;
}
if (ret)
{
value = (T)rawValue;
return true;
}
value = default;
return false;
}
async Task IKernelCommandHandler<SendValue>.HandleAsync(
SendValue command,
KernelInvocationContext context)
{
await SetValueAsync(command, context, SetValueAsync);
}
public async Task SetValueAsync(string name, object value, Type declaredType)
{
using var csharpTypeDeclaration = new StringWriter();
declaredType ??= value.GetType();
declaredType.WriteCSharpDeclarationTo(csharpTypeDeclaration);
await RunAsync($"{csharpTypeDeclaration} {name} = default;");
var scriptVariable = ScriptState.GetVariable(name);
scriptVariable.Value = value;
}
async Task IKernelCommandHandler<RequestHoverText>.HandleAsync(RequestHoverText command, KernelInvocationContext context)
{
await EnsureWorkspaceIsInitializedAsync(context);
using var _ = new GCPressure(1024 * 1024);
var document = _workspace.ForkDocumentForLanguageServices(command.Code);
var text = await document.GetTextAsync(context.CancellationToken);
var cursorPosition = text.Lines.GetPosition(command.LinePosition.ToCodeAnalysisLinePosition());
var service = QuickInfoService.GetService(document);
if (service != null)
{
var info = await service.GetQuickInfoAsync(document, cursorPosition, context.CancellationToken);
if (info is null)
{
return;
}
var scriptSpanStart = LinePosition.FromCodeAnalysisLinePosition(text.Lines.GetLinePosition(0));
var linePosSpan = LinePositionSpan.FromCodeAnalysisLinePositionSpan(text.Lines.GetLinePositionSpan(info.Span));
var correctedLinePosSpan = linePosSpan.SubtractLineOffset(scriptSpanStart);
context.Publish(
new HoverTextProduced(
command,
new[]
{
new FormattedValue("text/markdown", info.ToMarkdownString())
},
correctedLinePosSpan));
}
}
async Task IKernelCommandHandler<RequestSignatureHelp>.HandleAsync(RequestSignatureHelp command, KernelInvocationContext context)
{
await EnsureWorkspaceIsInitializedAsync(context);
var document = _workspace.ForkDocumentForLanguageServices(command.Code);
var signatureHelp = await SignatureHelpGenerator.GenerateSignatureInformation(document, command, context.CancellationToken);
if (signatureHelp is not null)
{
context.Publish(signatureHelp);
}
}
private async Task EnsureWorkspaceIsInitializedAsync(KernelInvocationContext context)
{
if (ScriptState is null)
{
ScriptState = await CSharpScript.RunAsync(
string.Empty,
_scriptOptions,
cancellationToken: context.CancellationToken)
.UntilCancelled(context.CancellationToken) ?? ScriptState;
await _workspace.UpdateWorkspaceAsync(ScriptState);
}
}
async Task IKernelCommandHandler<SubmitCode>.HandleAsync(SubmitCode submitCode, KernelInvocationContext context)
{
var codeSubmissionReceived = new CodeSubmissionReceived(submitCode);
context.Publish(codeSubmissionReceived);
var code = submitCode.Code;
var isComplete = IsCompleteSubmission(submitCode.Code);
if (isComplete)
{
context.Publish(new CompleteCodeSubmissionReceived(submitCode));
}
else
{
context.Publish(new IncompleteCodeSubmissionReceived(submitCode));
}
Exception exception = null;
string message = null;
if (!context.CancellationToken.IsCancellationRequested)
{
try
{
await RunAsync(
code,
context.CancellationToken,
e =>
{
exception = e;
return true;
});
}
catch (CompilationErrorException cpe)
{
exception = new CodeSubmissionCompilationErrorException(cpe);
}
catch (Exception e)
{
exception = e;
}
}
if (!context.CancellationToken.IsCancellationRequested)
{
ImmutableArray<CodeAnalysis.Diagnostic> diagnostics;
// Check for a compilation failure
if (exception is CodeSubmissionCompilationErrorException { InnerException: CompilationErrorException innerCompilationException })
{
diagnostics = innerCompilationException.Diagnostics;
// In the case of an error the diagnostics get attached to both the
// DiagnosticsProduced and CommandFailed events.
message =
string.Join(Environment.NewLine,
innerCompilationException.Diagnostics.Select(d => d.ToString()));
}
else
{
diagnostics = ScriptState?.Script.GetCompilation().GetDiagnostics() ?? ImmutableArray<CodeAnalysis.Diagnostic>.Empty;
}
// Publish the compilation diagnostics. This doesn't include the exception.
var kernelDiagnostics = diagnostics.Select(Diagnostic.FromCodeAnalysisDiagnostic).ToImmutableArray();
var formattedDiagnostics =
diagnostics
.Select(d => d.ToString())
.Select(text => new FormattedValue(PlainTextFormatter.MimeType, text))
.ToImmutableArray();
context.Publish(new DiagnosticsProduced(kernelDiagnostics, formattedDiagnostics, submitCode));
// Report the compilation failure or exception
if (exception is not null)
{
context.Fail(submitCode, exception, message);
}
else
{
if (ScriptState is not null && HasReturnValue)
{
IReadOnlyList<FormattedValue> formattedValues = ScriptState.ReturnValue switch
{
FormattedValue formattedValue => new[] { formattedValue },
IEnumerable<FormattedValue> formattedValueEnumerable => formattedValueEnumerable.ToArray(),
_ => FormattedValue.CreateManyFromObject(ScriptState.ReturnValue)
};
context.Publish(
new ReturnValueProduced(
ScriptState.ReturnValue,
submitCode,
formattedValues));
}
}
}
else
{
context.Fail(submitCode, null, "Command cancelled");
}
}
private async Task RunAsync(
string code,
CancellationToken cancellationToken = default,
Func<Exception, bool> catchException = default)
{
if (cancellationToken.IsCancellationRequested || IsDisposed)
{
return;
}
UpdateScriptOptionsIfWorkingDirectoryChanged();
if (ScriptState is null)
{
ScriptState = await CSharpScript.RunAsync(
code,
_scriptOptions,
cancellationToken: cancellationToken)
?? ScriptState;
}
else
{
ScriptState = await ScriptState.ContinueWithAsync(
code,
_scriptOptions,
catchException: catchException,
cancellationToken: cancellationToken)
?? ScriptState;
}
if (ScriptState is not null && ScriptState.Exception is null)
{
await _workspace.UpdateWorkspaceAsync(ScriptState);
}
void UpdateScriptOptionsIfWorkingDirectoryChanged()
{
var currentDir = Directory.GetCurrentDirectory();
if (!currentDir.Equals(_workingDirectory, StringComparison.Ordinal))
{
_workingDirectory = currentDir;
_scriptOptions = _scriptOptions
.WithMetadataResolver(CachingMetadataResolver.Default.WithBaseDirectory(_workingDirectory))
.WithSourceResolver(new SourceFileResolver(ImmutableArray<string>.Empty, _workingDirectory));
}
}
}
async Task IKernelCommandHandler<RequestCompletions>.HandleAsync(
RequestCompletions command,
KernelInvocationContext context)
{
await EnsureWorkspaceIsInitializedAsync(context);
var completionList =
await GetCompletionList(
command.Code,
SourceUtilities.GetCursorOffsetFromPosition(command.Code, command.LinePosition),
context.CancellationToken);
context.Publish(new CompletionsProduced(completionList, command));
}
private async Task<IReadOnlyList<CompletionItem>> GetCompletionList(
string code,
int cursorPosition,
CancellationToken contextCancellationToken)
{
using var _ = new GCPressure(1024 * 1024);
var document = _workspace.ForkDocumentForLanguageServices(code);
var service = CompletionService.GetService(document);
var completionList = await service.GetCompletionsAsync(document, cursorPosition, cancellationToken: contextCancellationToken);
if (completionList is null)
{
return [];
}
var items = new List<CompletionItem>();
foreach (CodeAnalysis.Completion.CompletionItem item in completionList.ItemsList)
{
// TODO: Getting a description for each item significantly slows this overall operation. We should look into caching approaches but shouldn't block completions here.
// var description = await service.GetDescriptionAsync(document, item, contextCancellationToken);
var completionItem = item.ToModel(CompletionDescription.Empty);
items.Add(completionItem);
}
return items;
}
internal DiagnosticsProduced GetDiagnosticsProduced(
KernelCommand command,
ImmutableArray<CodeAnalysis.Diagnostic> diagnostics)
{
var kernelDiagnostics = diagnostics.Select(Diagnostic.FromCodeAnalysisDiagnostic).ToImmutableArray();
var formattedDiagnostics =
diagnostics
.Select(d => new FormattedValue(PlainTextFormatter.MimeType, d.ToString()))
.ToArray();
return new DiagnosticsProduced(kernelDiagnostics, formattedDiagnostics, command);
}
async Task IKernelCommandHandler<RequestDiagnostics>.HandleAsync(
RequestDiagnostics command,
KernelInvocationContext context)
{
await EnsureWorkspaceIsInitializedAsync(context);
var document = _workspace.ForkDocumentForLanguageServices(command.Code);
var semanticModel = await document.GetSemanticModelAsync(context.CancellationToken);
var diagnostics = semanticModel.GetDiagnostics(cancellationToken: context.CancellationToken);
if (diagnostics.Length > 0)
{
context.Publish(GetDiagnosticsProduced(command, diagnostics));
}
}
private bool HasReturnValue =>
ScriptState is not null &&
(bool)_hasReturnValueMethod.Invoke(ScriptState.Script, null);
public void AddAssemblyReferences(IEnumerable<string> assemblyPaths)
{
var references = assemblyPaths
.Select(r => CachingMetadataResolver.ResolveReferenceWithXmlDocumentationProvider(r))
.ToArray();
foreach (var reference in references)
{
_workspace.AddPackageManagerReference(reference);
}
_scriptOptions = _scriptOptions.AddReferences(references);
}
}