-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathuxregexp.js
407 lines (333 loc) · 11.3 KB
/
uxregexp.js
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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
var RegExpTree = require('regexp-tree');
module.exports =
UXRegExp = (function() {
var use_collect_groups_with_same_name = 1;
var PREFIX_NON_CAPTURING = '$$';
var debug = 0;
var show = function(x) {
/* istanbul ignore next */
console.log(x);
};
var showt = function(x) {
/* istanbul ignore next */
show(JSON.stringify(x, null, ' '));
};
var showo = function(x) {
/* istanbul ignore next */
show(JSON.stringify(x));
};
//---------------------------------------------------------------------------- constructor
function UXRegExp(re, options) {
//if (debug >= 1) showo(['input expression', re, options]);
var flags = '';
var rtOptions = { allowGroupNameDuplicates: true };
if(typeof options === 'string') {
flags += options;
} else if(typeof options === 'object') {
if(options.flags) {
flags += options.flags;
delete options.flags;
}
if(options.debug) {
debug = options.debug;
delete options.debug;
}
}
if(typeof re !== 'string') {
re = re.toString();
}
// extract flags, set options and remove those not known by javascript
var matches = /^\s*\/([\s\S]*)\/([a-z]*)\s*$/.exec(re);
if (matches) {
re = matches[1];
flags += matches[2];
}
// escape '/'
re = re.replace(/\//g, '\\/');
re = re.replace(/\\\\\//g, '\\/');
// automatically use x-flag for regexp with newlines
if (re.includes('\n')) {
flags += 'x';
}
// santize flags (sort, uniq)
flags = flags.split('')
.sort()
.filter(
function(e,i,a) {
return !i || e != a[i-1];
}
)
.join('');
re = '/' + re + '/' + flags;
//showo(['after preprocess', re]);
// build AST from re
var ast = RegExpTree.parser.parse(re, rtOptions);
//if(debug >= 3) showt(ast);
// ensure all parts of alternatives (=sequences) are groups.
// this allows to determine the character positions
// by cummulating the lengths of preceding groups
// these must be wrapped
var toBeWrapped = function(node) {
var result = ! (node.type === 'Group');
//showo(['toBeWrapped', result, node.type, node.expression ? node.expression.type : node.value]);
return result;
}
// these can be combined when wrapped
var toBeCombined = function(node) {
var result = toBeWrapped(node)
&& ! (
node.type === 'Repetition'
&& node.expression.type === 'Group'
&& node.expression.capturing
);
//showo(['toBeCombined', result, node.type, node.expression ? node.expression.type : node.value]);
return result;
}
//var toBeCombined = toBeWrapped;
//var toBeCombined = function(node) { return false; };
// var unwrapped = RegExpTree.generate(ast);
// if(debug >= 2) show('--------------------- unwrapped');
// if(debug >= 2) show(unwrapped);
RegExpTree.traverse(ast, {
'Alternative': function(path) {
// ignore if this was created by collecting wrapped nodes
if(path.node.combined)
return;
//showo(['Alternative', path.node.expressions.map(function(x) {return [x.type, x.value]})]);
var children = [];
var collected = [];
var nCollected = 0;
var nDirect = 0;
path.node.expressions.forEach( function(child) {
//show([child.type, child.value, child.expression ? [child.expression.type, child.expression.value] : null]);
if(toBeCombined(child)) {
//showo(['collect', child.type, child.value]);
collected.push(child); // collect
nCollected++;
} else if(toBeWrapped(child)) {
//showo(['wrap ', child.type, child.value]);
if(collected.length) children.push(collected);
collected = [];
children.push([child]); // single array item -> wrap!
nCollected++;
} else {
//showo(['copy ', child.type, child.value]);
if(collected.length) children.push(collected);
collected = [];
children.push(child); // no wrap
nDirect++;
}
});
// TODO: wrapping not really necessary after the last capturing group
// to push all remaining objects without wrapping
//Array.prototype.push.apply(children, collected);
if(collected.length) children.push(collected);
//showo([nCollected, nDirect]);
if(1 || nCollected && nDirect) { // TODO: optimize groups in groups
// clear all expressions
path.node.expressions = [];
children.forEach(function(child) {
if(Array.isArray(child)) {
// collected nodes have to be wrapped in group
//showo(['child array', child.map(function(x) {return [x.type, x.value]})]);
// add Group
var groupPath = path.appendChild({
type: 'Group',
capturing: false,
expression: null,
wrapped: true
});
if(child.length > 1) {
// add array of collected nodes to group
var altPath = groupPath.setChild({
type: 'Alternative',
expressions: [],
combined: true
});
child.forEach(function(node) {
//showo(['append child alt', [node.type, node.value]]);
altPath.appendChild(node);
});
} else {
// add single collected node to group
//showo(['wrap single', child[0].type, child[0].value]);
groupPath.setChild(child[0]);
}
} else {
// add the node without wrapping
//showo(['append child', [child.type, child.value]]);
path.appendChild(child);
}
});
}
}
});
// var wrapped = RegExpTree.generate(ast);
// if(debug >= 1) show('--------------------- wrapped');
// if(debug >= 1) show(wrapped);
// determine names of all groups (named and numbered)
// find hierarchy of groups (collect an array of parent group names for each named group)
getParentNames = function(path) {
var parentNames = [];
while (path) {
path = path.getParent();
if (path) {
if (path.node.type === 'Group') {
if (path.node.name) {
parentNames.push(path.node.name);
}
}
}
}
return parentNames;
};
var names = [null];
var parents = {};
var indexCaptureGroup = 1;
var indexNonCaptureGroup = 1;
RegExpTree.traverse(ast, {
Group: function(path) {
var node = path.node;
var non_capturing = false;
if (!node.name) {
if(node.capturing) {
node.name = indexCaptureGroup;
} else {
non_capturing = true;
node.name = - (10000*(indexCaptureGroup-1) + indexNonCaptureGroup);
indexNonCaptureGroup++;
}
}
if (node.name) {
names.push(node.name);
if( ! non_capturing ) {
indexCaptureGroup++;
//indexNonCaptureGroup = 1;
}
parents[node.name] = getParentNames(path);
//show([node.name, parents[node.name]]);
}
node.capturing = true;
return;
}
});
// remove names from all groups
// set group numbers ofr named back references
RegExpTree.traverse(ast, {
Group: function(arg) {
var node = arg.node;
return delete node.name;
},
Backreference: function(arg) {
var node = arg.node;
node.kind = 'number';
node.reference = names.indexOf(node.reference);
node.number = node.reference;
return delete node.name;
}
});
this.names = names;
this.parents = parents;
//if(debug >= 3) show(names);
//if(debug >= 3) show(parents);
ast.flags = ast.flags.replace('x', '');
var xre = RegExpTree.generate(ast);
this.re = RegExpTree.toRegExp(xre);
//showt(this);
// if(debug >= 1) show('--------------------- re');
// if(debug >= 1) show(this.re);
}
//---------------------------------------------------------------------------- exec
UXRegExp.prototype.exec = function(text) {
//if (debug >= 1) showo(text);
var matches = this.re.exec(text);
//if (debug >= 1) showo(matches);
if (!matches)
return null;
var result = {
input: text,
groups: {},
names: [],
infos: {}
};
var setRootGroup = function(result, name, val, info) {
result[name] = val;
result.infos[name] = info;
}
var setGroup = function(result, name, val, info) {
if(val != null) {
if( use_collect_groups_with_same_name && result.groups[name] != null ) {
if(Array.isArray(result.groups[name])) {
result.groups[name].push(val);
result.infos[name].push(info);
} else {
result.groups[name] = [result.groups[name], val];
result.infos[name] = [result.infos[name], info];
}
} else {
result.groups[name] = val;
result.infos[name] = info;
}
}
result.names.push(name);
}
var charIndexAll = matches.index;
setRootGroup(result, 'all',
matches[0],
{index: charIndexAll}
);
setRootGroup(result, 'pre',
matches.input.substring(0, charIndexAll),
{index: 0}
);
setRootGroup(result, 'post',
matches.input.substring(charIndexAll + matches[0].length),
{index: charIndexAll + matches[0].length}
);
//if (debug >= 3) showo(result);
// collect result groups as strings or groups according to original expression
var position = [];
var groupedMin = text.length;
var groupedMax = 0;
var next = [charIndexAll];
var lastLevel = 0;
for (var i = 1; i < this.names.length; i++) {
var name = this.names[i];
var val = matches[i];
var len = val ? val.length : 0;
var level = (this.parents[name] || []).length;
if( ! position[level] )
position[level] = 0;
var pos;
if(level > lastLevel)
pos = position[lastLevel];
else
pos = next[level];
position[level] = pos;
if(name && ! (typeof name === "number" && name < 0)) {
if(pos < groupedMin)
groupedMin = pos;
if(pos + len > groupedMax)
groupedMax = pos + len;
setGroup(result, name, val, {index: pos});
}
next[level] = pos + len;
//if (debug >= 2) show([' '.repeat(level), name, pos, next[level]]);
lastLevel = level;
}
setRootGroup(result, 'grouped',
text.slice(groupedMin, groupedMax),
{index: groupedMin}
);
//if (debug >= 1) showt(result);
return result;
};
//---------------------------------------------------------------------------- test
UXRegExp.prototype.test = function(text) {
return this.re.test(text);
};
UXRegExp.show = show;
UXRegExp.showo = showo;
UXRegExp.showt = showt;
return UXRegExp;
})();