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.3KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  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.Conditional:
  26. let condition = this.compileNode(node.condition)
  27. if (condition) {
  28. return this.compileNode(node.ifCase)
  29. } else {
  30. return this.compileNode(node.elseCase)
  31. }
  32. case AST.Application:
  33. if (node.function.constructor === AST.Identifier) {
  34. let f = this.env.get(node.function.name)
  35. return f(...node.args.map(arg => this.compileNode(arg)))
  36. } else if (node.function.constructor === AST.Lambda) {
  37. let env = new Env(this.env)
  38. node.function.parameters.forEach((param, index) => {
  39. env.set(param.name, node.args[index])
  40. })
  41. let compiler = new Compiler(env)
  42. return compiler.compileNode(node.function.body)
  43. }
  44. return ''
  45. }
  46. }
  47. }