c_ast.js 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  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. for(let condition of case_.conditions)
  29. {
  30. cases.push(`case ${condition}:`);
  31. }
  32. cases.push(`{`);
  33. cases.push.apply(cases, indent(print_syntax_tree(case_.body), 4));
  34. cases.push(`}`);
  35. cases.push(`break;`);
  36. }
  37. if(statement.default_case)
  38. {
  39. cases.push(`default:`);
  40. cases.push.apply(cases, indent(print_syntax_tree(statement.default_case.body), 4));
  41. }
  42. code.push(`switch(${statement.condition})`);
  43. code.push(`{`);
  44. code.push.apply(code, indent(cases, 4));
  45. code.push(`}`);
  46. }
  47. else if(statement.type === "if-else")
  48. {
  49. console.assert(statement.if_blocks.length >= 1);
  50. let first_if_block = statement.if_blocks[0];
  51. code.push(`if(${first_if_block.condition})`);
  52. code.push(`{`);
  53. code.push.apply(code, indent(print_syntax_tree(first_if_block.body), 4));
  54. code.push(`}`);
  55. for(let i = 1; i < statement.if_blocks.length; i++)
  56. {
  57. let if_block = statement.if_blocks[i];
  58. code.push(`else if(${if_block.condition})`);
  59. code.push(`{`);
  60. code.push.apply(code, indent(print_syntax_tree(if_block.body), 4));
  61. code.push(`}`);
  62. }
  63. if(statement.else_block)
  64. {
  65. code.push(`else`);
  66. code.push(`{`);
  67. code.push.apply(code, indent(print_syntax_tree(statement.else_block.body), 4));
  68. code.push(`}`);
  69. }
  70. }
  71. else
  72. {
  73. console.assert(false, "Unexpected type: " + statement.type);
  74. }
  75. }
  76. return code;
  77. }
  78. module.exports = {
  79. print_syntax_tree,
  80. };