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 { isIdentifier } from 'typescript'; 17import type { SourceFile, VariableStatement } from 'typescript'; 18 19/** 20 * get const declaration variable 21 * @param variableStatement 22 * @param sourceFile 23 * @returns 24 */ 25export function getVariableStatementDeclaration( 26 variableStatement: VariableStatement, 27 sourceFile: SourceFile 28): Array<StatementEntity> { 29 const statementsArray: Array<StatementEntity> = []; 30 variableStatement.declarationList.declarations.forEach(value => { 31 let statementName = ''; 32 let initializer = ''; 33 let typeName = ''; 34 let typeKind = -1; 35 36 if (isIdentifier(value.name)) { 37 statementName = value.name.escapedText.toString(); 38 } else { 39 statementName = sourceFile.text.substring(value.pos, value.end).trim(); 40 } 41 if (value.initializer !== undefined) { 42 initializer = sourceFile.text.substring(value.initializer.pos, value.initializer.end); 43 typeKind = value.initializer.kind; 44 } 45 if (value.type !== undefined) { 46 typeName = sourceFile.text.substring(value.type.pos, value.type.end); 47 typeKind = value.type.kind; 48 } 49 statementsArray.push({ 50 statementName: statementName, 51 typeName: typeName, 52 typeKind: typeKind, 53 initializer: initializer 54 }); 55 }); 56 return statementsArray; 57} 58 59export interface StatementEntity { 60 statementName: string, 61 typeName: string, 62 typeKind: number, 63 initializer: string 64} 65