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

stdlib.js 1.6KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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. }
  39. const my_handler = {
  40. get: function (target, prop) {
  41. let methods = Object.keys(builtins)
  42. if (methods.includes(prop)) {
  43. return builtins[prop]
  44. } else {
  45. methods = Object.keys(function_defs)
  46. if (methods.includes(prop)) {
  47. return (function () { eval(function_defs[prop].replace(/\$(\d+)/g, (m, n) => JSON.stringify(arguments[(+n-1)]))) })
  48. } else {
  49. console.error("Undefined function call! No such function: ", prop)
  50. }
  51. }
  52. },
  53. set: function (target, prop, data) {
  54. if (prop === 'w') data.map((w) => warnings.w = true)
  55. else console.error("Attempting to set unknown property on interpreter! How did you do that?")
  56. }
  57. }
  58. const _ = new Proxy({}, my_handler)
  59. module.exports = _