compat-named-capturing-groups-transform.js 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  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 translate `/(?<name>a)\k<name>/` to `/(a)\1/`.
  8. */
  9. module.exports = {
  10. // To track the names of the groups, and return them
  11. // in the transform result state.
  12. //
  13. // A map from name to number: {foo: 2, bar: 4}
  14. _groupNames: {},
  15. /**
  16. * Initialises the trasnform.
  17. */
  18. init: function init() {
  19. this._groupNames = {};
  20. },
  21. /**
  22. * Returns extra state, which eventually is returned to
  23. */
  24. getExtra: function getExtra() {
  25. return this._groupNames;
  26. },
  27. Group: function Group(path) {
  28. var node = path.node;
  29. if (!node.name) {
  30. return;
  31. }
  32. // Record group name.
  33. this._groupNames[node.name] = node.number;
  34. delete node.name;
  35. delete node.nameRaw;
  36. },
  37. Backreference: function Backreference(path) {
  38. var node = path.node;
  39. if (node.kind !== 'name') {
  40. return;
  41. }
  42. node.kind = 'number';
  43. node.reference = node.number;
  44. delete node.referenceRaw;
  45. }
  46. };