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.

81 lines
2.1 KiB

4 years ago
  1. /**
  2. * @author Toru Nagashima <https://github.com/mysticatea>
  3. * See LICENSE file in root directory for full license.
  4. */
  5. "use strict";
  6. const KEYS = require("./visitor-keys.json");
  7. // Types.
  8. const NODE_TYPES = Object.freeze(Object.keys(KEYS));
  9. // Freeze the keys.
  10. for (const type of NODE_TYPES) {
  11. Object.freeze(KEYS[type]);
  12. }
  13. Object.freeze(KEYS);
  14. // List to ignore keys.
  15. const KEY_BLACKLIST = new Set([
  16. "parent",
  17. "leadingComments",
  18. "trailingComments"
  19. ]);
  20. /**
  21. * Check whether a given key should be used or not.
  22. * @param {string} key The key to check.
  23. * @returns {boolean} `true` if the key should be used.
  24. */
  25. function filterKey(key) {
  26. return !KEY_BLACKLIST.has(key) && key[0] !== "_";
  27. }
  28. //------------------------------------------------------------------------------
  29. // Public interfaces
  30. //------------------------------------------------------------------------------
  31. module.exports = Object.freeze({
  32. /**
  33. * Visitor keys.
  34. * @type {{ [type: string]: string[] | undefined }}
  35. */
  36. KEYS,
  37. /**
  38. * Get visitor keys of a given node.
  39. * @param {Object} node The AST node to get keys.
  40. * @returns {string[]} Visitor keys of the node.
  41. */
  42. getKeys(node) {
  43. return Object.keys(node).filter(filterKey);
  44. },
  45. // Disable valid-jsdoc rule because it reports syntax error on the type of @returns.
  46. // eslint-disable-next-line valid-jsdoc
  47. /**
  48. * Make the union set with `KEYS` and given keys.
  49. * @param {Object} additionalKeys The additional keys.
  50. * @returns {{ [type: string]: string[] | undefined }} The union set.
  51. */
  52. unionWith(additionalKeys) {
  53. const retv = Object.assign({}, KEYS);
  54. for (const type of Object.keys(additionalKeys)) {
  55. if (retv.hasOwnProperty(type)) {
  56. const keys = new Set(additionalKeys[type]);
  57. for (const key of retv[type]) {
  58. keys.add(key);
  59. }
  60. retv[type] = Object.freeze(Array.from(keys));
  61. } else {
  62. retv[type] = Object.freeze(Array.from(additionalKeys[type]));
  63. }
  64. }
  65. return Object.freeze(retv);
  66. }
  67. });