Repository navigation
Expand file tree
/
Copy pathScript.cs
More file actions
546 lines (470 loc) · 27.1 KB
/
Copy pathScript.cs
File metadata and controls
546 lines (470 loc) · 27.1 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
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
// 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.Globalization;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Reflection;
using Microsoft.CodeAnalysis;
using Roslyn.Utilities;
using Microsoft.CodeAnalysis.Scripting.Hosting;
using System.Runtime.CompilerServices;
namespace Microsoft.CodeAnalysis.Scripting
{
/// <summary>
/// A class that represents a script that you can run.
///
/// Create a script using a language specific script class such as CSharpScript or VisualBasicScript.
/// </summary>
public abstract class Script
{
internal readonly ScriptCompiler Compiler;
internal readonly ScriptBuilder Builder;
private Compilation _lazyCompilation;
internal Script(ScriptCompiler compiler, ScriptBuilder builder, string code, ScriptOptions options, Type globalsTypeOpt, Script previousOpt)
{
Debug.Assert(code != null);
Debug.Assert(options != null);
Debug.Assert(compiler != null);
Debug.Assert(builder != null);
Compiler = compiler;
Builder = builder;
Previous = previousOpt;
Code = code;
Options = options;
GlobalsType = globalsTypeOpt;
}
internal static Script<T> CreateInitialScript<T>(ScriptCompiler compiler, string codeOpt, ScriptOptions optionsOpt, Type globalsTypeOpt, InteractiveAssemblyLoader assemblyLoaderOpt)
{
return new Script<T>(compiler, new ScriptBuilder(assemblyLoaderOpt ?? new InteractiveAssemblyLoader()), codeOpt ?? "", optionsOpt ?? ScriptOptions.Default, globalsTypeOpt, previousOpt: null);
}
/// <summary>
/// A script that will run first when this script is run.
/// Any declarations made in the previous script can be referenced in this script.
/// The end state from running this script includes all declarations made by both scripts.
/// </summary>
public Script Previous { get; }
/// <summary>
/// The options used by this script.
/// </summary>
public ScriptOptions Options { get; }
/// <summary>
/// The source code of the script.
/// </summary>
public string Code { get; }
/// <summary>
/// The type of an object whose members can be accessed by the script as global variables.
/// </summary>
public Type GlobalsType { get; }
/// <summary>
/// The expected return type of the script.
/// </summary>
public abstract Type ReturnType { get; }
/// <summary>
/// Creates a new version of this script with the specified options.
/// </summary>
public Script WithOptions(ScriptOptions options) => WithOptionsInternal(options);
internal abstract Script WithOptionsInternal(ScriptOptions options);
/// <summary>
/// Continues the script with given code snippet.
/// </summary>
public Script<object> ContinueWith(string code, ScriptOptions options = null) =>
ContinueWith<object>(code, options);
/// <summary>
/// Continues the script with given code snippet.
/// </summary>
public Script<TResult> ContinueWith<TResult>(string code, ScriptOptions options = null) =>
new Script<TResult>(Compiler, Builder, code ?? "", options ?? InheritOptions(Options), GlobalsType, this);
private static ScriptOptions InheritOptions(ScriptOptions previous)
{
// don't inherit references or imports, they have already been applied:
return previous.
WithReferences(ImmutableArray<MetadataReference>.Empty).
WithImports(ImmutableArray<string>.Empty);
}
/// <summary>
/// Get's the <see cref="Compilation"/> that represents the semantics of the script.
/// </summary>
public Compilation GetCompilation()
{
if (_lazyCompilation == null)
{
var compilation = Compiler.CreateSubmission(this);
Interlocked.CompareExchange(ref _lazyCompilation, compilation, null);
}
return _lazyCompilation;
}
/// <summary>
/// Runs the script from the beginning and returns the result of the last code snippet.
/// </summary>
/// <param name="globals">
/// An instance of <see cref="Script.GlobalsType"/> holding on values of global variables accessible from the script.
/// Must be specified if and only if the script was created with a <see cref="Script.GlobalsType"/>.
/// </param>
/// <param name="cancellationToken">Cancellation token.</param>
/// <returns>The result of the last code snippet.</returns>
internal Task<object> EvaluateAsync(object globals = null, CancellationToken cancellationToken = default(CancellationToken)) =>
CommonEvaluateAsync(globals, cancellationToken);
internal abstract Task<object> CommonEvaluateAsync(object globals, CancellationToken cancellationToken);
/// <summary>
/// Runs the script from the beginning.
/// </summary>
/// <param name="globals">
/// An instance of <see cref="Script.GlobalsType"/> holding on values for global variables accessible from the script.
/// Must be specified if and only if the script was created with <see cref="Script.GlobalsType"/>.
/// </param>
/// <param name="cancellationToken">Cancellation token.</param>
/// <returns>A <see cref="ScriptState"/> that represents the state after running the script, including all declared variables and return value.</returns>
public Task<ScriptState> RunAsync(object globals, CancellationToken cancellationToken) =>
CommonRunAsync(globals, null, cancellationToken);
/// <summary>
/// Runs the script from the beginning.
/// </summary>
/// <param name="globals">
/// An instance of <see cref="Script.GlobalsType"/> holding on values for global variables accessible from the script.
/// Must be specified if and only if the script was created with <see cref="Script.GlobalsType"/>.
/// </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 the script, including all declared variables and return value.</returns>
public Task<ScriptState> RunAsync(object globals = null, Func<Exception, bool> catchException = null, CancellationToken cancellationToken = default(CancellationToken)) =>
CommonRunAsync(globals, catchException, cancellationToken);
internal abstract Task<ScriptState> CommonRunAsync(object globals, Func<Exception, bool> catchException, CancellationToken cancellationToken);
/// <summary>
/// Run the script from the specified state.
/// </summary>
/// <param name="previousState">
/// Previous state of the script execution.
/// </param>
/// <param name="cancellationToken">Cancellation token.</param>
/// <returns>A <see cref="ScriptState"/> that represents the state after running the script, including all declared variables and return value.</returns>
public Task<ScriptState> RunFromAsync(ScriptState previousState, CancellationToken cancellationToken) =>
CommonRunFromAsync(previousState, null, cancellationToken);
/// <summary>
/// Run the script from the specified state.
/// </summary>
/// <param name="previousState">
/// Previous state of the script execution.
/// </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 the script, including all declared variables and return value.</returns>
public Task<ScriptState> RunFromAsync(ScriptState previousState, Func<Exception, bool> catchException = null, CancellationToken cancellationToken = default(CancellationToken)) =>
CommonRunFromAsync(previousState, catchException, cancellationToken);
internal abstract Task<ScriptState> CommonRunFromAsync(ScriptState previousState, Func<Exception, bool> catchException, CancellationToken cancellationToken);
/// <summary>
/// Forces the script through the compilation step.
/// If not called directly, the compilation step will occur on the first call to Run.
/// </summary>
public ImmutableArray<Diagnostic> Compile(CancellationToken cancellationToken = default(CancellationToken)) =>
CommonCompile(cancellationToken);
internal abstract ImmutableArray<Diagnostic> CommonCompile(CancellationToken cancellationToken);
internal abstract Func<object[], Task> CommonGetExecutor(CancellationToken cancellationToken);
// Apply recursive alias <host> to the host assembly reference, so that we hide its namespaces and global types behind it.
internal static readonly MetadataReferenceProperties HostAssemblyReferenceProperties =
MetadataReferenceProperties.Assembly.WithAliases(ImmutableArray.Create("<host>")).WithRecursiveAliases(true);
/// <summary>
/// Gets the references that need to be assigned to the compilation.
/// This can be different than the list of references defined by the <see cref="ScriptOptions"/> instance.
/// </summary>
internal ImmutableArray<MetadataReference> GetReferencesForCompilation(
CommonMessageProvider messageProvider,
DiagnosticBag diagnostics,
MetadataReference languageRuntimeReferenceOpt = null)
{
var resolver = Options.MetadataResolver;
var references = ArrayBuilder<MetadataReference>.GetInstance();
try
{
if (Previous == null)
{
var corLib = MetadataReference.CreateFromAssemblyInternal(typeof(object).GetTypeInfo().Assembly);
references.Add(corLib);
if (GlobalsType != null)
{
var globalsAssembly = GlobalsType.GetTypeInfo().Assembly;
// If the assembly doesn't have metadata (it's an in-memory or dynamic assembly),
// the host has to add reference to the metadata where globals type is located explicitly.
if (MetadataReference.HasMetadata(globalsAssembly))
{
references.Add(MetadataReference.CreateFromAssemblyInternal(globalsAssembly, HostAssemblyReferenceProperties));
}
}
if (languageRuntimeReferenceOpt != null)
{
references.Add(languageRuntimeReferenceOpt);
}
}
// add new references:
foreach (var reference in Options.MetadataReferences)
{
var unresolved = reference as UnresolvedMetadataReference;
if (unresolved != null)
{
var resolved = resolver.ResolveReference(unresolved.Reference, null, unresolved.Properties);
if (resolved.IsDefault)
{
diagnostics.Add(messageProvider.CreateDiagnostic(messageProvider.ERR_MetadataFileNotFound, Location.None, unresolved.Reference));
}
else
{
references.AddRange(resolved);
}
}
else
{
references.Add(reference);
}
}
return references.ToImmutable();
}
finally
{
references.Free();
}
}
// TODO: remove
internal bool HasReturnValue()
{
return GetCompilation().HasSubmissionResult();
}
}
public sealed class Script<T> : Script
{
private ImmutableArray<Func<object[], Task>> _lazyPrecedingExecutors;
private Func<object[], Task<T>> _lazyExecutor;
internal Script(ScriptCompiler compiler, ScriptBuilder builder, string code, ScriptOptions options, Type globalsTypeOpt, Script previousOpt)
: base(compiler, builder, code, options, globalsTypeOpt, previousOpt)
{
}
public override Type ReturnType => typeof(T);
public new Script<T> WithOptions(ScriptOptions options)
{
return (options == Options) ? this : new Script<T>(Compiler, Builder, Code, options, GlobalsType, Previous);
}
internal override Script WithOptionsInternal(ScriptOptions options) => WithOptions(options);
internal override ImmutableArray<Diagnostic> CommonCompile(CancellationToken cancellationToken)
{
// TODO: avoid throwing exception, report all diagnostics https://github.com/dotnet/roslyn/issues/5949
try
{
GetPrecedingExecutors(cancellationToken);
GetExecutor(cancellationToken);
return ImmutableArray.CreateRange(GetCompilation().GetDiagnostics(cancellationToken).Where(d => d.Severity == DiagnosticSeverity.Warning));
}
catch (CompilationErrorException e)
{
return ImmutableArray.CreateRange(e.Diagnostics.Where(d => d.Severity == DiagnosticSeverity.Error || d.Severity == DiagnosticSeverity.Warning));
}
}
internal override Func<object[], Task> CommonGetExecutor(CancellationToken cancellationToken)
=> GetExecutor(cancellationToken);
internal override Task<object> CommonEvaluateAsync(object globals, CancellationToken cancellationToken) =>
EvaluateAsync(globals, cancellationToken).CastAsync<T, object>();
internal override Task<ScriptState> CommonRunAsync(object globals, Func<Exception, bool> catchException, CancellationToken cancellationToken) =>
RunAsync(globals, catchException, cancellationToken).CastAsync<ScriptState<T>, ScriptState>();
internal override Task<ScriptState> CommonRunFromAsync(ScriptState previousState, Func<Exception, bool> catchException, CancellationToken cancellationToken) =>
RunFromAsync(previousState, catchException, cancellationToken).CastAsync<ScriptState<T>, ScriptState>();
/// <exception cref="CompilationErrorException">Compilation has errors.</exception>
private Func<object[], Task<T>> GetExecutor(CancellationToken cancellationToken)
{
if (_lazyExecutor == null)
{
Interlocked.CompareExchange(ref _lazyExecutor, Builder.CreateExecutor<T>(Compiler, GetCompilation(), cancellationToken), null);
}
return _lazyExecutor;
}
/// <exception cref="CompilationErrorException">Compilation has errors.</exception>
private ImmutableArray<Func<object[], Task>> GetPrecedingExecutors(CancellationToken cancellationToken)
{
if (_lazyPrecedingExecutors.IsDefault)
{
var preceding = TryGetPrecedingExecutors(null, cancellationToken);
Debug.Assert(!preceding.IsDefault);
InterlockedOperations.Initialize(ref _lazyPrecedingExecutors, preceding);
}
return _lazyPrecedingExecutors;
}
/// <exception cref="CompilationErrorException">Compilation has errors.</exception>
private ImmutableArray<Func<object[], Task>> TryGetPrecedingExecutors(Script lastExecutedScriptInChainOpt, CancellationToken cancellationToken)
{
Script script = Previous;
if (script == lastExecutedScriptInChainOpt)
{
return ImmutableArray<Func<object[], Task>>.Empty;
}
var scriptsReversed = ArrayBuilder<Script>.GetInstance();
while (script != null && script != lastExecutedScriptInChainOpt)
{
scriptsReversed.Add(script);
script = script.Previous;
}
if (lastExecutedScriptInChainOpt != null && script != lastExecutedScriptInChainOpt)
{
scriptsReversed.Free();
return default(ImmutableArray<Func<object[], Task>>);
}
var executors = ArrayBuilder<Func<object[], Task>>.GetInstance(scriptsReversed.Count);
// We need to build executors in the order in which they are chained,
// so that assemblies created for the submissions are loaded in the correct order.
for (int i = scriptsReversed.Count - 1; i >= 0; i--)
{
executors.Add(scriptsReversed[i].CommonGetExecutor(cancellationToken));
}
return executors.ToImmutableAndFree();
}
/// <summary>
/// Runs the script from the beginning and returns the result of the last code snippet.
/// </summary>
/// <param name="globals">
/// An instance of <see cref="Script.GlobalsType"/> holding on values of global variables accessible from the script.
/// Must be specified if and only if the script was created with a <see cref="Script.GlobalsType"/>.
/// </param>
/// <param name="cancellationToken">Cancellation token.</param>
/// <returns>The result of the last code snippet.</returns>
internal new Task<T> EvaluateAsync(object globals = null, CancellationToken cancellationToken = default(CancellationToken)) =>
RunAsync(globals, cancellationToken).GetEvaluationResultAsync();
/// <summary>
/// Runs the script from the beginning.
/// </summary>
/// <param name="globals">
/// An instance of <see cref="Script.GlobalsType"/> holding on values for global variables accessible from the script.
/// Must be specified if and only if the script was created with <see cref="Script.GlobalsType"/>.
/// </param>
/// <param name="cancellationToken">Cancellation token.</param>
/// <returns>A <see cref="ScriptState"/> that represents the state after running the script, including all declared variables and return value.</returns>
/// <exception cref="CompilationErrorException">Compilation has errors.</exception>
/// <exception cref="ArgumentException">The type of <paramref name="globals"/> doesn't match <see cref="Script.GlobalsType"/>.</exception>
public new Task<ScriptState<T>> RunAsync(object globals, CancellationToken cancellationToken)
=> RunAsync(globals, null, cancellationToken);
/// <summary>
/// Runs the script from the beginning.
/// </summary>
/// <param name="globals">
/// An instance of <see cref="Script.GlobalsType"/> holding on values for global variables accessible from the script.
/// Must be specified if and only if the script was created with <see cref="Script.GlobalsType"/>.
/// </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 the script, including all declared variables and return value.</returns>
/// <exception cref="CompilationErrorException">Compilation has errors.</exception>
/// <exception cref="ArgumentException">The type of <paramref name="globals"/> doesn't match <see cref="Script.GlobalsType"/>.</exception>
public new Task<ScriptState<T>> RunAsync(object globals = null, Func<Exception, bool> catchException = null, CancellationToken cancellationToken = default(CancellationToken))
{
// The following validation and executor construction may throw;
// do so synchronously so that the exception is not wrapped in the task.
ValidateGlobals(globals, GlobalsType);
var executionState = ScriptExecutionState.Create(globals);
var precedingExecutors = GetPrecedingExecutors(cancellationToken);
var currentExecutor = GetExecutor(cancellationToken);
return RunSubmissionsAsync(executionState, precedingExecutors, currentExecutor, catchException, cancellationToken);
}
/// <summary>
/// Creates a delegate that will run this script from the beginning when invoked.
/// </summary>
/// <remarks>
/// The delegate doesn't hold on this script or its compilation.
/// </remarks>
public ScriptRunner<T> CreateDelegate(CancellationToken cancellationToken = default(CancellationToken))
{
var precedingExecutors = GetPrecedingExecutors(cancellationToken);
var currentExecutor = GetExecutor(cancellationToken);
var globalsType = GlobalsType;
return (globals, token) =>
{
ValidateGlobals(globals, globalsType);
return ScriptExecutionState.Create(globals).RunSubmissionsAsync<T>(precedingExecutors, currentExecutor, null, null, token);
};
}
/// <summary>
/// Run the script from the specified state.
/// </summary>
/// <param name="previousState">
/// Previous state of the script execution.
/// </param>
/// <param name="cancellationToken">Cancellation token.</param>
/// <returns>A <see cref="ScriptState"/> that represents the state after running the script, including all declared variables and return value.</returns>
/// <exception cref="ArgumentNullException"><paramref name="previousState"/> is null.</exception>
/// <exception cref="ArgumentException"><paramref name="previousState"/> is not a previous execution state of this script.</exception>
public new Task<ScriptState<T>> RunFromAsync(ScriptState previousState, CancellationToken cancellationToken)
=> RunFromAsync(previousState, null, cancellationToken);
/// <summary>
/// Run the script from the specified state.
/// </summary>
/// <param name="previousState">
/// Previous state of the script execution.
/// </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 the script, including all declared variables and return value.</returns>
/// <exception cref="ArgumentNullException"><paramref name="previousState"/> is null.</exception>
/// <exception cref="ArgumentException"><paramref name="previousState"/> is not a previous execution state of this script.</exception>
public new Task<ScriptState<T>> RunFromAsync(ScriptState previousState, Func<Exception, bool> catchException = null, CancellationToken cancellationToken = default(CancellationToken))
{
// The following validation and executor construction may throw;
// do so synchronously so that the exception is not wrapped in the task.
if (previousState == null)
{
throw new ArgumentNullException(nameof(previousState));
}
if (previousState.Script == this)
{
// this state is already the output of running this script.
return Task.FromResult((ScriptState<T>)previousState);
}
var precedingExecutors = TryGetPrecedingExecutors(previousState.Script, cancellationToken);
if (precedingExecutors.IsDefault)
{
throw new ArgumentException(ScriptingResources.StartingStateIncompatible, nameof(previousState));
}
var currentExecutor = GetExecutor(cancellationToken);
ScriptExecutionState newExecutionState = previousState.ExecutionState.FreezeAndClone();
return RunSubmissionsAsync(newExecutionState, precedingExecutors, currentExecutor, catchException, cancellationToken);
}
private async Task<ScriptState<T>> RunSubmissionsAsync(
ScriptExecutionState executionState,
ImmutableArray<Func<object[], Task>> precedingExecutors,
Func<object[], Task> currentExecutor,
Func<Exception, bool> catchExceptionOpt,
CancellationToken cancellationToken)
{
var exceptionOpt = (catchExceptionOpt != null) ? new StrongBox<Exception>() : null;
T result = await executionState.RunSubmissionsAsync<T>(precedingExecutors, currentExecutor, exceptionOpt, catchExceptionOpt, cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
return new ScriptState<T>(executionState, this, result, exceptionOpt?.Value);
}
private static void ValidateGlobals(object globals, Type globalsType)
{
if (globalsType != null)
{
if (globals == null)
{
throw new ArgumentException(ScriptingResources.ScriptRequiresGlobalVariables, nameof(globals));
}
var runtimeType = globals.GetType().GetTypeInfo();
var globalsTypeInfo = globalsType.GetTypeInfo();
if (!globalsTypeInfo.IsAssignableFrom(runtimeType))
{
throw new ArgumentException(string.Format(ScriptingResources.GlobalsNotAssignable, runtimeType, globalsTypeInfo), nameof(globals));
}
}
else if (globals != null)
{
throw new ArgumentException(ScriptingResources.GlobalVariablesWithoutGlobalType, nameof(globals));
}
}
}
}