Jsm.Segment.cs 3.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. using OpenVIII.Fields.Scripts.Instructions;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Text;
  5. namespace OpenVIII.Fields.Scripts
  6. {
  7. public static partial class Jsm
  8. {
  9. public abstract partial class Segment : IFormattableScript
  10. {
  11. public Int32 From { get; }
  12. public Int32 To { get; }
  13. protected readonly List<IJsmInstruction> _list = new List<IJsmInstruction>();
  14. public Segment(Int32 from, Int32 to)
  15. {
  16. From = from;
  17. To = to;
  18. }
  19. public void Add(IJsmInstruction value)
  20. {
  21. _list.Add(value);
  22. }
  23. public override String ToString()
  24. {
  25. StringBuilder sb = new StringBuilder();
  26. ToString(sb);
  27. return sb.ToString();
  28. }
  29. public virtual void ToString(StringBuilder sb)
  30. {
  31. foreach (var item in _list)
  32. sb.AppendLine(item.ToString());
  33. }
  34. protected void FormatBranch(StringBuilder sb, IEnumerable<Object> items)
  35. {
  36. sb.AppendLine("{");
  37. Int32 pos = sb.Length;
  38. AppendItems(sb, items);
  39. if (sb.Length == pos)
  40. sb.AppendLine("// do nothing");
  41. sb.AppendLine("}");
  42. }
  43. protected void FormatBranch(ScriptWriter sw, IScriptFormatterContext formatterContext, IServices executionContext, IEnumerable<IJsmInstruction> items)
  44. {
  45. sw.AppendLine("{");
  46. sw.Indent++;
  47. var state = sw.RememberState();
  48. FormatItems(sw, formatterContext, executionContext, items);
  49. if (!state.IsChanged)
  50. {
  51. sw.AppendLine("// do nothing");
  52. }
  53. sw.Indent--;
  54. sw.AppendLine("}");
  55. }
  56. private static void AppendItems(StringBuilder sb, IEnumerable<Object> items)
  57. {
  58. Int32 position = -1;
  59. JMP lastItem = null;
  60. foreach (var item in items)
  61. {
  62. if (lastItem != null)
  63. throw new InvalidProgramException($"Unexpected jump: {lastItem}");
  64. lastItem = item as JMP;
  65. position = sb.Length;
  66. sb.Append('\t').AppendLine(item.ToString());
  67. }
  68. if (lastItem != null)
  69. sb.Length = position;
  70. }
  71. public virtual void Format(ScriptWriter sw, IScriptFormatterContext formatterContext, IServices services)
  72. {
  73. FormatItems(sw, formatterContext, services, _list);
  74. }
  75. private static void FormatItems(ScriptWriter sw, IScriptFormatterContext formatterContext, IServices executionContext, IEnumerable<IJsmInstruction> items)
  76. {
  77. foreach (var item in items)
  78. {
  79. if (item is IFormattableScript formattable)
  80. formattable.Format(sw, formatterContext, executionContext);
  81. else
  82. sw.AppendLine(item.ToString());
  83. }
  84. }
  85. }
  86. }
  87. }