123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253 |
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using NTERA.Core;
- using NTERA.EmuEra.Game.EraEmu.Content;
- using NTERA.Engine.Compiler;
- namespace NTERA.Engine.Runtime
- {
- public class EraRuntime : IScriptEngine
- {
- public IExecutionProvider ExecutionProvider { get; }
- public IConsole Console { get; protected set; }
- public Stack<StackFrame> ExecutionStack { get; } = new Stack<StackFrame>();
- protected List<FunctionDefinition> TotalProcedureDefinitions = new List<FunctionDefinition>(BaseDefinitions.DefaultGlobalFunctions);
- public EraRuntime(IExecutionProvider executionProvider)
- {
- ExecutionProvider = executionProvider;
- TotalProcedureDefinitions.AddRange(ExecutionProvider.DefinedProcedures);
- TotalProcedureDefinitions.AddRange(BaseDefinitions.DefaultGlobalFunctions);
- }
- public bool Initialize(IConsole console)
- {
- Console = console;
- return true;
- }
- public void Start()
- {
- Console.PrintSystemLine("EraJIT x64 0.0.0.0");
- Console.PrintSystemLine("");
- try
- {
- Call(ExecutionProvider.DefinedProcedures.First(x => x.Name == "SYSTEM_TITLE"));
- }
- catch (Exception ex)
- {
- Console.PrintSystemLine($"Unhandled exception: {ex.Message}");
- Console.PrintSystemLine("Stack trace:");
- foreach (var stackMember in ExecutionStack)
- Console.PrintSystemLine($" - @{stackMember.SelfDefinition.Name} ({stackMember.SelfDefinition.Position} > {stackMember.SelfDefinition.Filename})");
- throw;
- }
- System.Threading.Thread.Sleep(-1);
- }
- public ExecutionResult Call(FunctionDefinition function, IList<Value> parameters = null)
- {
- var localVariables = new VariableDictionary();
- foreach (var variable in function.Variables)
- localVariables[variable.Name] = variable.CalculatedValue;
- var globalVariables = new VariableDictionary();
- foreach (var variable in BaseDefinitions.DefaultGlobalVariables)
- globalVariables[variable.Name] = variable.CalculatedValue;
- var context = new StackFrame
- {
- SelfDefinition = function,
- GlobalVariables = globalVariables,
- LocalVariables = localVariables
- };
- ExecutionResult result;
- ExecutionStack.Push(context);
- if (function.Filename == "__GLOBAL")
- {
- var resultValue = Base.Functions.StaticFunctions[function.Name].Invoke(this, context, parameters);
- result = new ExecutionResult(ExecutionResultType.FunctionReturn, resultValue);
- }
- else
- {
- if (parameters != null)
- for (var index = 0; index < parameters.Count; index++)
- {
- FunctionParameter parameter;
- if (index < function.Parameters.Length)
- parameter = function.Parameters[index];
- else if (index >= function.Parameters.Length && function.Parameters.Last().IsArrayParameter)
- parameter = function.Parameters.Last();
- else
- throw new Exception($"Unable to assign parameter #{index + 1}");
- if (localVariables.ContainsKey(parameter.Name))
- localVariables[parameter.Name] = parameters[index];
- else if (globalVariables.ContainsKey(parameter.Name))
- globalVariables[parameter.Name] = parameters[index];
- else
- throw new Exception($"Unable to assign parameter '{parameter.Name}' to a variable");
- }
- var executionContents = ExecutionProvider.GetExecutionNodes(function);
- result = ExecuteSet(context, executionContents.ToList());
- }
- ExecutionStack.Pop();
- return result;
- }
- public ExecutionResult ExecuteSet(StackFrame context, IList<ExecutionNode> nodes)
- {
- for (int index = 0; index < nodes.Count; index++)
- {
- ExecutionNode node = nodes[index];
- if (node.Type == "result")
- {
- return new ExecutionResult(ExecutionResultType.FunctionReturn, ComputeExpression(context, node.SubNodes.Single()));
- }
-
- ExecuteNode(context, node);
- }
- return ExecutionResult.None;
- }
- public void ExecuteNode(StackFrame context, ExecutionNode node)
- {
- switch (node.Type)
- {
- case "statement":
- string statement = node.Metadata["name"];
- if (!Base.Keywords.StaticKeywords.TryGetValue(statement, out var keywordAction))
- throw new Exception($"Unknown statement: '{statement}'");
- keywordAction(this, context, node);
- return;
- case "assignment":
- string variableName = node["variable"].Metadata["name"];
- if (context.LocalVariables.ContainsKey(variableName))
- context.LocalVariables[variableName] = ComputeExpression(context, node["value"].SubNodes.Single());
- else if (context.GlobalVariables.ContainsKey(variableName))
- context.GlobalVariables[variableName] = ComputeExpression(context, node["value"].SubNodes.Single());
- else
- throw new Exception($"Unknown variable: '{variableName}'");
- return;
- default:
- throw new Exception($"Unknown node type: '{node.Type}'");
- }
- }
- public Value ComputeExpression(StackFrame context, ExecutionNode expressionNode)
- {
- switch (expressionNode.Type)
- {
- case "constant":
- ValueType type = (ValueType)Enum.Parse(typeof(ValueType), expressionNode.Metadata["type"]);
- string strValue = expressionNode.Metadata["value"];
- return type == ValueType.String ? (Value)strValue : (Value)double.Parse(strValue);
- case "variable":
- string variableName = expressionNode.Metadata["name"];
- if (context.LocalVariables.ContainsKey(variableName))
- return context.LocalVariables[variableName];
- else if (context.GlobalVariables.ContainsKey(variableName))
- return context.GlobalVariables[variableName];
- else
- throw new Exception($"Unable to retrieve variable '{variableName}'");
- case "call":
- string functionName = expressionNode.Metadata["target"];
- var function = TotalProcedureDefinitions.FirstOrDefault(func => func.IsReturnFunction && func.Name.Equals(functionName, StringComparison.OrdinalIgnoreCase));
- if (function == null)
- throw new Exception($"Unknown function: '{functionName}'");
- var executionResult = Call(function, expressionNode["parameters"].SubNodes.Select(x => ComputeExpression(context, x)).ToArray());
- if (executionResult.Type != ExecutionResultType.FunctionReturn || !executionResult.Result.HasValue)
- throw new Exception($"Unexpected result from function '{functionName}': {executionResult.Type}");
- return executionResult.Result.Value;
- case "operation":
- bool isUnary = expressionNode.Metadata.ContainsKey("unary") && bool.Parse(expressionNode.Metadata["unary"]);
- string operationType = expressionNode.Metadata["type"];
- Token operatorToken;
- switch (operationType)
- {
- case "add": operatorToken = Token.Plus; break;
- case "subtract": operatorToken = Token.Minus; break;
- default: throw new Exception($"Unknown operation type: '{operationType}'");
- }
- if (isUnary)
- {
- Value innerValue = ComputeExpression(context, expressionNode.SubNodes.Single());
- switch (operatorToken)
- {
- case Token.Plus: return innerValue;
- case Token.Minus: return innerValue * -1;
- default: throw new Exception($"Unsupported unary operation type: '{operationType}'");
- }
- }
-
- var left = ComputeExpression(context, expressionNode.SubNodes[0]);
- var right = ComputeExpression(context, expressionNode.SubNodes[1]);
- return left.Operate(right, operatorToken);
- default:
- throw new Exception($"Unknown expression type: '{expressionNode.Type}'");
- }
- }
- public void InputString(string input)
- {
- throw new NotImplementedException();
- }
- public void InputInteger(long input)
- {
- throw new NotImplementedException();
- }
- public void InputSystemInteger(long input)
- {
- throw new NotImplementedException();
- }
- public CroppedImage GetImage(string name)
- {
- throw new NotImplementedException();
- }
- }
- }
|