Jsm.ExecutableSegment.cs 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. using OpenVIII.Fields.Scripts.Instructions;
  2. using System;
  3. using System.Collections.Generic;
  4. namespace OpenVIII.Fields.Scripts
  5. {
  6. public static partial class Jsm
  7. {
  8. public class ExecutableSegment : Segment, IJsmInstruction
  9. {
  10. public ExecutableSegment(Int32 from, Int32 to)
  11. : base(from, to)
  12. {
  13. }
  14. public virtual IScriptExecuter GetExecuter()
  15. {
  16. return GetExecuter(_list);
  17. }
  18. internal static IScriptExecuter GetExecuter(IEnumerable<IJsmInstruction> instructions)
  19. {
  20. return new Executer(instructions);
  21. }
  22. private sealed class Executer : IScriptExecuter
  23. {
  24. private readonly IEnumerable<IJsmInstruction> _list;
  25. public Executer(IEnumerable<IJsmInstruction> list)
  26. {
  27. _list = list;
  28. }
  29. public IEnumerable<IAwaitable> Execute(IServices services)
  30. {
  31. foreach (IJsmInstruction instr in _list)
  32. {
  33. if (instr is JsmInstruction singleInstruction)
  34. {
  35. yield return singleInstruction.Execute(services);
  36. }
  37. else if (instr is ExecutableSegment segment)
  38. {
  39. // TODO: Change recursion to the loop
  40. IScriptExecuter nested = segment.GetExecuter();
  41. foreach (IAwaitable result in nested.Execute(services))
  42. yield return result;
  43. }
  44. else
  45. {
  46. throw new NotSupportedException($"Cannot execute instruction [{instr}] of type [{instr.GetType()}].");
  47. }
  48. }
  49. }
  50. }
  51. }
  52. }
  53. }