rust_ast.js 2.3 KB

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