11import type { Node } from "@babel/types" ;
22import type NodePath from "./path" ;
33import type Scope from "./scope" ;
4+ import type { HubInterface } from "./hub" ;
45
5- export let path : WeakMap < Node , Map < Node , NodePath > > = new WeakMap ( ) ;
6+ let pathsCache : WeakMap <
7+ HubInterface | typeof nullHub ,
8+ WeakMap < Node , Map < Node , NodePath > >
9+ > = new WeakMap ( ) ;
10+ export { pathsCache as path } ;
611export let scope : WeakMap < Node , Scope > = new WeakMap ( ) ;
712
813export function clear ( ) {
@@ -11,9 +16,39 @@ export function clear() {
1116}
1217
1318export function clearPath ( ) {
14- path = new WeakMap ( ) ;
19+ pathsCache = new WeakMap ( ) ;
1520}
1621
1722export function clearScope ( ) {
1823 scope = new WeakMap ( ) ;
1924}
25+
26+ // NodePath#hub can be null, but it's not a valid weakmap key because it
27+ // cannot be collected by GC. Use an object, knowing tht it will not be
28+ // collected anyway. It's not a memory leak because pathsCache.get(nullHub)
29+ // is itself a weakmap, so its entries can still be collected.
30+ const nullHub = Object . freeze ( { } as const ) ;
31+
32+ export function getCachedPaths ( hub : HubInterface | null , parent : Node ) {
33+ if ( ! process . env . BABEL_8_BREAKING ) {
34+ // Only use Hub as part of the cache key in Babel 8, because it is a
35+ // breaking change (it causes incompatibilities with older `@babel/core`
36+ // versions: see https://github.com/babel/babel/pull/15759)
37+ hub = null ;
38+ }
39+ return pathsCache . get ( hub ?? nullHub ) ?. get ( parent ) ;
40+ }
41+
42+ export function getOrCreateCachedPaths ( hub : HubInterface | null , parent : Node ) {
43+ if ( ! process . env . BABEL_8_BREAKING ) {
44+ hub = null ;
45+ }
46+
47+ let parents = pathsCache . get ( hub ?? nullHub ) ;
48+ if ( ! parents ) pathsCache . set ( hub ?? nullHub , ( parents = new WeakMap ( ) ) ) ;
49+
50+ let paths = parents . get ( parent ) ;
51+ if ( ! paths ) parents . set ( parent , ( paths = new Map ( ) ) ) ;
52+
53+ return paths ;
54+ }
0 commit comments