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 const fileText = sourceFile.getFullText(); 31 variableStatement.declarationList.declarations.forEach(value => { 32 let statementName = ''; 33 let initializer = ''; 34 let typeName = ''; 35 let typeKind = -1; 36 37 if (isIdentifier(value.name)) { 38 statementName = value.name.escapedText.toString(); 39 } else { 40 statementName = fileText.slice(value.pos, value.end).trim(); 41 } 42 if (value.initializer !== undefined) { 43 initializer = fileText.slice(value.initializer.pos, value.initializer.end); 44 typeKind = value.initializer.kind; 45 } 46 if (value.type !== undefined) { 47 typeName = fileText.slice(value.type.pos, value.type.end); 48 typeKind = value.type.kind; 49 } 50 statementsArray.push({ 51 statementName: statementName, 52 typeName: typeName, 53 typeKind: typeKind, 54 initializer: initializer 55 }); 56 }); 57 return statementsArray; 58} 59 60export interface StatementEntity { 61 statementName: string; 62 typeName: string; 63 typeKind: number; 64 initializer: string; 65} 66