forked from scriptcs/scriptcs
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRoslynScriptEngine.cs
More file actions
214 lines (173 loc) · 8.14 KB
/
RoslynScriptEngine.cs
File metadata and controls
214 lines (173 loc) · 8.14 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
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
using System;
using System.Collections.Generic;
using System.Linq;
using Common.Logging;
using Roslyn.Compilers;
using Roslyn.Compilers.CSharp;
using Roslyn.Scripting;
using Roslyn.Scripting.CSharp;
using ScriptCs.Contracts;
using System.Text.RegularExpressions;
namespace ScriptCs.Engine.Roslyn
{
public class RoslynScriptEngine : IScriptEngine
{
protected readonly ScriptEngine ScriptEngine;
private readonly IScriptHostFactory _scriptHostFactory;
public const string SessionKey = "Session";
private const string InvalidNamespaceError = "error CS0246";
public RoslynScriptEngine(IScriptHostFactory scriptHostFactory, ILog logger)
{
ScriptEngine = new ScriptEngine();
ScriptEngine.AddReference(typeof(ScriptExecutor).Assembly);
_scriptHostFactory = scriptHostFactory;
Logger = logger;
}
protected ILog Logger { get; private set; }
public string BaseDirectory
{
get { return ScriptEngine.BaseDirectory; }
set { ScriptEngine.BaseDirectory = value; }
}
public string CacheDirectory { get; set; }
public string FileName { get; set; }
public ScriptResult Execute(string code, string[] scriptArgs, AssemblyReferences references, IEnumerable<string> namespaces, ScriptPackSession scriptPackSession)
{
Guard.AgainstNullArgument("scriptPackSession", scriptPackSession);
Guard.AgainstNullArgument("references", references);
Logger.Debug("Starting to create execution components");
Logger.Debug("Creating script host");
var executionReferences = new AssemblyReferences(references.PathReferences, references.Assemblies);
executionReferences.PathReferences.UnionWith(scriptPackSession.References);
SessionState<Session> sessionState;
var isFirstExecution = !scriptPackSession.State.ContainsKey(SessionKey);
if (isFirstExecution)
{
code = code.DefineTrace();
var host = _scriptHostFactory.CreateScriptHost(new ScriptPackManager(scriptPackSession.Contexts), scriptArgs);
Logger.Debug("Creating session");
var hostType = host.GetType();
ScriptEngine.AddReference(hostType.Assembly);
var session = ScriptEngine.CreateSession(host, hostType);
var allNamespaces = namespaces.Union(scriptPackSession.Namespaces).Distinct();
foreach (var reference in executionReferences.PathReferences)
{
Logger.DebugFormat("Adding reference to {0}", reference);
session.AddReference(reference);
}
foreach (var assembly in executionReferences.Assemblies)
{
Logger.DebugFormat("Adding reference to {0}", assembly.FullName);
session.AddReference(assembly);
}
foreach (var @namespace in allNamespaces)
{
Logger.DebugFormat("Importing namespace {0}", @namespace);
session.ImportNamespace(@namespace);
}
sessionState = new SessionState<Session> { References = executionReferences, Session = session, Namespaces = new HashSet<string>(allNamespaces) };
scriptPackSession.State[SessionKey] = sessionState;
}
else
{
Logger.Debug("Reusing existing session");
sessionState = (SessionState<Session>)scriptPackSession.State[SessionKey];
if (sessionState.References == null)
{
sessionState.References = new AssemblyReferences();
}
if (sessionState.Namespaces == null)
{
sessionState.Namespaces = new HashSet<string>();
}
var newReferences = executionReferences.Except(sessionState.References);
foreach (var reference in newReferences.PathReferences)
{
Logger.DebugFormat("Adding reference to {0}", reference);
sessionState.Session.AddReference(reference);
sessionState.References.PathReferences.Add(reference);
}
foreach (var assembly in newReferences.Assemblies)
{
Logger.DebugFormat("Adding reference to {0}", assembly.FullName);
sessionState.Session.AddReference(assembly);
sessionState.References.Assemblies.Add(assembly);
}
var newNamespaces = namespaces.Except(sessionState.Namespaces);
foreach (var @namespace in newNamespaces)
{
Logger.DebugFormat("Importing namespace {0}", @namespace);
sessionState.Session.ImportNamespace(@namespace);
sessionState.Namespaces.Add(@namespace);
}
}
Logger.Debug("Starting execution");
var result = Execute(code, sessionState.Session);
if (result.InvalidNamespaces.Any())
{
var pendingNamespacesField = sessionState.Session.GetType().GetField("pendingNamespaces", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
if (pendingNamespacesField != null)
{
var pendingNamespacesValue = (ReadOnlyArray<string>)pendingNamespacesField.GetValue(sessionState.Session);
//no need to check this for null as ReadOnlyArray is a value type
if (pendingNamespacesValue.Any())
{
var fixedNamespaces = pendingNamespacesValue.ToList();
foreach (var @namespace in result.InvalidNamespaces)
{
sessionState.Namespaces.Remove(@namespace);
fixedNamespaces.Remove(@namespace);
}
pendingNamespacesField.SetValue(sessionState.Session, ReadOnlyArray<string>.CreateFrom<string>(fixedNamespaces));
}
}
}
Logger.Debug("Finished execution");
return result;
}
protected virtual ScriptResult Execute(string code, Session session)
{
Guard.AgainstNullArgument("session", session);
if (string.IsNullOrWhiteSpace(FileName) && !IsCompleteSubmission(code))
{
return ScriptResult.Incomplete;
}
try
{
var submission = session.CompileSubmission<object>(code);
try
{
return new ScriptResult(returnValue: submission.Execute());
}
catch (AggregateException ex)
{
return new ScriptResult(executionException: ex.InnerException);
}
catch (Exception ex)
{
return new ScriptResult(executionException: ex);
}
}
catch (Exception ex)
{
if (ex.Message.StartsWith(InvalidNamespaceError))
{
var offendingNamespace = Regex.Match(ex.Message, @"\'([^']*)\'").Groups[1].Value;
return new ScriptResult(compilationException: ex, invalidNamespaces: new string[1] {offendingNamespace});
}
return new ScriptResult(compilationException: ex);
}
}
private static bool IsCompleteSubmission(string code)
{
var options = new ParseOptions(
CompatibilityMode.None,
LanguageVersion.CSharp4,
true,
SourceCodeKind.Interactive,
default(ReadOnlyArray<string>));
var syntaxTree = SyntaxTree.ParseText(code, options: options);
return Syntax.IsCompleteSubmission(syntaxTree);
}
}
}