generate-identifier-regex.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. "use strict";
  2. // Which Unicode version should be used?
  3. const version = "10.0.0";
  4. const start = require("unicode-" +
  5. version +
  6. "/Binary_Property/ID_Start/code-points.js").filter(function(ch) {
  7. return ch > 0x7f;
  8. });
  9. let last = -1;
  10. const cont = [0x200c, 0x200d].concat(
  11. require("unicode-" +
  12. version +
  13. "/Binary_Property/ID_Continue/code-points.js").filter(function(ch) {
  14. return ch > 0x7f && search(start, ch, last + 1) == -1;
  15. })
  16. );
  17. function search(arr, ch, starting) {
  18. for (let i = starting; arr[i] <= ch && i < arr.length; last = i++) {
  19. if (arr[i] === ch) return i;
  20. }
  21. return -1;
  22. }
  23. function pad(str, width) {
  24. while (str.length < width) str = "0" + str;
  25. return str;
  26. }
  27. function esc(code) {
  28. const hex = code.toString(16);
  29. if (hex.length <= 2) return "\\x" + pad(hex, 2);
  30. else return "\\u" + pad(hex, 4);
  31. }
  32. function generate(chars) {
  33. const astral = [];
  34. let re = "";
  35. for (let i = 0, at = 0x10000; i < chars.length; i++) {
  36. const from = chars[i];
  37. let to = from;
  38. while (i < chars.length - 1 && chars[i + 1] == to + 1) {
  39. i++;
  40. to++;
  41. }
  42. if (to <= 0xffff) {
  43. if (from == to) re += esc(from);
  44. else if (from + 1 == to) re += esc(from) + esc(to);
  45. else re += esc(from) + "-" + esc(to);
  46. } else {
  47. astral.push(from - at, to - from);
  48. at = to;
  49. }
  50. }
  51. return { nonASCII: re, astral: astral };
  52. }
  53. const startData = generate(start);
  54. const contData = generate(cont);
  55. console.log('let nonASCIIidentifierStartChars = "' + startData.nonASCII + '";');
  56. console.log('let nonASCIIidentifierChars = "' + contData.nonASCII + '";');
  57. console.log(
  58. "const astralIdentifierStartCodes = " + JSON.stringify(startData.astral) + ";"
  59. );
  60. console.log(
  61. "const astralIdentifierCodes = " + JSON.stringify(contData.astral) + ";"
  62. );