node-event-generator.js 12 KB

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