rewrite-pattern.js 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338
  1. 'use strict';
  2. const generate = require('regjsgen').generate;
  3. const parse = require('regjsparser').parse;
  4. const regenerate = require('regenerate');
  5. const unicodeMatchProperty = require('unicode-match-property-ecmascript');
  6. const unicodeMatchPropertyValue = require('unicode-match-property-value-ecmascript');
  7. const iuMappings = require('./data/iu-mappings.js');
  8. const ESCAPE_SETS = require('./data/character-class-escape-sets.js');
  9. // Prepare a Regenerate set containing all code points, used for negative
  10. // character classes (if any).
  11. const UNICODE_SET = regenerate().addRange(0x0, 0x10FFFF);
  12. // Without the `u` flag, the range stops at 0xFFFF.
  13. // https://mths.be/es6#sec-pattern-semantics
  14. const BMP_SET = regenerate().addRange(0x0, 0xFFFF);
  15. // Prepare a Regenerate set containing all code points that are supposed to be
  16. // matched by `/./u`. https://mths.be/es6#sec-atom
  17. const DOT_SET_UNICODE = UNICODE_SET.clone() // all Unicode code points
  18. .remove(
  19. // minus `LineTerminator`s (https://mths.be/es6#sec-line-terminators):
  20. 0x000A, // Line Feed <LF>
  21. 0x000D, // Carriage Return <CR>
  22. 0x2028, // Line Separator <LS>
  23. 0x2029 // Paragraph Separator <PS>
  24. );
  25. const getCharacterClassEscapeSet = (character, unicode, ignoreCase) => {
  26. if (unicode) {
  27. if (ignoreCase) {
  28. return ESCAPE_SETS.UNICODE_IGNORE_CASE.get(character);
  29. }
  30. return ESCAPE_SETS.UNICODE.get(character);
  31. }
  32. return ESCAPE_SETS.REGULAR.get(character);
  33. };
  34. const getUnicodeDotSet = (dotAll) => {
  35. return dotAll ? UNICODE_SET : DOT_SET_UNICODE;
  36. };
  37. const getUnicodePropertyValueSet = (property, value) => {
  38. const path = value ?
  39. `${ property }/${ value }` :
  40. `Binary_Property/${ property }`;
  41. try {
  42. return require(`regenerate-unicode-properties/${ path }.js`);
  43. } catch (exception) {
  44. throw new Error(
  45. `Failed to recognize value \`${ value }\` for property ` +
  46. `\`${ property }\`.`
  47. );
  48. }
  49. };
  50. const handleLoneUnicodePropertyNameOrValue = (value) => {
  51. // It could be a `General_Category` value or a binary property.
  52. // Note: `unicodeMatchPropertyValue` throws on invalid values.
  53. try {
  54. const property = 'General_Category';
  55. const category = unicodeMatchPropertyValue(property, value);
  56. return getUnicodePropertyValueSet(property, category);
  57. } catch (exception) {}
  58. // It’s not a `General_Category` value, so check if it’s a binary
  59. // property. Note: `unicodeMatchProperty` throws on invalid properties.
  60. const property = unicodeMatchProperty(value);
  61. return getUnicodePropertyValueSet(property);
  62. };
  63. const getUnicodePropertyEscapeSet = (value, isNegative) => {
  64. const parts = value.split('=');
  65. const firstPart = parts[0];
  66. let set;
  67. if (parts.length == 1) {
  68. set = handleLoneUnicodePropertyNameOrValue(firstPart);
  69. } else {
  70. // The pattern consists of two parts, i.e. `Property=Value`.
  71. const property = unicodeMatchProperty(firstPart);
  72. const value = unicodeMatchPropertyValue(property, parts[1]);
  73. set = getUnicodePropertyValueSet(property, value);
  74. }
  75. if (isNegative) {
  76. return UNICODE_SET.clone().remove(set);
  77. }
  78. return set.clone();
  79. };
  80. // Given a range of code points, add any case-folded code points in that range
  81. // to a set.
  82. regenerate.prototype.iuAddRange = function(min, max) {
  83. const $this = this;
  84. do {
  85. const folded = caseFold(min);
  86. if (folded) {
  87. $this.add(folded);
  88. }
  89. } while (++min <= max);
  90. return $this;
  91. };
  92. const update = (item, pattern) => {
  93. let tree = parse(pattern, config.useUnicodeFlag ? 'u' : '');
  94. switch (tree.type) {
  95. case 'characterClass':
  96. case 'group':
  97. case 'value':
  98. // No wrapping needed.
  99. break;
  100. default:
  101. // Wrap the pattern in a non-capturing group.
  102. tree = wrap(tree, pattern);
  103. }
  104. Object.assign(item, tree);
  105. };
  106. const wrap = (tree, pattern) => {
  107. // Wrap the pattern in a non-capturing group.
  108. return {
  109. 'type': 'group',
  110. 'behavior': 'ignore',
  111. 'body': [tree],
  112. 'raw': `(?:${ pattern })`
  113. };
  114. };
  115. const caseFold = (codePoint) => {
  116. return iuMappings.get(codePoint) || false;
  117. };
  118. const processCharacterClass = (characterClassItem, regenerateOptions) => {
  119. let set = regenerate();
  120. for (const item of characterClassItem.body) {
  121. switch (item.type) {
  122. case 'value':
  123. set.add(item.codePoint);
  124. if (config.ignoreCase && config.unicode && !config.useUnicodeFlag) {
  125. const folded = caseFold(item.codePoint);
  126. if (folded) {
  127. set.add(folded);
  128. }
  129. }
  130. break;
  131. case 'characterClassRange':
  132. const min = item.min.codePoint;
  133. const max = item.max.codePoint;
  134. set.addRange(min, max);
  135. if (config.ignoreCase && config.unicode && !config.useUnicodeFlag) {
  136. set.iuAddRange(min, max);
  137. }
  138. break;
  139. case 'characterClassEscape':
  140. set.add(getCharacterClassEscapeSet(
  141. item.value,
  142. config.unicode,
  143. config.ignoreCase
  144. ));
  145. break;
  146. case 'unicodePropertyEscape':
  147. set.add(getUnicodePropertyEscapeSet(item.value, item.negative));
  148. break;
  149. // The `default` clause is only here as a safeguard; it should never be
  150. // reached. Code coverage tools should ignore it.
  151. /* istanbul ignore next */
  152. default:
  153. throw new Error(`Unknown term type: ${ item.type }`);
  154. }
  155. }
  156. if (characterClassItem.negative) {
  157. set = (config.unicode ? UNICODE_SET : BMP_SET).clone().remove(set);
  158. }
  159. update(characterClassItem, set.toString(regenerateOptions));
  160. return characterClassItem;
  161. };
  162. const updateNamedReference = (item, index) => {
  163. delete item.name;
  164. item.matchIndex = index;
  165. };
  166. const assertNoUnmatchedReferences = (groups) => {
  167. const unmatchedReferencesNames = Object.keys(groups.unmatchedReferences);
  168. if (unmatchedReferencesNames.length > 0) {
  169. throw new Error(`Unknown group names: ${unmatchedReferencesNames}`);
  170. }
  171. };
  172. const processTerm = (item, regenerateOptions, groups) => {
  173. switch (item.type) {
  174. case 'dot':
  175. if (config.unicode) {
  176. update(
  177. item,
  178. getUnicodeDotSet(config.dotAll).toString(regenerateOptions)
  179. );
  180. } else if (config.dotAll) {
  181. // TODO: consider changing this at the regenerate level.
  182. update(item, '[\\s\\S]');
  183. }
  184. break;
  185. case 'characterClass':
  186. item = processCharacterClass(item, regenerateOptions);
  187. break;
  188. case 'unicodePropertyEscape':
  189. if (config.unicodePropertyEscape) {
  190. update(
  191. item,
  192. getUnicodePropertyEscapeSet(item.value, item.negative)
  193. .toString(regenerateOptions)
  194. );
  195. }
  196. break;
  197. case 'characterClassEscape':
  198. update(
  199. item,
  200. getCharacterClassEscapeSet(
  201. item.value,
  202. config.unicode,
  203. config.ignoreCase
  204. ).toString(regenerateOptions)
  205. );
  206. break;
  207. case 'group':
  208. if (item.behavior == 'normal') {
  209. groups.lastIndex++;
  210. }
  211. if (item.name && config.namedGroup) {
  212. const name = item.name.value;
  213. if (groups.names[name]) {
  214. throw new Error(
  215. `Multiple groups with the same name (${ name }) are not allowed.`
  216. );
  217. }
  218. const index = groups.lastIndex;
  219. delete item.name;
  220. groups.names[name] = index;
  221. if (groups.onNamedGroup) {
  222. groups.onNamedGroup.call(null, name, index);
  223. }
  224. if (groups.unmatchedReferences[name]) {
  225. groups.unmatchedReferences[name].forEach(reference => {
  226. updateNamedReference(reference, index);
  227. });
  228. delete groups.unmatchedReferences[name];
  229. }
  230. }
  231. /* falls through */
  232. case 'alternative':
  233. case 'disjunction':
  234. case 'quantifier':
  235. item.body = item.body.map(term => {
  236. return processTerm(term, regenerateOptions, groups);
  237. });
  238. break;
  239. case 'value':
  240. const codePoint = item.codePoint;
  241. const set = regenerate(codePoint);
  242. if (config.ignoreCase && config.unicode && !config.useUnicodeFlag) {
  243. const folded = caseFold(codePoint);
  244. if (folded) {
  245. set.add(folded);
  246. }
  247. }
  248. update(item, set.toString(regenerateOptions));
  249. break;
  250. case 'reference':
  251. if (item.name) {
  252. const name = item.name.value;
  253. const index = groups.names[name];
  254. if (index) {
  255. updateNamedReference(item, index);
  256. break;
  257. }
  258. if (!groups.unmatchedReferences[name]) {
  259. groups.unmatchedReferences[name] = [];
  260. }
  261. // Keep track of references used before the corresponding group.
  262. groups.unmatchedReferences[name].push(item);
  263. }
  264. break;
  265. case 'anchor':
  266. case 'empty':
  267. case 'group':
  268. // Nothing to do here.
  269. break;
  270. // The `default` clause is only here as a safeguard; it should never be
  271. // reached. Code coverage tools should ignore it.
  272. /* istanbul ignore next */
  273. default:
  274. throw new Error(`Unknown term type: ${ item.type }`);
  275. }
  276. return item;
  277. };
  278. const config = {
  279. 'ignoreCase': false,
  280. 'unicode': false,
  281. 'dotAll': false,
  282. 'useUnicodeFlag': false,
  283. 'unicodePropertyEscape': false,
  284. 'namedGroup': false
  285. };
  286. const rewritePattern = (pattern, flags, options) => {
  287. config.unicode = flags && flags.includes('u');
  288. const regjsparserFeatures = {
  289. 'unicodePropertyEscape': config.unicode,
  290. 'namedGroups': true,
  291. 'lookbehind': options && options.lookbehind
  292. };
  293. config.ignoreCase = flags && flags.includes('i');
  294. const supportDotAllFlag = options && options.dotAllFlag;
  295. config.dotAll = supportDotAllFlag && flags && flags.includes('s');
  296. config.namedGroup = options && options.namedGroup;
  297. config.useUnicodeFlag = options && options.useUnicodeFlag;
  298. config.unicodePropertyEscape = options && options.unicodePropertyEscape;
  299. const regenerateOptions = {
  300. 'hasUnicodeFlag': config.useUnicodeFlag,
  301. 'bmpOnly': !config.unicode
  302. };
  303. const groups = {
  304. 'onNamedGroup': options && options.onNamedGroup,
  305. 'lastIndex': 0,
  306. 'names': Object.create(null), // { [name]: index }
  307. 'unmatchedReferences': Object.create(null) // { [name]: Array<reference> }
  308. };
  309. const tree = parse(pattern, flags, regjsparserFeatures);
  310. // Note: `processTerm` mutates `tree` and `groups`.
  311. processTerm(tree, regenerateOptions, groups);
  312. assertNoUnmatchedReferences(groups);
  313. return generate(tree);
  314. };
  315. module.exports = rewritePattern;