-
Notifications
You must be signed in to change notification settings - Fork 1
/
CompileService.cs
217 lines (168 loc) · 6.98 KB
/
CompileService.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
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.Emit;
using Newtonsoft.Json.Linq;
using System.Runtime.InteropServices.JavaScript;
namespace WasmRoslyn
{
public class CompileService
{
private readonly HttpClient _http;
public List<string> CompileLog { get; set; }
private List<MetadataReference> references { get; set; }
//public JSObject js;
public CompileService(HttpClient http/*, JSObject js*/)
{
_http = http;
//this.js = js;
}
public async Task SetReferences(List<string> assemblies)
{
//need to use the DLL atleast once so it gets added
JObject job = new JObject();
//Console.WriteLine("Setting References");
references = new List<MetadataReference>();
foreach(var assembly in assemblies)
{
if (assembly.ToLower().StartsWith("http"))
references.Add(await GetFileStreamExternal(assembly));
else
references.Add(await GetFileStream($"managed/{assembly}.dll"));
}
//Console.WriteLine("Finished Setting References");
}
public async Task Init()
{
List<string> assemblies = new List<string>();
// assemblies.Add("mscorlib");
// assemblies.Add("netstandard");
// assemblies.Add("System");
// assemblies.Add("System.Data");
if (references == null)
{
references = new List<MetadataReference>();
List<string> assemblyNames = new List<string>();
foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies())
{
references.Add(await GetFileStream($"managed/{assembly.GetName().Name}.dll"));
assemblyNames.Add(assembly.GetName().Name);
}
references.Add(await GetFileStream($"managed/System.Data.dll"));
assemblyNames.Add("System.Data");
references.Add(await GetFileStream($"managed/Newtonsoft.Json.dll"));
assemblyNames.Add("Newtonsoft.Json");
//js.Invoke("displayAssemblies", new object[] { assemblyNames.ToArray() });
}
}
public async Task<Type> CompileSourceCode(string code)
{
//Console.WriteLine("Compile assembly");
var assembly = await Compile(code);
if (assembly != null)
{
CompileLog.Add("Searching for first exported type.");
return assembly.GetExportedTypes().FirstOrDefault();
}
return null;
}
public async Task<Assembly> Compile(string code)
{
await Init();
SyntaxTree syntaxTree = CSharpSyntaxTree.ParseText(code, new CSharpParseOptions(LanguageVersion.Latest));
foreach (var diagnostic in syntaxTree.GetDiagnostics())
{
CompileLog.Add(diagnostic.ToString());
}
if (syntaxTree.GetDiagnostics().Any(i => i.Severity == DiagnosticSeverity.Error))
{
CompileLog.Add("Parse SyntaxTree Error!");
return null;
}
CompileLog.Add("Parse SyntaxTree Success");
//https://stackoverflow.com/questions/35711461/how-to-get-roslyn-to-compile-when-referenced-assemblies-have-references-to-both
var op = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary);
op = op.WithAssemblyIdentityComparer(DesktopAssemblyIdentityComparer.Default);
CSharpCompilation compilation = CSharpCompilation.Create("WasmRoslynDynamic", new[] { syntaxTree },
references, op);
using (MemoryStream stream = new MemoryStream())
{
EmitResult result = compilation.Emit(stream);
foreach (var diagnostic in result.Diagnostics)
{
CompileLog.Add(diagnostic.ToString());
}
if (!result.Success)
{
CompileLog.Add("Compilation error");
return null;
}
CompileLog.Add("Compilation success!");
Assembly assemby = AppDomain.CurrentDomain.Load(stream.ToArray());
return assemby;
}
}
public async Task<string> CompileAndRun(string code)
{
await Init();
var assemby = await this.Compile(code);
if (assemby != null)
{
var type = assemby.GetExportedTypes().FirstOrDefault();
//Console.WriteLine("Type: " + type.ToString());
var methodInfo = type.GetMethod("Main");
//var instance = Activator.CreateInstance(type);
//return await (Task<string>)methodInfo.Invoke(instance, null);
methodInfo.Invoke(null, null);
}
return null;
}
private async Task<MetadataReference> GetFileStream(string name)
{
//Console.WriteLine($"Fetching: {name}");
MetadataReference mr = null;
using (var stream = await _http.GetStreamAsync(name).ConfigureAwait(false))
using (var outputStream = new MemoryStream())
{
await stream.CopyToAsync(outputStream).ConfigureAwait(false);
// Make sure to set the position to 0
outputStream.Position = 0;
mr = MetadataReference.CreateFromStream(outputStream);
}
return mr;
}
private HttpClient http_external;
private async Task<MetadataReference> GetFileStreamExternal(string url)
{
try
{
//Console.WriteLine($"Fetching External: {url}");
if (http_external==null)
{
http_external = new HttpClient();
}
MetadataReference mr = null;
using (var stream = await http_external.GetStreamAsync(url).ConfigureAwait(false))
using (var outputStream = new MemoryStream())
{
await stream.CopyToAsync(outputStream).ConfigureAwait(false);
// Make sure to set the position to 0
outputStream.Position = 0;
mr = MetadataReference.CreateFromStream(outputStream);
}
return mr;
}catch(Exception ex)
{
Console.Error.WriteLine(ex.Message + ex.StackTrace);
return null;
}
}
}
}