Ohm-Management - Projektarbeit B-ME
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.

node-event-generator.js 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308
  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$/, ""));
  136. } catch (err) {
  137. if (typeof err.offset === "number") {
  138. throw new SyntaxError(`Syntax error in selector "${rawSelector}" at position ${err.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. /**
  176. * @param {SafeEmitter} emitter
  177. * An SafeEmitter which is the destination of events. This emitter must already
  178. * have registered listeners for all of the events that it needs to listen for.
  179. * (See lib/util/safe-emitter.js for more details on `SafeEmitter`.)
  180. * @returns {NodeEventGenerator} new instance
  181. */
  182. constructor(emitter) {
  183. this.emitter = emitter;
  184. this.currentAncestry = [];
  185. this.enterSelectorsByNodeType = new Map();
  186. this.exitSelectorsByNodeType = new Map();
  187. this.anyTypeEnterSelectors = [];
  188. this.anyTypeExitSelectors = [];
  189. emitter.eventNames().forEach(rawSelector => {
  190. const selector = parseSelector(rawSelector);
  191. if (selector.listenerTypes) {
  192. selector.listenerTypes.forEach(nodeType => {
  193. const typeMap = selector.isExit ? this.exitSelectorsByNodeType : this.enterSelectorsByNodeType;
  194. if (!typeMap.has(nodeType)) {
  195. typeMap.set(nodeType, []);
  196. }
  197. typeMap.get(nodeType).push(selector);
  198. });
  199. } else {
  200. (selector.isExit ? this.anyTypeExitSelectors : this.anyTypeEnterSelectors).push(selector);
  201. }
  202. });
  203. this.anyTypeEnterSelectors.sort(compareSpecificity);
  204. this.anyTypeExitSelectors.sort(compareSpecificity);
  205. this.enterSelectorsByNodeType.forEach(selectorList => selectorList.sort(compareSpecificity));
  206. this.exitSelectorsByNodeType.forEach(selectorList => selectorList.sort(compareSpecificity));
  207. }
  208. /**
  209. * Checks a selector against a node, and emits it if it matches
  210. * @param {ASTNode} node The node to check
  211. * @param {ASTSelector} selector An AST selector descriptor
  212. * @returns {void}
  213. */
  214. applySelector(node, selector) {
  215. if (esquery.matches(node, selector.parsedSelector, this.currentAncestry)) {
  216. this.emitter.emit(selector.rawSelector, node);
  217. }
  218. }
  219. /**
  220. * Applies all appropriate selectors to a node, in specificity order
  221. * @param {ASTNode} node The node to check
  222. * @param {boolean} isExit `false` if the node is currently being entered, `true` if it's currently being exited
  223. * @returns {void}
  224. */
  225. applySelectors(node, isExit) {
  226. const selectorsByNodeType = (isExit ? this.exitSelectorsByNodeType : this.enterSelectorsByNodeType).get(node.type) || [];
  227. const anyTypeSelectors = isExit ? this.anyTypeExitSelectors : this.anyTypeEnterSelectors;
  228. /*
  229. * selectorsByNodeType and anyTypeSelectors were already sorted by specificity in the constructor.
  230. * Iterate through each of them, applying selectors in the right order.
  231. */
  232. let selectorsByTypeIndex = 0;
  233. let anyTypeSelectorsIndex = 0;
  234. while (selectorsByTypeIndex < selectorsByNodeType.length || anyTypeSelectorsIndex < anyTypeSelectors.length) {
  235. if (
  236. selectorsByTypeIndex >= selectorsByNodeType.length ||
  237. anyTypeSelectorsIndex < anyTypeSelectors.length &&
  238. compareSpecificity(anyTypeSelectors[anyTypeSelectorsIndex], selectorsByNodeType[selectorsByTypeIndex]) < 0
  239. ) {
  240. this.applySelector(node, anyTypeSelectors[anyTypeSelectorsIndex++]);
  241. } else {
  242. this.applySelector(node, selectorsByNodeType[selectorsByTypeIndex++]);
  243. }
  244. }
  245. }
  246. /**
  247. * Emits an event of entering AST node.
  248. * @param {ASTNode} node - A node which was entered.
  249. * @returns {void}
  250. */
  251. enterNode(node) {
  252. if (node.parent) {
  253. this.currentAncestry.unshift(node.parent);
  254. }
  255. this.applySelectors(node, false);
  256. }
  257. /**
  258. * Emits an event of leaving AST node.
  259. * @param {ASTNode} node - A node which was left.
  260. * @returns {void}
  261. */
  262. leaveNode(node) {
  263. this.applySelectors(node, true);
  264. this.currentAncestry.shift();
  265. }
  266. }
  267. module.exports = NodeEventGenerator;