formatters.js 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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;
  64. //# sourceMappingURL=formatters.js.map