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
|
using Microsoft.CodeAnalysis.CSharp.Scripting;
using Microsoft.CodeAnalysis.Scripting;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using Tango.Core;
using Tango.Core.IO;
using Tango.Scripting.Core;
using System.IO;
using Tango.Core.Helpers;
namespace Tango.Scripting.Basic
{
public class Project<T> : ExtendedObject where T : IContext
{
public String ID { get; set; }
private String _name;
public String Name
{
get { return _name; }
set { _name = value; RaisePropertyChangedAuto(); }
}
private String _description;
public String Description
{
get { return _description; }
set { _description = value; RaisePropertyChangedAuto(); }
}
public ApartmentState ApartmentState { get; set; }
public ObservableCollection<ReferenceAssembly> ReferenceAssemblies { get; set; }
public ObservableCollection<Script> Scripts { get; set; }
[JsonIgnore]
public ObservableCollection<IScriptSource> AdditionalScripts
{
get
{
return Scripts.Where(x => !x.IsEntryPoint).Cast<IScriptSource>().ToObservableCollection();
}
}
public List<ScriptBreakPoint> BreakPoints { get; set; }
public Project()
{
ID = Guid.NewGuid().ToString();
ApartmentState = ApartmentState.MTA;
ReferenceAssemblies = new ObservableCollection<ReferenceAssembly>();
Scripts = new ObservableCollection<Script>();
Scripts.CollectionChanged += (x, e) => { RaisePropertyChanged(nameof(AdditionalScripts)); };
BreakPoints = new List<ScriptBreakPoint>();
}
public Task<CompilationResult> Compile()
{
return Task.Factory.StartNew<CompilationResult>(() =>
{
var result = new CompilationResult();
var tempFolder = TemporaryManager.CreateFolder(Name + "_" + ID);
result.TemporaryProjectPath = tempFolder;
String mainScriptCode = String.Empty;
foreach (var script in Scripts)
{
script.LoadCount = 0;
script.LoadCharCount = 0;
String code = script.Code;
String codeFile = Path.Combine(tempFolder, script.Name);
String loadingString = String.Empty;
foreach (var file in Scripts.Where(x => !x.IsEntryPoint && script != x).Select(x => Path.Combine(tempFolder, x.Name)))
{
loadingString += $"#load \"{file}\"\n";
script.LoadCount++;
}
script.LoadCharCount += loadingString.Length;
code = loadingString + code;
int debugLinesLength = 0;
foreach (var breakPoint in BreakPoints.Where(x => x.Script == script).OrderBy(x => x.LineNumber))
{
var debugLine = $"context.BreakPoint(\"{script.Name}\",{breakPoint.LineNumber}";
foreach (var symbol in breakPoint.ContextSymbols)
{
debugLine += $",\"{symbol.Name}\",{symbol.Offset},{symbol.Length},{symbol.Name}";
}
debugLine += ");";
StringBuilder builder = new StringBuilder(code);
builder.Insert(breakPoint.LineStartOffset + loadingString.Length + debugLinesLength, debugLine);
code = builder.ToString();
debugLinesLength += debugLine.Length;
}
if (!script.IsEntryPoint)
{
File.WriteAllText(codeFile, code);
}
else
{
code += Environment.NewLine + Environment.NewLine + "new Program().OnExecute(GlobalContext);";
mainScriptCode = code;
}
}
var scriptOptions = ScriptOptions.Default.WithReferences(LoadReferenceAssemblies()).WithEmitDebugInformation(true);
var s = CSharpScript.Create<object>(mainScriptCode, scriptOptions, typeof(GlobalObject<T>));
result.Script = s;
var compileResults = s.Compile();
GC.Collect();
foreach (var error in compileResults.Where(x => x.Severity == Microsoft.CodeAnalysis.DiagnosticSeverity.Error))
{
CompilationError cError = new CompilationError();
cError.File = System.IO.Path.GetFileName(error.Location.SourceTree.FilePath);
if (cError.File == String.Empty)
{
cError.File = Scripts.Single(x => x.IsEntryPoint).Name;
}
Script errorScript = Scripts.Single(x => x.Name == cError.File);
cError.Message = error.GetMessage();
cError.Severity = error.Severity;
cError.Position = error.Location.SourceSpan.Start - (errorScript != null ? errorScript.LoadCharCount : 0);
var line = error.Location.GetMappedLineSpan();
cError.Line = line.StartLinePosition.Line + 1 - (errorScript != null ? errorScript.LoadCount : 0);
cError.Column = line.StartLinePosition.Character + 1;
cError.Length = line.EndLinePosition.Character - line.StartLinePosition.Character;
result.Errors.Add(cError);
}
return result;
});
}
public async Task<ProjectSession<T>> Run(T context)
{
var result = await Compile();
if (result.Errors.Count > 0)
{
throw new InvalidOperationException($"Cannot run project with the following compilation errors:\n{String.Join(Environment.NewLine, result.Errors.Select(x => x.Message))}");
}
Thread scriptThread = null;
ProjectSession<T> session = null;
session = new ProjectSession<T>(this, () =>
{
scriptThread.Abort();
});
scriptThread = new Thread(() =>
{
try
{
var runResult = result.Script.RunAsync(globals: new GlobalObject<T>() { GlobalContext = context }).Result;
session.Completed(runResult.ReturnValue);
}
catch (ThreadAbortException)
{
}
catch (Exception ex)
{
session.Failed(ex.InnerException);
}
finally
{
BreakPoints.Clear();
GC.Collect();
}
});
scriptThread.SetApartmentState(ApartmentState);
scriptThread.IsBackground = true;
scriptThread.Start();
return session;
}
public List<Assembly> LoadReferenceAssemblies()
{
List<Assembly> loadedAssemblies = new List<Assembly>();
foreach (var asm in ReferenceAssemblies)
{
loadedAssemblies.Add(asm.Load());
}
return loadedAssemblies;
}
}
}
|