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

stdlib.js 2.2KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  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 (i = 0 ; i < amount.value; i++) {
  40. body()
  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()
  56. } else {
  57. if (body_false) {
  58. body_false()
  59. }
  60. }
  61. },
  62. modulo: function (arg1, arg2) {
  63. return {
  64. value: (arg1.value % arg2.value)
  65. }
  66. }
  67. }
  68. const my_handler = {
  69. get: function (target, prop) {
  70. let methods = Object.keys(builtins)
  71. if (methods.includes(prop)) {
  72. return builtins[prop]
  73. } else {
  74. methods = Object.keys(function_defs)
  75. if (methods.includes(prop)) {
  76. //return (function () { eval(function_defs[prop].replace(/\$(\d+)/g, (m, n) => JSON.stringify(arguments[(+n-1)]))) })
  77. return function_defs[prop]
  78. } else {
  79. console.error("Undefined function call! No such function: ", prop)
  80. }
  81. }
  82. },
  83. set: function (target, prop, data) {
  84. if (prop === 'w') data.map((w) => warnings.w = true)
  85. else console.error("Attempting to set unknown property on interpreter! How did you do that?")
  86. }
  87. }
  88. const _ = new Proxy({}, my_handler)
  89. module.exports = _