Debian Codegraph @

packages/babel-types/src/validators/matchesPattern.ts

raw
1 import {
2 isIdentifier,
3 isMemberExpression,
4 isStringLiteral,
5 isThisExpression,
6 } from "./generated";
7 import type * as t from "..";
8
9 /**
10 * Determines whether or not the input node `member` matches the
11 * input `match`.
12 *
13 * For example, given the match `React.createClass` it would match the
14 * parsed nodes of `React.createClass` and `React["createClass"]`.
15 */
16 export default function matchesPattern(
17 member: t.Node | null | undefined,
18 match: string | string[],
19 allowPartial?: boolean,
20 ): boolean {
21 // not a member expression
22 if (!isMemberExpression(member)) return false;
23
24 const parts = Array.isArray(match) ? match : match.split(".");
25 const nodes = [];
26
27 let node;
28 for (node = member; isMemberExpression(node); node = node.object) {
29 nodes.push(node.property);
30 }
31 nodes.push(node);
32
33 if (nodes.length < parts.length) return false;
34 if (!allowPartial && nodes.length > parts.length) return false;
35
36 for (let i = 0, j = nodes.length - 1; i < parts.length; i++, j--) {
37 const node = nodes[j];
38 let value;
39 if (isIdentifier(node)) {
40 value = node.name;
41 } else if (isStringLiteral(node)) {
42 value = node.value;
43 } else if (isThisExpression(node)) {
44 value = "this";
45 } else {
46 return false;
47 }
48
49 if (parts[i] !== value) return false;
50 }
51
52 return true;
53 }