Jsm.Expression.ValueExpression.cs 3.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. using System;
  2. using System.Globalization;
  3. namespace OpenVIII.Fields.Scripts
  4. {
  5. public static partial class Jsm
  6. {
  7. public static partial class Expression
  8. {
  9. public sealed class ValueExpression : IConstExpression
  10. {
  11. public Int64 Value { get; }
  12. private readonly TypeCode _typeCode;
  13. public static ValueExpression Create(Int32 value) => new ValueExpression(value, TypeCode.Int32);
  14. public static ValueExpression Create(UInt32 value) => new ValueExpression(value, TypeCode.UInt32);
  15. public static ValueExpression Create(Int16 value) => new ValueExpression(value, TypeCode.Int16);
  16. public static ValueExpression Create(UInt16 value) => new ValueExpression(value, TypeCode.UInt16);
  17. public static ValueExpression Create(Byte value) => new ValueExpression(value, TypeCode.Byte);
  18. public static ValueExpression Create(SByte value) => new ValueExpression(value, TypeCode.SByte);
  19. private ValueExpression(Int64 value, TypeCode typeCode)
  20. {
  21. Value = value;
  22. _typeCode = typeCode;
  23. if (_typeCode < TypeCode.SByte || typeCode > TypeCode.UInt32)
  24. throw new ArgumentOutOfRangeException($"Type {typeCode} isn't supported.", nameof(typeCode));
  25. }
  26. public void Format(ScriptWriter sw, IScriptFormatterContext formatterContext, IServices services)
  27. {
  28. switch (_typeCode)
  29. {
  30. case TypeCode.SByte:
  31. sw.Append("(SByte)");
  32. break;
  33. case TypeCode.Byte:
  34. sw.Append("(Byte)");
  35. break;
  36. case TypeCode.Int16:
  37. sw.Append("(Int16)");
  38. break;
  39. case TypeCode.UInt16:
  40. sw.Append("(UInt16)");
  41. break;
  42. }
  43. sw.Append(Value.ToString(CultureInfo.InvariantCulture));
  44. if (_typeCode == TypeCode.UInt32)
  45. sw.Append("u");
  46. }
  47. public IJsmExpression Evaluate(IServices services)
  48. {
  49. return this;
  50. }
  51. public Int64 Calculate(IServices services)
  52. {
  53. return Value;
  54. }
  55. public ILogicalExpression LogicalInverse()
  56. {
  57. return new ValueExpression(Value == 0 ? 1 : 0, TypeCode.Int32);
  58. }
  59. public override String ToString()
  60. {
  61. ScriptWriter sw = new ScriptWriter(capacity: 16);
  62. Format(sw, DummyFormatterContext.Instance, StatelessServices.Instance);
  63. return sw.Release();
  64. }
  65. }
  66. }
  67. }
  68. }