-
Notifications
You must be signed in to change notification settings - Fork 2
/
CompiledProgramRunner.cs
285 lines (238 loc) · 11.3 KB
/
CompiledProgramRunner.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
using BaZic.Core.ComponentModel;
using BaZic.Core.ComponentModel.Assemblies;
using BaZic.Core.Enums;
using BaZic.Runtime.BaZic.Code;
using BaZic.Runtime.BaZic.Code.AbstractSyntaxTree;
using BaZic.Runtime.Localization;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.Emit;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace BaZic.Runtime.BaZic.Runtime
{
/// <summary>
/// Provide a sets of method to compile and run a BaZic program.
/// </summary>
internal sealed class CompiledProgramRunner : MarshalByRefObject
{
#region Fields
private readonly BaZicInterpreterCore _baZicInterpreter;
private readonly BaZicProgram _program;
private readonly AssemblySandbox _assemblySandbox;
private object _compiledProgramInstance;
#endregion
#region Properties
/// <summary>
/// Gets the result of the Main method or the result of the Window.Closed event from the user interface.
/// </summary>
internal object ProgramResult { get; private set; }
#endregion
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="CompiledProgramRunner"/> class.
/// </summary>
/// <param name="baZicInterpreter">The <see cref="BaZicInterpreterCore"/> that called this class.</param>
/// <param name="program">The <see cref="BaZicProgram"/> to compile and run.</param>
/// <param name="assemblySandbox">The sandbox that contains the required assemblies.</param>
internal CompiledProgramRunner(BaZicInterpreterCore baZicInterpreter, BaZicProgram program, AssemblySandbox assemblySandbox)
{
Requires.NotNull(baZicInterpreter, nameof(baZicInterpreter));
Requires.NotNull(program, nameof(program));
Requires.NotNull(assemblySandbox, nameof(assemblySandbox));
_baZicInterpreter = baZicInterpreter;
_program = program;
_assemblySandbox = assemblySandbox;
}
#endregion
#region Methods
/// <summary>
/// Convert the BaZic program to CSharp code and build it in memory.
/// </summary>
/// <param name="outputType">The type of assembly to generate</param>
/// <param name="assemblyName">Defines the name of the assembly to generate.</param>
/// <param name="assemblyVersion">Defines the version of the assembly.</param>
/// <param name="assemblyCopyright">Defines the copyright of the assembly.</param>
/// <param name="releaseMode">Defines whether the compiler must build in release mode or debug mode.</param>
/// <returns>Returns the result of the build.</returns>
internal CompilerResult Build(BaZicCompilerOutputType outputType, string assemblyName, string assemblyVersion, string assemblyCopyright, bool releaseMode)
{
if (_baZicInterpreter.Verbose)
{
_baZicInterpreter.ChangeState(this, new BaZicInterpreterStateChangeEventArgs(L.BaZic.Runtime.CompiledProgramRunner.GenerationCSharp));
}
if (string.IsNullOrWhiteSpace(assemblyName))
{
assemblyName = _program.Id.ToString();
}
var codeGen = new CSharpCodeGenerator();
var csharpCode = codeGen.Generate(_program, assemblyName, assemblyVersion, assemblyCopyright);
var syntaxTree = CSharpSyntaxTree.ParseText(csharpCode);
if (_baZicInterpreter.Verbose)
{
_baZicInterpreter.ChangeState(this, new BaZicInterpreterStateChangeEventArgs(L.BaZic.Runtime.CompiledProgramRunner.Compiling));
}
var outputKind = OutputKind.ConsoleApplication;
if (outputType == BaZicCompilerOutputType.WindowsApp)
{
outputKind = OutputKind.WindowsApplication;
}
else if (outputType == BaZicCompilerOutputType.DynamicallyLinkedLibrary)
{
outputKind = OutputKind.DynamicallyLinkedLibrary;
}
var references = GetAssemblyReferences();
var options = new CSharpCompilationOptions(outputKind)
.WithAllowUnsafe(true)
.WithOptimizationLevel(releaseMode? OptimizationLevel.Release : OptimizationLevel.Debug)
.WithPlatform(Platform.AnyCpu);
var cSharpCompilation = CSharpCompilation.Create(assemblyName, new[] { syntaxTree }, references, options);
var assemblyStream = new MemoryStream();
var pdbStream = new MemoryStream();
var resources = new List<ResourceDescription>();
if (_program is BaZicUiProgram uiProgram)
{
foreach (var resourceFile in uiProgram.ResourceFilePaths)
{
if (!File.Exists(resourceFile))
{
return new CompilerResult
{
BuildErrors = new AggregateException(new FileNotFoundException("The resource file does not exist", resourceFile))
};
}
resources.Add(new ResourceDescription(Path.GetFileName(resourceFile), () => File.OpenRead(resourceFile), true));
}
}
var result = cSharpCompilation.Emit(peStream: assemblyStream, pdbStream: pdbStream, manifestResources: resources);
var errors = GetCompilationErrors(result);
if (errors != null)
{
return new CompilerResult
{
BuildErrors = errors
};
}
assemblyStream.Seek(0, SeekOrigin.Begin);
pdbStream.Seek(0, SeekOrigin.Begin);
if (_baZicInterpreter.Verbose)
{
_baZicInterpreter.ChangeState(this, new BaZicInterpreterStateChangeEventArgs(L.BaZic.Runtime.CompiledProgramRunner.BuiltSucceed));
}
return new CompilerResult
{
Assembly = assemblyStream,
Pdb = pdbStream
};
}
/// <summary>
/// Runs the compiled program.
/// </summary>
/// <param name="arguments">The arguments to pass to the program.</param>
internal void Run(params object[] arguments)
{
_baZicInterpreter.CheckState(BaZicInterpreterState.Preparing);
_baZicInterpreter.ChangeState(this, new BaZicInterpreterStateChangeEventArgs(BaZicInterpreterState.Running));
if (_baZicInterpreter.Verbose)
{
_baZicInterpreter.ChangeState(this, new BaZicInterpreterStateChangeEventArgs(L.BaZic.Runtime.CompiledProgramRunner.RunningProgram));
}
var argumentValues = new object[] { arguments };
if (_program is BaZicUiProgram)
{
ThreadHelper.RunOnStaThread(() =>
{
InitializeProgram();
var programHelper = _assemblySandbox.Reflection.GetProperty(_compiledProgramInstance, Consts.CompiledProgramHelperInstance);
_assemblySandbox.Reflection.SubscribeEvent(programHelper, Consts.CompiledProgramIdleStateOccuredEvent, () =>
{
_baZicInterpreter.ChangeState(this, new BaZicInterpreterStateChangeEventArgs(BaZicInterpreterState.Idle)); // Go to Idle mode.
});
ProgramResult = InvokeMethod(Consts.EntryPointMethodName, argumentValues);
});
}
else
{
InitializeProgram();
ProgramResult = InvokeMethod(Consts.EntryPointMethodName, argumentValues);
}
if (_baZicInterpreter.Verbose)
{
_baZicInterpreter.ChangeState(this, new BaZicInterpreterStateChangeEventArgs(L.BaZic.Runtime.CompiledProgramRunner.ExecutionEnded));
}
}
/// <summary>
/// Invokes a public method in the program.
/// </summary>
/// <param name="methodName">The name of the method.</param>
/// <param name="arguments">The arguments to pass to the program.</param>
/// <returns>Returns the result of the method.</returns>
internal object InvokeMethod(string methodName, params object[] arguments)
{
InitializeProgram();
return _assemblySandbox.Reflection.InvokeMethod(_compiledProgramInstance, methodName, arguments);
}
/// <summary>
/// Request to close the user interface of the running program.
/// </summary>
internal void CloseUserInterface()
{
InitializeProgram();
var programHelper = _assemblySandbox.Reflection.GetProperty(_compiledProgramInstance, Consts.CompiledProgramHelperInstance);
_assemblySandbox.Reflection.InvokeMethod(programHelper, Consts.CompiledCloseUserInterface);
}
/// <summary>
/// Creates an instance of the compiled program class, if it is not already instanciated.
/// </summary>
private void InitializeProgram()
{
if (_compiledProgramInstance == null)
{
_compiledProgramInstance = _assemblySandbox.Reflection.Instantiate(_assemblySandbox.GetTypeRef(Consts.CompiledProgramClassName));
}
}
/// <summary>
/// Gets a reference to the required assemblies.
/// </summary>
/// <returns>A list of reference to the assemblies.</returns>
private IReadOnlyList<MetadataReference> GetAssemblyReferences()
{
var references = new List<MetadataReference>();
references.Add(MetadataReference.CreateFromFile(typeof(object).Assembly.Location));
foreach (var assembly in _assemblySandbox.GetAssemblies().Where(a => a.IsDotNetAssembly))
{
references.Add(MetadataReference.CreateFromFile(assembly.Location));
}
return references.AsReadOnly();
}
/// <summary>
/// Throw exceptions if the compilation failed.
/// </summary>
/// <param name="result">The result of the compilation.</param>
/// <returns>Returns an <see cref="AggregateException"/> or null if the build succeeded.</returns>
private AggregateException GetCompilationErrors(EmitResult result)
{
if (result.Success)
{
return null;
}
var compilationErrors = result.Diagnostics.Where(diagnostic => diagnostic.IsWarningAsError || diagnostic.Severity == DiagnosticSeverity.Error).ToList();
if (!compilationErrors.Any())
{
return null;
}
var errorList = new List<Exception>();
foreach (var error in compilationErrors)
{
var errorNumber = error.Id;
var errorDescription = error.GetMessage();
var ErrorMessage = $"{errorNumber}: {errorDescription};";
errorList.Add(new Exception(L.BaZic.Runtime.CompiledProgramRunner.FormattedBuildFaild(errorNumber, errorDescription)));
}
return new AggregateException(errorList);
}
#endregion
}
}