hermes-parser 0.9.0 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,186 @@
1
+ /**
2
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
3
+ *
4
+ * This source code is licensed under the MIT license found in the
5
+ * LICENSE file in the root directory of this source tree.
6
+ *
7
+ *
8
+ * @format
9
+ */
10
+ 'use strict';
11
+
12
+ Object.defineProperty(exports, "__esModule", {
13
+ value: true
14
+ });
15
+ exports.deepCloneNode = deepCloneNode;
16
+ exports.nodeWith = nodeWith;
17
+ exports.removeNodeOnParent = removeNodeOnParent;
18
+ exports.replaceNodeOnParent = replaceNodeOnParent;
19
+ exports.setParentPointersInDirectChildren = setParentPointersInDirectChildren;
20
+ exports.shallowCloneNode = shallowCloneNode;
21
+ exports.updateAllParentPointers = updateAllParentPointers;
22
+
23
+ var _astArrayMutationHelpers = require("./astArrayMutationHelpers");
24
+
25
+ var _getVisitorKeys = require("../traverse/getVisitorKeys");
26
+
27
+ var _SimpleTraverser = require("../traverse/SimpleTraverser");
28
+
29
+ function getParentKey(target, parent) {
30
+ if (parent == null) {
31
+ throw new Error(`Expected parent node to be set on "${target.type}"`);
32
+ }
33
+
34
+ for (const key of (0, _getVisitorKeys.getVisitorKeys)(parent)) {
35
+ if ((0, _getVisitorKeys.isNode)( // $FlowExpectedError[prop-missing]
36
+ parent[key])) {
37
+ if (parent[key] === target) {
38
+ return {
39
+ type: 'single',
40
+ node: parent,
41
+ key
42
+ };
43
+ }
44
+ } else if (Array.isArray(parent[key])) {
45
+ for (let i = 0; i < parent[key].length; i += 1) {
46
+ const current = parent[key][i];
47
+
48
+ if (current === target) {
49
+ return {
50
+ type: 'array',
51
+ node: parent,
52
+ key,
53
+ targetIndex: i
54
+ };
55
+ }
56
+ }
57
+ }
58
+ } // this shouldn't happen ever
59
+
60
+
61
+ throw new Error(`Expected to find the ${target.type} as a direct child of the ${parent.type}.`);
62
+ }
63
+ /**
64
+ * Replace a node with a new node within an AST (via the parent pointer).
65
+ */
66
+
67
+
68
+ function replaceNodeOnParent(originalNode, originalNodeParent, nodeToReplaceWith) {
69
+ const replacementParent = getParentKey(originalNode, originalNodeParent);
70
+ const parent = replacementParent.node;
71
+
72
+ if (replacementParent.type === 'array') {
73
+ // $FlowExpectedError[prop-missing]
74
+ parent[replacementParent.key] = (0, _astArrayMutationHelpers.replaceInArray)( // $FlowExpectedError[prop-missing]
75
+ parent[replacementParent.key], replacementParent.targetIndex, [nodeToReplaceWith]);
76
+ } else {
77
+ // $FlowExpectedError[prop-missing]
78
+ parent[replacementParent.key] = nodeToReplaceWith;
79
+ }
80
+ }
81
+ /**
82
+ * Remove a node from the AST its connected to (via the parent pointer).
83
+ */
84
+
85
+
86
+ function removeNodeOnParent(originalNode, originalNodeParent) {
87
+ const replacementParent = getParentKey(originalNode, originalNodeParent);
88
+ const parent = replacementParent.node;
89
+
90
+ if (replacementParent.type === 'array') {
91
+ // $FlowExpectedError[prop-missing]
92
+ parent[replacementParent.key] = (0, _astArrayMutationHelpers.removeFromArray)( // $FlowExpectedError[prop-missing]
93
+ parent[replacementParent.key], replacementParent.targetIndex);
94
+ } else {
95
+ // $FlowExpectedError[prop-missing]
96
+ parent[replacementParent.key] = null;
97
+ }
98
+ }
99
+ /**
100
+ * Corrects the parent pointers in direct children of the given node.
101
+ */
102
+
103
+
104
+ function setParentPointersInDirectChildren(node) {
105
+ for (const key of (0, _getVisitorKeys.getVisitorKeys)(node)) {
106
+ if ((0, _getVisitorKeys.isNode)( // $FlowExpectedError[prop-missing]
107
+ node[key])) {
108
+ node[key].parent = node;
109
+ } else if (Array.isArray(node[key])) {
110
+ for (const child of node[key]) {
111
+ child.parent = node;
112
+ }
113
+ }
114
+ }
115
+ }
116
+ /**
117
+ * Traverses the entire subtree to ensure the parent pointers are set correctly.
118
+ */
119
+
120
+
121
+ function updateAllParentPointers(node) {
122
+ _SimpleTraverser.SimpleTraverser.traverse(node, {
123
+ enter(node, parent) {
124
+ // $FlowExpectedError[cannot-write]
125
+ node.parent = parent;
126
+ },
127
+
128
+ leave() {}
129
+
130
+ });
131
+ }
132
+ /**
133
+ * Clone node and add new props.
134
+ *
135
+ * This will only create a new object if the overrides actually result in a change.
136
+ */
137
+
138
+
139
+ function nodeWith(node, overrideProps) {
140
+ // Check if this will actually result in a change, maintaining referential equality is important.
141
+ const willBeUnchanged = Object.entries(overrideProps).every(([key, value]) => // $FlowExpectedError[prop-missing]
142
+ Array.isArray(value) ? (0, _astArrayMutationHelpers.arrayIsEqual)(node[key], value) : node[key] === value);
143
+
144
+ if (willBeUnchanged) {
145
+ return node;
146
+ } // Create new node.
147
+ // $FlowExpectedError[cannot-spread-interface]
148
+
149
+
150
+ const newNode = { ...node,
151
+ ...overrideProps
152
+ }; // Ensure parent pointers are correctly set within this nodes children.
153
+
154
+ setParentPointersInDirectChildren(newNode);
155
+ return newNode;
156
+ }
157
+ /**
158
+ * Shallow clones node, providing a new reference for an existing node.
159
+ */
160
+
161
+
162
+ function shallowCloneNode(node) {
163
+ // $FlowExpectedError[cannot-spread-interface]
164
+ const newNode = { ...node
165
+ }; // Ensure parent pointers are correctly set within this nodes children.
166
+
167
+ setParentPointersInDirectChildren(newNode);
168
+ return newNode;
169
+ }
170
+ /**
171
+ * Deeply clones node and its entire tree.
172
+ */
173
+
174
+
175
+ function deepCloneNode(node) {
176
+ const clone = JSON.parse(JSON.stringify(node, (key, value) => {
177
+ // null out parent pointers
178
+ if (key === 'parent') {
179
+ return undefined;
180
+ }
181
+
182
+ return value;
183
+ }));
184
+ updateAllParentPointers(clone);
185
+ return clone;
186
+ }
@@ -0,0 +1,205 @@
1
+ /**
2
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
3
+ *
4
+ * This source code is licensed under the MIT license found in the
5
+ * LICENSE file in the root directory of this source tree.
6
+ *
7
+ * @flow strict-local
8
+ * @format
9
+ */
10
+
11
+ 'use strict';
12
+
13
+ import type {ESNode} from 'hermes-estree';
14
+
15
+ import {
16
+ arrayIsEqual,
17
+ removeFromArray,
18
+ replaceInArray,
19
+ } from './astArrayMutationHelpers';
20
+ import {getVisitorKeys, isNode} from '../traverse/getVisitorKeys';
21
+ import {SimpleTraverser} from '../traverse/SimpleTraverser';
22
+
23
+ function getParentKey(
24
+ target: ESNode,
25
+ parent: ESNode,
26
+ ): $ReadOnly<
27
+ | {
28
+ type: 'single',
29
+ node: ESNode,
30
+ key: string,
31
+ }
32
+ | {
33
+ type: 'array',
34
+ node: ESNode,
35
+ key: string,
36
+ targetIndex: number,
37
+ },
38
+ > {
39
+ if (parent == null) {
40
+ throw new Error(`Expected parent node to be set on "${target.type}"`);
41
+ }
42
+ for (const key of getVisitorKeys(parent)) {
43
+ if (
44
+ isNode(
45
+ // $FlowExpectedError[prop-missing]
46
+ parent[key],
47
+ )
48
+ ) {
49
+ if (parent[key] === target) {
50
+ return {type: 'single', node: parent, key};
51
+ }
52
+ } else if (Array.isArray(parent[key])) {
53
+ for (let i = 0; i < parent[key].length; i += 1) {
54
+ const current = parent[key][i];
55
+ if (current === target) {
56
+ return {type: 'array', node: parent, key, targetIndex: i};
57
+ }
58
+ }
59
+ }
60
+ }
61
+
62
+ // this shouldn't happen ever
63
+ throw new Error(
64
+ `Expected to find the ${target.type} as a direct child of the ${parent.type}.`,
65
+ );
66
+ }
67
+
68
+ /**
69
+ * Replace a node with a new node within an AST (via the parent pointer).
70
+ */
71
+ export function replaceNodeOnParent(
72
+ originalNode: ESNode,
73
+ originalNodeParent: ESNode,
74
+ nodeToReplaceWith: ESNode,
75
+ ): void {
76
+ const replacementParent = getParentKey(originalNode, originalNodeParent);
77
+ const parent = replacementParent.node;
78
+ if (replacementParent.type === 'array') {
79
+ // $FlowExpectedError[prop-missing]
80
+ parent[replacementParent.key] = replaceInArray(
81
+ // $FlowExpectedError[prop-missing]
82
+ parent[replacementParent.key],
83
+ replacementParent.targetIndex,
84
+ [nodeToReplaceWith],
85
+ );
86
+ } else {
87
+ // $FlowExpectedError[prop-missing]
88
+ parent[replacementParent.key] = nodeToReplaceWith;
89
+ }
90
+ }
91
+
92
+ /**
93
+ * Remove a node from the AST its connected to (via the parent pointer).
94
+ */
95
+ export function removeNodeOnParent(
96
+ originalNode: ESNode,
97
+ originalNodeParent: ESNode,
98
+ ): void {
99
+ const replacementParent = getParentKey(originalNode, originalNodeParent);
100
+ const parent = replacementParent.node;
101
+ if (replacementParent.type === 'array') {
102
+ // $FlowExpectedError[prop-missing]
103
+ parent[replacementParent.key] = removeFromArray(
104
+ // $FlowExpectedError[prop-missing]
105
+ parent[replacementParent.key],
106
+ replacementParent.targetIndex,
107
+ );
108
+ } else {
109
+ // $FlowExpectedError[prop-missing]
110
+ parent[replacementParent.key] = null;
111
+ }
112
+ }
113
+
114
+ /**
115
+ * Corrects the parent pointers in direct children of the given node.
116
+ */
117
+ export function setParentPointersInDirectChildren(node: ESNode): void {
118
+ for (const key of getVisitorKeys(node)) {
119
+ if (
120
+ isNode(
121
+ // $FlowExpectedError[prop-missing]
122
+ node[key],
123
+ )
124
+ ) {
125
+ node[key].parent = node;
126
+ } else if (Array.isArray(node[key])) {
127
+ for (const child of node[key]) {
128
+ child.parent = node;
129
+ }
130
+ }
131
+ }
132
+ }
133
+
134
+ /**
135
+ * Traverses the entire subtree to ensure the parent pointers are set correctly.
136
+ */
137
+ export function updateAllParentPointers(node: ESNode) {
138
+ SimpleTraverser.traverse(node, {
139
+ enter(node, parent) {
140
+ // $FlowExpectedError[cannot-write]
141
+ node.parent = parent;
142
+ },
143
+ leave() {},
144
+ });
145
+ }
146
+
147
+ /**
148
+ * Clone node and add new props.
149
+ *
150
+ * This will only create a new object if the overrides actually result in a change.
151
+ */
152
+ export function nodeWith<T: ESNode>(node: T, overrideProps: $Partial<T>): T {
153
+ // Check if this will actually result in a change, maintaining referential equality is important.
154
+ const willBeUnchanged = Object.entries(overrideProps).every(([key, value]) =>
155
+ // $FlowExpectedError[prop-missing]
156
+ Array.isArray(value) ? arrayIsEqual(node[key], value) : node[key] === value,
157
+ );
158
+ if (willBeUnchanged) {
159
+ return node;
160
+ }
161
+
162
+ // Create new node.
163
+ // $FlowExpectedError[cannot-spread-interface]
164
+ const newNode: T = {
165
+ ...node,
166
+ ...overrideProps,
167
+ };
168
+
169
+ // Ensure parent pointers are correctly set within this nodes children.
170
+ setParentPointersInDirectChildren(newNode);
171
+
172
+ return newNode;
173
+ }
174
+
175
+ /**
176
+ * Shallow clones node, providing a new reference for an existing node.
177
+ */
178
+ export function shallowCloneNode<T: ESNode>(node: T): T {
179
+ // $FlowExpectedError[cannot-spread-interface]
180
+ const newNode: T = {...node};
181
+
182
+ // Ensure parent pointers are correctly set within this nodes children.
183
+ setParentPointersInDirectChildren(newNode);
184
+
185
+ return newNode;
186
+ }
187
+
188
+ /**
189
+ * Deeply clones node and its entire tree.
190
+ */
191
+ export function deepCloneNode<T: ESNode>(node: T): T {
192
+ const clone: T = JSON.parse(
193
+ JSON.stringify(node, (key, value) => {
194
+ // null out parent pointers
195
+ if (key === 'parent') {
196
+ return undefined;
197
+ }
198
+ return value;
199
+ }),
200
+ );
201
+
202
+ updateAllParentPointers(clone);
203
+
204
+ return clone;
205
+ }
@@ -0,0 +1,138 @@
1
+ /**
2
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
3
+ *
4
+ * This source code is licensed under the MIT license found in the
5
+ * LICENSE file in the root directory of this source tree.
6
+ *
7
+ *
8
+ * @format
9
+ */
10
+ 'use strict';
11
+
12
+ Object.defineProperty(exports, "__esModule", {
13
+ value: true
14
+ });
15
+ exports.SimpleTraverserSkip = exports.SimpleTraverserBreak = exports.SimpleTraverser = void 0;
16
+
17
+ var _getVisitorKeys = require("./getVisitorKeys");
18
+
19
+ /**
20
+ * Can be thrown within the traversal "enter" function to prevent the traverser
21
+ * from traversing the node any further, essentially culling the remainder of the
22
+ * AST branch
23
+ */
24
+ const SimpleTraverserSkip = new Error();
25
+ /**
26
+ * Can be thrown at any point during the traversal to immediately stop traversal
27
+ * entirely.
28
+ */
29
+
30
+ exports.SimpleTraverserSkip = SimpleTraverserSkip;
31
+ const SimpleTraverserBreak = new Error();
32
+ /**
33
+ * A very simple traverser class to traverse AST trees.
34
+ */
35
+
36
+ exports.SimpleTraverserBreak = SimpleTraverserBreak;
37
+
38
+ class SimpleTraverser {
39
+ /**
40
+ * Traverse the given AST tree.
41
+ * @param node The root node to traverse.
42
+ * @param options The option object.
43
+ */
44
+ traverse(node, options) {
45
+ try {
46
+ this._traverse(node, null, options);
47
+ } catch (ex) {
48
+ if (ex === SimpleTraverserBreak) {
49
+ return;
50
+ }
51
+
52
+ throw ex;
53
+ }
54
+ }
55
+ /**
56
+ * Traverse the given AST tree recursively.
57
+ * @param node The current node.
58
+ * @param parent The parent node.
59
+ * @private
60
+ */
61
+
62
+
63
+ _traverse(node, parent, options) {
64
+ if (!(0, _getVisitorKeys.isNode)(node)) {
65
+ return;
66
+ }
67
+
68
+ try {
69
+ options.enter(node, parent);
70
+ } catch (ex) {
71
+ if (ex === SimpleTraverserSkip) {
72
+ return;
73
+ }
74
+
75
+ this._setErrorContext(ex, node);
76
+
77
+ throw ex;
78
+ }
79
+
80
+ const keys = (0, _getVisitorKeys.getVisitorKeys)(node, options.visitorKeys);
81
+
82
+ for (const key of keys) {
83
+ // $FlowExpectedError[prop-missing]
84
+ const child = node[key];
85
+
86
+ if (Array.isArray(child)) {
87
+ for (let j = 0; j < child.length; ++j) {
88
+ this._traverse(child[j], node, options);
89
+ }
90
+ } else {
91
+ this._traverse(child, node, options);
92
+ }
93
+ }
94
+
95
+ try {
96
+ options.leave(node, parent);
97
+ } catch (ex) {
98
+ if (ex === SimpleTraverserSkip) {
99
+ return;
100
+ }
101
+
102
+ this._setErrorContext(ex, node);
103
+
104
+ throw ex;
105
+ }
106
+ }
107
+ /**
108
+ * Set useful contextual information onto the error object.
109
+ * @param ex The error object.
110
+ * @param node The current node.
111
+ * @private
112
+ */
113
+
114
+
115
+ _setErrorContext(ex, node) {
116
+ // $FlowFixMe[prop-missing]
117
+ ex.currentNode = {
118
+ type: node.type,
119
+ range: node.range,
120
+ loc: node.loc
121
+ };
122
+ }
123
+ /**
124
+ * Traverse the given AST tree.
125
+ * @param node The root node to traverse.
126
+ * @param options The option object.
127
+ */
128
+
129
+
130
+ static traverse(node, options) {
131
+ new SimpleTraverser().traverse(node, options);
132
+ }
133
+
134
+ }
135
+
136
+ exports.SimpleTraverser = SimpleTraverser;
137
+ SimpleTraverser.Break = SimpleTraverserBreak;
138
+ SimpleTraverser.Skip = SimpleTraverserSkip;
@@ -0,0 +1,132 @@
1
+ /**
2
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
3
+ *
4
+ * This source code is licensed under the MIT license found in the
5
+ * LICENSE file in the root directory of this source tree.
6
+ *
7
+ * @flow strict-local
8
+ * @format
9
+ */
10
+
11
+ 'use strict';
12
+
13
+ import type {VisitorKeysType} from './getVisitorKeys';
14
+ import type {ESNode} from 'hermes-estree';
15
+
16
+ import {getVisitorKeys, isNode} from './getVisitorKeys';
17
+
18
+ export type TraverserCallback = (node: ESNode, parent: ?ESNode) => void;
19
+ export type TraverserOptions = $ReadOnly<{
20
+ /** The callback function which is called on entering each node. */
21
+ enter: TraverserCallback,
22
+ /** The callback function which is called on leaving each node. */
23
+ leave: TraverserCallback,
24
+ /** The set of visitor keys to use for traversal. Defaults to the `hermes-eslint` visitor keys */
25
+ visitorKeys?: ?VisitorKeysType,
26
+ }>;
27
+
28
+ /**
29
+ * Can be thrown within the traversal "enter" function to prevent the traverser
30
+ * from traversing the node any further, essentially culling the remainder of the
31
+ * AST branch
32
+ */
33
+ export const SimpleTraverserSkip: Error = new Error();
34
+ /**
35
+ * Can be thrown at any point during the traversal to immediately stop traversal
36
+ * entirely.
37
+ */
38
+ export const SimpleTraverserBreak: Error = new Error();
39
+
40
+ /**
41
+ * A very simple traverser class to traverse AST trees.
42
+ */
43
+ export class SimpleTraverser {
44
+ static Break: Error = SimpleTraverserBreak;
45
+ static Skip: Error = SimpleTraverserSkip;
46
+
47
+ /**
48
+ * Traverse the given AST tree.
49
+ * @param node The root node to traverse.
50
+ * @param options The option object.
51
+ */
52
+ traverse(node: ESNode, options: TraverserOptions): void {
53
+ try {
54
+ this._traverse(node, null, options);
55
+ } catch (ex) {
56
+ if (ex === SimpleTraverserBreak) {
57
+ return;
58
+ }
59
+ throw ex;
60
+ }
61
+ }
62
+
63
+ /**
64
+ * Traverse the given AST tree recursively.
65
+ * @param node The current node.
66
+ * @param parent The parent node.
67
+ * @private
68
+ */
69
+ _traverse(node: ESNode, parent: ?ESNode, options: TraverserOptions): void {
70
+ if (!isNode(node)) {
71
+ return;
72
+ }
73
+
74
+ try {
75
+ options.enter(node, parent);
76
+ } catch (ex) {
77
+ if (ex === SimpleTraverserSkip) {
78
+ return;
79
+ }
80
+ this._setErrorContext(ex, node);
81
+ throw ex;
82
+ }
83
+
84
+ const keys = getVisitorKeys(node, options.visitorKeys);
85
+ for (const key of keys) {
86
+ // $FlowExpectedError[prop-missing]
87
+ const child = node[key];
88
+
89
+ if (Array.isArray(child)) {
90
+ for (let j = 0; j < child.length; ++j) {
91
+ this._traverse(child[j], node, options);
92
+ }
93
+ } else {
94
+ this._traverse(child, node, options);
95
+ }
96
+ }
97
+
98
+ try {
99
+ options.leave(node, parent);
100
+ } catch (ex) {
101
+ if (ex === SimpleTraverserSkip) {
102
+ return;
103
+ }
104
+ this._setErrorContext(ex, node);
105
+ throw ex;
106
+ }
107
+ }
108
+
109
+ /**
110
+ * Set useful contextual information onto the error object.
111
+ * @param ex The error object.
112
+ * @param node The current node.
113
+ * @private
114
+ */
115
+ _setErrorContext(ex: Error, node: ESNode): void {
116
+ // $FlowFixMe[prop-missing]
117
+ ex.currentNode = {
118
+ type: node.type,
119
+ range: node.range,
120
+ loc: node.loc,
121
+ };
122
+ }
123
+
124
+ /**
125
+ * Traverse the given AST tree.
126
+ * @param node The root node to traverse.
127
+ * @param options The option object.
128
+ */
129
+ static traverse(node: ESNode, options: TraverserOptions) {
130
+ new SimpleTraverser().traverse(node, options);
131
+ }
132
+ }
@@ -0,0 +1,33 @@
1
+ /**
2
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
3
+ *
4
+ * This source code is licensed under the MIT license found in the
5
+ * LICENSE file in the root directory of this source tree.
6
+ *
7
+ *
8
+ * @format
9
+ */
10
+ 'use strict';
11
+
12
+ Object.defineProperty(exports, "__esModule", {
13
+ value: true
14
+ });
15
+ exports.getVisitorKeys = getVisitorKeys;
16
+ exports.isNode = isNode;
17
+
18
+ var _hermesEslint = require("hermes-eslint");
19
+
20
+ function isNode(thing) {
21
+ return typeof thing === 'object' && thing != null && typeof thing.type === 'string';
22
+ }
23
+
24
+ function getVisitorKeys(node, visitorKeys) {
25
+ const keys = (visitorKeys != null ? visitorKeys : _hermesEslint.VisitorKeys)[node.type];
26
+
27
+ if (keys == null) {
28
+ throw new Error(`No visitor keys found for node type "${node.type}".`);
29
+ } // $FlowExpectedError[prop-missing]
30
+
31
+
32
+ return keys;
33
+ }