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

stdlib.js 2.0KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  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. log: function (ref) {
  13. console.log(ref.value)
  14. },
  15. ref: function (refname) {
  16. return {
  17. name: refname,
  18. value: global_obj[refname]
  19. }
  20. },
  21. def: function (prop, body) {
  22. let methods = Object.keys(function_defs)
  23. if (methods.includes(prop.name)) {
  24. console.warn("Warning! Redefining function, did you mean to do this?")
  25. }
  26. function_defs[prop.name] = body;
  27. },
  28. repeat: function (amount, body) {
  29. for (let i = 0 ; i < amount.value; i++) {
  30. body.bind(_)()
  31. }
  32. },
  33. eQ: function (arg1, arg2) {
  34. return {
  35. value: arg1.value === arg2.value
  36. }
  37. },
  38. eq: function (arg1, arg2) {
  39. return {
  40. value: arg1.value == arg2.value
  41. }
  42. },
  43. if: function (pred, body_true, body_false) {
  44. if (pred.value) {
  45. body_true.bind(_)()
  46. } else {
  47. if (body_false) {
  48. body_false.bind(_)()
  49. }
  50. }
  51. },
  52. and: function (pred1, pred2) {
  53. return pred1 && pred2
  54. },
  55. or: function (pred1, pred2) {
  56. return pred1 || pred2
  57. },
  58. neg: function (pred) {
  59. return !pred
  60. },
  61. }
  62. const my_handler = {
  63. get: function (target, prop) {
  64. let methods = Object.keys(builtins)
  65. if (methods.includes(prop)) {
  66. return builtins[prop]
  67. } else {
  68. methods = Object.keys(function_defs)
  69. if (methods.includes(prop)) {
  70. return function_defs[prop]
  71. } else {
  72. console.error("Undefined function call! No such function: ", prop)
  73. }
  74. }
  75. },
  76. set: function (target, prop, data) {
  77. if (prop === 'w') data.map((w) => warnings.w = true)
  78. else console.error("Attempting to set unknown property on interpreter! How did you do that?")
  79. }
  80. }
  81. const proxy_obj = new Proxy({}, my_handler)
  82. let _
  83. module.exports = function (self) {
  84. _ = self
  85. return proxy_obj
  86. }