2 * @fileoverview The event generator for AST nodes.
3 * @author Toru Nagashima
8 //------------------------------------------------------------------------------
10 //------------------------------------------------------------------------------
12 const esquery = require("esquery");
13 const lodash = require("lodash");
15 //------------------------------------------------------------------------------
17 //------------------------------------------------------------------------------
20 * An object describing an AST selector
21 * @typedef {Object} ASTSelector
22 * @property {string} rawSelector The string that was parsed into this selector
23 * @property {boolean} isExit `true` if this should be emitted when exiting the node rather than when entering
24 * @property {Object} parsedSelector An object (from esquery) describing the matching behavior of the selector
25 * @property {string[]|null} listenerTypes A list of node types that could possibly cause the selector to match,
26 * or `null` if all node types could cause a match
27 * @property {number} attributeCount The total number of classes, pseudo-classes, and attribute queries in this selector
28 * @property {number} identifierCount The total number of identifier queries in this selector
31 //------------------------------------------------------------------------------
33 //------------------------------------------------------------------------------
36 * Gets the possible types of a selector
37 * @param {Object} parsedSelector An object (from esquery) describing the matching behavior of the selector
38 * @returns {string[]|null} The node types that could possibly trigger this selector, or `null` if all node types could trigger it
40 function getPossibleTypes(parsedSelector) {
41 switch (parsedSelector.type) {
43 return [parsedSelector.value];
46 const typesForComponents = parsedSelector.selectors.map(getPossibleTypes);
48 if (typesForComponents.every(Boolean)) {
49 return lodash.union(...typesForComponents);
55 const typesForComponents = parsedSelector.selectors.map(getPossibleTypes).filter(typesForComponent => typesForComponent);
57 // If all of the components could match any type, then the compound could also match any type.
58 if (!typesForComponents.length) {
63 * If at least one of the components could only match a particular type, the compound could only match
64 * the intersection of those types.
66 return lodash.intersection(...typesForComponents);
73 return getPossibleTypes(parsedSelector.right);
82 * Counts the number of class, pseudo-class, and attribute queries in this selector
83 * @param {Object} parsedSelector An object (from esquery) describing the selector's matching behavior
84 * @returns {number} The number of class, pseudo-class, and attribute queries in this selector
86 function countClassAttributes(parsedSelector) {
87 switch (parsedSelector.type) {
92 return countClassAttributes(parsedSelector.left) + countClassAttributes(parsedSelector.right);
97 return parsedSelector.selectors.reduce((sum, childSelector) => sum + countClassAttributes(childSelector), 0);
102 case "nth-last-child":
111 * Counts the number of identifier queries in this selector
112 * @param {Object} parsedSelector An object (from esquery) describing the selector's matching behavior
113 * @returns {number} The number of identifier queries
115 function countIdentifiers(parsedSelector) {
116 switch (parsedSelector.type) {
121 return countIdentifiers(parsedSelector.left) + countIdentifiers(parsedSelector.right);
126 return parsedSelector.selectors.reduce((sum, childSelector) => sum + countIdentifiers(childSelector), 0);
137 * Compares the specificity of two selector objects, with CSS-like rules.
138 * @param {ASTSelector} selectorA An AST selector descriptor
139 * @param {ASTSelector} selectorB Another AST selector descriptor
141 * a value less than 0 if selectorA is less specific than selectorB
142 * a value greater than 0 if selectorA is more specific than selectorB
143 * a value less than 0 if selectorA and selectorB have the same specificity, and selectorA <= selectorB alphabetically
144 * a value greater than 0 if selectorA and selectorB have the same specificity, and selectorA > selectorB alphabetically
146 function compareSpecificity(selectorA, selectorB) {
147 return selectorA.attributeCount - selectorB.attributeCount ||
148 selectorA.identifierCount - selectorB.identifierCount ||
149 (selectorA.rawSelector <= selectorB.rawSelector ? -1 : 1);
153 * Parses a raw selector string, and throws a useful error if parsing fails.
154 * @param {string} rawSelector A raw AST selector
155 * @returns {Object} An object (from esquery) describing the matching behavior of this selector
156 * @throws {Error} An error if the selector is invalid
158 function tryParseSelector(rawSelector) {
160 return esquery.parse(rawSelector.replace(/:exit$/u, ""));
162 if (err.location && err.location.start && typeof err.location.start.offset === "number") {
163 throw new SyntaxError(`Syntax error in selector "${rawSelector}" at position ${err.location.start.offset}: ${err.message}`);
170 * Parses a raw selector string, and returns the parsed selector along with specificity and type information.
171 * @param {string} rawSelector A raw AST selector
172 * @returns {ASTSelector} A selector descriptor
174 const parseSelector = lodash.memoize(rawSelector => {
175 const parsedSelector = tryParseSelector(rawSelector);
179 isExit: rawSelector.endsWith(":exit"),
181 listenerTypes: getPossibleTypes(parsedSelector),
182 attributeCount: countClassAttributes(parsedSelector),
183 identifierCount: countIdentifiers(parsedSelector)
187 //------------------------------------------------------------------------------
189 //------------------------------------------------------------------------------
192 * The event generator for AST nodes.
193 * This implements below interface.
196 * interface EventGenerator {
197 * emitter: SafeEmitter;
198 * enterNode(node: ASTNode): void;
199 * leaveNode(node: ASTNode): void;
203 class NodeEventGenerator {
205 // eslint-disable-next-line jsdoc/require-description
207 * @param {SafeEmitter} emitter
208 * An SafeEmitter which is the destination of events. This emitter must already
209 * have registered listeners for all of the events that it needs to listen for.
210 * (See lib/linter/safe-emitter.js for more details on `SafeEmitter`.)
211 * @param {ESQueryOptions} esqueryOptions `esquery` options for traversing custom nodes.
212 * @returns {NodeEventGenerator} new instance
214 constructor(emitter, esqueryOptions) {
215 this.emitter = emitter;
216 this.esqueryOptions = esqueryOptions;
217 this.currentAncestry = [];
218 this.enterSelectorsByNodeType = new Map();
219 this.exitSelectorsByNodeType = new Map();
220 this.anyTypeEnterSelectors = [];
221 this.anyTypeExitSelectors = [];
223 emitter.eventNames().forEach(rawSelector => {
224 const selector = parseSelector(rawSelector);
226 if (selector.listenerTypes) {
227 const typeMap = selector.isExit ? this.exitSelectorsByNodeType : this.enterSelectorsByNodeType;
229 selector.listenerTypes.forEach(nodeType => {
230 if (!typeMap.has(nodeType)) {
231 typeMap.set(nodeType, []);
233 typeMap.get(nodeType).push(selector);
237 const selectors = selector.isExit ? this.anyTypeExitSelectors : this.anyTypeEnterSelectors;
239 selectors.push(selector);
242 this.anyTypeEnterSelectors.sort(compareSpecificity);
243 this.anyTypeExitSelectors.sort(compareSpecificity);
244 this.enterSelectorsByNodeType.forEach(selectorList => selectorList.sort(compareSpecificity));
245 this.exitSelectorsByNodeType.forEach(selectorList => selectorList.sort(compareSpecificity));
249 * Checks a selector against a node, and emits it if it matches
250 * @param {ASTNode} node The node to check
251 * @param {ASTSelector} selector An AST selector descriptor
254 applySelector(node, selector) {
255 if (esquery.matches(node, selector.parsedSelector, this.currentAncestry, this.esqueryOptions)) {
256 this.emitter.emit(selector.rawSelector, node);
261 * Applies all appropriate selectors to a node, in specificity order
262 * @param {ASTNode} node The node to check
263 * @param {boolean} isExit `false` if the node is currently being entered, `true` if it's currently being exited
266 applySelectors(node, isExit) {
267 const selectorsByNodeType = (isExit ? this.exitSelectorsByNodeType : this.enterSelectorsByNodeType).get(node.type) || [];
268 const anyTypeSelectors = isExit ? this.anyTypeExitSelectors : this.anyTypeEnterSelectors;
271 * selectorsByNodeType and anyTypeSelectors were already sorted by specificity in the constructor.
272 * Iterate through each of them, applying selectors in the right order.
274 let selectorsByTypeIndex = 0;
275 let anyTypeSelectorsIndex = 0;
277 while (selectorsByTypeIndex < selectorsByNodeType.length || anyTypeSelectorsIndex < anyTypeSelectors.length) {
279 selectorsByTypeIndex >= selectorsByNodeType.length ||
280 anyTypeSelectorsIndex < anyTypeSelectors.length &&
281 compareSpecificity(anyTypeSelectors[anyTypeSelectorsIndex], selectorsByNodeType[selectorsByTypeIndex]) < 0
283 this.applySelector(node, anyTypeSelectors[anyTypeSelectorsIndex++]);
285 this.applySelector(node, selectorsByNodeType[selectorsByTypeIndex++]);
291 * Emits an event of entering AST node.
292 * @param {ASTNode} node A node which was entered.
297 this.currentAncestry.unshift(node.parent);
299 this.applySelectors(node, false);
303 * Emits an event of leaving AST node.
304 * @param {ASTNode} node A node which was left.
308 this.applySelectors(node, true);
309 this.currentAncestry.shift();
313 module.exports = NodeEventGenerator;