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