You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

332 lines
9.4 KiB

4 years ago
  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. update(
  190. item,
  191. getUnicodePropertyEscapeSet(item.value, item.negative)
  192. .toString(regenerateOptions)
  193. );
  194. break;
  195. case 'characterClassEscape':
  196. update(
  197. item,
  198. getCharacterClassEscapeSet(
  199. item.value,
  200. config.unicode,
  201. config.ignoreCase
  202. ).toString(regenerateOptions)
  203. );
  204. break;
  205. case 'group':
  206. if (item.behavior == 'normal') {
  207. groups.lastIndex++;
  208. }
  209. if (item.name) {
  210. const name = item.name.value;
  211. if (groups.names[name]) {
  212. throw new Error(
  213. `Multiple groups with the same name (${ name }) are not allowed.`
  214. );
  215. }
  216. const index = groups.lastIndex;
  217. delete item.name;
  218. groups.names[name] = index;
  219. if (groups.onNamedGroup) {
  220. groups.onNamedGroup.call(null, name, index);
  221. }
  222. if (groups.unmatchedReferences[name]) {
  223. groups.unmatchedReferences[name].forEach(reference => {
  224. updateNamedReference(reference, index);
  225. });
  226. delete groups.unmatchedReferences[name];
  227. }
  228. }
  229. /* falls through */
  230. case 'alternative':
  231. case 'disjunction':
  232. case 'quantifier':
  233. item.body = item.body.map(term => {
  234. return processTerm(term, regenerateOptions, groups);
  235. });
  236. break;
  237. case 'value':
  238. const codePoint = item.codePoint;
  239. const set = regenerate(codePoint);
  240. if (config.ignoreCase && config.unicode && !config.useUnicodeFlag) {
  241. const folded = caseFold(codePoint);
  242. if (folded) {
  243. set.add(folded);
  244. }
  245. }
  246. update(item, set.toString(regenerateOptions));
  247. break;
  248. case 'reference':
  249. if (item.name) {
  250. const name = item.name.value;
  251. const index = groups.names[name];
  252. if (index) {
  253. updateNamedReference(item, index);
  254. break;
  255. }
  256. if (!groups.unmatchedReferences[name]) {
  257. groups.unmatchedReferences[name] = [];
  258. }
  259. // Keep track of references used before the corresponding group.
  260. groups.unmatchedReferences[name].push(item);
  261. }
  262. break;
  263. case 'anchor':
  264. case 'empty':
  265. case 'group':
  266. // Nothing to do here.
  267. break;
  268. // The `default` clause is only here as a safeguard; it should never be
  269. // reached. Code coverage tools should ignore it.
  270. /* istanbul ignore next */
  271. default:
  272. throw new Error(`Unknown term type: ${ item.type }`);
  273. }
  274. return item;
  275. };
  276. const config = {
  277. 'ignoreCase': false,
  278. 'unicode': false,
  279. 'dotAll': false,
  280. 'useUnicodeFlag': false
  281. };
  282. const rewritePattern = (pattern, flags, options) => {
  283. const regjsparserFeatures = {
  284. 'unicodePropertyEscape': options && options.unicodePropertyEscape,
  285. 'namedGroups': options && options.namedGroup,
  286. 'lookbehind': options && options.lookbehind
  287. };
  288. config.ignoreCase = flags && flags.includes('i');
  289. config.unicode = flags && flags.includes('u');
  290. const supportDotAllFlag = options && options.dotAllFlag;
  291. config.dotAll = supportDotAllFlag && flags && flags.includes('s');
  292. config.useUnicodeFlag = options && options.useUnicodeFlag;
  293. const regenerateOptions = {
  294. 'hasUnicodeFlag': config.useUnicodeFlag,
  295. 'bmpOnly': !config.unicode
  296. };
  297. const groups = {
  298. 'onNamedGroup': options && options.onNamedGroup,
  299. 'lastIndex': 0,
  300. 'names': Object.create(null), // { [name]: index }
  301. 'unmatchedReferences': Object.create(null) // { [name]: Array<reference> }
  302. };
  303. const tree = parse(pattern, flags, regjsparserFeatures);
  304. // Note: `processTerm` mutates `tree` and `groups`.
  305. processTerm(tree, regenerateOptions, groups);
  306. assertNoUnmatchedReferences(groups);
  307. return generate(tree);
  308. };
  309. module.exports = rewritePattern;