-
Notifications
You must be signed in to change notification settings - Fork 4k
/
SyntaxGenerator.cs
2410 lines (2016 loc) · 109 KB
/
SyntaxGenerator.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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.LanguageService;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Simplification;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Editing
{
/// <summary>
/// A language agnostic factory for creating syntax nodes.
///
/// This API can be used to create language specific syntax nodes that are semantically
/// similar between languages.
///
/// The trees generated by this API will try to respect user preferences when
/// possible. For example, generating <see cref="MemberAccessExpression(SyntaxNode, string)"/>
/// will be done in a way such that "this." or "Me." will be simplified according to user
/// preference if <see cref="Simplifier" /> is used.
/// </summary>
public abstract class SyntaxGenerator : ILanguageService
{
public static readonly SyntaxRemoveOptions DefaultRemoveOptions = SyntaxRemoveOptions.KeepUnbalancedDirectives | SyntaxRemoveOptions.AddElasticMarker;
internal abstract SyntaxTrivia CarriageReturnLineFeed { get; }
internal abstract SyntaxTrivia ElasticCarriageReturnLineFeed { get; }
internal abstract SyntaxTrivia ElasticMarker { get; }
internal abstract bool RequiresExplicitImplementationForInterfaceMembers { get; }
internal ISyntaxFacts SyntaxFacts => SyntaxGeneratorInternal.SyntaxFacts;
internal abstract SyntaxGeneratorInternal SyntaxGeneratorInternal { get; }
internal abstract SyntaxTrivia Whitespace(string text);
internal abstract SyntaxTrivia SingleLineComment(string text);
internal abstract SyntaxToken CreateInterpolatedStringStartToken(bool isVerbatim);
internal abstract SyntaxToken CreateInterpolatedStringEndToken();
/// <summary>
/// Gets the <see cref="SyntaxGenerator"/> for the specified language.
/// </summary>
public static SyntaxGenerator GetGenerator(Workspace workspace, string language)
=> GetGenerator(workspace.Services.SolutionServices, language);
/// <summary>
/// Gets the <see cref="SyntaxGenerator"/> for the specified language.
/// </summary>
internal static SyntaxGenerator GetGenerator(SolutionServices services, string language)
=> services.GetLanguageServices(language).GetRequiredService<SyntaxGenerator>();
/// <summary>
/// Gets the <see cref="SyntaxGenerator"/> for the language corresponding to the document.
/// </summary>
public static SyntaxGenerator GetGenerator(Document document)
=> GetGenerator(document.Project);
/// <summary>
/// Gets the <see cref="SyntaxGenerator"/> for the language corresponding to the project.
/// </summary>
public static SyntaxGenerator GetGenerator(Project project)
=> project.Services.GetRequiredService<SyntaxGenerator>();
#region Declarations
/// <summary>
/// Returns the node if it is a declaration, the immediate enclosing declaration if one exists, or null.
/// </summary>
public SyntaxNode? GetDeclaration(SyntaxNode? node)
{
while (node != null)
{
if (GetDeclarationKind(node) != DeclarationKind.None)
{
return node;
}
node = node.Parent;
}
return null;
}
/// <summary>
/// Returns the enclosing declaration of the specified kind or null.
/// </summary>
public SyntaxNode? GetDeclaration(SyntaxNode? node, DeclarationKind kind)
{
while (node != null)
{
if (GetDeclarationKind(node) == kind)
{
return node;
}
node = node.Parent;
}
return null;
}
/// <summary>
/// Creates a field declaration.
/// </summary>
public abstract SyntaxNode FieldDeclaration(
string name,
SyntaxNode type,
Accessibility accessibility = Accessibility.NotApplicable,
DeclarationModifiers modifiers = default,
SyntaxNode? initializer = null);
/// <summary>
/// Creates a field declaration matching an existing field symbol.
/// </summary>
public SyntaxNode FieldDeclaration(IFieldSymbol field)
{
var initializer = field.HasConstantValue ? this.LiteralExpression(field.ConstantValue) : null;
return FieldDeclaration(field, initializer);
}
/// <summary>
/// Creates a field declaration matching an existing field symbol.
/// </summary>
public SyntaxNode FieldDeclaration(IFieldSymbol field, SyntaxNode? initializer)
{
return FieldDeclaration(
field.Name,
TypeExpression(field.Type),
field.DeclaredAccessibility,
DeclarationModifiers.From(field),
initializer);
}
//internal abstract SyntaxNode ObjectMemberInitializer(IEnumerable<SyntaxNode> fieldInitializers);
//internal abstract SyntaxNode NamedFieldInitializer(SyntaxNode name, SyntaxNode value);
//internal abstract SyntaxNode WithObjectCreationInitializer(SyntaxNode objectCreationExpression, SyntaxNode initializer);
/// <summary>
/// Creates a method declaration.
/// </summary>
#pragma warning disable RS0026 // Do not add multiple public overloads with optional parameters
public SyntaxNode MethodDeclaration(
string name,
IEnumerable<SyntaxNode>? parameters = null,
IEnumerable<string>? typeParameters = null,
SyntaxNode? returnType = null,
Accessibility accessibility = Accessibility.NotApplicable,
DeclarationModifiers modifiers = default,
IEnumerable<SyntaxNode>? statements = null)
{
return MethodDeclaration(
name, parameters, typeParameters?.Select(n => TypeParameter(n)), returnType, accessibility, modifiers, statements);
}
#pragma warning restore RS0026 // Do not add multiple public overloads with optional parameters
private protected abstract SyntaxNode MethodDeclaration(
string name,
IEnumerable<SyntaxNode>? parameters,
IEnumerable<SyntaxNode>? typeParameters,
SyntaxNode? returnType,
Accessibility accessibility,
DeclarationModifiers modifiers,
IEnumerable<SyntaxNode>? statements);
/// <summary>
/// Creates a method declaration matching an existing method symbol.
/// </summary>
public SyntaxNode MethodDeclaration(IMethodSymbol method, IEnumerable<SyntaxNode>? statements = null)
=> MethodDeclaration(method, method.Name, statements);
internal SyntaxNode MethodDeclaration(IMethodSymbol method, string name, IEnumerable<SyntaxNode>? statements = null)
{
var decl = MethodDeclaration(
name,
typeParameters: method.TypeParameters.Select(p => TypeParameter(p)),
parameters: method.Parameters.Select(p => ParameterDeclaration(p)),
returnType: method.ReturnType.IsSystemVoid() ? null : TypeExpression(method.ReturnType, method.RefKind),
accessibility: method.DeclaredAccessibility,
modifiers: DeclarationModifiers.From(method),
statements: statements);
if (method.TypeParameters.Length > 0)
{
// Overrides are special. Specifically, in an override, if a type parameter has no constraints, then we
// want to still add `where T : default` if that type parameter is used with NRT (e.g. `T?`) that way
// the language can distinguish if this is a Nullable Value Type or not.
if (method.IsOverride)
{
foreach (var typeParameter in method.TypeParameters)
{
if (HasNullableAnnotation(typeParameter, method))
{
if (!HasSomeConstraint(typeParameter))
{
// if there are no constraints, add `where T : default` so it's known this not an NVT
// and is just an unconstrained type parameter.
decl = WithDefaultConstraint(decl, typeParameter.Name);
}
else if (!typeParameter.HasValueTypeConstraint)
{
// if there are some constraints, add `where T : class` so it's known this is not an NVT
// and must specifically be some reference type.
decl = WithTypeConstraint(decl, typeParameter.Name, SpecialTypeConstraintKind.ReferenceType);
}
}
}
}
else
{
decl = this.WithTypeParametersAndConstraints(decl, method.TypeParameters);
}
}
if (method.ExplicitInterfaceImplementations.Length > 0)
{
decl = this.WithExplicitInterfaceImplementations(decl,
ImmutableArray<ISymbol>.CastUp(method.ExplicitInterfaceImplementations));
}
return decl;
bool HasNullableAnnotation(ITypeParameterSymbol typeParameter, IMethodSymbol method)
{
return method.ReturnType.GetReferencedTypeParameters().Any(t => IsNullableAnnotatedTypeParameter(typeParameter, t)) ||
method.Parameters.Any(p => p.Type.GetReferencedTypeParameters().Any(t => IsNullableAnnotatedTypeParameter(typeParameter, t)));
}
static bool IsNullableAnnotatedTypeParameter(ITypeParameterSymbol typeParameter, ITypeParameterSymbol current)
{
return Equals(current, typeParameter) && current.NullableAnnotation == NullableAnnotation.Annotated;
}
}
/// <summary>
/// Creates a method declaration.
/// </summary>
public virtual SyntaxNode OperatorDeclaration(
OperatorKind kind,
IEnumerable<SyntaxNode>? parameters = null,
SyntaxNode? returnType = null,
Accessibility accessibility = Accessibility.NotApplicable,
DeclarationModifiers modifiers = default,
IEnumerable<SyntaxNode>? statements = null)
{
throw new NotImplementedException();
}
/// <summary>
/// Creates a operator or conversion declaration matching an existing method symbol.
/// </summary>
public SyntaxNode OperatorDeclaration(IMethodSymbol method, IEnumerable<SyntaxNode>? statements = null)
{
if (method.MethodKind is not (MethodKind.UserDefinedOperator or MethodKind.Conversion))
throw new ArgumentException("Method is not an operator.");
var decl = OperatorDeclaration(
GetOperatorKind(method),
parameters: method.Parameters.Select(p => ParameterDeclaration(p)),
returnType: method.ReturnType.IsSystemVoid() ? null : TypeExpression(method.ReturnType, method.RefKind),
accessibility: method.DeclaredAccessibility,
modifiers: DeclarationModifiers.From(method),
statements: statements);
return decl;
}
private static OperatorKind GetOperatorKind(IMethodSymbol method)
=> method.Name switch
{
WellKnownMemberNames.ImplicitConversionName => OperatorKind.ImplicitConversion,
WellKnownMemberNames.ExplicitConversionName => OperatorKind.ExplicitConversion,
WellKnownMemberNames.AdditionOperatorName => OperatorKind.Addition,
WellKnownMemberNames.BitwiseAndOperatorName => OperatorKind.BitwiseAnd,
WellKnownMemberNames.BitwiseOrOperatorName => OperatorKind.BitwiseOr,
WellKnownMemberNames.DecrementOperatorName => OperatorKind.Decrement,
WellKnownMemberNames.DivisionOperatorName => OperatorKind.Division,
WellKnownMemberNames.EqualityOperatorName => OperatorKind.Equality,
WellKnownMemberNames.ExclusiveOrOperatorName => OperatorKind.ExclusiveOr,
WellKnownMemberNames.FalseOperatorName => OperatorKind.False,
WellKnownMemberNames.GreaterThanOperatorName => OperatorKind.GreaterThan,
WellKnownMemberNames.GreaterThanOrEqualOperatorName => OperatorKind.GreaterThanOrEqual,
WellKnownMemberNames.IncrementOperatorName => OperatorKind.Increment,
WellKnownMemberNames.InequalityOperatorName => OperatorKind.Inequality,
WellKnownMemberNames.LeftShiftOperatorName => OperatorKind.LeftShift,
WellKnownMemberNames.LessThanOperatorName => OperatorKind.LessThan,
WellKnownMemberNames.LessThanOrEqualOperatorName => OperatorKind.LessThanOrEqual,
WellKnownMemberNames.LogicalNotOperatorName => OperatorKind.LogicalNot,
WellKnownMemberNames.ModulusOperatorName => OperatorKind.Modulus,
WellKnownMemberNames.MultiplyOperatorName => OperatorKind.Multiply,
WellKnownMemberNames.OnesComplementOperatorName => OperatorKind.OnesComplement,
WellKnownMemberNames.RightShiftOperatorName => OperatorKind.RightShift,
WellKnownMemberNames.UnsignedRightShiftOperatorName => OperatorKind.UnsignedRightShift,
WellKnownMemberNames.SubtractionOperatorName => OperatorKind.Subtraction,
WellKnownMemberNames.TrueOperatorName => OperatorKind.True,
WellKnownMemberNames.UnaryNegationOperatorName => OperatorKind.UnaryNegation,
WellKnownMemberNames.UnaryPlusOperatorName => OperatorKind.UnaryPlus,
_ => throw new ArgumentException("Unknown operator kind."),
};
/// <summary>
/// Creates a parameter declaration.
/// </summary>
#pragma warning disable RS0026 // Do not add multiple public overloads with optional parameters
public SyntaxNode ParameterDeclaration(
string name,
SyntaxNode? type = null,
SyntaxNode? initializer = null,
RefKind refKind = RefKind.None)
{
return ParameterDeclaration(name, type, initializer, refKind, isExtension: false, isParams: false);
}
#pragma warning restore RS0026 // Do not add multiple public overloads with optional parameters
private protected abstract SyntaxNode ParameterDeclaration(
string name,
SyntaxNode? type,
SyntaxNode? initializer,
RefKind refKind,
bool isExtension,
bool isParams);
/// <summary>
/// Creates a parameter declaration matching an existing parameter symbol.
/// </summary>
public SyntaxNode ParameterDeclaration(IParameterSymbol symbol, SyntaxNode? initializer = null)
{
return ParameterDeclaration(
symbol.Name,
TypeExpression(symbol.Type),
initializer is not null ? initializer :
symbol.HasExplicitDefaultValue ? GenerateExpression(symbol.Type, symbol.ExplicitDefaultValue, canUseFieldReference: true) : null,
symbol.RefKind,
isExtension: symbol is { Ordinal: 0, ContainingSymbol: IMethodSymbol { IsExtensionMethod: true } },
symbol.IsParams);
}
private protected abstract SyntaxNode TypeParameter(ITypeParameterSymbol typeParameter);
private protected abstract SyntaxNode TypeParameter(string name);
private protected abstract SyntaxNode GenerateExpression(ITypeSymbol? type, object? value, bool canUseFieldReference);
/// <summary>
/// Creates a property declaration. The property will have a <c>get</c> accessor if
/// <see cref="DeclarationModifiers.IsWriteOnly"/> is <see langword="false"/> and will have
/// a <c>set</c> accessor if <see cref="DeclarationModifiers.IsReadOnly"/> is <see
/// langword="false"/>.
/// </summary>
/// <remarks>
/// In C# there is a distinction between passing in <see langword="null"/> for <paramref
/// name="getAccessorStatements"/> or <paramref name="setAccessorStatements"/> versus
/// passing in an empty list. <see langword="null"/> will produce an auto-property-accessor
/// (i.e. <c>get;</c>) whereas an empty list will produce an accessor with an empty block
/// (i.e. <c>get { }</c>).
/// </remarks>
public abstract SyntaxNode PropertyDeclaration(
string name,
SyntaxNode type,
Accessibility accessibility = Accessibility.NotApplicable,
DeclarationModifiers modifiers = default,
IEnumerable<SyntaxNode>? getAccessorStatements = null,
IEnumerable<SyntaxNode>? setAccessorStatements = null);
/// <summary>
/// Creates a property declaration using an existing property symbol as a signature.
/// </summary>
public SyntaxNode PropertyDeclaration(
IPropertySymbol property,
IEnumerable<SyntaxNode>? getAccessorStatements = null,
IEnumerable<SyntaxNode>? setAccessorStatements = null)
{
var propertyAccessibility = property.DeclaredAccessibility;
var getMethodSymbol = property.GetMethod;
var setMethodSymbol = property.SetMethod;
SyntaxNode? getAccessor = null;
SyntaxNode? setAccessor = null;
if (getMethodSymbol is not null)
{
var getMethodAccessibility = getMethodSymbol.DeclaredAccessibility;
getAccessor = GetAccessorDeclaration(getMethodAccessibility < propertyAccessibility ? getMethodAccessibility : Accessibility.NotApplicable, getAccessorStatements);
}
if (setMethodSymbol is not null)
{
var setMethodAccessibility = setMethodSymbol.DeclaredAccessibility;
setAccessor = SetAccessorDeclaration(setMethodAccessibility < propertyAccessibility ? setMethodAccessibility : Accessibility.NotApplicable, setAccessorStatements);
}
var propDecl = PropertyDeclaration(
property.Name,
TypeExpression(property.Type, property.RefKind),
getAccessor,
setAccessor,
propertyAccessibility,
DeclarationModifiers.From(property));
if (property.ExplicitInterfaceImplementations.Length > 0)
{
propDecl = this.WithExplicitInterfaceImplementations(propDecl,
ImmutableArray<ISymbol>.CastUp(property.ExplicitInterfaceImplementations));
}
return propDecl;
}
private protected abstract SyntaxNode PropertyDeclaration(
string name,
SyntaxNode type,
SyntaxNode? getAccessor,
SyntaxNode? setAccessor,
Accessibility accessibility,
DeclarationModifiers modifiers);
public SyntaxNode WithAccessorDeclarations(SyntaxNode declaration, params SyntaxNode[] accessorDeclarations)
=> WithAccessorDeclarations(declaration, (IEnumerable<SyntaxNode>)accessorDeclarations);
public abstract SyntaxNode WithAccessorDeclarations(SyntaxNode declaration, IEnumerable<SyntaxNode> accessorDeclarations);
public abstract SyntaxNode GetAccessorDeclaration(
Accessibility accessibility = Accessibility.NotApplicable,
IEnumerable<SyntaxNode>? statements = null);
public abstract SyntaxNode SetAccessorDeclaration(
Accessibility accessibility = Accessibility.NotApplicable,
IEnumerable<SyntaxNode>? statements = null);
/// <summary>
/// Creates an indexer declaration.
/// </summary>
public abstract SyntaxNode IndexerDeclaration(
IEnumerable<SyntaxNode> parameters,
SyntaxNode type,
Accessibility accessibility = Accessibility.NotApplicable,
DeclarationModifiers modifiers = default,
IEnumerable<SyntaxNode>? getAccessorStatements = null,
IEnumerable<SyntaxNode>? setAccessorStatements = null);
/// <summary>
/// Creates an indexer declaration matching an existing indexer symbol.
/// </summary>
public SyntaxNode IndexerDeclaration(
IPropertySymbol indexer,
IEnumerable<SyntaxNode>? getAccessorStatements = null,
IEnumerable<SyntaxNode>? setAccessorStatements = null)
{
var indexerDecl = IndexerDeclaration(
indexer.Parameters.Select(p => this.ParameterDeclaration(p)),
TypeExpression(indexer.Type, indexer.RefKind),
indexer.DeclaredAccessibility,
DeclarationModifiers.From(indexer),
getAccessorStatements,
setAccessorStatements);
if (indexer.ExplicitInterfaceImplementations.Length > 0)
{
indexerDecl = this.WithExplicitInterfaceImplementations(indexerDecl,
ImmutableArray<ISymbol>.CastUp(indexer.ExplicitInterfaceImplementations));
}
return indexerDecl;
}
/// <summary>
/// Creates a statement that adds the given handler to the given event.
/// </summary>
public abstract SyntaxNode AddEventHandler(SyntaxNode @event, SyntaxNode handler);
/// <summary>
/// Creates a statement that removes the given handler from the given event.
/// </summary>
public abstract SyntaxNode RemoveEventHandler(SyntaxNode @event, SyntaxNode handler);
/// <summary>
/// Creates an event declaration.
/// </summary>
public abstract SyntaxNode EventDeclaration(
string name,
SyntaxNode type,
Accessibility accessibility = Accessibility.NotApplicable,
DeclarationModifiers modifiers = default);
/// <summary>
/// Creates an event declaration from an existing event symbol
/// </summary>
public SyntaxNode EventDeclaration(IEventSymbol symbol)
{
var ev = EventDeclaration(
symbol.Name,
TypeExpression(symbol.Type),
symbol.DeclaredAccessibility,
DeclarationModifiers.From(symbol));
if (symbol.ExplicitInterfaceImplementations.Length > 0)
{
ev = this.WithExplicitInterfaceImplementations(ev,
ImmutableArray<ISymbol>.CastUp(symbol.ExplicitInterfaceImplementations));
}
return ev;
}
/// <summary>
/// Creates a custom event declaration.
/// </summary>
public abstract SyntaxNode CustomEventDeclaration(
string name,
SyntaxNode type,
Accessibility accessibility = Accessibility.NotApplicable,
DeclarationModifiers modifiers = default,
IEnumerable<SyntaxNode>? parameters = null,
IEnumerable<SyntaxNode>? addAccessorStatements = null,
IEnumerable<SyntaxNode>? removeAccessorStatements = null);
/// <summary>
/// Creates a custom event declaration from an existing event symbol.
/// </summary>
public SyntaxNode CustomEventDeclaration(
IEventSymbol symbol,
IEnumerable<SyntaxNode>? addAccessorStatements = null,
IEnumerable<SyntaxNode>? removeAccessorStatements = null)
{
var invoke = symbol.Type.GetMembers("Invoke").FirstOrDefault(m => m.Kind == SymbolKind.Method) as IMethodSymbol;
var parameters = invoke?.Parameters.Select(p => this.ParameterDeclaration(p));
return CustomEventDeclaration(
symbol.Name,
TypeExpression(symbol.Type),
symbol.DeclaredAccessibility,
DeclarationModifiers.From(symbol),
parameters: parameters,
addAccessorStatements: addAccessorStatements,
removeAccessorStatements: removeAccessorStatements);
}
/// <summary>
/// Creates a constructor declaration.
/// </summary>
public abstract SyntaxNode ConstructorDeclaration(
string? containingTypeName = null,
IEnumerable<SyntaxNode>? parameters = null,
Accessibility accessibility = Accessibility.NotApplicable,
DeclarationModifiers modifiers = default,
IEnumerable<SyntaxNode>? baseConstructorArguments = null,
IEnumerable<SyntaxNode>? statements = null);
/// <summary>
/// Create a constructor declaration using
/// </summary>
public SyntaxNode ConstructorDeclaration(
IMethodSymbol constructorMethod,
IEnumerable<SyntaxNode>? baseConstructorArguments = null,
IEnumerable<SyntaxNode>? statements = null)
{
return ConstructorDeclaration(
constructorMethod.ContainingType != null ? constructorMethod.ContainingType.Name : "New",
constructorMethod.Parameters.Select(p => ParameterDeclaration(p)),
constructorMethod.DeclaredAccessibility,
DeclarationModifiers.From(constructorMethod),
baseConstructorArguments,
statements);
}
private protected abstract SyntaxNode DestructorDeclaration(IMethodSymbol destructorMethod);
/// <summary>
/// Converts method, property and indexer declarations into public interface implementations.
/// This is equivalent to an implicit C# interface implementation (you can access it via the interface or directly via the named member.)
/// </summary>
public SyntaxNode? AsPublicInterfaceImplementation(SyntaxNode declaration, SyntaxNode interfaceType)
=> AsPublicInterfaceImplementation(declaration, interfaceType, interfaceMemberName: null);
/// <summary>
/// Converts method, property and indexer declarations into public interface implementations.
/// This is equivalent to an implicit C# interface implementation (you can access it via the interface or directly via the named member.)
/// </summary>
public abstract SyntaxNode? AsPublicInterfaceImplementation(SyntaxNode declaration, SyntaxNode interfaceType, string? interfaceMemberName);
/// <summary>
/// Converts method, property and indexer declarations into private interface implementations.
/// This is equivalent to a C# explicit interface implementation (you can declare it for access via the interface, but cannot call it directly).
/// </summary>
public SyntaxNode? AsPrivateInterfaceImplementation(SyntaxNode declaration, SyntaxNode interfaceType)
=> AsPrivateInterfaceImplementation(declaration, interfaceType, interfaceMemberName: null);
/// <summary>
/// Converts method, property and indexer declarations into private interface implementations.
/// This is equivalent to a C# explicit interface implementation (you can declare it for access via the interface, but cannot call it directly).
/// </summary>
public abstract SyntaxNode? AsPrivateInterfaceImplementation(SyntaxNode declaration, SyntaxNode interfaceType, string? interfaceMemberName);
/// <summary>
/// Creates a class declaration.
/// </summary>
public SyntaxNode ClassDeclaration(
string name,
IEnumerable<string>? typeParameters = null,
Accessibility accessibility = Accessibility.NotApplicable,
DeclarationModifiers modifiers = default,
SyntaxNode? baseType = null,
IEnumerable<SyntaxNode>? interfaceTypes = null,
IEnumerable<SyntaxNode>? members = null)
{
return ClassDeclaration(
isRecord: false, name, typeParameters?.Select(TypeParameter), accessibility, modifiers, baseType, interfaceTypes, members);
}
private protected abstract SyntaxNode ClassDeclaration(
bool isRecord,
string name,
IEnumerable<SyntaxNode>? typeParameters,
Accessibility accessibility,
DeclarationModifiers modifiers,
SyntaxNode? baseType,
IEnumerable<SyntaxNode>? interfaceTypes,
IEnumerable<SyntaxNode>? members);
/// <summary>
/// Creates a struct declaration.
/// </summary>
public SyntaxNode StructDeclaration(
string name,
IEnumerable<string>? typeParameters = null,
Accessibility accessibility = Accessibility.NotApplicable,
DeclarationModifiers modifiers = default,
IEnumerable<SyntaxNode>? interfaceTypes = null,
IEnumerable<SyntaxNode>? members = null)
{
return StructDeclaration(
isRecord: false, name, typeParameters?.Select(TypeParameter), accessibility, modifiers, interfaceTypes, members);
}
private protected abstract SyntaxNode StructDeclaration(
bool isRecord,
string name,
IEnumerable<SyntaxNode>? typeParameters,
Accessibility accessibility,
DeclarationModifiers modifiers,
IEnumerable<SyntaxNode>? interfaceTypes,
IEnumerable<SyntaxNode>? members);
/// <summary>
/// Creates a interface declaration.
/// </summary>
public SyntaxNode InterfaceDeclaration(
string name,
IEnumerable<string>? typeParameters = null,
Accessibility accessibility = Accessibility.NotApplicable,
IEnumerable<SyntaxNode>? interfaceTypes = null,
IEnumerable<SyntaxNode>? members = null)
{
return InterfaceDeclaration(
name, typeParameters?.Select(n => TypeParameter(n)), accessibility, interfaceTypes, members);
}
private protected abstract SyntaxNode InterfaceDeclaration(
string name,
IEnumerable<SyntaxNode>? typeParameters,
Accessibility accessibility,
IEnumerable<SyntaxNode>? interfaceTypes,
IEnumerable<SyntaxNode>? members);
/// <summary>
/// Creates an enum declaration.
/// </summary>
public abstract SyntaxNode EnumDeclaration(
string name,
Accessibility accessibility = Accessibility.NotApplicable,
DeclarationModifiers modifiers = default,
IEnumerable<SyntaxNode>? members = null);
/// <summary>
/// Creates an enum declaration
/// </summary>
internal abstract SyntaxNode EnumDeclaration(
string name,
SyntaxNode? underlyingType,
Accessibility accessibility = Accessibility.NotApplicable,
DeclarationModifiers modifiers = default,
IEnumerable<SyntaxNode>? members = null);
/// <summary>
/// Creates an enum member
/// </summary>
public abstract SyntaxNode EnumMember(string name, SyntaxNode? expression = null);
/// <summary>
/// Creates a delegate declaration.
/// </summary>
public SyntaxNode DelegateDeclaration(
string name,
IEnumerable<SyntaxNode>? parameters = null,
IEnumerable<string>? typeParameters = null,
SyntaxNode? returnType = null,
Accessibility accessibility = Accessibility.NotApplicable,
DeclarationModifiers modifiers = default)
{
return DelegateDeclaration(
name, parameters, typeParameters?.Select(n => TypeParameter(n)), returnType, accessibility, modifiers);
}
private protected abstract SyntaxNode DelegateDeclaration(
string name,
IEnumerable<SyntaxNode>? parameters,
IEnumerable<SyntaxNode>? typeParameters,
SyntaxNode? returnType,
Accessibility accessibility,
DeclarationModifiers modifiers);
/// <summary>
/// Creates a declaration matching an existing symbol.
/// </summary>
public SyntaxNode Declaration(ISymbol symbol)
{
switch (symbol.Kind)
{
case SymbolKind.Field:
return FieldDeclaration((IFieldSymbol)symbol);
case SymbolKind.Property:
var property = (IPropertySymbol)symbol;
if (property.IsIndexer)
{
return IndexerDeclaration(property);
}
else
{
return PropertyDeclaration(property);
}
case SymbolKind.Event:
var ev = (IEventSymbol)symbol;
return EventDeclaration(ev);
case SymbolKind.Method:
var method = (IMethodSymbol)symbol;
switch (method.MethodKind)
{
case MethodKind.Constructor:
case MethodKind.SharedConstructor:
return ConstructorDeclaration(method);
case MethodKind.Destructor:
return DestructorDeclaration(method);
case MethodKind.Ordinary or MethodKind.ExplicitInterfaceImplementation:
return MethodDeclaration(method);
case MethodKind.UserDefinedOperator or MethodKind.Conversion:
return OperatorDeclaration(method);
}
break;
case SymbolKind.Parameter:
return ParameterDeclaration((IParameterSymbol)symbol);
case SymbolKind.NamedType:
var type = (INamedTypeSymbol)symbol;
var declaration = type.TypeKind switch
{
TypeKind.Class => ClassDeclaration(
type.IsRecord,
type.Name,
type.TypeParameters.Select(TypeParameter),
accessibility: type.DeclaredAccessibility,
modifiers: DeclarationModifiers.From(type),
baseType: type.BaseType != null ? TypeExpression(type.BaseType) : null,
interfaceTypes: type.Interfaces.Select(TypeExpression),
members: type.GetMembers().Where(CanBeDeclared).Select(Declaration)),
TypeKind.Struct => StructDeclaration(
type.IsRecord,
type.Name,
type.TypeParameters.Select(TypeParameter),
accessibility: type.DeclaredAccessibility,
modifiers: DeclarationModifiers.From(type),
interfaceTypes: type.Interfaces.Select(TypeExpression),
members: type.GetMembers().Where(CanBeDeclared).Select(Declaration)),
TypeKind.Interface => InterfaceDeclaration(
type.Name,
type.TypeParameters.Select(TypeParameter),
accessibility: type.DeclaredAccessibility,
interfaceTypes: type.Interfaces.Select(TypeExpression),
members: type.GetMembers().Where(CanBeDeclared).Select(Declaration)),
TypeKind.Enum => EnumDeclaration(
type.Name,
underlyingType: type.EnumUnderlyingType is null or { SpecialType: SpecialType.System_Int32 }
? null
: TypeExpression(type.EnumUnderlyingType.SpecialType),
accessibility: type.DeclaredAccessibility,
members: type.GetMembers().Where(s => s.Kind == SymbolKind.Field).Select(Declaration)),
TypeKind.Delegate => type.GetMembers(WellKnownMemberNames.DelegateInvokeName) is [IMethodSymbol invoke, ..]
? DelegateDeclaration(
type.Name,
typeParameters: type.TypeParameters.Select(TypeParameter),
parameters: invoke.Parameters.Select(p => ParameterDeclaration(p)),
returnType: invoke.ReturnsVoid ? null : TypeExpression(invoke.ReturnType),
accessibility: type.DeclaredAccessibility,
modifiers: DeclarationModifiers.From(type))
: null,
_ => null,
};
if (declaration != null)
return WithTypeParametersAndConstraints(declaration, type.TypeParameters);
break;
}
throw new ArgumentException("Symbol cannot be converted to a declaration");
}
private static bool CanBeDeclared(ISymbol symbol)
{
// Skip implicitly declared members from a record. No need to synthesize those as the compiler will do it
// anyways.
if (symbol.ContainingType?.IsRecord is true)
{
if (symbol.IsImplicitlyDeclared)
return false;
}
switch (symbol.Kind)
{
case SymbolKind.Field:
case SymbolKind.Property:
case SymbolKind.Event:
case SymbolKind.Parameter:
return symbol.CanBeReferencedByName;
case SymbolKind.Method:
var method = (IMethodSymbol)symbol;
switch (method.MethodKind)
{
case MethodKind.Constructor:
case MethodKind.SharedConstructor:
return true;
case MethodKind.Ordinary:
return method.CanBeReferencedByName;
}
break;
case SymbolKind.NamedType:
var type = (INamedTypeSymbol)symbol;
switch (type.TypeKind)
{
case TypeKind.Class:
case TypeKind.Struct:
case TypeKind.Interface:
case TypeKind.Enum:
case TypeKind.Delegate:
return type.CanBeReferencedByName;
}
break;
}
return false;
}
private SyntaxNode WithTypeParametersAndConstraints(SyntaxNode declaration, ImmutableArray<ITypeParameterSymbol> typeParameters)
{
if (typeParameters.Length > 0)
{
declaration = WithTypeParameters(declaration, typeParameters.Select(tp => TypeParameter(tp)));
foreach (var tp in typeParameters)
{
if (HasSomeConstraint(tp))
{
declaration = this.WithTypeConstraint(declaration, tp.Name,
kinds: (tp.HasConstructorConstraint ? SpecialTypeConstraintKind.Constructor : SpecialTypeConstraintKind.None)
| (tp.HasReferenceTypeConstraint ? SpecialTypeConstraintKind.ReferenceType : SpecialTypeConstraintKind.None)
| (tp.HasValueTypeConstraint ? SpecialTypeConstraintKind.ValueType : SpecialTypeConstraintKind.None),
types: tp.ConstraintTypes.Select(TypeExpression));
}
}
}
return declaration;
}
private static bool HasSomeConstraint(ITypeParameterSymbol typeParameter)
=> typeParameter.HasConstructorConstraint || typeParameter.HasReferenceTypeConstraint || typeParameter.HasValueTypeConstraint || typeParameter.ConstraintTypes.Length > 0;
internal abstract SyntaxNode WithExplicitInterfaceImplementations(
SyntaxNode declaration, ImmutableArray<ISymbol> explicitInterfaceImplementations, bool removeDefaults = true);
/// <summary>
/// Converts a declaration (method, class, etc) into a declaration with type parameters.
/// </summary>
public SyntaxNode WithTypeParameters(SyntaxNode declaration, IEnumerable<string> typeParameters)
=> WithTypeParameters(declaration, typeParameters.Select(n => TypeParameter(n)));
private protected abstract SyntaxNode WithTypeParameters(SyntaxNode declaration, IEnumerable<SyntaxNode> typeParameters);
/// <summary>
/// Converts a declaration (method, class, etc) into a declaration with type parameters.
/// </summary>
public SyntaxNode WithTypeParameters(SyntaxNode declaration, params string[] typeParameters)
=> WithTypeParameters(declaration, (IEnumerable<string>)typeParameters);
/// <summary>
/// Adds a type constraint to a type parameter of a declaration.
/// </summary>
public abstract SyntaxNode WithTypeConstraint(SyntaxNode declaration, string typeParameterName, SpecialTypeConstraintKind kinds, IEnumerable<SyntaxNode>? types = null);
private protected abstract SyntaxNode WithDefaultConstraint(SyntaxNode declaration, string typeParameterName);
/// <summary>
/// Adds a type constraint to a type parameter of a declaration.
/// </summary>
public SyntaxNode WithTypeConstraint(SyntaxNode declaration, string typeParameterName, SpecialTypeConstraintKind kinds, params SyntaxNode[] types)
=> WithTypeConstraint(declaration, typeParameterName, kinds, (IEnumerable<SyntaxNode>)types);
/// <summary>
/// Adds a type constraint to a type parameter of a declaration.
/// </summary>
public SyntaxNode WithTypeConstraint(SyntaxNode declaration, string typeParameterName, params SyntaxNode[] types)
=> WithTypeConstraint(declaration, typeParameterName, SpecialTypeConstraintKind.None, (IEnumerable<SyntaxNode>)types);
/// <summary>
/// Creates a namespace declaration.
/// </summary>
/// <param name="name">The name of the namespace.</param>
/// <param name="declarations">Zero or more namespace or type declarations.</param>
public abstract SyntaxNode NamespaceDeclaration(SyntaxNode name, IEnumerable<SyntaxNode> declarations);
/// <summary>
/// Creates a namespace declaration.
/// </summary>
/// <param name="name">The name of the namespace.</param>
/// <param name="declarations">Zero or more namespace or type declarations.</param>
public SyntaxNode NamespaceDeclaration(SyntaxNode name, params SyntaxNode[] declarations)
=> NamespaceDeclaration(name, (IEnumerable<SyntaxNode>)declarations);
/// <summary>
/// Creates a namespace declaration.
/// </summary>
/// <param name="name">The name of the namespace.</param>
/// <param name="declarations">Zero or more namespace or type declarations.</param>
public SyntaxNode NamespaceDeclaration(string name, IEnumerable<SyntaxNode> declarations)
=> NamespaceDeclaration(DottedName(name), declarations);
/// <summary>
/// Creates a namespace declaration.
/// </summary>
/// <param name="name">The name of the namespace.</param>
/// <param name="declarations">Zero or more namespace or type declarations.</param>
public SyntaxNode NamespaceDeclaration(string name, params SyntaxNode[] declarations)
=> NamespaceDeclaration(DottedName(name), (IEnumerable<SyntaxNode>)declarations);
/// <summary>
/// Creates a compilation unit declaration
/// </summary>
/// <param name="declarations">Zero or more namespace import, namespace or type declarations.</param>
public abstract SyntaxNode CompilationUnit(IEnumerable<SyntaxNode> declarations);
/// <summary>
/// Creates a compilation unit declaration
/// </summary>
/// <param name="declarations">Zero or more namespace import, namespace or type declarations.</param>
public SyntaxNode CompilationUnit(params SyntaxNode[] declarations)
=> CompilationUnit((IEnumerable<SyntaxNode>)declarations);
/// <summary>
/// Creates a namespace import declaration.
/// </summary>
/// <param name="name">The name of the namespace being imported.</param>
public abstract SyntaxNode NamespaceImportDeclaration(SyntaxNode name);
/// <summary>
/// Creates a namespace import declaration.
/// </summary>
/// <param name="name">The name of the namespace being imported.</param>
public SyntaxNode NamespaceImportDeclaration(string name)
=> NamespaceImportDeclaration(DottedName(name));
/// <summary>
/// Creates an alias import declaration.
/// </summary>
/// <param name="aliasIdentifierName">The name of the alias.</param>
/// <param name="symbol">The namespace or type to be aliased.</param>
public SyntaxNode AliasImportDeclaration(string aliasIdentifierName, INamespaceOrTypeSymbol symbol)
=> AliasImportDeclaration(aliasIdentifierName, NameExpression(symbol));
/// <summary>
/// Creates an alias import declaration.
/// </summary>