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

stdlib.js 2.2KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  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. __get_arg: function (arg) {
  62. if (process.argv.length > arg) {
  63. return { value: process.argv[arg] }
  64. } else {
  65. return { value: "" }
  66. }
  67. }
  68. }
  69. const my_handler = {
  70. get: function (target, prop) {
  71. let methods = Object.keys(builtins)
  72. if (methods.includes(prop)) {
  73. return builtins[prop]
  74. } else {
  75. methods = Object.keys(function_defs)
  76. if (methods.includes(prop)) {
  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 proxy_obj = new Proxy({}, my_handler)
  89. let _
  90. module.exports = function (self) {
  91. _ = self
  92. return proxy_obj
  93. }