using Newtonsoft.Json.Linq;
using Serein.Library;
using Serein.Library.Api;
using Serein.Library.Utils;
using Serein.Script.Node;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Xml.Linq;
namespace Serein.Script
{
public sealed class SereinSciptException : Exception
{
//public ASTNode Node { get; }
public override string Message { get; }
public SereinSciptException(ASTNode node, string message)
{
//this.Node = node;
Message = $"异常信息 : {message} ,代码在第{node.Row}行: {node.Code.Trim()}";
}
}
///
/// 脚本运行上下文
///
public interface IScriptInvokeContext
{
IDynamicContext FlowContext { get; }
///
/// 是否该退出了
///
bool IsReturn { get; }
///
/// 是否严格检查 Null 值 (禁止使用 Null)
///
bool IsCheckNullValue { get; }
///
/// 获取变量的值
///
///
///
object GetVarValue(string varName);
///
/// 设置变量的值
///
///
///
///
bool SetVarValue(string varName, object value);
///
/// 结束调用
///
///
bool Exit();
}
public class ScriptInvokeContext : IScriptInvokeContext
{
public ScriptInvokeContext(IDynamicContext dynamicContext)
{
FlowContext = dynamicContext;
}
public IDynamicContext FlowContext{ get; }
///
/// 定义的变量
///
private Dictionary _variables = new Dictionary();
///
/// 是否该退出了
///
public bool IsReturn { get; set; }
///
/// 是否严格检查 Null 值 (禁止使用 Null)
///
public bool IsCheckNullValue { get; set; }
object IScriptInvokeContext.GetVarValue(string varName)
{
_variables.TryGetValue(varName, out var value);
return value;
}
bool IScriptInvokeContext.SetVarValue(string varName, object? value)
{
if (!_variables.TryAdd(varName, value))
{
_variables[varName] = value;
}
return true;
}
bool IScriptInvokeContext.Exit()
{
// 清理脚本中加载的非托管资源
foreach (var nodeObj in _variables.Values)
{
if (nodeObj is not null)
{
if (typeof(IDisposable).IsAssignableFrom(nodeObj?.GetType()) && nodeObj is IDisposable disposable)
{
disposable?.Dispose();
}
}
else
{
}
}
_variables.Clear();
return true ;
}
}
public class SereinScriptInterpreter
{
///
/// 挂载的函数
///
private static Dictionary _functionTable = new Dictionary();
///
/// 挂载的函数调用的对象(用于函数需要实例才能调用的场景)
///
private Dictionary> _callFuncOfGetObjects = new Dictionary>();
///
/// 定义的类型
///
private Dictionary _classDefinition = new Dictionary();
///
/// 挂载静态函数
///
///
///
public static void AddStaticFunction(string functionName, MethodInfo methodInfo)
{
_functionTable[functionName] = new DelegateDetails(methodInfo);
}
///
/// 挂载函数
///
/// 函数名称
/// 方法信息
public void AddFunction(string functionName, MethodInfo methodInfo, Func