quantifier-range-to-symbol-transform.js 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. /**
  2. * The MIT License (MIT)
  3. * Copyright (c) 2017-present Dmitry Soshnikov <dmitry.soshnikov@gmail.com>
  4. */
  5. 'use strict';
  6. /**
  7. * A regexp-tree plugin to replace different range-based quantifiers
  8. * with their symbol equivalents.
  9. *
  10. * a{0,} -> a*
  11. * a{1,} -> a+
  12. * a{1} -> a
  13. *
  14. * NOTE: the following is automatically handled in the generator:
  15. *
  16. * a{3,3} -> a{3}
  17. */
  18. module.exports = {
  19. Quantifier: function Quantifier(path) {
  20. var node = path.node;
  21. if (node.kind !== 'Range') {
  22. return;
  23. }
  24. // a{0,} -> a*
  25. rewriteOpenZero(path);
  26. // a{1,} -> a+
  27. rewriteOpenOne(path);
  28. // a{1} -> a
  29. rewriteExactOne(path);
  30. }
  31. };
  32. function rewriteOpenZero(path) {
  33. var node = path.node;
  34. if (node.from !== 0 || node.to) {
  35. return;
  36. }
  37. node.kind = '*';
  38. delete node.from;
  39. }
  40. function rewriteOpenOne(path) {
  41. var node = path.node;
  42. if (node.from !== 1 || node.to) {
  43. return;
  44. }
  45. node.kind = '+';
  46. delete node.from;
  47. }
  48. function rewriteExactOne(path) {
  49. var node = path.node;
  50. if (node.from !== 1 || node.to !== 1) {
  51. return;
  52. }
  53. path.parentPath.replace(path.parentPath.node.expression);
  54. }