Skip to content

Commit 789a98a

Browse files
ASTVisitor: use type intersection instead of type union (#2959)
1 parent 2c2d87e commit 789a98a

File tree

2 files changed

+20
-18
lines changed

2 files changed

+20
-18
lines changed

src/language/visitor.d.ts

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -6,17 +6,17 @@ import { ASTNode, ASTKindToNode } from './ast';
66
* A visitor is provided to visit, it contains the collection of
77
* relevant functions to be called during the visitor's traversal.
88
*/
9-
export type ASTVisitor = EnterLeave<ASTVisitFn<ASTNode>> | ShapeMapVisitor;
9+
export type ASTVisitor = EnterLeaveVisitor<ASTNode> & KindVisitor;
1010

11-
interface EnterLeave<T> {
12-
readonly enter?: T;
13-
readonly leave?: T;
14-
}
15-
16-
type ShapeMapVisitor = {
17-
[K in keyof ASTKindToNode]?:
11+
type KindVisitor = {
12+
readonly [K in keyof ASTKindToNode]?:
1813
| ASTVisitFn<ASTKindToNode[K]>
19-
| EnterLeave<ASTVisitFn<ASTKindToNode[K]>>;
14+
| EnterLeaveVisitor<ASTKindToNode[K]>;
15+
};
16+
17+
type EnterLeaveVisitor<TVisitedNode extends ASTNode> = {
18+
readonly enter?: ASTVisitFn<TVisitedNode>;
19+
readonly leave?: ASTVisitFn<TVisitedNode>;
2020
};
2121

2222
/**

src/language/visitor.js

Lines changed: 11 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -7,14 +7,17 @@ import { isNode } from './ast';
77
* A visitor is provided to visit, it contains the collection of
88
* relevant functions to be called during the visitor's traversal.
99
*/
10-
export type ASTVisitor =
11-
| EnterLeave<ASTVisitFn<ASTNode>>
12-
| ShapeMap<
13-
ASTKindToNode,
14-
<Node>(Node) => ASTVisitFn<Node> | EnterLeave<ASTVisitFn<Node>>,
15-
>;
16-
type EnterLeave<T> = {| +enter?: T, +leave?: T |};
17-
type ShapeMap<O, F> = $Shape<$ObjMap<O, F>>;
10+
export type ASTVisitor = $Shape<EnterLeaveVisitor<ASTNode> & KindVisitor>;
11+
12+
type KindVisitor = $ObjMap<
13+
ASTKindToNode,
14+
<Node>(Node) => ASTVisitFn<Node> | EnterLeaveVisitor<Node>,
15+
>;
16+
17+
type EnterLeaveVisitor<TVisitedNode: ASTNode> = {|
18+
+enter?: ASTVisitFn<TVisitedNode>,
19+
+leave?: ASTVisitFn<TVisitedNode>,
20+
|};
1821

1922
/**
2023
* A visitor is comprised of visit functions, which are called on each node
@@ -389,7 +392,6 @@ export function getVisitFn(
389392
return kindSpecificVisitor;
390393
}
391394
} else {
392-
// $FlowFixMe[prop-missing]
393395
const specificVisitor = isLeaving ? visitor.leave : visitor.enter;
394396
if (specificVisitor) {
395397
// { enter() {}, leave() {} }

0 commit comments

Comments
 (0)