A basic compiler based off of thejameskyle's super-tiny-compiler

stdlib.js 2.4KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. const global_obj = {}
  2. const function_defs = {}
  3. const warnings = {}
  4. const builtins = {
  5. assign: function (ref, value) {
  6. if (!ref.name) {
  7. console.error('Argument 1 of assign must always be a VariableReference')
  8. process.exit(1)
  9. }
  10. global_obj[ref.name] = value.value
  11. },
  12. add: function (arg1, arg2) {
  13. return {
  14. value: (arg1.value + arg2.value)
  15. }
  16. },
  17. subtract: function (arg1, arg2) {
  18. return {
  19. value: (arg1.value - arg2.value)
  20. }
  21. },
  22. log: function (ref) {
  23. console.log(ref.value)
  24. },
  25. ref: function (refname) {
  26. return {
  27. name: refname,
  28. value: global_obj[refname]
  29. }
  30. },
  31. def: function (prop, body) {
  32. let methods = Object.keys(function_defs)
  33. if (methods.includes(prop.name)) {
  34. console.warn("Warning! Redefining function, did you mean to do this?")
  35. }
  36. function_defs[prop.name] = body;
  37. },
  38. repeat: function (amount, body) {
  39. for (ii = 0 ; ii < amount.value; ii++) {
  40. body.bind(_)()
  41. }
  42. },
  43. eQ: function (arg1, arg2) {
  44. return {
  45. value: arg1.value === arg2.value
  46. }
  47. },
  48. eq: function (arg1, arg2) {
  49. return {
  50. value: arg1.value == arg2.value
  51. }
  52. },
  53. if: function (pred, body_true, body_false) {
  54. if (pred.value) {
  55. body_true.bind(_)()
  56. } else {
  57. if (body_false) {
  58. body_false.bind(_)()
  59. }
  60. }
  61. },
  62. and: function (pred1, pred2) {
  63. return pred1 && pred2
  64. },
  65. or: function (pred1, pred2) {
  66. return pred1 || pred2
  67. },
  68. modulo: function (arg1, arg2) {
  69. return {
  70. value: (arg1.value % arg2.value)
  71. }
  72. }
  73. }
  74. const my_handler = {
  75. get: function (target, prop) {
  76. let methods = Object.keys(builtins)
  77. if (methods.includes(prop)) {
  78. return builtins[prop]
  79. } else {
  80. methods = Object.keys(function_defs)
  81. if (methods.includes(prop)) {
  82. //return (function () { eval(function_defs[prop].replace(/\$(\d+)/g, (m, n) => JSON.stringify(arguments[(+n-1)]))) })
  83. return function_defs[prop]
  84. } else {
  85. console.error("Undefined function call! No such function: ", prop)
  86. }
  87. }
  88. },
  89. set: function (target, prop, data) {
  90. if (prop === 'w') data.map((w) => warnings.w = true)
  91. else console.error("Attempting to set unknown property on interpreter! How did you do that?")
  92. }
  93. }
  94. const proxy_obj = new Proxy({}, my_handler)
  95. let _
  96. module.exports = function (self) {
  97. _ = self
  98. return proxy_obj
  99. }