formatters.js 1.4 KB

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