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

stdlib.js 2.3KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  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 (let i = 0 ; i < amount.value; i++) {
  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. neg: function (pred) {
  69. return !pred
  70. },
  71. modulo: function (arg1, arg2) {
  72. return {
  73. value: (arg1.value % arg2.value)
  74. }
  75. }
  76. }
  77. const my_handler = {
  78. get: function (target, prop) {
  79. let methods = Object.keys(builtins)
  80. if (methods.includes(prop)) {
  81. return builtins[prop]
  82. } else {
  83. methods = Object.keys(function_defs)
  84. if (methods.includes(prop)) {
  85. return function_defs[prop]
  86. } else {
  87. console.error("Undefined function call! No such function: ", prop)
  88. }
  89. }
  90. },
  91. set: function (target, prop, data) {
  92. if (prop === 'w') data.map((w) => warnings.w = true)
  93. else console.error("Attempting to set unknown property on interpreter! How did you do that?")
  94. }
  95. }
  96. const proxy_obj = new Proxy({}, my_handler)
  97. let _
  98. module.exports = function (self) {
  99. _ = self
  100. return proxy_obj
  101. }