1/* 2 * Copyright (c) 2022-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 16export function throwError(error: string): never { 17 throw new Error(error) 18} 19 20export function withWarning<T>(value: T, message: string): T { 21 console.warn(message) 22 return value 23} 24 25export function isNumber(value: any): value is number { 26 return typeof value === `number` 27} 28 29function replacePercentOutsideStrings(code: string): string { 30 const stringPattern = /("[^"]*"|'[^']*'|`[^`]*`)/g; 31 const percentPattern = /(?<!["'`])(%)(?![\d\s])/g; 32 const strings = code.match(stringPattern) || []; 33 34 let placeholderCounter = 0; 35 const placeholderMap = new Map<string, string>(); 36 strings.forEach((string) => { 37 const placeholder = `__STRING_PLACEHOLDER_${placeholderCounter++}__`; 38 placeholderMap.set(placeholder, string); 39 code = code.replace(string, placeholder); 40 }); 41 42 code = code.replace(percentPattern, '_'); 43 44 placeholderMap.forEach((originalString, placeholder) => { 45 code = code.replace(new RegExp(placeholder, 'g'), originalString); 46 }); 47 48 return code; 49} 50 51function replaceIllegalHashes(code: string): string { 52 const stringPattern = /("[^"]*"|'[^']*'|`[^`]*`)/g; 53 const strings = code.match(stringPattern) || []; 54 55 let placeholderCounter = 0; 56 const placeholderMap = new Map<string, string>(); 57 strings.forEach((string) => { 58 const placeholder = `__STRING_PLACEHOLDER_${placeholderCounter++}__`; 59 placeholderMap.set(placeholder, string); 60 code = code.replace(string, placeholder); 61 }); 62 63 code = code.replace(/#/g, '_'); 64 65 placeholderMap.forEach((originalString, placeholder) => { 66 code = code.replace(new RegExp(placeholder, 'g'), originalString); 67 }); 68 69 return code; 70} 71 72/* 73 TODO: 74 The lowerings insert %% and other special symbols into names of temporary variables. 75 Until we keep feeding ast dumps back to the parser this function is needed. 76 */ 77export function filterSource(text: string): string { 78 const filtered = replaceIllegalHashes(replacePercentOutsideStrings(text)) 79 .replaceAll("<cctor>", "_cctor_") 80 81 return filtered 82} 83 84export function getEnumName(enumType: any, value: number): string | undefined { 85 return enumType[value]; 86}