A templating language that looks like Lisp and compiles to HTML
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

compiler.js 1.1KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. const AST = require('./ast')
  2. const Env = require('./env')
  3. module.exports = class Compiler {
  4. constructor(env = null) {
  5. this.result = ''
  6. if (env) {
  7. this.env = env
  8. } else {
  9. this.env = new Env()
  10. }
  11. }
  12. compile(tree) {
  13. tree.forEach(node => {
  14. this.result += this.compileNode(node)
  15. })
  16. return this.result
  17. }
  18. compileNode(node) {
  19. switch (node.constructor) {
  20. case AST.Number:
  21. case AST.String:
  22. return node.value
  23. case AST.Identifier:
  24. return this.compileNode(this.env.get(node.name))
  25. case AST.Application:
  26. if (node.function.constructor === AST.Identifier) {
  27. let f = this.env.get(node.function.name)
  28. return f(...node.args.map(arg => this.compileNode(arg)))
  29. } else if (node.function.constructor === AST.Lambda) {
  30. let env = new Env(this.env)
  31. node.function.parameters.forEach((param, index) => {
  32. env.set(param.name, node.args[index])
  33. })
  34. let compiler = new Compiler(env)
  35. return compiler.compileNode(node.function.body)
  36. }
  37. return ''
  38. }
  39. }
  40. }