mirror of
https://github.com/StockSharp/StockSharp.git
synced 2026-12-04 08:32:23 +00:00
Register language extensions at startup and create their compilers on first use. Prepare shared Python modules during initialization and defer the IronPython engine.
253 lines
9.8 KiB
C#
253 lines
9.8 KiB
C#
namespace StockSharp.Algo.Compilation;
|
|
|
|
using System;
|
|
using System.Collections.Generic;
|
|
using System.IO;
|
|
using System.Text;
|
|
using System.Linq;
|
|
using System.ComponentModel;
|
|
using System.Reflection;
|
|
using System.Threading;
|
|
using System.Threading.Tasks;
|
|
|
|
using Ecng.Common;
|
|
using Ecng.IO;
|
|
using Ecng.Configuration;
|
|
using Ecng.Reflection;
|
|
using Ecng.Logging;
|
|
using Ecng.ComponentModel;
|
|
using Ecng.Compilation;
|
|
using Ecng.Compilation.FSharp;
|
|
using Ecng.Compilation.Python;
|
|
using Ecng.Compilation.Roslyn;
|
|
|
|
using IronPython.Hosting;
|
|
|
|
using Microsoft.Scripting.Utils;
|
|
|
|
using StockSharp.Configuration;
|
|
|
|
/// <summary>
|
|
/// Provides extension methods and helpers for dynamic compilation and Python integration in StockSharp Studio.
|
|
/// </summary>
|
|
public static class CompilationExtensions
|
|
{
|
|
private sealed class LazyCompiler(string extension, Func<ICompiler> createCompiler) : ICompiler
|
|
{
|
|
private readonly Lazy<ICompiler> _compiler = new(createCompiler);
|
|
|
|
public string Extension { get; } = extension;
|
|
public bool IsAssemblyPersistable => _compiler.Value.IsAssemblyPersistable;
|
|
public bool IsTabsSupported => _compiler.Value.IsTabsSupported;
|
|
public bool IsCaseSensitive => _compiler.Value.IsCaseSensitive;
|
|
public bool IsReferencesSupported => _compiler.Value.IsReferencesSupported;
|
|
|
|
public ICompilerContext CreateContext() => _compiler.Value.CreateContext();
|
|
|
|
public Task<CompilationError[]> Analyse(object analyzer, IEnumerable<object> analyzerSettings, string name,
|
|
IEnumerable<string> sources, IEnumerable<(string name, byte[] body)> refs, CancellationToken cancellationToken)
|
|
=> _compiler.Value.Analyse(analyzer, analyzerSettings, name, sources, refs, cancellationToken);
|
|
|
|
public Task<CompilationResult> Compile(string name, IEnumerable<string> sources,
|
|
IEnumerable<(string name, byte[] body)> refs, CancellationToken cancellationToken)
|
|
=> _compiler.Value.Compile(name, sources, refs, cancellationToken);
|
|
}
|
|
|
|
private class PythonStream(ILogReceiver logs) : Stream
|
|
{
|
|
private readonly ILogReceiver _logs = logs ?? throw new ArgumentNullException(nameof(logs));
|
|
|
|
// The engine decides where to cut the byte stream, so a multi-byte character can arrive
|
|
// split between two writes. The decoder keeps such an incomplete tail until the rest of
|
|
// its bytes turn up, and the lock guards that state against concurrently running scripts.
|
|
private readonly Decoder _decoder = Encoding.UTF8.GetDecoder();
|
|
private readonly Lock _sync = new();
|
|
|
|
// Grown to fit and then reused: a script writes to its log a line at a time, and an array
|
|
// per write is an allocation for nothing. Held under the same lock the decoder is.
|
|
private char[] _chars = [];
|
|
|
|
public override bool CanRead => false;
|
|
public override bool CanSeek => false;
|
|
public override bool CanWrite => true;
|
|
|
|
public override long Length => throw new NotSupportedException();
|
|
public override long Position { get => throw new NotSupportedException(); set => throw new NotSupportedException(); }
|
|
|
|
public override void Write(byte[] buffer, int offset, int count)
|
|
{
|
|
ArgumentNullException.ThrowIfNull(buffer);
|
|
|
|
if (count <= 0)
|
|
return;
|
|
|
|
string text;
|
|
|
|
using (_sync.EnterScope())
|
|
{
|
|
var max = Encoding.UTF8.GetMaxCharCount(count);
|
|
|
|
if (_chars.Length < max)
|
|
_chars = new char[max];
|
|
|
|
var charCount = _decoder.GetChars(buffer, offset, count, _chars, 0, flush: false);
|
|
|
|
if (charCount == 0)
|
|
return;
|
|
|
|
// Only what this write decoded is read, so whatever an earlier one left further along
|
|
// the buffer is never seen.
|
|
text = new(_chars, 0, charCount);
|
|
}
|
|
|
|
_logs.LogInfo(text);
|
|
}
|
|
|
|
public override void Flush()
|
|
{
|
|
}
|
|
|
|
public override int Read(byte[] buffer, int offset, int count) => throw new NotSupportedException();
|
|
public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException();
|
|
public override void SetLength(long value) => throw new NotSupportedException();
|
|
}
|
|
|
|
private static IEnumerable<(string name, string body)> GetPythonCommon()
|
|
{
|
|
var assembly = typeof(CompilationExtensions).Assembly;
|
|
|
|
var resourceNames = assembly.GetManifestResourceNames();
|
|
|
|
var prefix = $"{typeof(CompilationExtensions).Namespace}.python_common.";
|
|
|
|
foreach (var resourceName in resourceNames.Where(n => n.StartsWithIgnoreCase(prefix)))
|
|
{
|
|
using var stream = assembly.GetManifestResourceStream(resourceName)
|
|
?? throw new InvalidOperationException(resourceName);
|
|
|
|
using var reader = new StreamReader(stream);
|
|
yield return (resourceName.Remove(prefix, true), reader.ReadToEnd());
|
|
}
|
|
}
|
|
|
|
private class PythonCustomTypeDescriptorProvider : ICustomTypeDescriptorProvider
|
|
{
|
|
private class PythonCustomTypeDescriptor(Type type, object instance) : ICustomTypeDescriptorEx
|
|
{
|
|
private class PythonPropertyDescriptor(PropertyInfo propInfo, Type componentType, object instance) : NamedPropertyDescriptor(propInfo.Name, [.. propInfo.GetAttributes()])
|
|
{
|
|
public override Type ComponentType { get; } = componentType ?? throw new ArgumentNullException(nameof(componentType));
|
|
public override bool IsReadOnly { get; } = !propInfo.IsModifiable();
|
|
public override Type PropertyType { get; } = propInfo.PropertyType;
|
|
|
|
public override bool CanResetValue(object component) => false;
|
|
public override object GetValue(object component) => propInfo.GetValue(instance);
|
|
public override void SetValue(object component, object value) => propInfo.SetValue(instance, value);
|
|
public override void ResetValue(object component) => throw new NotSupportedException();
|
|
public override bool ShouldSerializeValue(object component) => false;
|
|
}
|
|
|
|
private readonly ICustomTypeDescriptor _underlying = (ICustomTypeDescriptor)instance;
|
|
private readonly PropertyDescriptorCollection _props = new([.. type.GetProperties().Select(p => new PythonPropertyDescriptor(p, type, instance))]);
|
|
|
|
public object Instance { get; } = instance ?? throw new ArgumentNullException(nameof(instance));
|
|
|
|
AttributeCollection ICustomTypeDescriptor.GetAttributes() => _underlying.GetAttributes();
|
|
string ICustomTypeDescriptor.GetClassName() => _underlying.GetClassName();
|
|
string ICustomTypeDescriptor.GetComponentName() => _underlying.GetComponentName();
|
|
TypeConverter ICustomTypeDescriptor.GetConverter() => _underlying.GetConverter();
|
|
object ICustomTypeDescriptor.GetEditor(Type editorBaseType) => _underlying.GetEditor(editorBaseType);
|
|
|
|
EventDescriptor ICustomTypeDescriptor.GetDefaultEvent() => _underlying.GetDefaultEvent();
|
|
EventDescriptorCollection ICustomTypeDescriptor.GetEvents() => _underlying.GetEvents();
|
|
EventDescriptorCollection ICustomTypeDescriptor.GetEvents(Attribute[] attributes) => _underlying.GetEvents(attributes);
|
|
|
|
PropertyDescriptor ICustomTypeDescriptor.GetDefaultProperty() => GetProperties().TryGetDefault(type);
|
|
public PropertyDescriptorCollection GetProperties() => _props;
|
|
PropertyDescriptorCollection ICustomTypeDescriptor.GetProperties(Attribute[] attributes) => this.GetFilteredProperties(attributes);
|
|
object ICustomTypeDescriptor.GetPropertyOwner(PropertyDescriptor pd) => Instance;
|
|
}
|
|
|
|
bool ICustomTypeDescriptorProvider.TryGet(Type type, object instance, out ICustomTypeDescriptor descriptor)
|
|
{
|
|
if (type is null) throw new ArgumentNullException(nameof(type));
|
|
if (instance is null) throw new ArgumentNullException(nameof(instance));
|
|
|
|
descriptor = default;
|
|
|
|
if (!instance.IsPythonObject())
|
|
return false;
|
|
|
|
descriptor = new PythonCustomTypeDescriptor(type, instance);
|
|
return true;
|
|
}
|
|
}
|
|
|
|
private static ICompiler CreatePythonCompiler(string pythonUtilsPath, ILogReceiver logs)
|
|
{
|
|
var pythonEngine = Python.CreateEngine();
|
|
|
|
var paths = pythonEngine.GetSearchPaths();
|
|
paths.Add(pythonUtilsPath);
|
|
pythonEngine.SetSearchPaths(paths);
|
|
|
|
var pyIO = pythonEngine.Runtime.IO;
|
|
var outputStream = new PythonStream(logs);
|
|
pyIO.SetOutput(outputStream, Encoding.UTF8);
|
|
pyIO.SetErrorOutput(outputStream, Encoding.UTF8);
|
|
|
|
return new PythonCompiler(pythonEngine);
|
|
}
|
|
|
|
/// <summary>
|
|
/// Prepares common Python files and registers the supported compilers.
|
|
/// </summary>
|
|
/// <param name="fileSystem">File system.</param>
|
|
/// <param name="logs">The log receiver for output and error messages.</param>
|
|
/// <param name="extraPythonCommon">Additional Python common files to include.</param>
|
|
/// <param name="cancellationToken">A cancellation token for async operations.</param>
|
|
public static async Task Init(IFileSystem fileSystem, ILogReceiver logs, IEnumerable<(string name, string body)> extraPythonCommon, CancellationToken cancellationToken)
|
|
{
|
|
await Task.Yield();
|
|
|
|
ArgumentNullException.ThrowIfNull(fileSystem);
|
|
ArgumentNullException.ThrowIfNull(extraPythonCommon);
|
|
|
|
cancellationToken.ThrowIfCancellationRequested();
|
|
ArgumentNullException.ThrowIfNull(logs);
|
|
|
|
var pythonUtilsPath = Paths.PythonUtilsPath;
|
|
fileSystem.CreateDirectory(pythonUtilsPath);
|
|
|
|
foreach (var (name, body) in extraPythonCommon.Concat(GetPythonCommon()))
|
|
{
|
|
cancellationToken.ThrowIfCancellationRequested();
|
|
|
|
try
|
|
{
|
|
await fileSystem.WriteAllTextAsync(Path.Combine(pythonUtilsPath, name), body, cancellationToken: cancellationToken);
|
|
}
|
|
catch (OperationCanceledException)
|
|
{
|
|
// A caller who cancelled must not be told the environment is ready, so this one
|
|
// leaves by the same door it came in instead of being logged as a write failure.
|
|
throw;
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
logs.AddErrorLog(ex);
|
|
}
|
|
}
|
|
|
|
ConfigManager.RegisterService(new CompilerProvider
|
|
{
|
|
{ FileExts.CSharp, new CSharpCompiler() },
|
|
{ FileExts.VisualBasic, new LazyCompiler(FileExts.VisualBasic, static () => new VisualBasicCompiler()) },
|
|
{ FileExts.FSharp, new LazyCompiler(FileExts.FSharp, static () => new FSharpCompiler()) },
|
|
{ FileExts.Python, new LazyCompiler(FileExts.Python, () => CreatePythonCompiler(pythonUtilsPath, logs)) }
|
|
});
|
|
|
|
ConfigManager.RegisterService<ICustomTypeDescriptorProvider>(new PythonCustomTypeDescriptorProvider());
|
|
}
|
|
}
|