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 ExecutionStack { get; } = new Stack(); protected List TotalProcedureDefinitions = new List(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 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 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(); } } }