BuiltInFunctions.cs 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Reflection;
  5. namespace NTERA.Interpreter
  6. {
  7. public partial class Interpreter
  8. {
  9. private void GenerateFunctionDictionary()
  10. {
  11. FunctionDictionary = new Dictionary<string, BasicFunction>(StringComparer.InvariantCultureIgnoreCase);
  12. foreach (var method in typeof(Interpreter).GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance))
  13. {
  14. var attribute = (BuiltInFunctionAttribute)method.GetCustomAttributes(typeof(BuiltInFunctionAttribute), true).FirstOrDefault();
  15. if (attribute == null)
  16. continue;
  17. FunctionDictionary[attribute.Name] = args => (Value)method.Invoke(this, new object[] { args });
  18. }
  19. }
  20. [BuiltInFunction("abs")]
  21. private Value Abs(List<Value> args)
  22. {
  23. if (args.Count != 1)
  24. throw new ArgumentException();
  25. return new Value(Math.Abs(args[0].Real));
  26. }
  27. [BuiltInFunction("min")]
  28. private Value Min(List<Value> args)
  29. {
  30. if (args.Count != 2)
  31. throw new ArgumentException();
  32. return new Value(Math.Min(args[0].Real, args[1].Real));
  33. }
  34. [BuiltInFunction("max")]
  35. private Value Max(List<Value> args)
  36. {
  37. if (args.Count != 2)
  38. throw new ArgumentException();
  39. return new Value(Math.Max(args[0].Real, args[1].Real));
  40. }
  41. [BuiltInFunction("not")]
  42. private Value Not(List<Value> args)
  43. {
  44. if (args.Count != 1)
  45. throw new ArgumentException();
  46. return new Value(args[0].Real == 0 ? 1 : 0);
  47. }
  48. private readonly Random random = new Random();
  49. [BuiltInFunction("rand")]
  50. private Value Rand(List<Value> args)
  51. {
  52. if (args.Count != 2)
  53. throw new ArgumentException();
  54. return new Value(random.Next((int)args[0].Real, (int)args[1].Real - 1));
  55. }
  56. [BuiltInFunction("tostr")]
  57. private Value ToStr(List<Value> args)
  58. {
  59. if (args.Count != 2)
  60. throw new ArgumentException();
  61. return ((int)args[0].Real).ToString(args[1].String);
  62. }
  63. }
  64. }