EraRuntime.cs 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Drawing;
  4. using System.Linq;
  5. using System.Runtime.CompilerServices;
  6. using NTERA.Core;
  7. using NTERA.EmuEra.Game.EraEmu.Content;
  8. using NTERA.Engine.Compiler;
  9. namespace NTERA.Engine.Runtime
  10. {
  11. public class EraRuntime : IScriptEngine
  12. {
  13. public IExecutionProvider ExecutionProvider { get; }
  14. public IConsole Console { get; protected set; }
  15. public Stack<StackFrame> ExecutionStack { get; } = new Stack<StackFrame>();
  16. protected List<FunctionDefinition> TotalProcedureDefinitions = new List<FunctionDefinition>(BaseDefinitions.DefaultGlobalFunctions);
  17. public EraRuntime(IExecutionProvider executionProvider)
  18. {
  19. ExecutionProvider = executionProvider;
  20. TotalProcedureDefinitions.AddRange(ExecutionProvider.DefinedProcedures);
  21. TotalProcedureDefinitions.AddRange(BaseDefinitions.DefaultGlobalFunctions);
  22. }
  23. public bool Initialize(IConsole console)
  24. {
  25. Console = console;
  26. return true;
  27. }
  28. public void Start()
  29. {
  30. Console.PrintSystemLine("EraJIT x64 0.0.0.0");
  31. Console.PrintSystemLine("");
  32. try
  33. {
  34. Call(ExecutionProvider.DefinedProcedures.First(x => x.Name == "SYSTEM_TITLE"));
  35. }
  36. catch (Exception ex)
  37. {
  38. Console.PrintSystemLine($"Unhandled exception: {ex.Message}");
  39. Console.PrintSystemLine("Stack trace:");
  40. foreach (var stackMember in ExecutionStack)
  41. Console.PrintSystemLine($" - @{stackMember.SelfDefinition.Name} ({stackMember.SelfDefinition.Position} > {stackMember.SelfDefinition.Filename})");
  42. throw;
  43. }
  44. System.Threading.Thread.Sleep(-1);
  45. }
  46. public ExecutionResult Call(FunctionDefinition function, IList<Value> parameters = null)
  47. {
  48. var localVariables = new Dictionary<string, Variable>();
  49. var globalVariables = new Dictionary<string, Variable>();
  50. foreach (var variable in function.Variables)
  51. {
  52. var localVariable = new Variable(variable.Name, variable.ValueType);
  53. localVariable[0] = variable.CalculatedValue;
  54. localVariables.Add(variable.Name, localVariable);
  55. }
  56. foreach (var variable in BaseDefinitions.DefaultGlobalVariables)
  57. {
  58. var globalVariable = new Variable(variable.Name, variable.ValueType);
  59. globalVariable[0] = variable.CalculatedValue;
  60. globalVariables.Add(variable.Name, globalVariable);
  61. }
  62. var context = new StackFrame
  63. {
  64. SelfDefinition = function,
  65. GlobalVariables = globalVariables,
  66. LocalVariables = localVariables
  67. };
  68. ExecutionResult result;
  69. ExecutionStack.Push(context);
  70. if (function.Filename == "__GLOBAL")
  71. {
  72. var resultValue = Base.Functions.StaticFunctions[function.Name].Invoke(this, context, parameters);
  73. result = new ExecutionResult(ExecutionResultType.FunctionReturn, resultValue);
  74. }
  75. else
  76. {
  77. if (parameters != null)
  78. {
  79. for (var index = 0; index < parameters.Count; index++)
  80. {
  81. FunctionParameter parameter;
  82. if (index < function.Parameters.Length)
  83. parameter = function.Parameters[index];
  84. else if (index >= function.Parameters.Length && function.Parameters.Last().IsArrayParameter)
  85. parameter = function.Parameters.Last();
  86. else
  87. throw new EraRuntimeException($"Unable to assign parameter #{index + 1}");
  88. var paramVariable = ComputeVariable(context, parameter.Name);
  89. paramVariable[parameter.Index] = parameters[index];
  90. }
  91. }
  92. var executionContents = ExecutionProvider.GetExecutionNodes(function);
  93. result = ExecuteSet(context, executionContents.ToList());
  94. }
  95. ExecutionStack.Pop();
  96. return result;
  97. }
  98. public ExecutionResult ExecuteSet(StackFrame context, IList<ExecutionNode> nodes)
  99. {
  100. for (int index = 0; index < nodes.Count; index++)
  101. {
  102. ExecutionNode node = nodes[index];
  103. if (node.Type == "statement")
  104. {
  105. if (node["name"].Equals("FOR", StringComparison.OrdinalIgnoreCase))
  106. {
  107. int endIndex = -1;
  108. int forLevel = 0;
  109. for (int subIndex = index + 1; subIndex < nodes.Count; subIndex++)
  110. {
  111. ExecutionNode subNode = nodes[subIndex];
  112. if (subNode.Type != "statement")
  113. continue;
  114. if (subNode["name"].Equals("FOR", StringComparison.OrdinalIgnoreCase))
  115. forLevel++;
  116. if (subNode["name"].Equals("NEXT", StringComparison.OrdinalIgnoreCase))
  117. {
  118. if (forLevel == 0)
  119. {
  120. endIndex = subIndex;
  121. break;
  122. }
  123. forLevel--;
  124. }
  125. }
  126. if (endIndex == -1)
  127. throw new EraRuntimeException("Could not find matching NEXT for FOR statement");
  128. //string variableName =
  129. //for (context.LocalVariables[])
  130. ExecuteSet(context, nodes.Skip(index).Take(endIndex - index).ToArray());
  131. index = endIndex;
  132. continue;
  133. }
  134. }
  135. if (node.Type == "result")
  136. {
  137. return new ExecutionResult(ExecutionResultType.FunctionReturn, ComputeExpression(context, node.Single()));
  138. }
  139. ExecuteNode(context, node);
  140. }
  141. return ExecutionResult.None;
  142. }
  143. public void ExecuteNode(StackFrame context, ExecutionNode node)
  144. {
  145. switch (node.Type)
  146. {
  147. case "statement":
  148. string statement = node["name"];
  149. if (!Base.Keywords.StaticKeywords.TryGetValue(statement, out var keywordAction))
  150. throw new EraRuntimeException($"Unknown statement: '{statement}'");
  151. keywordAction(this, context, node);
  152. return;
  153. case "assignment":
  154. Variable variable = ComputeVariable(context, node.GetSubtype("variable"), out var index);
  155. variable[index] = ComputeExpression(context, node.GetSubtype("value").Single());
  156. return;
  157. case "call":
  158. string procedureName = node["target"];
  159. var procedure = TotalProcedureDefinitions.FirstOrDefault(func => !func.IsReturnFunction && func.Name.Equals(procedureName, StringComparison.OrdinalIgnoreCase));
  160. if (procedure == null)
  161. throw new EraRuntimeException($"Unknown procedure: '{procedureName}'");
  162. var executionResult = Call(procedure, node.GetSubtype("parameters").Select(x => ComputeExpression(context, x)).ToArray());
  163. if (executionResult.Type != ExecutionResultType.None || executionResult.Result.HasValue)
  164. throw new EraRuntimeException($"Unexpected result from procedure '{procedureName}': {executionResult.Type}");
  165. return;
  166. default:
  167. throw new EraRuntimeException($"Unknown node type: '{node.Type}'");
  168. }
  169. }
  170. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  171. public Variable ComputeVariable(StackFrame context, ExecutionNode variableNode, out int[] index)
  172. {
  173. string variableName = variableNode["name"];
  174. index = new[] { 0 };
  175. if (variableNode.SubNodes.Any(x => x.Type == "index"))
  176. {
  177. ExecutionNode indexNode = variableNode.GetSubtype("index");
  178. index = indexNode.SubNodes.Select(x => (int)ComputeExpression(context, x)).ToArray();
  179. }
  180. return ComputeVariable(context, variableName);
  181. }
  182. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  183. public Variable ComputeVariable(StackFrame context, string variableName)
  184. {
  185. if (context.LocalVariables.TryGetValue(variableName, out var variable)
  186. || context.GlobalVariables.TryGetValue(variableName, out variable))
  187. return variable;
  188. throw new EraRuntimeException($"Unable to retrieve variable '{variableName}'");
  189. }
  190. public Value ComputeExpression(StackFrame context, ExecutionNode expressionNode)
  191. {
  192. switch (expressionNode.Type)
  193. {
  194. case "constant":
  195. ValueType type = (ValueType)Enum.Parse(typeof(ValueType), expressionNode["type"]);
  196. string strValue = expressionNode["value"];
  197. return type == ValueType.String ? (Value)strValue : (Value)double.Parse(strValue);
  198. case "variable":
  199. Variable variable = ComputeVariable(context, expressionNode, out var index);
  200. return variable[index];
  201. case "call":
  202. string functionName = expressionNode["target"];
  203. var function = TotalProcedureDefinitions.FirstOrDefault(func => func.IsReturnFunction && func.Name.Equals(functionName, StringComparison.OrdinalIgnoreCase));
  204. if (function == null)
  205. throw new EraRuntimeException($"Unknown function: '{functionName}'");
  206. var executionResult = Call(function, expressionNode.GetSubtype("parameters").Select(x => ComputeExpression(context, x)).ToArray());
  207. if (executionResult.Type != ExecutionResultType.FunctionReturn || !executionResult.Result.HasValue)
  208. throw new EraRuntimeException($"Unexpected result from function '{functionName}': {executionResult.Type}");
  209. return executionResult.Result.Value;
  210. case "operation":
  211. bool isUnary = expressionNode.Metadata.ContainsKey("unary") && bool.Parse(expressionNode["unary"]);
  212. string operationType = expressionNode["type"];
  213. Token operatorToken;
  214. switch (operationType)
  215. {
  216. case "add":
  217. operatorToken = Token.Plus;
  218. break;
  219. case "subtract":
  220. operatorToken = Token.Minus;
  221. break;
  222. default: throw new EraRuntimeException($"Unknown operation type: '{operationType}'");
  223. }
  224. if (isUnary)
  225. {
  226. Value innerValue = ComputeExpression(context, expressionNode.Single());
  227. switch (operatorToken)
  228. {
  229. case Token.Plus: return innerValue;
  230. case Token.Minus: return innerValue * -1;
  231. default: throw new EraRuntimeException($"Unsupported unary operation type: '{operationType}'");
  232. }
  233. }
  234. var left = ComputeExpression(context, expressionNode[0]);
  235. var right = ComputeExpression(context, expressionNode[1]);
  236. return left.Operate(right, operatorToken);
  237. default:
  238. throw new EraRuntimeException($"Unknown expression type: '{expressionNode.Type}'");
  239. }
  240. }
  241. public void InputString(string input)
  242. {
  243. throw new NotImplementedException();
  244. }
  245. public void InputInteger(long input)
  246. {
  247. throw new NotImplementedException();
  248. }
  249. public void InputSystemInteger(long input)
  250. {
  251. throw new NotImplementedException();
  252. }
  253. public CroppedImage GetImage(string name)
  254. {
  255. var bitmap = new Bitmap(@"M:\era\eraSemifullTest\resources\bbb.png");
  256. return new CroppedImage(name, bitmap, new Rectangle(Point.Empty, bitmap.Size), false);
  257. }
  258. }
  259. }