rust_ast.js 2.2 KB

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