formatters.js 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. exports.statements = exports.statement = exports.smart = exports.program = exports.expression = void 0;
  6. var _t = require("@babel/types");
  7. const {
  8. assertExpressionStatement
  9. } = _t;
  10. function makeStatementFormatter(fn) {
  11. return {
  12. code: str => `/* @babel/template */;\n${str}`,
  13. validate: () => {},
  14. unwrap: ast => {
  15. return fn(ast.program.body.slice(1));
  16. }
  17. };
  18. }
  19. const smart = makeStatementFormatter(body => {
  20. if (body.length > 1) {
  21. return body;
  22. } else {
  23. return body[0];
  24. }
  25. });
  26. exports.smart = smart;
  27. const statements = makeStatementFormatter(body => body);
  28. exports.statements = statements;
  29. const statement = makeStatementFormatter(body => {
  30. if (body.length === 0) {
  31. throw new Error("Found nothing to return.");
  32. }
  33. if (body.length > 1) {
  34. throw new Error("Found multiple statements but wanted one");
  35. }
  36. return body[0];
  37. });
  38. exports.statement = statement;
  39. const expression = {
  40. code: str => `(\n${str}\n)`,
  41. validate: ast => {
  42. if (ast.program.body.length > 1) {
  43. throw new Error("Found multiple statements but wanted one");
  44. }
  45. if (expression.unwrap(ast).start === 0) {
  46. throw new Error("Parse result included parens.");
  47. }
  48. },
  49. unwrap: ({
  50. program
  51. }) => {
  52. const [stmt] = program.body;
  53. assertExpressionStatement(stmt);
  54. return stmt.expression;
  55. }
  56. };
  57. exports.expression = expression;
  58. const program = {
  59. code: str => str,
  60. validate: () => {},
  61. unwrap: ast => ast.program
  62. };
  63. exports.program = program;