Repository navigation
Expand file tree
/
Copy pathScriptState.cs
More file actions
276 lines (239 loc) · 11.7 KB
/
Copy pathScriptState.cs
File metadata and controls
276 lines (239 loc) · 11.7 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
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
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using System.Reflection;
using System.Collections.Generic;
namespace Microsoft.CodeAnalysis.Scripting
{
/// <summary>
/// The result of running a script.
/// </summary>
public abstract class ScriptState
{
/// <summary>
/// The script that ran to produce this result.
/// </summary>
public Script Script { get; }
/// <summary>
/// Caught exception originating from the script top-level code.
/// </summary>
/// <remarks>
/// Exceptions are only caught and stored here if the API returning the <see cref="ScriptState"/> is instructed to do so.
/// By default they are propagated to the caller of the API.
/// </remarks>
public Exception Exception { get; }
internal ScriptExecutionState ExecutionState { get; }
private ImmutableArray<ScriptVariable> _lazyVariables;
private IReadOnlyDictionary<string, int> _lazyVariableMap;
internal ScriptState(ScriptExecutionState executionState, Script script, Exception exceptionOpt)
{
Debug.Assert(executionState != null);
Debug.Assert(script != null);
ExecutionState = executionState;
Script = script;
Exception = exceptionOpt;
}
/// <summary>
/// The final value produced by running the script.
/// </summary>
public object ReturnValue => GetReturnValue();
internal abstract object GetReturnValue();
/// <summary>
/// Returns variables defined by the scripts in the declaration order.
/// </summary>
public ImmutableArray<ScriptVariable> Variables
{
get
{
if (_lazyVariables == null)
{
ImmutableInterlocked.InterlockedInitialize(ref _lazyVariables, CreateVariables());
}
return _lazyVariables;
}
}
/// <summary>
/// Returns a script variable of the specified name.
/// </summary>
/// <remarks>
/// If multiple script variables are defined in the script (in distinct submissions) returns the last one.
/// Name lookup is case sensitive in C# scripts and case insensitive in VB scripts.
/// </remarks>
/// <returns><see cref="ScriptVariable"/> or null, if no variable of the specified <paramref name="name"/> is defined in the script.</returns>
/// <exception cref="ArgumentNullException"><paramref name="name"/> is null.</exception>
public ScriptVariable GetVariable(string name)
{
if (name == null)
{
throw new ArgumentNullException(nameof(name));
}
int index;
return GetVariableMap().TryGetValue(name, out index) ? Variables[index] : null;
}
private ImmutableArray<ScriptVariable> CreateVariables()
{
var result = ImmutableArray.CreateBuilder<ScriptVariable>();
var executionState = ExecutionState;
// Don't include the globals object (slot #0)
for (int i = 1; i < executionState.SubmissionStateCount; i++)
{
var state = executionState.GetSubmissionState(i);
Debug.Assert(state != null);
foreach (var field in state.GetType().GetTypeInfo().DeclaredFields)
{
// TODO: synthesized fields of submissions shouldn't be public
if (field.IsPublic && field.Name.Length > 0 && (char.IsLetterOrDigit(field.Name[0]) || field.Name[0] == '_'))
{
result.Add(new ScriptVariable(state, field));
}
}
}
return result.ToImmutable();
}
private IReadOnlyDictionary<string, int> GetVariableMap()
{
if (_lazyVariableMap == null)
{
var map = new Dictionary<string, int>(Script.Compiler.IdentifierComparer);
for (int i = 0; i < Variables.Length; i++)
{
map[Variables[i].Name] = i;
}
_lazyVariableMap = map;
}
return _lazyVariableMap;
}
/// <summary>
/// Continues script execution from the state represented by this instance by running the specified code snippet.
/// </summary>
/// <param name="code">The code to be executed.</param>
/// <param name="options">Options.</param>
/// <param name="cancellationToken">Cancellation token.</param>
/// <returns>A <see cref="ScriptState"/> that represents the state after running <paramref name="code"/>, including all declared variables and return value.</returns>
public Task<ScriptState<object>> ContinueWithAsync(string code, ScriptOptions options, CancellationToken cancellationToken)
=> ContinueWithAsync<object>(code, options, null, cancellationToken);
/// <summary>
/// Continues script execution from the state represented by this instance by running the specified code snippet.
/// </summary>
/// <param name="code">The code to be executed.</param>
/// <param name="options">Options.</param>
/// <param name="catchException">
/// If specified, any exception thrown by the script top-level code is passed to <paramref name="catchException"/>.
/// If it returns true the exception is caught and stored on the resulting <see cref="ScriptState"/>, otherwise the exception is propagated to the caller.
/// </param>
/// <param name="cancellationToken">Cancellation token.</param>
/// <returns>A <see cref="ScriptState"/> that represents the state after running <paramref name="code"/>, including all declared variables, return value and caught exception (if applicable).</returns>
public Task<ScriptState<object>> ContinueWithAsync(string code, ScriptOptions options = null, Func<Exception, bool> catchException = null, CancellationToken cancellationToken = default(CancellationToken))
=> Script.ContinueWith<object>(code, options).RunFromAsync(this, catchException, cancellationToken);
/// <summary>
/// Continues script execution from the state represented by this instance by running the specified code snippet.
/// </summary>
/// <param name="code">The code to be executed.</param>
/// <param name="options">Options.</param>
/// <param name="cancellationToken">Cancellation token.</param>
/// <returns>A <see cref="ScriptState"/> that represents the state after running <paramref name="code"/>, including all declared variables and return value.</returns>
public Task<ScriptState<TResult>> ContinueWithAsync<TResult>(string code, ScriptOptions options, CancellationToken cancellationToken)
=> ContinueWithAsync<TResult>(code, options, null, cancellationToken);
/// <summary>
/// Continues script execution from the state represented by this instance by running the specified code snippet.
/// </summary>
/// <param name="code">The code to be executed.</param>
/// <param name="options">Options.</param>
/// <param name="catchException">
/// If specified, any exception thrown by the script top-level code is passed to <paramref name="catchException"/>.
/// If it returns true the exception is caught and stored on the resulting <see cref="ScriptState"/>, otherwise the exception is propagated to the caller.
/// </param>
/// <param name="cancellationToken">Cancellation token.</param>
/// <returns>A <see cref="ScriptState"/> that represents the state after running <paramref name="code"/>, including all declared variables, return value and caught exception (if applicable).</returns>
public Task<ScriptState<TResult>> ContinueWithAsync<TResult>(string code, ScriptOptions options = null, Func<Exception, bool> catchException = null, CancellationToken cancellationToken = default(CancellationToken))
=> Script.ContinueWith<TResult>(code, options).RunFromAsync(this, catchException, cancellationToken);
// How do we resolve overloads? We should use the language semantics.
// https://github.com/dotnet/roslyn/issues/3720
#if TODO
/// <summary>
/// Invoke a method declared by the script.
/// </summary>
public object Invoke(string name, params object[] args)
{
var func = this.FindMethod(name, args != null ? args.Length : 0);
if (func != null)
{
return func(args);
}
return null;
}
private Func<object[], object> FindMethod(string name, int argCount)
{
for (int i = _executionState.Count - 1; i >= 0; i--)
{
var sub = _executionState[i];
if (sub != null)
{
var type = sub.GetType();
var method = FindMethod(type, name, argCount);
if (method != null)
{
return (args) => method.Invoke(sub, args);
}
}
}
return null;
}
private MethodInfo FindMethod(Type type, string name, int argCount)
{
return type.GetMethod(name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
}
/// <summary>
/// Create a delegate to a method declared by the script.
/// </summary>
public TDelegate CreateDelegate<TDelegate>(string name)
{
var delegateInvokeMethod = typeof(TDelegate).GetMethod("Invoke", BindingFlags.Instance | BindingFlags.Public);
for (int i = _executionState.Count - 1; i >= 0; i--)
{
var sub = _executionState[i];
if (sub != null)
{
var type = sub.GetType();
var method = FindMatchingMethod(type, name, delegateInvokeMethod);
if (method != null)
{
return (TDelegate)(object)method.CreateDelegate(typeof(TDelegate), sub);
}
}
}
return default(TDelegate);
}
private MethodInfo FindMatchingMethod(Type instanceType, string name, MethodInfo delegateInvokeMethod)
{
var dprms = delegateInvokeMethod.GetParameters();
foreach (var mi in instanceType.GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic))
{
if (mi.Name == name)
{
var prms = mi.GetParameters();
if (prms.Length == dprms.Length)
{
// TODO: better matching..
return mi;
}
}
}
return null;
}
#endif
}
public sealed class ScriptState<T> : ScriptState
{
public new T ReturnValue { get; }
internal override object GetReturnValue() => ReturnValue;
internal ScriptState(ScriptExecutionState executionState, Script script, T value, Exception exceptionOpt)
: base(executionState, script, exceptionOpt)
{
ReturnValue = value;
}
}
}