1/* 2 * Copyright (c) 2023 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 { SyntaxKind } from 'typescript'; 17import { getClassNameSet } from '../common/commonUtils'; 18import type { StatementEntity } from '../declaration-node/variableStatementResolve'; 19 20/** 21 * generate const variable statement 22 * @param statementEntity 23 * @returns 24 */ 25export function generateVariableStatementDelcatation(statementEntity: StatementEntity, isInnerModule: boolean): string { 26 let statementBody = ''; 27 if (isInnerModule) { 28 statementBody = `const ${statementEntity.statementName} = `; 29 } else { 30 statementBody = `${statementEntity.statementName}: `; 31 } 32 let statementValue; 33 if (statementEntity.typeKind === SyntaxKind.StringKeyword) { 34 statementValue = '\'\''; 35 } else if (statementEntity.typeKind === SyntaxKind.LiteralType || statementEntity.typeKind === SyntaxKind.StringLiteral || 36 statementEntity.typeKind === SyntaxKind.NumericLiteral) { 37 if (statementEntity.initializer === '') { 38 if (statementEntity.typeName.endsWith('n')) { 39 statementValue = statementEntity.typeName.replace('n', ''); 40 } else { 41 statementValue = statementEntity.typeName; 42 } 43 } else { 44 statementValue = statementEntity.initializer; 45 } 46 } else if (statementEntity.typeKind === SyntaxKind.NumberKeyword) { 47 statementValue = 0; 48 } else if (statementEntity.typeKind === SyntaxKind.UnionType) { 49 statementValue = statementEntity.typeName.split('|')[0]; 50 } else if (statementEntity.typeKind === SyntaxKind.TypeReference) { 51 if (statementEntity.typeName.includes('<')) { 52 const tmpTypeName = statementEntity.typeName.split('<')[0]; 53 if (getClassNameSet().has(tmpTypeName)) { 54 statementValue = `new ${tmpTypeName}()`; 55 } else { 56 statementValue = `${tmpTypeName}`; 57 } 58 } else { 59 statementValue = statementEntity.typeName; 60 } 61 } else if (statementEntity.typeKind === SyntaxKind.BooleanKeyword) { 62 statementValue = 'true'; 63 } else if (statementEntity.initializer !== '') { 64 statementValue = statementEntity.initializer.endsWith('n'); 65 } else { 66 statementValue = `'[PC Preivew] unknown ${statementEntity.statementName}'`; 67 } 68 statementBody += statementValue; 69 if (isInnerModule) { 70 statementBody += ';'; 71 } else { 72 statementBody += ','; 73 } 74 return statementBody; 75} 76