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 { getCommonPath } from '../path'; 17const common = require(getCommonPath()); 18const UniqueId = common.UniqueId; 19 20export class GenSymGenerator { 21 // Global for the whole program. 22 private static callCount: number = 0; 23 static instance: GenSymGenerator; 24 25 // Set `stable` to true if you want to have more predictable values. 26 // For example for tests. 27 // Don't use it in production! 28 private constructor(public stableForTests: boolean = false) { 29 if (stableForTests) GenSymGenerator.callCount = 0; 30 } 31 32 static getInstance(stableForTests: boolean = false): GenSymGenerator { 33 if (!this.instance) { 34 this.instance = new GenSymGenerator(stableForTests); 35 } 36 37 return this.instance; 38 } 39 40 sha1Id(callName: string): string { 41 const uniqId = new UniqueId(); 42 uniqId.addString('gensym uniqid'); 43 uniqId.addString(callName); 44 uniqId.addI32(GenSymGenerator.callCount++); 45 return uniqId.compute().substring(0, 7); 46 } 47 48 stringId(callName: string): string { 49 return `${GenSymGenerator.callCount++}_${callName}_id`; 50 } 51 52 id(callName: string = ''): string { 53 const positionId = this.stableForTests ? this.stringId(callName) : this.sha1Id(callName); 54 55 const coreceToStr = parseInt(positionId, 16).toString(); 56 57 // compiler use gensym%%_ but % is illegal before after-check phase 58 return `gensym___${coreceToStr}`; 59 } 60} 61