forked from scriptcs/scriptcs
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMonoScriptEngine.cs
More file actions
175 lines (143 loc) · 6.31 KB
/
MonoScriptEngine.cs
File metadata and controls
175 lines (143 loc) · 6.31 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
extern alias MonoCSharp;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Mono.Collections.Generic;
using MonoCSharp::Mono.CSharp;
using ScriptCs.Contracts;
using ScriptCs.Engine.Mono.Segmenter;
namespace ScriptCs.Engine.Mono
{
public class MonoScriptEngine : IReplEngine
{
public const string SessionKey = "MonoSession";
private readonly IScriptHostFactory _scriptHostFactory;
private readonly ILog _log;
public string BaseDirectory { get; set; }
public string CacheDirectory { get; set; }
public string FileName { get; set; }
[Obsolete("Support for Common.Logging types was deprecated in version 0.15.0 and will soon be removed.")]
public MonoScriptEngine(IScriptHostFactory scriptHostFactory, Common.Logging.ILog logger)
: this(scriptHostFactory, new CommonLoggingLogProvider(logger))
{
}
public MonoScriptEngine(IScriptHostFactory scriptHostFactory, ILogProvider logProvider)
{
Guard.AgainstNullArgument("logProvider", logProvider);
_scriptHostFactory = scriptHostFactory;
_log = logProvider.ForCurrentType();
#pragma warning disable 618
Logger = new ScriptCsLogger(_log);
#pragma warning restore 618
}
[Obsolete("Support for Common.Logging types was deprecated in version 0.15.0 and will soon be removed.")]
public Common.Logging.ILog Logger { get; set; }
public ICollection<string> GetLocalVariables(ScriptPackSession scriptPackSession)
{
if (scriptPackSession != null && scriptPackSession.State.ContainsKey(SessionKey))
{
var sessionState = (SessionState<Evaluator>)scriptPackSession.State[SessionKey];
var vars = sessionState.Session.GetVars();
if (!string.IsNullOrWhiteSpace(vars) && vars.Contains(Environment.NewLine))
{
return vars.Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
}
}
return new Collection<string>();
}
public ScriptResult Execute(
string code,
string[] scriptArgs,
AssemblyReferences references,
IEnumerable<string> namespaces,
ScriptPackSession scriptPackSession)
{
Guard.AgainstNullArgument("references", references);
Guard.AgainstNullArgument("scriptPackSession", scriptPackSession);
references = references.Union(scriptPackSession.References);
SessionState<Evaluator> sessionState;
var isFirstExecution = !scriptPackSession.State.ContainsKey(SessionKey);
if (isFirstExecution)
{
code = code.DefineTrace();
_log.Debug("Creating session");
var context = new CompilerContext(
new CompilerSettings { AssemblyReferences = references.Paths.ToList() },
new ConsoleReportPrinter());
var evaluator = new Evaluator(context);
var allNamespaces = namespaces.Union(scriptPackSession.Namespaces).Distinct();
var host = _scriptHostFactory.CreateScriptHost(
new ScriptPackManager(scriptPackSession.Contexts), scriptArgs);
MonoHost.SetHost((ScriptHost)host);
ScriptLibraryWrapper.SetHost(host);
evaluator.ReferenceAssembly(typeof(MonoHost).Assembly);
evaluator.InteractiveBaseClass = typeof(MonoHost);
sessionState = new SessionState<Evaluator>
{
References = references,
Namespaces = new HashSet<string>(),
Session = evaluator,
};
ImportNamespaces(allNamespaces, sessionState);
scriptPackSession.State[SessionKey] = sessionState;
}
else
{
_log.Debug("Reusing existing session");
sessionState = (SessionState<Evaluator>)scriptPackSession.State[SessionKey];
var newReferences = sessionState.References == null
? references
: references.Except(sessionState.References);
foreach (var reference in newReferences.Paths)
{
_log.DebugFormat("Adding reference to {0}", reference);
sessionState.Session.LoadAssembly(reference);
}
sessionState.References = references;
var newNamespaces = sessionState.Namespaces == null
? namespaces
: namespaces.Except(sessionState.Namespaces);
ImportNamespaces(newNamespaces, sessionState);
}
_log.Debug("Starting execution");
var result = Execute(code, sessionState.Session);
_log.Debug("Finished execution");
return result;
}
protected virtual ScriptResult Execute(string code, Evaluator session)
{
Guard.AgainstNullArgument("session", session);
try
{
object scriptResult = null;
var segmenter = new ScriptSegmenter();
foreach (var segment in segmenter.Segment(code))
{
bool resultSet;
session.Evaluate(segment.Code, out scriptResult, out resultSet);
}
return new ScriptResult(returnValue: scriptResult);
}
catch (AggregateException ex)
{
return new ScriptResult(executionException: ex.InnerException);
}
catch (Exception ex)
{
return new ScriptResult(executionException: ex);
}
}
private void ImportNamespaces(IEnumerable<string> namespaces, SessionState<Evaluator> sessionState)
{
var builder = new StringBuilder();
foreach (var ns in namespaces)
{
_log.DebugFormat(ns);
builder.AppendLine(string.Format("using {0};", ns));
sessionState.Namespaces.Add(ns);
}
sessionState.Session.Compile(builder.ToString());
}
}
}