ungroup-transform.js 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  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 remove unnecessary groups.
  8. *
  9. * /(?:a)/ -> /a/
  10. */
  11. function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }
  12. module.exports = {
  13. Group: function Group(path) {
  14. var node = path.node,
  15. parent = path.parent;
  16. var childPath = path.getChild();
  17. if (node.capturing || !childPath) {
  18. return;
  19. }
  20. // Don't optimize /a(?:b|c)/ to /ab|c/
  21. // but /(?:b|c)/ to /b|c/ is ok
  22. if (childPath.node.type === 'Disjunction' && parent.type !== 'RegExp') {
  23. return;
  24. }
  25. // Don't optimize /(?:ab)+/ to /ab+/
  26. // but /(?:a)+/ to /a+/ is ok
  27. // and /(?:[a-d])+/ to /[a-d]+/ is ok too
  28. if (parent.type === 'Repetition' && childPath.node.type !== 'Char' && childPath.node.type !== 'CharacterClass') {
  29. return;
  30. }
  31. if (childPath.node.type === 'Alternative') {
  32. var parentPath = path.getParent();
  33. if (parentPath.node.type === 'Alternative') {
  34. // /abc(?:def)ghi/ When (?:def) is ungrouped its content must be merged with parent alternative
  35. parentPath.replace({
  36. type: 'Alternative',
  37. expressions: [].concat(_toConsumableArray(parent.expressions.slice(0, path.index)), _toConsumableArray(childPath.node.expressions), _toConsumableArray(parent.expressions.slice(path.index + 1)))
  38. });
  39. }
  40. } else {
  41. path.replace(childPath.node);
  42. }
  43. }
  44. };