Repository navigation
Expand file tree
/
Copy pathTemplateFeatureService.cs
More file actions
1250 lines (1140 loc) · 54.7 KB
/
Copy pathTemplateFeatureService.cs
File metadata and controls
1250 lines (1140 loc) · 54.7 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
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
using System.Globalization;
using System.Text.RegularExpressions;
using System.Xml.Linq;
using Microsoft.CodeAnalysis;
using Typewriter.Abstractions;
using Typewriter.Engine;
using Typewriter.Roslyn;
namespace Typewriter.LanguageServer;
internal sealed class TemplateFeatureService : IDisposable
{
private static readonly TimeSpan RegexTimeout = TimeSpan.FromSeconds(seconds: 1);
private static readonly string[] CSharpCompletionKeywords =
[
"bool",
"break",
"case",
"class",
"const",
"continue",
"else",
"false",
"foreach",
"if",
"int",
"long",
"new",
"null",
"private",
"public",
"return",
"static",
"struct",
"string",
"switch",
"true",
"typeof",
"using",
"var",
"void",
];
private static readonly string[] CSharpCodeModelTypes =
[
"Attribute",
"AttributeArgument",
"Class",
"Constant",
"Delegate",
"Enum",
"EnumValue",
"Field",
"File",
"Interface",
"Method",
"Parameter",
"Property",
"Record",
"Settings",
"Struct",
"Type",
];
private static readonly string[] TypeScriptCompletionKeywords =
[
"as",
"async",
"await",
"boolean",
"break",
"case",
"catch",
"class",
"const",
"continue",
"declare",
"default",
"delete",
"do",
"else",
"enum",
"export",
"extends",
"false",
"finally",
"for",
"from",
"function",
"get",
"if",
"implements",
"import",
"in",
"instanceof",
"interface",
"keyof",
"let",
"namespace",
"new",
"null",
"number",
"of",
"private",
"protected",
"public",
"readonly",
"return",
"satisfies",
"set",
"static",
"string",
"super",
"switch",
"this",
"throw",
"true",
"try",
"type",
"typeof",
"undefined",
"var",
"void",
"while",
"yield",
];
private static readonly string[] TypeScriptBuiltInTypes =
[
"any",
"Array",
"bigint",
"Date",
"Map",
"never",
"object",
"Omit",
"Partial",
"Pick",
"Promise",
"Readonly",
"Record",
"Required",
"Set",
"symbol",
"unknown",
];
private readonly EmbeddedCSharpLanguageService _embeddedCSharpService = new();
private ProjectCompilationsCacheEntry? _projectCompilationsCache;
public async Task<LspCompletionList> GetCompletionsAsync(
TextDocumentState document,
LanguageServerSettings settings,
LspPosition position,
CancellationToken cancellationToken)
{
var language = TemplateEmbeddedLanguage.GetKindAt(document: document, position: position);
if (language == EmbeddedLanguageKind.CSharp)
{
var embedded = await _embeddedCSharpService.GetCompletionsAsync(
document: document,
templateOffset: document.GetOffset(position: position),
projectCompilations: await LoadProjectCompilationsAsync(document: document, settings: settings, cancellationToken: cancellationToken).ConfigureAwait(continueOnCapturedContext: false),
cancellationToken: cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
if (embedded is not null && embedded.Items.Count > 0)
{
return new LspCompletionList(
IsIncomplete: embedded.IsIncomplete,
Items: MergeEmbeddedCSharpCompletions(embeddedItems: embedded.Items));
}
}
var items = await GetAnalysisItemsAsync(document: document, settings: settings, cancellationToken: cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
if (language == EmbeddedLanguageKind.CSharp)
{
return new LspCompletionList(IsIncomplete: false, Items: CreateCSharpCompletionItems(analysisItems: items));
}
if (language == EmbeddedLanguageKind.TypeScript)
{
return new LspCompletionList(IsIncomplete: false, Items: CreateTypeScriptCompletionItems(analysisItems: items));
}
var templateItems = items
.GroupBy(keySelector: item => item.Label, comparer: StringComparer.OrdinalIgnoreCase)
.Select(selector: group => group.First())
.OrderBy(keySelector: item => item.Label, comparer: StringComparer.OrdinalIgnoreCase)
.Select(
selector: item => new LspCompletionItem(
Label: item.Label,
Kind: item.CompletionKind,
Detail: item.Detail,
Documentation: item.Documentation,
InsertText: item.InsertText,
InsertTextFormat: item.InsertTextFormat))
.ToArray();
return new LspCompletionList(IsIncomplete: false, Items: templateItems);
}
public async Task<LspHover?> GetHoverAsync(
TextDocumentState document,
LanguageServerSettings settings,
LspPosition position,
CancellationToken cancellationToken)
{
if (TemplateEmbeddedLanguage.GetKindAt(document: document, position: position) == EmbeddedLanguageKind.CSharp)
{
var embeddedHover = await _embeddedCSharpService.GetHoverAsync(
document: document,
templateOffset: document.GetOffset(position: position),
projectCompilations: await LoadProjectCompilationsAsync(document: document, settings: settings, cancellationToken: cancellationToken).ConfigureAwait(continueOnCapturedContext: false),
cancellationToken: cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
if (embeddedHover is not null)
{
return embeddedHover;
}
}
var token = document.GetToken(position: position);
if (string.IsNullOrWhiteSpace(value: token.Text))
{
return null;
}
var items = await GetAnalysisItemsAsync(document: document, settings: settings, cancellationToken: cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
var item = items.FirstOrDefault(predicate: candidate => MatchesToken(item: candidate, token: token.Text));
if (item is null)
{
return null;
}
return new LspHover(
Contents: new LspMarkupContent(Kind: "markdown", Value: CreateHoverMarkdown(item: item)),
Range: CreateRange(document: document, start: token.Start, end: token.End));
}
public async Task<IReadOnlyList<LspLocation>> GetDefinitionsAsync(
TextDocumentState document,
LanguageServerSettings settings,
LspPosition position,
CancellationToken cancellationToken)
{
if (TemplateEmbeddedLanguage.GetKindAt(document: document, position: position) == EmbeddedLanguageKind.CSharp)
{
var embeddedDefinitions = await _embeddedCSharpService.GetDefinitionsAsync(
document: document,
templateOffset: document.GetOffset(position: position),
projectCompilations: await LoadProjectCompilationsAsync(document: document, settings: settings, cancellationToken: cancellationToken).ConfigureAwait(continueOnCapturedContext: false),
cancellationToken: cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
if (embeddedDefinitions.Count > 0)
{
return embeddedDefinitions;
}
}
var token = document.GetToken(position: position);
var line = document.GetLine(position: position);
if (IsOutputDirective(line: line))
{
var generatedLocations = await GetGeneratedFileLocationsAsync(
document: document,
settings: settings,
cancellationToken: cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
if (generatedLocations.Count > 0)
{
return generatedLocations;
}
}
if (string.IsNullOrWhiteSpace(value: token.Text))
{
return [];
}
var items = await GetAnalysisItemsAsync(document: document, settings: settings, cancellationToken: cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
var locations = items
.Where(predicate: item => ShouldIncludeDefinition(item: item, token: token))
.Select(selector: item => item.Location)
.OfType<SourceLocation>()
.Select(selector: ToLspLocation)
.GroupBy(keySelector: location => $"{location.Uri}:{location.Range.Start.Line.ToString(CultureInfo.InvariantCulture)}:{location.Range.Start.Character.ToString(CultureInfo.InvariantCulture)}", comparer: StringComparer.OrdinalIgnoreCase)
.Select(selector: group => group.First())
.ToArray();
return locations;
}
public void Dispose() => _embeddedCSharpService.Dispose();
private static void AddTemplateItems(ICollection<TemplateAnalysisItem> items)
{
AddTemplateMember(
items: items,
label: "Types",
detail: "Collection",
documentation: "All public/internal C# types available to this template.",
insertText: "Types[$0]");
AddTemplateMember(items: items, label: "Classes", detail: "Collection", documentation: "C# classes.", insertText: "Classes[$0]");
AddTemplateMember(items: items, label: "Records", detail: "Collection", documentation: "C# records.", insertText: "Records[$0]");
AddTemplateMember(items: items, label: "Structs", detail: "Collection", documentation: "C# structs.", insertText: "Structs[$0]");
AddTemplateMember(items: items, label: "Interfaces", detail: "Collection", documentation: "C# interfaces.", insertText: "Interfaces[$0]");
AddTemplateMember(items: items, label: "Enums", detail: "Collection", documentation: "C# enums.", insertText: "Enums[$0]");
AddTemplateMember(items: items, label: "Properties", detail: "Collection", documentation: "Properties on the current type.", insertText: "Properties[$0]");
AddTemplateMember(items: items, label: "Methods", detail: "Collection", documentation: "Methods on the current type.", insertText: "Methods[$0]");
AddTemplateMember(items: items, label: "Parameters", detail: "Collection", documentation: "Parameters on the current method.", insertText: "Parameters[$0]");
AddTemplateMember(items: items, label: "Constants", detail: "Collection", documentation: "Constants on the current type.", insertText: "Constants[$0]");
AddTemplateMember(items: items, label: "Attributes", detail: "Collection", documentation: "Attributes on the current metadata item.", insertText: "Attributes[$0]");
AddTemplateMember(items: items, label: "Arguments", detail: "Collection", documentation: "Arguments on the current attribute.", insertText: "Arguments[$0]");
AddTemplateMember(items: items, label: "Values", detail: "Collection", documentation: "Values on the current enum.", insertText: "Values[$0]");
AddTemplateMember(items: items, label: "EnumValues", detail: "Collection", documentation: "Values on the current enum.", insertText: "EnumValues[$0]");
AddTemplateMember(items: items, label: "TypeArguments", detail: "Collection", documentation: "Generic type arguments for the current type reference.", insertText: "TypeArguments[$0]");
AddTemplateMember(items: items, label: "Fields", detail: "Collection", documentation: "Instance fields on the current type.", insertText: "Fields[$0]");
AddTemplateMember(items: items, label: "StaticReadOnlyFields", detail: "Collection", documentation: "Static readonly fields on the current type.", insertText: "StaticReadOnlyFields[$0]");
AddTemplateMember(items: items, label: "Events", detail: "Collection", documentation: "Events on the current type.", insertText: "Events[$0]");
AddTemplateMember(items: items, label: "Delegates", detail: "Collection", documentation: "Delegates declared in the file or on the current type.", insertText: "Delegates[$0]");
AddTemplateMember(items: items, label: "NestedClasses", detail: "Collection", documentation: "Classes nested inside the current type.", insertText: "NestedClasses[$0]");
AddTemplateMember(items: items, label: "NestedEnums", detail: "Collection", documentation: "Enums nested inside the current type.", insertText: "NestedEnums[$0]");
AddTemplateMember(items: items, label: "NestedInterfaces", detail: "Collection", documentation: "Interfaces nested inside the current type.", insertText: "NestedInterfaces[$0]");
AddTemplateMember(items: items, label: "NestedRecords", detail: "Collection", documentation: "Records nested inside the current type.", insertText: "NestedRecords[$0]");
AddTemplateMember(items: items, label: "NestedStructs", detail: "Collection", documentation: "Structs nested inside the current type.", insertText: "NestedStructs[$0]");
AddTemplateMember(items: items, label: "TupleElements", detail: "Collection", documentation: "Elements of the current value tuple type.", insertText: "TupleElements[$0]");
foreach (var scalar in CreateScalarItems())
{
items.Add(item: scalar);
}
foreach (var filter in CreateFilterItems())
{
items.Add(item: filter);
}
}
private static IEnumerable<TemplateAnalysisItem> CreateScalarItems()
{
yield return Scalar(label: "Name", documentation: "Current item name.");
yield return Scalar(label: "name", documentation: "Current item name with camel-case formatting.");
yield return Scalar(label: "FullName", documentation: "Fully-qualified metadata name.");
yield return Scalar(label: "Namespace", documentation: "Containing namespace.");
yield return Scalar(label: "Type", documentation: "TypeScript rendering of the current item's type.");
yield return Scalar(label: "ReturnType", documentation: "Method return type.");
yield return Scalar(label: "Value", documentation: "Constant, enum, attribute argument, or property/field initializer value.");
yield return Scalar(label: "DefaultValue", documentation: "Parameter default value.");
yield return Scalar(label: "Parent", documentation: "Parent metadata object.");
yield return Scalar(label: "IsNullable", documentation: "Whether the current type reference or property is nullable.");
yield return Scalar(label: "IsStatic", documentation: "Whether the current type/member is static.");
yield return Scalar(label: "IsAbstract", documentation: "Whether the current method is abstract.");
yield return Scalar(label: "IsGeneric", documentation: "Whether the current method or type reference is generic.");
yield return Scalar(label: "IsStruct", documentation: "Whether the current type is a struct.");
yield return Scalar(label: "IsIndexer", documentation: "Whether the current property is an indexer.");
yield return Scalar(label: "HasGetter", documentation: "Whether the current property has a getter.");
yield return Scalar(label: "HasSetter", documentation: "Whether the current property has a setter.");
yield return Scalar(label: "IsRequired", documentation: "Whether the current property is required.");
yield return Scalar(label: "HasDefaultValue", documentation: "Whether the current parameter has a default value.");
yield return Scalar(label: "IsCollection", documentation: "Whether the current type reference is a collection.");
yield return Scalar(label: "IsDictionary", documentation: "Whether the current type reference is a dictionary.");
yield return Scalar(label: "IsEnum", documentation: "Whether the current type reference is an enum.");
yield return Scalar(label: "IsPrimitive", documentation: "Whether the current type reference is primitive.");
yield return Scalar(label: "IsDateLike", documentation: "Whether the current type reference represents date/time data.");
yield return Scalar(label: "Default", documentation: "Default TypeScript value for the current type reference.");
yield return Scalar(label: "OriginalName", documentation: "Original C# type name.");
yield return Scalar(label: "ClassName", documentation: "TypeScript-friendly class name.");
yield return Scalar(label: "TypeParameters", documentation: "Legacy type parameter placeholder.");
yield return Scalar(label: "BaseClass", documentation: "Direct base class of the current class or type; empty when the class inherits only from object. Exposes the same members as a class, for example $BaseClass[ extends $Name].");
yield return Scalar(label: "BaseRecord", documentation: "Direct base record of the current record; empty when there is none.");
yield return Scalar(label: "ContainingClass", documentation: "Class the current item is nested inside; empty for top-level items.");
yield return Scalar(label: "AssemblyName", documentation: "Name of the assembly that declares the current item.");
yield return Scalar(label: "DocComment", documentation: "XML documentation comment of the current item. Use $DocComment.Summary, $DocComment.Returns, or $DocComment.Parameters.");
yield return Scalar(label: "ElementType", documentation: "Element type of the current array or enumerable type reference, for example string for string[].");
yield return Scalar(label: "IsFlags", documentation: "Whether the current enum is decorated with [Flags].");
}
private static IEnumerable<TemplateAnalysisItem> CreateFilterItems()
{
yield return Filter(label: "Class", documentation: "Keep only classes.");
yield return Filter(label: "Record", documentation: "Keep only records.");
yield return Filter(label: "Struct", documentation: "Keep only structs.");
yield return Filter(label: "Interface", documentation: "Keep only interfaces.");
yield return Filter(label: "Enum", documentation: "Keep only enums.");
yield return Filter(label: "HasProperties", documentation: "Keep types with properties.");
yield return Filter(label: "HasMethods", documentation: "Keep types with methods.");
yield return Filter(label: "HasConstants", documentation: "Keep types with constants.");
yield return Filter(label: "Static", documentation: "Keep static types.");
yield return Filter(label: "NonStatic", documentation: "Keep non-static types.");
yield return Filter(label: "Public", documentation: "Keep public metadata items.");
yield return Filter(label: "Internal", documentation: "Keep internal metadata items.");
yield return Filter(label: "Name=", documentation: "Filter by metadata name.");
yield return Filter(label: "Namespace=", documentation: "Filter by namespace.");
yield return Filter(label: "[Attribute]", documentation: "Filter by attribute name.");
yield return Filter(label: ":BaseType", documentation: "Filter by base type or implemented interface.");
}
private static TemplateAnalysisItem Scalar(
string label,
string documentation) =>
new(
Label: label,
CompletionKind: CompletionKind.Property,
Detail: "Template member",
Documentation: documentation,
TargetKind: TemplateAnalysisTargetKind.TemplateMember);
private static TemplateAnalysisItem Filter(
string label,
string documentation) =>
new(
Label: label,
CompletionKind: CompletionKind.Keyword,
Detail: "Template filter",
Documentation: documentation,
TargetKind: TemplateAnalysisTargetKind.Filter);
private static void AddTemplateMember(
ICollection<TemplateAnalysisItem> items,
string label,
string detail,
string documentation,
string insertText)
{
items.Add(
item: new TemplateAnalysisItem(
Label: label,
CompletionKind: CompletionKind.Snippet,
Detail: detail,
Documentation: documentation,
InsertText: insertText,
InsertTextFormat: InsertTextFormat.Snippet,
TargetKind: TemplateAnalysisTargetKind.TemplateMember));
}
private static void AddHelperItems(
ICollection<TemplateAnalysisItem> items,
string content)
{
foreach (Match match in Regex.Matches(
input: content,
pattern: @"(?:public\s+|private\s+|internal\s+|protected\s+|static\s+)*[A-Za-z_][A-Za-z0-9_<>,\.\s\?]*\s+(?<name>[A-Za-z_][A-Za-z0-9_]*)\s*\(",
options: RegexOptions.CultureInvariant,
matchTimeout: RegexTimeout))
{
var name = match.Groups[groupname: "name"].Value;
if (name.Equals(value: "Template", comparisonType: StringComparison.Ordinal)
|| name.Equals(value: "if", comparisonType: StringComparison.Ordinal)
|| name.Equals(value: "for", comparisonType: StringComparison.Ordinal)
|| name.Equals(value: "foreach", comparisonType: StringComparison.Ordinal)
|| name.Equals(value: "while", comparisonType: StringComparison.Ordinal)
|| name.Equals(value: "switch", comparisonType: StringComparison.Ordinal))
{
continue;
}
items.Add(
item: new TemplateAnalysisItem(
Label: name,
CompletionKind: CompletionKind.Function,
Detail: "Template helper",
Documentation: "Helper method declared in this .tst template.",
TargetKind: TemplateAnalysisTargetKind.Helper));
}
}
private static IReadOnlyList<LspCompletionItem> MergeEmbeddedCSharpCompletions(
IReadOnlyList<LspCompletionItem> embeddedItems)
{
var items = new List<LspCompletionItem>(collection: embeddedItems);
foreach (var keyword in CSharpCompletionKeywords)
{
items.Add(
item: new LspCompletionItem(
Label: keyword,
Kind: CompletionKind.Keyword,
Detail: "C# keyword",
Documentation: "Keyword available inside a Typewriter C# helper block."));
}
foreach (var typeName in CSharpCodeModelTypes)
{
items.Add(
item: new LspCompletionItem(
Label: typeName,
Kind: CompletionKind.Class,
Detail: "Typewriter.CodeModel type",
Documentation: "CodeModel type available to compiled Typewriter helper methods."));
}
return DeduplicateCompletions(items: items);
}
private static IReadOnlyList<LspCompletionItem> CreateCSharpCompletionItems(
IReadOnlyList<TemplateAnalysisItem> analysisItems)
{
var items = new List<LspCompletionItem>();
foreach (var keyword in CSharpCompletionKeywords)
{
items.Add(
item: new LspCompletionItem(
Label: keyword,
Kind: CompletionKind.Keyword,
Detail: "C# keyword",
Documentation: "Keyword available inside a Typewriter C# helper block."));
}
foreach (var typeName in CSharpCodeModelTypes)
{
items.Add(
item: new LspCompletionItem(
Label: typeName,
Kind: CompletionKind.Class,
Detail: "Typewriter.CodeModel type",
Documentation: "CodeModel type available to compiled Typewriter helper methods."));
}
foreach (var helper in analysisItems.Where(predicate: item => item.TargetKind == TemplateAnalysisTargetKind.Helper))
{
items.Add(
item: new LspCompletionItem(
Label: helper.Label,
Kind: CompletionKind.Function,
Detail: helper.Detail,
Documentation: helper.Documentation));
}
return DeduplicateCompletions(items: items);
}
private static IReadOnlyList<LspCompletionItem> CreateTypeScriptCompletionItems(
IReadOnlyList<TemplateAnalysisItem> analysisItems)
{
var items = new List<LspCompletionItem>();
AddTypewriterSnippetItems(items: items);
foreach (var keyword in TypeScriptCompletionKeywords)
{
items.Add(
item: new LspCompletionItem(
Label: keyword,
Kind: CompletionKind.Keyword,
Detail: "TypeScript keyword",
Documentation: "Keyword available inside generated TypeScript output text."));
}
foreach (var typeName in TypeScriptBuiltInTypes)
{
items.Add(
item: new LspCompletionItem(
Label: typeName,
Kind: CompletionKind.Class,
Detail: "TypeScript type",
Documentation: "Built-in or utility type available inside generated TypeScript output text."));
}
foreach (var type in analysisItems.Where(predicate: item => item.TargetKind == TemplateAnalysisTargetKind.Type))
{
items.Add(
item: new LspCompletionItem(
Label: type.Label,
Kind: type.CompletionKind,
Detail: type.Detail,
Documentation: type.Documentation));
}
return DeduplicateCompletions(items: items);
}
private static void AddTypewriterSnippetItems(ICollection<LspCompletionItem> items)
{
AddTypewriterSnippet(
items: items,
label: "$Types",
insertText: "Types[$0]",
documentation: "All public/internal C# types available to this template.");
AddTypewriterSnippet(items: items, label: "$Classes", insertText: "Classes[$0]", documentation: "C# classes.");
AddTypewriterSnippet(items: items, label: "$Records", insertText: "Records[$0]", documentation: "C# records.");
AddTypewriterSnippet(items: items, label: "$Structs", insertText: "Structs[$0]", documentation: "C# structs.");
AddTypewriterSnippet(items: items, label: "$Interfaces", insertText: "Interfaces[$0]", documentation: "C# interfaces.");
AddTypewriterSnippet(items: items, label: "$Enums", insertText: "Enums[$0]", documentation: "C# enums.");
AddTypewriterSnippet(items: items, label: "$Properties", insertText: "Properties[$0]", documentation: "Properties on the current type.");
AddTypewriterSnippet(items: items, label: "$Methods", insertText: "Methods[$0]", documentation: "Methods on the current type.");
AddTypewriterSnippet(items: items, label: "$Parameters", insertText: "Parameters[$0]", documentation: "Parameters on the current method.");
AddTypewriterSnippet(items: items, label: "$Constants", insertText: "Constants[$0]", documentation: "Constants on the current type.");
AddTypewriterSnippet(items: items, label: "$Name", insertText: "Name", documentation: "Current item name.");
AddTypewriterSnippet(items: items, label: "$name", insertText: "name", documentation: "Current item name with camel-case formatting.");
AddTypewriterSnippet(items: items, label: "$Type", insertText: "Type", documentation: "TypeScript rendering of the current item's type.");
AddTypewriterSnippet(items: items, label: "$Default", insertText: "Default", documentation: "Default TypeScript value for the current type reference.");
}
private static void AddTypewriterSnippet(
ICollection<LspCompletionItem> items,
string label,
string insertText,
string documentation)
{
items.Add(
item: new LspCompletionItem(
Label: label,
Kind: CompletionKind.Snippet,
Detail: "Typewriter template expression",
Documentation: documentation,
InsertText: "$" + insertText,
InsertTextFormat: InsertTextFormat.Snippet));
}
private static IReadOnlyList<LspCompletionItem> DeduplicateCompletions(
IEnumerable<LspCompletionItem> items) =>
items
.GroupBy(keySelector: item => item.Label, comparer: StringComparer.Ordinal)
.Select(selector: group => group.First())
.OrderBy(keySelector: item => item.Label, comparer: StringComparer.OrdinalIgnoreCase)
.ToArray();
#pragma warning disable MA0051 // Method is too long
private static void AddMetadataItems(
ICollection<TemplateAnalysisItem> items,
ProjectMetadata project)
#pragma warning restore MA0051 // Method is too long
{
foreach (var type in project.Types)
{
items.Add(
item: new TemplateAnalysisItem(
Label: type.Name,
CompletionKind: GetTypeCompletionKind(type: type),
Detail: $"{type.Kind} {type.FullName}",
Documentation: type.Documentation ?? $"C# {type.Kind.ToString().ToLowerInvariant()} {type.FullName}.",
Location: type.Location,
TargetKind: TemplateAnalysisTargetKind.Type));
items.Add(
item: new TemplateAnalysisItem(
Label: type.FullName,
CompletionKind: GetTypeCompletionKind(type: type),
Detail: $"{type.Kind} {type.FullName}",
Documentation: type.Documentation ?? $"C# {type.Kind.ToString().ToLowerInvariant()} {type.FullName}.",
Location: type.Location,
TargetKind: TemplateAnalysisTargetKind.Type));
foreach (var property in type.Properties)
{
AddMember(
items: items,
label: property.Name,
completionKind: CompletionKind.Property,
detail: $"Property {type.Name}.{property.Name}: {property.Type.Name}",
documentation: property.Documentation ?? $"C# property {property.FullName}.",
location: property.Location,
targetKind: TemplateAnalysisTargetKind.Property);
foreach (var parameter in property.Parameters)
{
AddMember(
items: items,
label: parameter.Name,
completionKind: CompletionKind.Variable,
detail: $"Indexer parameter {property.Name}.{parameter.Name}: {parameter.Type.Name}",
documentation: parameter.Documentation ?? $"C# indexer parameter {parameter.FullName}.",
location: parameter.Location,
targetKind: TemplateAnalysisTargetKind.Parameter);
}
}
foreach (var method in type.Methods)
{
AddMember(
items: items,
label: method.Name,
completionKind: CompletionKind.Method,
detail: $"Method {type.Name}.{method.Name}(): {method.ReturnType.Name}",
documentation: method.Documentation ?? $"C# method {method.FullName}.",
location: method.Location,
targetKind: TemplateAnalysisTargetKind.Method);
foreach (var parameter in method.Parameters)
{
AddMember(
items: items,
label: parameter.Name,
completionKind: CompletionKind.Variable,
detail: $"Parameter {method.Name}.{parameter.Name}: {parameter.Type.Name}",
documentation: parameter.Documentation ?? $"C# parameter {parameter.FullName}.",
location: parameter.Location,
targetKind: TemplateAnalysisTargetKind.Parameter);
}
}
foreach (var constant in type.Constants)
{
AddMember(
items: items,
label: constant.Name,
completionKind: CompletionKind.Constant,
detail: $"Constant {type.Name}.{constant.Name}: {constant.Type.Name}",
documentation: constant.Documentation ?? $"C# constant {constant.FullName}.",
location: constant.Location,
targetKind: TemplateAnalysisTargetKind.Constant);
}
foreach (var enumValue in type.EnumValues)
{
AddMember(
items: items,
label: enumValue.Name,
completionKind: CompletionKind.EnumMember,
detail: $"Enum value {type.Name}.{enumValue.Name}",
documentation: enumValue.Documentation ?? $"C# enum value {type.FullName}.{enumValue.Name}.",
location: enumValue.Location,
targetKind: TemplateAnalysisTargetKind.EnumValue);
}
}
}
private static void AddMember(
ICollection<TemplateAnalysisItem> items,
string label,
int completionKind,
string detail,
string documentation,
SourceLocation? location,
TemplateAnalysisTargetKind targetKind)
{
items.Add(
item: new TemplateAnalysisItem(
Label: label,
CompletionKind: completionKind,
Detail: detail,
Documentation: documentation,
Location: location,
TargetKind: targetKind));
}
private static IReadOnlyList<string> ResolveProjectPaths(
LanguageServerSettings settings,
string workspacePath,
string templatePath)
{
var configuredProjectPath = settings.ResolveProjectPath(workspacePath: workspacePath);
if (!string.IsNullOrWhiteSpace(value: configuredProjectPath))
{
return [configuredProjectPath];
}
var root = Path.GetFullPath(path: workspacePath);
if (File.Exists(path: root) && root.EndsWith(value: ".csproj", comparisonType: StringComparison.OrdinalIgnoreCase))
{
return [root];
}
var projects = FindProjectPaths(root: root);
if (projects.Length == 1)
{
return [projects[0]];
}
if (projects.Length > 1 && settings.AllProjects)
{
return projects;
}
var nearestProjectPath = FindNearestAncestorProjectPath(
templatePath: templatePath,
workspacePath: root,
projectPaths: projects);
return !string.IsNullOrWhiteSpace(value: nearestProjectPath)
? [nearestProjectPath]
: [];
}
private static string? FindNearestAncestorProjectPath(
string? templatePath,
string workspacePath,
IEnumerable<string> projectPaths)
{
if (string.IsNullOrWhiteSpace(value: templatePath))
{
return null;
}
var projectPathSet = projectPaths
.Select(selector: Path.GetFullPath)
.ToHashSet(comparer: StringComparer.OrdinalIgnoreCase);
var workspaceRoot = GetProjectSearchRoot(workspacePath: workspacePath);
var directory = Path.GetDirectoryName(path: Path.GetFullPath(path: templatePath));
while (!string.IsNullOrWhiteSpace(value: directory)
&& IsSameOrChildPath(path: directory, root: workspaceRoot))
{
if (Directory.Exists(path: directory))
{
var projectPath = Directory
.EnumerateFiles(path: directory, searchPattern: "*.csproj", searchOption: SearchOption.TopDirectoryOnly)
.Select(selector: Path.GetFullPath)
.Where(predicate: projectPathSet.Contains)
.Order(comparer: StringComparer.OrdinalIgnoreCase)
.FirstOrDefault();
if (!string.IsNullOrWhiteSpace(value: projectPath))
{
return projectPath;
}
}
if (PathEquals(left: directory, right: workspaceRoot))
{
return null;
}
directory = Directory.GetParent(path: directory)?.FullName;
}
return null;
}
private static string GetProjectSearchRoot(string workspacePath)
{
var root = Path.GetFullPath(path: workspacePath);
return File.Exists(path: root)
? Path.GetDirectoryName(path: root) ?? root
: root;
}
private static bool IsSameOrChildPath(
string path,
string root)
{
var relativePath = Path.GetRelativePath(relativeTo: root, path: path);
return string.Equals(a: relativePath, b: ".", comparisonType: StringComparison.Ordinal)
|| (!relativePath.StartsWith(value: "..", comparisonType: StringComparison.Ordinal)
&& !Path.IsPathRooted(path: relativePath));
}
private static bool PathEquals(
string left,
string right) =>
string.Equals(
a: Path.TrimEndingDirectorySeparator(path: Path.GetFullPath(path: left)),
b: Path.TrimEndingDirectorySeparator(path: Path.GetFullPath(path: right)),
comparisonType: StringComparison.OrdinalIgnoreCase);
private static string[] FindProjectPaths(string root)
{
if (File.Exists(path: root)
&& (root.EndsWith(value: ".sln", comparisonType: StringComparison.OrdinalIgnoreCase)
|| root.EndsWith(value: ".slnx", comparisonType: StringComparison.OrdinalIgnoreCase)))
{
return root.EndsWith(value: ".slnx", comparisonType: StringComparison.OrdinalIgnoreCase)
? GetProjectsFromSlnx(solutionPath: root)
: GetProjectsFromSln(solutionPath: root);
}
if (File.Exists(path: root))
{
root = Path.GetDirectoryName(path: root) ?? root;
}
return Directory.Exists(path: root)
? Directory.EnumerateFiles(path: root, searchPattern: "*.csproj", searchOption: SearchOption.AllDirectories)
.Where(predicate: path => !path.Contains(value: $"{Path.DirectorySeparatorChar}bin{Path.DirectorySeparatorChar}", comparisonType: StringComparison.OrdinalIgnoreCase))
.Where(predicate: path => !path.Contains(value: $"{Path.DirectorySeparatorChar}obj{Path.DirectorySeparatorChar}", comparisonType: StringComparison.OrdinalIgnoreCase))
.Order(comparer: StringComparer.OrdinalIgnoreCase)
.Select(selector: Path.GetFullPath)
.ToArray()
: [];
}
private static string[] GetProjectsFromSlnx(string solutionPath)
{
var solutionDirectory = Path.GetDirectoryName(path: solutionPath) ?? Environment.CurrentDirectory;
var document = XDocument.Load(uri: solutionPath);
return document
.Descendants()
.Where(predicate: element => element.Name.LocalName.Equals(value: "Project", comparisonType: StringComparison.Ordinal))
.Select(selector: element => element.Attribute(name: "Path")?.Value)
.Where(predicate: path => !string.IsNullOrWhiteSpace(value: path))
.Select(selector: path => ResolveSolutionProjectPath(solutionDirectory: solutionDirectory, projectPath: path!))
.Where(predicate: path => path.EndsWith(value: ".csproj", comparisonType: StringComparison.OrdinalIgnoreCase))
.Where(predicate: File.Exists)
.Order(comparer: StringComparer.OrdinalIgnoreCase)
.ToArray();
}
private static string[] GetProjectsFromSln(string solutionPath)
{
var solutionDirectory = Path.GetDirectoryName(path: solutionPath) ?? Environment.CurrentDirectory;
#pragma warning disable SEC0116,SCS0018
return File.ReadLines(path: solutionPath)
.Select(selector: TryReadSlnProjectPath)
.Where(predicate: path => !string.IsNullOrWhiteSpace(value: path))
.Select(selector: path => ResolveSolutionProjectPath(solutionDirectory: solutionDirectory, projectPath: path!))
.Where(predicate: path => path.EndsWith(value: ".csproj", comparisonType: StringComparison.OrdinalIgnoreCase))
.Where(predicate: File.Exists)
.Order(comparer: StringComparer.OrdinalIgnoreCase)
.ToArray();
#pragma warning restore SEC0116,SCS0018
}
private static string? TryReadSlnProjectPath(string line)
{
if (!line.StartsWith(value: "Project(", comparisonType: StringComparison.Ordinal))
{
return null;
}
var parts = line.Split(separator: ',', options: StringSplitOptions.TrimEntries);
return parts.Length >= 2
? parts[1].Trim(trimChar: '"')
: null;
}
private static string ResolveSolutionProjectPath(
string solutionDirectory,
string projectPath)
{
var normalized = projectPath.Replace(oldChar: '\\', newChar: Path.DirectorySeparatorChar);
return Path.GetFullPath(
path: Path.IsPathRooted(path: normalized)
? normalized
: Path.Combine(path1: solutionDirectory, path2: normalized));
}
private static bool ShouldIncludeDefinition(
TemplateAnalysisItem item,
TemplateToken token)
{
if (item.Location is null)
{
return false;
}
var text = token.Text.Trim(trimChar: '$');
if (MatchesLabel(item: item, token: text))
{
return true;
}
if (!token.HasTemplatePrefix)
{
return false;
}
return text switch
{
"Types" => item.TargetKind == TemplateAnalysisTargetKind.Type,
"Classes" => item.TargetKind == TemplateAnalysisTargetKind.Type && item.Detail.StartsWith(value: "Class", comparisonType: StringComparison.OrdinalIgnoreCase),
"Records" => item.TargetKind == TemplateAnalysisTargetKind.Type && item.Detail.StartsWith(value: "Record", comparisonType: StringComparison.OrdinalIgnoreCase),
"Structs" => item.TargetKind == TemplateAnalysisTargetKind.Type && item.Detail.StartsWith(value: "Struct", comparisonType: StringComparison.OrdinalIgnoreCase),
"Interfaces" => item.TargetKind == TemplateAnalysisTargetKind.Type && item.Detail.StartsWith(value: "Interface", comparisonType: StringComparison.OrdinalIgnoreCase),
"Enums" => item.TargetKind == TemplateAnalysisTargetKind.Type && item.Detail.StartsWith(value: "Enum", comparisonType: StringComparison.OrdinalIgnoreCase),
"Properties" => item.TargetKind == TemplateAnalysisTargetKind.Property,
"Methods" => item.TargetKind == TemplateAnalysisTargetKind.Method,
"Parameters" => item.TargetKind == TemplateAnalysisTargetKind.Parameter,
"Constants" => item.TargetKind == TemplateAnalysisTargetKind.Constant,
"Values" or "EnumValues" => item.TargetKind == TemplateAnalysisTargetKind.EnumValue,
_ => false,
};
}
private static bool MatchesToken(
TemplateAnalysisItem item,
string token)
{
var normalizedToken = token.Trim(trimChar: '$');
return MatchesLabel(item: item, token: normalizedToken)
|| item.Detail.Contains(value: normalizedToken, comparisonType: StringComparison.OrdinalIgnoreCase);
}
private static bool MatchesLabel(
TemplateAnalysisItem item,
string token)
{
var normalizedToken = token.Trim(trimChar: '$');
return item.Label.Equals(value: normalizedToken, comparisonType: StringComparison.OrdinalIgnoreCase);
}
private static string CreateHoverMarkdown(TemplateAnalysisItem item)
{
var prefix = item.TargetKind is TemplateAnalysisTargetKind.TemplateMember
or TemplateAnalysisTargetKind.Filter
or TemplateAnalysisTargetKind.Helper
? "$"
: string.Empty;
return $"**{prefix}{item.Label}**\n\n{item.Detail}\n\n{item.Documentation}";
}
private static LspRange CreateRange(
TextDocumentState document,
int start,
int end) =>
new(Start: OffsetToPosition(text: document.Text, offset: start), End: OffsetToPosition(text: document.Text, offset: end));
private static LspPosition OffsetToPosition(
string text,
int offset)
{
var line = 0;
var character = 0;
for (var index = 0; index < offset && index < text.Length; index++)
{
if (text[index: index] == '\n')
{
line++;
character = 0;