This commit is contained in:
Jelle Luteijn 2022-05-15 11:19:49 +02:00
parent 16e76d6b31
commit 484dbfc9d9
529 changed files with 113694 additions and 0 deletions

View file

@ -0,0 +1,103 @@
using System;
using System.Runtime.Remoting;
using System.Security.Permissions;
using System.Threading;
using AspClassic.Scripting.Utils;
namespace AspClassic.Scripting.Hosting;
public sealed class CompiledCode : MarshalByRefObject
{
private readonly ScriptEngine _engine;
private readonly ScriptCode _code;
private ScriptScope _defaultScope;
internal ScriptCode ScriptCode => _code;
public ScriptEngine Engine => _engine;
public ScriptScope DefaultScope
{
get
{
if (_defaultScope == null)
{
Interlocked.CompareExchange(ref _defaultScope, new ScriptScope(_engine, _code.CreateScope()), null);
}
return _defaultScope;
}
}
internal CompiledCode(ScriptEngine engine, ScriptCode code)
{
_engine = engine;
_code = code;
}
public dynamic Execute()
{
return _code.Run(DefaultScope.Scope);
}
public dynamic Execute(ScriptScope scope)
{
ContractUtils.RequiresNotNull(scope, "scope");
return _code.Run(scope.Scope);
}
public T Execute<T>()
{
return _engine.Operations.ConvertTo<T>((object)Execute());
}
public T Execute<T>(ScriptScope scope)
{
return _engine.Operations.ConvertTo<T>((object)Execute(scope));
}
public ObjectHandle ExecuteAndWrap()
{
return new ObjectHandle((object)Execute());
}
public ObjectHandle ExecuteAndWrap(ScriptScope scope)
{
return new ObjectHandle((object)Execute(scope));
}
public ObjectHandle ExecuteAndWrap(out ObjectHandle exception)
{
exception = null;
try
{
return new ObjectHandle((object)Execute());
}
catch (Exception o)
{
exception = new ObjectHandle(o);
return null;
}
}
public ObjectHandle ExecuteAndWrap(ScriptScope scope, out ObjectHandle exception)
{
exception = null;
try
{
return new ObjectHandle((object)Execute(scope));
}
catch (Exception o)
{
exception = new ObjectHandle(o);
return null;
}
}
[SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.Infrastructure)]
public override object InitializeLifetimeService()
{
return null;
}
}

View file

@ -0,0 +1,93 @@
using System;
using System.Configuration;
using AspClassic.Scripting.Utils;
namespace AspClassic.Scripting.Hosting.Configuration;
public class LanguageElement : ConfigurationElement
{
private const string _Names = "names";
private const string _Extensions = "extensions";
private const string _Type = "type";
private const string _DisplayName = "displayName";
private static ConfigurationPropertyCollection _Properties = new ConfigurationPropertyCollection
{
new ConfigurationProperty("names", typeof(string), null),
new ConfigurationProperty("extensions", typeof(string), null),
new ConfigurationProperty("type", typeof(string), null, ConfigurationPropertyOptions.IsRequired),
new ConfigurationProperty("displayName", typeof(string), null)
};
protected override ConfigurationPropertyCollection Properties => _Properties;
public string Names
{
get
{
return (string)base["names"];
}
set
{
base["names"] = value;
}
}
public string Extensions
{
get
{
return (string)base["extensions"];
}
set
{
base["extensions"] = value;
}
}
public string Type
{
get
{
return (string)base["type"];
}
set
{
base["type"] = value;
}
}
public string DisplayName
{
get
{
return (string)base["displayName"];
}
set
{
base["displayName"] = value;
}
}
public string[] GetNamesArray()
{
return Split(Names);
}
public string[] GetExtensionsArray()
{
return Split(Extensions);
}
private static string[] Split(string str)
{
if (str == null)
{
return ArrayUtils.EmptyStrings;
}
return str.Split(new char[2] { ';', ',' }, StringSplitOptions.RemoveEmptyEntries);
}
}

View file

@ -0,0 +1,22 @@
using System.Configuration;
namespace AspClassic.Scripting.Hosting.Configuration;
public class LanguageElementCollection : ConfigurationElementCollection
{
public override ConfigurationElementCollectionType CollectionType => ConfigurationElementCollectionType.BasicMap;
protected override bool ThrowOnDuplicate => false;
protected override string ElementName => "language";
protected override ConfigurationElement CreateNewElement()
{
return new LanguageElement();
}
protected override object GetElementKey(ConfigurationElement element)
{
return ((LanguageElement)element).Type;
}
}

View file

@ -0,0 +1,105 @@
using System;
using System.Configuration;
using AspClassic.Scripting.Runtime;
namespace AspClassic.Scripting.Hosting.Configuration;
public class OptionElement : ConfigurationElement
{
internal sealed class Key : IEquatable<Key>
{
private readonly string _option;
private readonly string _language;
public string Option => _option;
public string Language => _language;
public Key(string option, string language)
{
_option = option;
_language = language;
}
public override bool Equals(object obj)
{
return Equals(obj as Key);
}
public bool Equals(Key other)
{
if (other != null && DlrConfiguration.OptionNameComparer.Equals(_option, other._option))
{
return DlrConfiguration.LanguageNameComparer.Equals(_language, other._language);
}
return false;
}
public override int GetHashCode()
{
return _option.GetHashCode() ^ (_language ?? string.Empty).GetHashCode();
}
public override string ToString()
{
return (string.IsNullOrEmpty(_language) ? string.Empty : (_language + ":")) + _option;
}
}
private const string _Option = "option";
private const string _Value = "value";
private const string _Language = "language";
private static ConfigurationPropertyCollection _Properties = new ConfigurationPropertyCollection
{
new ConfigurationProperty("option", typeof(string), string.Empty, ConfigurationPropertyOptions.IsRequired | ConfigurationPropertyOptions.IsKey),
new ConfigurationProperty("value", typeof(string), string.Empty, ConfigurationPropertyOptions.IsRequired),
new ConfigurationProperty("language", typeof(string), string.Empty, ConfigurationPropertyOptions.IsKey)
};
protected override ConfigurationPropertyCollection Properties => _Properties;
public string Name
{
get
{
return (string)base["option"];
}
set
{
base["option"] = value;
}
}
public string Value
{
get
{
return (string)base["value"];
}
set
{
base["value"] = value;
}
}
public string Language
{
get
{
return (string)base["language"];
}
set
{
base["language"] = value;
}
}
internal object GetKey()
{
return new Key(Name, Language);
}
}

View file

@ -0,0 +1,25 @@
using System.Configuration;
namespace AspClassic.Scripting.Hosting.Configuration;
public class OptionElementCollection : ConfigurationElementCollection
{
public override ConfigurationElementCollectionType CollectionType => ConfigurationElementCollectionType.AddRemoveClearMap;
protected override bool ThrowOnDuplicate => false;
public OptionElementCollection()
{
base.AddElementName = "set";
}
protected override ConfigurationElement CreateNewElement()
{
return new OptionElement();
}
protected override object GetElementKey(ConfigurationElement element)
{
return ((OptionElement)element).GetKey();
}
}

View file

@ -0,0 +1,166 @@
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Xml;
using AspClassic.Scripting.Runtime;
using AspClassic.Scripting.Utils;
namespace AspClassic.Scripting.Hosting.Configuration;
public class Section : ConfigurationSection
{
private const string _DebugMode = "debugMode";
private const string _PrivateBinding = "privateBinding";
private const string _Languages = "languages";
private const string _Options = "options";
public static readonly string SectionName = "AspClassic.Scripting";
private static ConfigurationPropertyCollection _Properties = new ConfigurationPropertyCollection
{
new ConfigurationProperty("debugMode", typeof(bool?), null),
new ConfigurationProperty("privateBinding", typeof(bool?), null),
new ConfigurationProperty("languages", typeof(LanguageElementCollection), null, ConfigurationPropertyOptions.IsDefaultCollection),
new ConfigurationProperty("options", typeof(OptionElementCollection), null)
};
protected override ConfigurationPropertyCollection Properties => _Properties;
public bool? DebugMode
{
get
{
return (bool?)base["debugMode"];
}
set
{
base["debugMode"] = value;
}
}
public bool? PrivateBinding
{
get
{
return (bool?)base["privateBinding"];
}
set
{
base["privateBinding"] = value;
}
}
public IEnumerable<LanguageElement> GetLanguages()
{
if (!(base["languages"] is LanguageElementCollection languages))
{
yield break;
}
foreach (object languageConfig in languages)
{
yield return (LanguageElement)languageConfig;
}
}
public IEnumerable<OptionElement> GetOptions()
{
if (!(base["options"] is OptionElementCollection options))
{
yield break;
}
foreach (object option in options)
{
yield return (OptionElement)option;
}
}
private static Section LoadFromFile(Stream configFileStream)
{
Section section = new Section();
using XmlReader xmlReader = XmlReader.Create(configFileStream);
if (xmlReader.ReadToDescendant("configuration") && xmlReader.ReadToDescendant(SectionName))
{
section.DeserializeElement(xmlReader, serializeCollectionKey: false);
return section;
}
return null;
}
internal static void LoadRuntimeSetup(ScriptRuntimeSetup setup, Stream configFileStream)
{
Section section = ((configFileStream == null) ? (ConfigurationManager.GetSection(SectionName) as Section) : LoadFromFile(configFileStream));
if (section == null)
{
return;
}
if (section.DebugMode.HasValue)
{
setup.DebugMode = section.DebugMode.Value;
}
if (section.PrivateBinding.HasValue)
{
setup.PrivateBinding = section.PrivateBinding.Value;
}
foreach (LanguageElement language in section.GetLanguages())
{
string type = language.Type;
string[] namesArray = language.GetNamesArray();
string[] extensionsArray = language.GetExtensionsArray();
string displayName = language.DisplayName ?? ((namesArray.Length > 0) ? namesArray[0] : language.Type);
bool flag = false;
foreach (LanguageSetup languageSetup in setup.LanguageSetups)
{
if (languageSetup.TypeName == type)
{
languageSetup.Names.Clear();
string[] array = namesArray;
foreach (string item in array)
{
languageSetup.Names.Add(item);
}
languageSetup.FileExtensions.Clear();
string[] array2 = extensionsArray;
foreach (string item2 in array2)
{
languageSetup.FileExtensions.Add(item2);
}
languageSetup.DisplayName = displayName;
flag = true;
break;
}
}
if (!flag)
{
setup.LanguageSetups.Add(new LanguageSetup(type, displayName, namesArray, extensionsArray));
}
}
OptionElement option;
foreach (OptionElement option2 in section.GetOptions())
{
option = option2;
if (string.IsNullOrEmpty(option.Language))
{
setup.Options[option.Name] = option.Value;
continue;
}
bool flag2 = false;
foreach (LanguageSetup languageSetup2 in setup.LanguageSetups)
{
if (Utils.CollectionExtensions.Any(languageSetup2.Names,(string s) => DlrConfiguration.LanguageNameComparer.Equals(s, option.Language)))
{
languageSetup2.Options[option.Name] = option.Value;
flag2 = true;
break;
}
}
if (flag2)
{
continue;
}
throw new ConfigurationErrorsException($"Unknown language name: '{option.Language}'");
}
}
}

View file

@ -0,0 +1,43 @@
using System;
using System.Collections.Generic;
using System.Runtime.Remoting;
using System.Security.Permissions;
using AspClassic.Scripting.Runtime;
namespace AspClassic.Scripting.Hosting;
public sealed class DocumentationOperations : MarshalByRefObject
{
private readonly DocumentationProvider _provider;
internal DocumentationOperations(DocumentationProvider provider)
{
_provider = provider;
}
public ICollection<MemberDoc> GetMembers(object value)
{
return _provider.GetMembers(value);
}
public ICollection<OverloadDoc> GetOverloads(object value)
{
return _provider.GetOverloads(value);
}
public ICollection<MemberDoc> GetMembers(ObjectHandle value)
{
return _provider.GetMembers(value.Unwrap());
}
public ICollection<OverloadDoc> GetOverloads(ObjectHandle value)
{
return _provider.GetOverloads(value.Unwrap());
}
[SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.Infrastructure)]
public override object InitializeLifetimeService()
{
return null;
}
}

View file

@ -0,0 +1,20 @@
using System;
using System.Security.Permissions;
namespace AspClassic.Scripting.Hosting;
public abstract class ErrorListener : MarshalByRefObject
{
internal void ReportError(ScriptSource source, string message, SourceSpan span, int errorCode, Severity severity)
{
ErrorReported(source, message, span, errorCode, severity);
}
public abstract void ErrorReported(ScriptSource source, string message, SourceSpan span, int errorCode, Severity severity);
[SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.Infrastructure)]
public override object InitializeLifetimeService()
{
return null;
}
}

View file

@ -0,0 +1,27 @@
namespace AspClassic.Scripting.Hosting;
internal sealed class ErrorListenerProxySink : ErrorSink
{
private readonly ErrorListener _listener;
private readonly ScriptSource _source;
public ErrorListenerProxySink(ScriptSource source, ErrorListener listener)
{
_listener = listener;
_source = source;
}
public override void Add(SourceUnit sourceUnit, string message, SourceSpan span, int errorCode, Severity severity)
{
if (_listener != null)
{
ScriptSource source = ((sourceUnit == _source.SourceUnit) ? _source : new ScriptSource(_source.Engine.Runtime.GetEngine(sourceUnit.LanguageContext), sourceUnit));
_listener.ErrorReported(source, message, span, errorCode, severity);
}
else if (severity == Severity.FatalError || severity == Severity.Error)
{
throw new SyntaxErrorException(message, sourceUnit, span, errorCode, severity);
}
}
}

View file

@ -0,0 +1,28 @@
using System.IO;
namespace AspClassic.Scripting.Hosting;
public sealed class ErrorSinkProxyListener : ErrorListener
{
private ErrorSink _errorSink;
public ErrorSinkProxyListener(ErrorSink errorSink)
{
_errorSink = errorSink;
}
public override void ErrorReported(ScriptSource source, string message, SourceSpan span, int errorCode, Severity severity)
{
string code = null;
string line = null;
try
{
code = source.GetCode();
line = source.GetCodeLine(span.Start.Line);
}
catch (IOException)
{
}
_errorSink.Add(message, source.Path, code, line, span, errorCode, severity);
}
}

View file

@ -0,0 +1,61 @@
using System;
using System.Runtime.Remoting;
using System.Security.Permissions;
using AspClassic.Scripting.Runtime;
using AspClassic.Scripting.Utils;
namespace AspClassic.Scripting.Hosting;
public sealed class ExceptionOperations : MarshalByRefObject
{
private readonly LanguageContext _context;
internal ExceptionOperations(LanguageContext context)
{
_context = context;
}
public string FormatException(Exception exception)
{
return _context.FormatException(exception);
}
public void GetExceptionMessage(Exception exception, out string message, out string errorTypeName)
{
_context.GetExceptionMessage(exception, out message, out errorTypeName);
}
public bool HandleException(Exception exception)
{
ContractUtils.RequiresNotNull(exception, "exception");
return false;
}
public string FormatException(ObjectHandle exception)
{
Exception ex = exception.Unwrap() as Exception;
ContractUtils.Requires(ex != null, "exception", "ObjectHandle must be to Exception object");
return _context.FormatException(ex);
}
public void GetExceptionMessage(ObjectHandle exception, out string message, out string errorTypeName)
{
Exception ex = exception.Unwrap() as Exception;
ContractUtils.Requires(ex != null, "exception", "ObjectHandle must be to Exception object");
_context.GetExceptionMessage(ex, out message, out errorTypeName);
}
public bool HandleException(ObjectHandle exception)
{
Exception ex = exception.Unwrap() as Exception;
ContractUtils.Requires(ex != null, "exception", "ObjectHandle must be to Exception object");
ContractUtils.RequiresNotNull(ex, "exception");
return false;
}
[SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.Infrastructure)]
public override object InitializeLifetimeService()
{
return null;
}
}

View file

@ -0,0 +1,186 @@
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Threading;
using AspClassic.Scripting.Utils;
namespace AspClassic.Scripting.Hosting;
[Serializable]
public sealed class LanguageSetup
{
private string _typeName;
private string _displayName;
private IList<string> _names;
private IList<string> _fileExtensions;
private IDictionary<string, object> _options;
private bool _frozen;
private bool? _interpretedMode;
private bool? _exceptionDetail;
private bool? _perfStats;
private bool? _noAdaptiveCompilation;
public string TypeName
{
get
{
return _typeName;
}
set
{
ContractUtils.RequiresNotEmpty(value, "value");
CheckFrozen();
_typeName = value;
}
}
public string DisplayName
{
get
{
return _displayName;
}
set
{
ContractUtils.RequiresNotNull(value, "value");
CheckFrozen();
_displayName = value;
}
}
public IList<string> Names => _names;
public IList<string> FileExtensions => _fileExtensions;
public IDictionary<string, object> Options => _options;
[Obsolete("This option is ignored")]
public bool InterpretedMode
{
get
{
return GetCachedOption("InterpretedMode", ref _interpretedMode);
}
set
{
CheckFrozen();
Options["InterpretedMode"] = value;
}
}
[Obsolete("Use Options[\"NoAdaptiveCompilation\"] instead.")]
public bool NoAdaptiveCompilation
{
get
{
return GetCachedOption("NoAdaptiveCompilation", ref _noAdaptiveCompilation);
}
set
{
CheckFrozen();
Options["NoAdaptiveCompilation"] = value;
}
}
public bool ExceptionDetail
{
get
{
return GetCachedOption("ExceptionDetail", ref _exceptionDetail);
}
set
{
CheckFrozen();
Options["ExceptionDetail"] = value;
}
}
[Obsolete("Use Options[\"PerfStats\"] instead.")]
public bool PerfStats
{
get
{
return GetCachedOption("PerfStats", ref _perfStats);
}
set
{
CheckFrozen();
Options["PerfStats"] = value;
}
}
public LanguageSetup(string typeName)
: this(typeName, "", ArrayUtils.EmptyStrings, ArrayUtils.EmptyStrings)
{
}
public LanguageSetup(string typeName, string displayName)
: this(typeName, displayName, ArrayUtils.EmptyStrings, ArrayUtils.EmptyStrings)
{
}
public LanguageSetup(string typeName, string displayName, IEnumerable<string> names, IEnumerable<string> fileExtensions)
{
ContractUtils.RequiresNotEmpty(typeName, "typeName");
ContractUtils.RequiresNotNull(displayName, "displayName");
ContractUtils.RequiresNotNull(names, "names");
ContractUtils.RequiresNotNull(fileExtensions, "fileExtensions");
_typeName = typeName;
_displayName = displayName;
_names = new List<string>(names);
_fileExtensions = new List<string>(fileExtensions);
_options = new Dictionary<string, object>();
}
public T GetOption<T>(string name, T defaultValue)
{
if (_options != null && _options.TryGetValue(name, out var value))
{
if (value is T)
{
return (T)value;
}
return (T)Convert.ChangeType(value, typeof(T), Thread.CurrentThread.CurrentCulture);
}
return defaultValue;
}
private bool GetCachedOption(string name, ref bool? storage)
{
if (storage.HasValue)
{
return storage.Value;
}
if (_frozen)
{
storage = GetOption(name, defaultValue: false);
return storage.Value;
}
return GetOption(name, defaultValue: false);
}
internal void Freeze()
{
_frozen = true;
_names = new ReadOnlyCollection<string>(ArrayUtils.MakeArray(_names));
_fileExtensions = new ReadOnlyCollection<string>(ArrayUtils.MakeArray(_fileExtensions));
_options = new AspClassic.Scripting.Utils.ReadOnlyDictionary<string, object>(new Dictionary<string, object>(_options));
}
private void CheckFrozen()
{
if (_frozen)
{
throw new InvalidOperationException("Cannot modify LanguageSetup after it has been used to create a ScriptRuntime");
}
}
}

View file

@ -0,0 +1,24 @@
using System;
using AspClassic.Scripting.Utils;
namespace AspClassic.Scripting.Hosting;
[Serializable]
public class MemberDoc
{
private readonly string _name;
private readonly MemberKind _kind;
public string Name => _name;
public MemberKind Kind => _kind;
public MemberDoc(string name, MemberKind kind)
{
ContractUtils.RequiresNotNull(name, "name");
ContractUtils.Requires(kind >= MemberKind.None && kind <= MemberKind.Namespace, "kind");
_name = name;
_kind = kind;
}
}

View file

@ -0,0 +1,19 @@
namespace AspClassic.Scripting.Hosting;
public enum MemberKind
{
None,
Class,
Delegate,
Enum,
Event,
Field,
Function,
Module,
Property,
Constant,
EnumMember,
Instance,
Method,
Namespace
}

View file

@ -0,0 +1,741 @@
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Runtime.Remoting;
using System.Security.Permissions;
using AspClassic.Scripting.Runtime;
using AspClassic.Scripting.Utils;
namespace AspClassic.Scripting.Hosting;
public sealed class ObjectOperations : MarshalByRefObject
{
private readonly DynamicOperations _ops;
private readonly ScriptEngine _engine;
public ScriptEngine Engine => _engine;
internal ObjectOperations(DynamicOperations ops, ScriptEngine engine)
{
_ops = ops;
_engine = engine;
}
public bool IsCallable(object obj)
{
return _ops.IsCallable(obj);
}
public dynamic Invoke(object obj, params object[] parameters)
{
return _ops.Invoke(obj, parameters);
}
public dynamic InvokeMember(object obj, string memberName, params object[] parameters)
{
return _ops.InvokeMember(obj, memberName, parameters);
}
public dynamic CreateInstance(object obj, params object[] parameters)
{
return _ops.CreateInstance(obj, parameters);
}
public dynamic GetMember(object obj, string name)
{
return _ops.GetMember(obj, name);
}
public T GetMember<T>(object obj, string name)
{
return _ops.GetMember<T>(obj, name);
}
public bool TryGetMember(object obj, string name, out object value)
{
return _ops.TryGetMember(obj, name, out value);
}
public bool ContainsMember(object obj, string name)
{
return _ops.ContainsMember(obj, name);
}
public void RemoveMember(object obj, string name)
{
_ops.RemoveMember(obj, name);
}
public void SetMember(object obj, string name, object value)
{
_ops.SetMember(obj, name, value);
}
public void SetMember<T>(object obj, string name, T value)
{
_ops.SetMember(obj, name, value);
}
public dynamic GetMember(object obj, string name, bool ignoreCase)
{
return _ops.GetMember(obj, name, ignoreCase);
}
public T GetMember<T>(object obj, string name, bool ignoreCase)
{
return _ops.GetMember<T>(obj, name, ignoreCase);
}
public bool TryGetMember(object obj, string name, bool ignoreCase, out object value)
{
return _ops.TryGetMember(obj, name, ignoreCase, out value);
}
public bool ContainsMember(object obj, string name, bool ignoreCase)
{
return _ops.ContainsMember(obj, name, ignoreCase);
}
public void RemoveMember(object obj, string name, bool ignoreCase)
{
_ops.RemoveMember(obj, name, ignoreCase);
}
public void SetMember(object obj, string name, object value, bool ignoreCase)
{
_ops.SetMember(obj, name, value, ignoreCase);
}
public void SetMember<T>(object obj, string name, T value, bool ignoreCase)
{
_ops.SetMember(obj, name, value, ignoreCase);
}
public T ConvertTo<T>(object obj)
{
return _ops.ConvertTo<T>(obj);
}
public object ConvertTo(object obj, Type type)
{
ContractUtils.RequiresNotNull(type, "type");
return _ops.ConvertTo(obj, type);
}
public bool TryConvertTo<T>(object obj, out T result)
{
return _ops.TryConvertTo<T>(obj, out result);
}
public bool TryConvertTo(object obj, Type type, out object result)
{
return _ops.TryConvertTo(obj, type, out result);
}
public T ExplicitConvertTo<T>(object obj)
{
return _ops.ExplicitConvertTo<T>(obj);
}
public object ExplicitConvertTo(object obj, Type type)
{
ContractUtils.RequiresNotNull(type, "type");
return _ops.ExplicitConvertTo(obj, type);
}
public bool TryExplicitConvertTo<T>(object obj, out T result)
{
return _ops.TryExplicitConvertTo<T>(obj, out result);
}
public bool TryExplicitConvertTo(object obj, Type type, out object result)
{
return _ops.TryExplicitConvertTo(obj, type, out result);
}
public T ImplicitConvertTo<T>(object obj)
{
return _ops.ImplicitConvertTo<T>(obj);
}
public object ImplicitConvertTo(object obj, Type type)
{
ContractUtils.RequiresNotNull(type, "type");
return _ops.ImplicitConvertTo(obj, type);
}
public bool TryImplicitConvertTo<T>(object obj, out T result)
{
return _ops.TryImplicitConvertTo<T>(obj, out result);
}
public bool TryImplicitConvertTo(object obj, Type type, out object result)
{
return _ops.TryImplicitConvertTo(obj, type, out result);
}
public dynamic DoOperation(ExpressionType operation, object target)
{
return _ops.DoOperation<object, object>(operation, target);
}
public TResult DoOperation<TTarget, TResult>(ExpressionType operation, TTarget target)
{
return _ops.DoOperation<TTarget, TResult>(operation, target);
}
public dynamic DoOperation(ExpressionType operation, object target, object other)
{
return _ops.DoOperation<object, object, object>(operation, target, other);
}
public TResult DoOperation<TTarget, TOther, TResult>(ExpressionType operation, TTarget target, TOther other)
{
return _ops.DoOperation<TTarget, TOther, TResult>(operation, target, other);
}
public dynamic Add(object self, object other)
{
return DoOperation(ExpressionType.Add, self, other);
}
public dynamic Subtract(object self, object other)
{
return DoOperation(ExpressionType.Subtract, self, other);
}
public dynamic Power(object self, object other)
{
return DoOperation(ExpressionType.Power, self, other);
}
public dynamic Multiply(object self, object other)
{
return DoOperation(ExpressionType.Multiply, self, other);
}
public dynamic Divide(object self, object other)
{
return DoOperation(ExpressionType.Divide, self, other);
}
public dynamic Modulo(object self, object other)
{
return DoOperation(ExpressionType.Modulo, self, other);
}
public dynamic LeftShift(object self, object other)
{
return DoOperation(ExpressionType.LeftShift, self, other);
}
public dynamic RightShift(object self, object other)
{
return DoOperation(ExpressionType.RightShift, self, other);
}
public dynamic BitwiseAnd(object self, object other)
{
return DoOperation(ExpressionType.And, self, other);
}
public dynamic BitwiseOr(object self, object other)
{
return DoOperation(ExpressionType.Or, self, other);
}
public dynamic ExclusiveOr(object self, object other)
{
return DoOperation(ExpressionType.ExclusiveOr, self, other);
}
public bool LessThan(object self, object other)
{
return ConvertTo<bool>(_ops.DoOperation<object, object, object>(ExpressionType.LessThan, self, other));
}
public bool GreaterThan(object self, object other)
{
return ConvertTo<bool>(_ops.DoOperation<object, object, object>(ExpressionType.GreaterThan, self, other));
}
public bool LessThanOrEqual(object self, object other)
{
return ConvertTo<bool>(_ops.DoOperation<object, object, object>(ExpressionType.LessThanOrEqual, self, other));
}
public bool GreaterThanOrEqual(object self, object other)
{
return ConvertTo<bool>(_ops.DoOperation<object, object, object>(ExpressionType.GreaterThanOrEqual, self, other));
}
public bool Equal(object self, object other)
{
return ConvertTo<bool>(_ops.DoOperation<object, object, object>(ExpressionType.Equal, self, other));
}
public bool NotEqual(object self, object other)
{
return ConvertTo<bool>(_ops.DoOperation<object, object, object>(ExpressionType.NotEqual, self, other));
}
[Obsolete("Use Format method instead.")]
public string GetCodeRepresentation(object obj)
{
return obj.ToString();
}
public string Format(object obj)
{
return _ops.Format(obj);
}
public IList<string> GetMemberNames(object obj)
{
return _ops.GetMemberNames(obj);
}
public string GetDocumentation(object obj)
{
return _ops.GetDocumentation(obj);
}
public IList<string> GetCallSignatures(object obj)
{
return _ops.GetCallSignatures(obj);
}
[Obsolete("Use Invoke instead")]
public object Call(object obj, params object[] parameters)
{
return _ops.Invoke(obj, parameters);
}
[Obsolete("Use the ExpressionType overload instead")]
public object DoOperation(Operators op, object target)
{
ExpressionType linqOp = GetLinqOp(op);
return _ops.DoOperation<object, object>(linqOp, target);
}
[Obsolete("Use ExpressionType overload instead")]
public TResult DoOperation<TTarget, TResult>(Operators op, TTarget target)
{
return _ops.DoOperation<TTarget, TResult>(GetLinqOp(op), target);
}
[Obsolete]
private static ExpressionType GetLinqOp(Operators op)
{
ExpressionType? expressionType = null;
return (op switch
{
Operators.Positive => ExpressionType.UnaryPlus,
Operators.Negate => ExpressionType.Negate,
Operators.OnesComplement => ExpressionType.OnesComplement,
Operators.IsFalse => ExpressionType.IsFalse,
Operators.Decrement => ExpressionType.Decrement,
Operators.Increment => ExpressionType.Increment,
_ => throw new InvalidOperationException($"Unrecognized shared operation: {op}"),
});
}
[Obsolete("Use Modulo instead")]
public object Modulus(object self, object other)
{
return Modulo(self, other);
}
[Obsolete("Use ExpressionType overload instead")]
public object DoOperation(Operators op, object target, object other)
{
return _ops.DoOperation<object, object, object>(GetLinqBinaryOp(op), target, other);
}
[Obsolete]
private static ExpressionType GetLinqBinaryOp(Operators op)
{
ExpressionType? expressionType = null;
return (op switch
{
Operators.Add => ExpressionType.Add,
Operators.BitwiseAnd => ExpressionType.And,
Operators.Divide => ExpressionType.Divide,
Operators.ExclusiveOr => ExpressionType.ExclusiveOr,
Operators.Mod => ExpressionType.Modulo,
Operators.Multiply => ExpressionType.Multiply,
Operators.BitwiseOr => ExpressionType.Or,
Operators.Power => ExpressionType.Power,
Operators.RightShift => ExpressionType.RightShift,
Operators.LeftShift => ExpressionType.LeftShift,
Operators.Subtract => ExpressionType.Subtract,
Operators.Equals => ExpressionType.Equal,
Operators.GreaterThan => ExpressionType.GreaterThan,
Operators.GreaterThanOrEqual => ExpressionType.GreaterThanOrEqual,
Operators.LessThan => ExpressionType.LessThan,
Operators.LessThanOrEqual => ExpressionType.LessThanOrEqual,
Operators.NotEquals => ExpressionType.NotEqual,
_ => throw new InvalidOperationException($"Unrecognized shared operation: {op}"),
});
}
[Obsolete("Use the ExpressionType overload instead")]
public TResult DoOperation<TTarget, TOther, TResult>(Operators op, TTarget target, TOther other)
{
return _ops.DoOperation<TTarget, TOther, TResult>(GetLinqBinaryOp(op), target, other);
}
[Obsolete("Use Invoke instead")]
public ObjectHandle Call(ObjectHandle obj, params ObjectHandle[] parameters)
{
return Invoke(obj, parameters);
}
[Obsolete("Use Invoke instead")]
public ObjectHandle Call(ObjectHandle obj, params object[] parameters)
{
return Invoke(obj, parameters);
}
[Obsolete("Use the ExpressionType overload instead")]
public object DoOperation(Operators op, ObjectHandle target)
{
return DoOperation(op, GetLocalObject(target));
}
[Obsolete("Use the ExpressionType enum instead")]
public ObjectHandle DoOperation(Operators op, ObjectHandle target, ObjectHandle other)
{
return new ObjectHandle(DoOperation(op, GetLocalObject(target), GetLocalObject(other)));
}
[Obsolete("Use Modulo instead")]
public ObjectHandle Modulus(ObjectHandle self, ObjectHandle other)
{
return Modulo(self, other);
}
public bool IsCallable([NotNull] ObjectHandle obj)
{
return IsCallable(GetLocalObject(obj));
}
public ObjectHandle Invoke([NotNull] ObjectHandle obj, params ObjectHandle[] parameters)
{
ContractUtils.RequiresNotNull(parameters, "parameters");
return new ObjectHandle((object)Invoke(GetLocalObject(obj), GetLocalObjects(parameters)));
}
public ObjectHandle Invoke([NotNull] ObjectHandle obj, params object[] parameters)
{
return new ObjectHandle((object)Invoke(GetLocalObject(obj), parameters));
}
public ObjectHandle Create([NotNull] ObjectHandle obj, [NotNull] params ObjectHandle[] parameters)
{
return new ObjectHandle((object)CreateInstance(GetLocalObject(obj), GetLocalObjects(parameters)));
}
public ObjectHandle Create([NotNull] ObjectHandle obj, params object[] parameters)
{
return new ObjectHandle((object)CreateInstance(GetLocalObject(obj), parameters));
}
public void SetMember([NotNull] ObjectHandle obj, string name, [NotNull] ObjectHandle value)
{
SetMember(GetLocalObject(obj), name, GetLocalObject(value));
}
public void SetMember<T>([NotNull] ObjectHandle obj, string name, T value)
{
SetMember(GetLocalObject(obj), name, value);
}
public ObjectHandle GetMember([NotNull] ObjectHandle obj, string name)
{
return new ObjectHandle((object)GetMember(GetLocalObject(obj), name));
}
public T GetMember<T>([NotNull] ObjectHandle obj, string name)
{
return GetMember<T>(GetLocalObject(obj), name);
}
public bool TryGetMember([NotNull] ObjectHandle obj, string name, out ObjectHandle value)
{
if (TryGetMember(GetLocalObject(obj), name, out var value2))
{
value = new ObjectHandle(value2);
return true;
}
value = null;
return false;
}
public bool ContainsMember([NotNull] ObjectHandle obj, string name)
{
return ContainsMember(GetLocalObject(obj), name);
}
public void RemoveMember([NotNull] ObjectHandle obj, string name)
{
RemoveMember(GetLocalObject(obj), name);
}
public ObjectHandle ConvertTo<T>([NotNull] ObjectHandle obj)
{
return new ObjectHandle(ConvertTo<T>(GetLocalObject(obj)));
}
public ObjectHandle ConvertTo([NotNull] ObjectHandle obj, Type type)
{
return new ObjectHandle(ConvertTo(GetLocalObject(obj), type));
}
public bool TryConvertTo<T>([NotNull] ObjectHandle obj, out ObjectHandle result)
{
if (TryConvertTo<T>(GetLocalObject(obj), out var result2))
{
result = new ObjectHandle(result2);
return true;
}
result = null;
return false;
}
public bool TryConvertTo([NotNull] ObjectHandle obj, Type type, out ObjectHandle result)
{
if (TryConvertTo(GetLocalObject(obj), type, out var result2))
{
result = new ObjectHandle(result2);
return true;
}
result = null;
return false;
}
public ObjectHandle ExplicitConvertTo<T>([NotNull] ObjectHandle obj)
{
return new ObjectHandle(_ops.ExplicitConvertTo<T>(GetLocalObject(obj)));
}
public ObjectHandle ExplicitConvertTo([NotNull] ObjectHandle obj, Type type)
{
ContractUtils.RequiresNotNull(type, "type");
return new ObjectHandle(_ops.ExplicitConvertTo(GetLocalObject(obj), type));
}
public bool TryExplicitConvertTo<T>([NotNull] ObjectHandle obj, out ObjectHandle result)
{
T result2;
bool flag = _ops.TryExplicitConvertTo<T>(GetLocalObject(obj), out result2);
if (flag)
{
result = new ObjectHandle(obj);
}
else
{
result = null;
}
return flag;
}
public bool TryExplicitConvertTo([NotNull] ObjectHandle obj, Type type, out ObjectHandle result)
{
object result2;
bool flag = _ops.TryExplicitConvertTo(GetLocalObject(obj), type, out result2);
if (flag)
{
result = new ObjectHandle(obj);
}
else
{
result = null;
}
return flag;
}
public ObjectHandle ImplicitConvertTo<T>([NotNull] ObjectHandle obj)
{
return new ObjectHandle(_ops.ImplicitConvertTo<T>(GetLocalObject(obj)));
}
public ObjectHandle ImplicitConvertTo([NotNull] ObjectHandle obj, Type type)
{
ContractUtils.RequiresNotNull(type, "type");
return new ObjectHandle(_ops.ImplicitConvertTo(GetLocalObject(obj), type));
}
public bool TryImplicitConvertTo<T>([NotNull] ObjectHandle obj, out ObjectHandle result)
{
T result2;
bool flag = _ops.TryImplicitConvertTo<T>(GetLocalObject(obj), out result2);
if (flag)
{
result = new ObjectHandle(obj);
}
else
{
result = null;
}
return flag;
}
public bool TryImplicitConvertTo([NotNull] ObjectHandle obj, Type type, out ObjectHandle result)
{
object result2;
bool flag = _ops.TryImplicitConvertTo(GetLocalObject(obj), type, out result2);
if (flag)
{
result = new ObjectHandle(obj);
}
else
{
result = null;
}
return flag;
}
public T Unwrap<T>([NotNull] ObjectHandle obj)
{
return ConvertTo<T>(GetLocalObject(obj));
}
public ObjectHandle DoOperation(ExpressionType op, [NotNull] ObjectHandle target)
{
return new ObjectHandle((object)DoOperation(op, GetLocalObject(target)));
}
public ObjectHandle DoOperation(ExpressionType op, ObjectHandle target, ObjectHandle other)
{
return new ObjectHandle((object)DoOperation(op, GetLocalObject(target), GetLocalObject(other)));
}
public ObjectHandle Add([NotNull] ObjectHandle self, [NotNull] ObjectHandle other)
{
return new ObjectHandle((object)Add(GetLocalObject(self), GetLocalObject(other)));
}
public ObjectHandle Subtract([NotNull] ObjectHandle self, [NotNull] ObjectHandle other)
{
return new ObjectHandle((object)Subtract(GetLocalObject(self), GetLocalObject(other)));
}
public ObjectHandle Power([NotNull] ObjectHandle self, [NotNull] ObjectHandle other)
{
return new ObjectHandle((object)Power(GetLocalObject(self), GetLocalObject(other)));
}
public ObjectHandle Multiply([NotNull] ObjectHandle self, [NotNull] ObjectHandle other)
{
return new ObjectHandle((object)Multiply(GetLocalObject(self), GetLocalObject(other)));
}
public ObjectHandle Divide([NotNull] ObjectHandle self, [NotNull] ObjectHandle other)
{
return new ObjectHandle((object)Divide(GetLocalObject(self), GetLocalObject(other)));
}
public ObjectHandle Modulo([NotNull] ObjectHandle self, [NotNull] ObjectHandle other)
{
return new ObjectHandle((object)Modulo(GetLocalObject(self), GetLocalObject(other)));
}
public ObjectHandle LeftShift([NotNull] ObjectHandle self, [NotNull] ObjectHandle other)
{
return new ObjectHandle((object)LeftShift(GetLocalObject(self), GetLocalObject(other)));
}
public ObjectHandle RightShift([NotNull] ObjectHandle self, [NotNull] ObjectHandle other)
{
return new ObjectHandle((object)RightShift(GetLocalObject(self), GetLocalObject(other)));
}
public ObjectHandle BitwiseAnd([NotNull] ObjectHandle self, [NotNull] ObjectHandle other)
{
return new ObjectHandle((object)BitwiseAnd(GetLocalObject(self), GetLocalObject(other)));
}
public ObjectHandle BitwiseOr([NotNull] ObjectHandle self, [NotNull] ObjectHandle other)
{
return new ObjectHandle((object)BitwiseOr(GetLocalObject(self), GetLocalObject(other)));
}
public ObjectHandle ExclusiveOr([NotNull] ObjectHandle self, [NotNull] ObjectHandle other)
{
return new ObjectHandle((object)ExclusiveOr(GetLocalObject(self), GetLocalObject(other)));
}
public bool LessThan([NotNull] ObjectHandle self, [NotNull] ObjectHandle other)
{
return LessThan(GetLocalObject(self), GetLocalObject(other));
}
public bool GreaterThan([NotNull] ObjectHandle self, [NotNull] ObjectHandle other)
{
return GreaterThan(GetLocalObject(self), GetLocalObject(other));
}
public bool LessThanOrEqual([NotNull] ObjectHandle self, [NotNull] ObjectHandle other)
{
return LessThanOrEqual(GetLocalObject(self), GetLocalObject(other));
}
public bool GreaterThanOrEqual([NotNull] ObjectHandle self, [NotNull] ObjectHandle other)
{
return GreaterThanOrEqual(GetLocalObject(self), GetLocalObject(other));
}
public bool Equal([NotNull] ObjectHandle self, [NotNull] ObjectHandle other)
{
return Equal(GetLocalObject(self), GetLocalObject(other));
}
public bool NotEqual([NotNull] ObjectHandle self, [NotNull] ObjectHandle other)
{
return NotEqual(GetLocalObject(self), GetLocalObject(other));
}
public string Format([NotNull] ObjectHandle obj)
{
return Format(GetLocalObject(obj));
}
public IList<string> GetMemberNames([NotNull] ObjectHandle obj)
{
return GetMemberNames(GetLocalObject(obj));
}
public string GetDocumentation([NotNull] ObjectHandle obj)
{
return GetDocumentation(GetLocalObject(obj));
}
public IList<string> GetCallSignatures([NotNull] ObjectHandle obj)
{
return GetCallSignatures(GetLocalObject(obj));
}
private static object GetLocalObject([NotNull] ObjectHandle obj)
{
ContractUtils.RequiresNotNull(obj, "obj");
return obj.Unwrap();
}
private static object[] GetLocalObjects(ObjectHandle[] ohs)
{
object[] array = new object[ohs.Length];
for (int i = 0; i < array.Length; i++)
{
array[i] = GetLocalObject(ohs[i]);
}
return array;
}
[SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.Infrastructure)]
public override object InitializeLifetimeService()
{
return null;
}
}

View file

@ -0,0 +1,44 @@
using System;
using System.Collections.Generic;
using AspClassic.Scripting.Utils;
namespace AspClassic.Scripting.Hosting;
[Serializable]
public class OverloadDoc
{
private readonly string _name;
private readonly string _doc;
private readonly ICollection<ParameterDoc> _params;
private readonly ParameterDoc _returnParam;
public string Name => _name;
public string Documentation => _doc;
public ICollection<ParameterDoc> Parameters => _params;
public ParameterDoc ReturnParameter => _returnParam;
public OverloadDoc(string name, string documentation, ICollection<ParameterDoc> parameters)
{
ContractUtils.RequiresNotNull(name, "name");
ContractUtils.RequiresNotNullItems(parameters, "parameters");
_name = name;
_params = parameters;
_doc = documentation;
}
public OverloadDoc(string name, string documentation, ICollection<ParameterDoc> parameters, ParameterDoc returnParameter)
{
ContractUtils.RequiresNotNull(name, "name");
ContractUtils.RequiresNotNullItems(parameters, "parameters");
_name = name;
_params = parameters;
_doc = documentation;
_returnParam = returnParameter;
}
}

View file

@ -0,0 +1,53 @@
using System;
using AspClassic.Scripting.Utils;
namespace AspClassic.Scripting.Hosting;
[Serializable]
public class ParameterDoc
{
private readonly string _name;
private readonly string _typeName;
private readonly string _doc;
private readonly ParameterFlags _flags;
public string Name => _name;
public string TypeName => _typeName;
public ParameterFlags Flags => _flags;
public string Documentation => _doc;
public ParameterDoc(string name)
: this(name, null, null, ParameterFlags.None)
{
}
public ParameterDoc(string name, ParameterFlags paramFlags)
: this(name, null, null, paramFlags)
{
}
public ParameterDoc(string name, string typeName)
: this(name, typeName, null, ParameterFlags.None)
{
}
public ParameterDoc(string name, string typeName, string documentation)
: this(name, typeName, documentation, ParameterFlags.None)
{
}
public ParameterDoc(string name, string typeName, string documentation, ParameterFlags paramFlags)
{
ContractUtils.RequiresNotNull(name, "name");
_name = name;
_flags = paramFlags;
_typeName = typeName;
_doc = documentation;
}
}

View file

@ -0,0 +1,11 @@
using System;
namespace AspClassic.Scripting.Hosting;
[Flags]
public enum ParameterFlags
{
None = 0,
ParamsArray = 1,
ParamsDict = 2
}

View file

@ -0,0 +1,64 @@
using System;
using System.Runtime.Remoting;
using AspClassic.Scripting.Runtime;
using AspClassic.Scripting.Utils;
namespace AspClassic.Scripting.Hosting.Providers;
public static class HostingHelpers
{
public static ScriptDomainManager GetDomainManager(ScriptRuntime runtime)
{
ContractUtils.RequiresNotNull(runtime, "runtime");
return runtime.Manager;
}
public static LanguageContext GetLanguageContext(ScriptEngine engine)
{
ContractUtils.RequiresNotNull(engine, "engine");
return engine.LanguageContext;
}
public static SourceUnit GetSourceUnit(ScriptSource scriptSource)
{
ContractUtils.RequiresNotNull(scriptSource, "scriptSource");
return scriptSource.SourceUnit;
}
public static ScriptCode GetScriptCode(CompiledCode compiledCode)
{
ContractUtils.RequiresNotNull(compiledCode, "compiledCode");
return compiledCode.ScriptCode;
}
public static SharedIO GetSharedIO(ScriptIO io)
{
ContractUtils.RequiresNotNull(io, "io");
return io.SharedIO;
}
public static Scope GetScope(ScriptScope scriptScope)
{
ContractUtils.RequiresNotNull(scriptScope, "scriptScope");
return scriptScope.Scope;
}
public static ScriptScope CreateScriptScope(ScriptEngine engine, Scope scope)
{
ContractUtils.RequiresNotNull(engine, "engine");
ContractUtils.RequiresNotNull(scope, "scope");
ContractUtils.Requires(!RemotingServices.IsTransparentProxy(engine), "engine", "The engine cannot be a transparent proxy");
return new ScriptScope(engine, scope);
}
[Obsolete("You should implement a service via LanguageContext and call ScriptEngine.GetService")]
public static TRet CallEngine<T, TRet>(ScriptEngine engine, Func<LanguageContext, T, TRet> f, T arg)
{
return engine.Call(f, arg);
}
public static DocumentationOperations CreateDocumentationOperations(DocumentationProvider provider)
{
return new DocumentationOperations(provider);
}
}

View file

@ -0,0 +1,439 @@
using System;
using System.CodeDom;
using System.Collections.Generic;
using System.Diagnostics;
using System.Dynamic;
using System.Runtime.Remoting;
using System.Security.Permissions;
using System.Text;
using System.Threading;
using AspClassic.Scripting.Runtime;
using AspClassic.Scripting.Utils;
namespace AspClassic.Scripting.Hosting;
[DebuggerDisplay("{Setup.DisplayName}")]
public sealed class ScriptEngine : MarshalByRefObject
{
private readonly LanguageContext _language;
private readonly ScriptRuntime _runtime;
private LanguageSetup _config;
private ObjectOperations _operations;
public ObjectOperations Operations
{
get
{
if (_operations == null)
{
Interlocked.CompareExchange(ref _operations, CreateOperations(), null);
}
return _operations;
}
}
public LanguageSetup Setup
{
get
{
if (_config == null)
{
LanguageConfiguration languageConfig = _runtime.Manager.Configuration.GetLanguageConfig(_language);
foreach (LanguageSetup languageSetup in _runtime.Setup.LanguageSetups)
{
if (languageConfig.ProviderName == new AssemblyQualifiedTypeName(languageSetup.TypeName))
{
return _config = languageSetup;
}
}
}
return _config;
}
}
public ScriptRuntime Runtime => _runtime;
public Version LanguageVersion => _language.LanguageVersion;
internal LanguageContext LanguageContext => _language;
internal ScriptEngine(ScriptRuntime runtime, LanguageContext context)
{
_runtime = runtime;
_language = context;
}
public ObjectOperations CreateOperations()
{
return new ObjectOperations(new DynamicOperations(_language), this);
}
public ObjectOperations CreateOperations(ScriptScope scope)
{
ContractUtils.RequiresNotNull(scope, "scope");
return new ObjectOperations(_language.Operations, this);
}
public dynamic Execute(string expression)
{
return CreateScriptSourceFromString(expression).Execute();
}
public dynamic Execute(string expression, ScriptScope scope)
{
return CreateScriptSourceFromString(expression).Execute(scope);
}
public T Execute<T>(string expression)
{
return Operations.ConvertTo<T>((object)Execute(expression));
}
public T Execute<T>(string expression, ScriptScope scope)
{
return Operations.ConvertTo<T>((object)Execute(expression, scope));
}
public ScriptScope ExecuteFile(string path)
{
return ExecuteFile(path, CreateScope());
}
public ScriptScope ExecuteFile(string path, ScriptScope scope)
{
CreateScriptSourceFromFile(path).Execute(scope);
return scope;
}
public ObjectHandle ExecuteAndWrap(string expression, ScriptScope scope)
{
return new ObjectHandle((object)Execute(expression, scope));
}
public ObjectHandle ExecuteAndWrap(string expression)
{
return new ObjectHandle((object)Execute(expression));
}
public ObjectHandle ExecuteAndWrap(string expression, ScriptScope scope, out ObjectHandle exception)
{
exception = null;
try
{
return new ObjectHandle((object)Execute(expression, scope));
}
catch (Exception o)
{
exception = new ObjectHandle(o);
return null;
}
}
public ObjectHandle ExecuteAndWrap(string expression, out ObjectHandle exception)
{
exception = null;
try
{
return new ObjectHandle((object)Execute(expression));
}
catch (Exception o)
{
exception = new ObjectHandle(o);
return null;
}
}
public ScriptScope CreateScope()
{
return new ScriptScope(this, new Scope());
}
[Obsolete("IAttributesCollection is obsolete, use CreateScope(IDynamicMetaObjectProvider) instead")]
public ScriptScope CreateScope(IAttributesCollection dictionary)
{
ContractUtils.RequiresNotNull(dictionary, "dictionary");
return new ScriptScope(this, new Scope(dictionary));
}
public ScriptScope CreateScope(IDynamicMetaObjectProvider storage)
{
ContractUtils.RequiresNotNull(storage, "storage");
return new ScriptScope(this, new Scope(storage));
}
public ScriptScope GetScope(string path)
{
ContractUtils.RequiresNotNull(path, "path");
Scope scope = _language.GetScope(path);
if (scope == null)
{
return null;
}
return new ScriptScope(this, scope);
}
public ScriptSource CreateScriptSourceFromString(string expression)
{
ContractUtils.RequiresNotNull(expression, "expression");
return CreateScriptSource(new SourceStringContentProvider(expression), null, SourceCodeKind.AutoDetect);
}
public ScriptSource CreateScriptSourceFromString(string code, SourceCodeKind kind)
{
ContractUtils.RequiresNotNull(code, "code");
ContractUtils.Requires(kind.IsValid(), "kind");
return CreateScriptSource(new SourceStringContentProvider(code), null, kind);
}
public ScriptSource CreateScriptSourceFromString(string expression, string path)
{
ContractUtils.RequiresNotNull(expression, "expression");
return CreateScriptSource(new SourceStringContentProvider(expression), path, SourceCodeKind.AutoDetect);
}
public ScriptSource CreateScriptSourceFromString(string code, string path, SourceCodeKind kind)
{
ContractUtils.RequiresNotNull(code, "code");
ContractUtils.Requires(kind.IsValid(), "kind");
return CreateScriptSource(new SourceStringContentProvider(code), path, kind);
}
public ScriptSource CreateScriptSourceFromFile(string path)
{
return CreateScriptSourceFromFile(path, StringUtils.DefaultEncoding, SourceCodeKind.File);
}
public ScriptSource CreateScriptSourceFromFile(string path, Encoding encoding)
{
return CreateScriptSourceFromFile(path, encoding, SourceCodeKind.File);
}
public ScriptSource CreateScriptSourceFromFile(string path, Encoding encoding, SourceCodeKind kind)
{
ContractUtils.RequiresNotNull(path, "path");
ContractUtils.RequiresNotNull(encoding, "encoding");
ContractUtils.Requires(kind.IsValid(), "kind");
if (!_language.CanCreateSourceCode)
{
throw new NotSupportedException("Invariant engine cannot create scripts");
}
return new ScriptSource(this, _language.CreateFileUnit(path, encoding, kind));
}
public ScriptSource CreateScriptSource(CodeObject content)
{
return CreateScriptSource(content, null, SourceCodeKind.File);
}
public ScriptSource CreateScriptSource(CodeObject content, string path)
{
return CreateScriptSource(content, path, SourceCodeKind.File);
}
public ScriptSource CreateScriptSource(CodeObject content, SourceCodeKind kind)
{
return CreateScriptSource(content, null, kind);
}
public ScriptSource CreateScriptSource(CodeObject content, string path, SourceCodeKind kind)
{
ContractUtils.RequiresNotNull(content, "content");
if (!_language.CanCreateSourceCode)
{
throw new NotSupportedException("Invariant engine cannot create scripts");
}
return new ScriptSource(this, _language.GenerateSourceCode(content, path, kind));
}
public ScriptSource CreateScriptSource(StreamContentProvider content, string path)
{
ContractUtils.RequiresNotNull(content, "content");
return CreateScriptSource(content, path, StringUtils.DefaultEncoding, SourceCodeKind.File);
}
public ScriptSource CreateScriptSource(StreamContentProvider content, string path, Encoding encoding)
{
ContractUtils.RequiresNotNull(content, "content");
ContractUtils.RequiresNotNull(encoding, "encoding");
return CreateScriptSource(content, path, encoding, SourceCodeKind.File);
}
public ScriptSource CreateScriptSource(StreamContentProvider content, string path, Encoding encoding, SourceCodeKind kind)
{
ContractUtils.RequiresNotNull(content, "content");
ContractUtils.RequiresNotNull(encoding, "encoding");
ContractUtils.Requires(kind.IsValid(), "kind");
return CreateScriptSource(new LanguageBoundTextContentProvider(_language, content, encoding, path), path, kind);
}
public ScriptSource CreateScriptSource(TextContentProvider contentProvider, string path, SourceCodeKind kind)
{
ContractUtils.RequiresNotNull(contentProvider, "contentProvider");
ContractUtils.Requires(kind.IsValid(), "kind");
if (!_language.CanCreateSourceCode)
{
throw new NotSupportedException("Invariant engine cannot create scripts");
}
return new ScriptSource(this, _language.CreateSourceUnit(contentProvider, path, kind));
}
[Obsolete("Use ScriptScope.GetVariable instead")]
public dynamic GetVariable(ScriptScope scope, string name)
{
ContractUtils.RequiresNotNull(scope, "scope");
ContractUtils.RequiresNotNull(name, "name");
return scope.GetVariable(name);
}
[Obsolete("Use ScriptScope.RemoveVariable instead")]
public bool RemoveVariable(ScriptScope scope, string name)
{
ContractUtils.RequiresNotNull(scope, "scope");
ContractUtils.RequiresNotNull(name, "name");
return scope.RemoveVariable(name);
}
[Obsolete("Use ScriptScope.SetVariable instead")]
public void SetVariable(ScriptScope scope, string name, object value)
{
ContractUtils.RequiresNotNull(scope, "scope");
ContractUtils.RequiresNotNull(name, "name");
scope.SetVariable(name, value);
}
[Obsolete("Use ScriptScope.TryGetVariable instead")]
public bool TryGetVariable(ScriptScope scope, string name, out object value)
{
ContractUtils.RequiresNotNull(scope, "scope");
ContractUtils.RequiresNotNull(name, "name");
return scope.TryGetVariable(name, out value);
}
[Obsolete("Use ScriptScope.GetVariable<T> instead. If the target scope is not bound to any language or you need control over the conversion use ScriptScope.GetVariable and ScriptEngine.Operations.ConvertTo<T>")]
public T GetVariable<T>(ScriptScope scope, string name)
{
ContractUtils.RequiresNotNull(scope, "scope");
ContractUtils.RequiresNotNull(name, "name");
return Operations.ConvertTo<T>((object)GetVariable(scope, name));
}
[Obsolete("Use ScriptScope.GetVariable<T> instead. If the target scope is not bound to any language or you need control over the conversion use ScriptScope.GetVariable and ScriptEngine.Operations.ConvertTo<T>")]
public bool TryGetVariable<T>(ScriptScope scope, string name, out T value)
{
ContractUtils.RequiresNotNull(scope, "scope");
ContractUtils.RequiresNotNull(name, "name");
if (TryGetVariable(scope, name, out var value2))
{
return Operations.TryConvertTo<T>(value2, out value);
}
value = default(T);
return false;
}
[Obsolete("Use ScriptScope.ContainsVariable instead")]
public bool ContainsVariable(ScriptScope scope, string name)
{
ContractUtils.RequiresNotNull(scope, "scope");
ContractUtils.RequiresNotNull(name, "name");
object value;
return TryGetVariable(scope, name, out value);
}
[Obsolete("Use ScriptScope.GetVariableHandle instead")]
public ObjectHandle GetVariableHandle(ScriptScope scope, string name)
{
ContractUtils.RequiresNotNull(scope, "scope");
ContractUtils.RequiresNotNull(name, "name");
return new ObjectHandle((object)GetVariable(scope, name));
}
[Obsolete("Use ScriptScope.SetVariable instead")]
public void SetVariable(ScriptScope scope, string name, ObjectHandle value)
{
ContractUtils.RequiresNotNull(scope, "scope");
ContractUtils.RequiresNotNull(name, "name");
SetVariable(scope, name, value.Unwrap());
}
[Obsolete("Use ScriptScope.TryGetVariableHandle instead")]
public bool TryGetVariableHandle(ScriptScope scope, string name, out ObjectHandle value)
{
ContractUtils.RequiresNotNull(scope, "scope");
ContractUtils.RequiresNotNull(name, "name");
if (TryGetVariable(scope, name, out var value2))
{
value = new ObjectHandle(value2);
return true;
}
value = null;
return false;
}
public TService GetService<TService>(params object[] args) where TService : class
{
if (typeof(TService) == typeof(TokenCategorizer))
{
TokenizerService service = _language.GetService<TokenizerService>(ArrayUtils.Insert(_language, args));
if (service == null)
{
return null;
}
return (TService)(object)new TokenCategorizer(service);
}
if (typeof(TService) == typeof(ExceptionOperations))
{
ExceptionOperations service2 = _language.GetService<ExceptionOperations>(new object[0]);
if (service2 == null)
{
return (TService)(object)new ExceptionOperations(_language);
}
return (TService)(object)service2;
}
if (typeof(TService) == typeof(DocumentationOperations))
{
DocumentationProvider service3 = _language.GetService<DocumentationProvider>(args);
if (service3 == null)
{
return null;
}
return (TService)(object)new DocumentationOperations(service3);
}
return _language.GetService<TService>(args);
}
public CompilerOptions GetCompilerOptions()
{
return _language.GetCompilerOptions();
}
public CompilerOptions GetCompilerOptions(ScriptScope scope)
{
return _language.GetCompilerOptions(scope.Scope);
}
public void SetSearchPaths(ICollection<string> paths)
{
ContractUtils.RequiresNotNull(paths, "paths");
ContractUtils.RequiresNotNullItems(paths, "paths");
_language.SetSearchPaths(paths);
}
public ICollection<string> GetSearchPaths()
{
return _language.GetSearchPaths();
}
internal TRet Call<T, TRet>(Func<LanguageContext, T, TRet> f, T arg)
{
return f(_language, arg);
}
[SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.Infrastructure)]
public override object InitializeLifetimeService()
{
return null;
}
}

View file

@ -0,0 +1,43 @@
using System;
using System.Security.Permissions;
namespace AspClassic.Scripting.Hosting;
public class ScriptHost : MarshalByRefObject
{
private ScriptRuntime _runtime;
public ScriptRuntime Runtime
{
get
{
if (_runtime == null)
{
throw new InvalidOperationException("Host not initialized");
}
return _runtime;
}
}
public virtual PlatformAdaptationLayer PlatformAdaptationLayer => PlatformAdaptationLayer.Default;
internal void SetRuntime(ScriptRuntime runtime)
{
_runtime = runtime;
RuntimeAttached();
}
protected virtual void RuntimeAttached()
{
}
protected internal virtual void EngineCreated(ScriptEngine engine)
{
}
[SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.Infrastructure)]
public override object InitializeLifetimeService()
{
return null;
}
}

View file

@ -0,0 +1,15 @@
using AspClassic.Scripting.Runtime;
namespace AspClassic.Scripting.Hosting;
internal sealed class ScriptHostProxy : DynamicRuntimeHostingProvider
{
private readonly ScriptHost _host;
public override PlatformAdaptationLayer PlatformAdaptationLayer => _host.PlatformAdaptationLayer;
public ScriptHostProxy(ScriptHost host)
{
_host = host;
}
}

View file

@ -0,0 +1,92 @@
using System;
using System.IO;
using System.Security.Permissions;
using System.Text;
using AspClassic.Scripting.Runtime;
using AspClassic.Scripting.Utils;
namespace AspClassic.Scripting.Hosting;
public sealed class ScriptIO : MarshalByRefObject
{
private readonly SharedIO _io;
public Stream InputStream => _io.InputStream;
public Stream OutputStream => _io.OutputStream;
public Stream ErrorStream => _io.ErrorStream;
public TextReader InputReader => _io.InputReader;
public TextWriter OutputWriter => _io.OutputWriter;
public TextWriter ErrorWriter => _io.ErrorWriter;
public Encoding InputEncoding => _io.InputEncoding;
public Encoding OutputEncoding => _io.OutputEncoding;
public Encoding ErrorEncoding => _io.ErrorEncoding;
internal SharedIO SharedIO => _io;
internal ScriptIO(SharedIO io)
{
_io = io;
}
public void SetOutput(Stream stream, Encoding encoding)
{
ContractUtils.RequiresNotNull(stream, "stream");
ContractUtils.RequiresNotNull(encoding, "encoding");
_io.SetOutput(stream, new StreamWriter(stream, encoding));
}
public void SetOutput(Stream stream, TextWriter writer)
{
ContractUtils.RequiresNotNull(stream, "stream");
ContractUtils.RequiresNotNull(writer, "writer");
_io.SetOutput(stream, writer);
}
public void SetErrorOutput(Stream stream, Encoding encoding)
{
ContractUtils.RequiresNotNull(stream, "stream");
ContractUtils.RequiresNotNull(encoding, "encoding");
_io.SetErrorOutput(stream, new StreamWriter(stream, encoding));
}
public void SetErrorOutput(Stream stream, TextWriter writer)
{
ContractUtils.RequiresNotNull(stream, "stream");
ContractUtils.RequiresNotNull(writer, "writer");
_io.SetErrorOutput(stream, writer);
}
public void SetInput(Stream stream, Encoding encoding)
{
ContractUtils.RequiresNotNull(stream, "stream");
ContractUtils.RequiresNotNull(encoding, "encoding");
_io.SetInput(stream, new StreamReader(stream, encoding), encoding);
}
public void SetInput(Stream stream, TextReader reader, Encoding encoding)
{
ContractUtils.RequiresNotNull(stream, "stream");
ContractUtils.RequiresNotNull(reader, "writer");
ContractUtils.RequiresNotNull(encoding, "encoding");
_io.SetInput(stream, reader, encoding);
}
public void RedirectToConsole()
{
_io.RedirectToConsole();
}
[SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.Infrastructure)]
public override object InitializeLifetimeService()
{
return null;
}
}

View file

@ -0,0 +1,309 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Dynamic;
using System.IO;
using System.Reflection;
using System.Security.Permissions;
using System.Threading;
using AspClassic.Scripting.Runtime;
using AspClassic.Scripting.Utils;
namespace AspClassic.Scripting.Hosting;
public sealed class ScriptRuntime : MarshalByRefObject
{
private readonly Dictionary<LanguageContext, ScriptEngine> _engines;
private readonly ScriptDomainManager _manager;
private readonly InvariantContext _invariantContext;
private readonly ScriptIO _io;
private readonly ScriptHost _host;
private readonly ScriptRuntimeSetup _setup;
private readonly object _lock = new object();
private ScriptScope _globals;
private Scope _scopeGlobals;
private ScriptEngine _invariantEngine;
internal ScriptDomainManager Manager => _manager;
public ScriptHost Host => _host;
public ScriptIO IO => _io;
public ScriptRuntimeSetup Setup => _setup;
public ScriptScope Globals
{
get
{
Scope globals = _manager.Globals;
if (_scopeGlobals == globals)
{
return _globals;
}
lock (_lock)
{
if (_scopeGlobals != globals)
{
_globals = new ScriptScope(InvariantEngine, globals);
_scopeGlobals = globals;
}
return _globals;
}
}
set
{
ContractUtils.RequiresNotNull(value, "value");
lock (_lock)
{
_globals = value;
_manager.Globals = value.Scope;
}
}
}
public ObjectOperations Operations => InvariantEngine.Operations;
internal ScriptEngine InvariantEngine
{
get
{
if (_invariantEngine == null)
{
_invariantEngine = GetEngine(_invariantContext);
}
return _invariantEngine;
}
}
public ScriptRuntime(ScriptRuntimeSetup setup)
{
ContractUtils.RequiresNotNull(setup, "setup");
DlrConfiguration configuration = setup.ToConfiguration();
_setup = setup;
try
{
_host = (ScriptHost)Activator.CreateInstance(setup.HostType, Utils.CollectionExtensions.ToArray(setup.HostArguments));
}
catch (TargetInvocationException ex)
{
throw new InvalidImplementationException(Strings.InvalidCtorImplementation(setup.HostType, ex.InnerException.Message), ex.InnerException);
}
catch (Exception ex2)
{
throw new InvalidImplementationException(Strings.InvalidCtorImplementation(setup.HostType, ex2.Message), ex2);
}
ScriptHostProxy hostingProvider = new ScriptHostProxy(_host);
_manager = new ScriptDomainManager(hostingProvider, configuration);
_invariantContext = new InvariantContext(_manager);
_io = new ScriptIO(_manager.SharedIO);
_engines = new Dictionary<LanguageContext, ScriptEngine>();
_globals = new ScriptScope(GetEngineNoLockNoNotification(_invariantContext, out var _), _manager.Globals);
_host.SetRuntime(this);
if (!setup.Options.TryGetValue("NoDefaultReferences", out var value) || !Convert.ToBoolean(value))
{
LoadAssembly(typeof(string).Assembly);
LoadAssembly(typeof(Debug).Assembly);
}
}
public static ScriptRuntime CreateFromConfiguration()
{
return new ScriptRuntime(ScriptRuntimeSetup.ReadConfiguration());
}
public static ScriptRuntime CreateRemote(AppDomain domain, ScriptRuntimeSetup setup)
{
ContractUtils.RequiresNotNull(domain, "domain");
return (ScriptRuntime)domain.CreateInstanceAndUnwrap(typeof(ScriptRuntime).Assembly.FullName, typeof(ScriptRuntime).FullName, ignoreCase: false, BindingFlags.Default, null, new object[1] { setup }, null, null);
}
[SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.Infrastructure)]
public override object InitializeLifetimeService()
{
return null;
}
public ScriptEngine GetEngine(string languageName)
{
ContractUtils.RequiresNotNull(languageName, "languageName");
if (!TryGetEngine(languageName, out var engine))
{
throw new ArgumentException($"Unknown language name: '{languageName}'");
}
return engine;
}
public ScriptEngine GetEngineByTypeName(string assemblyQualifiedTypeName)
{
ContractUtils.RequiresNotNull(assemblyQualifiedTypeName, "assemblyQualifiedTypeName");
return GetEngine(_manager.GetLanguageByTypeName(assemblyQualifiedTypeName));
}
public ScriptEngine GetEngineByFileExtension(string fileExtension)
{
ContractUtils.RequiresNotNull(fileExtension, "fileExtension");
if (!TryGetEngineByFileExtension(fileExtension, out var engine))
{
throw new ArgumentException($"Unknown file extension: '{fileExtension}'");
}
return engine;
}
public bool TryGetEngine(string languageName, out ScriptEngine engine)
{
if (!_manager.TryGetLanguage(languageName, out var language))
{
engine = null;
return false;
}
engine = GetEngine(language);
return true;
}
public bool TryGetEngineByFileExtension(string fileExtension, out ScriptEngine engine)
{
if (!_manager.TryGetLanguageByFileExtension(fileExtension, out var language))
{
engine = null;
return false;
}
engine = GetEngine(language);
return true;
}
internal ScriptEngine GetEngine(LanguageContext language)
{
ScriptEngine engineNoLockNoNotification;
bool freshEngineCreated;
lock (_engines)
{
engineNoLockNoNotification = GetEngineNoLockNoNotification(language, out freshEngineCreated);
}
if (freshEngineCreated && !object.ReferenceEquals(language, _invariantContext))
{
_host.EngineCreated(engineNoLockNoNotification);
}
return engineNoLockNoNotification;
}
private ScriptEngine GetEngineNoLockNoNotification(LanguageContext language, out bool freshEngineCreated)
{
if (freshEngineCreated = !_engines.TryGetValue(language, out var value))
{
value = new ScriptEngine(this, language);
Thread.MemoryBarrier();
_engines.Add(language, value);
}
return value;
}
public ScriptScope CreateScope()
{
return InvariantEngine.CreateScope();
}
public ScriptScope CreateScope(string languageId)
{
return GetEngine(languageId).CreateScope();
}
public ScriptScope CreateScope(IDynamicMetaObjectProvider storage)
{
return InvariantEngine.CreateScope(storage);
}
public ScriptScope CreateScope(string languageId, IDynamicMetaObjectProvider storage)
{
return GetEngine(languageId).CreateScope(storage);
}
[Obsolete("IAttributesCollection is obsolete, use CreateScope(IDynamicMetaObjectProvider) instead")]
public ScriptScope CreateScope(IAttributesCollection dictionary)
{
return InvariantEngine.CreateScope(dictionary);
}
[Obsolete("IAttributesCollection is obsolete, use CreateScope(string, IDynamicMetaObjectProvider) instead")]
public ScriptScope CreateScope(string languageId, IAttributesCollection storage)
{
return GetEngine(languageId).CreateScope(storage);
}
public ScriptScope ExecuteFile(string path)
{
ContractUtils.RequiresNotEmpty(path, "path");
string extension = Path.GetExtension(path);
if (!TryGetEngineByFileExtension(extension, out var engine))
{
throw new ArgumentException($"File extension '{extension}' is not associated with any language.");
}
return engine.ExecuteFile(path);
}
public ScriptScope UseFile(string path)
{
ContractUtils.RequiresNotEmpty(path, "path");
string extension = Path.GetExtension(path);
if (!TryGetEngineByFileExtension(extension, out var engine))
{
throw new ArgumentException($"File extension '{extension}' is not associated with any language.");
}
ICollection<string> searchPaths = engine.GetSearchPaths();
if (searchPaths.Count == 0)
{
throw new InvalidOperationException($"No search paths defined for language '{engine.Setup.DisplayName}'");
}
foreach (string item in searchPaths)
{
string path2 = Path.Combine(item, path);
ScriptScope scope = engine.GetScope(path2);
if (scope != null)
{
return scope;
}
}
foreach (string item2 in searchPaths)
{
string path3 = Path.Combine(item2, path);
if (_manager.Platform.FileExists(path3))
{
return ExecuteFile(path3);
}
}
string arg = Utils.CollectionExtensions.Aggregate(searchPaths ,(string x, string y) => x + ", " + y);
throw new FileNotFoundException($"File '{path}' not found in language's search path: {arg}");
}
public void LoadAssembly(Assembly assembly)
{
_manager.LoadAssembly(assembly);
}
public ObjectOperations CreateOperations()
{
return InvariantEngine.CreateOperations();
}
public void Shutdown()
{
List<LanguageContext> list;
lock (_engines)
{
list = new List<LanguageContext>(_engines.Keys);
}
foreach (LanguageContext item in list)
{
item.Shutdown();
}
}
}

View file

@ -0,0 +1,151 @@
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using AspClassic.Scripting.Hosting.Configuration;
using AspClassic.Scripting.Runtime;
using AspClassic.Scripting.Utils;
namespace AspClassic.Scripting.Hosting;
[Serializable]
public sealed class ScriptRuntimeSetup
{
private Type _hostType;
private IList<object> _hostArguments;
private IList<LanguageSetup> _languageSetups;
private bool _debugMode;
private bool _privateBinding;
private IDictionary<string, object> _options;
private bool _frozen;
public IList<LanguageSetup> LanguageSetups => _languageSetups;
public bool DebugMode
{
get
{
return _debugMode;
}
set
{
CheckFrozen();
_debugMode = value;
}
}
public bool PrivateBinding
{
get
{
return _privateBinding;
}
set
{
CheckFrozen();
_privateBinding = value;
}
}
public Type HostType
{
get
{
return _hostType;
}
set
{
ContractUtils.RequiresNotNull(value, "value");
ContractUtils.Requires(typeof(ScriptHost).IsAssignableFrom(value), "value", "Must be ScriptHost or a derived type of ScriptHost");
CheckFrozen();
_hostType = value;
}
}
public IDictionary<string, object> Options => _options;
public IList<object> HostArguments
{
get
{
return _hostArguments;
}
set
{
ContractUtils.RequiresNotNull(value, "value");
CheckFrozen();
_hostArguments = value;
}
}
public ScriptRuntimeSetup()
{
_languageSetups = new List<LanguageSetup>();
_options = new Dictionary<string, object>();
_hostType = typeof(ScriptHost);
_hostArguments = ArrayUtils.EmptyObjects;
}
internal DlrConfiguration ToConfiguration()
{
ContractUtils.Requires(_languageSetups.Count > 0, "ScriptRuntimeSetup must have at least one LanguageSetup");
ReadOnlyCollection<LanguageSetup> readOnlyCollection = new ReadOnlyCollection<LanguageSetup>(ArrayUtils.MakeArray(_languageSetups));
ReadOnlyCollection<object> hostArguments = new ReadOnlyCollection<object>(ArrayUtils.MakeArray(_hostArguments));
AspClassic.Scripting.Utils.ReadOnlyDictionary<string, object> options = new AspClassic.Scripting.Utils.ReadOnlyDictionary<string, object>(new Dictionary<string, object>(_options));
DlrConfiguration dlrConfiguration = new DlrConfiguration(_debugMode, _privateBinding, options);
foreach (LanguageSetup item in readOnlyCollection)
{
dlrConfiguration.AddLanguage(item.TypeName, item.DisplayName, item.Names, item.FileExtensions, item.Options);
}
_languageSetups = readOnlyCollection;
_options = options;
_hostArguments = hostArguments;
Freeze(readOnlyCollection);
return dlrConfiguration;
}
private void Freeze(ReadOnlyCollection<LanguageSetup> setups)
{
foreach (LanguageSetup setup in setups)
{
setup.Freeze();
}
_frozen = true;
}
private void CheckFrozen()
{
if (_frozen)
{
throw new InvalidOperationException("Cannot modify ScriptRuntimeSetup after it has been used to create a ScriptRuntime");
}
}
public static ScriptRuntimeSetup ReadConfiguration()
{
ScriptRuntimeSetup scriptRuntimeSetup = new ScriptRuntimeSetup();
Section.LoadRuntimeSetup(scriptRuntimeSetup, null);
return scriptRuntimeSetup;
}
public static ScriptRuntimeSetup ReadConfiguration(Stream configFileStream)
{
ContractUtils.RequiresNotNull(configFileStream, "configFileStream");
ScriptRuntimeSetup scriptRuntimeSetup = new ScriptRuntimeSetup();
Section.LoadRuntimeSetup(scriptRuntimeSetup, configFileStream);
return scriptRuntimeSetup;
}
public static ScriptRuntimeSetup ReadConfiguration(string configFilePath)
{
ContractUtils.RequiresNotNull(configFilePath, "configFilePath");
using FileStream configFileStream = File.OpenRead(configFilePath);
return ReadConfiguration(configFileStream);
}
}

View file

@ -0,0 +1,203 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Dynamic;
using System.Linq.Expressions;
using System.Runtime.Remoting;
using System.Security.Permissions;
using AspClassic.Scripting.Runtime;
using AspClassic.Scripting.Utils;
namespace AspClassic.Scripting.Hosting;
[DebuggerTypeProxy(typeof(DebugView))]
public sealed class ScriptScope : MarshalByRefObject, IDynamicMetaObjectProvider
{
internal sealed class DebugView
{
private readonly ScriptScope _scope;
public ScriptEngine Language => _scope._engine;
public Hashtable Variables
{
get
{
Hashtable hashtable = new Hashtable();
foreach (KeyValuePair<string, object> item in _scope.GetItems())
{
hashtable[item.Key] = item.Value;
}
return hashtable;
}
}
public DebugView(ScriptScope scope)
{
_scope = scope;
}
}
private sealed class Meta : DynamicMetaObject
{
internal Meta(Expression parameter, ScriptScope scope)
: base(parameter, BindingRestrictions.Empty, scope)
{
}
public override DynamicMetaObject BindGetMember(GetMemberBinder action)
{
ParameterExpression parameterExpression = Expression.Variable(typeof(object), "result");
DynamicMetaObject dynamicMetaObject = action.FallbackGetMember(this);
return new DynamicMetaObject(Expression.Block(new ParameterExpression[1] { parameterExpression }, Expression.Condition(Expression.Call(Expression.Convert(base.Expression, typeof(ScriptScope)), typeof(ScriptScope).GetMethod("TryGetVariable", new Type[2]
{
typeof(string),
typeof(object).MakeByRefType()
}), Expression.Constant(action.Name), parameterExpression), parameterExpression, Expression.Convert(dynamicMetaObject.Expression, typeof(object)))), BindingRestrictions.GetTypeRestriction(base.Expression, typeof(ScriptScope)).Merge(dynamicMetaObject.Restrictions));
}
public override DynamicMetaObject BindSetMember(SetMemberBinder action, DynamicMetaObject value)
{
Expression arg = Expression.Convert(value.Expression, typeof(object));
return new DynamicMetaObject(Expression.Block(Expression.Call(Expression.Convert(base.Expression, typeof(ScriptScope)), typeof(ScriptScope).GetMethod("SetVariable", new Type[2]
{
typeof(string),
typeof(object)
}), Expression.Constant(action.Name), arg), arg), base.Restrictions.Merge(value.Restrictions).Merge(BindingRestrictions.GetTypeRestriction(base.Expression, typeof(ScriptScope))));
}
public override DynamicMetaObject BindDeleteMember(DeleteMemberBinder action)
{
DynamicMetaObject dynamicMetaObject = action.FallbackDeleteMember(this);
return new DynamicMetaObject(Expression.IfThenElse(Expression.Call(Expression.Convert(base.Expression, typeof(ScriptScope)), typeof(ScriptScope).GetMethod("RemoveVariable"), Expression.Constant(action.Name)), Expression.Empty(), dynamicMetaObject.Expression), base.Restrictions.Merge(BindingRestrictions.GetTypeRestriction(base.Expression, typeof(ScriptScope))).Merge(dynamicMetaObject.Restrictions));
}
public override DynamicMetaObject BindInvokeMember(InvokeMemberBinder action, DynamicMetaObject[] args)
{
DynamicMetaObject dynamicMetaObject = action.FallbackInvokeMember(this, args);
ParameterExpression parameterExpression = Expression.Variable(typeof(object), "result");
DynamicMetaObject dynamicMetaObject2 = action.FallbackInvoke(new DynamicMetaObject(parameterExpression, BindingRestrictions.Empty), args, null);
return new DynamicMetaObject(Expression.Block(new ParameterExpression[1] { parameterExpression }, Expression.Condition(Expression.Call(Expression.Convert(base.Expression, typeof(ScriptScope)), typeof(ScriptScope).GetMethod("TryGetVariable", new Type[2]
{
typeof(string),
typeof(object).MakeByRefType()
}), Expression.Constant(action.Name), parameterExpression), Expression.Convert(dynamicMetaObject2.Expression, typeof(object)), Expression.Convert(dynamicMetaObject.Expression, typeof(object)))), BindingRestrictions.Combine(args).Merge(BindingRestrictions.GetTypeRestriction(base.Expression, typeof(ScriptScope))).Merge(dynamicMetaObject.Restrictions));
}
public override IEnumerable<string> GetDynamicMemberNames()
{
return ((ScriptScope)base.Value).GetVariableNames();
}
}
private readonly Scope _scope;
private readonly ScriptEngine _engine;
internal Scope Scope => _scope;
public ScriptEngine Engine => _engine;
public ScriptScope(ScriptEngine engine, Scope scope)
{
_scope = scope;
_engine = engine;
}
public dynamic GetVariable(string name)
{
return _engine.LanguageContext.ScopeGetVariable(Scope, name);
}
public T GetVariable<T>(string name)
{
return _engine.LanguageContext.ScopeGetVariable<T>(Scope, name);
}
public bool TryGetVariable(string name, out dynamic value)
{
return _engine.LanguageContext.ScopeTryGetVariable(Scope, name, out value);
}
public bool TryGetVariable<T>(string name, out T value)
{
if (_engine.LanguageContext.ScopeTryGetVariable(Scope, name, out var value2))
{
value = _engine.Operations.ConvertTo<T>(value2);
return true;
}
value = default(T);
return false;
}
public void SetVariable(string name, object value)
{
_engine.LanguageContext.ScopeSetVariable(Scope, name, value);
}
public ObjectHandle GetVariableHandle(string name)
{
return new ObjectHandle((object)GetVariable(name));
}
public bool TryGetVariableHandle(string name, out ObjectHandle handle)
{
if (TryGetVariable(name, out var value))
{
handle = new ObjectHandle(value);
return true;
}
handle = null;
return false;
}
public void SetVariable(string name, ObjectHandle handle)
{
ContractUtils.RequiresNotNull(handle, "handle");
SetVariable(name, handle.Unwrap());
}
public bool ContainsVariable(string name)
{
object value;
return TryGetVariable(name, out value);
}
public bool RemoveVariable(string name)
{
if (_engine.Operations.ContainsMember(_scope, name))
{
_engine.Operations.RemoveMember(_scope, name);
return true;
}
return false;
}
public IEnumerable<string> GetVariableNames()
{
return _engine.Operations.GetMemberNames((object)_scope.Storage);
}
public IEnumerable<KeyValuePair<string, object>> GetItems()
{
List<KeyValuePair<string, object>> list = new List<KeyValuePair<string, object>>();
foreach (string variableName in GetVariableNames())
{
list.Add(new KeyValuePair<string, object>(variableName, (object)_engine.Operations.GetMember((object)_scope.Storage, variableName)));
}
list.TrimExcess();
return list;
}
DynamicMetaObject IDynamicMetaObjectProvider.GetMetaObject(Expression parameter)
{
return new Meta(parameter, this);
}
[SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.Infrastructure)]
public override object InitializeLifetimeService()
{
return null;
}
}

View file

@ -0,0 +1,163 @@
using System;
using System.Diagnostics;
using System.Runtime.Remoting;
using System.Security.Permissions;
using System.Text;
using AspClassic.Scripting.Utils;
namespace AspClassic.Scripting.Hosting;
[DebuggerDisplay("{Path ?? \"<anonymous>\"}")]
public sealed class ScriptSource : MarshalByRefObject
{
private readonly ScriptEngine _engine;
private readonly SourceUnit _unit;
internal SourceUnit SourceUnit => _unit;
public string Path => _unit.Path;
public SourceCodeKind Kind => _unit.Kind;
public ScriptEngine Engine => _engine;
internal ScriptSource(ScriptEngine engine, SourceUnit sourceUnit)
{
_unit = sourceUnit;
_engine = engine;
}
public CompiledCode Compile()
{
return CompileInternal(null, null);
}
public CompiledCode Compile(ErrorListener errorListener)
{
ContractUtils.RequiresNotNull(errorListener, "errorListener");
return CompileInternal(null, errorListener);
}
public CompiledCode Compile(CompilerOptions compilerOptions)
{
ContractUtils.RequiresNotNull(compilerOptions, "compilerOptions");
return CompileInternal(compilerOptions, null);
}
public CompiledCode Compile(CompilerOptions compilerOptions, ErrorListener errorListener)
{
ContractUtils.RequiresNotNull(errorListener, "errorListener");
ContractUtils.RequiresNotNull(compilerOptions, "compilerOptions");
return CompileInternal(compilerOptions, errorListener);
}
private CompiledCode CompileInternal(CompilerOptions compilerOptions, ErrorListener errorListener)
{
ErrorSink errorSink = new ErrorListenerProxySink(this, errorListener);
ScriptCode scriptCode = ((compilerOptions != null) ? _unit.Compile(compilerOptions, errorSink) : _unit.Compile(errorSink));
if (scriptCode == null)
{
return null;
}
return new CompiledCode(_engine, scriptCode);
}
public dynamic Execute(ScriptScope scope)
{
ContractUtils.RequiresNotNull(scope, "scope");
return _unit.Execute(scope.Scope);
}
public dynamic Execute()
{
return _unit.Execute();
}
public T Execute<T>(ScriptScope scope)
{
return _engine.Operations.ConvertTo<T>((object)Execute(scope));
}
public T Execute<T>()
{
return _engine.Operations.ConvertTo<T>((object)Execute());
}
public ObjectHandle ExecuteAndWrap(ScriptScope scope)
{
return new ObjectHandle((object)Execute(scope));
}
public ObjectHandle ExecuteAndWrap()
{
return new ObjectHandle((object)Execute());
}
public int ExecuteProgram()
{
return _unit.LanguageContext.ExecuteProgram(_unit);
}
public ScriptCodeParseResult GetCodeProperties()
{
return _unit.GetCodeProperties();
}
public ScriptCodeParseResult GetCodeProperties(CompilerOptions options)
{
return _unit.GetCodeProperties(options);
}
public SourceCodeReader GetReader()
{
return _unit.GetReader();
}
public Encoding DetectEncoding()
{
using SourceCodeReader sourceCodeReader = _unit.GetReader();
return sourceCodeReader.Encoding;
}
public string[] GetCodeLines(int start, int count)
{
return _unit.GetCodeLines(start, count);
}
public string GetCodeLine(int line)
{
return _unit.GetCodeLine(line);
}
public string GetCode()
{
return _unit.GetCode();
}
public int MapLine(int line)
{
return _unit.MapLine(line);
}
public SourceSpan MapLine(SourceSpan span)
{
return new SourceSpan(_unit.MakeLocation(span.Start), _unit.MakeLocation(span.End));
}
public SourceLocation MapLine(SourceLocation location)
{
return _unit.MakeLocation(location);
}
public string MapLinetoFile(int line)
{
return _unit.Path;
}
[SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.Infrastructure)]
public override object InitializeLifetimeService()
{
return null;
}
}

View file

@ -0,0 +1,65 @@
using System;
using System.Collections.Generic;
using System.Security.Permissions;
using AspClassic.Scripting.Runtime;
namespace AspClassic.Scripting.Hosting;
public sealed class TokenCategorizer : MarshalByRefObject
{
private readonly TokenizerService _tokenizer;
public object CurrentState => _tokenizer.CurrentState;
public SourceLocation CurrentPosition => _tokenizer.CurrentPosition;
public bool IsRestartable => _tokenizer.IsRestartable;
public ErrorSink ErrorSink
{
get
{
return _tokenizer.ErrorSink;
}
set
{
_tokenizer.ErrorSink = value;
}
}
internal TokenCategorizer(TokenizerService tokenizer)
{
_tokenizer = tokenizer;
}
public void Initialize(object state, ScriptSource scriptSource, SourceLocation initialLocation)
{
_tokenizer.Initialize(state, scriptSource.SourceUnit.GetReader(), scriptSource.SourceUnit, initialLocation);
}
public TokenInfo ReadToken()
{
return _tokenizer.ReadToken();
}
public bool SkipToken()
{
return _tokenizer.SkipToken();
}
public IEnumerable<TokenInfo> ReadTokens(int characterCount)
{
return _tokenizer.ReadTokens(characterCount);
}
public bool SkipTokens(int characterCount)
{
return _tokenizer.SkipTokens(characterCount);
}
[SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.Infrastructure)]
public override object InitializeLifetimeService()
{
return null;
}
}