@ontrails/source 0.2.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.
package/src/walk.ts ADDED
@@ -0,0 +1,87 @@
1
+ /** Shared AST walkers. */
2
+
3
+ import { walk as walkWithOxc } from 'oxc-walker';
4
+ import type {
5
+ ScopeTracker,
6
+ WalkerCallbackContext,
7
+ WalkOptions,
8
+ } from 'oxc-walker';
9
+
10
+ import { isAstNode } from './nodes.js';
11
+ import type { AstNode, AstParentContext } from './nodes.js';
12
+
13
+ export type WalkFn = (node: unknown, visit: (node: AstNode) => void) => void;
14
+
15
+ export const walkChildren = (
16
+ node: AstNode,
17
+ visit: (node: AstNode) => void,
18
+ recurse: WalkFn
19
+ ): void => {
20
+ for (const val of Object.values(node)) {
21
+ if (Array.isArray(val)) {
22
+ for (const item of val) {
23
+ recurse(item, visit);
24
+ }
25
+ } else if (val && typeof val === 'object' && (val as AstNode).type) {
26
+ recurse(val, visit);
27
+ }
28
+ }
29
+ };
30
+
31
+ /** Walk an AST node tree, calling `visit` on every node. */
32
+ export const walk: WalkFn = (node, visit) => {
33
+ if (!node || typeof node !== 'object') {
34
+ return;
35
+ }
36
+ const n = node as AstNode;
37
+ if (n.type) {
38
+ visit(n);
39
+ }
40
+ walkChildren(n, visit, walk);
41
+ };
42
+
43
+ const toAstParentContext = (
44
+ parent: unknown,
45
+ ctx: WalkerCallbackContext
46
+ ): AstParentContext => ({
47
+ index: ctx.index,
48
+ key: ctx.key,
49
+ parent: isAstNode(parent) ? parent : null,
50
+ });
51
+
52
+ export const walkWithOxcFacade = (
53
+ node: unknown,
54
+ enter: (node: AstNode, context: AstParentContext) => void,
55
+ scopeTracker?: ScopeTracker
56
+ ): void => {
57
+ if (!isAstNode(node)) {
58
+ return;
59
+ }
60
+
61
+ const options: Partial<WalkOptions> = {
62
+ enter(candidate, parent, ctx) {
63
+ if (!isAstNode(candidate)) {
64
+ return;
65
+ }
66
+ enter(candidate, toAstParentContext(parent, ctx));
67
+ },
68
+ };
69
+
70
+ if (scopeTracker) {
71
+ options.scopeTracker = scopeTracker;
72
+ }
73
+
74
+ walkWithOxc(node as never, options);
75
+ };
76
+
77
+ /**
78
+ * Walk an AST node tree with parent, key, and index context for each visited
79
+ * node. This is the supported source facade over `oxc-walker` for rules and
80
+ * rewriters that need structural context.
81
+ */
82
+ export const walkWithParents = (
83
+ node: unknown,
84
+ visit: (node: AstNode, context: AstParentContext) => void
85
+ ): void => {
86
+ walkWithOxcFacade(node, visit);
87
+ };