1/* 2 * Copyright (c) 2025 Huawei Device Co., Ltd. 3 * Licensed under the Apache License, Version 2.0 (the "License"); 4 * you may not use this file except in compliance with the License. 5 * You may obtain a copy of the License at 6 * 7 * http://www.apache.org/licenses/LICENSE-2.0 8 * 9 * Unless required by applicable law or agreed to in writing, software 10 * distributed under the License is distributed on an "AS IS" BASIS, 11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 * See the License for the specific language governing permissions and 13 * limitations under the License. 14 */ 15 16import { Es2pandaAstNodeType } from '../Es2pandaEnums'; 17import { throwError } from '../utils'; 18import { global } from './static/global'; 19import { KNativePointer, nullptr } from '@koalaui/interop'; 20import { AstNode, UnsupportedNode } from './peers/AstNode'; 21 22export const nodeByType = new Map<Es2pandaAstNodeType, { new (peer: KNativePointer): AstNode }>([]); 23 24const cache = new Map<KNativePointer, AstNode>(); 25export function clearNodeCache(): void { 26 cache.clear(); 27} 28 29function getOrPut(peer: KNativePointer, create: (peer: KNativePointer) => AstNode): AstNode { 30 if (cache.has(peer)) { 31 return cache.get(peer)!; 32 } 33 34 const newNode = create(peer); 35 cache.set(peer, newNode); 36 return newNode; 37} 38 39export function classByPeer<T extends AstNode>(peer: KNativePointer): T { 40 if (peer === nullptr) { 41 throwError('classByPeer: peer is NULLPTR'); 42 } 43 const type = global.generatedEs2panda._AstNodeTypeConst(global.context, peer); 44 const node = nodeByType.get(type) ?? UnsupportedNode; 45 return getOrPut(peer, (peer) => new node(peer)) as T; 46} 47