| 1 | 'use strict';
|
|---|
| 2 |
|
|---|
| 3 | const fill = require('fill-range');
|
|---|
| 4 | const utils = require('./utils');
|
|---|
| 5 |
|
|---|
| 6 | const compile = (ast, options = {}) => {
|
|---|
| 7 | const walk = (node, parent = {}) => {
|
|---|
| 8 | const invalidBlock = utils.isInvalidBrace(parent);
|
|---|
| 9 | const invalidNode = node.invalid === true && options.escapeInvalid === true;
|
|---|
| 10 | const invalid = invalidBlock === true || invalidNode === true;
|
|---|
| 11 | const prefix = options.escapeInvalid === true ? '\\' : '';
|
|---|
| 12 | let output = '';
|
|---|
| 13 |
|
|---|
| 14 | if (node.isOpen === true) {
|
|---|
| 15 | return prefix + node.value;
|
|---|
| 16 | }
|
|---|
| 17 |
|
|---|
| 18 | if (node.isClose === true) {
|
|---|
| 19 | console.log('node.isClose', prefix, node.value);
|
|---|
| 20 | return prefix + node.value;
|
|---|
| 21 | }
|
|---|
| 22 |
|
|---|
| 23 | if (node.type === 'open') {
|
|---|
| 24 | return invalid ? prefix + node.value : '(';
|
|---|
| 25 | }
|
|---|
| 26 |
|
|---|
| 27 | if (node.type === 'close') {
|
|---|
| 28 | return invalid ? prefix + node.value : ')';
|
|---|
| 29 | }
|
|---|
| 30 |
|
|---|
| 31 | if (node.type === 'comma') {
|
|---|
| 32 | return node.prev.type === 'comma' ? '' : invalid ? node.value : '|';
|
|---|
| 33 | }
|
|---|
| 34 |
|
|---|
| 35 | if (node.value) {
|
|---|
| 36 | return node.value;
|
|---|
| 37 | }
|
|---|
| 38 |
|
|---|
| 39 | if (node.nodes && node.ranges > 0) {
|
|---|
| 40 | const args = utils.reduce(node.nodes);
|
|---|
| 41 | const range = fill(...args, { ...options, wrap: false, toRegex: true, strictZeros: true });
|
|---|
| 42 |
|
|---|
| 43 | if (range.length !== 0) {
|
|---|
| 44 | return args.length > 1 && range.length > 1 ? `(${range})` : range;
|
|---|
| 45 | }
|
|---|
| 46 | }
|
|---|
| 47 |
|
|---|
| 48 | if (node.nodes) {
|
|---|
| 49 | for (const child of node.nodes) {
|
|---|
| 50 | output += walk(child, node);
|
|---|
| 51 | }
|
|---|
| 52 | }
|
|---|
| 53 |
|
|---|
| 54 | return output;
|
|---|
| 55 | };
|
|---|
| 56 |
|
|---|
| 57 | return walk(ast);
|
|---|
| 58 | };
|
|---|
| 59 |
|
|---|
| 60 | module.exports = compile;
|
|---|