char-plus-to-star-transform.js 743 Bytes
Newer Older
liang ce committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
/**
 * The MIT License (MIT)
 * Copyright (c) 2017-present Dmitry Soshnikov <dmitry.soshnikov@gmail.com>
 */

'use strict';

/**
 * A regexp-tree plugin to replace `a+` to `aa*`, since NFA/DFA
 * handles Kleene-closure `a*`, and `a+` is just a syntactic sugar.
 */

module.exports = {
  Repetition: function Repetition(path) {
    var node = path.node,
        parent = path.parent;


    if (node.quantifier.kind !== '+') {
      return;
    }

    if (parent.type === 'Alternative') {
      path.getParent().insertChildAt(node.expression, path.index);
    } else {
      path.replace({
        type: 'Alternative',
        expressions: [node.expression, node]
      });
    }

    // Change quantifier.
    node.quantifier.kind = '*';
  }
};