-
Notifications
You must be signed in to change notification settings - Fork 21
/
Copy pathCSharpCompilerService.cs
425 lines (352 loc) · 17.4 KB
/
CSharpCompilerService.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
using System.Collections.Immutable;
using Luthetus.Common.RazorLib.Keys.Models;
using Luthetus.Common.RazorLib.Installations.Models;
using Luthetus.TextEditor.RazorLib;
using Luthetus.TextEditor.RazorLib.Exceptions;
using Luthetus.TextEditor.RazorLib.Autocompletes.Models;
using Luthetus.TextEditor.RazorLib.CompilerServices;
using Luthetus.TextEditor.RazorLib.CompilerServices.Interfaces;
using Luthetus.TextEditor.RazorLib.CompilerServices.Implementations;
using Luthetus.TextEditor.RazorLib.CompilerServices.Facts;
using Luthetus.TextEditor.RazorLib.CompilerServices.Syntax;
using Luthetus.TextEditor.RazorLib.CompilerServices.Syntax.Nodes;
using Luthetus.TextEditor.RazorLib.Cursors.Models;
using Luthetus.TextEditor.RazorLib.Lexers.Models;
using Luthetus.TextEditor.RazorLib.TextEditors.Models;
using Luthetus.CompilerServices.CSharp.BinderCase;
using Luthetus.CompilerServices.CSharp.LexerCase;
using Luthetus.CompilerServices.CSharp.ParserCase;
using Luthetus.CompilerServices.CSharp.RuntimeAssemblies;
namespace Luthetus.CompilerServices.CSharp.CompilerServiceCase;
public sealed class CSharpCompilerService : CompilerService
{
/// <summary>
/// TODO: The CSharpBinder should be private, but for now I'm making it public to be usable in the CompilerServiceExplorer Blazor component.
/// </summary>
public readonly CSharpBinder CSharpBinder = new();
public CSharpCompilerService(ITextEditorService textEditorService)
: base(textEditorService)
{
Binder = CSharpBinder;
_compilerServiceOptions = new()
{
RegisterResourceFunc = resourceUri => new CSharpResource(resourceUri, this),
};
RuntimeAssembliesLoaderFactory.LoadDotNet6(CSharpBinder);
}
public override Type? SymbolRendererType { get; protected set; }
public override Type? DiagnosticRendererType { get; protected set; }
public event Action? CursorMovedInSyntaxTree;
public void SetSymbolRendererType(Type? symbolRendererType)
{
SymbolRendererType = symbolRendererType;
}
public void SetDiagnosticRendererType(Type? diagnosticRendererType)
{
DiagnosticRendererType = diagnosticRendererType;
}
public override ValueTask ParseAsync(ITextEditorEditContext editContext, TextEditorModelModifier modelModifier, bool shouldApplySyntaxHighlighting)
{
var resourceUri = modelModifier.ResourceUri;
if (!_resourceMap.ContainsKey(resourceUri))
return ValueTask.CompletedTask;
_textEditorService.ModelApi.StartPendingCalculatePresentationModel(
editContext,
modelModifier,
CompilerServiceDiagnosticPresentationFacts.PresentationKey,
CompilerServiceDiagnosticPresentationFacts.EmptyPresentationModel);
var presentationModel = modelModifier.PresentationModelList.First(
x => x.TextEditorPresentationKey == CompilerServiceDiagnosticPresentationFacts.PresentationKey);
var cSharpCompilationUnit = new CSharpCompilationUnit(resourceUri, CSharpBinder);
var lexerOutput = CSharpLexer.Lex(resourceUri, presentationModel.PendingCalculation.ContentAtRequest);
// Even if the parser throws an exception, be sure to
// make use of the Lexer to do whatever syntax highlighting is possible.
try
{
cSharpCompilationUnit.BinderSession = (CSharpBinderSession)CSharpBinder.StartBinderSession(resourceUri);
CSharpParser.Parse(cSharpCompilationUnit, ref lexerOutput);
}
finally
{
lock (_resourceMapLock)
{
if (_resourceMap.ContainsKey(resourceUri))
{
var resource = (CSharpResource)_resourceMap[resourceUri];
resource.SyntaxTokenList = lexerOutput.SyntaxTokenList;
resource.MiscTextSpanList = lexerOutput.MiscTextSpanList;
if (cSharpCompilationUnit is not null)
resource.CompilationUnit = cSharpCompilationUnit;
}
}
var diagnosticTextSpans = GetDiagnosticsFor(modelModifier.ResourceUri)
.Select(x => x.TextSpan)
.ToArray();
modelModifier.CompletePendingCalculatePresentationModel(
CompilerServiceDiagnosticPresentationFacts.PresentationKey,
CompilerServiceDiagnosticPresentationFacts.EmptyPresentationModel,
diagnosticTextSpans);
if (shouldApplySyntaxHighlighting)
{
editContext.TextEditorService.ModelApi.ApplySyntaxHighlighting(
editContext,
modelModifier);
}
OnResourceParsed();
}
return ValueTask.CompletedTask;
}
public override List<AutocompleteEntry> GetAutocompleteEntries(string word, TextEditorTextSpan textSpan)
{
var boundScope = CSharpBinder.GetScope(null, textSpan);
if (boundScope is null)
return base._emptyAutocompleteEntryList;
var autocompleteEntryList = new List<AutocompleteEntry>();
var targetScope = boundScope;
if (textSpan.GetText() == ".")
{
var textEditorModel = _textEditorService.ModelApi.GetOrDefault(textSpan.ResourceUri);
if (textEditorModel is null)
return autocompleteEntryList.DistinctBy(x => x.DisplayName).ToList();
var compilerService = textEditorModel.CompilerService;
var compilerServiceResource = compilerService.GetCompilerServiceResourceFor(textEditorModel.ResourceUri);
if (compilerServiceResource is null)
return autocompleteEntryList.DistinctBy(x => x.DisplayName).ToList();
var targetNode = CSharpBinder.GetSyntaxNode(
(CSharpCompilationUnit)compilerServiceResource.CompilationUnit,
textSpan.StartingIndexInclusive - 1,
textSpan.ResourceUri,
compilerServiceResource);
if (targetNode is null)
return autocompleteEntryList.DistinctBy(x => x.DisplayName).ToList();
TypeClauseNode? typeClauseNode = null;
if (targetNode.SyntaxKind == SyntaxKind.VariableReferenceNode)
typeClauseNode = ((VariableReferenceNode)targetNode).VariableDeclarationNode?.TypeClauseNode;
else if (targetNode.SyntaxKind == SyntaxKind.VariableDeclarationNode)
typeClauseNode = ((VariableDeclarationNode)targetNode).TypeClauseNode;
else if (targetNode.SyntaxKind == SyntaxKind.TypeClauseNode)
typeClauseNode = (TypeClauseNode)targetNode;
else if (targetNode.SyntaxKind == SyntaxKind.TypeDefinitionNode)
typeClauseNode = ((TypeDefinitionNode)targetNode).ToTypeClause();
else if (targetNode.SyntaxKind == SyntaxKind.ConstructorDefinitionNode)
typeClauseNode = ((ConstructorDefinitionNode)targetNode).ReturnTypeClauseNode;
if (typeClauseNode is null)
return autocompleteEntryList.DistinctBy(x => x.DisplayName).ToList();
var maybeTypeDefinitionNode = CSharpBinder.GetDefinitionNode((CSharpCompilationUnit)compilerServiceResource.CompilationUnit, typeClauseNode.TypeIdentifierToken.TextSpan, SyntaxKind.TypeClauseNode);
if (maybeTypeDefinitionNode is null || maybeTypeDefinitionNode.SyntaxKind != SyntaxKind.TypeDefinitionNode)
return autocompleteEntryList.DistinctBy(x => x.DisplayName).ToList();
var typeDefinitionNode = (TypeDefinitionNode)maybeTypeDefinitionNode;
var memberList = typeDefinitionNode.GetMemberList();
autocompleteEntryList.AddRange(
memberList
.Select(node =>
{
if (node.SyntaxKind == SyntaxKind.VariableDeclarationNode)
{
var variableDeclarationNode = (VariableDeclarationNode)node;
return variableDeclarationNode.IdentifierToken.TextSpan.GetText();
}
else if (node.SyntaxKind == SyntaxKind.TypeDefinitionNode)
{
var typeDefinitionNode = (TypeDefinitionNode)node;
return typeDefinitionNode.TypeIdentifierToken.TextSpan.GetText();
}
else if (node.SyntaxKind == SyntaxKind.FunctionDefinitionNode)
{
var functionDefinitionNode = (FunctionDefinitionNode)node;
return functionDefinitionNode.FunctionIdentifierToken.TextSpan.GetText();
}
else
{
return string.Empty;
}
})
.ToArray()
//.Where(x => x.Contains(word, StringComparison.InvariantCulture))
.Distinct()
.Take(5)
.Select(x =>
{
return new AutocompleteEntry(
x,
AutocompleteEntryKind.Variable,
null);
}));
}
else
{
while (targetScope is not null)
{
autocompleteEntryList.AddRange(
CSharpBinder.GetVariableDeclarationNodesByScope(compilationUnit: null, textSpan.ResourceUri, targetScope.IndexKey)
.Select(x => x.IdentifierToken.TextSpan.GetText())
.ToArray()
.Where(x => x.Contains(word, StringComparison.InvariantCulture))
.Distinct()
.Take(5)
.Select(x =>
{
return new AutocompleteEntry(
x,
AutocompleteEntryKind.Variable,
null);
}));
autocompleteEntryList.AddRange(
CSharpBinder.GetFunctionDefinitionNodesByScope(compilationUnit: null, textSpan.ResourceUri, targetScope.IndexKey)
.Select(x => x.FunctionIdentifierToken.TextSpan.GetText())
.ToArray()
.Where(x => x.Contains(word, StringComparison.InvariantCulture))
.Distinct()
.Take(5)
.Select(x =>
{
return new AutocompleteEntry(
x,
AutocompleteEntryKind.Function,
null);
}));
if (targetScope.ParentIndexKey is null)
targetScope = null;
else
targetScope = CSharpBinder.GetScopeByScopeIndexKey(compilationUnit: null, textSpan.ResourceUri, targetScope.ParentIndexKey.Value);
}
var allTypeDefinitions = CSharpBinder.AllTypeDefinitions;
autocompleteEntryList.AddRange(
allTypeDefinitions
.Where(x => x.Key.TypeIdentifier.Contains(word, StringComparison.InvariantCulture))
.Distinct()
.Take(5)
.Select(x =>
{
return new AutocompleteEntry(
x.Key.TypeIdentifier,
AutocompleteEntryKind.Type,
() =>
{
// TODO: The namespace code is buggy at the moment.
// It is annoying how this keeps adding the wrong namespace.
// Just have it do nothing for now. (2024-08-24)
// ===============================================================
/*if (boundScope.EncompassingNamespaceStatementNode.IdentifierToken.TextSpan.GetText() == x.Key.NamespaceIdentifier ||
boundScope.CurrentUsingStatementNodeList.Any(usn => usn.NamespaceIdentifier.TextSpan.GetText() == x.Key.NamespaceIdentifier))
{
return Task.CompletedTask;
}
_textEditorService.PostUnique(
"Add using statement",
editContext =>
{
var modelModifier = editContext.GetModelModifier(textSpan.ResourceUri);
if (modelModifier is null)
return Task.CompletedTask;
var viewModelList = _textEditorService.ModelApi.GetViewModelsOrEmpty(textSpan.ResourceUri);
var cursor = new TextEditorCursor(0, 0, true);
var cursorModifierBag = new CursorModifierBagTextEditor(
Key<TextEditorViewModel>.Empty,
new List<TextEditorCursorModifier> { new(cursor) });
var textToInsert = $"using {x.Key.NamespaceIdentifier};\n";
modelModifier.Insert(
textToInsert,
cursorModifierBag,
cancellationToken: CancellationToken.None);
foreach (var unsafeViewModel in viewModelList)
{
var viewModelModifier = editContext.GetViewModelModifier(unsafeViewModel.ViewModelKey);
var viewModelCursorModifierBag = editContext.GetCursorModifierBag(viewModelModifier?.ViewModel);
if (viewModelModifier is null || viewModelCursorModifierBag is null)
continue;
foreach (var cursorModifier in viewModelCursorModifierBag.List)
{
for (int i = 0; i < textToInsert.Length; i++)
{
_textEditorService.ViewModelApi.MoveCursor(
new KeyboardEventArgs
{
Key = KeyboardKeyFacts.MovementKeys.ARROW_RIGHT,
},
editContext,
modelModifier,
viewModelModifier,
viewModelCursorModifierBag);
}
}
editContext.TextEditorService.ModelApi.ApplySyntaxHighlighting(
editContext,
modelModifier);
}
return Task.CompletedTask;
});*/
return Task.CompletedTask;
});
}));
}
AddSnippets(autocompleteEntryList, word, textSpan);
return autocompleteEntryList.DistinctBy(x => x.DisplayName).ToList();
}
private void AddSnippets(List<AutocompleteEntry> autocompleteEntryList, string word, TextEditorTextSpan textSpan)
{
if ("prop".Contains(word))
{
autocompleteEntryList.Add(new AutocompleteEntry(
"prop",
AutocompleteEntryKind.Snippet,
() => PropSnippet(word, textSpan, "public TYPE NAME { get; set; }")));
}
if ("propnn".Contains(word))
{
autocompleteEntryList.Add(new AutocompleteEntry(
"propnn",
AutocompleteEntryKind.Snippet,
() => PropSnippet(word, textSpan, "public TYPE NAME { get; set; } = null!;")));
}
}
private Task PropSnippet(string word, TextEditorTextSpan textSpan, string textToInsert)
{
_textEditorService.TextEditorWorker.PostUnique(
nameof(PropSnippet),
editContext =>
{
var modelModifier = editContext.GetModelModifier(textSpan.ResourceUri);
if (modelModifier is null)
return ValueTask.CompletedTask;
var viewModelList = _textEditorService.ModelApi.GetViewModelsOrEmpty(textSpan.ResourceUri);
var viewModel = viewModelList.FirstOrDefault(x => x.Category.Value == "main")
?? viewModelList.FirstOrDefault();
if (viewModel is null)
return ValueTask.CompletedTask;
var viewModelModifier = editContext.GetViewModelModifier(viewModel.ViewModelKey);
var primaryCursorModifier = editContext.GetPrimaryCursorModifier(
editContext.GetCursorModifierBag(viewModelModifier?.ViewModel));
if (viewModelModifier is null || primaryCursorModifier is null)
return ValueTask.CompletedTask;
var cursorModifierBag = new CursorModifierBagTextEditor(
Key<TextEditorViewModel>.Empty,
new List<TextEditorCursorModifier> { primaryCursorModifier });
var cursorPositionIndex = modelModifier.GetPositionIndex(primaryCursorModifier);
var behindPositionIndex = cursorPositionIndex - 1;
var behindCursor = new TextEditorCursor(
primaryCursorModifier.LineIndex,
primaryCursorModifier.ColumnIndex - 1,
primaryCursorModifier.IsPrimaryCursor);
modelModifier.Insert(
textToInsert,
cursorModifierBag,
cancellationToken: CancellationToken.None);
if (behindPositionIndex > 0 && modelModifier.GetCharacter(behindPositionIndex) == 'p')
{
modelModifier.Delete(
new CursorModifierBagTextEditor(
Key<TextEditorViewModel>.Empty,
new List<TextEditorCursorModifier> { new(behindCursor) }),
1,
expandWord: false,
TextEditorModelModifier.DeleteKind.Delete);
}
modelModifier.CompilerService.ResourceWasModified(
modelModifier.ResourceUri,
ImmutableArray<TextEditorTextSpan>.Empty);
return ValueTask.CompletedTask;
});
return Task.CompletedTask;
}
}