node-event-generator.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311
  1. /**
  2. * @fileoverview The event generator for AST nodes.
  3. * @author Toru Nagashima
  4. */
  5. "use strict";
  6. //------------------------------------------------------------------------------
  7. // Requirements
  8. //------------------------------------------------------------------------------
  9. const esquery = require("esquery");
  10. const lodash = require("lodash");
  11. //------------------------------------------------------------------------------
  12. // Typedefs
  13. //------------------------------------------------------------------------------
  14. /**
  15. * An object describing an AST selector
  16. * @typedef {Object} ASTSelector
  17. * @property {string} rawSelector The string that was parsed into this selector
  18. * @property {boolean} isExit `true` if this should be emitted when exiting the node rather than when entering
  19. * @property {Object} parsedSelector An object (from esquery) describing the matching behavior of the selector
  20. * @property {string[]|null} listenerTypes A list of node types that could possibly cause the selector to match,
  21. * or `null` if all node types could cause a match
  22. * @property {number} attributeCount The total number of classes, pseudo-classes, and attribute queries in this selector
  23. * @property {number} identifierCount The total number of identifier queries in this selector
  24. */
  25. //------------------------------------------------------------------------------
  26. // Helpers
  27. //------------------------------------------------------------------------------
  28. /**
  29. * Gets the possible types of a selector
  30. * @param {Object} parsedSelector An object (from esquery) describing the matching behavior of the selector
  31. * @returns {string[]|null} The node types that could possibly trigger this selector, or `null` if all node types could trigger it
  32. */
  33. function getPossibleTypes(parsedSelector) {
  34. switch (parsedSelector.type) {
  35. case "identifier":
  36. return [parsedSelector.value];
  37. case "matches": {
  38. const typesForComponents = parsedSelector.selectors.map(getPossibleTypes);
  39. if (typesForComponents.every(Boolean)) {
  40. return lodash.union(...typesForComponents);
  41. }
  42. return null;
  43. }
  44. case "compound": {
  45. const typesForComponents = parsedSelector.selectors.map(getPossibleTypes).filter(typesForComponent => typesForComponent);
  46. // If all of the components could match any type, then the compound could also match any type.
  47. if (!typesForComponents.length) {
  48. return null;
  49. }
  50. /*
  51. * If at least one of the components could only match a particular type, the compound could only match
  52. * the intersection of those types.
  53. */
  54. return lodash.intersection(...typesForComponents);
  55. }
  56. case "child":
  57. case "descendant":
  58. case "sibling":
  59. case "adjacent":
  60. return getPossibleTypes(parsedSelector.right);
  61. default:
  62. return null;
  63. }
  64. }
  65. /**
  66. * Counts the number of class, pseudo-class, and attribute queries in this selector
  67. * @param {Object} parsedSelector An object (from esquery) describing the selector's matching behavior
  68. * @returns {number} The number of class, pseudo-class, and attribute queries in this selector
  69. */
  70. function countClassAttributes(parsedSelector) {
  71. switch (parsedSelector.type) {
  72. case "child":
  73. case "descendant":
  74. case "sibling":
  75. case "adjacent":
  76. return countClassAttributes(parsedSelector.left) + countClassAttributes(parsedSelector.right);
  77. case "compound":
  78. case "not":
  79. case "matches":
  80. return parsedSelector.selectors.reduce((sum, childSelector) => sum + countClassAttributes(childSelector), 0);
  81. case "attribute":
  82. case "field":
  83. case "nth-child":
  84. case "nth-last-child":
  85. return 1;
  86. default:
  87. return 0;
  88. }
  89. }
  90. /**
  91. * Counts the number of identifier queries in this selector
  92. * @param {Object} parsedSelector An object (from esquery) describing the selector's matching behavior
  93. * @returns {number} The number of identifier queries
  94. */
  95. function countIdentifiers(parsedSelector) {
  96. switch (parsedSelector.type) {
  97. case "child":
  98. case "descendant":
  99. case "sibling":
  100. case "adjacent":
  101. return countIdentifiers(parsedSelector.left) + countIdentifiers(parsedSelector.right);
  102. case "compound":
  103. case "not":
  104. case "matches":
  105. return parsedSelector.selectors.reduce((sum, childSelector) => sum + countIdentifiers(childSelector), 0);
  106. case "identifier":
  107. return 1;
  108. default:
  109. return 0;
  110. }
  111. }
  112. /**
  113. * Compares the specificity of two selector objects, with CSS-like rules.
  114. * @param {ASTSelector} selectorA An AST selector descriptor
  115. * @param {ASTSelector} selectorB Another AST selector descriptor
  116. * @returns {number}
  117. * a value less than 0 if selectorA is less specific than selectorB
  118. * a value greater than 0 if selectorA is more specific than selectorB
  119. * a value less than 0 if selectorA and selectorB have the same specificity, and selectorA <= selectorB alphabetically
  120. * a value greater than 0 if selectorA and selectorB have the same specificity, and selectorA > selectorB alphabetically
  121. */
  122. function compareSpecificity(selectorA, selectorB) {
  123. return selectorA.attributeCount - selectorB.attributeCount ||
  124. selectorA.identifierCount - selectorB.identifierCount ||
  125. (selectorA.rawSelector <= selectorB.rawSelector ? -1 : 1);
  126. }
  127. /**
  128. * Parses a raw selector string, and throws a useful error if parsing fails.
  129. * @param {string} rawSelector A raw AST selector
  130. * @returns {Object} An object (from esquery) describing the matching behavior of this selector
  131. * @throws {Error} An error if the selector is invalid
  132. */
  133. function tryParseSelector(rawSelector) {
  134. try {
  135. return esquery.parse(rawSelector.replace(/:exit$/u, ""));
  136. } catch (err) {
  137. if (err.location && err.location.start && typeof err.location.start.offset === "number") {
  138. throw new SyntaxError(`Syntax error in selector "${rawSelector}" at position ${err.location.start.offset}: ${err.message}`);
  139. }
  140. throw err;
  141. }
  142. }
  143. /**
  144. * Parses a raw selector string, and returns the parsed selector along with specificity and type information.
  145. * @param {string} rawSelector A raw AST selector
  146. * @returns {ASTSelector} A selector descriptor
  147. */
  148. const parseSelector = lodash.memoize(rawSelector => {
  149. const parsedSelector = tryParseSelector(rawSelector);
  150. return {
  151. rawSelector,
  152. isExit: rawSelector.endsWith(":exit"),
  153. parsedSelector,
  154. listenerTypes: getPossibleTypes(parsedSelector),
  155. attributeCount: countClassAttributes(parsedSelector),
  156. identifierCount: countIdentifiers(parsedSelector)
  157. };
  158. });
  159. //------------------------------------------------------------------------------
  160. // Public Interface
  161. //------------------------------------------------------------------------------
  162. /**
  163. * The event generator for AST nodes.
  164. * This implements below interface.
  165. *
  166. * ```ts
  167. * interface EventGenerator {
  168. * emitter: SafeEmitter;
  169. * enterNode(node: ASTNode): void;
  170. * leaveNode(node: ASTNode): void;
  171. * }
  172. * ```
  173. */
  174. class NodeEventGenerator {
  175. // eslint-disable-next-line jsdoc/require-description
  176. /**
  177. * @param {SafeEmitter} emitter
  178. * An SafeEmitter which is the destination of events. This emitter must already
  179. * have registered listeners for all of the events that it needs to listen for.
  180. * (See lib/linter/safe-emitter.js for more details on `SafeEmitter`.)
  181. * @returns {NodeEventGenerator} new instance
  182. */
  183. constructor(emitter) {
  184. this.emitter = emitter;
  185. this.currentAncestry = [];
  186. this.enterSelectorsByNodeType = new Map();
  187. this.exitSelectorsByNodeType = new Map();
  188. this.anyTypeEnterSelectors = [];
  189. this.anyTypeExitSelectors = [];
  190. emitter.eventNames().forEach(rawSelector => {
  191. const selector = parseSelector(rawSelector);
  192. if (selector.listenerTypes) {
  193. const typeMap = selector.isExit ? this.exitSelectorsByNodeType : this.enterSelectorsByNodeType;
  194. selector.listenerTypes.forEach(nodeType => {
  195. if (!typeMap.has(nodeType)) {
  196. typeMap.set(nodeType, []);
  197. }
  198. typeMap.get(nodeType).push(selector);
  199. });
  200. return;
  201. }
  202. const selectors = selector.isExit ? this.anyTypeExitSelectors : this.anyTypeEnterSelectors;
  203. selectors.push(selector);
  204. });
  205. this.anyTypeEnterSelectors.sort(compareSpecificity);
  206. this.anyTypeExitSelectors.sort(compareSpecificity);
  207. this.enterSelectorsByNodeType.forEach(selectorList => selectorList.sort(compareSpecificity));
  208. this.exitSelectorsByNodeType.forEach(selectorList => selectorList.sort(compareSpecificity));
  209. }
  210. /**
  211. * Checks a selector against a node, and emits it if it matches
  212. * @param {ASTNode} node The node to check
  213. * @param {ASTSelector} selector An AST selector descriptor
  214. * @returns {void}
  215. */
  216. applySelector(node, selector) {
  217. if (esquery.matches(node, selector.parsedSelector, this.currentAncestry)) {
  218. this.emitter.emit(selector.rawSelector, node);
  219. }
  220. }
  221. /**
  222. * Applies all appropriate selectors to a node, in specificity order
  223. * @param {ASTNode} node The node to check
  224. * @param {boolean} isExit `false` if the node is currently being entered, `true` if it's currently being exited
  225. * @returns {void}
  226. */
  227. applySelectors(node, isExit) {
  228. const selectorsByNodeType = (isExit ? this.exitSelectorsByNodeType : this.enterSelectorsByNodeType).get(node.type) || [];
  229. const anyTypeSelectors = isExit ? this.anyTypeExitSelectors : this.anyTypeEnterSelectors;
  230. /*
  231. * selectorsByNodeType and anyTypeSelectors were already sorted by specificity in the constructor.
  232. * Iterate through each of them, applying selectors in the right order.
  233. */
  234. let selectorsByTypeIndex = 0;
  235. let anyTypeSelectorsIndex = 0;
  236. while (selectorsByTypeIndex < selectorsByNodeType.length || anyTypeSelectorsIndex < anyTypeSelectors.length) {
  237. if (
  238. selectorsByTypeIndex >= selectorsByNodeType.length ||
  239. anyTypeSelectorsIndex < anyTypeSelectors.length &&
  240. compareSpecificity(anyTypeSelectors[anyTypeSelectorsIndex], selectorsByNodeType[selectorsByTypeIndex]) < 0
  241. ) {
  242. this.applySelector(node, anyTypeSelectors[anyTypeSelectorsIndex++]);
  243. } else {
  244. this.applySelector(node, selectorsByNodeType[selectorsByTypeIndex++]);
  245. }
  246. }
  247. }
  248. /**
  249. * Emits an event of entering AST node.
  250. * @param {ASTNode} node A node which was entered.
  251. * @returns {void}
  252. */
  253. enterNode(node) {
  254. if (node.parent) {
  255. this.currentAncestry.unshift(node.parent);
  256. }
  257. this.applySelectors(node, false);
  258. }
  259. /**
  260. * Emits an event of leaving AST node.
  261. * @param {ASTNode} node A node which was left.
  262. * @returns {void}
  263. */
  264. leaveNode(node) {
  265. this.applySelectors(node, true);
  266. this.currentAncestry.shift();
  267. }
  268. }
  269. module.exports = NodeEventGenerator;