rust_ast.js 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. "use strict";
  2. function repeat(s, n)
  3. {
  4. let out = "";
  5. for(let i = 0; i < n; i++) out += s;
  6. return out;
  7. }
  8. function indent(lines, how_much)
  9. {
  10. return lines.map(line => repeat(" ", how_much) + line);
  11. }
  12. function print_syntax_tree(statements)
  13. {
  14. let code = [];
  15. for(let statement of statements)
  16. {
  17. if(typeof statement === "string")
  18. {
  19. code.push(statement);
  20. }
  21. else if(statement.type === "switch")
  22. {
  23. console.assert(statement.condition);
  24. const cases = [];
  25. for(let case_ of statement.cases)
  26. {
  27. console.assert(case_.conditions.length >= 1);
  28. cases.push(case_.conditions.join(" | ") + " => {");
  29. cases.push.apply(cases, indent(print_syntax_tree(case_.body), 4));
  30. cases.push(`},`);
  31. }
  32. if(statement.default_case)
  33. {
  34. cases.push(`_ => {`);
  35. cases.push.apply(cases, indent(print_syntax_tree(statement.default_case.body), 4));
  36. cases.push(`}`);
  37. }
  38. code.push(`match ${statement.condition} {`);
  39. code.push.apply(code, indent(cases, 4));
  40. code.push(`}`);
  41. }
  42. else if(statement.type === "if-else")
  43. {
  44. console.assert(statement.if_blocks.length >= 1);
  45. let first_if_block = statement.if_blocks[0];
  46. code.push(`if ${first_if_block.condition} {`);
  47. code.push.apply(code, indent(print_syntax_tree(first_if_block.body), 4));
  48. code.push(`}`);
  49. for(let i = 1; i < statement.if_blocks.length; i++)
  50. {
  51. let if_block = statement.if_blocks[i];
  52. code.push(`else if ${if_block.condition} {`);
  53. code.push.apply(code, indent(print_syntax_tree(if_block.body), 4));
  54. code.push(`}`);
  55. }
  56. if(statement.else_block)
  57. {
  58. code.push(`else {`);
  59. code.push.apply(code, indent(print_syntax_tree(statement.else_block.body), 4));
  60. code.push(`}`);
  61. }
  62. }
  63. else
  64. {
  65. console.assert(false, "Unexpected type: " + statement.type, "In:", statement);
  66. }
  67. }
  68. return code;
  69. }
  70. module.exports = {
  71. print_syntax_tree,
  72. };