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.

44 lines
956 B

5 years ago
  1. #!/usr/bin/env node
  2. var recast = require("recast");
  3. var types = recast.types;
  4. var n = types.namedTypes;
  5. var b = types.builders;
  6. require("recast").run(function(ast, callback) {
  7. recast.visit(ast, {
  8. visitIfStatement: function(path) {
  9. var stmt = path.node;
  10. stmt.consequent = fix(stmt.consequent);
  11. var alt = stmt.alternate;
  12. if (!n.IfStatement.check(alt)) {
  13. stmt.alternate = fix(alt);
  14. }
  15. this.traverse(path);
  16. },
  17. visitWhileStatement: visitLoop,
  18. visitForStatement: visitLoop,
  19. visitForInStatement: visitLoop
  20. });
  21. callback(ast);
  22. });
  23. function visitLoop(path) {
  24. var loop = path.node;
  25. loop.body = fix(loop.body);
  26. this.traverse(path);
  27. }
  28. function fix(clause) {
  29. if (clause) {
  30. if (!n.BlockStatement.check(clause)) {
  31. clause = b.blockStatement([clause]);
  32. }
  33. }
  34. return clause;
  35. }