-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathProgram.cs
More file actions
34 lines (27 loc) · 1.27 KB
/
Program.cs
File metadata and controls
34 lines (27 loc) · 1.27 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
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
namespace SyntaxRewriter;
class Program
{
static async Task Main()
{
string code = File.ReadAllText("Sample.cs");
await ProcessAsync(code);
}
static async Task ProcessAsync(string code)
{
SyntaxTree tree = CSharpSyntaxTree.ParseText(code);
var compilation = CSharpCompilation.Create("Sample")
.AddReferences(MetadataReference.CreateFromFile(typeof(object).Assembly.Location))
.AddSyntaxTrees(tree);
SemanticModel semanticModel = compilation.GetSemanticModel(tree);
AutoPropertyRewriter propertyRewriter = new(semanticModel);
SyntaxNode root = await tree.GetRootAsync().ConfigureAwait(false);
SyntaxNode rootWithAutoProperties = propertyRewriter.Visit(root);
compilation = compilation.RemoveAllSyntaxTrees().AddSyntaxTrees(rootWithAutoProperties.SyntaxTree);
semanticModel = compilation.GetSemanticModel(rootWithAutoProperties.SyntaxTree);
RemoveBackingFieldRewriter fieldRewriter = new(semanticModel, propertyRewriter.FieldsToRemove.ToArray());
SyntaxNode rootWithFieldsRemoved = fieldRewriter.Visit(rootWithAutoProperties);
Console.WriteLine(rootWithFieldsRemoved);
}
}