-
Notifications
You must be signed in to change notification settings - Fork 620
/
Copy pathTreePattern.ts
236 lines (210 loc) · 7.29 KB
/
TreePattern.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
// Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license.
// See LICENSE in the project root for license information.
/**
* Indicates the tree-like data structure that {@link TreePattern} will traverse.
*
* @remarks
* Since `TreePattern` makes relatively few assumptions object the object structure, this is
* just an alias for `any`. At least as far as the portions to be matched, the tree nodes
* are expected to be JSON-like structures made from JavaScript arrays, JavaScript objects,
* and primitive values that can be compared using `===`.
*
* @public
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export type TreeNode = any;
class TreePatternArg {
public readonly keyName: string;
public readonly subtree: TreeNode | undefined;
public constructor(keyName: string, subtree?: TreeNode) {
this.keyName = keyName;
this.subtree = subtree;
}
}
class TreePatternAlternatives {
public readonly possibleSubtrees: TreeNode[];
public constructor(possibleSubtrees: TreeNode[]) {
this.possibleSubtrees = possibleSubtrees;
}
}
/**
* Provides additional detail about the success or failure of {@link TreePattern.match}.
*
* @remarks
* On success, the object will contain keys for any successfully matched tags, as
* defined using {@link TreePattern.tag}.
*
* On failure, the `failPath` member will indicate the JSON path of the node that
* failed to match.
*
* @public
*/
export type ITreePatternCaptureSet =
| {
[tagName: string]: TreeNode;
}
| { failPath: string };
/**
* A fast, lightweight pattern matcher for tree structures such as an Abstract Syntax Tree (AST).
* @public
*/
export class TreePattern {
private readonly _pattern: TreeNode;
public constructor(pattern: TreeNode) {
this._pattern = pattern;
}
/**
* Labels a subtree within the search pattern, so that the matching object can be retrieved.
*
* @remarks
* Used to build the `pattern` tree for {@link TreePattern.match}. For the given `subtree` of the pattern,
* if it is matched, that node will be assigned to the `captures` object using `tagName` as the key.
*
* Example:
*
* ```ts
* const myCaptures: { personName?: string } = {};
* const myPattern = {
* name: TreePattern.tag('personName')
* };
* if (myPattern.match({ name: 'Bob' }, myCaptures)) {
* console.log(myCaptures.personName);
* }
* ```
*/
public static tag(tagName: string, subtree?: TreeNode): TreeNode {
return new TreePatternArg(tagName, subtree);
}
/**
* Used to specify alternative possible subtrees in the search pattern.
*
* @remarks
* Used to build the `pattern` tree for {@link TreePattern.match}. Allows several alternative patterns
* to be matched for a given subtree.
*
* Example:
*
* ```ts
* const myPattern: TreePattern = new TreePattern({
* animal: TreePattern.oneOf([
* { kind: 'dog', bark: 'loud' },
* { kind: 'cat', meow: 'quiet' }
* ])
* });
* if (myPattern.match({ animal: { kind: 'dog', bark: 'loud' } })) {
* console.log('I can match dog.');
* }
* if (myPattern.match({ animal: { kind: 'cat', meow: 'quiet' } })) {
* console.log('I can match cat, too.');
* }
* ```
*/
public static oneOf(possibleSubtrees: TreeNode[]): TreeNode {
return new TreePatternAlternatives(possibleSubtrees);
}
/**
* Match an input tree.
*
* @remarks
* Return true if the `root` node matches the pattern. (If the `root` node does not match, the child nodes are
* not recursively tested, since for an Abstract Syntax Tree the caller is typically an efficient visitor
* callback that already handles that job.)
*
* If the input matches the pattern, any tagged subtrees will be assigned to the `captures` target object
* if provided. If the input does not match, the path of the mismatched node will be assigned to
* `captures.failPath`.
*
* @param root - the input tree to be matched
* @param captures - an optional object to receive any subtrees that were matched using {@link TreePattern.tag}
* @returns `true` if `root` matches the pattern, or `false` otherwise
*/
public match(root: TreeNode, captures: ITreePatternCaptureSet = {}): boolean {
return TreePattern._matchTreeRecursive(root, this._pattern, captures, 'root');
}
private static _matchTreeRecursive(
root: TreeNode,
pattern: TreeNode,
captures: ITreePatternCaptureSet,
path: string
): boolean {
if (pattern === undefined) {
throw new Error('pattern has an undefined value at ' + path);
}
// Avoid "Element implicitly has an 'any' type" (TS7053)
const castedCaptures: Record<string, TreeNode> = captures;
if (pattern instanceof TreePatternArg) {
if (pattern.subtree !== undefined) {
if (!TreePattern._matchTreeRecursive(root, pattern.subtree, captures, path)) {
return false;
}
}
castedCaptures[pattern.keyName] = root;
return true;
}
if (pattern instanceof TreePatternAlternatives) {
// Try each possible alternative until we find one that matches
for (const possibleSubtree of pattern.possibleSubtrees) {
// We shouldn't update "captures" unless the match is fully successful.
// So make a temporary copy of it.
const tempCaptures: Record<string, TreeNode> = { ...captures };
if (TreePattern._matchTreeRecursive(root, possibleSubtree, tempCaptures, path)) {
// The match was successful, so assign the tempCaptures results back into the
// original "captures" object.
for (const key of Object.getOwnPropertyNames(tempCaptures)) {
castedCaptures[key] = tempCaptures[key];
}
return true;
}
}
// None of the alternatives matched
return false;
}
if (Array.isArray(pattern)) {
if (!Array.isArray(root)) {
captures.failPath = path;
return false;
}
if (root.length !== pattern.length) {
captures.failPath = path;
return false;
}
for (let i: number = 0; i < pattern.length; ++i) {
const subPath: string = path + '[' + i + ']';
const rootElement: TreeNode = root[i];
const patternElement: TreeNode = pattern[i];
if (!TreePattern._matchTreeRecursive(rootElement, patternElement, captures, subPath)) {
return false;
}
}
return true;
}
// In JavaScript, typeof null === 'object'
if (typeof pattern === 'object' && pattern !== null) {
if (typeof root !== 'object' || root === null) {
captures.failPath = path;
return false;
}
for (const keyName of Object.getOwnPropertyNames(pattern)) {
let subPath: string;
if (/^[a-z_][a-z0-9_]*$/i.test(keyName)) {
subPath = path + '.' + keyName;
} else {
subPath = path + '[' + JSON.stringify(keyName) + ']';
}
if (!Object.hasOwnProperty.call(root, keyName)) {
captures.failPath = subPath;
return false;
}
if (!TreePattern._matchTreeRecursive(root[keyName], pattern[keyName], captures, subPath)) {
return false;
}
}
return true;
}
if (root !== pattern) {
captures.failPath = path;
return false;
}
return true;
}
}