isIdentifier.js 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. import {IS_IDENTIFIER_CHAR, IS_IDENTIFIER_START} from "../parser/util/identifier";
  2. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Lexical_grammar
  3. // Hard-code a list of reserved words rather than trying to use keywords or contextual keywords
  4. // from the parser, since currently there are various exceptions, like `package` being reserved
  5. // but unused and various contextual keywords being reserved. Note that we assume that all code
  6. // compiled by Sucrase is in a module, so strict mode words and await are all considered reserved
  7. // here.
  8. const RESERVED_WORDS = new Set([
  9. // Reserved keywords as of ECMAScript 2015
  10. "break",
  11. "case",
  12. "catch",
  13. "class",
  14. "const",
  15. "continue",
  16. "debugger",
  17. "default",
  18. "delete",
  19. "do",
  20. "else",
  21. "export",
  22. "extends",
  23. "finally",
  24. "for",
  25. "function",
  26. "if",
  27. "import",
  28. "in",
  29. "instanceof",
  30. "new",
  31. "return",
  32. "super",
  33. "switch",
  34. "this",
  35. "throw",
  36. "try",
  37. "typeof",
  38. "var",
  39. "void",
  40. "while",
  41. "with",
  42. "yield",
  43. // Future reserved keywords
  44. "enum",
  45. "implements",
  46. "interface",
  47. "let",
  48. "package",
  49. "private",
  50. "protected",
  51. "public",
  52. "static",
  53. "await",
  54. // Literals that cannot be used as identifiers
  55. "false",
  56. "null",
  57. "true",
  58. ]);
  59. /**
  60. * Determine if the given name is a legal variable name.
  61. *
  62. * This is needed when transforming TypeScript enums; if an enum key is a valid
  63. * variable name, it might be referenced later in the enum, so we need to
  64. * declare a variable.
  65. */
  66. export default function isIdentifier(name) {
  67. if (name.length === 0) {
  68. return false;
  69. }
  70. if (!IS_IDENTIFIER_START[name.charCodeAt(0)]) {
  71. return false;
  72. }
  73. for (let i = 1; i < name.length; i++) {
  74. if (!IS_IDENTIFIER_CHAR[name.charCodeAt(i)]) {
  75. return false;
  76. }
  77. }
  78. return !RESERVED_WORDS.has(name);
  79. }